daemon.go 18 KB

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