apic_metrics.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. package apiserver
  2. import (
  3. "context"
  4. "time"
  5. log "github.com/sirupsen/logrus"
  6. "golang.org/x/exp/slices"
  7. "github.com/crowdsecurity/go-cs-lib/pkg/ptr"
  8. "github.com/crowdsecurity/go-cs-lib/pkg/trace"
  9. "github.com/crowdsecurity/go-cs-lib/pkg/version"
  10. "github.com/crowdsecurity/crowdsec/pkg/models"
  11. )
  12. func (a *apic) GetMetrics() (*models.Metrics, error) {
  13. machines, err := a.dbClient.ListMachines()
  14. if err != nil {
  15. return nil, err
  16. }
  17. machinesInfo := make([]*models.MetricsAgentInfo, len(machines))
  18. for i, machine := range machines {
  19. machinesInfo[i] = &models.MetricsAgentInfo{
  20. Version: machine.Version,
  21. Name: machine.MachineId,
  22. LastUpdate: machine.UpdatedAt.String(),
  23. LastPush: ptr.OrEmpty(machine.LastPush).String(),
  24. }
  25. }
  26. bouncers, err := a.dbClient.ListBouncers()
  27. if err != nil {
  28. return nil, err
  29. }
  30. bouncersInfo := make([]*models.MetricsBouncerInfo, len(bouncers))
  31. for i, bouncer := range bouncers {
  32. bouncersInfo[i] = &models.MetricsBouncerInfo{
  33. Version: bouncer.Version,
  34. CustomName: bouncer.Name,
  35. Name: bouncer.Type,
  36. LastPull: bouncer.LastPull.String(),
  37. }
  38. }
  39. return &models.Metrics{
  40. ApilVersion: ptr.Of(version.String()),
  41. Machines: machinesInfo,
  42. Bouncers: bouncersInfo,
  43. }, nil
  44. }
  45. func (a *apic) fetchMachineIDs() ([]string, error) {
  46. machines, err := a.dbClient.ListMachines()
  47. if err != nil {
  48. return nil, err
  49. }
  50. ret := make([]string, len(machines))
  51. for i, machine := range machines {
  52. ret[i] = machine.MachineId
  53. }
  54. // sorted slices are required for the slices.Equal comparison
  55. slices.Sort(ret)
  56. return ret, nil
  57. }
  58. // SendMetrics sends metrics to the API server until it receives a stop signal.
  59. //
  60. // Metrics are sent at start, then at the randomized metricsIntervalFirst,
  61. // then at regular metricsInterval. If a change is detected in the list
  62. // of machines, the next metrics are sent immediately.
  63. func (a *apic) SendMetrics(stop chan (bool)) {
  64. defer trace.CatchPanic("lapi/metricsToAPIC")
  65. // verify the list of machines every <checkInt> interval
  66. const checkInt = 20 * time.Second
  67. // intervals must always be > 0
  68. metInts := []time.Duration{1 * time.Millisecond, a.metricsIntervalFirst, a.metricsInterval}
  69. log.Infof("Start send metrics to CrowdSec Central API (interval: %s once, then %s)",
  70. metInts[1].Round(time.Second), metInts[2])
  71. count := -1
  72. nextMetInt := func() time.Duration {
  73. if count < len(metInts)-1 {
  74. count++
  75. }
  76. return metInts[count]
  77. }
  78. machineIDs := []string{}
  79. reloadMachineIDs := func() {
  80. ids, err := a.fetchMachineIDs()
  81. if err != nil {
  82. log.Debugf("unable to get machines (%s), will retry", err)
  83. return
  84. }
  85. machineIDs = ids
  86. }
  87. // store the list of machine IDs to compare
  88. // with the next list
  89. reloadMachineIDs()
  90. checkTicker := time.NewTicker(checkInt)
  91. metTicker := time.NewTicker(nextMetInt())
  92. for {
  93. select {
  94. case <-stop:
  95. checkTicker.Stop()
  96. metTicker.Stop()
  97. return
  98. case <-checkTicker.C:
  99. oldIDs := machineIDs
  100. reloadMachineIDs()
  101. if !slices.Equal(oldIDs, machineIDs) {
  102. log.Infof("capi metrics: machines changed, immediate send")
  103. metTicker.Reset(1 * time.Millisecond)
  104. }
  105. case <-metTicker.C:
  106. metTicker.Stop()
  107. log.Debug("capi metrics: acquiring lock")
  108. err := a.dbClient.AcquirePushMetricsLock()
  109. if a.dbClient.IsLocked(err) {
  110. log.Infof("another instance of crowdsec is already pushing metrics, skipping")
  111. metTicker.Reset(nextMetInt())
  112. return
  113. }
  114. if err != nil {
  115. log.Errorf("unable to acquire pushMetrics lock (%s)", err)
  116. }
  117. metrics, err := a.GetMetrics()
  118. if err != nil {
  119. log.Errorf("unable to get metrics (%s), will retry", err)
  120. }
  121. log.Info("capi metrics: sending")
  122. _, _, err = a.apiClient.Metrics.Add(context.Background(), metrics)
  123. if err != nil {
  124. log.Errorf("capi metrics: failed: %s", err)
  125. }
  126. log.Debug("capi metrics: releasing lock")
  127. err = a.dbClient.ReleasePushMetricsLock()
  128. if err != nil {
  129. log.Errorf("unable to release metrics lock (%s)", err)
  130. }
  131. metTicker.Reset(nextMetInt())
  132. case <-a.metricsTomb.Dying(): // if one apic routine is dying, do we kill the others?
  133. checkTicker.Stop()
  134. metTicker.Stop()
  135. a.pullTomb.Kill(nil)
  136. a.pushTomb.Kill(nil)
  137. return
  138. }
  139. }
  140. }