timer.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package logic
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gravitl/netmaker/logger"
  6. )
  7. // == Constants ==
  8. // How long to wait before sending telemetry to server (24 hours)
  9. const timer_hours_between_runs = 24
  10. // == Public ==
  11. // TimerCheckpoint - Checks if 24 hours has passed since telemetry was last sent. If so, sends telemetry data to posthog
  12. func TimerCheckpoint() error {
  13. // get the telemetry record in the DB, which contains a timestamp
  14. telRecord, err := fetchTelemetryRecord()
  15. if err != nil {
  16. return err
  17. }
  18. sendtime := time.Unix(telRecord.LastSend, 0).Add(time.Hour * time.Duration(timer_hours_between_runs))
  19. // can set to 2 minutes for testing
  20. // sendtime := time.Unix(telRecord.LastSend, 0).Add(time.Minute * 2)
  21. enoughTimeElapsed := time.Now().After(sendtime)
  22. // if more than 24 hours has elapsed, send telemetry to posthog
  23. if enoughTimeElapsed {
  24. // run any time hooks
  25. runHooks()
  26. }
  27. // set telemetry timestamp for server, restarts 24 hour cycle
  28. return setTelemetryTimestamp(telRecord.UUID)
  29. }
  30. // AddHook - adds a hook function to run every 24hrs
  31. func AddHook(ifaceToAdd interface{}) {
  32. timeHooks = append(timeHooks, ifaceToAdd)
  33. }
  34. // == private ==
  35. // timeHooks - functions to run once a day, functions must take no parameters
  36. var timeHooks = []interface{}{
  37. loggerDump,
  38. sendTelemetry,
  39. }
  40. func loggerDump() error {
  41. logger.DumpFile(fmt.Sprintf("data/netmaker.log.%s", time.Now().Format(logger.TimeFormatDay)))
  42. return nil
  43. }
  44. // runHooks - runs the functions currently in the timeHooks data structure
  45. func runHooks() {
  46. for _, hook := range timeHooks {
  47. if err := hook.(func() error)(); err != nil {
  48. logger.Log(1, "error occurred when running timer function:", err.Error())
  49. }
  50. }
  51. }