2
0

mq.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 * 4)
  31. opts.SetKeepAlive(time.Minute)
  32. opts.SetCleanSession(true)
  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.CreateDefaultDenyRule(); 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. client.Disconnect(240)
  70. logger.Log(0, "node update subscription failed")
  71. }
  72. if token := client.Subscribe(fmt.Sprintf("host/serverupdate/%s/#", serverName), 0, mqtt.MessageHandler(UpdateHost)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  73. client.Disconnect(240)
  74. logger.Log(0, "host update subscription failed")
  75. }
  76. if token := client.Subscribe(fmt.Sprintf("signal/%s/#", serverName), 0, mqtt.MessageHandler(ClientPeerUpdate)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  77. client.Disconnect(240)
  78. logger.Log(0, "node client subscription failed")
  79. }
  80. if token := client.Subscribe(fmt.Sprintf("metrics/%s/#", serverName), 0, mqtt.MessageHandler(UpdateMetrics)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  81. client.Disconnect(240)
  82. logger.Log(0, "node metrics subscription failed")
  83. }
  84. opts.SetOrderMatters(false)
  85. opts.SetResumeSubs(true)
  86. })
  87. opts.SetConnectionLostHandler(func(c mqtt.Client, e error) {
  88. slog.Warn("detected broker connection lost", "err", e.Error())
  89. c.Disconnect(250)
  90. slog.Info("re-initiating MQ connection")
  91. SetupMQTT(false)
  92. })
  93. mqclient = mqtt.NewClient(opts)
  94. tperiod := time.Now().Add(10 * time.Second)
  95. for {
  96. if token := mqclient.Connect(); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  97. logger.Log(2, "unable to connect to broker, retrying ...")
  98. if time.Now().After(tperiod) {
  99. if token.Error() == nil {
  100. if fatal {
  101. logger.FatalLog("could not connect to broker, token timeout, exiting ...")
  102. }
  103. logger.Log(0, "could not connect to broker, token timeout, exiting ...")
  104. } else {
  105. if fatal {
  106. logger.FatalLog("could not connect to broker, exiting ...", token.Error().Error())
  107. }
  108. logger.Log(0, "could not connect to broker, exiting ...", token.Error().Error())
  109. }
  110. }
  111. } else {
  112. break
  113. }
  114. time.Sleep(2 * time.Second)
  115. }
  116. }
  117. // Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
  118. func Keepalive(ctx context.Context) {
  119. for {
  120. select {
  121. case <-ctx.Done():
  122. return
  123. case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
  124. sendPeers()
  125. }
  126. }
  127. }
  128. // IsConnected - function for determining if the mqclient is connected or not
  129. func IsConnected() bool {
  130. return mqclient != nil && mqclient.IsConnectionOpen()
  131. }
  132. // CloseClient - function to close the mq connection from server
  133. func CloseClient() {
  134. mqclient.Disconnect(250)
  135. }