apic_metrics.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package apiserver
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "slices"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/crowdsecurity/go-cs-lib/ptr"
  11. "github.com/crowdsecurity/go-cs-lib/trace"
  12. "github.com/crowdsecurity/go-cs-lib/version"
  13. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  14. "github.com/crowdsecurity/crowdsec/pkg/models"
  15. )
  16. func (a *apic) GetUsageMetrics() (*models.AllMetrics, error) {
  17. lpsMetrics, err := a.dbClient.GetLPsUsageMetrics()
  18. if err != nil {
  19. return nil, err
  20. }
  21. //spew.Dump(lpsMetrics)
  22. bouncersMetrics, err := a.dbClient.GetBouncersUsageMetrics()
  23. if err != nil {
  24. return nil, err
  25. }
  26. //spew.Dump(bouncersMetrics)
  27. allMetrics := &models.AllMetrics{}
  28. /*allLps, err := a.dbClient.ListMachines()
  29. if err != nil {
  30. return nil, err
  31. }
  32. allBouncers, err := a.dbClient.ListBouncers()
  33. if err != nil {
  34. return nil, err
  35. }*/
  36. lpsCache := make(map[string]*ent.Machine)
  37. bouncersCache := make(map[string]*ent.Bouncer)
  38. for _, lpsMetric := range lpsMetrics {
  39. lpName := lpsMetric.GeneratedBy
  40. metrics := models.LogProcessorsMetricsItems0{}
  41. err := json.Unmarshal([]byte(lpsMetric.Payload), &metrics)
  42. if err != nil {
  43. log.Errorf("unable to unmarshal LPs metrics (%s)", err)
  44. continue
  45. }
  46. var lp *ent.Machine
  47. if _, ok := lpsCache[lpName]; !ok {
  48. lp, err = a.dbClient.QueryMachineByID(lpName)
  49. if err != nil {
  50. log.Errorf("unable to get LP information for %s: %s", lpName, err)
  51. continue
  52. }
  53. } else {
  54. lp = lpsCache[lpName]
  55. }
  56. if lp.Hubstate != nil {
  57. metrics.HubItems = *lp.Hubstate
  58. }
  59. metrics.Os = &models.OSversion{
  60. Name: lp.Osname,
  61. Version: lp.Osversion,
  62. }
  63. metrics.FeatureFlags = strings.Split(lp.Featureflags, ",")
  64. metrics.Version = &lp.Version
  65. //TODO: meta
  66. allMetrics.LogProcessors = append(allMetrics.LogProcessors, models.LogProcessorsMetrics{&metrics})
  67. }
  68. for _, bouncersMetric := range bouncersMetrics {
  69. bouncerName := bouncersMetric.GeneratedBy
  70. metrics := models.RemediationComponentsMetricsItems0{}
  71. err := json.Unmarshal([]byte(bouncersMetric.Payload), &metrics)
  72. if err != nil {
  73. log.Errorf("unable to unmarshal bouncers metrics (%s)", err)
  74. continue
  75. }
  76. var bouncer *ent.Bouncer
  77. if _, ok := bouncersCache[bouncerName]; !ok {
  78. bouncer, err = a.dbClient.SelectBouncerByName(bouncerName)
  79. if err != nil {
  80. log.Errorf("unable to get bouncer information for %s: %s", bouncerName, err)
  81. continue
  82. }
  83. } else {
  84. bouncer = bouncersCache[bouncerName]
  85. }
  86. metrics.Os = &models.OSversion{
  87. Name: bouncer.Osname,
  88. Version: bouncer.Osversion,
  89. }
  90. metrics.Type = bouncer.Type
  91. metrics.FeatureFlags = strings.Split(bouncer.Featureflags, ",")
  92. //TODO: meta
  93. allMetrics.RemediationComponents = append(allMetrics.RemediationComponents, models.RemediationComponentsMetrics{&metrics})
  94. }
  95. //bouncerInfos := make(map[string]string)
  96. //TODO: add LAPI metrics
  97. return allMetrics, nil
  98. }
  99. func (a *apic) GetMetrics() (*models.Metrics, error) {
  100. machines, err := a.dbClient.ListMachines()
  101. if err != nil {
  102. return nil, err
  103. }
  104. machinesInfo := make([]*models.MetricsAgentInfo, len(machines))
  105. for i, machine := range machines {
  106. machinesInfo[i] = &models.MetricsAgentInfo{
  107. Version: machine.Version,
  108. Name: machine.MachineId,
  109. LastUpdate: machine.UpdatedAt.Format(time.RFC3339),
  110. LastPush: ptr.OrEmpty(machine.LastPush).Format(time.RFC3339),
  111. }
  112. }
  113. bouncers, err := a.dbClient.ListBouncers()
  114. if err != nil {
  115. return nil, err
  116. }
  117. bouncersInfo := make([]*models.MetricsBouncerInfo, len(bouncers))
  118. for i, bouncer := range bouncers {
  119. bouncersInfo[i] = &models.MetricsBouncerInfo{
  120. Version: bouncer.Version,
  121. CustomName: bouncer.Name,
  122. Name: bouncer.Type,
  123. LastPull: bouncer.LastPull.Format(time.RFC3339),
  124. }
  125. }
  126. return &models.Metrics{
  127. ApilVersion: ptr.Of(version.String()),
  128. Machines: machinesInfo,
  129. Bouncers: bouncersInfo,
  130. }, nil
  131. }
  132. func (a *apic) fetchMachineIDs() ([]string, error) {
  133. machines, err := a.dbClient.ListMachines()
  134. if err != nil {
  135. return nil, err
  136. }
  137. ret := make([]string, len(machines))
  138. for i, machine := range machines {
  139. ret[i] = machine.MachineId
  140. }
  141. // sorted slices are required for the slices.Equal comparison
  142. slices.Sort(ret)
  143. return ret, nil
  144. }
  145. // SendMetrics sends metrics to the API server until it receives a stop signal.
  146. //
  147. // Metrics are sent at start, then at the randomized metricsIntervalFirst,
  148. // then at regular metricsInterval. If a change is detected in the list
  149. // of machines, the next metrics are sent immediately.
  150. func (a *apic) SendMetrics(stop chan (bool)) {
  151. defer trace.CatchPanic("lapi/metricsToAPIC")
  152. // verify the list of machines every <checkInt> interval
  153. const checkInt = 20 * time.Second
  154. // intervals must always be > 0
  155. metInts := []time.Duration{1 * time.Millisecond, a.metricsIntervalFirst, a.metricsInterval}
  156. log.Infof("Start sending metrics to CrowdSec Central API (interval: %s once, then %s)",
  157. metInts[1].Round(time.Second), metInts[2])
  158. count := -1
  159. nextMetInt := func() time.Duration {
  160. if count < len(metInts)-1 {
  161. count++
  162. }
  163. return metInts[count]
  164. }
  165. machineIDs := []string{}
  166. reloadMachineIDs := func() {
  167. ids, err := a.fetchMachineIDs()
  168. if err != nil {
  169. log.Debugf("unable to get machines (%s), will retry", err)
  170. return
  171. }
  172. machineIDs = ids
  173. }
  174. // store the list of machine IDs to compare
  175. // with the next list
  176. reloadMachineIDs()
  177. checkTicker := time.NewTicker(checkInt)
  178. metTicker := time.NewTicker(nextMetInt())
  179. for {
  180. select {
  181. case <-stop:
  182. checkTicker.Stop()
  183. metTicker.Stop()
  184. return
  185. case <-checkTicker.C:
  186. oldIDs := machineIDs
  187. reloadMachineIDs()
  188. if !slices.Equal(oldIDs, machineIDs) {
  189. log.Infof("capi metrics: machines changed, immediate send")
  190. metTicker.Reset(1 * time.Millisecond)
  191. }
  192. case <-metTicker.C:
  193. metTicker.Stop()
  194. metrics, err := a.GetMetrics()
  195. if err != nil {
  196. log.Errorf("unable to get metrics (%s)", err)
  197. }
  198. // metrics are nil if they could not be retrieved
  199. if metrics != nil {
  200. log.Info("capi metrics: sending")
  201. _, _, err = a.apiClient.Metrics.Add(context.Background(), metrics)
  202. if err != nil {
  203. log.Errorf("capi metrics: failed: %s", err)
  204. }
  205. }
  206. metTicker.Reset(nextMetInt())
  207. case <-a.metricsTomb.Dying(): // if one apic routine is dying, do we kill the others?
  208. checkTicker.Stop()
  209. metTicker.Stop()
  210. a.pullTomb.Kill(nil)
  211. a.pushTomb.Kill(nil)
  212. return
  213. }
  214. }
  215. }
  216. func (a *apic) SendUsageMetrics() {
  217. defer trace.CatchPanic("lapi/usageMetricsToAPIC")
  218. ticker := time.NewTicker(5 * time.Second)
  219. for {
  220. select {
  221. case <-a.metricsTomb.Dying():
  222. //The normal metrics routine also kills push/pull tombs, does that make sense ?
  223. ticker.Stop()
  224. return
  225. case <-ticker.C:
  226. metrics, err := a.GetUsageMetrics()
  227. if err != nil {
  228. log.Errorf("unable to get usage metrics (%s)", err)
  229. }
  230. jsonStr, err := json.Marshal(metrics)
  231. if err != nil {
  232. log.Errorf("unable to marshal usage metrics (%s)", err)
  233. }
  234. fmt.Printf("Usage metrics: %s\n", string(jsonStr))
  235. }
  236. }
  237. }