mq.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package mq
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. mqtt "github.com/eclipse/paho.mqtt.golang"
  7. "github.com/gravitl/netmaker/logger"
  8. "github.com/gravitl/netmaker/netclient/ncutils"
  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. id := ncutils.MakeRandomString(23)
  23. opts.ClientID = id
  24. opts.SetUsername(user)
  25. opts.SetPassword(password)
  26. opts.SetAutoReconnect(true)
  27. opts.SetConnectRetry(true)
  28. opts.SetConnectRetryInterval(time.Second << 2)
  29. opts.SetKeepAlive(time.Minute)
  30. opts.SetWriteTimeout(time.Minute)
  31. }
  32. // SetupMQTT creates a connection to broker and return client
  33. func SetupMQTT() {
  34. if servercfg.GetBrokerType() == emqxBrokerType {
  35. time.Sleep(7 * time.Second) // wait for the REST endpoint to be ready
  36. // setup authenticator and create admin user
  37. if err := CreateEmqxDefaultAuthenticator(); err != nil {
  38. logger.Log(0, err.Error())
  39. }
  40. if err := CreateEmqxUser(servercfg.GetMqUserName(), servercfg.GetMqPassword(), true); err != nil {
  41. log.Fatal(err)
  42. }
  43. }
  44. opts := mqtt.NewClientOptions()
  45. setMqOptions(servercfg.GetMqUserName(), servercfg.GetMqPassword(), opts)
  46. opts.SetOnConnectHandler(func(client mqtt.Client) {
  47. if token := client.Subscribe("ping/#", 2, mqtt.MessageHandler(Ping)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  48. client.Disconnect(240)
  49. logger.Log(0, "ping subscription failed")
  50. }
  51. if token := client.Subscribe("update/#", 0, mqtt.MessageHandler(UpdateNode)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  52. client.Disconnect(240)
  53. logger.Log(0, "node update subscription failed")
  54. }
  55. if token := client.Subscribe("host/serverupdate/#", 0, mqtt.MessageHandler(UpdateHost)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  56. client.Disconnect(240)
  57. logger.Log(0, "host update subscription failed")
  58. }
  59. if token := client.Subscribe("signal/#", 0, mqtt.MessageHandler(ClientPeerUpdate)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  60. client.Disconnect(240)
  61. logger.Log(0, "node client subscription failed")
  62. }
  63. if token := client.Subscribe("metrics/#", 0, mqtt.MessageHandler(UpdateMetrics)); token.WaitTimeout(MQ_TIMEOUT*time.Second) && token.Error() != nil {
  64. client.Disconnect(240)
  65. logger.Log(0, "node metrics subscription failed")
  66. }
  67. opts.SetOrderMatters(true)
  68. opts.SetResumeSubs(true)
  69. })
  70. mqclient = mqtt.NewClient(opts)
  71. tperiod := time.Now().Add(10 * time.Second)
  72. for {
  73. if token := mqclient.Connect(); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  74. logger.Log(2, "unable to connect to broker, retrying ...")
  75. if time.Now().After(tperiod) {
  76. if token.Error() == nil {
  77. logger.FatalLog("could not connect to broker, token timeout, exiting ...")
  78. } else {
  79. logger.FatalLog("could not connect to broker, exiting ...", token.Error().Error())
  80. }
  81. }
  82. } else {
  83. break
  84. }
  85. time.Sleep(2 * time.Second)
  86. }
  87. }
  88. // Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
  89. func Keepalive(ctx context.Context) {
  90. for {
  91. select {
  92. case <-ctx.Done():
  93. return
  94. case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
  95. sendPeers()
  96. }
  97. }
  98. }
  99. // IsConnected - function for determining if the mqclient is connected or not
  100. func IsConnected() bool {
  101. return mqclient != nil && mqclient.IsConnected()
  102. }