util.go 5.8 KB

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