util.go 6.6 KB

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