mq.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package mq
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. mqtt "github.com/eclipse/paho.mqtt.golang"
  7. "github.com/gravitl/netmaker/logger"
  8. "github.com/gravitl/netmaker/netclient/ncutils"
  9. "github.com/gravitl/netmaker/servercfg"
  10. )
  11. // KEEPALIVE_TIMEOUT - time in seconds for timeout
  12. const KEEPALIVE_TIMEOUT = 60 //timeout in seconds
  13. // MQ_DISCONNECT - disconnects MQ
  14. const MQ_DISCONNECT = 250
  15. // MQ_TIMEOUT - timeout for MQ
  16. const MQ_TIMEOUT = 30
  17. var peer_force_send = 0
  18. var mqclient mqtt.Client
  19. // SetUpAdminClient - sets up admin client for the MQ
  20. func SetUpAdminClient() {
  21. opts := mqtt.NewClientOptions()
  22. setMqOptions(mqAdminUserName, servercfg.GetMqAdminPassword(), opts)
  23. mqAdminClient = mqtt.NewClient(opts)
  24. opts.SetOnConnectHandler(func(client mqtt.Client) {
  25. if token := client.Subscribe(dynamicSecSubTopic, 2, mqtt.MessageHandler(watchDynSecTopic)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  26. client.Disconnect(240)
  27. logger.Log(0, fmt.Sprintf("Dynamic security client subscription failed: %v ", token.Error()))
  28. }
  29. opts.SetOrderMatters(true)
  30. opts.SetResumeSubs(true)
  31. })
  32. tperiod := time.Now().Add(10 * time.Second)
  33. for {
  34. if token := mqAdminClient.Connect(); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  35. logger.Log(2, "Admin: unable to connect to broker, retrying ...")
  36. if time.Now().After(tperiod) {
  37. if token.Error() == nil {
  38. logger.FatalLog("Admin: could not connect to broker, token timeout, exiting ...")
  39. } else {
  40. logger.FatalLog("Admin: could not connect to broker, exiting ...", token.Error().Error())
  41. }
  42. }
  43. } else {
  44. break
  45. }
  46. time.Sleep(2 * time.Second)
  47. }
  48. }
  49. func setMqOptions(user, password string, opts *mqtt.ClientOptions) {
  50. broker, _ := servercfg.GetMessageQueueEndpoint()
  51. opts.AddBroker(broker)
  52. id := ncutils.MakeRandomString(23)
  53. opts.ClientID = id
  54. opts.SetUsername(user)
  55. opts.SetPassword(password)
  56. opts.SetAutoReconnect(true)
  57. opts.SetConnectRetry(true)
  58. opts.SetConnectRetryInterval(time.Second << 2)
  59. opts.SetKeepAlive(time.Minute)
  60. opts.SetWriteTimeout(time.Minute)
  61. }
  62. // SetupMQTT creates a connection to broker and return client
  63. func SetupMQTT() {
  64. opts := mqtt.NewClientOptions()
  65. setMqOptions(mqNetmakerServerUserName, servercfg.GetMqAdminPassword(), opts)
  66. opts.SetOnConnectHandler(func(client mqtt.Client) {
  67. if token := client.Subscribe("ping/#", 2, mqtt.MessageHandler(Ping)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  68. client.Disconnect(240)
  69. logger.Log(0, "ping subscription failed")
  70. }
  71. if token := client.Subscribe("update/#", 0, mqtt.MessageHandler(UpdateNode)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  72. client.Disconnect(240)
  73. logger.Log(0, "node update subscription failed")
  74. }
  75. if token := client.Subscribe("signal/#", 0, mqtt.MessageHandler(ClientPeerUpdate)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  76. client.Disconnect(240)
  77. logger.Log(0, "node client subscription failed")
  78. }
  79. if token := client.Subscribe("metrics/#", 0, mqtt.MessageHandler(UpdateMetrics)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  80. client.Disconnect(240)
  81. logger.Log(0, "node metrics subscription failed")
  82. }
  83. opts.SetOrderMatters(true)
  84. opts.SetResumeSubs(true)
  85. })
  86. mqclient = mqtt.NewClient(opts)
  87. tperiod := time.Now().Add(10 * time.Second)
  88. for {
  89. if token := mqclient.Connect(); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  90. logger.Log(2, "unable to connect to broker, retrying ...")
  91. if time.Now().After(tperiod) {
  92. if token.Error() == nil {
  93. logger.FatalLog("could not connect to broker, token timeout, exiting ...")
  94. } else {
  95. logger.FatalLog("could not connect to broker, exiting ...", token.Error().Error())
  96. }
  97. }
  98. } else {
  99. break
  100. }
  101. time.Sleep(2 * time.Second)
  102. }
  103. }
  104. // Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
  105. func Keepalive(ctx context.Context) {
  106. for {
  107. select {
  108. case <-ctx.Done():
  109. return
  110. case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
  111. sendPeers()
  112. }
  113. }
  114. }