util.go 7.1 KB

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