mq.go 4.8 KB

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