mq.go 3.7 KB

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