config.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. package nebula
  2. import (
  3. "fmt"
  4. "github.com/imdario/mergo"
  5. "github.com/sirupsen/logrus"
  6. "gopkg.in/yaml.v2"
  7. "io/ioutil"
  8. "os"
  9. "os/signal"
  10. "path/filepath"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "syscall"
  15. "time"
  16. )
  17. type Config struct {
  18. path string
  19. files []string
  20. Settings map[interface{}]interface{}
  21. oldSettings map[interface{}]interface{}
  22. callbacks []func(*Config)
  23. }
  24. func NewConfig() *Config {
  25. return &Config{
  26. Settings: make(map[interface{}]interface{}),
  27. }
  28. }
  29. // Load will find all yaml files within path and load them in lexical order
  30. func (c *Config) Load(path string) error {
  31. c.path = path
  32. c.files = make([]string, 0)
  33. err := c.resolve(path)
  34. if err != nil {
  35. return err
  36. }
  37. sort.Strings(c.files)
  38. err = c.parse()
  39. if err != nil {
  40. return err
  41. }
  42. return nil
  43. }
  44. // RegisterReloadCallback stores a function to be called when a config reload is triggered. The functions registered
  45. // here should decide if they need to make a change to the current process before making the change. HasChanged can be
  46. // used to help decide if a change is necessary.
  47. // These functions should return quickly or spawn their own go routine if they will take a while
  48. func (c *Config) RegisterReloadCallback(f func(*Config)) {
  49. c.callbacks = append(c.callbacks, f)
  50. }
  51. // HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
  52. // k in both the old and new settings will be serialized, the result of the string comparison is returned.
  53. // If k is an empty string the entire config is tested.
  54. // It's important to note that this is very rudimentary and susceptible to configuration ordering issues indicating
  55. // there is change when there actually wasn't any.
  56. func (c *Config) HasChanged(k string) bool {
  57. if c.oldSettings == nil {
  58. return false
  59. }
  60. var (
  61. nv interface{}
  62. ov interface{}
  63. )
  64. if k == "" {
  65. nv = c.Settings
  66. ov = c.oldSettings
  67. k = "all settings"
  68. } else {
  69. nv = c.get(k, c.Settings)
  70. ov = c.get(k, c.oldSettings)
  71. }
  72. newVals, err := yaml.Marshal(nv)
  73. if err != nil {
  74. l.WithField("config_path", k).WithError(err).Error("Error while marshaling new config")
  75. }
  76. oldVals, err := yaml.Marshal(ov)
  77. if err != nil {
  78. l.WithField("config_path", k).WithError(err).Error("Error while marshaling old config")
  79. }
  80. return string(newVals) != string(oldVals)
  81. }
  82. // CatchHUP will listen for the HUP signal in a go routine and reload all configs found in the
  83. // original path provided to Load. The old settings are shallow copied for change detection after the reload.
  84. func (c *Config) CatchHUP() {
  85. ch := make(chan os.Signal, 1)
  86. signal.Notify(ch, syscall.SIGHUP)
  87. go func() {
  88. for range ch {
  89. l.Info("Caught HUP, reloading config")
  90. c.ReloadConfig()
  91. }
  92. }()
  93. }
  94. func (c *Config) ReloadConfig() {
  95. c.oldSettings = make(map[interface{}]interface{})
  96. for k, v := range c.Settings {
  97. c.oldSettings[k] = v
  98. }
  99. err := c.Load(c.path)
  100. if err != nil {
  101. l.WithField("config_path", c.path).WithError(err).Error("Error occurred while reloading config")
  102. return
  103. }
  104. for _, v := range c.callbacks {
  105. v(c)
  106. }
  107. }
  108. // GetString will get the string for k or return the default d if not found or invalid
  109. func (c *Config) GetString(k, d string) string {
  110. r := c.Get(k)
  111. if r == nil {
  112. return d
  113. }
  114. return fmt.Sprintf("%v", r)
  115. }
  116. // GetStringSlice will get the slice of strings for k or return the default d if not found or invalid
  117. func (c *Config) GetStringSlice(k string, d []string) []string {
  118. r := c.Get(k)
  119. if r == nil {
  120. return d
  121. }
  122. rv, ok := r.([]interface{})
  123. if !ok {
  124. return d
  125. }
  126. v := make([]string, len(rv))
  127. for i := 0; i < len(v); i++ {
  128. v[i] = fmt.Sprintf("%v", rv[i])
  129. }
  130. return v
  131. }
  132. // GetMap will get the map for k or return the default d if not found or invalid
  133. func (c *Config) GetMap(k string, d map[interface{}]interface{}) map[interface{}]interface{} {
  134. r := c.Get(k)
  135. if r == nil {
  136. return d
  137. }
  138. v, ok := r.(map[interface{}]interface{})
  139. if !ok {
  140. return d
  141. }
  142. return v
  143. }
  144. // GetInt will get the int for k or return the default d if not found or invalid
  145. func (c *Config) GetInt(k string, d int) int {
  146. r := c.GetString(k, strconv.Itoa(d))
  147. v, err := strconv.Atoi(r)
  148. if err != nil {
  149. return d
  150. }
  151. return v
  152. }
  153. // GetBool will get the bool for k or return the default d if not found or invalid
  154. func (c *Config) GetBool(k string, d bool) bool {
  155. r := strings.ToLower(c.GetString(k, fmt.Sprintf("%v", d)))
  156. v, err := strconv.ParseBool(r)
  157. if err != nil {
  158. switch r {
  159. case "y", "yes":
  160. return true
  161. case "n", "no":
  162. return false
  163. }
  164. return d
  165. }
  166. return v
  167. }
  168. // GetDuration will get the duration for k or return the default d if not found or invalid
  169. func (c *Config) GetDuration(k string, d time.Duration) time.Duration {
  170. r := c.GetString(k, "")
  171. v, err := time.ParseDuration(r)
  172. if err != nil {
  173. return d
  174. }
  175. return v
  176. }
  177. func (c *Config) Get(k string) interface{} {
  178. return c.get(k, c.Settings)
  179. }
  180. func (c *Config) get(k string, v interface{}) interface{} {
  181. parts := strings.Split(k, ".")
  182. for _, p := range parts {
  183. m, ok := v.(map[interface{}]interface{})
  184. if !ok {
  185. return nil
  186. }
  187. v, ok = m[p]
  188. if !ok {
  189. return nil
  190. }
  191. }
  192. return v
  193. }
  194. func (c *Config) resolve(path string) error {
  195. i, err := os.Stat(path)
  196. if err != nil {
  197. return nil
  198. }
  199. if !i.IsDir() {
  200. c.addFile(path)
  201. return nil
  202. }
  203. paths, err := readDirNames(path)
  204. if err != nil {
  205. return fmt.Errorf("problem while reading directory %s: %s", path, err)
  206. }
  207. for _, p := range paths {
  208. err := c.resolve(filepath.Join(path, p))
  209. if err != nil {
  210. return err
  211. }
  212. }
  213. return nil
  214. }
  215. func (c *Config) addFile(path string) error {
  216. ext := filepath.Ext(path)
  217. if ext != ".yaml" && ext != ".yml" {
  218. return nil
  219. }
  220. ap, err := filepath.Abs(path)
  221. if err != nil {
  222. return err
  223. }
  224. c.files = append(c.files, ap)
  225. return nil
  226. }
  227. func (c *Config) parse() error {
  228. var m map[interface{}]interface{}
  229. for _, path := range c.files {
  230. b, err := ioutil.ReadFile(path)
  231. if err != nil {
  232. return err
  233. }
  234. var nm map[interface{}]interface{}
  235. err = yaml.Unmarshal(b, &nm)
  236. if err != nil {
  237. return err
  238. }
  239. // We need to use WithAppendSlice so that firewall rules in separate
  240. // files are appended together
  241. err = mergo.Merge(&nm, m, mergo.WithAppendSlice)
  242. m = nm
  243. if err != nil {
  244. return err
  245. }
  246. }
  247. c.Settings = m
  248. return nil
  249. }
  250. func readDirNames(path string) ([]string, error) {
  251. f, err := os.Open(path)
  252. if err != nil {
  253. return nil, err
  254. }
  255. paths, err := f.Readdirnames(-1)
  256. f.Close()
  257. if err != nil {
  258. return nil, err
  259. }
  260. sort.Strings(paths)
  261. return paths, nil
  262. }
  263. func configLogger(c *Config) error {
  264. // set up our logging level
  265. logLevel, err := logrus.ParseLevel(strings.ToLower(c.GetString("logging.level", "info")))
  266. if err != nil {
  267. return fmt.Errorf("%s; possible levels: %s", err, logrus.AllLevels)
  268. }
  269. l.SetLevel(logLevel)
  270. logFormat := strings.ToLower(c.GetString("logging.format", "text"))
  271. switch logFormat {
  272. case "text":
  273. l.Formatter = &logrus.TextFormatter{}
  274. case "json":
  275. l.Formatter = &logrus.JSONFormatter{}
  276. default:
  277. return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
  278. }
  279. return nil
  280. }