controller.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package exporter
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. "time"
  7. "github.com/opencost/opencost/core/pkg/log"
  8. "github.com/opencost/opencost/core/pkg/opencost"
  9. "github.com/opencost/opencost/core/pkg/source"
  10. "github.com/opencost/opencost/core/pkg/util/atomic"
  11. "github.com/opencost/opencost/core/pkg/util/timeutil"
  12. "github.com/opencost/opencost/core/pkg/util/typeutil"
  13. )
  14. // ExportController is a controller interface that is responsible for exporting data on a specific interval.
  15. type ExportController interface {
  16. // Name returns the name of the controller
  17. Name() string
  18. // Start starts a background compute processing loop, which will compute the data for the current resolution and export it
  19. // on the provided interval. This function will return `true` if the loop was started successfully, and `false` if it was
  20. // already running.
  21. Start(interval time.Duration) bool
  22. // Stops the compute processing loop
  23. Stop()
  24. }
  25. // EventExportController[T] is used to export timestamped events of type T on a specific interval.
  26. type EventExportController[T any] struct {
  27. runState atomic.AtomicRunState
  28. source ExportSource[T]
  29. exporter EventExporter[T]
  30. typeName string
  31. }
  32. // NewEventExportController creates a new `EventExportController[T]` instance which is used to export timestamped events of type T
  33. // on a specific interval.
  34. func NewEventExportController[T any](source ExportSource[T], exporter EventExporter[T]) *EventExportController[T] {
  35. return &EventExportController[T]{
  36. source: source,
  37. exporter: exporter,
  38. typeName: reflect.TypeOf((*T)(nil)).Elem().String(),
  39. }
  40. }
  41. // Name returns the name of the controller, which is the name of the T-type
  42. func (cd *EventExportController[T]) Name() string {
  43. return cd.typeName
  44. }
  45. // Start starts a background export loop, which will create a new event instance for the current minute-truncated time
  46. // and export it on the provided interval. This function will return `true` if the loop was started successfully, and
  47. // `false` if it was already running.
  48. func (cd *EventExportController[T]) Start(interval time.Duration) bool {
  49. cd.runState.WaitForReset()
  50. if !cd.runState.Start() {
  51. return false
  52. }
  53. go func() {
  54. for {
  55. select {
  56. case <-cd.runState.OnStop():
  57. cd.runState.Reset()
  58. return // exit go routine
  59. case <-time.After(interval):
  60. }
  61. // truncate the time to the second to ensure broad enough coverage for event exports
  62. t := time.Now().UTC().Truncate(time.Second)
  63. evt := cd.source.Make(t)
  64. if evt == nil {
  65. log.Debugf("[%s] No event data to export", cd.typeName)
  66. continue
  67. }
  68. err := cd.exporter.Export(t, evt)
  69. if err != nil {
  70. log.Warnf("[%s] Error during Write: %s", cd.typeName, err)
  71. }
  72. }
  73. }()
  74. return true
  75. }
  76. // Stops the export loop
  77. func (cd *EventExportController[T]) Stop() {
  78. cd.runState.Stop()
  79. }
  80. // ComputeExportController[T] is a controller type which leverages a `ComputeSource[T]` and `Exporter[T]`
  81. // to regularly compute the data for the current resolution and export it on a specific interval.
  82. type ComputeExportController[T any] struct {
  83. runState atomic.AtomicRunState
  84. source ComputeSource[T]
  85. exporter ComputeExporter[T]
  86. resolution time.Duration
  87. sourceResolution time.Duration
  88. lastExport time.Time
  89. typeName string
  90. }
  91. // NewComputeExportController creates a new `ComputeExportController[T]` instance.
  92. func NewComputeExportController[T any](
  93. source ComputeSource[T],
  94. exporter ComputeExporter[T],
  95. resolution time.Duration,
  96. sourceResolution time.Duration,
  97. ) *ComputeExportController[T] {
  98. return &ComputeExportController[T]{
  99. source: source,
  100. resolution: resolution,
  101. sourceResolution: sourceResolution,
  102. exporter: exporter,
  103. typeName: reflect.TypeOf((*T)(nil)).Elem().String(),
  104. }
  105. }
  106. // Name returns the name of the controller, which is a combination of the type name and the resolution
  107. func (cd *ComputeExportController[T]) Name() string {
  108. return cd.typeName + "-" + timeutil.FormatStoreResolution(cd.resolution)
  109. }
  110. // Start starts a background compute processing loop, which will compute the data for the current resolution and export it
  111. // on the provided interval. This function will return `true` if the loop was started successfully, and `false` if it was
  112. // already running.
  113. func (cd *ComputeExportController[T]) Start(interval time.Duration) bool {
  114. // Before we attempt to start, we must ensure we are not in a stopping state
  115. cd.runState.WaitForReset()
  116. // This will atomically check the current state to ensure we can run, then advances the state.
  117. // If the state is already started, it will return false.
  118. if !cd.runState.Start() {
  119. return false
  120. }
  121. // our run state is advanced, let's execute our action on the interval
  122. // spawn a new goroutine which will loop and wait the interval each iteration
  123. go func() {
  124. for {
  125. // use a select statement to receive whichever channel receives data first
  126. select {
  127. // if our stop channel receives data, it means we have explicitly called
  128. // Stop(), and must reset our AtomicRunState to it's initial idle state
  129. case <-cd.runState.OnStop():
  130. cd.runState.Reset()
  131. return // exit go routine
  132. // After our interval elapses, fall through
  133. case <-time.After(interval):
  134. }
  135. now := time.Now().UTC()
  136. windows := cd.exportWindowsFor(now)
  137. for _, window := range windows {
  138. err := cd.export(window)
  139. if err != nil {
  140. // Check ErrorCollection to set Warnings and Errors
  141. if source.IsErrorCollection(err) {
  142. c := err.(source.QueryErrorCollection)
  143. errors, warnings := c.ToErrorAndWarningStrings()
  144. cd.logErrors(window, warnings, errors)
  145. continue
  146. }
  147. log.Errorf("[%s] %s", cd.typeName, err)
  148. } else {
  149. cd.lastExport = now
  150. }
  151. }
  152. }
  153. }()
  154. return true
  155. }
  156. // exportWindows uses the last export time to determine the current time windows to
  157. // export. This will, at most, return 2 windows: the previous resolution window and
  158. // the current resolution window.
  159. func (cd *ComputeExportController[T]) exportWindowsFor(now time.Time) []opencost.Window {
  160. start := now.Truncate(cd.resolution)
  161. end := start.Add(cd.resolution)
  162. if cd.lastExport.IsZero() {
  163. return []opencost.Window{
  164. opencost.NewClosedWindow(start, end),
  165. }
  166. }
  167. lastStart := cd.lastExport.Truncate(cd.resolution)
  168. if lastStart.Equal(start) {
  169. return []opencost.Window{
  170. opencost.NewClosedWindow(start, end),
  171. }
  172. }
  173. lastEnd := lastStart.Add(cd.resolution)
  174. // we've identified that the last export window is not the same as the current,
  175. // so we should export the previous resolution window as well as the current one
  176. return []opencost.Window{
  177. opencost.NewClosedWindow(lastStart, lastEnd),
  178. opencost.NewClosedWindow(start, end),
  179. }
  180. }
  181. // export computes and exports the data for a given time window
  182. func (cd *ComputeExportController[T]) export(window opencost.Window) error {
  183. if window.IsOpen() {
  184. return fmt.Errorf("window is open: %s", window.String())
  185. }
  186. start, end := *window.Start(), *window.End()
  187. log.Debugf("[%s] Reporting for window: %s - %s", cd.typeName, start.UTC(), end.UTC())
  188. if !cd.source.CanCompute(start, end) {
  189. return fmt.Errorf("cannot compute window: [Start: %s, End: %s]", start, end)
  190. }
  191. set, err := cd.source.Compute(start, end, cd.sourceResolution)
  192. // all errors but NoDataError are considered a halt to the export
  193. if err != nil && !source.IsNoDataError(err) {
  194. return err
  195. }
  196. log.Debugf("[%s] Exporting data for window: %s - %s", cd.typeName, start.UTC(), end.UTC())
  197. err = cd.exporter.Export(window, set)
  198. if err != nil {
  199. return fmt.Errorf("write error: %w", err)
  200. }
  201. return nil
  202. }
  203. // Stops the compute processing loop
  204. func (cd *ComputeExportController[T]) Stop() {
  205. cd.runState.Stop()
  206. }
  207. // temporary
  208. func (cd *ComputeExportController[T]) logErrors(window opencost.Window, warnings []string, errors []string) {
  209. start, end := window.Start(), window.End()
  210. for _, w := range warnings {
  211. log.Warnf("[%s] (%s-%s) %s", cd.typeName, start.Format(time.RFC3339), end.Format(time.RFC3339), w)
  212. }
  213. for _, e := range errors {
  214. log.Errorf("[%s] (%s-%s) %s", cd.typeName, start.Format(time.RFC3339), end.Format(time.RFC3339), e)
  215. }
  216. }
  217. type ComputeExportControllerGroup[T any] struct {
  218. controllers []*ComputeExportController[T]
  219. }
  220. func NewComputeExportControllerGroup[T any](controllers ...*ComputeExportController[T]) *ComputeExportControllerGroup[T] {
  221. return &ComputeExportControllerGroup[T]{controllers: controllers}
  222. }
  223. func (g *ComputeExportControllerGroup[T]) Name() string {
  224. var sb strings.Builder
  225. sb.WriteRune('[')
  226. for i, c := range g.controllers {
  227. if i > 0 {
  228. sb.WriteRune('/')
  229. }
  230. sb.WriteString(c.Name())
  231. }
  232. sb.WriteRune(']')
  233. return sb.String()
  234. }
  235. func (g *ComputeExportControllerGroup[T]) Start(interval time.Duration) bool {
  236. if len(g.controllers) == 0 {
  237. log.Warnf("ComputeExportControllerGroup[%s] has no controllers to start", typeutil.TypeOf[T]())
  238. return false
  239. }
  240. for _, c := range g.controllers {
  241. if !c.Start(interval) {
  242. return false
  243. }
  244. }
  245. return true
  246. }
  247. func (g *ComputeExportControllerGroup[T]) Stop() {
  248. for _, c := range g.controllers {
  249. c.Stop()
  250. }
  251. }
  252. func (g *ComputeExportControllerGroup[T]) Resolutions() []time.Duration {
  253. resolutions := make([]time.Duration, 0, len(g.controllers))
  254. for _, c := range g.controllers {
  255. resolutions = append(resolutions, c.resolution)
  256. }
  257. return resolutions
  258. }