util.go 6.9 KB

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