controller.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. lastExport time.Time
  88. typeName string
  89. // now returns the current time; overridable for tests
  90. now func() time.Time
  91. }
  92. // NewComputeExportController creates a new `ComputeExportController[T]` instance.
  93. func NewComputeExportController[T any](
  94. source ComputeSource[T],
  95. exporter ComputeExporter[T],
  96. resolution time.Duration,
  97. ) *ComputeExportController[T] {
  98. return &ComputeExportController[T]{
  99. source: source,
  100. resolution: resolution,
  101. exporter: exporter,
  102. typeName: reflect.TypeFor[T]().String(),
  103. now: func() time.Time { return time.Now().UTC() },
  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. cd.tick(cd.now())
  136. }
  137. }()
  138. return true
  139. }
  140. // tick runs a single export pass for the provided time.
  141. func (cd *ComputeExportController[T]) tick(now time.Time) {
  142. windows := cd.exportWindowsFor(now)
  143. for _, window := range windows {
  144. err := cd.export(window)
  145. if err != nil {
  146. // Check ErrorCollection to set Warnings and Errors
  147. if source.IsErrorCollection(err) {
  148. c := err.(source.QueryErrorCollection)
  149. errors, warnings := c.ToErrorAndWarningStrings()
  150. cd.logErrors(window, warnings, errors)
  151. continue
  152. }
  153. log.Errorf("[%s] %s", cd.typeName, err)
  154. } else {
  155. cd.lastExport = now
  156. }
  157. }
  158. }
  159. // exportWindows uses the last export time to determine the current time windows to
  160. // export. This will, at most, return 2 windows: the previous resolution window and
  161. // the current resolution window.
  162. func (cd *ComputeExportController[T]) exportWindowsFor(now time.Time) []opencost.Window {
  163. start := now.Truncate(cd.resolution)
  164. end := start.Add(cd.resolution)
  165. if cd.lastExport.IsZero() {
  166. return []opencost.Window{
  167. opencost.NewClosedWindow(start, end),
  168. }
  169. }
  170. lastStart := cd.lastExport.Truncate(cd.resolution)
  171. if lastStart.Equal(start) {
  172. return []opencost.Window{
  173. opencost.NewClosedWindow(start, end),
  174. }
  175. }
  176. lastEnd := lastStart.Add(cd.resolution)
  177. // we've identified that the last export window is not the same as the current,
  178. // so we should export the previous resolution window as well as the current one
  179. return []opencost.Window{
  180. opencost.NewClosedWindow(lastStart, lastEnd),
  181. opencost.NewClosedWindow(start, end),
  182. }
  183. }
  184. // export computes and exports the data for a given time window
  185. func (cd *ComputeExportController[T]) export(window opencost.Window) error {
  186. if window.IsOpen() {
  187. return fmt.Errorf("window is open: %s", window.String())
  188. }
  189. start, end := *window.Start(), *window.End()
  190. log.Debugf("[%s] Reporting for window: %s - %s", cd.typeName, start.UTC(), end.UTC())
  191. if !cd.source.CanCompute(start, end) {
  192. return fmt.Errorf("cannot compute window: [Start: %s, End: %s]", start, end)
  193. }
  194. set, err := cd.source.Compute(start, end)
  195. // all errors but NoDataError are considered a halt to the export
  196. if err != nil && !source.IsNoDataError(err) {
  197. return err
  198. }
  199. log.Debugf("[%s] Exporting data for window: %s - %s", cd.typeName, start.UTC(), end.UTC())
  200. err = cd.exporter.Export(window, set)
  201. if err != nil {
  202. return fmt.Errorf("write error: %w", err)
  203. }
  204. return nil
  205. }
  206. // Stops the compute processing loop
  207. func (cd *ComputeExportController[T]) Stop() {
  208. cd.runState.Stop()
  209. }
  210. // temporary
  211. func (cd *ComputeExportController[T]) logErrors(window opencost.Window, warnings []string, errors []string) {
  212. start, end := window.Start(), window.End()
  213. for _, w := range warnings {
  214. log.Warnf("[%s] (%s-%s) %s", cd.typeName, start.Format(time.RFC3339), end.Format(time.RFC3339), w)
  215. }
  216. for _, e := range errors {
  217. log.Errorf("[%s] (%s-%s) %s", cd.typeName, start.Format(time.RFC3339), end.Format(time.RFC3339), e)
  218. }
  219. }
  220. type ComputeExportControllerGroup[T any] struct {
  221. controllers []*ComputeExportController[T]
  222. }
  223. func NewComputeExportControllerGroup[T any](controllers ...*ComputeExportController[T]) *ComputeExportControllerGroup[T] {
  224. return &ComputeExportControllerGroup[T]{controllers: controllers}
  225. }
  226. func (g *ComputeExportControllerGroup[T]) Name() string {
  227. var sb strings.Builder
  228. sb.WriteRune('[')
  229. for i, c := range g.controllers {
  230. if i > 0 {
  231. sb.WriteRune('/')
  232. }
  233. sb.WriteString(c.Name())
  234. }
  235. sb.WriteRune(']')
  236. return sb.String()
  237. }
  238. func (g *ComputeExportControllerGroup[T]) Start(interval time.Duration) bool {
  239. if len(g.controllers) == 0 {
  240. log.Debugf("ComputeExportControllerGroup[%s] has no controllers to start", typeutil.TypeOf[T]())
  241. return false
  242. }
  243. for _, c := range g.controllers {
  244. if !c.Start(interval) {
  245. return false
  246. }
  247. }
  248. return true
  249. }
  250. func (g *ComputeExportControllerGroup[T]) Stop() {
  251. for _, c := range g.controllers {
  252. c.Stop()
  253. }
  254. }
  255. func (g *ComputeExportControllerGroup[T]) Resolutions() []time.Duration {
  256. resolutions := make([]time.Duration, 0, len(g.controllers))
  257. for _, c := range g.controllers {
  258. resolutions = append(resolutions, c.resolution)
  259. }
  260. return resolutions
  261. }