util.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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/patrickmn/go-cache"
  9. "github.com/sirupsen/logrus"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "sort"
  15. "strings"
  16. )
  17. const (
  18. logFileName = "stream.log"
  19. etc_dir = "/etc/"
  20. data_dir = "/data/"
  21. log_dir = "/log/"
  22. StreamConf = "kuiper.yaml"
  23. KuiperBaseKey = "KuiperBaseKey"
  24. )
  25. var (
  26. Log *logrus.Logger
  27. Config *XStreamConf
  28. IsTesting bool
  29. Clock clock.Clock
  30. logFile *os.File
  31. )
  32. func LoadConf(confName string) ([]byte, error) {
  33. confDir, err := GetConfLoc()
  34. if err != nil {
  35. return nil, err
  36. }
  37. file := confDir + confName
  38. b, err := ioutil.ReadFile(file)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return b, nil
  43. }
  44. type XStreamConf struct {
  45. Debug bool `yaml:"debug"`
  46. Port int `yaml:"port"`
  47. Prometheus bool `yaml:"prometheus"`
  48. PrometheusPort int `yaml:"prometheusPort"`
  49. }
  50. func init() {
  51. Log = logrus.New()
  52. Log.SetFormatter(&logrus.TextFormatter{
  53. DisableColors: true,
  54. FullTimestamp: true,
  55. })
  56. Log.Debugf("init with args %s", os.Args)
  57. for _, arg := range os.Args {
  58. if strings.HasPrefix(arg, "-test.") {
  59. IsTesting = true
  60. break
  61. }
  62. }
  63. if IsTesting {
  64. Log.Debugf("running in testing mode")
  65. Clock = clock.NewMock()
  66. } else {
  67. Clock = clock.New()
  68. }
  69. }
  70. func InitConf() {
  71. b, err := LoadConf(StreamConf)
  72. if err != nil {
  73. Log.Fatal(err)
  74. }
  75. var cfg map[string]XStreamConf
  76. if err := yaml.Unmarshal(b, &cfg); err != nil {
  77. Log.Fatal(err)
  78. }
  79. if c, ok := cfg["basic"]; !ok {
  80. Log.Fatal("No basic config in kuiper.yaml")
  81. } else {
  82. Config = &c
  83. }
  84. if !Config.Debug {
  85. logDir, err := GetLoc(log_dir)
  86. if err != nil {
  87. Log.Fatal(err)
  88. }
  89. file := logDir + logFileName
  90. logFile, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  91. if err == nil {
  92. Log.Out = logFile
  93. } else {
  94. Log.Infof("Failed to log to file, using default stderr")
  95. }
  96. } else {
  97. Log.SetLevel(logrus.DebugLevel)
  98. }
  99. }
  100. type KeyValue interface {
  101. Open() error
  102. Close() error
  103. Set(key string, value interface{}) error
  104. Replace(key string, value interface{}) error
  105. Get(key string) (interface{}, bool)
  106. Delete(key string) error
  107. Keys() (keys []string, err error)
  108. }
  109. type SimpleKVStore struct {
  110. path string
  111. c *cache.Cache
  112. }
  113. var stores = make(map[string]*SimpleKVStore)
  114. func GetSimpleKVStore(path string) *SimpleKVStore {
  115. if s, ok := stores[path]; ok {
  116. return s
  117. } else {
  118. c := cache.New(cache.NoExpiration, 0)
  119. if _, err := os.Stat(path); os.IsNotExist(err) {
  120. os.MkdirAll(path, os.ModePerm)
  121. }
  122. sStore := &SimpleKVStore{path: path + "/stores.data", c: c}
  123. stores[path] = sStore
  124. return sStore
  125. }
  126. }
  127. func (m *SimpleKVStore) Open() error {
  128. if _, err := os.Stat(m.path); os.IsNotExist(err) {
  129. return nil
  130. }
  131. if e := m.c.LoadFile(m.path); e != nil {
  132. return e
  133. }
  134. return nil
  135. }
  136. func (m *SimpleKVStore) Close() error {
  137. e := m.saveToFile()
  138. m.c.Flush() //Delete all of the values from memory.
  139. return e
  140. }
  141. func (m *SimpleKVStore) saveToFile() error {
  142. if e := m.c.SaveFile(m.path); e != nil {
  143. return e
  144. }
  145. return nil
  146. }
  147. func (m *SimpleKVStore) Set(key string, value interface{}) error {
  148. if m.c == nil {
  149. return fmt.Errorf("cache %s has not been initialized yet", m.path)
  150. }
  151. if err := m.c.Add(key, value, cache.NoExpiration); err != nil {
  152. return err
  153. }
  154. return m.saveToFile()
  155. }
  156. func (m *SimpleKVStore) Replace(key string, value interface{}) error {
  157. if m.c == nil {
  158. return fmt.Errorf("cache %s has not been initialized yet", m.path)
  159. }
  160. m.c.Set(key, value, cache.NoExpiration)
  161. return m.saveToFile()
  162. }
  163. func (m *SimpleKVStore) Get(key string) (interface{}, bool) {
  164. return m.c.Get(key)
  165. }
  166. func (m *SimpleKVStore) Delete(key string) error {
  167. if m.c == nil {
  168. return fmt.Errorf("cache %s has not been initialized yet", m.path)
  169. }
  170. if _, found := m.c.Get(key); found {
  171. m.c.Delete(key)
  172. } else {
  173. return fmt.Errorf("%s is not found", key)
  174. }
  175. return m.saveToFile()
  176. }
  177. func (m *SimpleKVStore) Keys() (keys []string, err error) {
  178. if m.c == nil {
  179. return nil, fmt.Errorf("Cache %s has not been initialized yet.", m.path)
  180. }
  181. its := m.c.Items()
  182. keys = make([]string, 0, len(its))
  183. for k := range its {
  184. keys = append(keys, k)
  185. }
  186. return keys, nil
  187. }
  188. func PrintMap(m map[string]string, buff *bytes.Buffer) {
  189. si := make([]string, 0, len(m))
  190. for s := range m {
  191. si = append(si, s)
  192. }
  193. sort.Strings(si)
  194. for _, s := range si {
  195. buff.WriteString(fmt.Sprintf("%s: %s\n", s, m[s]))
  196. }
  197. }
  198. func CloseLogger() {
  199. if logFile != nil {
  200. logFile.Close()
  201. }
  202. }
  203. func GetConfLoc() (string, error) {
  204. return GetLoc(etc_dir)
  205. }
  206. func GetDataLoc() (string, error) {
  207. return GetLoc(data_dir)
  208. }
  209. func GetLoc(subdir string) (string, error) {
  210. dir, err := os.Getwd()
  211. if err != nil {
  212. return "", err
  213. }
  214. if base := os.Getenv(KuiperBaseKey); base != "" {
  215. Log.Infof("Specified Kuiper base folder at location %s.\n", base)
  216. dir = base
  217. }
  218. confDir := dir + subdir
  219. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  220. lastdir := dir
  221. for len(dir) > 0 {
  222. dir = filepath.Dir(dir)
  223. if lastdir == dir {
  224. break
  225. }
  226. confDir = dir + subdir
  227. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  228. lastdir = dir
  229. continue
  230. } else {
  231. //Log.Printf("Trying to load file from %s", confDir)
  232. return confDir, nil
  233. }
  234. }
  235. } else {
  236. //Log.Printf("Trying to load file from %s", confDir)
  237. return confDir, nil
  238. }
  239. return "", fmt.Errorf("conf dir not found, please set KuiperBaseKey program environment variable correctly.")
  240. }
  241. func GetAndCreateDataLoc(dir string) (string, error) {
  242. dataDir, err := GetDataLoc()
  243. if err != nil {
  244. return "", err
  245. }
  246. d := path.Join(path.Dir(dataDir), dir)
  247. if _, err := os.Stat(d); os.IsNotExist(err) {
  248. err = os.MkdirAll(d, 0755)
  249. if err != nil {
  250. return "", err
  251. }
  252. }
  253. return d, nil
  254. }
  255. func ProcessPath(p string) (string, error) {
  256. if abs, err := filepath.Abs(p); err != nil {
  257. return "", nil
  258. } else {
  259. if _, err := os.Stat(abs); os.IsNotExist(err) {
  260. return "", err
  261. }
  262. return abs, nil
  263. }
  264. }
  265. /*********** Type Cast Utilities *****/
  266. //TODO datetime type
  267. func ToString(input interface{}) string {
  268. return fmt.Sprintf("%v", input)
  269. }
  270. func ToInt(input interface{}) (int, error) {
  271. switch t := input.(type) {
  272. case float64:
  273. return int(t), nil
  274. case int64:
  275. return int(t), nil
  276. case int:
  277. return t, nil
  278. default:
  279. return 0, fmt.Errorf("unsupported type %T of %[1]v", input)
  280. }
  281. }
  282. /*
  283. * Convert a map into a struct. The output parameter must be a pointer to a struct
  284. * The struct can have the json meta data
  285. */
  286. func MapToStruct(input map[string]interface{}, output interface{}) error {
  287. // convert map to json
  288. jsonString, err := json.Marshal(input)
  289. if err != nil {
  290. return err
  291. }
  292. // convert json to struct
  293. return json.Unmarshal(jsonString, output)
  294. }