handlers.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package mq
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. mqtt "github.com/eclipse/paho.mqtt.golang"
  7. "github.com/gravitl/netmaker/database"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/logic"
  10. "github.com/gravitl/netmaker/logic/hostactions"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/netclient/ncutils"
  13. "github.com/gravitl/netmaker/servercfg"
  14. )
  15. // DefaultHandler default message queue handler -- NOT USED
  16. func DefaultHandler(client mqtt.Client, msg mqtt.Message) {
  17. logger.Log(0, "MQTT Message: Topic: ", string(msg.Topic()), " Message: ", string(msg.Payload()))
  18. }
  19. // Ping message Handler -- handles ping topic from client nodes
  20. func Ping(client mqtt.Client, msg mqtt.Message) {
  21. go func() {
  22. id, err := getID(msg.Topic())
  23. if err != nil {
  24. logger.Log(0, "error getting node.ID sent on ping topic ")
  25. return
  26. }
  27. node, err := logic.GetNodeByID(id)
  28. if err != nil {
  29. logger.Log(3, "mq-ping error getting node: ", err.Error())
  30. record, err := database.FetchRecord(database.NODES_TABLE_NAME, id)
  31. if err != nil {
  32. logger.Log(3, "error reading database ", err.Error())
  33. return
  34. }
  35. logger.Log(3, "record from database")
  36. logger.Log(3, record)
  37. return
  38. }
  39. decrypted, decryptErr := decryptMsg(&node, msg.Payload())
  40. if decryptErr != nil {
  41. logger.Log(0, "error decrypting when updating node ", node.ID.String(), decryptErr.Error())
  42. return
  43. }
  44. var checkin models.NodeCheckin
  45. if err := json.Unmarshal(decrypted, &checkin); err != nil {
  46. logger.Log(1, "error unmarshaling payload ", err.Error())
  47. return
  48. }
  49. host, err := logic.GetHost(node.HostID.String())
  50. if err != nil {
  51. logger.Log(0, "error retrieving host for node ", node.ID.String(), err.Error())
  52. return
  53. }
  54. node.SetLastCheckIn()
  55. host.Version = checkin.Version
  56. node.Connected = checkin.Connected
  57. host.Interfaces = checkin.Ifaces
  58. for i := range host.Interfaces {
  59. host.Interfaces[i].AddressString = host.Interfaces[i].Address.String()
  60. }
  61. if err := logic.UpdateNode(&node, &node); err != nil {
  62. logger.Log(0, "error updating node", node.ID.String(), " on checkin", err.Error())
  63. return
  64. }
  65. logger.Log(3, "ping processed for node", node.ID.String())
  66. // --TODO --set client version once feature is implemented.
  67. //node.SetClientVersion(msg.Payload())
  68. }()
  69. }
  70. // UpdateNode message Handler -- handles updates from client nodes
  71. func UpdateNode(client mqtt.Client, msg mqtt.Message) {
  72. go func() {
  73. id, err := getID(msg.Topic())
  74. if err != nil {
  75. logger.Log(1, "error getting node.ID sent on ", msg.Topic(), err.Error())
  76. return
  77. }
  78. currentNode, err := logic.GetNodeByID(id)
  79. if err != nil {
  80. logger.Log(1, "error getting node ", id, err.Error())
  81. return
  82. }
  83. decrypted, decryptErr := decryptMsg(&currentNode, msg.Payload())
  84. if decryptErr != nil {
  85. logger.Log(1, "failed to decrypt message for node ", id, decryptErr.Error())
  86. return
  87. }
  88. var newNode models.Node
  89. if err := json.Unmarshal(decrypted, &newNode); err != nil {
  90. logger.Log(1, "error unmarshaling payload ", err.Error())
  91. return
  92. }
  93. ifaceDelta := logic.IfaceDelta(&currentNode, &newNode)
  94. if servercfg.Is_EE && ifaceDelta {
  95. if err = logic.EnterpriseResetAllPeersFailovers(currentNode.ID, currentNode.Network); err != nil {
  96. logger.Log(1, "failed to reset failover list during node update", currentNode.ID.String(), currentNode.Network)
  97. }
  98. }
  99. newNode.SetLastCheckIn()
  100. if err := logic.UpdateNode(&currentNode, &newNode); err != nil {
  101. logger.Log(1, "error saving node", err.Error())
  102. return
  103. }
  104. if ifaceDelta { // reduce number of unneeded updates, by only sending on iface changes
  105. if err = PublishPeerUpdate(); err != nil {
  106. logger.Log(0, "error updating peers when node", currentNode.ID.String(), "informed the server of an interface change", err.Error())
  107. }
  108. }
  109. logger.Log(1, "updated node", id, newNode.ID.String())
  110. }()
  111. }
  112. // UpdateHost message Handler -- handles host updates from clients
  113. func UpdateHost(client mqtt.Client, msg mqtt.Message) {
  114. go func(msg mqtt.Message) {
  115. id, err := getID(msg.Topic())
  116. if err != nil {
  117. logger.Log(1, "error getting host.ID sent on ", msg.Topic(), err.Error())
  118. return
  119. }
  120. currentHost, err := logic.GetHost(id)
  121. if err != nil {
  122. logger.Log(1, "error getting host ", id, err.Error())
  123. return
  124. }
  125. decrypted, decryptErr := decryptMsgWithHost(currentHost, msg.Payload())
  126. if decryptErr != nil {
  127. logger.Log(1, "failed to decrypt message for host ", id, decryptErr.Error())
  128. return
  129. }
  130. var hostUpdate models.HostUpdate
  131. if err := json.Unmarshal(decrypted, &hostUpdate); err != nil {
  132. logger.Log(1, "error unmarshaling payload ", err.Error())
  133. return
  134. }
  135. logger.Log(3, fmt.Sprintf("recieved host update: %s\n", hostUpdate.Host.ID.String()))
  136. var sendPeerUpdate bool
  137. switch hostUpdate.Action {
  138. case models.Acknowledgement:
  139. hu := hostactions.GetAction(currentHost.ID.String())
  140. if hu != nil {
  141. if err = HostUpdate(hu); err != nil {
  142. logger.Log(0, "failed to send new node to host", hostUpdate.Host.Name, currentHost.ID.String(), err.Error())
  143. return
  144. } else {
  145. if err = PublishSingleHostPeerUpdate(currentHost, nil); err != nil {
  146. logger.Log(0, "failed peers publish after join acknowledged", hostUpdate.Host.Name, currentHost.ID.String(), err.Error())
  147. return
  148. }
  149. }
  150. }
  151. case models.UpdateHost:
  152. sendPeerUpdate = logic.UpdateHostFromClient(&hostUpdate.Host, currentHost)
  153. err := logic.UpsertHost(currentHost)
  154. if err != nil {
  155. logger.Log(0, "failed to update host: ", currentHost.ID.String(), err.Error())
  156. return
  157. }
  158. case models.DeleteHost:
  159. if servercfg.GetBrokerType() == servercfg.EmqxBrokerType {
  160. // delete EMQX credentials for host
  161. if err := DeleteEmqxUser(currentHost.ID.String()); err != nil {
  162. logger.Log(0, "failed to remove host credentials from EMQX: ", currentHost.ID.String(), err.Error())
  163. return
  164. }
  165. }
  166. if err := logic.DisassociateAllNodesFromHost(currentHost.ID.String()); err != nil {
  167. logger.Log(0, "failed to delete all nodes of host: ", currentHost.ID.String(), err.Error())
  168. return
  169. }
  170. if err := logic.RemoveHostByID(currentHost.ID.String()); err != nil {
  171. logger.Log(0, "failed to delete host: ", currentHost.ID.String(), err.Error())
  172. return
  173. }
  174. sendPeerUpdate = true
  175. }
  176. if sendPeerUpdate {
  177. err := PublishPeerUpdate()
  178. if err != nil {
  179. logger.Log(0, "failed to pulish peer update: ", err.Error())
  180. }
  181. }
  182. // if servercfg.Is_EE && ifaceDelta {
  183. // if err = logic.EnterpriseResetAllPeersFailovers(currentHost.ID.String(), currentHost.Network); err != nil {
  184. // logger.Log(1, "failed to reset failover list during node update", currentHost.ID.String(), currentHost.Network)
  185. // }
  186. // }
  187. }(msg)
  188. }
  189. // UpdateMetrics message Handler -- handles updates from client nodes for metrics
  190. func UpdateMetrics(client mqtt.Client, msg mqtt.Message) {
  191. if servercfg.Is_EE {
  192. go func() {
  193. id, err := getID(msg.Topic())
  194. if err != nil {
  195. logger.Log(1, "error getting node.ID sent on ", msg.Topic(), err.Error())
  196. return
  197. }
  198. currentNode, err := logic.GetNodeByID(id)
  199. if err != nil {
  200. logger.Log(1, "error getting node ", id, err.Error())
  201. return
  202. }
  203. decrypted, decryptErr := decryptMsg(&currentNode, msg.Payload())
  204. if decryptErr != nil {
  205. logger.Log(1, "failed to decrypt message for node ", id, decryptErr.Error())
  206. return
  207. }
  208. var newMetrics models.Metrics
  209. if err := json.Unmarshal(decrypted, &newMetrics); err != nil {
  210. logger.Log(1, "error unmarshaling payload ", err.Error())
  211. return
  212. }
  213. shouldUpdate := updateNodeMetrics(&currentNode, &newMetrics)
  214. if err = logic.UpdateMetrics(id, &newMetrics); err != nil {
  215. logger.Log(1, "faield to update node metrics", id, err.Error())
  216. return
  217. }
  218. if servercfg.IsMetricsExporter() {
  219. if err := pushMetricsToExporter(newMetrics); err != nil {
  220. logger.Log(2, fmt.Sprintf("failed to push node: [%s] metrics to exporter, err: %v",
  221. currentNode.ID, err))
  222. }
  223. }
  224. if newMetrics.Connectivity != nil {
  225. err := logic.EnterpriseFailoverFunc(&currentNode)
  226. if err != nil {
  227. logger.Log(0, "failed to failover for node", currentNode.ID.String(), "on network", currentNode.Network, "-", err.Error())
  228. }
  229. }
  230. if shouldUpdate {
  231. logger.Log(2, "updating peers after node", currentNode.ID.String(), currentNode.Network, "detected connectivity issues")
  232. host, err := logic.GetHost(currentNode.HostID.String())
  233. if err == nil {
  234. if err = PublishSingleHostPeerUpdate(host, nil); err != nil {
  235. logger.Log(0, "failed to publish update after failover peer change for node", currentNode.ID.String(), currentNode.Network)
  236. }
  237. }
  238. }
  239. logger.Log(1, "updated node metrics", id)
  240. }()
  241. }
  242. }
  243. // ClientPeerUpdate message handler -- handles updating peers after signal from client nodes
  244. func ClientPeerUpdate(client mqtt.Client, msg mqtt.Message) {
  245. go func() {
  246. id, err := getID(msg.Topic())
  247. if err != nil {
  248. logger.Log(1, "error getting node.ID sent on ", msg.Topic(), err.Error())
  249. return
  250. }
  251. currentNode, err := logic.GetNodeByID(id)
  252. if err != nil {
  253. logger.Log(1, "error getting node ", id, err.Error())
  254. return
  255. }
  256. decrypted, decryptErr := decryptMsg(&currentNode, msg.Payload())
  257. if decryptErr != nil {
  258. logger.Log(1, "failed to decrypt message during client peer update for node ", id, decryptErr.Error())
  259. return
  260. }
  261. switch decrypted[0] {
  262. case ncutils.ACK:
  263. //do we still need this
  264. case ncutils.DONE:
  265. updateNodePeers(&currentNode)
  266. }
  267. logger.Log(1, "sent peer updates after signal received from", id)
  268. }()
  269. }
  270. func updateNodePeers(currentNode *models.Node) {
  271. if err := PublishPeerUpdate(); err != nil {
  272. logger.Log(1, "error publishing peer update ", err.Error())
  273. return
  274. }
  275. }
  276. func updateNodeMetrics(currentNode *models.Node, newMetrics *models.Metrics) bool {
  277. if newMetrics.FailoverPeers == nil {
  278. newMetrics.FailoverPeers = make(map[string]string)
  279. }
  280. oldMetrics, err := logic.GetMetrics(currentNode.ID.String())
  281. if err != nil {
  282. logger.Log(1, "error finding old metrics for node", currentNode.ID.String())
  283. return false
  284. }
  285. if oldMetrics.FailoverPeers == nil {
  286. oldMetrics.FailoverPeers = make(map[string]string)
  287. }
  288. var attachedClients []models.ExtClient
  289. if currentNode.IsIngressGateway {
  290. clients, err := logic.GetExtClientsByID(currentNode.ID.String(), currentNode.Network)
  291. if err == nil {
  292. attachedClients = clients
  293. }
  294. }
  295. if len(attachedClients) > 0 {
  296. // associate ext clients with IDs
  297. for i := range attachedClients {
  298. extMetric := newMetrics.Connectivity[attachedClients[i].PublicKey]
  299. if len(extMetric.NodeName) == 0 &&
  300. len(newMetrics.Connectivity[attachedClients[i].ClientID].NodeName) > 0 { // cover server clients
  301. extMetric = newMetrics.Connectivity[attachedClients[i].ClientID]
  302. if extMetric.TotalReceived > 0 && extMetric.TotalSent > 0 {
  303. extMetric.Connected = true
  304. }
  305. }
  306. extMetric.NodeName = attachedClients[i].ClientID
  307. delete(newMetrics.Connectivity, attachedClients[i].PublicKey)
  308. newMetrics.Connectivity[attachedClients[i].ClientID] = extMetric
  309. }
  310. }
  311. // run through metrics for each peer
  312. for k := range newMetrics.Connectivity {
  313. currMetric := newMetrics.Connectivity[k]
  314. oldMetric := oldMetrics.Connectivity[k]
  315. currMetric.TotalTime += oldMetric.TotalTime
  316. currMetric.Uptime += oldMetric.Uptime // get the total uptime for this connection
  317. if currMetric.Uptime == 0 || currMetric.TotalTime == 0 {
  318. currMetric.PercentUp = 0
  319. } else {
  320. currMetric.PercentUp = 100.0 * (float64(currMetric.Uptime) / float64(currMetric.TotalTime))
  321. }
  322. totalUpMinutes := currMetric.Uptime * ncutils.CheckInInterval
  323. currMetric.ActualUptime = time.Duration(totalUpMinutes) * time.Minute
  324. delete(oldMetrics.Connectivity, k) // remove from old data
  325. newMetrics.Connectivity[k] = currMetric
  326. }
  327. // add nodes that need failover
  328. nodes, err := logic.GetNetworkNodes(currentNode.Network)
  329. if err != nil {
  330. logger.Log(0, "failed to retrieve nodes while updating metrics")
  331. return false
  332. }
  333. for _, node := range nodes {
  334. if !newMetrics.Connectivity[node.ID.String()].Connected &&
  335. len(newMetrics.Connectivity[node.ID.String()].NodeName) > 0 &&
  336. node.Connected &&
  337. len(node.FailoverNode) > 0 &&
  338. !node.Failover {
  339. newMetrics.FailoverPeers[node.ID.String()] = node.FailoverNode.String()
  340. }
  341. }
  342. shouldUpdate := len(oldMetrics.FailoverPeers) == 0 && len(newMetrics.FailoverPeers) > 0
  343. for k, v := range oldMetrics.FailoverPeers {
  344. if len(newMetrics.FailoverPeers[k]) > 0 && len(v) == 0 {
  345. shouldUpdate = true
  346. }
  347. if len(v) > 0 && len(newMetrics.FailoverPeers[k]) == 0 {
  348. newMetrics.FailoverPeers[k] = v
  349. }
  350. }
  351. for k := range oldMetrics.Connectivity { // cleanup any left over data, self healing
  352. delete(newMetrics.Connectivity, k)
  353. }
  354. return shouldUpdate
  355. }