mq.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package mq
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. mqtt "github.com/eclipse/paho.mqtt.golang"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/logic"
  10. "github.com/gravitl/netmaker/servercfg"
  11. "golang.org/x/exp/slog"
  12. )
  13. // KEEPALIVE_TIMEOUT - time in seconds for timeout
  14. const KEEPALIVE_TIMEOUT = 60 //timeout in seconds
  15. // MQ_DISCONNECT - disconnects MQ
  16. const MQ_DISCONNECT = 250
  17. // MQ_TIMEOUT - timeout for MQ
  18. const MQ_TIMEOUT = 30
  19. var peer_force_send = 0
  20. var mqclient mqtt.Client
  21. func setMqOptions(user, password string, opts *mqtt.ClientOptions) {
  22. broker, _ := servercfg.GetMessageQueueEndpoint()
  23. opts.AddBroker(broker)
  24. opts.ClientID = logic.RandomString(23)
  25. opts.SetUsername(user)
  26. opts.SetPassword(password)
  27. opts.SetAutoReconnect(true)
  28. opts.SetConnectRetry(true)
  29. opts.SetCleanSession(true)
  30. opts.SetConnectRetryInterval(time.Second * 1)
  31. opts.SetKeepAlive(time.Second * 15)
  32. opts.SetOrderMatters(false)
  33. opts.SetWriteTimeout(time.Minute)
  34. }
  35. // SetupMQTT creates a connection to broker and return client
  36. func SetupMQTT(fatal bool) {
  37. if servercfg.GetBrokerType() == servercfg.EmqxBrokerType {
  38. if emqx.GetType() == servercfg.EmqxOnPremDeploy {
  39. time.Sleep(10 * time.Second) // wait for the REST endpoint to be ready
  40. // setup authenticator and create admin user
  41. if err := emqx.CreateEmqxDefaultAuthenticator(); err != nil {
  42. logger.Log(0, err.Error())
  43. }
  44. emqx.DeleteEmqxUser(servercfg.GetMqUserName())
  45. if err := emqx.CreateEmqxUserforServer(); err != nil {
  46. log.Fatal(err)
  47. }
  48. // create an ACL authorization source for the built in EMQX MNESIA database
  49. if err := emqx.CreateEmqxDefaultAuthorizer(); err != nil {
  50. logger.Log(0, err.Error())
  51. }
  52. // create a default deny ACL to all topics for all users
  53. if err := emqx.CreateDefaultAllowRule(); err != nil {
  54. log.Fatal(err)
  55. }
  56. } else {
  57. emqx.DeleteEmqxUser(servercfg.GetMqUserName())
  58. if err := emqx.CreateEmqxUserforServer(); err != nil {
  59. log.Fatal(err)
  60. }
  61. }
  62. }
  63. opts := mqtt.NewClientOptions()
  64. setMqOptions(servercfg.GetMqUserName(), servercfg.GetMqPassword(), opts)
  65. logger.Log(0, "Mq Client Connecting with Random ID: ", opts.ClientID)
  66. opts.SetOnConnectHandler(func(client mqtt.Client) {
  67. serverName := servercfg.GetServer()
  68. if token := client.Subscribe(fmt.Sprintf("update/%s/#", serverName), 0, mqtt.MessageHandler(UpdateNode)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  69. logger.Log(0, "node update subscription failed")
  70. }
  71. if token := client.Subscribe(fmt.Sprintf("host/serverupdate/%s/#", serverName), 0, mqtt.MessageHandler(UpdateHost)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  72. logger.Log(0, "host update subscription failed")
  73. }
  74. if token := client.Subscribe(fmt.Sprintf("signal/%s/#", serverName), 0, mqtt.MessageHandler(ClientPeerUpdate)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  75. logger.Log(0, "node client subscription failed")
  76. }
  77. if token := client.Subscribe(fmt.Sprintf("metrics/%s/#", serverName), 0, mqtt.MessageHandler(UpdateMetrics)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  78. logger.Log(0, "node metrics subscription failed")
  79. }
  80. opts.SetOrderMatters(false)
  81. opts.SetResumeSubs(true)
  82. })
  83. opts.SetConnectionLostHandler(func(c mqtt.Client, e error) {
  84. slog.Warn("detected broker connection lost", "err", e.Error())
  85. c.Disconnect(250)
  86. slog.Info("re-initiating MQ connection")
  87. SetupMQTT(false)
  88. })
  89. mqclient = mqtt.NewClient(opts)
  90. tperiod := time.Now().Add(10 * time.Second)
  91. for {
  92. if token := mqclient.Connect(); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  93. logger.Log(2, "unable to connect to broker, retrying ...")
  94. if time.Now().After(tperiod) {
  95. if token.Error() == nil {
  96. if fatal {
  97. logger.FatalLog("could not connect to broker, token timeout, exiting ...")
  98. }
  99. logger.Log(0, "could not connect to broker, token timeout, exiting ...")
  100. } else {
  101. if fatal {
  102. logger.FatalLog("could not connect to broker, exiting ...", token.Error().Error())
  103. }
  104. logger.Log(0, "could not connect to broker, exiting ...", token.Error().Error())
  105. }
  106. }
  107. } else {
  108. break
  109. }
  110. time.Sleep(2 * time.Second)
  111. }
  112. }
  113. // Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
  114. func Keepalive(ctx context.Context) {
  115. go PublishPeerUpdate(true)
  116. for {
  117. select {
  118. case <-ctx.Done():
  119. return
  120. case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
  121. sendPeers()
  122. }
  123. }
  124. }
  125. // IsConnected - function for determining if the mqclient is connected or not
  126. func IsConnected() bool {
  127. return mqclient != nil && mqclient.IsConnected()
  128. }
  129. // IsConnectionOpen - function for determining if the mqclient is connected or not
  130. func IsConnectionOpen() bool {
  131. return mqclient != nil && mqclient.IsConnectionOpen()
  132. }
  133. // CloseClient - function to close the mq connection from server
  134. func CloseClient() {
  135. mqclient.Disconnect(250)
  136. }