| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 | package mqimport (	"context"	"log"	"time"	mqtt "github.com/eclipse/paho.mqtt.golang"	"github.com/gravitl/netmaker/logger"	"github.com/gravitl/netmaker/netclient/ncutils"	"github.com/gravitl/netmaker/servercfg")// KEEPALIVE_TIMEOUT - time in seconds for timeoutconst KEEPALIVE_TIMEOUT = 60 //timeout in seconds// MQ_DISCONNECT - disconnects MQconst MQ_DISCONNECT = 250var peer_force_send = 0// SetupMQTT creates a connection to broker and return clientfunc SetupMQTT(publish bool) mqtt.Client {	opts := mqtt.NewClientOptions()	opts.AddBroker("tcp://127.0.0.1:1883")	id := ncutils.MakeRandomString(23)	opts.ClientID = id	opts.SetAutoReconnect(true)	opts.SetConnectRetry(true)	opts.SetConnectRetryInterval(time.Second << 2)	opts.SetKeepAlive(time.Minute)	opts.SetWriteTimeout(time.Minute)	opts.SetOnConnectHandler(func(client mqtt.Client) {		if !publish {			if servercfg.GetDebug() {				if token := client.Subscribe("#", 2, mqtt.MessageHandler(DefaultHandler)); token.Wait() && token.Error() != nil {					client.Disconnect(240)					logger.Log(0, "default subscription failed")				}			}			if token := client.Subscribe("ping/#", 2, mqtt.MessageHandler(Ping)); token.Wait() && token.Error() != nil {				client.Disconnect(240)				logger.Log(0, "ping subscription failed")			}			if token := client.Subscribe("update/#", 0, mqtt.MessageHandler(UpdateNode)); token.Wait() && token.Error() != nil {				client.Disconnect(240)				logger.Log(0, "node update subscription failed")			}			if token := client.Subscribe("signal/#", 0, mqtt.MessageHandler(ClientPeerUpdate)); token.Wait() && token.Error() != nil {				client.Disconnect(240)				logger.Log(0, "node client subscription failed")			}			logger.Log(3, "message queue subscriptions succeeded")		}	})	opts.SetOrderMatters(true)	opts.SetResumeSubs(true)	client := mqtt.NewClient(opts)	tperiod := time.Now().Add(10 * time.Second)	for {		if token := client.Connect(); token.Wait() && token.Error() != nil {			logger.Log(2, "unable to connect to broker, retrying ...")			if time.Now().After(tperiod) {				log.Fatal(0, "could not connect to broker, exiting ...", token.Error())			}		} else {			break		}		time.Sleep(2 * time.Second)	}	logger.Log(2, "connected to broker")	return client}// Keepalive -- periodically pings all nodes to let them know server is still alive and doing wellfunc Keepalive(ctx context.Context) {	for {		select {		case <-ctx.Done():			return		case <-time.After(time.Second * KEEPALIVE_TIMEOUT):			sendPeers()		}	}}
 |