mq.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. var peer_force_send = 0
  16. // SetupMQTT creates a connection to broker and return client
  17. func SetupMQTT(publish bool) mqtt.Client {
  18. opts := mqtt.NewClientOptions()
  19. opts.AddBroker(servercfg.GetMessageQueueEndpoint())
  20. id := ncutils.MakeRandomString(23)
  21. opts.ClientID = id
  22. opts.SetAutoReconnect(true)
  23. opts.SetConnectRetry(true)
  24. opts.SetConnectRetryInterval(time.Second << 2)
  25. opts.SetKeepAlive(time.Minute)
  26. opts.SetWriteTimeout(time.Minute)
  27. opts.SetOnConnectHandler(func(client mqtt.Client) {
  28. if !publish {
  29. if servercfg.GetDebug() {
  30. if token := client.Subscribe("#", 2, mqtt.MessageHandler(DefaultHandler)); token.Wait() && token.Error() != nil {
  31. client.Disconnect(240)
  32. logger.Log(0, "default subscription failed")
  33. }
  34. }
  35. if token := client.Subscribe("ping/#", 2, mqtt.MessageHandler(Ping)); token.Wait() && token.Error() != nil {
  36. client.Disconnect(240)
  37. logger.Log(0, "ping subscription failed")
  38. }
  39. if token := client.Subscribe("update/#", 0, mqtt.MessageHandler(UpdateNode)); token.Wait() && token.Error() != nil {
  40. client.Disconnect(240)
  41. logger.Log(0, "node update subscription failed")
  42. }
  43. if token := client.Subscribe("signal/#", 0, mqtt.MessageHandler(ClientPeerUpdate)); token.Wait() && token.Error() != nil {
  44. client.Disconnect(240)
  45. logger.Log(0, "node client subscription failed")
  46. }
  47. opts.SetOrderMatters(true)
  48. opts.SetResumeSubs(true)
  49. }
  50. })
  51. client := mqtt.NewClient(opts)
  52. tperiod := time.Now().Add(10 * time.Second)
  53. for {
  54. if token := client.Connect(); token.Wait() && token.Error() != nil {
  55. logger.Log(2, "unable to connect to broker, retrying ...")
  56. if time.Now().After(tperiod) {
  57. log.Fatal(0, "could not connect to broker, exiting ...", token.Error())
  58. }
  59. } else {
  60. break
  61. }
  62. time.Sleep(2 * time.Second)
  63. }
  64. return client
  65. }
  66. // Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
  67. func Keepalive(ctx context.Context) {
  68. for {
  69. select {
  70. case <-ctx.Done():
  71. return
  72. case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
  73. sendPeers()
  74. }
  75. }
  76. }