metrics.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package logic
  2. import (
  3. "context"
  4. "math"
  5. "strconv"
  6. "time"
  7. "github.com/gravitl/netmaker/models"
  8. )
  9. type MetricsMonitor struct {
  10. cancel context.CancelFunc
  11. }
  12. var metricsMonitor MetricsMonitor
  13. func GetMetricsMonitor() *MetricsMonitor {
  14. return &metricsMonitor
  15. }
  16. func (m *MetricsMonitor) Start() {
  17. if m.cancel != nil {
  18. m.cancel()
  19. m.cancel = nil
  20. }
  21. var ctx context.Context
  22. ctx, m.cancel = context.WithCancel(context.Background())
  23. go func(ctx context.Context) {
  24. metricsInterval, _ := strconv.Atoi(GetServerSettings().MetricInterval)
  25. if metricsInterval == 0 {
  26. return
  27. }
  28. checkInterval := time.Duration(2*metricsInterval) * time.Minute
  29. for {
  30. select {
  31. case <-time.After(checkInterval):
  32. nodes, _ := GetAllNodes()
  33. for _, node := range nodes {
  34. if node.Connected || node.PendingDelete {
  35. continue
  36. }
  37. nodeMetrics, err := GetMetrics(node.ID.String())
  38. if err == nil {
  39. inc := math.Round(float64(time.Since(nodeMetrics.UpdatedAt)) / float64(time.Minute))
  40. for peer, peerMetrics := range nodeMetrics.Connectivity {
  41. peerMetrics.TotalTime += int64(inc)
  42. peerMetrics.PercentUp = 100.0 * (float64(peerMetrics.Uptime) / float64(peerMetrics.TotalTime))
  43. nodeMetrics.Connectivity[peer] = peerMetrics
  44. }
  45. _ = UpdateMetrics(node.ID.String(), nodeMetrics)
  46. }
  47. }
  48. case <-ctx.Done():
  49. return
  50. }
  51. }
  52. }(ctx)
  53. }
  54. func (m *MetricsMonitor) Stop() {
  55. m.cancel()
  56. m.cancel = nil
  57. }
  58. var DeleteMetrics = func(string) error {
  59. return nil
  60. }
  61. var UpdateMetrics = func(string, *models.Metrics) error {
  62. return nil
  63. }
  64. var GetMetrics = func(string) (*models.Metrics, error) {
  65. var metrics models.Metrics
  66. return &metrics, nil
  67. }