config.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. // InitialLoad returns true if this is the first load of the config, and ReloadConfig has not been called yet.
  67. func (c *C) InitialLoad() bool {
  68. return c.oldSettings == nil
  69. }
  70. // HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
  71. // k in both the old and new settings will be serialized, the result of the string comparison is returned.
  72. // If k is an empty string the entire config is tested.
  73. // It's important to note that this is very rudimentary and susceptible to configuration ordering issues indicating
  74. // there is change when there actually wasn't any.
  75. func (c *C) HasChanged(k string) bool {
  76. if c.oldSettings == nil {
  77. return false
  78. }
  79. var (
  80. nv interface{}
  81. ov interface{}
  82. )
  83. if k == "" {
  84. nv = c.Settings
  85. ov = c.oldSettings
  86. k = "all settings"
  87. } else {
  88. nv = c.get(k, c.Settings)
  89. ov = c.get(k, c.oldSettings)
  90. }
  91. newVals, err := yaml.Marshal(nv)
  92. if err != nil {
  93. c.l.WithField("config_path", k).WithError(err).Error("Error while marshaling new config")
  94. }
  95. oldVals, err := yaml.Marshal(ov)
  96. if err != nil {
  97. c.l.WithField("config_path", k).WithError(err).Error("Error while marshaling old config")
  98. }
  99. return string(newVals) != string(oldVals)
  100. }
  101. // CatchHUP will listen for the HUP signal in a go routine and reload all configs found in the
  102. // original path provided to Load. The old settings are shallow copied for change detection after the reload.
  103. func (c *C) CatchHUP(ctx context.Context) {
  104. ch := make(chan os.Signal, 1)
  105. signal.Notify(ch, syscall.SIGHUP)
  106. go func() {
  107. for {
  108. select {
  109. case <-ctx.Done():
  110. signal.Stop(ch)
  111. close(ch)
  112. return
  113. case <-ch:
  114. c.l.Info("Caught HUP, reloading config")
  115. c.ReloadConfig()
  116. }
  117. }
  118. }()
  119. }
  120. func (c *C) ReloadConfig() {
  121. c.reloadLock.Lock()
  122. defer c.reloadLock.Unlock()
  123. c.oldSettings = make(map[interface{}]interface{})
  124. for k, v := range c.Settings {
  125. c.oldSettings[k] = v
  126. }
  127. err := c.Load(c.path)
  128. if err != nil {
  129. c.l.WithField("config_path", c.path).WithError(err).Error("Error occurred while reloading config")
  130. return
  131. }
  132. for _, v := range c.callbacks {
  133. v(c)
  134. }
  135. }
  136. func (c *C) ReloadConfigString(raw string) error {
  137. c.reloadLock.Lock()
  138. defer c.reloadLock.Unlock()
  139. c.oldSettings = make(map[interface{}]interface{})
  140. for k, v := range c.Settings {
  141. c.oldSettings[k] = v
  142. }
  143. err := c.LoadString(raw)
  144. if err != nil {
  145. return err
  146. }
  147. for _, v := range c.callbacks {
  148. v(c)
  149. }
  150. return nil
  151. }
  152. // GetString will get the string for k or return the default d if not found or invalid
  153. func (c *C) GetString(k, d string) string {
  154. r := c.Get(k)
  155. if r == nil {
  156. return d
  157. }
  158. return fmt.Sprintf("%v", r)
  159. }
  160. // GetStringSlice will get the slice of strings for k or return the default d if not found or invalid
  161. func (c *C) GetStringSlice(k string, d []string) []string {
  162. r := c.Get(k)
  163. if r == nil {
  164. return d
  165. }
  166. rv, ok := r.([]interface{})
  167. if !ok {
  168. return d
  169. }
  170. v := make([]string, len(rv))
  171. for i := 0; i < len(v); i++ {
  172. v[i] = fmt.Sprintf("%v", rv[i])
  173. }
  174. return v
  175. }
  176. // GetMap will get the map for k or return the default d if not found or invalid
  177. func (c *C) GetMap(k string, d map[interface{}]interface{}) map[interface{}]interface{} {
  178. r := c.Get(k)
  179. if r == nil {
  180. return d
  181. }
  182. v, ok := r.(map[interface{}]interface{})
  183. if !ok {
  184. return d
  185. }
  186. return v
  187. }
  188. // GetInt will get the int for k or return the default d if not found or invalid
  189. func (c *C) GetInt(k string, d int) int {
  190. r := c.GetString(k, strconv.Itoa(d))
  191. v, err := strconv.Atoi(r)
  192. if err != nil {
  193. return d
  194. }
  195. return v
  196. }
  197. // GetBool will get the bool for k or return the default d if not found or invalid
  198. func (c *C) GetBool(k string, d bool) bool {
  199. r := strings.ToLower(c.GetString(k, fmt.Sprintf("%v", d)))
  200. v, err := strconv.ParseBool(r)
  201. if err != nil {
  202. switch r {
  203. case "y", "yes":
  204. return true
  205. case "n", "no":
  206. return false
  207. }
  208. return d
  209. }
  210. return v
  211. }
  212. // GetDuration will get the duration for k or return the default d if not found or invalid
  213. func (c *C) GetDuration(k string, d time.Duration) time.Duration {
  214. r := c.GetString(k, "")
  215. v, err := time.ParseDuration(r)
  216. if err != nil {
  217. return d
  218. }
  219. return v
  220. }
  221. func (c *C) Get(k string) interface{} {
  222. return c.get(k, c.Settings)
  223. }
  224. func (c *C) IsSet(k string) bool {
  225. return c.get(k, c.Settings) != nil
  226. }
  227. func (c *C) get(k string, v interface{}) interface{} {
  228. parts := strings.Split(k, ".")
  229. for _, p := range parts {
  230. m, ok := v.(map[interface{}]interface{})
  231. if !ok {
  232. return nil
  233. }
  234. v, ok = m[p]
  235. if !ok {
  236. return nil
  237. }
  238. }
  239. return v
  240. }
  241. // direct signifies if this is the config path directly specified by the user,
  242. // versus a file/dir found by recursing into that path
  243. func (c *C) resolve(path string, direct bool) error {
  244. i, err := os.Stat(path)
  245. if err != nil {
  246. return nil
  247. }
  248. if !i.IsDir() {
  249. c.addFile(path, direct)
  250. return nil
  251. }
  252. paths, err := readDirNames(path)
  253. if err != nil {
  254. return fmt.Errorf("problem while reading directory %s: %s", path, err)
  255. }
  256. for _, p := range paths {
  257. err := c.resolve(filepath.Join(path, p), false)
  258. if err != nil {
  259. return err
  260. }
  261. }
  262. return nil
  263. }
  264. func (c *C) addFile(path string, direct bool) error {
  265. ext := filepath.Ext(path)
  266. if !direct && ext != ".yaml" && ext != ".yml" {
  267. return nil
  268. }
  269. ap, err := filepath.Abs(path)
  270. if err != nil {
  271. return err
  272. }
  273. c.files = append(c.files, ap)
  274. return nil
  275. }
  276. func (c *C) parseRaw(b []byte) error {
  277. var m map[interface{}]interface{}
  278. err := yaml.Unmarshal(b, &m)
  279. if err != nil {
  280. return err
  281. }
  282. c.Settings = m
  283. return nil
  284. }
  285. func (c *C) parse() error {
  286. var m map[interface{}]interface{}
  287. for _, path := range c.files {
  288. b, err := ioutil.ReadFile(path)
  289. if err != nil {
  290. return err
  291. }
  292. var nm map[interface{}]interface{}
  293. err = yaml.Unmarshal(b, &nm)
  294. if err != nil {
  295. return err
  296. }
  297. // We need to use WithAppendSlice so that firewall rules in separate
  298. // files are appended together
  299. err = mergo.Merge(&nm, m, mergo.WithAppendSlice)
  300. m = nm
  301. if err != nil {
  302. return err
  303. }
  304. }
  305. c.Settings = m
  306. return nil
  307. }
  308. func readDirNames(path string) ([]string, error) {
  309. f, err := os.Open(path)
  310. if err != nil {
  311. return nil, err
  312. }
  313. paths, err := f.Readdirnames(-1)
  314. f.Close()
  315. if err != nil {
  316. return nil, err
  317. }
  318. sort.Strings(paths)
  319. return paths, nil
  320. }