config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. package config
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "maps"
  8. "math"
  9. "os"
  10. "os/signal"
  11. "path/filepath"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "syscall"
  17. "time"
  18. "dario.cat/mergo"
  19. "go.yaml.in/yaml/v3"
  20. )
  21. type C struct {
  22. path string
  23. files []string
  24. Settings map[string]any
  25. oldSettings map[string]any
  26. callbacks []func(*C, *Reload)
  27. l *slog.Logger
  28. reloadLock sync.Mutex
  29. // Set by the first reload that needs a restart and never cleared. Guarded by reloadLock
  30. needsRestart bool
  31. // callbackLock guards callbacks. Registration is not confined to startup: CatchHUP is
  32. // running from inside Main, and anything wired up after Main returns registers while
  33. // a HUP could already be reloading, so append and iteration have to be serialized.
  34. callbackLock sync.Mutex
  35. }
  36. func NewC(l *slog.Logger) *C {
  37. return &C{
  38. Settings: make(map[string]any),
  39. l: l,
  40. }
  41. }
  42. // Load will find all yaml files within path and load them in lexical order
  43. func (c *C) Load(path string) error {
  44. c.path = path
  45. c.files = make([]string, 0)
  46. err := c.resolve(path, true)
  47. if err != nil {
  48. return err
  49. }
  50. if len(c.files) == 0 {
  51. return fmt.Errorf("no config files found at %s", path)
  52. }
  53. sort.Strings(c.files)
  54. err = c.parse()
  55. if err != nil {
  56. return err
  57. }
  58. return nil
  59. }
  60. func (c *C) LoadString(raw string) error {
  61. if raw == "" {
  62. return errors.New("Empty configuration")
  63. }
  64. return c.parseRaw([]byte(raw))
  65. }
  66. // RegisterReloadCallback stores a function to be called when a config reload is triggered. The functions registered
  67. // here should decide if they need to make a change to the current process before making the change. HasChanged can be
  68. // used to help decide if a change is necessary.
  69. // These functions should return quickly or spawn their own go routine if they will take a while.
  70. // Use r to report anything that failed or needs a restart to apply.
  71. func (c *C) RegisterReloadCallback(f func(c *C, r *Reload)) {
  72. c.callbackLock.Lock()
  73. defer c.callbackLock.Unlock()
  74. c.callbacks = append(c.callbacks, f)
  75. }
  76. // reloadCallbacks returns a snapshot of the registered callbacks. Reloads iterate the
  77. // snapshot rather than the live slice, so a registration from another goroutine cannot
  78. // race the loop; a callback registered while a reload is in progress runs from the next
  79. // reload on. callbackLock is not held during the calls themselves, so a callback that
  80. // registers another callback does not deadlock.
  81. func (c *C) reloadCallbacks() []func(*C, *Reload) {
  82. c.callbackLock.Lock()
  83. defer c.callbackLock.Unlock()
  84. return append(make([]func(*C, *Reload), 0, len(c.callbacks)), c.callbacks...)
  85. }
  86. // InitialLoad returns true if this is the first load of the config, and ReloadConfig has not been called yet.
  87. func (c *C) InitialLoad() bool {
  88. return c.oldSettings == nil
  89. }
  90. // Render returns keys and their values as yaml, for a subsystem to remember what it applied. Empty means they couldn't
  91. // be rendered and should never match.
  92. func (c *C) Render(keys ...string) string {
  93. m := make(map[string]any, len(keys))
  94. for _, k := range keys {
  95. m[k] = c.Get(k)
  96. }
  97. b, err := yaml.Marshal(m)
  98. if err != nil {
  99. c.l.Debug("Failed to render config", "keys", keys, "error", err)
  100. return ""
  101. }
  102. return string(b)
  103. }
  104. // HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
  105. // k in both the old and new settings will be serialized, the result of the string comparison is returned.
  106. // If k is an empty string the entire config is tested.
  107. // It's important to note that this is very rudimentary and susceptible to configuration ordering issues indicating
  108. // there is change when there actually wasn't any.
  109. func (c *C) HasChanged(k string) bool {
  110. if c.oldSettings == nil {
  111. return false
  112. }
  113. var (
  114. nv any
  115. ov any
  116. )
  117. if k == "" {
  118. nv = c.Settings
  119. ov = c.oldSettings
  120. k = "all settings"
  121. } else {
  122. nv = c.get(k, c.Settings)
  123. ov = c.get(k, c.oldSettings)
  124. }
  125. newVals, err := yaml.Marshal(nv)
  126. if err != nil {
  127. c.l.Error("Error while marshaling new config",
  128. "config_path", k,
  129. "error", err,
  130. )
  131. }
  132. oldVals, err := yaml.Marshal(ov)
  133. if err != nil {
  134. c.l.Error("Error while marshaling old config",
  135. "config_path", k,
  136. "error", err,
  137. )
  138. }
  139. return string(newVals) != string(oldVals)
  140. }
  141. // CatchHUP will listen for the HUP signal in a go routine and reload all configs found in the
  142. // original path provided to Load. The old settings are shallow copied for change detection after the reload.
  143. func (c *C) CatchHUP(ctx context.Context) {
  144. if c.path == "" {
  145. return
  146. }
  147. ch := make(chan os.Signal, 1)
  148. signal.Notify(ch, syscall.SIGHUP)
  149. go func() {
  150. for {
  151. select {
  152. case <-ctx.Done():
  153. signal.Stop(ch)
  154. close(ch)
  155. return
  156. case <-ch:
  157. c.l.Info("Caught HUP, reloading config")
  158. c.ReloadConfig().Log(c.l)
  159. }
  160. }
  161. }()
  162. }
  163. // ReloadConfig reloads the config from the path provided to Load and runs every registered callback. A config that
  164. // fails to load is logged here, like any other failure, and the result carries the error for the summary.
  165. func (c *C) ReloadConfig() ReloadResult {
  166. c.reloadLock.Lock()
  167. defer c.reloadLock.Unlock()
  168. c.oldSettings = make(map[string]any)
  169. maps.Copy(c.oldSettings, c.Settings)
  170. if err := c.Load(c.path); err != nil {
  171. c.l.Error("Error occurred while reloading config", "config_path", c.path, "error", err)
  172. return ReloadResult{Err: err, RestartRequired: c.needsRestart}
  173. }
  174. return c.runCallbacks()
  175. }
  176. // ReloadConfigString is ReloadConfig for a config held in memory rather than on disk.
  177. func (c *C) ReloadConfigString(raw string) ReloadResult {
  178. c.reloadLock.Lock()
  179. defer c.reloadLock.Unlock()
  180. c.oldSettings = make(map[string]any)
  181. maps.Copy(c.oldSettings, c.Settings)
  182. if err := c.LoadString(raw); err != nil {
  183. c.l.Error("Error occurred while reloading config", "error", err)
  184. return ReloadResult{Err: err, RestartRequired: c.needsRestart}
  185. }
  186. return c.runCallbacks()
  187. }
  188. func (c *C) runCallbacks() ReloadResult {
  189. r := &Reload{c: c}
  190. for _, v := range c.reloadCallbacks() {
  191. v(c, r)
  192. }
  193. if r.restart {
  194. c.needsRestart = true
  195. }
  196. return ReloadResult{Failed: r.failed, RestartRequired: c.needsRestart, RestartKeys: r.keys}
  197. }
  198. // GetString will get the string for k or return the default d if not found or invalid
  199. func (c *C) GetString(k, d string) string {
  200. r := c.Get(k)
  201. if r == nil {
  202. return d
  203. }
  204. return fmt.Sprintf("%v", r)
  205. }
  206. // GetStringSlice will get the slice of strings for k or return the default d if not found or invalid
  207. func (c *C) GetStringSlice(k string, d []string) []string {
  208. r := c.Get(k)
  209. if r == nil {
  210. return d
  211. }
  212. rv, ok := r.([]any)
  213. if !ok {
  214. return d
  215. }
  216. v := make([]string, len(rv))
  217. for i := range v {
  218. v[i] = fmt.Sprintf("%v", rv[i])
  219. }
  220. return v
  221. }
  222. // GetMap will get the map for k or return the default d if not found or invalid
  223. func (c *C) GetMap(k string, d map[string]any) map[string]any {
  224. r := c.Get(k)
  225. if r == nil {
  226. return d
  227. }
  228. v, ok := r.(map[string]any)
  229. if !ok {
  230. return d
  231. }
  232. return v
  233. }
  234. // GetInt will get the int for k or return the default d if not found or invalid
  235. func (c *C) GetInt(k string, d int) int {
  236. r := c.GetString(k, strconv.Itoa(d))
  237. v, err := strconv.Atoi(r)
  238. if err != nil {
  239. return d
  240. }
  241. return v
  242. }
  243. // GetUint32 will get the uint32 for k or return the default d if not found or invalid
  244. func (c *C) GetUint32(k string, d uint32) uint32 {
  245. r := c.GetInt(k, int(d))
  246. if r < 0 || uint64(r) > uint64(math.MaxUint32) {
  247. return d
  248. }
  249. return uint32(r)
  250. }
  251. // GetBool will get the bool for k or return the default d if not found or invalid
  252. func (c *C) GetBool(k string, d bool) bool {
  253. r := strings.ToLower(c.GetString(k, fmt.Sprintf("%v", d)))
  254. v, err := strconv.ParseBool(r)
  255. if err != nil {
  256. switch r {
  257. case "y", "yes":
  258. return true
  259. case "n", "no":
  260. return false
  261. }
  262. return d
  263. }
  264. return v
  265. }
  266. func AsBool(v any) (value bool, ok bool) {
  267. switch x := v.(type) {
  268. case bool:
  269. return x, true
  270. case string:
  271. switch x {
  272. case "y", "yes":
  273. return true, true
  274. case "n", "no":
  275. return false, true
  276. }
  277. }
  278. return false, false
  279. }
  280. // GetDuration will get the duration for k or return the default d if not found or invalid
  281. func (c *C) GetDuration(k string, d time.Duration) time.Duration {
  282. r := c.GetString(k, "")
  283. v, err := time.ParseDuration(r)
  284. if err != nil {
  285. return d
  286. }
  287. return v
  288. }
  289. func (c *C) Get(k string) any {
  290. return c.get(k, c.Settings)
  291. }
  292. func (c *C) IsSet(k string) bool {
  293. return c.get(k, c.Settings) != nil
  294. }
  295. func (c *C) get(k string, v any) any {
  296. parts := strings.SplitSeq(k, ".")
  297. for p := range parts {
  298. m, ok := v.(map[string]any)
  299. if !ok {
  300. return nil
  301. }
  302. v, ok = m[p]
  303. if !ok {
  304. return nil
  305. }
  306. }
  307. return v
  308. }
  309. // direct signifies if this is the config path directly specified by the user,
  310. // versus a file/dir found by recursing into that path
  311. func (c *C) resolve(path string, direct bool) error {
  312. i, err := os.Stat(path)
  313. if err != nil {
  314. return nil
  315. }
  316. if !i.IsDir() {
  317. c.addFile(path, direct)
  318. return nil
  319. }
  320. paths, err := readDirNames(path)
  321. if err != nil {
  322. return fmt.Errorf("problem while reading directory %s: %s", path, err)
  323. }
  324. for _, p := range paths {
  325. err := c.resolve(filepath.Join(path, p), false)
  326. if err != nil {
  327. return err
  328. }
  329. }
  330. return nil
  331. }
  332. func (c *C) addFile(path string, direct bool) error {
  333. ext := filepath.Ext(path)
  334. if !direct && ext != ".yaml" && ext != ".yml" {
  335. return nil
  336. }
  337. ap, err := filepath.Abs(path)
  338. if err != nil {
  339. return err
  340. }
  341. c.files = append(c.files, ap)
  342. return nil
  343. }
  344. func (c *C) parseRaw(b []byte) error {
  345. var m map[string]any
  346. err := yaml.Unmarshal(b, &m)
  347. if err != nil {
  348. return err
  349. }
  350. c.Settings = m
  351. return nil
  352. }
  353. func (c *C) parse() error {
  354. var m map[string]any
  355. for _, path := range c.files {
  356. b, err := os.ReadFile(path)
  357. if err != nil {
  358. return err
  359. }
  360. var nm map[string]any
  361. err = yaml.Unmarshal(b, &nm)
  362. if err != nil {
  363. return fmt.Errorf("%s: %w", path, err)
  364. }
  365. // We need to use WithAppendSlice so that firewall rules in separate
  366. // files are appended together
  367. err = mergo.Merge(&nm, m, mergo.WithAppendSlice)
  368. m = nm
  369. if err != nil {
  370. return err
  371. }
  372. }
  373. c.Settings = m
  374. return nil
  375. }
  376. func readDirNames(path string) ([]string, error) {
  377. f, err := os.Open(path)
  378. if err != nil {
  379. return nil, err
  380. }
  381. paths, err := f.Readdirnames(-1)
  382. f.Close()
  383. if err != nil {
  384. return nil, err
  385. }
  386. sort.Strings(paths)
  387. return paths, nil
  388. }