mq.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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/netclient/ncutils"
  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 := ncutils.MakeRandomString(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. }
  46. opts := mqtt.NewClientOptions()
  47. setMqOptions(servercfg.GetMqUserName(), servercfg.GetMqPassword(), opts)
  48. opts.SetOnConnectHandler(func(client mqtt.Client) {
  49. serverName := servercfg.GetServer()
  50. if token := client.Subscribe(fmt.Sprintf("update/%s/#", serverName), 0, mqtt.MessageHandler(UpdateNode)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  51. client.Disconnect(240)
  52. logger.Log(0, "node update subscription failed")
  53. }
  54. if token := client.Subscribe(fmt.Sprintf("host/serverupdate/%s/#", serverName), 0, mqtt.MessageHandler(UpdateHost)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  55. client.Disconnect(240)
  56. logger.Log(0, "host update subscription failed")
  57. }
  58. if token := client.Subscribe(fmt.Sprintf("signal/%s/#", serverName), 0, mqtt.MessageHandler(ClientPeerUpdate)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  59. client.Disconnect(240)
  60. logger.Log(0, "node client subscription failed")
  61. }
  62. if token := client.Subscribe(fmt.Sprintf("metrics/%s/#", serverName), 0, mqtt.MessageHandler(UpdateMetrics)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  63. client.Disconnect(240)
  64. logger.Log(0, "node metrics subscription failed")
  65. }
  66. opts.SetOrderMatters(true)
  67. opts.SetResumeSubs(true)
  68. })
  69. mqclient = mqtt.NewClient(opts)
  70. tperiod := time.Now().Add(10 * time.Second)
  71. for {
  72. if token := mqclient.Connect(); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  73. logger.Log(2, "unable to connect to broker, retrying ...")
  74. if time.Now().After(tperiod) {
  75. if token.Error() == nil {
  76. logger.FatalLog("could not connect to broker, token timeout, exiting ...")
  77. } else {
  78. logger.FatalLog("could not connect to broker, exiting ...", token.Error().Error())
  79. }
  80. }
  81. } else {
  82. break
  83. }
  84. time.Sleep(2 * time.Second)
  85. }
  86. }
  87. // Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
  88. func Keepalive(ctx context.Context) {
  89. for {
  90. select {
  91. case <-ctx.Done():
  92. return
  93. case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
  94. sendPeers()
  95. }
  96. }
  97. }
  98. // IsConnected - function for determining if the mqclient is connected or not
  99. func IsConnected() bool {
  100. return mqclient != nil && mqclient.IsConnected()
  101. }
  102. // CloseClient - function to close the mq connection from server
  103. func CloseClient() {
  104. mqclient.Disconnect(250)
  105. }