util.go 8.1 KB

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