config.go 7.6 KB

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