apic_metrics.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package apiserver
  2. import (
  3. "context"
  4. "slices"
  5. "time"
  6. log "github.com/sirupsen/logrus"
  7. "github.com/crowdsecurity/go-cs-lib/ptr"
  8. "github.com/crowdsecurity/go-cs-lib/trace"
  9. "github.com/crowdsecurity/go-cs-lib/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.Format(time.RFC3339),
  23. LastPush: ptr.OrEmpty(machine.LastPush).Format(time.RFC3339),
  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.Format(time.RFC3339),
  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 sending 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. metrics, err := a.GetMetrics()
  108. if err != nil {
  109. log.Errorf("unable to get metrics (%s)", err)
  110. }
  111. // metrics are nil if they could not be retrieved
  112. if metrics != nil {
  113. log.Info("capi metrics: sending")
  114. _, _, err = a.apiClient.Metrics.Add(context.Background(), metrics)
  115. if err != nil {
  116. log.Errorf("capi metrics: failed: %s", err)
  117. }
  118. }
  119. metTicker.Reset(nextMetInt())
  120. case <-a.metricsTomb.Dying(): // if one apic routine is dying, do we kill the others?
  121. checkTicker.Stop()
  122. metTicker.Stop()
  123. a.pullTomb.Kill(nil)
  124. a.pushTomb.Kill(nil)
  125. return
  126. }
  127. }
  128. }