daemon.go 10 KB

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