handlers.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. package mq
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "math"
  7. "time"
  8. mqtt "github.com/eclipse/paho.mqtt.golang"
  9. "github.com/google/uuid"
  10. "github.com/gravitl/netmaker/database"
  11. "github.com/gravitl/netmaker/logic"
  12. "github.com/gravitl/netmaker/logic/hostactions"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/netclient/ncutils"
  15. "github.com/gravitl/netmaker/servercfg"
  16. "golang.org/x/exp/slog"
  17. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  18. )
  19. // DefaultHandler default message queue handler -- NOT USED
  20. func DefaultHandler(client mqtt.Client, msg mqtt.Message) {
  21. slog.Info("mqtt default handler", "topic", msg.Topic(), "message", msg.Payload())
  22. }
  23. // UpdateNode message Handler -- handles updates from client nodes
  24. func UpdateNode(client mqtt.Client, msg mqtt.Message) {
  25. id, err := getID(msg.Topic())
  26. if err != nil {
  27. slog.Error("error getting node.ID ", "topic", msg.Topic(), "error", err)
  28. return
  29. }
  30. currentNode, err := logic.GetNodeByID(id)
  31. if err != nil {
  32. slog.Error("error getting node", "id", id, "error", err)
  33. return
  34. }
  35. decrypted, decryptErr := decryptMsg(&currentNode, msg.Payload())
  36. if decryptErr != nil {
  37. slog.Error("failed to decrypt message for node", "id", id, "error", decryptErr)
  38. return
  39. }
  40. var newNode models.Node
  41. if err := json.Unmarshal(decrypted, &newNode); err != nil {
  42. slog.Error("error unmarshaling payload", "error", err)
  43. return
  44. }
  45. ifaceDelta := logic.IfaceDelta(&currentNode, &newNode)
  46. if servercfg.Is_EE && ifaceDelta {
  47. if err = logic.EnterpriseResetAllPeersFailovers(currentNode.ID, currentNode.Network); err != nil {
  48. slog.Warn("failed to reset failover list during node update", "nodeid", currentNode.ID, "network", currentNode.Network)
  49. }
  50. }
  51. newNode.SetLastCheckIn()
  52. if err := logic.UpdateNode(&currentNode, &newNode); err != nil {
  53. slog.Error("error saving node", "id", id, "error", err)
  54. return
  55. }
  56. if ifaceDelta { // reduce number of unneeded updates, by only sending on iface changes
  57. if err = PublishPeerUpdate(); err != nil {
  58. slog.Warn("error updating peers when node informed the server of an interface change", "nodeid", currentNode.ID, "error", err)
  59. }
  60. }
  61. slog.Info("updated node", "id", id, "newnodeid", newNode.ID)
  62. }
  63. // UpdateHost message Handler -- handles host updates from clients
  64. func UpdateHost(client mqtt.Client, msg mqtt.Message) {
  65. id, err := getID(msg.Topic())
  66. if err != nil {
  67. slog.Error("error getting host.ID sent on ", "topic", msg.Topic(), "error", err)
  68. return
  69. }
  70. currentHost, err := logic.GetHost(id)
  71. if err != nil {
  72. slog.Error("error getting host", "id", id, "error", err)
  73. return
  74. }
  75. decrypted, decryptErr := decryptMsgWithHost(currentHost, msg.Payload())
  76. if decryptErr != nil {
  77. slog.Error("failed to decrypt message for host", "id", id, "error", decryptErr)
  78. return
  79. }
  80. var hostUpdate models.HostUpdate
  81. if err := json.Unmarshal(decrypted, &hostUpdate); err != nil {
  82. slog.Error("error unmarshaling payload", "error", err)
  83. return
  84. }
  85. slog.Info("recieved host update", "name", hostUpdate.Host.Name, "id", hostUpdate.Host.ID)
  86. var sendPeerUpdate bool
  87. switch hostUpdate.Action {
  88. case models.CheckIn:
  89. sendPeerUpdate = handleHostCheckin(&hostUpdate.Host, currentHost)
  90. case models.Acknowledgement:
  91. hu := hostactions.GetAction(currentHost.ID.String())
  92. if hu != nil {
  93. if err = HostUpdate(hu); err != nil {
  94. slog.Error("failed to send new node to host", "name", hostUpdate.Host.Name, "id", currentHost.ID, "error", err)
  95. return
  96. } else {
  97. if servercfg.GetBrokerType() == servercfg.EmqxBrokerType {
  98. if err = AppendNodeUpdateACL(hu.Host.ID.String(), hu.Node.Network, hu.Node.ID.String(), servercfg.GetServer()); err != nil {
  99. slog.Error("failed to add ACLs for EMQX node", "error", err)
  100. return
  101. }
  102. }
  103. if err = PublishSingleHostPeerUpdate(context.Background(), currentHost, nil, nil); err != nil {
  104. slog.Error("failed peers publish after join acknowledged", "name", hostUpdate.Host.Name, "id", currentHost.ID, "error", err)
  105. return
  106. }
  107. if err = handleNewNodeDNS(&hu.Host, &hu.Node); err != nil {
  108. slog.Error("failed to send dns update after node added to host", "name", hostUpdate.Host.Name, "id", currentHost.ID, "error", err)
  109. return
  110. }
  111. }
  112. }
  113. case models.UpdateHost:
  114. if hostUpdate.Host.PublicKey != currentHost.PublicKey {
  115. //remove old peer entry
  116. peerUpdate := models.HostPeerUpdate{
  117. ServerVersion: servercfg.GetVersion(),
  118. Peers: []wgtypes.PeerConfig{
  119. {
  120. PublicKey: currentHost.PublicKey,
  121. Remove: true,
  122. },
  123. },
  124. }
  125. data, err := json.Marshal(&peerUpdate)
  126. if err != nil {
  127. slog.Error("failed to marshal peer update", "error", err)
  128. }
  129. hosts := logic.GetRelatedHosts(hostUpdate.Host.ID.String())
  130. server := servercfg.GetServer()
  131. for _, host := range hosts {
  132. publish(&host, fmt.Sprintf("peers/host/%s/%s", host.ID.String(), server), data)
  133. }
  134. }
  135. sendPeerUpdate = logic.UpdateHostFromClient(&hostUpdate.Host, currentHost)
  136. err := logic.UpsertHost(currentHost)
  137. if err != nil {
  138. slog.Error("failed to update host", "id", currentHost.ID, "error", err)
  139. return
  140. }
  141. case models.DeleteHost:
  142. if servercfg.GetBrokerType() == servercfg.EmqxBrokerType {
  143. // delete EMQX credentials for host
  144. if err := DeleteEmqxUser(currentHost.ID.String()); err != nil {
  145. slog.Error("failed to remove host credentials from EMQX", "id", currentHost.ID, "error", err)
  146. return
  147. }
  148. }
  149. if err := logic.DisassociateAllNodesFromHost(currentHost.ID.String()); err != nil {
  150. slog.Error("failed to delete all nodes of host", "id", currentHost.ID, "error", err)
  151. return
  152. }
  153. if err := logic.RemoveHostByID(currentHost.ID.String()); err != nil {
  154. slog.Error("failed to delete host", "id", currentHost.ID, "error", err)
  155. return
  156. }
  157. sendPeerUpdate = true
  158. case models.RegisterWithTurn:
  159. if servercfg.IsUsingTurn() {
  160. err = logic.RegisterHostWithTurn(hostUpdate.Host.ID.String(), hostUpdate.Host.HostPass)
  161. if err != nil {
  162. slog.Error("failed to register host with turn server", "id", currentHost.ID, "error", err)
  163. return
  164. }
  165. }
  166. }
  167. if sendPeerUpdate {
  168. err := PublishPeerUpdate()
  169. if err != nil {
  170. slog.Error("failed to publish peer update", "error", err)
  171. }
  172. }
  173. // if servercfg.Is_EE && ifaceDelta {
  174. // if err = logic.EnterpriseResetAllPeersFailovers(currentHost.ID.String(), currentHost.Network); err != nil {
  175. // logger.Log(1, "failed to reset failover list during node update", currentHost.ID.String(), currentHost.Network)
  176. // }
  177. // }
  178. }
  179. // UpdateMetrics message Handler -- handles updates from client nodes for metrics
  180. func UpdateMetrics(client mqtt.Client, msg mqtt.Message) {
  181. if servercfg.Is_EE {
  182. id, err := getID(msg.Topic())
  183. if err != nil {
  184. slog.Error("error getting ID sent on ", "topic", msg.Topic(), "error", err)
  185. return
  186. }
  187. currentNode, err := logic.GetNodeByID(id)
  188. if err != nil {
  189. slog.Error("error getting node", "id", id, "error", err)
  190. return
  191. }
  192. decrypted, decryptErr := decryptMsg(&currentNode, msg.Payload())
  193. if decryptErr != nil {
  194. slog.Error("failed to decrypt message for node", "id", id, "error", decryptErr)
  195. return
  196. }
  197. var newMetrics models.Metrics
  198. if err := json.Unmarshal(decrypted, &newMetrics); err != nil {
  199. slog.Error("error unmarshaling payload", "error", err)
  200. return
  201. }
  202. shouldUpdate := updateNodeMetrics(&currentNode, &newMetrics)
  203. if err = logic.UpdateMetrics(id, &newMetrics); err != nil {
  204. slog.Error("failed to update node metrics", "id", id, "error", err)
  205. return
  206. }
  207. if servercfg.IsMetricsExporter() {
  208. if err := pushMetricsToExporter(newMetrics); err != nil {
  209. slog.Error("failed to push node metrics to exporter", "id", currentNode.ID, "error", err)
  210. }
  211. }
  212. if newMetrics.Connectivity != nil {
  213. err := logic.EnterpriseFailoverFunc(&currentNode)
  214. if err != nil {
  215. slog.Error("failed to failover for node", "id", currentNode.ID, "network", currentNode.Network, "error", err)
  216. }
  217. }
  218. if shouldUpdate {
  219. slog.Info("updating peers after node detected connectivity issues", "id", currentNode.ID, "network", currentNode.Network)
  220. host, err := logic.GetHost(currentNode.HostID.String())
  221. if err == nil {
  222. if err = PublishSingleHostPeerUpdate(context.Background(), host, nil, nil); err != nil {
  223. slog.Warn("failed to publish update after failover peer change for node", "id", currentNode.ID, "network", currentNode.Network, "error", err)
  224. }
  225. }
  226. }
  227. slog.Info("updated node metrics", "id", id)
  228. }
  229. }
  230. // ClientPeerUpdate message handler -- handles updating peers after signal from client nodes
  231. func ClientPeerUpdate(client mqtt.Client, msg mqtt.Message) {
  232. id, err := getID(msg.Topic())
  233. if err != nil {
  234. slog.Error("error getting node.ID sent on ", "topic", msg.Topic(), "error", err)
  235. return
  236. }
  237. currentNode, err := logic.GetNodeByID(id)
  238. if err != nil {
  239. slog.Error("error getting node", "id", id, "error", err)
  240. return
  241. }
  242. decrypted, decryptErr := decryptMsg(&currentNode, msg.Payload())
  243. if decryptErr != nil {
  244. slog.Error("failed to decrypt message for node", "id", id, "error", decryptErr)
  245. return
  246. }
  247. switch decrypted[0] {
  248. case ncutils.ACK:
  249. // do we still need this
  250. case ncutils.DONE:
  251. if err = PublishPeerUpdate(); err != nil {
  252. slog.Error("error publishing peer update for node", "id", currentNode.ID, "error", err)
  253. return
  254. }
  255. }
  256. slog.Info("sent peer updates after signal received from", "id", id)
  257. }
  258. func updateNodeMetrics(currentNode *models.Node, newMetrics *models.Metrics) bool {
  259. if newMetrics.FailoverPeers == nil {
  260. newMetrics.FailoverPeers = make(map[string]string)
  261. }
  262. oldMetrics, err := logic.GetMetrics(currentNode.ID.String())
  263. if err != nil {
  264. slog.Error("error finding old metrics for node", "id", currentNode.ID, "error", err)
  265. return false
  266. }
  267. if oldMetrics.FailoverPeers == nil {
  268. oldMetrics.FailoverPeers = make(map[string]string)
  269. }
  270. var attachedClients []models.ExtClient
  271. if currentNode.IsIngressGateway {
  272. clients, err := logic.GetExtClientsByID(currentNode.ID.String(), currentNode.Network)
  273. if err == nil {
  274. attachedClients = clients
  275. }
  276. }
  277. if len(attachedClients) > 0 {
  278. // associate ext clients with IDs
  279. for i := range attachedClients {
  280. extMetric := newMetrics.Connectivity[attachedClients[i].PublicKey]
  281. if len(extMetric.NodeName) == 0 &&
  282. len(newMetrics.Connectivity[attachedClients[i].ClientID].NodeName) > 0 { // cover server clients
  283. extMetric = newMetrics.Connectivity[attachedClients[i].ClientID]
  284. if extMetric.TotalReceived > 0 && extMetric.TotalSent > 0 {
  285. extMetric.Connected = true
  286. }
  287. }
  288. extMetric.NodeName = attachedClients[i].ClientID
  289. delete(newMetrics.Connectivity, attachedClients[i].PublicKey)
  290. newMetrics.Connectivity[attachedClients[i].ClientID] = extMetric
  291. }
  292. }
  293. // run through metrics for each peer
  294. for k := range newMetrics.Connectivity {
  295. currMetric := newMetrics.Connectivity[k]
  296. oldMetric := oldMetrics.Connectivity[k]
  297. currMetric.TotalTime += oldMetric.TotalTime
  298. currMetric.Uptime += oldMetric.Uptime // get the total uptime for this connection
  299. if currMetric.CollectedByProxy {
  300. currMetric.TotalReceived += oldMetric.TotalReceived
  301. currMetric.TotalSent += oldMetric.TotalSent
  302. } else {
  303. if currMetric.TotalReceived < oldMetric.TotalReceived {
  304. currMetric.TotalReceived += oldMetric.TotalReceived
  305. } else {
  306. currMetric.TotalReceived += int64(math.Abs(float64(currMetric.TotalReceived) - float64(oldMetric.TotalReceived)))
  307. }
  308. if currMetric.TotalSent < oldMetric.TotalSent {
  309. currMetric.TotalSent += oldMetric.TotalSent
  310. } else {
  311. currMetric.TotalSent += int64(math.Abs(float64(currMetric.TotalSent) - float64(oldMetric.TotalSent)))
  312. }
  313. }
  314. if currMetric.Uptime == 0 || currMetric.TotalTime == 0 {
  315. currMetric.PercentUp = 0
  316. } else {
  317. currMetric.PercentUp = 100.0 * (float64(currMetric.Uptime) / float64(currMetric.TotalTime))
  318. }
  319. totalUpMinutes := currMetric.Uptime * ncutils.CheckInInterval
  320. currMetric.ActualUptime = time.Duration(totalUpMinutes) * time.Minute
  321. delete(oldMetrics.Connectivity, k) // remove from old data
  322. newMetrics.Connectivity[k] = currMetric
  323. }
  324. // add nodes that need failover
  325. nodes, err := logic.GetNetworkNodes(currentNode.Network)
  326. if err != nil {
  327. slog.Error("failed to retrieve nodes while updating metrics", "error", err)
  328. return false
  329. }
  330. for _, node := range nodes {
  331. if !newMetrics.Connectivity[node.ID.String()].Connected &&
  332. len(newMetrics.Connectivity[node.ID.String()].NodeName) > 0 &&
  333. node.Connected &&
  334. len(node.FailoverNode) > 0 &&
  335. !node.Failover {
  336. newMetrics.FailoverPeers[node.ID.String()] = node.FailoverNode.String()
  337. }
  338. }
  339. shouldUpdate := len(oldMetrics.FailoverPeers) == 0 && len(newMetrics.FailoverPeers) > 0
  340. for k, v := range oldMetrics.FailoverPeers {
  341. if len(newMetrics.FailoverPeers[k]) > 0 && len(v) == 0 {
  342. shouldUpdate = true
  343. }
  344. if len(v) > 0 && len(newMetrics.FailoverPeers[k]) == 0 {
  345. newMetrics.FailoverPeers[k] = v
  346. }
  347. }
  348. for k := range oldMetrics.Connectivity { // cleanup any left over data, self healing
  349. delete(newMetrics.Connectivity, k)
  350. }
  351. return shouldUpdate
  352. }
  353. func handleNewNodeDNS(host *models.Host, node *models.Node) error {
  354. dns := models.DNSUpdate{
  355. Action: models.DNSInsert,
  356. Name: host.Name + "." + node.Network,
  357. }
  358. if node.Address.IP != nil {
  359. dns.Address = node.Address.IP.String()
  360. if err := PublishDNSUpdate(node.Network, dns); err != nil {
  361. return err
  362. }
  363. } else if node.Address6.IP != nil {
  364. dns.Address = node.Address6.IP.String()
  365. if err := PublishDNSUpdate(node.Network, dns); err != nil {
  366. return err
  367. }
  368. }
  369. if err := PublishAllDNS(node); err != nil {
  370. return err
  371. }
  372. return nil
  373. }
  374. func handleHostCheckin(h, currentHost *models.Host) bool {
  375. if h == nil {
  376. return false
  377. }
  378. for i := range currentHost.Nodes {
  379. currNodeID := currentHost.Nodes[i]
  380. node, err := logic.GetNodeByID(currNodeID)
  381. if err != nil {
  382. if database.IsEmptyRecord(err) {
  383. fakeNode := models.Node{}
  384. fakeNode.ID, _ = uuid.Parse(currNodeID)
  385. fakeNode.Action = models.NODE_DELETE
  386. fakeNode.PendingDelete = true
  387. if err := NodeUpdate(&fakeNode); err != nil {
  388. slog.Warn("failed to inform host to remove node", "host", currentHost.Name, "hostid", currentHost.ID, "nodeid", currNodeID, "error", err)
  389. }
  390. }
  391. continue
  392. }
  393. if err := logic.UpdateNodeCheckin(&node); err != nil {
  394. slog.Warn("failed to update node on checkin", "nodeid", node.ID, "error", err)
  395. }
  396. }
  397. for i := range h.Interfaces {
  398. h.Interfaces[i].AddressString = h.Interfaces[i].Address.String()
  399. }
  400. /// version or firewall in use change does not require a peerUpdate
  401. if h.Version != currentHost.Version || h.FirewallInUse != currentHost.FirewallInUse {
  402. currentHost.FirewallInUse = h.FirewallInUse
  403. currentHost.Version = h.Version
  404. if err := logic.UpsertHost(currentHost); err != nil {
  405. slog.Error("failed to update host after check-in", "name", h.Name, "id", h.ID, "error", err)
  406. return false
  407. }
  408. }
  409. ifaceDelta := len(h.Interfaces) != len(currentHost.Interfaces) ||
  410. !h.EndpointIP.Equal(currentHost.EndpointIP) ||
  411. (len(h.NatType) > 0 && h.NatType != currentHost.NatType) ||
  412. h.DefaultInterface != currentHost.DefaultInterface ||
  413. h.EndpointDetection != servercfg.EndpointDetectionEnabled()
  414. if ifaceDelta { // only save if something changes
  415. currentHost.EndpointIP = h.EndpointIP
  416. currentHost.Interfaces = h.Interfaces
  417. currentHost.DefaultInterface = h.DefaultInterface
  418. currentHost.NatType = h.NatType
  419. if err := logic.UpsertHost(currentHost); err != nil {
  420. slog.Error("failed to update host after check-in", "name", h.Name, "id", h.ID, "error", err)
  421. return false
  422. }
  423. slog.Info("updated host after check-in", "name", currentHost.Name, "id", currentHost.ID)
  424. }
  425. slog.Info("check-in processed for host", "name", h.Name, "id", h.ID)
  426. return ifaceDelta
  427. }