store.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package configissues
  2. import (
  3. "context"
  4. "maps"
  5. "sync"
  6. "time"
  7. health "github.com/jamesread/armature-health/v2"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. // Issues are kept by armature-health in memory, grouped by where they come from.
  11. // A rebuild replaces the "config" and "config.load" sources, and leaves "runtime"
  12. // alone, so issues found while OliveTin is running survive config reloads.
  13. const (
  14. sourceConfig = "config"
  15. sourceConfigLoad = "config.load"
  16. sourceRuntime = "runtime"
  17. )
  18. var sourceOrder = []string{sourceConfigLoad, sourceRuntime, sourceConfig}
  19. // OliveTin only shows open issues, so resolved ones are not kept for long.
  20. const resolvedRetention = time.Hour
  21. var (
  22. service = health.NewService(nil, nil, nil, health.Options{
  23. SourceTitles: map[string]string{
  24. sourceConfig: "Configuration",
  25. sourceConfigLoad: "Configuration loading",
  26. sourceRuntime: "Runtime",
  27. },
  28. ResolvedRetention: resolvedRetention,
  29. })
  30. stickyMu sync.Mutex
  31. sticky []Issue
  32. // writeMu makes each change and the logging of the issues it adds one step,
  33. // so concurrent reports cannot log the same new issue twice.
  34. writeMu sync.Mutex
  35. // current is the ordered issue list, rebuilt after each change. Every change
  36. // goes through this package, so it always matches what is stored.
  37. snapshotMu sync.RWMutex
  38. current []Issue
  39. currentSeverities map[string]string
  40. )
  41. // BeginConfigLoad clears sticky issues captured during config decode/include load.
  42. func BeginConfigLoad() {
  43. stickyMu.Lock()
  44. defer stickyMu.Unlock()
  45. sticky = nil
  46. }
  47. // ReportSticky records an issue that cannot be re-derived after config decode
  48. // (for example unset environment variables that were already expanded).
  49. func ReportSticky(issue Issue) {
  50. stickyMu.Lock()
  51. defer stickyMu.Unlock()
  52. sticky = append(sticky, issue)
  53. }
  54. // CopySticky returns a copy of sticky load-time issues.
  55. func CopySticky() []Issue {
  56. stickyMu.Lock()
  57. defer stickyMu.Unlock()
  58. out := make([]Issue, len(sticky))
  59. copy(out, sticky)
  60. return out
  61. }
  62. // Replace sets the issues derived from the current configuration. Issues that
  63. // were already present are kept (and not logged again), and missing ones are
  64. // resolved.
  65. func Replace(next []Issue) {
  66. setSource(sourceConfig, next)
  67. }
  68. // ReplaceLoadIssues sets the issues found while loading configuration.
  69. func ReplaceLoadIssues(next []Issue) {
  70. setSource(sourceConfigLoad, next)
  71. }
  72. // Report adds a live issue if it is not already present and logs it when new.
  73. // Use this for runtime discoveries that happen outside Rebuild (for example
  74. // filesystem watcher setup failures). The next Rebuild resolves it unless the
  75. // rebuild finds it again.
  76. func Report(issue Issue) {
  77. raise(sourceConfig, issue)
  78. }
  79. // List returns the current issues.
  80. func List() []Issue {
  81. snapshotMu.RLock()
  82. defer snapshotMu.RUnlock()
  83. out := make([]Issue, len(current))
  84. copy(out, current)
  85. return out
  86. }
  87. // Count returns the number of current issues.
  88. func Count() int {
  89. snapshotMu.RLock()
  90. defer snapshotMu.RUnlock()
  91. return len(current)
  92. }
  93. func setSource(sourceID string, next []Issue) {
  94. writeMu.Lock()
  95. defer writeMu.Unlock()
  96. before := copyCurrentSeverities()
  97. rememberOrder(sourceID, next)
  98. if err := service.SetIssues(context.Background(), sourceID, toHealthIssues(next)); err != nil {
  99. log.WithError(err).WithField("source", sourceID).Error("Could not save configuration issues")
  100. return
  101. }
  102. refreshSnapshot()
  103. logNewIssues(before, next)
  104. }
  105. func raise(sourceID string, issue Issue) {
  106. writeMu.Lock()
  107. defer writeMu.Unlock()
  108. before := copyCurrentSeverities()
  109. if err := service.Raise(context.Background(), sourceID, toHealthIssue(issue)); err != nil {
  110. log.WithError(err).WithField("source", sourceID).Error("Could not save configuration issue")
  111. return
  112. }
  113. // Raising an issue that is already listed with the same severity only adds an
  114. // occurrence, so the list does not need rebuilding. This keeps repeated reports,
  115. // such as every call to a deprecated API method, cheap.
  116. if before[issueKey(issue)] == string(healthSeverity(issue.Severity)) {
  117. return
  118. }
  119. refreshSnapshot()
  120. logNewIssues(before, []Issue{issue})
  121. }
  122. // refreshSnapshot rebuilds the list returned by List after a change, so that
  123. // reading the list does not have to sort every stored issue each time.
  124. func refreshSnapshot() {
  125. stored, err := service.ListIssues(context.Background(), false, true)
  126. if err != nil {
  127. log.WithError(err).Error("Could not list configuration issues")
  128. return
  129. }
  130. // Severities are keyed by the stored key rather than one worked out again from
  131. // the listed issue, because armature-health shortens long titles and attributes.
  132. views := orderedIssueViews(stored)
  133. ordered := make([]Issue, 0, len(views))
  134. severities := make(map[string]string, len(views))
  135. for _, view := range views {
  136. ordered = append(ordered, fromHealthIssue(view))
  137. severities[view.IssueKey] = view.Severity
  138. }
  139. snapshotMu.Lock()
  140. defer snapshotMu.Unlock()
  141. current = ordered
  142. currentSeverities = severities
  143. }
  144. func copyCurrentSeverities() map[string]string {
  145. snapshotMu.RLock()
  146. defer snapshotMu.RUnlock()
  147. out := make(map[string]string, len(currentSeverities))
  148. maps.Copy(out, currentSeverities)
  149. return out
  150. }
  151. // logNewIssues logs issues that were not open before, or whose severity changed,
  152. // in the order they were collected, so startup and reloads do not repeat the
  153. // same warnings.
  154. func logNewIssues(before map[string]string, issues []Issue) {
  155. for _, issue := range issues {
  156. key := issueKey(issue)
  157. severity := string(healthSeverity(issue.Severity))
  158. if before[key] == severity {
  159. continue
  160. }
  161. before[key] = severity
  162. logNewIssue(issue)
  163. }
  164. }
  165. func logNewIssue(issue Issue) {
  166. fields := log.Fields{
  167. "code": issue.Code,
  168. "actionTitle": issue.ActionTitle,
  169. "argumentName": issue.ArgumentName,
  170. "configFile": issue.ConfigFile,
  171. "source": issue.Source,
  172. }
  173. if issue.Severity == SeverityError {
  174. log.WithFields(fields).Error(issue.Message)
  175. return
  176. }
  177. log.WithFields(fields).Warn(issue.Message)
  178. }