util.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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/sirupsen/logrus"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "sort"
  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. RestPort int `yaml:"restPort"`
  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. func PrintMap(m map[string]string, buff *bytes.Buffer) {
  101. si := make([]string, 0, len(m))
  102. for s := range m {
  103. si = append(si, s)
  104. }
  105. sort.Strings(si)
  106. for _, s := range si {
  107. buff.WriteString(fmt.Sprintf("%s: %s\n", s, m[s]))
  108. }
  109. }
  110. func CloseLogger() {
  111. if logFile != nil {
  112. logFile.Close()
  113. }
  114. }
  115. func GetConfLoc() (string, error) {
  116. return GetLoc(etc_dir)
  117. }
  118. func GetDataLoc() (string, error) {
  119. return GetLoc(data_dir)
  120. }
  121. func GetLoc(subdir string) (string, error) {
  122. dir, err := os.Getwd()
  123. if err != nil {
  124. return "", err
  125. }
  126. if base := os.Getenv(KuiperBaseKey); base != "" {
  127. Log.Infof("Specified Kuiper base folder at location %s.\n", base)
  128. dir = base
  129. }
  130. confDir := dir + subdir
  131. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  132. lastdir := dir
  133. for len(dir) > 0 {
  134. dir = filepath.Dir(dir)
  135. if lastdir == dir {
  136. break
  137. }
  138. confDir = dir + subdir
  139. if _, err := os.Stat(confDir); os.IsNotExist(err) {
  140. lastdir = dir
  141. continue
  142. } else {
  143. //Log.Printf("Trying to load file from %s", confDir)
  144. return confDir, nil
  145. }
  146. }
  147. } else {
  148. //Log.Printf("Trying to load file from %s", confDir)
  149. return confDir, nil
  150. }
  151. return "", fmt.Errorf("conf dir not found, please set KuiperBaseKey program environment variable correctly.")
  152. }
  153. func GetAndCreateDataLoc(dir string) (string, error) {
  154. dataDir, err := GetDataLoc()
  155. if err != nil {
  156. return "", err
  157. }
  158. d := path.Join(path.Dir(dataDir), dir)
  159. if _, err := os.Stat(d); os.IsNotExist(err) {
  160. err = os.MkdirAll(d, 0755)
  161. if err != nil {
  162. return "", err
  163. }
  164. }
  165. return d, nil
  166. }
  167. func ProcessPath(p string) (string, error) {
  168. if abs, err := filepath.Abs(p); err != nil {
  169. return "", nil
  170. } else {
  171. if _, err := os.Stat(abs); os.IsNotExist(err) {
  172. return "", err
  173. }
  174. return abs, nil
  175. }
  176. }
  177. /*********** Type Cast Utilities *****/
  178. //TODO datetime type
  179. func ToString(input interface{}) string {
  180. return fmt.Sprintf("%v", input)
  181. }
  182. func ToInt(input interface{}) (int, error) {
  183. switch t := input.(type) {
  184. case float64:
  185. return int(t), nil
  186. case int64:
  187. return int(t), nil
  188. case int:
  189. return t, nil
  190. default:
  191. return 0, fmt.Errorf("unsupported type %T of %[1]v", input)
  192. }
  193. }
  194. /*
  195. * Convert a map into a struct. The output parameter must be a pointer to a struct
  196. * The struct can have the json meta data
  197. */
  198. func MapToStruct(input map[string]interface{}, output interface{}) error {
  199. // convert map to json
  200. jsonString, err := json.Marshal(input)
  201. if err != nil {
  202. return err
  203. }
  204. // convert json to struct
  205. return json.Unmarshal(jsonString, output)
  206. }