util.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. func GetLoc(subdir string) (string, error) {
  197. if "relative" == LoadFileType {
  198. return relativePath(subdir)
  199. }
  200. if "absolute" == LoadFileType {
  201. return absolutePath(subdir)
  202. }
  203. return "", fmt.Errorf("Unrecognized loading method.")
  204. }
  205. func relativePath(subdir string) (dir string, err error) {
  206. dir, err = os.Getwd()
  207. if err != nil {
  208. return "", err
  209. }
  210. if base := os.Getenv(KuiperBaseKey); base != "" {
  211. Log.Infof("Specified Kuiper base folder at location %s.\n", base)
  212. dir = base
  213. }
  214. confDir := dir + subdir
  215. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  216. lastdir := dir
  217. for len(dir) > 0 {
  218. dir = filepath.Dir(dir)
  219. if lastdir == dir {
  220. break
  221. }
  222. confDir = dir + subdir
  223. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  224. lastdir = dir
  225. continue
  226. } else {
  227. //Log.Printf("Trying to load file from %s", confDir)
  228. return confDir, nil
  229. }
  230. }
  231. } else {
  232. //Log.Printf("Trying to load file from %s", confDir)
  233. return confDir, nil
  234. }
  235. return "", fmt.Errorf("conf dir not found, please set KuiperBaseKey program environment variable correctly.")
  236. }
  237. func ProcessPath(p string) (string, error) {
  238. if abs, err := filepath.Abs(p); err != nil {
  239. return "", nil
  240. } else {
  241. if _, err := os.Stat(abs); os.IsNotExist(err) {
  242. return "", err
  243. }
  244. return abs, nil
  245. }
  246. }
  247. /*********** Type Cast Utilities *****/
  248. //TODO datetime type
  249. func ToString(input interface{}) string {
  250. return fmt.Sprintf("%v", input)
  251. }
  252. func ToInt(input interface{}) (int, error) {
  253. switch t := input.(type) {
  254. case float64:
  255. return int(t), nil
  256. case int64:
  257. return int(t), nil
  258. case int:
  259. return t, nil
  260. default:
  261. return 0, fmt.Errorf("unsupported type %T of %[1]v", input)
  262. }
  263. }
  264. /*
  265. * Convert a map into a struct. The output parameter must be a pointer to a struct
  266. * The struct can have the json meta data
  267. */
  268. func MapToStruct(input, output interface{}) error {
  269. // convert map to json
  270. jsonString, err := json.Marshal(input)
  271. if err != nil {
  272. return err
  273. }
  274. // convert json to struct
  275. return json.Unmarshal(jsonString, output)
  276. }
  277. func ConvertMap(s map[interface{}]interface{}) map[string]interface{} {
  278. r := make(map[string]interface{})
  279. for k, v := range s {
  280. switch t := v.(type) {
  281. case map[interface{}]interface{}:
  282. v = ConvertMap(t)
  283. case []interface{}:
  284. v = ConvertArray(t)
  285. }
  286. r[fmt.Sprintf("%v", k)] = v
  287. }
  288. return r
  289. }
  290. func ConvertArray(s []interface{}) []interface{} {
  291. r := make([]interface{}, len(s))
  292. for i, e := range s {
  293. switch t := e.(type) {
  294. case map[interface{}]interface{}:
  295. e = ConvertMap(t)
  296. case []interface{}:
  297. e = ConvertArray(t)
  298. }
  299. r[i] = e
  300. }
  301. return r
  302. }
  303. func SyncMapToMap(sm *sync.Map) map[string]interface{} {
  304. m := make(map[string]interface{})
  305. sm.Range(func(k interface{}, v interface{}) bool {
  306. m[fmt.Sprintf("%v", k)] = v
  307. return true
  308. })
  309. return m
  310. }
  311. func MapToSyncMap(m map[string]interface{}) *sync.Map {
  312. sm := new(sync.Map)
  313. for k, v := range m {
  314. sm.Store(k, v)
  315. }
  316. return sm
  317. }
  318. func ReadJsonUnmarshal(path string, ret interface{}) error {
  319. sliByte, err := ioutil.ReadFile(path)
  320. if nil != err {
  321. return err
  322. }
  323. err = json.Unmarshal(sliByte, ret)
  324. if nil != err {
  325. return err
  326. }
  327. return nil
  328. }
  329. func ReadYamlUnmarshal(path string, ret interface{}) error {
  330. sliByte, err := ioutil.ReadFile(path)
  331. if nil != err {
  332. return err
  333. }
  334. err = yaml.Unmarshal(sliByte, ret)
  335. if nil != err {
  336. return err
  337. }
  338. return nil
  339. }
  340. func WriteYamlMarshal(path string, data interface{}) error {
  341. y, err := yaml.Marshal(data)
  342. if nil != err {
  343. return err
  344. }
  345. return ioutil.WriteFile(path, y, 0666)
  346. }