netmaker/mq/mq.go

215 lines
6.4 KiB
Go
Raw Normal View History

2022-01-13 05:23:34 +08:00
package mq
import (
"context"
2022-01-16 07:16:44 +08:00
"encoding/json"
2022-01-13 05:23:34 +08:00
"errors"
2022-01-29 04:33:30 +08:00
"fmt"
"log"
2022-01-13 05:23:34 +08:00
"strings"
"time"
2022-01-13 05:23:34 +08:00
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gravitl/netmaker/database"
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/logic"
"github.com/gravitl/netmaker/models"
2022-01-19 06:32:12 +08:00
"github.com/gravitl/netmaker/servercfg"
2022-01-13 05:23:34 +08:00
)
const KEEPALIVE_TIMEOUT = 60 //timeout in seconds
const MQ_DISCONNECT = 250
2022-01-26 07:15:27 +08:00
// DefaultHandler default message queue handler - only called when GetDebug == true
2022-01-13 05:23:34 +08:00
var DefaultHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
2022-01-26 07:15:27 +08:00
logger.Log(0, "MQTT Message: Topic: ", string(msg.Topic()), " Message: ", string(msg.Payload()))
2022-01-13 05:23:34 +08:00
}
// Ping message Handler -- handles ping topic from client nodes
2022-01-13 05:23:34 +08:00
var Ping mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
2022-01-26 07:15:27 +08:00
logger.Log(0, "Ping Handler: ", msg.Topic())
2022-01-13 05:23:34 +08:00
go func() {
2022-01-15 04:35:15 +08:00
id, err := GetID(msg.Topic())
2022-01-13 05:23:34 +08:00
if err != nil {
logger.Log(0, "error getting node.ID sent on ping topic ")
return
}
2022-01-15 04:35:15 +08:00
node, err := logic.GetNodeByID(id)
2022-01-13 05:23:34 +08:00
if err != nil {
2022-01-26 07:15:27 +08:00
logger.Log(0, "mq-ping error getting node: ", err.Error())
2022-01-15 04:35:15 +08:00
record, err := database.FetchRecord(database.NODES_TABLE_NAME, id)
2022-01-13 05:23:34 +08:00
if err != nil {
logger.Log(0, "error reading database ", err.Error())
return
}
logger.Log(0, "record from database")
logger.Log(0, record)
return
}
2022-01-30 04:11:21 +08:00
_, decryptErr := decryptMsg(&node, msg.Payload())
2022-01-29 04:33:30 +08:00
if decryptErr != nil {
logger.Log(0, "error updating node ", node.ID, err.Error())
return
}
2022-01-13 05:23:34 +08:00
node.SetLastCheckIn()
2022-01-19 22:44:35 +08:00
if err := logic.UpdateNode(&node, &node); err != nil {
2022-01-26 07:15:27 +08:00
logger.Log(0, "error updating node ", err.Error())
2022-01-19 06:32:12 +08:00
}
2022-01-30 04:11:21 +08:00
logger.Log(3, "ping processed for node", node.ID)
2022-01-13 05:23:34 +08:00
// --TODO --set client version once feature is implemented.
//node.SetClientVersion(msg.Payload())
}()
}
// UpdateNode message Handler -- handles updates from client nodes
var UpdateNode mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
2022-01-13 05:23:34 +08:00
go func() {
2022-01-15 04:35:15 +08:00
id, err := GetID(msg.Topic())
2022-01-13 05:23:34 +08:00
if err != nil {
2022-01-26 07:15:27 +08:00
logger.Log(1, "error getting node.ID sent on ", msg.Topic(), err.Error())
return
}
2022-01-29 04:33:30 +08:00
currentNode, err := logic.GetNodeByID(id)
if err != nil {
logger.Log(1, "error getting node ", id, err.Error())
return
}
2022-01-30 04:02:37 +08:00
decrypted, decryptErr := decryptMsg(&currentNode, msg.Payload())
2022-01-29 04:33:30 +08:00
if decryptErr != nil {
logger.Log(1, "failed to decrypt message for node ", id, decryptErr.Error())
return
}
2022-01-26 07:15:27 +08:00
logger.Log(1, "Update Node Handler", id)
var newNode models.Node
2022-01-29 04:33:30 +08:00
if err := json.Unmarshal(decrypted, &newNode); err != nil {
2022-01-26 07:15:27 +08:00
logger.Log(1, "error unmarshaling payload ", err.Error())
2022-01-13 05:23:34 +08:00
return
}
if err := logic.UpdateNode(&currentNode, &newNode); err != nil {
2022-01-26 07:15:27 +08:00
logger.Log(1, "error saving node", err.Error())
2022-01-19 06:32:12 +08:00
}
2022-01-31 09:52:56 +08:00
if err := PublishPeerUpdate(&newNode); err != nil {
logger.Log(1, "error publishing peer update ", err.Error())
return
}
2022-01-27 05:06:45 +08:00
logger.Log(1, "no need to update peers")
2022-01-13 05:23:34 +08:00
}()
}
// PublishPeerUpdate --- deterines and publishes a peer update to all the peers of a node
2022-01-29 04:33:30 +08:00
func PublishPeerUpdate(newNode *models.Node) error {
2022-01-31 09:50:37 +08:00
networkNodes, err := logic.GetNetworkNodes(newNode.Network)
2022-01-13 05:23:34 +08:00
if err != nil {
2022-01-26 07:15:27 +08:00
logger.Log(1, "err getting Network Nodes", err.Error())
2022-01-16 07:16:44 +08:00
return err
}
2022-01-19 22:44:35 +08:00
for _, node := range networkNodes {
2022-01-31 08:58:20 +08:00
if node.IsServer == "yes" {
continue
}
peerUpdate, err := logic.GetPeerUpdate(&node)
if err != nil {
2022-01-31 00:51:39 +08:00
logger.Log(1, "error getting peer update for node", node.ID, err.Error())
continue
2022-01-19 22:44:35 +08:00
}
2022-01-19 06:32:12 +08:00
data, err := json.Marshal(&peerUpdate)
2022-01-16 07:16:44 +08:00
if err != nil {
2022-01-29 04:33:30 +08:00
logger.Log(2, "error marshaling peer update for node", node.ID, err.Error())
continue
2022-01-16 07:16:44 +08:00
}
2022-01-29 22:14:18 +08:00
if err = publish(&node, fmt.Sprintf("peers/%s/%s", node.Network, node.ID), data); err != nil {
2022-01-29 04:33:30 +08:00
logger.Log(1, "failed to publish peer update for node", node.ID)
2022-01-31 09:07:50 +08:00
} else {
2022-01-31 22:58:43 +08:00
logger.Log(0, fmt.Sprintf("sent peer update for network, %s and node, %s", node.Network, node.Name))
2022-01-13 05:23:34 +08:00
}
}
return nil
2022-01-13 05:23:34 +08:00
}
// GetID -- decodes a message queue topic and returns the embedded node.ID
2022-01-13 05:23:34 +08:00
func GetID(topic string) (string, error) {
parts := strings.Split(topic, "/")
count := len(parts)
if count == 1 {
return "", errors.New("invalid topic")
}
2022-01-15 04:35:15 +08:00
//the last part of the topic will be the node.ID
2022-01-15 06:22:11 +08:00
return parts[count-1], nil
2022-01-13 05:23:34 +08:00
}
2022-01-19 06:32:12 +08:00
2022-01-29 04:33:30 +08:00
// NodeUpdate -- publishes a node update
func NodeUpdate(node *models.Node) error {
2022-01-29 04:33:30 +08:00
if !servercfg.IsMessageQueueBackend() {
return nil
}
2022-01-22 22:04:11 +08:00
logger.Log(3, "publishing node update to "+node.Name)
data, err := json.Marshal(node)
if err != nil {
2022-01-26 07:15:27 +08:00
logger.Log(2, "error marshalling node update ", err.Error())
return err
}
2022-01-29 22:14:18 +08:00
if err = publish(node, fmt.Sprintf("update/%s/%s", node.Network, node.ID), data); err != nil {
2022-01-29 04:33:30 +08:00
logger.Log(2, "error publishing node update to peer ", node.ID, err.Error())
return err
}
return nil
}
// SetupMQTT creates a connection to broker and return client
func SetupMQTT() mqtt.Client {
2022-01-19 06:32:12 +08:00
opts := mqtt.NewClientOptions()
broker := servercfg.GetMessageQueueEndpoint()
opts.AddBroker(broker)
2022-01-28 04:52:31 +08:00
client := mqtt.NewClient(opts)
2022-01-28 04:46:45 +08:00
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 ...")
2022-01-28 04:52:31 +08:00
if time.Now().After(tperiod) {
2022-01-28 04:46:45 +08:00
log.Fatal(0, "could not connect to broker, exiting ...", token.Error())
}
} else {
break
}
time.Sleep(2 * time.Second)
2022-01-19 06:32:12 +08:00
}
2022-01-27 22:48:32 +08:00
logger.Log(2, "connected to message queue", broker)
return client
2022-01-19 06:32:12 +08:00
}
// Keepalive -- periodically pings all nodes to let them know server is still alive and doing well
func Keepalive(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case <-time.After(time.Second * KEEPALIVE_TIMEOUT):
2022-01-27 22:48:32 +08:00
client := SetupMQTT()
networks, err := logic.GetNetworks()
if err != nil {
2022-01-27 22:48:32 +08:00
logger.Log(1, "error retrieving networks for keepalive", err.Error())
}
2022-01-27 22:48:32 +08:00
for _, network := range networks {
var id string
for _, servAddr := range network.DefaultServerAddrs {
if servAddr.IsLeader {
id = servAddr.ID
}
}
if id == "" {
2022-01-27 22:48:32 +08:00
logger.Log(0, "leader not defined for network", network.NetID)
continue
}
if token := client.Publish("serverkeepalive/"+id, 0, false, servercfg.GetVersion()); token.Wait() && token.Error() != nil {
logger.Log(1, "error publishing server keepalive for network", network.NetID, token.Error().Error())
} else {
logger.Log(2, "keepalive sent for network", network.NetID)
}
client.Disconnect(MQ_DISCONNECT)
}
}
}
}