timer.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package logic
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "github.com/gravitl/netmaker/logger"
  8. "github.com/gravitl/netmaker/models"
  9. )
  10. // == Constants ==
  11. // How long to wait before sending telemetry to server (24 hours)
  12. const timer_hours_between_runs = 24
  13. // == Public ==
  14. // TimerCheckpoint - Checks if 24 hours has passed since telemetry was last sent. If so, sends telemetry data to posthog
  15. func TimerCheckpoint() error {
  16. // get the telemetry record in the DB, which contains a timestamp
  17. telRecord, err := fetchTelemetryRecord()
  18. if err != nil {
  19. return err
  20. }
  21. sendtime := time.Unix(telRecord.LastSend, 0).Add(time.Hour * time.Duration(timer_hours_between_runs))
  22. // can set to 2 minutes for testing
  23. // sendtime := time.Unix(telRecord.LastSend, 0).Add(time.Minute * 2)
  24. enoughTimeElapsed := time.Now().After(sendtime)
  25. // if more than 24 hours has elapsed, send telemetry to posthog
  26. if enoughTimeElapsed {
  27. // run any time hooks
  28. runHooks()
  29. return setTelemetryTimestamp(&telRecord)
  30. }
  31. return nil
  32. }
  33. // AddHook - adds a hook function to run every 24hrs
  34. func AddHook(ifaceToAdd interface{}) {
  35. timeHooks = append(timeHooks, ifaceToAdd)
  36. }
  37. var HookManagerCh = make(chan models.HookDetails, 2)
  38. func StartHookManager(ctx context.Context, wg *sync.WaitGroup) {
  39. defer wg.Done()
  40. for {
  41. select {
  42. case <-ctx.Done():
  43. logger.Log(0, "## Stopping Hook Manager")
  44. return
  45. case newhook := <-HookManagerCh:
  46. wg.Add(1)
  47. go addHookWithInterval(ctx, wg, newhook.Hook, newhook.Interval)
  48. }
  49. }
  50. }
  51. func addHookWithInterval(ctx context.Context, wg *sync.WaitGroup, hook func() error, interval time.Duration) {
  52. defer wg.Done()
  53. ticker := time.NewTicker(interval)
  54. defer ticker.Stop()
  55. for {
  56. select {
  57. case <-ctx.Done():
  58. return
  59. case <-ticker.C:
  60. hook()
  61. }
  62. }
  63. }
  64. // == private ==
  65. // timeHooks - functions to run once a day, functions must take no parameters
  66. var timeHooks = []interface{}{
  67. loggerDump,
  68. sendTelemetry,
  69. }
  70. func loggerDump() error {
  71. logger.DumpFile(fmt.Sprintf("data/netmaker.log.%s", time.Now().Format(logger.TimeFormatDay)))
  72. return nil
  73. }
  74. // runHooks - runs the functions currently in the timeHooks data structure
  75. func runHooks() {
  76. for _, hook := range timeHooks {
  77. if err := hook.(func() error)(); err != nil {
  78. logger.Log(1, "error occurred when running timer function:", err.Error())
  79. }
  80. }
  81. }