util.go 7.7 KB

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