1
0

config.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package config
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "math"
  8. "os"
  9. "os/signal"
  10. "path/filepath"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "syscall"
  16. "time"
  17. "dario.cat/mergo"
  18. "go.yaml.in/yaml/v3"
  19. )
  20. type C struct {
  21. path string
  22. files []string
  23. Settings map[string]any
  24. oldSettings map[string]any
  25. callbacks []func(*C)
  26. l *slog.Logger
  27. reloadLock sync.Mutex
  28. }
  29. func NewC(l *slog.Logger) *C {
  30. return &C{
  31. Settings: make(map[string]any),
  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 any
  81. ov any
  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.Error("Error while marshaling new config",
  94. "config_path", k,
  95. "error", err,
  96. )
  97. }
  98. oldVals, err := yaml.Marshal(ov)
  99. if err != nil {
  100. c.l.Error("Error while marshaling old config",
  101. "config_path", k,
  102. "error", err,
  103. )
  104. }
  105. return string(newVals) != string(oldVals)
  106. }
  107. // CatchHUP will listen for the HUP signal in a go routine and reload all configs found in the
  108. // original path provided to Load. The old settings are shallow copied for change detection after the reload.
  109. func (c *C) CatchHUP(ctx context.Context) {
  110. if c.path == "" {
  111. return
  112. }
  113. ch := make(chan os.Signal, 1)
  114. signal.Notify(ch, syscall.SIGHUP)
  115. go func() {
  116. for {
  117. select {
  118. case <-ctx.Done():
  119. signal.Stop(ch)
  120. close(ch)
  121. return
  122. case <-ch:
  123. c.l.Info("Caught HUP, reloading config")
  124. c.ReloadConfig()
  125. }
  126. }
  127. }()
  128. }
  129. func (c *C) ReloadConfig() {
  130. c.reloadLock.Lock()
  131. defer c.reloadLock.Unlock()
  132. c.oldSettings = make(map[string]any)
  133. for k, v := range c.Settings {
  134. c.oldSettings[k] = v
  135. }
  136. err := c.Load(c.path)
  137. if err != nil {
  138. c.l.Error("Error occurred while reloading config",
  139. "config_path", c.path,
  140. "error", err,
  141. )
  142. return
  143. }
  144. for _, v := range c.callbacks {
  145. v(c)
  146. }
  147. }
  148. func (c *C) ReloadConfigString(raw string) error {
  149. c.reloadLock.Lock()
  150. defer c.reloadLock.Unlock()
  151. c.oldSettings = make(map[string]any)
  152. for k, v := range c.Settings {
  153. c.oldSettings[k] = v
  154. }
  155. err := c.LoadString(raw)
  156. if err != nil {
  157. return err
  158. }
  159. for _, v := range c.callbacks {
  160. v(c)
  161. }
  162. return nil
  163. }
  164. // GetString will get the string for k or return the default d if not found or invalid
  165. func (c *C) GetString(k, d string) string {
  166. r := c.Get(k)
  167. if r == nil {
  168. return d
  169. }
  170. return fmt.Sprintf("%v", r)
  171. }
  172. // GetStringSlice will get the slice of strings for k or return the default d if not found or invalid
  173. func (c *C) GetStringSlice(k string, d []string) []string {
  174. r := c.Get(k)
  175. if r == nil {
  176. return d
  177. }
  178. rv, ok := r.([]any)
  179. if !ok {
  180. return d
  181. }
  182. v := make([]string, len(rv))
  183. for i := 0; i < len(v); i++ {
  184. v[i] = fmt.Sprintf("%v", rv[i])
  185. }
  186. return v
  187. }
  188. // GetMap will get the map for k or return the default d if not found or invalid
  189. func (c *C) GetMap(k string, d map[string]any) map[string]any {
  190. r := c.Get(k)
  191. if r == nil {
  192. return d
  193. }
  194. v, ok := r.(map[string]any)
  195. if !ok {
  196. return d
  197. }
  198. return v
  199. }
  200. // GetInt will get the int for k or return the default d if not found or invalid
  201. func (c *C) GetInt(k string, d int) int {
  202. r := c.GetString(k, strconv.Itoa(d))
  203. v, err := strconv.Atoi(r)
  204. if err != nil {
  205. return d
  206. }
  207. return v
  208. }
  209. // GetUint32 will get the uint32 for k or return the default d if not found or invalid
  210. func (c *C) GetUint32(k string, d uint32) uint32 {
  211. r := c.GetInt(k, int(d))
  212. if r < 0 || uint64(r) > uint64(math.MaxUint32) {
  213. return d
  214. }
  215. return uint32(r)
  216. }
  217. // GetBool will get the bool for k or return the default d if not found or invalid
  218. func (c *C) GetBool(k string, d bool) bool {
  219. r := strings.ToLower(c.GetString(k, fmt.Sprintf("%v", d)))
  220. v, err := strconv.ParseBool(r)
  221. if err != nil {
  222. switch r {
  223. case "y", "yes":
  224. return true
  225. case "n", "no":
  226. return false
  227. }
  228. return d
  229. }
  230. return v
  231. }
  232. func AsBool(v any) (value bool, ok bool) {
  233. switch x := v.(type) {
  234. case bool:
  235. return x, true
  236. case string:
  237. switch x {
  238. case "y", "yes":
  239. return true, true
  240. case "n", "no":
  241. return false, true
  242. }
  243. }
  244. return false, false
  245. }
  246. // GetDuration will get the duration for k or return the default d if not found or invalid
  247. func (c *C) GetDuration(k string, d time.Duration) time.Duration {
  248. r := c.GetString(k, "")
  249. v, err := time.ParseDuration(r)
  250. if err != nil {
  251. return d
  252. }
  253. return v
  254. }
  255. func (c *C) Get(k string) any {
  256. return c.get(k, c.Settings)
  257. }
  258. func (c *C) IsSet(k string) bool {
  259. return c.get(k, c.Settings) != nil
  260. }
  261. func (c *C) get(k string, v any) any {
  262. parts := strings.Split(k, ".")
  263. for _, p := range parts {
  264. m, ok := v.(map[string]any)
  265. if !ok {
  266. return nil
  267. }
  268. v, ok = m[p]
  269. if !ok {
  270. return nil
  271. }
  272. }
  273. return v
  274. }
  275. // direct signifies if this is the config path directly specified by the user,
  276. // versus a file/dir found by recursing into that path
  277. func (c *C) resolve(path string, direct bool) error {
  278. i, err := os.Stat(path)
  279. if err != nil {
  280. return nil
  281. }
  282. if !i.IsDir() {
  283. c.addFile(path, direct)
  284. return nil
  285. }
  286. paths, err := readDirNames(path)
  287. if err != nil {
  288. return fmt.Errorf("problem while reading directory %s: %s", path, err)
  289. }
  290. for _, p := range paths {
  291. err := c.resolve(filepath.Join(path, p), false)
  292. if err != nil {
  293. return err
  294. }
  295. }
  296. return nil
  297. }
  298. func (c *C) addFile(path string, direct bool) error {
  299. ext := filepath.Ext(path)
  300. if !direct && ext != ".yaml" && ext != ".yml" {
  301. return nil
  302. }
  303. ap, err := filepath.Abs(path)
  304. if err != nil {
  305. return err
  306. }
  307. c.files = append(c.files, ap)
  308. return nil
  309. }
  310. func (c *C) parseRaw(b []byte) error {
  311. var m map[string]any
  312. err := yaml.Unmarshal(b, &m)
  313. if err != nil {
  314. return err
  315. }
  316. c.Settings = m
  317. return nil
  318. }
  319. func (c *C) parse() error {
  320. var m map[string]any
  321. for _, path := range c.files {
  322. b, err := os.ReadFile(path)
  323. if err != nil {
  324. return err
  325. }
  326. var nm map[string]any
  327. err = yaml.Unmarshal(b, &nm)
  328. if err != nil {
  329. return err
  330. }
  331. // We need to use WithAppendSlice so that firewall rules in separate
  332. // files are appended together
  333. err = mergo.Merge(&nm, m, mergo.WithAppendSlice)
  334. m = nm
  335. if err != nil {
  336. return err
  337. }
  338. }
  339. c.Settings = m
  340. return nil
  341. }
  342. func readDirNames(path string) ([]string, error) {
  343. f, err := os.Open(path)
  344. if err != nil {
  345. return nil, err
  346. }
  347. paths, err := f.Readdirnames(-1)
  348. f.Close()
  349. if err != nil {
  350. return nil, err
  351. }
  352. sort.Strings(paths)
  353. return paths, nil
  354. }