mq.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 token := client.Subscribe("ping/#", 2, mqtt.MessageHandler(Ping)); token.Wait() && token.Error() != nil {
  30. client.Disconnect(240)
  31. logger.Log(0, "ping subscription failed")
  32. }
  33. if token := client.Subscribe("update/#", 0, mqtt.MessageHandler(UpdateNode)); token.Wait() && token.Error() != nil {
  34. client.Disconnect(240)
  35. logger.Log(0, "node update subscription failed")
  36. }
  37. if token := client.Subscribe("signal/#", 0, mqtt.MessageHandler(ClientPeerUpdate)); token.Wait() && token.Error() != nil {
  38. client.Disconnect(240)
  39. logger.Log(0, "node client subscription failed")
  40. }
  41. opts.SetOrderMatters(true)
  42. opts.SetResumeSubs(true)
  43. }
  44. })
  45. client := mqtt.NewClient(opts)
  46. tperiod := time.Now().Add(10 * time.Second)
  47. for {
  48. if token := client.Connect(); token.Wait() && token.Error() != nil {
  49. logger.Log(2, "unable to connect to broker, retrying ...")
  50. if time.Now().After(tperiod) {
  51. log.Fatal(0, "could not connect to broker, exiting ...", token.Error())
  52. }
  53. } else {
  54. break
  55. }
  56. time.Sleep(2 * time.Second)
  57. }
  58. return client
  59. }
  60. // Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
  61. func Keepalive(ctx context.Context) {
  62. for {
  63. select {
  64. case <-ctx.Done():
  65. return
  66. case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
  67. sendPeers()
  68. }
  69. }
  70. }