util.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/benbjohnson/clock"
  7. "github.com/go-yaml/yaml"
  8. "github.com/sirupsen/logrus"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "runtime"
  15. "sort"
  16. "strings"
  17. )
  18. const (
  19. logFileName = "stream.log"
  20. etc_dir = "/etc/"
  21. data_dir = "/data/"
  22. log_dir = "/log/"
  23. StreamConf = "kuiper.yaml"
  24. KuiperBaseKey = "KuiperBaseKey"
  25. MetaKey = "__meta"
  26. )
  27. var (
  28. Log *logrus.Logger
  29. Config *KuiperConf
  30. IsTesting bool
  31. Clock clock.Clock
  32. logFile *os.File
  33. LoadFileType = "relative"
  34. )
  35. func LoadConf(confName string) ([]byte, error) {
  36. confDir, err := GetConfLoc()
  37. if err != nil {
  38. return nil, err
  39. }
  40. file := path.Join(confDir, confName)
  41. // file := confDir + confName
  42. b, err := ioutil.ReadFile(file)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return b, nil
  47. }
  48. type tlsConf struct {
  49. Certfile string `yaml:"certfile"`
  50. Keyfile string `yaml:"keyfile"`
  51. }
  52. type KuiperConf struct {
  53. Basic struct {
  54. Debug bool `yaml:"debug"`
  55. ConsoleLog bool `yaml:"consoleLog"`
  56. FileLog bool `yaml:"fileLog"`
  57. Port int `yaml:"port"`
  58. RestPort int `yaml:"restPort"`
  59. RestTls *tlsConf `yaml:"restTls"`
  60. Prometheus bool `yaml:"prometheus"`
  61. PrometheusPort int `yaml:"prometheusPort"`
  62. }
  63. Sink struct {
  64. CacheThreshold int `yaml:"cacheThreshold"`
  65. CacheTriggerCount int `yaml:"cacheTriggerCount"`
  66. }
  67. }
  68. func init() {
  69. Log = logrus.New()
  70. Log.SetReportCaller(true)
  71. Log.SetFormatter(&logrus.TextFormatter{
  72. CallerPrettyfier: func(f *runtime.Frame) (string, string) {
  73. filename := path.Base(f.File)
  74. return "", fmt.Sprintf("%s:%d", filename, f.Line)
  75. },
  76. DisableColors: true,
  77. FullTimestamp: true,
  78. })
  79. Log.Debugf("init with args %s", os.Args)
  80. for _, arg := range os.Args {
  81. if strings.HasPrefix(arg, "-test.") {
  82. IsTesting = true
  83. break
  84. }
  85. }
  86. if IsTesting {
  87. Log.Debugf("running in testing mode")
  88. Clock = clock.NewMock()
  89. } else {
  90. Clock = clock.New()
  91. }
  92. }
  93. func InitConf() {
  94. b, err := LoadConf(StreamConf)
  95. if err != nil {
  96. Log.Fatal(err)
  97. }
  98. kc := KuiperConf{}
  99. if err := yaml.Unmarshal(b, &kc); err != nil {
  100. Log.Fatal(err)
  101. } else {
  102. Config = &kc
  103. }
  104. if Config.Basic.Debug {
  105. Log.SetLevel(logrus.DebugLevel)
  106. }
  107. logDir, err := GetLoc(log_dir)
  108. if err != nil {
  109. Log.Fatal(err)
  110. }
  111. file := logDir + logFileName
  112. logFile, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  113. if err == nil {
  114. if Config.Basic.ConsoleLog {
  115. if Config.Basic.FileLog {
  116. mw := io.MultiWriter(os.Stdout, logFile)
  117. Log.SetOutput(mw)
  118. }
  119. } else {
  120. if Config.Basic.FileLog {
  121. Log.SetOutput(logFile)
  122. }
  123. }
  124. } else {
  125. fmt.Println("Failed to init log file settings...")
  126. Log.Infof("Failed to log to file, using default stderr.")
  127. }
  128. }
  129. func PrintMap(m map[string]string, buff *bytes.Buffer) {
  130. si := make([]string, 0, len(m))
  131. for s := range m {
  132. si = append(si, s)
  133. }
  134. sort.Strings(si)
  135. for _, s := range si {
  136. buff.WriteString(fmt.Sprintf("%s: %s\n", s, m[s]))
  137. }
  138. }
  139. func CloseLogger() {
  140. if logFile != nil {
  141. logFile.Close()
  142. }
  143. }
  144. func GetConfLoc() (string, error) {
  145. return GetLoc(etc_dir)
  146. }
  147. func GetDataLoc() (string, error) {
  148. return GetLoc(data_dir)
  149. }
  150. func absolutePath(subdir string) (dir string, err error) {
  151. subdir = strings.TrimLeft(subdir, `/`)
  152. subdir = strings.TrimRight(subdir, `/`)
  153. switch subdir {
  154. case "etc":
  155. dir = "/etc/kuiper/"
  156. break
  157. case "data":
  158. dir = "/var/lib/kuiper/data/"
  159. break
  160. case "log":
  161. dir = "/var/log/kuiper/"
  162. break
  163. case "plugins":
  164. dir = "/var/lib/kuiper/plugins/"
  165. break
  166. }
  167. if _, err = os.Stat(dir); os.IsExist(err) {
  168. return dir, nil
  169. }
  170. return "", err
  171. }
  172. /*
  173. func GetLoc(subdir string) (string, error) {
  174. if base := os.Getenv(KuiperBaseKey); base != "" {
  175. Log.Infof("Specified Kuiper base folder at location %s.\n", base)
  176. dir = base
  177. } else {
  178. dir, err = filepath.Abs(filepath.Dir(os.Args[0]))
  179. if err != nil {
  180. return "", err
  181. }
  182. dir = filepath.Dir(dir)
  183. }
  184. dir = path.Join(dir, subdir)
  185. if _, err := os.Stat(dir); os.IsNotExist(err) {
  186. return "", fmt.Errorf("conf dir not found : %s", dir)
  187. }
  188. return dir, nil
  189. }
  190. */
  191. func GetLoc(subdir string) (string, error) {
  192. if "relative" == LoadFileType {
  193. return relativePath(subdir)
  194. }
  195. if "absolute" == LoadFileType {
  196. return absolutePath(subdir)
  197. }
  198. return "", fmt.Errorf("Unrecognized loading method.")
  199. }
  200. func relativePath(subdir string) (dir string, err error) {
  201. dir, err = os.Getwd()
  202. if err != nil {
  203. return "", err
  204. }
  205. if base := os.Getenv(KuiperBaseKey); base != "" {
  206. Log.Infof("Specified Kuiper base folder at location %s.\n", base)
  207. dir = base
  208. }
  209. confDir := dir + subdir
  210. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  211. lastdir := dir
  212. for len(dir) > 0 {
  213. dir = filepath.Dir(dir)
  214. if lastdir == dir {
  215. break
  216. }
  217. confDir = dir + subdir
  218. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  219. lastdir = dir
  220. continue
  221. } else {
  222. //Log.Printf("Trying to load file from %s", confDir)
  223. return confDir, nil
  224. }
  225. }
  226. } else {
  227. //Log.Printf("Trying to load file from %s", confDir)
  228. return confDir, nil
  229. }
  230. return "", fmt.Errorf("conf dir not found, please set KuiperBaseKey program environment variable correctly.")
  231. }
  232. func GetAndCreateDataLoc(dir string) (string, error) {
  233. dataDir, err := GetDataLoc()
  234. if err != nil {
  235. return "", err
  236. }
  237. d := path.Join(path.Dir(dataDir), dir)
  238. if _, err := os.Stat(d); os.IsNotExist(err) {
  239. err = os.MkdirAll(d, 0755)
  240. if err != nil {
  241. return "", err
  242. }
  243. }
  244. return d, nil
  245. }
  246. func ProcessPath(p string) (string, error) {
  247. if abs, err := filepath.Abs(p); err != nil {
  248. return "", nil
  249. } else {
  250. if _, err := os.Stat(abs); os.IsNotExist(err) {
  251. return "", err
  252. }
  253. return abs, nil
  254. }
  255. }
  256. /*********** Type Cast Utilities *****/
  257. //TODO datetime type
  258. func ToString(input interface{}) string {
  259. return fmt.Sprintf("%v", input)
  260. }
  261. func ToInt(input interface{}) (int, error) {
  262. switch t := input.(type) {
  263. case float64:
  264. return int(t), nil
  265. case int64:
  266. return int(t), nil
  267. case int:
  268. return t, nil
  269. default:
  270. return 0, fmt.Errorf("unsupported type %T of %[1]v", input)
  271. }
  272. }
  273. /*
  274. * Convert a map into a struct. The output parameter must be a pointer to a struct
  275. * The struct can have the json meta data
  276. */
  277. func MapToStruct(input map[string]interface{}, output interface{}) error {
  278. // convert map to json
  279. jsonString, err := json.Marshal(input)
  280. if err != nil {
  281. return err
  282. }
  283. // convert json to struct
  284. return json.Unmarshal(jsonString, output)
  285. }
  286. func ConvertMap(s map[interface{}]interface{}) map[string]interface{} {
  287. r := make(map[string]interface{})
  288. for k, v := range s {
  289. switch t := v.(type) {
  290. case map[interface{}]interface{}:
  291. v = ConvertMap(t)
  292. case []interface{}:
  293. v = ConvertArray(t)
  294. }
  295. r[fmt.Sprintf("%v", k)] = v
  296. }
  297. return r
  298. }
  299. func ConvertArray(s []interface{}) []interface{} {
  300. r := make([]interface{}, len(s))
  301. for i, e := range s {
  302. switch t := e.(type) {
  303. case map[interface{}]interface{}:
  304. e = ConvertMap(t)
  305. case []interface{}:
  306. e = ConvertArray(t)
  307. }
  308. r[i] = e
  309. }
  310. return r
  311. }