util.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/go-yaml/yaml"
  7. "github.com/patrickmn/go-cache"
  8. "github.com/sirupsen/logrus"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "time"
  14. )
  15. const (
  16. logFileName = "stream.log"
  17. etc_dir = "/etc/"
  18. data_dir = "/data/"
  19. log_dir = "/log/"
  20. )
  21. var (
  22. Log *logrus.Logger
  23. Config *XStreamConf
  24. IsTesting bool
  25. logFile *os.File
  26. mockTicker *MockTicker
  27. mockTimer *MockTimer
  28. mockNow int64
  29. )
  30. type logRedirect struct {
  31. }
  32. func (l *logRedirect) Errorf(f string, v ...interface{}) {
  33. Log.Error(fmt.Sprintf(f, v...))
  34. }
  35. func (l *logRedirect) Infof(f string, v ...interface{}) {
  36. Log.Info(fmt.Sprintf(f, v...))
  37. }
  38. func (l *logRedirect) Warningf(f string, v ...interface{}) {
  39. Log.Warning(fmt.Sprintf(f, v...))
  40. }
  41. func (l *logRedirect) Debugf(f string, v ...interface{}) {
  42. Log.Debug(fmt.Sprintf(f, v...))
  43. }
  44. func LoadConf(confName string) ([]byte, error) {
  45. confDir, err := GetConfLoc()
  46. if err != nil {
  47. return nil, err
  48. }
  49. file := confDir + confName
  50. b, err := ioutil.ReadFile(file)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return b, nil
  55. }
  56. type XStreamConf struct {
  57. Debug bool `yaml:"debug"`
  58. Port int `yaml:"port"`
  59. Prometheus bool `yaml:"prometheus"`
  60. PrometheusPort int `yaml:"prometheusPort"`
  61. }
  62. var StreamConf = "kuiper.yaml"
  63. const KuiperBaseKey = "KuiperBaseKey"
  64. func init() {
  65. Log = logrus.New()
  66. Log.SetFormatter(&logrus.TextFormatter{
  67. DisableColors: true,
  68. FullTimestamp: true,
  69. })
  70. }
  71. func InitConf() {
  72. b, err := LoadConf(StreamConf)
  73. if err != nil {
  74. Log.Fatal(err)
  75. }
  76. var cfg map[string]XStreamConf
  77. if err := yaml.Unmarshal(b, &cfg); err != nil {
  78. Log.Fatal(err)
  79. }
  80. if c, ok := cfg["basic"]; !ok {
  81. Log.Fatal("No basic config in kuiper.yaml")
  82. } else {
  83. Config = &c
  84. }
  85. if !Config.Debug {
  86. logDir, err := GetLoc(log_dir)
  87. if err != nil {
  88. Log.Fatal(err)
  89. }
  90. file := logDir + logFileName
  91. logFile, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  92. if err == nil {
  93. Log.Out = logFile
  94. } else {
  95. Log.Infof("Failed to log to file, using default stderr")
  96. }
  97. } else {
  98. Log.SetLevel(logrus.DebugLevel)
  99. }
  100. }
  101. type KeyValue interface {
  102. Open() error
  103. Close() error
  104. Set(key string, value interface{}) error
  105. Replace(key string, value interface{}) error
  106. Get(key string) (interface{}, bool)
  107. Delete(key string) error
  108. Keys() (keys []string, err error)
  109. }
  110. type SimpleKVStore struct {
  111. path string
  112. c *cache.Cache
  113. }
  114. var stores = make(map[string]*SimpleKVStore)
  115. func GetSimpleKVStore(path string) *SimpleKVStore {
  116. if s, ok := stores[path]; ok {
  117. return s
  118. } else {
  119. c := cache.New(cache.NoExpiration, 0)
  120. if _, err := os.Stat(path); os.IsNotExist(err) {
  121. os.MkdirAll(path, os.ModePerm)
  122. }
  123. sStore := &SimpleKVStore{path: path + "/stores.data", c: c}
  124. stores[path] = sStore
  125. return sStore
  126. }
  127. }
  128. func (m *SimpleKVStore) Open() error {
  129. if _, err := os.Stat(m.path); os.IsNotExist(err) {
  130. return nil
  131. }
  132. if e := m.c.LoadFile(m.path); e != nil {
  133. return e
  134. }
  135. return nil
  136. }
  137. func (m *SimpleKVStore) Close() error {
  138. e := m.saveToFile()
  139. m.c.Flush() //Delete all of the values from memory.
  140. return e
  141. }
  142. func (m *SimpleKVStore) saveToFile() error {
  143. if e := m.c.SaveFile(m.path); e != nil {
  144. return e
  145. }
  146. return nil
  147. }
  148. func (m *SimpleKVStore) Set(key string, value interface{}) error {
  149. if m.c == nil {
  150. return fmt.Errorf("cache %s has not been initialized yet", m.path)
  151. }
  152. if err := m.c.Add(key, value, cache.NoExpiration); err != nil {
  153. return err
  154. }
  155. return m.saveToFile()
  156. }
  157. func (m *SimpleKVStore) Replace(key string, value interface{}) error {
  158. if m.c == nil {
  159. return fmt.Errorf("cache %s has not been initialized yet", m.path)
  160. }
  161. m.c.Set(key, value, cache.NoExpiration)
  162. return m.saveToFile()
  163. }
  164. func (m *SimpleKVStore) Get(key string) (interface{}, bool) {
  165. return m.c.Get(key)
  166. }
  167. func (m *SimpleKVStore) Delete(key string) error {
  168. if m.c == nil {
  169. return fmt.Errorf("cache %s has not been initialized yet", m.path)
  170. }
  171. if _, found := m.c.Get(key); found {
  172. m.c.Delete(key)
  173. } else {
  174. return fmt.Errorf("%s is not found", key)
  175. }
  176. return m.saveToFile()
  177. }
  178. func (m *SimpleKVStore) Keys() (keys []string, err error) {
  179. if m.c == nil {
  180. return nil, fmt.Errorf("Cache %s has not been initialized yet.", m.path)
  181. }
  182. its := m.c.Items()
  183. keys = make([]string, 0, len(its))
  184. for k := range its {
  185. keys = append(keys, k)
  186. }
  187. return keys, nil
  188. }
  189. func PrintMap(m map[string]string, buff *bytes.Buffer) {
  190. for k, v := range m {
  191. buff.WriteString(fmt.Sprintf("%s: %s\n", k, v))
  192. }
  193. }
  194. func CloseLogger() {
  195. if logFile != nil {
  196. logFile.Close()
  197. }
  198. }
  199. func GetConfLoc() (string, error) {
  200. return GetLoc(etc_dir)
  201. }
  202. func GetDataLoc() (string, error) {
  203. return GetLoc(data_dir)
  204. }
  205. func GetLoc(subdir string) (string, 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 GetAndCreateDataLoc(dir string) (string, error) {
  238. dataDir, err := GetDataLoc()
  239. if err != nil {
  240. return "", err
  241. }
  242. d := path.Join(path.Dir(dataDir), dir)
  243. if _, err := os.Stat(d); os.IsNotExist(err) {
  244. err = os.MkdirAll(d, 0755)
  245. if err != nil {
  246. return "", err
  247. }
  248. }
  249. return d, nil
  250. }
  251. //Time related. For Mock
  252. func GetTicker(duration int) Ticker {
  253. if IsTesting {
  254. if mockTicker == nil {
  255. mockTicker = NewMockTicker(duration)
  256. } else {
  257. mockTicker.SetDuration(duration)
  258. }
  259. return mockTicker
  260. } else {
  261. return NewDefaultTicker(duration)
  262. }
  263. }
  264. func GetTimer(duration int) Timer {
  265. if IsTesting {
  266. if mockTimer == nil {
  267. mockTimer = NewMockTimer(duration)
  268. } else {
  269. mockTimer.SetDuration(duration)
  270. }
  271. return mockTimer
  272. } else {
  273. return NewDefaultTimer(duration)
  274. }
  275. }
  276. func GetNowInMilli() int64 {
  277. if IsTesting {
  278. return GetMockNow()
  279. } else {
  280. return TimeToUnixMilli(time.Now())
  281. }
  282. }
  283. func ProcessPath(p string) (string, error) {
  284. if abs, err := filepath.Abs(p); err != nil {
  285. return "", nil
  286. } else {
  287. if _, err := os.Stat(abs); os.IsNotExist(err) {
  288. return "", err
  289. }
  290. return abs, nil
  291. }
  292. }
  293. /****** For Test Only ********/
  294. func GetMockTicker() *MockTicker {
  295. return mockTicker
  296. }
  297. func ResetMockTicker() {
  298. if mockTicker != nil {
  299. mockTicker.lastTick = 0
  300. }
  301. }
  302. func GetMockTimer() *MockTimer {
  303. return mockTimer
  304. }
  305. func SetMockNow(now int64) {
  306. mockNow = now
  307. }
  308. func GetMockNow() int64 {
  309. return mockNow
  310. }
  311. /*********** Type Cast Utilities *****/
  312. //TODO datetime type
  313. func ToString(input interface{}) string {
  314. return fmt.Sprintf("%v", input)
  315. }
  316. func ToInt(input interface{}) (int, error) {
  317. switch t := input.(type) {
  318. case float64:
  319. return int(t), nil
  320. case int64:
  321. return int(t), nil
  322. case int:
  323. return t, nil
  324. default:
  325. return 0, fmt.Errorf("unsupported type %T of %[1]v", input)
  326. }
  327. }
  328. /*
  329. * Convert a map into a struct. The output parameter must be a pointer to a struct
  330. * The struct can have the json meta data
  331. */
  332. func MapToStruct(input map[string]interface{}, output interface{}) error {
  333. // convert map to json
  334. jsonString, err := json.Marshal(input)
  335. if err != nil {
  336. return err
  337. }
  338. // convert json to struct
  339. return json.Unmarshal(jsonString, output)
  340. }