config_reloader.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package config
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "path/filepath"
  7. "reflect"
  8. "regexp"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "github.com/OliveTin/OliveTin/internal/configissues"
  13. "github.com/go-viper/mapstructure/v2"
  14. "github.com/knadh/koanf/parsers/yaml"
  15. "github.com/knadh/koanf/providers/file"
  16. "github.com/knadh/koanf/v2"
  17. "github.com/prometheus/client_golang/prometheus"
  18. "github.com/prometheus/client_golang/prometheus/promauto"
  19. log "github.com/sirupsen/logrus"
  20. )
  21. var (
  22. metricConfigActionCount = promauto.NewGauge(prometheus.GaugeOpts{
  23. Name: "olivetin_config_action_count",
  24. Help: "The number of actions in the config file",
  25. })
  26. metricConfigReloadedCount = promauto.NewCounter(prometheus.CounterOpts{
  27. Name: "olivetin_config_reloaded_count",
  28. Help: "The number of times the config has been reloaded",
  29. })
  30. listeners []func()
  31. )
  32. func AddListener(l func()) {
  33. listeners = append(listeners, l)
  34. }
  35. func AppendSource(cfg *Config, k *koanf.Koanf, configPath string) {
  36. log.WithFields(log.Fields{
  37. "configPath": configPath,
  38. }).Info("Appending cfg source")
  39. configissues.BeginConfigLoad()
  40. BeginLoadedSources()
  41. RecordLoadedSource(configPath)
  42. stampLoadedConfigSources(k, configPath)
  43. loadIncludedConfigsFromDir(k, configPath)
  44. if !unmarshalRoot(k, cfg) {
  45. return
  46. }
  47. applyStampedSourceFiles(k, cfg)
  48. afterLoadFinalize(cfg, configPath)
  49. }
  50. func unmarshalRoot(k *koanf.Koanf, cfg *Config) bool {
  51. err := k.UnmarshalWithConf("", cfg, koanf.UnmarshalConf{
  52. Tag: "koanf",
  53. DecoderConfig: &mapstructure.DecoderConfig{
  54. DecodeHook: mapstructure.ComposeDecodeHookFunc(
  55. envDecodeHookFunc,
  56. justificationDecodeHookFunc,
  57. mapstructure.StringToTimeDurationHookFunc(),
  58. mapstructure.TextUnmarshallerHookFunc(),
  59. ),
  60. WeaklyTypedInput: true,
  61. },
  62. })
  63. if err != nil {
  64. reportDecodeFailure(err)
  65. return false
  66. }
  67. return true
  68. }
  69. // A decode failure stops AppendSource before the issue list is rebuilt, so the
  70. // issue is published to the live list immediately as well as kept for later
  71. // rebuilds.
  72. func reportDecodeFailure(err error) {
  73. issue := configissues.Issue{
  74. Severity: configissues.SeverityError,
  75. Code: configissues.CodeConfigDecode,
  76. Message: fmt.Sprintf("Configuration could not be decoded: %v", err),
  77. }
  78. configissues.ReportSticky(issue)
  79. configissues.Report(issue)
  80. }
  81. func afterLoadFinalize(cfg *Config, configPath string) {
  82. metricConfigReloadedCount.Inc()
  83. metricConfigActionCount.Set(float64(len(cfg.Actions)))
  84. cfg.SetDir(filepath.Dir(configPath))
  85. cfg.Sanitize()
  86. applyPortEnvironmentOverride(cfg)
  87. for _, l := range listeners {
  88. l()
  89. }
  90. }
  91. // applyPortEnvironmentOverride lets the PORT environment variable take precedence
  92. // over the configured HTTP frontend port.
  93. func applyPortEnvironmentOverride(cfg *Config) {
  94. envPort := strings.TrimSpace(os.Getenv("PORT"))
  95. if envPort == "" {
  96. return
  97. }
  98. port, ok := parseEnvPort(envPort)
  99. if !ok {
  100. return
  101. }
  102. host, ok := listenHostOrDefault(cfg.ListenAddressSingleHTTPFrontend)
  103. if !ok {
  104. log.WithFields(log.Fields{
  105. "PORT": envPort,
  106. "listenAddress": cfg.ListenAddressSingleHTTPFrontend,
  107. }).Error("Ignoring PORT environment variable because listenAddressSingleHTTPFrontend is invalid")
  108. return
  109. }
  110. cfg.ListenAddressSingleHTTPFrontend = net.JoinHostPort(host, strconv.Itoa(port))
  111. log.WithFields(log.Fields{
  112. "address": cfg.ListenAddressSingleHTTPFrontend,
  113. }).Info("Using PORT environment variable for single HTTP frontend listen address")
  114. }
  115. func parseEnvPort(envPort string) (int, bool) {
  116. port, err := strconv.Atoi(envPort)
  117. if err != nil || port < 1 || port > 65535 {
  118. log.WithFields(log.Fields{
  119. "PORT": envPort,
  120. "error": err,
  121. }).Error("Ignoring invalid PORT environment variable")
  122. return 0, false
  123. }
  124. return port, true
  125. }
  126. func listenHostOrDefault(listenAddress string) (string, bool) {
  127. if strings.TrimSpace(listenAddress) == "" {
  128. return "0.0.0.0", true
  129. }
  130. host, _, err := net.SplitHostPort(listenAddress)
  131. if err != nil {
  132. return "", false
  133. }
  134. if host == "" {
  135. return "0.0.0.0", true
  136. }
  137. return host, true
  138. }
  139. // buildIncludePath constructs the full path to the include directory.
  140. func buildIncludePath(k *koanf.Koanf, baseConfigPath string) string {
  141. relativeIncludePath := k.String("include")
  142. return filepath.Join(filepath.Dir(baseConfigPath), relativeIncludePath)
  143. }
  144. // loadAndMergeYamlFiles loads and merges all YAML files from the include directory.
  145. func loadAndMergeYamlFiles(k *koanf.Koanf, includePath string, yamlFiles []string) {
  146. sort.Strings(yamlFiles)
  147. for _, filename := range yamlFiles {
  148. loadAndMergeIncludedFile(k, includePath, filename)
  149. }
  150. log.Infof("Finished loading %d included config file(s)", len(yamlFiles))
  151. }
  152. // loadIncludedConfigsFromDir loads configuration files from an include directory and merges them
  153. func loadIncludedConfigsFromDir(k *koanf.Koanf, baseConfigPath string) {
  154. relativeIncludePath := k.String("include")
  155. if relativeIncludePath == "" {
  156. return
  157. }
  158. includePath := buildIncludePath(k, baseConfigPath)
  159. log.WithFields(log.Fields{
  160. "includePath": includePath,
  161. }).Infof("Loading included configs from dir")
  162. yamlFiles, ok := listYamlFiles(includePath)
  163. if !ok || len(yamlFiles) == 0 {
  164. return
  165. }
  166. loadAndMergeYamlFiles(k, includePath, yamlFiles)
  167. }
  168. // validateIncludeDirectory checks if the given path exists and is a directory.
  169. func validateIncludeDirectory(includePath string) bool {
  170. dirInfo, err := os.Stat(includePath)
  171. if err != nil {
  172. log.Warnf("Include directory not found: %s", includePath)
  173. return false
  174. }
  175. if !dirInfo.IsDir() {
  176. log.Warnf("Include path is not a directory: %s", includePath)
  177. return false
  178. }
  179. return true
  180. }
  181. // isYamlFile checks if a filename has a YAML extension.
  182. func isYamlFile(name string) bool {
  183. return strings.HasSuffix(name, ".yml") || strings.HasSuffix(name, ".yaml")
  184. }
  185. // filterYamlFilesFromEntries extracts YAML file names from directory entries.
  186. func filterYamlFilesFromEntries(entries []os.DirEntry) []string {
  187. var yamlFiles []string
  188. for _, entry := range entries {
  189. if entry.IsDir() {
  190. continue
  191. }
  192. if isYamlFile(entry.Name()) {
  193. yamlFiles = append(yamlFiles, entry.Name())
  194. }
  195. }
  196. return yamlFiles
  197. }
  198. func listYamlFiles(includePath string) ([]string, bool) {
  199. if !validateIncludeDirectory(includePath) {
  200. return nil, false
  201. }
  202. entries, err := os.ReadDir(includePath)
  203. if err != nil {
  204. log.Errorf("Error reading include directory: %v", err)
  205. return nil, false
  206. }
  207. yamlFiles := filterYamlFilesFromEntries(entries)
  208. if len(yamlFiles) == 0 {
  209. log.Infof("No YAML files found in include directory: %s", includePath)
  210. }
  211. return yamlFiles, true
  212. }
  213. func loadAndMergeIncludedFile(k *koanf.Koanf, includePath, filename string) {
  214. filePath := filepath.Join(includePath, filename)
  215. if err := k.Load(file.Provider(filePath), yaml.Parser(), koanf.WithMergeFunc(mergeFuncForSource(filePath))); err != nil {
  216. configissues.ReportSticky(configissues.Issue{
  217. Severity: configissues.SeverityError,
  218. Code: configissues.CodeIncludeParse,
  219. Message: fmt.Sprintf("Included config file could not be loaded: %v", err),
  220. ConfigFile: filePath,
  221. })
  222. log.Errorf("Error loading included config file %s: %v", filePath, err)
  223. return
  224. }
  225. RecordLoadedSource(filePath)
  226. log.WithFields(log.Fields{
  227. "filePath": filePath,
  228. }).Info("Successfully loaded included config file")
  229. }
  230. func mergeFuncForSource(sourceFile string) func(src, dest map[string]any) error {
  231. return func(src map[string]any, dest map[string]any) error {
  232. return mergeFunc(src, dest, sourceFile)
  233. }
  234. }
  235. // mergeActionsWhenBothExist merges actions when both src and dest have actions.
  236. func mergeActionsWhenBothExist(srcActions any, destActions any, dest map[string]any, sourceFile string) {
  237. stampSourceOnMaps(srcActions, sourceFile)
  238. srcSlice, ok1 := srcActions.([]any)
  239. destSlice, ok2 := destActions.([]any)
  240. if ok1 && ok2 {
  241. dest["actions"] = append(destSlice, srcSlice...)
  242. } else {
  243. dest["actions"] = srcActions
  244. }
  245. }
  246. // mergeActionsFromSource merges actions from source into destination.
  247. func mergeActionsFromSource(srcActions any, dest map[string]any, sourceFile string) {
  248. if destActions, ok := dest["actions"]; ok {
  249. mergeActionsWhenBothExist(srcActions, destActions, dest, sourceFile)
  250. } else {
  251. stampSourceOnMaps(srcActions, sourceFile)
  252. dest["actions"] = srcActions
  253. }
  254. }
  255. // mergeDashboardsWhenBothExist merges dashboards when both src and dest have dashboards.
  256. func mergeDashboardsWhenBothExist(srcDashboards any, destDashboards any, dest map[string]any) {
  257. srcSlice, ok1 := srcDashboards.([]any)
  258. destSlice, ok2 := destDashboards.([]any)
  259. if ok1 && ok2 {
  260. dest["dashboards"] = append(destSlice, srcSlice...)
  261. } else {
  262. dest["dashboards"] = srcDashboards
  263. }
  264. }
  265. // mergeDashboardsFromSource merges dashboards from source into destination.
  266. func mergeDashboardsFromSource(srcDashboards any, dest map[string]any) {
  267. if destDashboards, ok := dest["dashboards"]; ok {
  268. mergeDashboardsWhenBothExist(srcDashboards, destDashboards, dest)
  269. } else {
  270. dest["dashboards"] = srcDashboards
  271. }
  272. }
  273. // mergeEntitiesWhenBothExist merges entities when both src and dest have entities.
  274. func mergeEntitiesWhenBothExist(srcEntities any, destEntities any, dest map[string]any, sourceFile string) {
  275. stampSourceOnMaps(srcEntities, sourceFile)
  276. srcSlice, ok1 := srcEntities.([]any)
  277. destSlice, ok2 := destEntities.([]any)
  278. if ok1 && ok2 {
  279. dest["entities"] = append(destSlice, srcSlice...)
  280. } else {
  281. dest["entities"] = srcEntities
  282. }
  283. }
  284. // mergeEntitiesFromSource merges entities from source into destination.
  285. func mergeEntitiesFromSource(srcEntities any, dest map[string]any, sourceFile string) {
  286. if destEntities, ok := dest["entities"]; ok {
  287. mergeEntitiesWhenBothExist(srcEntities, destEntities, dest, sourceFile)
  288. } else {
  289. stampSourceOnMaps(srcEntities, sourceFile)
  290. dest["entities"] = srcEntities
  291. }
  292. }
  293. func mergeFunc(src map[string]any, dest map[string]any, sourceFile string) error {
  294. if srcActions, ok := src["actions"]; ok {
  295. mergeActionsFromSource(srcActions, dest, sourceFile)
  296. }
  297. if srcDashboards, ok := src["dashboards"]; ok {
  298. mergeDashboardsFromSource(srcDashboards, dest)
  299. }
  300. if srcEntities, ok := src["entities"]; ok {
  301. mergeEntitiesFromSource(srcEntities, dest, sourceFile)
  302. }
  303. return nil
  304. }
  305. var envRegex = regexp.MustCompile(`\${{ *?(\S+) *?}}`)
  306. func justificationDecodeHookFunc(from reflect.Type, to reflect.Type, data any) (any, error) {
  307. if to.Kind() != reflect.String || from.Kind() != reflect.Bool {
  308. return data, nil
  309. }
  310. if data.(bool) {
  311. return JustificationRequiredNoTemplate, nil
  312. }
  313. return "", nil
  314. }
  315. func envDecodeHookFunc(from reflect.Type, to reflect.Type, data any) (any, error) {
  316. log.Tracef("envDecodeHookFunc called: from=%v, to=%v, data=%v", from, to, data)
  317. if from.Kind() != reflect.String {
  318. return data, nil
  319. }
  320. input := data.(string)
  321. log.Debugf("Processing string input: %q", input)
  322. output := envRegex.ReplaceAllStringFunc(input, func(match string) string {
  323. submatches := envRegex.FindStringSubmatch(match)
  324. key := submatches[1]
  325. val, set := os.LookupEnv(key)
  326. log.Debugf("Environment variable %q: set=%v, value=%q", key, set, val)
  327. if !set {
  328. configissues.ReportSticky(configissues.Issue{
  329. Severity: configissues.SeverityWarning,
  330. Code: configissues.CodeEnvUnset,
  331. Message: fmt.Sprintf("Config file references unset environment variable %q", key),
  332. Source: key,
  333. })
  334. }
  335. return val
  336. })
  337. log.Debugf("Environment variable interpolation result: %q -> %q", input, output)
  338. return output, nil
  339. }