mq.go 4.5 KB

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