mq.go 4.1 KB

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