publishers.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package mq
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "time"
  7. "github.com/gravitl/netmaker/logger"
  8. "github.com/gravitl/netmaker/logic"
  9. "github.com/gravitl/netmaker/logic/metrics"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/nm-proxy/manager"
  12. "github.com/gravitl/netmaker/servercfg"
  13. "github.com/gravitl/netmaker/serverctl"
  14. )
  15. // PublishPeerUpdate --- deterines and publishes a peer update to all the peers of a node
  16. func PublishPeerUpdate(newNode *models.Node, publishToSelf bool) error {
  17. if !servercfg.IsMessageQueueBackend() {
  18. return nil
  19. }
  20. networkNodes, err := logic.GetNetworkNodes(newNode.Network)
  21. if err != nil {
  22. logger.Log(1, "err getting Network Nodes", err.Error())
  23. return err
  24. }
  25. for _, node := range networkNodes {
  26. if node.IsServer == "yes" {
  27. if servercfg.IsProxyEnabled() {
  28. err := PublishProxyUpdate(manager.AddInterface, &node)
  29. if err != nil {
  30. logger.Log(0, "failed to send proxy update for server: ", err.Error())
  31. }
  32. }
  33. continue
  34. }
  35. if !publishToSelf && newNode.ID == node.ID {
  36. //skip self
  37. continue
  38. }
  39. err = PublishSinglePeerUpdate(&node)
  40. if err != nil {
  41. logger.Log(1, "failed to publish peer update to node", node.Name, "on network", node.Network, ":", err.Error())
  42. }
  43. }
  44. return err
  45. }
  46. func PublishProxyUpdate(action manager.ProxyAction, node *models.Node) error {
  47. peerUpdates, err := logic.GetPeersForProxy(node, false)
  48. if err != nil {
  49. return err
  50. }
  51. err = ProxyUpdate(&manager.ManagerAction{
  52. Action: action,
  53. Payload: peerUpdates}, node)
  54. if err != nil {
  55. logger.Log(1, "failed to send proxy update: ", err.Error())
  56. return err
  57. }
  58. return nil
  59. }
  60. // PublishSinglePeerUpdate --- determines and publishes a peer update to one node
  61. func PublishSinglePeerUpdate(node *models.Node) error {
  62. peerUpdate, err := logic.GetPeerUpdate(node)
  63. if err != nil {
  64. return err
  65. }
  66. if node.Proxy {
  67. proxyUpdate, err := logic.GetPeersForProxy(node, false)
  68. if err != nil {
  69. return err
  70. }
  71. peerUpdate.ProxyUpdate = manager.ManagerAction{
  72. Action: manager.AddInterface,
  73. Payload: proxyUpdate,
  74. }
  75. }
  76. data, err := json.Marshal(&peerUpdate)
  77. if err != nil {
  78. return err
  79. }
  80. return publish(node, fmt.Sprintf("peers/%s/%s", node.Network, node.ID), data)
  81. }
  82. // PublishPeerUpdate --- publishes a peer update to all the peers of a node
  83. func PublishExtPeerUpdate(node *models.Node) error {
  84. var err error
  85. if logic.IsLocalServer(node) {
  86. if err = logic.ServerUpdate(node, false); err != nil {
  87. logger.Log(1, "server node:", node.ID, "failed to update peers with ext clients")
  88. return err
  89. } else {
  90. return nil
  91. }
  92. }
  93. if !servercfg.IsMessageQueueBackend() {
  94. return nil
  95. }
  96. peerUpdate, err := logic.GetPeerUpdate(node)
  97. if err != nil {
  98. return err
  99. }
  100. data, err := json.Marshal(&peerUpdate)
  101. if err != nil {
  102. return err
  103. }
  104. if err = publish(node, fmt.Sprintf("peers/%s/%s", node.Network, node.ID), data); err != nil {
  105. return err
  106. }
  107. go PublishPeerUpdate(node, false)
  108. return nil
  109. }
  110. // NodeUpdate -- publishes a node update
  111. func NodeUpdate(node *models.Node) error {
  112. var err error
  113. if !servercfg.IsMessageQueueBackend() || node.IsServer == "yes" {
  114. return nil
  115. }
  116. logger.Log(3, "publishing node update to "+node.Name)
  117. if len(node.NetworkSettings.AccessKeys) > 0 {
  118. node.NetworkSettings.AccessKeys = []models.AccessKey{} // not to be sent (don't need to spread access keys around the network; we need to know how to reach other nodes, not become them)
  119. }
  120. if node.Proxy {
  121. err = PublishProxyUpdate(manager.AddInterface, node)
  122. if err != nil {
  123. logger.Log(1, "failed to publish proxy update to node", node.Name, "on network", node.Network, ":", err.Error())
  124. }
  125. } else {
  126. data, err := json.Marshal(node)
  127. if err != nil {
  128. logger.Log(2, "error marshalling node update ", err.Error())
  129. return err
  130. }
  131. if err = publish(node, fmt.Sprintf("update/%s/%s", node.Network, node.ID), data); err != nil {
  132. logger.Log(2, "error publishing node update to peer ", node.ID, err.Error())
  133. return err
  134. }
  135. }
  136. return nil
  137. }
  138. //ProxyUpdate -- publishes updates to peers related to proxy
  139. func ProxyUpdate(proxyPayload *manager.ManagerAction, node *models.Node) error {
  140. if !servercfg.IsMessageQueueBackend() {
  141. return nil
  142. }
  143. if node.IsServer == "yes" {
  144. logic.ProxyMgmChan <- proxyPayload
  145. return nil
  146. }
  147. logger.Log(3, "publishing proxy update to "+node.Name)
  148. data, err := json.Marshal(proxyPayload)
  149. if err != nil {
  150. logger.Log(2, "error marshalling node update ", err.Error())
  151. return err
  152. }
  153. if err = publish(node, fmt.Sprintf("proxy/%s/%s", node.Network, node.ID), data); err != nil {
  154. logger.Log(2, "error publishing proxy update to peer ", node.ID, err.Error())
  155. return err
  156. }
  157. return nil
  158. }
  159. // sendPeers - retrieve networks, send peer ports to all peers
  160. func sendPeers() {
  161. networks, err := logic.GetNetworks()
  162. if err != nil {
  163. logger.Log(1, "error retrieving networks for keepalive", err.Error())
  164. }
  165. var force bool
  166. peer_force_send++
  167. if peer_force_send == 5 {
  168. // run iptables update to ensure gateways work correctly and mq is forwarded if containerized
  169. if servercfg.ManageIPTables() != "off" {
  170. serverctl.InitIPTables(false)
  171. }
  172. servercfg.SetHost()
  173. force = true
  174. peer_force_send = 0
  175. err := logic.TimerCheckpoint() // run telemetry & log dumps if 24 hours has passed..
  176. if err != nil {
  177. logger.Log(3, "error occurred on timer,", err.Error())
  178. }
  179. collectServerMetrics(networks[:])
  180. }
  181. for _, network := range networks {
  182. serverNode, errN := logic.GetNetworkServerLocal(network.NetID)
  183. if errN == nil {
  184. serverNode.SetLastCheckIn()
  185. if err := logic.UpdateNode(&serverNode, &serverNode); err != nil {
  186. logger.Log(0, "failed checkin for server node", serverNode.Name, "on network", network.NetID, err.Error())
  187. }
  188. }
  189. isLeader := logic.IsLeader(&serverNode)
  190. if errN == nil && isLeader {
  191. if network.DefaultUDPHolePunch == "yes" {
  192. if logic.ShouldPublishPeerPorts(&serverNode) || force {
  193. if force {
  194. logger.Log(2, "sending scheduled peer update (5 min)")
  195. }
  196. err = PublishPeerUpdate(&serverNode, false)
  197. if err != nil {
  198. logger.Log(1, "error publishing udp port updates for network", network.NetID)
  199. logger.Log(1, errN.Error())
  200. }
  201. }
  202. }
  203. } else {
  204. if isLeader {
  205. logger.Log(1, "unable to retrieve leader for network ", network.NetID)
  206. }
  207. logger.Log(2, "server checkin complete for server", serverNode.Name, "on network", network.NetID)
  208. serverctl.SyncServerNetwork(network.NetID)
  209. if errN != nil {
  210. logger.Log(1, errN.Error())
  211. }
  212. if servercfg.IsProxyEnabled() {
  213. serverctl.SyncServerNetworkWithProxy()
  214. }
  215. }
  216. }
  217. }
  218. // ServerStartNotify - notifies all non server nodes to pull changes after a restart
  219. func ServerStartNotify() error {
  220. nodes, err := logic.GetAllNodes()
  221. if err != nil {
  222. return err
  223. }
  224. for i := range nodes {
  225. nodes[i].Action = models.NODE_FORCE_UPDATE
  226. if err = NodeUpdate(&nodes[i]); err != nil {
  227. logger.Log(1, "error when notifying node", nodes[i].Name, " - ", nodes[i].ID, "of a server startup")
  228. }
  229. }
  230. return nil
  231. }
  232. // function to collect and store metrics for server nodes
  233. func collectServerMetrics(networks []models.Network) {
  234. if !servercfg.Is_EE {
  235. return
  236. }
  237. if len(networks) > 0 {
  238. for i := range networks {
  239. currentNetworkNodes, err := logic.GetNetworkNodes(networks[i].NetID)
  240. if err != nil {
  241. continue
  242. }
  243. currentServerNodes := logic.GetServerNodes(networks[i].NetID)
  244. if len(currentServerNodes) > 0 {
  245. for i := range currentServerNodes {
  246. if logic.IsLocalServer(&currentServerNodes[i]) {
  247. serverMetrics := logic.CollectServerMetrics(currentServerNodes[i].ID, currentNetworkNodes)
  248. if serverMetrics != nil {
  249. serverMetrics.NodeName = currentServerNodes[i].Name
  250. serverMetrics.NodeID = currentServerNodes[i].ID
  251. serverMetrics.IsServer = "yes"
  252. serverMetrics.Network = currentServerNodes[i].Network
  253. if err = metrics.GetExchangedBytesForNode(&currentServerNodes[i], serverMetrics); err != nil {
  254. logger.Log(1, fmt.Sprintf("failed to update exchanged bytes info for server: %s, err: %v",
  255. currentServerNodes[i].Name, err))
  256. }
  257. updateNodeMetrics(&currentServerNodes[i], serverMetrics)
  258. if err = logic.UpdateMetrics(currentServerNodes[i].ID, serverMetrics); err != nil {
  259. logger.Log(1, "failed to update metrics for server node", currentServerNodes[i].ID)
  260. }
  261. if servercfg.IsMetricsExporter() {
  262. logger.Log(2, "-------------> SERVER METRICS: ", fmt.Sprintf("%+v", serverMetrics))
  263. if err := pushMetricsToExporter(*serverMetrics); err != nil {
  264. logger.Log(2, "failed to push server metrics to exporter: ", err.Error())
  265. }
  266. }
  267. }
  268. }
  269. }
  270. }
  271. }
  272. }
  273. }
  274. func pushMetricsToExporter(metrics models.Metrics) error {
  275. logger.Log(2, "----> Pushing metrics to exporter")
  276. data, err := json.Marshal(metrics)
  277. if err != nil {
  278. return errors.New("failed to marshal metrics: " + err.Error())
  279. }
  280. if token := mqclient.Publish("metrics_exporter", 2, true, data); !token.WaitTimeout(MQ_TIMEOUT*time.Second) || token.Error() != nil {
  281. var err error
  282. if token.Error() == nil {
  283. err = errors.New("connection timeout")
  284. } else {
  285. err = token.Error()
  286. }
  287. return err
  288. }
  289. return nil
  290. }