controller.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. }
  90. // NewComputeExportController creates a new `ComputeExportController[T]` instance.
  91. func NewComputeExportController[T any](
  92. source ComputeSource[T],
  93. exporter ComputeExporter[T],
  94. resolution time.Duration,
  95. ) *ComputeExportController[T] {
  96. return &ComputeExportController[T]{
  97. source: source,
  98. resolution: resolution,
  99. exporter: exporter,
  100. typeName: reflect.TypeOf((*T)(nil)).Elem().String(),
  101. }
  102. }
  103. // Name returns the name of the controller, which is a combination of the type name and the resolution
  104. func (cd *ComputeExportController[T]) Name() string {
  105. return cd.typeName + "-" + timeutil.FormatStoreResolution(cd.resolution)
  106. }
  107. // Start starts a background compute processing loop, which will compute the data for the current resolution and export it
  108. // on the provided interval. This function will return `true` if the loop was started successfully, and `false` if it was
  109. // already running.
  110. func (cd *ComputeExportController[T]) Start(interval time.Duration) bool {
  111. // Before we attempt to start, we must ensure we are not in a stopping state
  112. cd.runState.WaitForReset()
  113. // This will atomically check the current state to ensure we can run, then advances the state.
  114. // If the state is already started, it will return false.
  115. if !cd.runState.Start() {
  116. return false
  117. }
  118. // our run state is advanced, let's execute our action on the interval
  119. // spawn a new goroutine which will loop and wait the interval each iteration
  120. go func() {
  121. for {
  122. // use a select statement to receive whichever channel receives data first
  123. select {
  124. // if our stop channel receives data, it means we have explicitly called
  125. // Stop(), and must reset our AtomicRunState to it's initial idle state
  126. case <-cd.runState.OnStop():
  127. cd.runState.Reset()
  128. return // exit go routine
  129. // After our interval elapses, fall through
  130. case <-time.After(interval):
  131. }
  132. now := time.Now().UTC()
  133. windows := cd.exportWindowsFor(now)
  134. for _, window := range windows {
  135. err := cd.export(window)
  136. if err != nil {
  137. // Check ErrorCollection to set Warnings and Errors
  138. if source.IsErrorCollection(err) {
  139. c := err.(source.QueryErrorCollection)
  140. errors, warnings := c.ToErrorAndWarningStrings()
  141. cd.logErrors(window, warnings, errors)
  142. continue
  143. }
  144. log.Errorf("[%s] %s", cd.typeName, err)
  145. } else {
  146. cd.lastExport = now
  147. }
  148. }
  149. }
  150. }()
  151. return true
  152. }
  153. // exportWindows uses the last export time to determine the current time windows to
  154. // export. This will, at most, return 2 windows: the previous resolution window and
  155. // the current resolution window.
  156. func (cd *ComputeExportController[T]) exportWindowsFor(now time.Time) []opencost.Window {
  157. start := now.Truncate(cd.resolution)
  158. end := start.Add(cd.resolution)
  159. if cd.lastExport.IsZero() {
  160. return []opencost.Window{
  161. opencost.NewClosedWindow(start, end),
  162. }
  163. }
  164. lastStart := cd.lastExport.Truncate(cd.resolution)
  165. if lastStart.Equal(start) {
  166. return []opencost.Window{
  167. opencost.NewClosedWindow(start, end),
  168. }
  169. }
  170. lastEnd := lastStart.Add(cd.resolution)
  171. // we've identified that the last export window is not the same as the current,
  172. // so we should export the previous resolution window as well as the current one
  173. return []opencost.Window{
  174. opencost.NewClosedWindow(lastStart, lastEnd),
  175. opencost.NewClosedWindow(start, end),
  176. }
  177. }
  178. // export computes and exports the data for a given time window
  179. func (cd *ComputeExportController[T]) export(window opencost.Window) error {
  180. if window.IsOpen() {
  181. return fmt.Errorf("window is open: %s", window.String())
  182. }
  183. start, end := *window.Start(), *window.End()
  184. log.Debugf("[%s] Reporting for window: %s - %s", cd.typeName, start.UTC(), end.UTC())
  185. if !cd.source.CanCompute(start, end) {
  186. return fmt.Errorf("cannot compute window: [Start: %s, End: %s]", start, end)
  187. }
  188. set, err := cd.source.Compute(start, end)
  189. // all errors but NoDataError are considered a halt to the export
  190. if err != nil && !source.IsNoDataError(err) {
  191. return err
  192. }
  193. log.Debugf("[%s] Exporting data for window: %s - %s", cd.typeName, start.UTC(), end.UTC())
  194. err = cd.exporter.Export(window, set)
  195. if err != nil {
  196. return fmt.Errorf("write error: %w", err)
  197. }
  198. return nil
  199. }
  200. // Stops the compute processing loop
  201. func (cd *ComputeExportController[T]) Stop() {
  202. cd.runState.Stop()
  203. }
  204. // temporary
  205. func (cd *ComputeExportController[T]) logErrors(window opencost.Window, warnings []string, errors []string) {
  206. start, end := window.Start(), window.End()
  207. for _, w := range warnings {
  208. log.Warnf("[%s] (%s-%s) %s", cd.typeName, start.Format(time.RFC3339), end.Format(time.RFC3339), w)
  209. }
  210. for _, e := range errors {
  211. log.Errorf("[%s] (%s-%s) %s", cd.typeName, start.Format(time.RFC3339), end.Format(time.RFC3339), e)
  212. }
  213. }
  214. type ComputeExportControllerGroup[T any] struct {
  215. controllers []*ComputeExportController[T]
  216. }
  217. func NewComputeExportControllerGroup[T any](controllers ...*ComputeExportController[T]) *ComputeExportControllerGroup[T] {
  218. return &ComputeExportControllerGroup[T]{controllers: controllers}
  219. }
  220. func (g *ComputeExportControllerGroup[T]) Name() string {
  221. var sb strings.Builder
  222. sb.WriteRune('[')
  223. for i, c := range g.controllers {
  224. if i > 0 {
  225. sb.WriteRune('/')
  226. }
  227. sb.WriteString(c.Name())
  228. }
  229. sb.WriteRune(']')
  230. return sb.String()
  231. }
  232. func (g *ComputeExportControllerGroup[T]) Start(interval time.Duration) bool {
  233. if len(g.controllers) == 0 {
  234. log.Warnf("ComputeExportControllerGroup[%s] has no controllers to start", typeutil.TypeOf[T]())
  235. return false
  236. }
  237. for _, c := range g.controllers {
  238. if !c.Start(interval) {
  239. return false
  240. }
  241. }
  242. return true
  243. }
  244. func (g *ComputeExportControllerGroup[T]) Stop() {
  245. for _, c := range g.controllers {
  246. c.Stop()
  247. }
  248. }
  249. func (g *ComputeExportControllerGroup[T]) Resolutions() []time.Duration {
  250. resolutions := make([]time.Duration, 0, len(g.controllers))
  251. for _, c := range g.controllers {
  252. resolutions = append(resolutions, c.resolution)
  253. }
  254. return resolutions
  255. }