daemon.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package functions
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "os"
  8. "os/signal"
  9. "runtime"
  10. "sync"
  11. "syscall"
  12. "time"
  13. mqtt "github.com/eclipse/paho.mqtt.golang"
  14. "github.com/gravitl/netmaker/models"
  15. "github.com/gravitl/netmaker/netclient/config"
  16. "github.com/gravitl/netmaker/netclient/local"
  17. "github.com/gravitl/netmaker/netclient/ncutils"
  18. "github.com/gravitl/netmaker/netclient/wireguard"
  19. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  20. )
  21. var messageCache = make(map[string]string, 20)
  22. const lastNodeUpdate = "lnu"
  23. const lastPeerUpdate = "lpu"
  24. func insert(network, which, cache string) {
  25. var mu sync.Mutex
  26. mu.Lock()
  27. defer mu.Unlock()
  28. messageCache[fmt.Sprintf("%s%s", network, which)] = cache
  29. }
  30. func read(network, which string) string {
  31. return messageCache[fmt.Sprintf("%s%s", network, which)]
  32. }
  33. // Daemon runs netclient daemon from command line
  34. func Daemon() error {
  35. ctx, cancel := context.WithCancel(context.Background())
  36. networks, err := ncutils.GetSystemNetworks()
  37. if err != nil {
  38. cancel()
  39. return err
  40. }
  41. for _, network := range networks {
  42. go MessageQueue(ctx, network)
  43. }
  44. quit := make(chan os.Signal, 1)
  45. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  46. <-quit
  47. cancel()
  48. ncutils.Log("all done")
  49. return nil
  50. }
  51. // SetupMQTT creates a connection to broker and return client
  52. func SetupMQTT(cfg *config.ClientConfig) mqtt.Client {
  53. opts := mqtt.NewClientOptions()
  54. for i, addr := range cfg.Node.NetworkSettings.DefaultServerAddrs {
  55. if addr != "" {
  56. ncutils.Log(fmt.Sprintf("adding server (%d) to listen on network %s \n", (i + 1), cfg.Node.Network))
  57. opts.AddBroker(addr + ":1883")
  58. }
  59. }
  60. opts.SetDefaultPublishHandler(All)
  61. client := mqtt.NewClient(opts)
  62. if token := client.Connect(); token.Wait() && token.Error() != nil {
  63. log.Fatal(token.Error())
  64. }
  65. return client
  66. }
  67. // MessageQueue sets up Message Queue and subsribes/publishes updates to/from server
  68. func MessageQueue(ctx context.Context, network string) {
  69. ncutils.Log("netclient go routine started for " + network)
  70. var cfg config.ClientConfig
  71. cfg.Network = network
  72. cfg.ReadConfig()
  73. ncutils.Log("daemon started for network:" + network)
  74. client := SetupMQTT(&cfg)
  75. if cfg.DebugOn {
  76. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  77. log.Fatal(token.Error())
  78. }
  79. ncutils.Log("subscribed to all topics for debugging purposes")
  80. }
  81. if token := client.Subscribe("update/"+cfg.Node.ID, 0, NodeUpdate); token.Wait() && token.Error() != nil {
  82. log.Fatal(token.Error())
  83. }
  84. if cfg.DebugOn {
  85. ncutils.Log("subscribed to node updates for node " + cfg.Node.Name + " update/" + cfg.Node.ID)
  86. }
  87. if token := client.Subscribe("update/peers/"+cfg.Node.ID, 0, UpdatePeers); token.Wait() && token.Error() != nil {
  88. log.Fatal(token.Error())
  89. }
  90. if cfg.DebugOn {
  91. ncutils.Log("subscribed to node updates for node " + cfg.Node.Name + " update/peers/" + cfg.Node.ID)
  92. }
  93. defer client.Disconnect(250)
  94. go Checkin(ctx, &cfg, network)
  95. <-ctx.Done()
  96. ncutils.Log("shutting down daemon")
  97. }
  98. // All -- mqtt message hander for all ('#') topics
  99. var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  100. ncutils.Log("default message handler -- received message but not handling")
  101. ncutils.Log("Topic: " + string(msg.Topic()))
  102. //ncutils.Log("Message: " + string(msg.Payload()))
  103. }
  104. // NodeUpdate -- mqtt message handler for /update/<NodeID> topic
  105. var NodeUpdate mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  106. ncutils.Log("received message to update node " + string(msg.Payload()))
  107. //potentiall blocking i/o so do this in a go routine
  108. go func() {
  109. var newNode models.Node
  110. var cfg config.ClientConfig
  111. err := json.Unmarshal(msg.Payload(), &newNode)
  112. if err != nil {
  113. ncutils.Log("error unmarshalling node update data" + err.Error())
  114. return
  115. }
  116. // see if cache hit, if so skip
  117. var currentMessage = read(newNode.Network, lastNodeUpdate)
  118. if currentMessage == string(msg.Payload()) {
  119. return
  120. }
  121. insert(newNode.Network, lastNodeUpdate, string(msg.Payload()))
  122. cfg.Network = newNode.Network
  123. cfg.ReadConfig()
  124. //check if interface name has changed if so delete.
  125. if cfg.Node.Interface != newNode.Interface {
  126. if err = wireguard.RemoveConf(cfg.Node.Interface, true); err != nil {
  127. ncutils.PrintLog("could not delete old interface "+cfg.Node.Interface+": "+err.Error(), 1)
  128. }
  129. }
  130. newNode.PullChanges = "no"
  131. //ensure that OS never changes
  132. newNode.OS = runtime.GOOS
  133. cfg.Node = newNode
  134. switch newNode.Action {
  135. case models.NODE_DELETE:
  136. if err := RemoveLocalInstance(&cfg, cfg.Network); err != nil {
  137. ncutils.PrintLog("error deleting local instance: "+err.Error(), 1)
  138. return
  139. }
  140. if token := client.Unsubscribe("update/"+newNode.ID, "update/peers/"+newNode.ID); token.Wait() && token.Error() != nil {
  141. ncutils.PrintLog("error unsubscribing during node deletion", 1)
  142. }
  143. return
  144. case models.NODE_UPDATE_KEY:
  145. if err := UpdateKeys(&cfg, client); err != nil {
  146. ncutils.PrintLog("err updating wireguard keys: "+err.Error(), 1)
  147. }
  148. case models.NODE_NOOP:
  149. default:
  150. }
  151. //Save new config
  152. if err := config.Write(&cfg, cfg.Network); err != nil {
  153. ncutils.PrintLog("error updating node configuration: "+err.Error(), 1)
  154. }
  155. nameserver := cfg.Server.CoreDNSAddr
  156. privateKey, err := wireguard.RetrievePrivKey(newNode.Network)
  157. if err != nil {
  158. ncutils.Log("error reading PrivateKey " + err.Error())
  159. return
  160. }
  161. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  162. if err := wireguard.UpdateWgInterface(file, privateKey, nameserver, newNode); err != nil {
  163. ncutils.Log("error updating wireguard config " + err.Error())
  164. return
  165. }
  166. ncutils.Log("applyWGQuickConf to " + file)
  167. err = wireguard.ApplyWGQuickConf(file)
  168. if err != nil {
  169. ncutils.Log("error restarting wg after node update " + err.Error())
  170. return
  171. }
  172. //deal with DNS
  173. if newNode.DNSOn == "yes" {
  174. ncutils.Log("setting up DNS")
  175. if err = local.UpdateDNS(cfg.Node.Interface, cfg.Network, cfg.Server.CoreDNSAddr); err != nil {
  176. ncutils.Log("error applying dns" + err.Error())
  177. }
  178. } else {
  179. ncutils.Log("settng DNS off")
  180. _, err := ncutils.RunCmd("/usr/bin/resolvectl revert "+cfg.Node.Interface, true)
  181. if err != nil {
  182. ncutils.Log("error applying dns" + err.Error())
  183. }
  184. }
  185. }()
  186. }
  187. // UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
  188. var UpdatePeers mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  189. go func() {
  190. var peerUpdate models.PeerUpdate
  191. err := json.Unmarshal(msg.Payload(), &peerUpdate)
  192. if err != nil {
  193. ncutils.Log("error unmarshalling peer data")
  194. return
  195. }
  196. // see if cache hit, if so skip
  197. var currentMessage = read(peerUpdate.Network, lastPeerUpdate)
  198. if currentMessage == string(msg.Payload()) {
  199. return
  200. }
  201. insert(peerUpdate.Network, lastPeerUpdate, string(msg.Payload()))
  202. ncutils.Log("update peer handler")
  203. var cfg config.ClientConfig
  204. cfg.Network = peerUpdate.Network
  205. cfg.ReadConfig()
  206. var shouldReSub = shouldResub(cfg.Node.NetworkSettings.DefaultServerAddrs, peerUpdate.ServerAddrs)
  207. if shouldReSub {
  208. client.Disconnect(250) // kill client
  209. // un sub, re sub.. how?
  210. client.Unsubscribe("update/"+cfg.Node.ID, "update/peers/"+cfg.Node.ID)
  211. cfg.Node.NetworkSettings.DefaultServerAddrs = peerUpdate.ServerAddrs
  212. }
  213. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  214. err = wireguard.UpdateWgPeers(file, peerUpdate.Peers)
  215. if err != nil {
  216. ncutils.Log("error updating wireguard peers" + err.Error())
  217. return
  218. }
  219. ncutils.Log("applyWGQuickConf to " + file)
  220. err = wireguard.ApplyWGQuickConf(file)
  221. if err != nil {
  222. ncutils.Log("error restarting wg after peer update " + err.Error())
  223. return
  224. }
  225. }()
  226. }
  227. // Resubscribe --- handles resubscribing if needed
  228. func Resubscribe(client mqtt.Client, cfg *config.ClientConfig) {
  229. if err := config.ModConfig(&cfg.Node); err == nil {
  230. client.Disconnect(250)
  231. client = SetupMQTT(cfg)
  232. if token := client.Subscribe("update/"+cfg.Node.ID, 0, NodeUpdate); token.Wait() && token.Error() != nil {
  233. log.Fatal(token.Error())
  234. }
  235. if cfg.DebugOn {
  236. ncutils.Log("subscribed to node updates for node " + cfg.Node.Name + " update/" + cfg.Node.ID)
  237. }
  238. if token := client.Subscribe("update/peers/"+cfg.Node.ID, 0, UpdatePeers); token.Wait() && token.Error() != nil {
  239. log.Fatal(token.Error())
  240. }
  241. ncutils.Log("finished re subbing")
  242. } else {
  243. ncutils.Log("could not mod config when re-subbing")
  244. }
  245. }
  246. // UpdateKeys -- updates private key and returns new publickey
  247. func UpdateKeys(cfg *config.ClientConfig, client mqtt.Client) error {
  248. ncutils.Log("received message to update keys")
  249. //potentiall blocking i/o so do this in a go routine
  250. key, err := wgtypes.GeneratePrivateKey()
  251. if err != nil {
  252. ncutils.Log("error generating privatekey " + err.Error())
  253. return err
  254. }
  255. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  256. if err := wireguard.UpdatePrivateKey(file, key.String()); err != nil {
  257. ncutils.Log("error updating wireguard key " + err.Error())
  258. return err
  259. }
  260. cfg.Node.PublicKey = key.PublicKey().String()
  261. PublishNodeUpdate(cfg)
  262. if err := config.ModConfig(&cfg.Node); err != nil {
  263. ncutils.Log("error updating local config " + err.Error())
  264. }
  265. return nil
  266. }
  267. // Checkin -- go routine that checks for public or local ip changes, publishes changes
  268. // if there are no updates, simply "pings" the server as a checkin
  269. func Checkin(ctx context.Context, cfg *config.ClientConfig, network string) {
  270. for {
  271. select {
  272. case <-ctx.Done():
  273. ncutils.Log("Checkin cancelled")
  274. return
  275. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  276. case <-time.After(time.Second * 60):
  277. ncutils.Log("Checkin running")
  278. //read latest config
  279. cfg.ReadConfig()
  280. if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
  281. extIP, err := ncutils.GetPublicIP()
  282. if err != nil {
  283. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  284. }
  285. if cfg.Node.Endpoint != extIP && extIP != "" {
  286. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
  287. cfg.Node.Endpoint = extIP
  288. PublishNodeUpdate(cfg)
  289. }
  290. intIP, err := getPrivateAddr()
  291. if err != nil {
  292. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  293. }
  294. if cfg.Node.LocalAddress != intIP && intIP != "" {
  295. ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
  296. cfg.Node.LocalAddress = intIP
  297. PublishNodeUpdate(cfg)
  298. }
  299. } else {
  300. localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
  301. if err != nil {
  302. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  303. }
  304. if cfg.Node.Endpoint != localIP && localIP != "" {
  305. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
  306. cfg.Node.Endpoint = localIP
  307. PublishNodeUpdate(cfg)
  308. }
  309. }
  310. Hello(cfg, network)
  311. ncutils.Log("Checkin complete")
  312. }
  313. }
  314. }
  315. // PublishNodeUpdates -- saves node and pushes changes to broker
  316. func PublishNodeUpdate(cfg *config.ClientConfig) {
  317. if err := config.Write(cfg, cfg.Network); err != nil {
  318. ncutils.Log("error saving configuration" + err.Error())
  319. }
  320. client := SetupMQTT(cfg)
  321. data, err := json.Marshal(cfg.Node)
  322. if err != nil {
  323. ncutils.Log("error marshling node update " + err.Error())
  324. }
  325. if token := client.Publish("update/"+cfg.Node.ID, 0, false, data); token.Wait() && token.Error() != nil {
  326. ncutils.Log("error publishing endpoint update " + token.Error().Error())
  327. }
  328. client.Disconnect(250)
  329. }
  330. // Hello -- ping the broker to let server know node is alive and doing fine
  331. func Hello(cfg *config.ClientConfig, network string) {
  332. client := SetupMQTT(cfg)
  333. if token := client.Publish("ping/"+cfg.Node.ID, 2, false, "hello world!"); token.Wait() && token.Error() != nil {
  334. ncutils.Log("error publishing ping " + token.Error().Error())
  335. }
  336. client.Disconnect(250)
  337. }
  338. func shouldResub(currentServers, newServers []string) bool {
  339. if len(currentServers) != len(newServers) {
  340. return false
  341. }
  342. for _, srv := range currentServers {
  343. if !ncutils.StringSliceContains(newServers, srv) {
  344. return true
  345. }
  346. }
  347. return false
  348. }