daemon.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package functions
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "os"
  9. "os/signal"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "time"
  15. mqtt "github.com/eclipse/paho.mqtt.golang"
  16. "github.com/gravitl/netmaker/logger"
  17. "github.com/gravitl/netmaker/models"
  18. "github.com/gravitl/netmaker/netclient/auth"
  19. "github.com/gravitl/netmaker/netclient/config"
  20. "github.com/gravitl/netmaker/netclient/local"
  21. "github.com/gravitl/netmaker/netclient/ncutils"
  22. "github.com/gravitl/netmaker/netclient/wireguard"
  23. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  24. )
  25. // ServerKeepalive - stores time of last server keepalive message
  26. var keepalive = make(map[string]time.Time, 3)
  27. var messageCache = make(map[string]string, 20)
  28. const lastNodeUpdate = "lnu"
  29. const lastPeerUpdate = "lpu"
  30. func insert(network, which, cache string) {
  31. var mu sync.Mutex
  32. mu.Lock()
  33. defer mu.Unlock()
  34. messageCache[fmt.Sprintf("%s%s", network, which)] = cache
  35. }
  36. func read(network, which string) string {
  37. return messageCache[fmt.Sprintf("%s%s", network, which)]
  38. }
  39. // Daemon runs netclient daemon from command line
  40. func Daemon() error {
  41. ctx, cancel := context.WithCancel(context.Background())
  42. networks, err := ncutils.GetSystemNetworks()
  43. if err != nil {
  44. cancel()
  45. return err
  46. }
  47. for _, network := range networks {
  48. go MessageQueue(ctx, network)
  49. }
  50. quit := make(chan os.Signal, 1)
  51. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  52. <-quit
  53. cancel()
  54. ncutils.Log("all done")
  55. return nil
  56. }
  57. // SetupMQTT creates a connection to broker and return client
  58. func SetupMQTT(cfg *config.ClientConfig) mqtt.Client {
  59. opts := mqtt.NewClientOptions()
  60. for _, server := range cfg.Node.NetworkSettings.DefaultServerAddrs {
  61. if server.Address != "" && server.IsLeader {
  62. ncutils.Log(fmt.Sprintf("adding server (%s) to listen on network %s", server.Address, cfg.Node.Network))
  63. opts.AddBroker(server.Address + ":1883")
  64. break
  65. }
  66. }
  67. opts.SetDefaultPublishHandler(All)
  68. client := mqtt.NewClient(opts)
  69. tperiod := time.Now().Add(10 * time.Second)
  70. for {
  71. if token := client.Connect(); token.Wait() && token.Error() != nil {
  72. logger.Log(2, "unable to connect to broker, retrying ...")
  73. if time.Now().After(tperiod) {
  74. log.Fatal(0, "could not connect to broker, exiting ...", token.Error())
  75. }
  76. } else {
  77. break
  78. }
  79. time.Sleep(2 * time.Second)
  80. }
  81. return client
  82. }
  83. // MessageQueue sets up Message Queue and subsribes/publishes updates to/from server
  84. func MessageQueue(ctx context.Context, network string) {
  85. ncutils.Log("netclient go routine started for " + network)
  86. var cfg config.ClientConfig
  87. cfg.Network = network
  88. cfg.ReadConfig()
  89. ncutils.Log("daemon started for network:" + network)
  90. client := SetupMQTT(&cfg)
  91. if cfg.DebugOn {
  92. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  93. log.Fatal(token.Error())
  94. }
  95. ncutils.Log("subscribed to all topics for debugging purposes")
  96. }
  97. if token := client.Subscribe(fmt.Sprintf("update/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(NodeUpdate)); token.Wait() && token.Error() != nil {
  98. log.Fatal(token.Error())
  99. }
  100. if cfg.DebugOn {
  101. ncutils.Log(fmt.Sprintf("subscribed to node updates for node %s update/%s/%s", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
  102. }
  103. if token := client.Subscribe(fmt.Sprintf("peers/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(UpdatePeers)); token.Wait() && token.Error() != nil {
  104. log.Fatal(token.Error())
  105. }
  106. if cfg.DebugOn {
  107. ncutils.Log(fmt.Sprintf("subscribed to peer updates for node %s peers/%s/%s", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
  108. }
  109. var id string
  110. for _, server := range cfg.NetworkSettings.DefaultServerAddrs {
  111. if server.IsLeader {
  112. id = server.ID
  113. }
  114. if server.Address != "" {
  115. if token := client.Subscribe("serverkeepalive/"+id, 0, mqtt.MessageHandler(ServerKeepAlive)); token.Wait() && token.Error() != nil {
  116. log.Fatal(token.Error())
  117. }
  118. if cfg.DebugOn {
  119. ncutils.Log("subscribed to server keepalives for server " + id)
  120. }
  121. } else {
  122. ncutils.Log("leader not defined for network" + cfg.Network)
  123. }
  124. }
  125. defer client.Disconnect(250)
  126. go MonitorKeepalive(ctx, client, &cfg)
  127. go Checkin(ctx, &cfg, network)
  128. <-ctx.Done()
  129. ncutils.Log("shutting down daemon")
  130. }
  131. // All -- mqtt message hander for all ('#') topics
  132. var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  133. ncutils.Log("default message handler -- received message but not handling")
  134. ncutils.Log("Topic: " + string(msg.Topic()))
  135. //ncutils.Log("Message: " + string(msg.Payload()))
  136. }
  137. // NodeUpdate -- mqtt message handler for /update/<NodeID> topic
  138. func NodeUpdate(client mqtt.Client, msg mqtt.Message) {
  139. //potentiall blocking i/o so do this in a go routine
  140. go func() {
  141. var newNode models.Node
  142. var cfg config.ClientConfig
  143. var network = parseNetworkFromTopic(msg.Topic())
  144. cfg.Network = network
  145. cfg.ReadConfig()
  146. data, dataErr := decryptMsg(&cfg, msg.Payload())
  147. if dataErr != nil {
  148. return
  149. }
  150. err := json.Unmarshal([]byte(data), &newNode)
  151. if err != nil {
  152. ncutils.Log("error unmarshalling node update data" + err.Error())
  153. return
  154. }
  155. ncutils.Log("received message to update node " + newNode.Name)
  156. // see if cache hit, if so skip
  157. var currentMessage = read(newNode.Network, lastNodeUpdate)
  158. if currentMessage == string(data) {
  159. return
  160. }
  161. insert(newNode.Network, lastNodeUpdate, string(data))
  162. //check if interface name has changed if so delete.
  163. if cfg.Node.Interface != newNode.Interface {
  164. if err = wireguard.RemoveConf(cfg.Node.Interface, true); err != nil {
  165. ncutils.PrintLog("could not delete old interface "+cfg.Node.Interface+": "+err.Error(), 1)
  166. }
  167. }
  168. newNode.PullChanges = "no"
  169. //ensure that OS never changes
  170. newNode.OS = runtime.GOOS
  171. cfg.Node = newNode
  172. switch newNode.Action {
  173. case models.NODE_DELETE:
  174. if err := RemoveLocalInstance(&cfg, cfg.Network); err != nil {
  175. ncutils.PrintLog("error deleting local instance: "+err.Error(), 1)
  176. return
  177. }
  178. if token := client.Unsubscribe("update/"+newNode.ID, "update/peers/"+newNode.ID); token.Wait() && token.Error() != nil {
  179. ncutils.PrintLog("error unsubscribing during node deletion", 1)
  180. }
  181. return
  182. case models.NODE_UPDATE_KEY:
  183. if err := UpdateKeys(&cfg, client); err != nil {
  184. ncutils.PrintLog("err updating wireguard keys: "+err.Error(), 1)
  185. }
  186. case models.NODE_NOOP:
  187. default:
  188. }
  189. //Save new config
  190. if err := config.Write(&cfg, cfg.Network); err != nil {
  191. ncutils.PrintLog("error updating node configuration: "+err.Error(), 1)
  192. }
  193. nameserver := cfg.Server.CoreDNSAddr
  194. privateKey, err := wireguard.RetrievePrivKey(newNode.Network)
  195. if err != nil {
  196. ncutils.Log("error reading PrivateKey " + err.Error())
  197. return
  198. }
  199. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  200. if err := wireguard.UpdateWgInterface(file, privateKey, nameserver, newNode); err != nil {
  201. ncutils.Log("error updating wireguard config " + err.Error())
  202. return
  203. }
  204. ncutils.Log("applyWGQuickConf to " + file)
  205. err = wireguard.ApplyWGQuickConf(file)
  206. if err != nil {
  207. ncutils.Log("error restarting wg after node update " + err.Error())
  208. return
  209. }
  210. //deal with DNS
  211. if newNode.DNSOn == "yes" {
  212. ncutils.Log("setting up DNS")
  213. if err = local.UpdateDNS(cfg.Node.Interface, cfg.Network, cfg.Server.CoreDNSAddr); err != nil {
  214. ncutils.Log("error applying dns" + err.Error())
  215. }
  216. } else {
  217. ncutils.Log("settng DNS off")
  218. _, err := ncutils.RunCmd("/usr/bin/resolvectl revert "+cfg.Node.Interface, true)
  219. if err != nil {
  220. ncutils.Log("error applying dns" + err.Error())
  221. }
  222. }
  223. }()
  224. }
  225. // UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
  226. func UpdatePeers(client mqtt.Client, msg mqtt.Message) {
  227. go func() {
  228. var peerUpdate models.PeerUpdate
  229. var network = parseNetworkFromTopic(msg.Topic())
  230. var cfg = config.ClientConfig{}
  231. cfg.Network = network
  232. cfg.ReadConfig()
  233. data, dataErr := decryptMsg(&cfg, msg.Payload())
  234. if dataErr != nil {
  235. return
  236. }
  237. err := json.Unmarshal([]byte(data), &peerUpdate)
  238. if err != nil {
  239. ncutils.Log("error unmarshalling peer data")
  240. return
  241. }
  242. // see if cache hit, if so skip
  243. var currentMessage = read(peerUpdate.Network, lastPeerUpdate)
  244. if currentMessage == string(data) {
  245. return
  246. }
  247. insert(peerUpdate.Network, lastPeerUpdate, string(data))
  248. ncutils.Log("update peer handler")
  249. var shouldReSub = shouldResub(cfg.Node.NetworkSettings.DefaultServerAddrs, peerUpdate.ServerAddrs)
  250. if shouldReSub {
  251. Resubscribe(client, &cfg)
  252. cfg.Node.NetworkSettings.DefaultServerAddrs = peerUpdate.ServerAddrs
  253. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  254. err = wireguard.UpdateWgPeers(file, peerUpdate.Peers)
  255. if err != nil {
  256. ncutils.Log("error updating wireguard peers" + err.Error())
  257. return
  258. }
  259. ncutils.Log("applyWGQuickConf to " + file)
  260. err = wireguard.ApplyWGQuickConf(file)
  261. if err != nil {
  262. ncutils.Log("error restarting wg after peer update " + err.Error())
  263. return
  264. }
  265. }
  266. }()
  267. }
  268. // MonitorKeepalive - checks time last server keepalive received. If more than 3+ minutes, notify and resubscribe
  269. func MonitorKeepalive(ctx context.Context, client mqtt.Client, cfg *config.ClientConfig) {
  270. var id string
  271. for _, servAddr := range cfg.NetworkSettings.DefaultServerAddrs {
  272. if servAddr.IsLeader {
  273. id = servAddr.ID
  274. }
  275. }
  276. for {
  277. select {
  278. case <-ctx.Done():
  279. return
  280. case <-time.After(time.Second * 150):
  281. if time.Since(keepalive[id]) > time.Second*200 { // more than 3+ minutes
  282. ncutils.Log("server keepalive not recieved in more than minutes, resubscribe to message queue")
  283. Resubscribe(client, cfg)
  284. }
  285. }
  286. }
  287. }
  288. // ServerKeepAlive -- handler to react to keepalive messages published by server
  289. func ServerKeepAlive(client mqtt.Client, msg mqtt.Message) {
  290. serverid, err := getID(msg.Topic())
  291. if err != nil {
  292. ncutils.Log("invalid ID in serverkeepalive topic")
  293. }
  294. keepalive[serverid] = time.Now()
  295. ncutils.Log("keepalive from server")
  296. }
  297. // Resubscribe --- handles resubscribing if needed
  298. func Resubscribe(client mqtt.Client, cfg *config.ClientConfig) error {
  299. if err := config.ModConfig(&cfg.Node); err == nil {
  300. ncutils.Log("resubbing on network " + cfg.Node.Network)
  301. client.Disconnect(250)
  302. client = SetupMQTT(cfg)
  303. if token := client.Subscribe("update/"+cfg.Node.ID, 0, NodeUpdate); token.Wait() && token.Error() != nil {
  304. log.Fatal(token.Error())
  305. }
  306. if cfg.DebugOn {
  307. ncutils.Log("subscribed to node updates for node " + cfg.Node.Name + " update/" + cfg.Node.ID)
  308. }
  309. if token := client.Subscribe("update/peers/"+cfg.Node.ID, 0, UpdatePeers); token.Wait() && token.Error() != nil {
  310. log.Fatal(token.Error())
  311. }
  312. ncutils.Log("finished re subbing")
  313. return nil
  314. } else {
  315. ncutils.Log("could not mod config when re-subbing")
  316. return err
  317. }
  318. }
  319. // UpdateKeys -- updates private key and returns new publickey
  320. func UpdateKeys(cfg *config.ClientConfig, client mqtt.Client) error {
  321. ncutils.Log("received message to update keys")
  322. //potentiall blocking i/o so do this in a go routine
  323. key, err := wgtypes.GeneratePrivateKey()
  324. if err != nil {
  325. ncutils.Log("error generating privatekey " + err.Error())
  326. return err
  327. }
  328. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  329. if err := wireguard.UpdatePrivateKey(file, key.String()); err != nil {
  330. ncutils.Log("error updating wireguard key " + err.Error())
  331. return err
  332. }
  333. cfg.Node.PublicKey = key.PublicKey().String()
  334. PublishNodeUpdate(cfg)
  335. if err := config.ModConfig(&cfg.Node); err != nil {
  336. ncutils.Log("error updating local config " + err.Error())
  337. }
  338. return nil
  339. }
  340. // Checkin -- go routine that checks for public or local ip changes, publishes changes
  341. // if there are no updates, simply "pings" the server as a checkin
  342. func Checkin(ctx context.Context, cfg *config.ClientConfig, network string) {
  343. for {
  344. select {
  345. case <-ctx.Done():
  346. ncutils.Log("Checkin cancelled")
  347. return
  348. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  349. case <-time.After(time.Second * 60):
  350. ncutils.Log("Checkin running")
  351. //read latest config
  352. cfg.ReadConfig()
  353. if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
  354. extIP, err := ncutils.GetPublicIP()
  355. if err != nil {
  356. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  357. }
  358. if cfg.Node.Endpoint != extIP && extIP != "" {
  359. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
  360. cfg.Node.Endpoint = extIP
  361. PublishNodeUpdate(cfg)
  362. }
  363. intIP, err := getPrivateAddr()
  364. if err != nil {
  365. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  366. }
  367. if cfg.Node.LocalAddress != intIP && intIP != "" {
  368. ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
  369. cfg.Node.LocalAddress = intIP
  370. PublishNodeUpdate(cfg)
  371. }
  372. } else {
  373. localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
  374. if err != nil {
  375. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  376. }
  377. if cfg.Node.Endpoint != localIP && localIP != "" {
  378. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
  379. cfg.Node.Endpoint = localIP
  380. PublishNodeUpdate(cfg)
  381. }
  382. }
  383. Hello(cfg, network)
  384. ncutils.Log("Checkin complete")
  385. }
  386. }
  387. }
  388. // PublishNodeUpdates -- saves node and pushes changes to broker
  389. func PublishNodeUpdate(cfg *config.ClientConfig) {
  390. if err := config.Write(cfg, cfg.Network); err != nil {
  391. ncutils.Log("error saving configuration" + err.Error())
  392. }
  393. data, err := json.Marshal(cfg.Node)
  394. if err != nil {
  395. ncutils.Log("error marshling node update " + err.Error())
  396. }
  397. if err = publish(cfg, fmt.Sprintf("update/%s", cfg.Node.ID), data); err != nil {
  398. ncutils.Log(fmt.Sprintf("error publishing endpoint update, %v", err))
  399. }
  400. }
  401. // Hello -- ping the broker to let server know node is alive and doing fine
  402. func Hello(cfg *config.ClientConfig, network string) {
  403. if err := publish(cfg, fmt.Sprintf("ping/%s", cfg.Node.ID), []byte("hello world!")); err != nil {
  404. ncutils.Log(fmt.Sprintf("error publishing ping, %v", err))
  405. }
  406. }
  407. func publish(cfg *config.ClientConfig, dest string, msg []byte) error {
  408. // setup the keys
  409. trafficPrivKey, err := auth.RetrieveTrafficKey(cfg.Node.Network)
  410. if err != nil {
  411. return err
  412. }
  413. serverPubKey, err := ncutils.ConvertBytesToKey(cfg.Node.TrafficKeys.Server)
  414. if err != nil {
  415. return err
  416. }
  417. client := SetupMQTT(cfg)
  418. defer client.Disconnect(250)
  419. encrypted, err := ncutils.BoxEncrypt(msg, serverPubKey, trafficPrivKey)
  420. if err != nil {
  421. return err
  422. }
  423. if token := client.Publish(dest, 0, false, encrypted); token.Wait() && token.Error() != nil {
  424. return token.Error()
  425. }
  426. return nil
  427. }
  428. func parseNetworkFromTopic(topic string) string {
  429. return strings.Split(topic, "/")[1]
  430. }
  431. func decryptMsg(cfg *config.ClientConfig, msg []byte) ([]byte, error) {
  432. // setup the keys
  433. diskKey, keyErr := auth.RetrieveTrafficKey(cfg.Node.Network)
  434. if keyErr != nil {
  435. return nil, keyErr
  436. }
  437. serverPubKey, err := ncutils.ConvertBytesToKey(cfg.Node.TrafficKeys.Server)
  438. if err != nil {
  439. return nil, err
  440. }
  441. return ncutils.BoxDecrypt(msg, serverPubKey, diskKey)
  442. }
  443. func shouldResub(currentServers, newServers []models.ServerAddr) bool {
  444. if len(currentServers) != len(newServers) {
  445. return true
  446. }
  447. for _, srv := range currentServers {
  448. if !ncutils.ServerAddrSliceContains(newServers, srv) {
  449. return true
  450. }
  451. }
  452. return false
  453. }
  454. func getID(topic string) (string, error) {
  455. parts := strings.Split(topic, "/")
  456. count := len(parts)
  457. if count == 1 {
  458. return "", errors.New("invalid topic")
  459. }
  460. //the last part of the topic will be the network.ID
  461. return parts[count-1], nil
  462. }