mq.go 4.0 KB

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