daemon.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package functions
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "os/signal"
  8. "strings"
  9. "sync"
  10. "syscall"
  11. "time"
  12. mqtt "github.com/eclipse/paho.mqtt.golang"
  13. "github.com/go-ping/ping"
  14. "github.com/gravitl/netmaker/models"
  15. "github.com/gravitl/netmaker/netclient/auth"
  16. "github.com/gravitl/netmaker/netclient/config"
  17. "github.com/gravitl/netmaker/netclient/daemon"
  18. "github.com/gravitl/netmaker/netclient/ncutils"
  19. "github.com/gravitl/netmaker/netclient/wireguard"
  20. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  21. )
  22. var messageCache = new(sync.Map)
  23. var networkcontext = new(sync.Map)
  24. const lastNodeUpdate = "lnu"
  25. const lastPeerUpdate = "lpu"
  26. type cachedMessage struct {
  27. Message string
  28. LastSeen time.Time
  29. }
  30. // Daemon runs netclient daemon from command line
  31. func Daemon() error {
  32. // == initial pull of all networks ==
  33. networks, _ := ncutils.GetSystemNetworks()
  34. for _, network := range networks {
  35. var cfg config.ClientConfig
  36. cfg.Network = network
  37. cfg.ReadConfig()
  38. initialPull(cfg.Network)
  39. }
  40. // == get all the comms networks on machine ==
  41. commsNetworks, err := getCommsNetworks(networks[:])
  42. if err != nil {
  43. return errors.New("no comm networks exist")
  44. }
  45. // == subscribe to all nodes on each comms network on machine ==
  46. for currCommsNet := range commsNetworks {
  47. ncutils.PrintLog("started comms network daemon, "+currCommsNet, 1)
  48. ctx, cancel := context.WithCancel(context.Background())
  49. networkcontext.Store(currCommsNet, cancel)
  50. go messageQueue(ctx, currCommsNet)
  51. }
  52. // == add waitgroup and cancel for checkin routine ==
  53. wg := sync.WaitGroup{}
  54. ctx, cancel := context.WithCancel(context.Background())
  55. wg.Add(1)
  56. go Checkin(ctx, &wg, commsNetworks)
  57. quit := make(chan os.Signal, 1)
  58. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  59. <-quit
  60. for currCommsNet := range commsNetworks {
  61. if cancel, ok := networkcontext.Load(currCommsNet); ok {
  62. cancel.(context.CancelFunc)()
  63. }
  64. }
  65. cancel()
  66. ncutils.Log("shutting down netclient daemon")
  67. wg.Wait()
  68. ncutils.Log("shutdown complete")
  69. return nil
  70. }
  71. // UpdateKeys -- updates private key and returns new publickey
  72. func UpdateKeys(nodeCfg *config.ClientConfig, client mqtt.Client) error {
  73. ncutils.Log("received message to update keys")
  74. key, err := wgtypes.GeneratePrivateKey()
  75. if err != nil {
  76. ncutils.Log("error generating privatekey " + err.Error())
  77. return err
  78. }
  79. file := ncutils.GetNetclientPathSpecific() + nodeCfg.Node.Interface + ".conf"
  80. if err := wireguard.UpdatePrivateKey(file, key.String()); err != nil {
  81. ncutils.Log("error updating wireguard key " + err.Error())
  82. return err
  83. }
  84. nodeCfg.Node.PublicKey = key.PublicKey().String()
  85. if err := config.ModConfig(&nodeCfg.Node); err != nil {
  86. ncutils.Log("error updating local config " + err.Error())
  87. }
  88. var commsCfg = getCommsCfgByNode(&nodeCfg.Node)
  89. PublishNodeUpdate(&commsCfg, nodeCfg)
  90. if err = wireguard.ApplyConf(&nodeCfg.Node, nodeCfg.Node.Interface, file); err != nil {
  91. ncutils.Log("error applying new config " + err.Error())
  92. return err
  93. }
  94. return nil
  95. }
  96. // PingServer -- checks if server is reachable
  97. // use commsCfg only*
  98. func PingServer(commsCfg *config.ClientConfig) error {
  99. node := getServerAddress(commsCfg)
  100. pinger, err := ping.NewPinger(node)
  101. if err != nil {
  102. return err
  103. }
  104. pinger.Timeout = 2 * time.Second
  105. pinger.Run()
  106. stats := pinger.Statistics()
  107. if stats.PacketLoss == 100 {
  108. return errors.New("ping error")
  109. }
  110. return nil
  111. }
  112. // == Private ==
  113. // sets MQ client subscriptions for a specific node config
  114. // should be called for each node belonging to a given comms network
  115. func setSubscriptions(client mqtt.Client, nodeCfg *config.ClientConfig) {
  116. if nodeCfg.DebugOn {
  117. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  118. ncutils.Log(token.Error().Error())
  119. return
  120. }
  121. ncutils.Log("subscribed to all topics for debugging purposes")
  122. }
  123. if token := client.Subscribe(fmt.Sprintf("update/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID), 0, mqtt.MessageHandler(NodeUpdate)); token.Wait() && token.Error() != nil {
  124. ncutils.Log(token.Error().Error())
  125. return
  126. }
  127. if nodeCfg.DebugOn {
  128. ncutils.Log(fmt.Sprintf("subscribed to node updates for node %s update/%s/%s", nodeCfg.Node.Name, nodeCfg.Node.Network, nodeCfg.Node.ID))
  129. }
  130. if token := client.Subscribe(fmt.Sprintf("peers/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID), 0, mqtt.MessageHandler(UpdatePeers)); token.Wait() && token.Error() != nil {
  131. ncutils.Log(token.Error().Error())
  132. return
  133. }
  134. if nodeCfg.DebugOn {
  135. ncutils.Log(fmt.Sprintf("subscribed to peer updates for node %s peers/%s/%s", nodeCfg.Node.Name, nodeCfg.Node.Network, nodeCfg.Node.ID))
  136. }
  137. }
  138. // on a delete usually, pass in the nodecfg to unsubscribe client broker communications
  139. // for the node in nodeCfg
  140. func unsubscribeNode(client mqtt.Client, nodeCfg *config.ClientConfig) {
  141. client.Unsubscribe(fmt.Sprintf("update/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID))
  142. var ok = true
  143. if token := client.Unsubscribe(fmt.Sprintf("update/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID)); token.Wait() && token.Error() != nil {
  144. ncutils.PrintLog("unable to unsubscribe from updates for node "+nodeCfg.Node.Name+"\n"+token.Error().Error(), 1)
  145. ok = false
  146. }
  147. if token := client.Unsubscribe(fmt.Sprintf("peers/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID)); token.Wait() && token.Error() != nil {
  148. ncutils.PrintLog("unable to unsubscribe from peer updates for node "+nodeCfg.Node.Name+"\n"+token.Error().Error(), 1)
  149. ok = false
  150. }
  151. if ok {
  152. ncutils.PrintLog("successfully unsubscribed node "+nodeCfg.Node.ID+" : "+nodeCfg.Node.Name, 0)
  153. }
  154. }
  155. // sets up Message Queue and subsribes/publishes updates to/from server
  156. // the client should subscribe to ALL nodes that exist on unique comms network locally
  157. func messageQueue(ctx context.Context, commsNet string) {
  158. var commsCfg config.ClientConfig
  159. commsCfg.Network = commsNet
  160. commsCfg.ReadConfig()
  161. ncutils.Log("netclient daemon started for network: " + commsNet)
  162. client := setupMQTT(&commsCfg, false)
  163. defer client.Disconnect(250)
  164. <-ctx.Done()
  165. ncutils.Log("shutting down daemon for comms network " + commsNet)
  166. }
  167. // setupMQTT creates a connection to broker and return client
  168. // utilizes comms client configs to setup connections
  169. func setupMQTT(commsCfg *config.ClientConfig, publish bool) mqtt.Client {
  170. opts := mqtt.NewClientOptions()
  171. server := getServerAddress(commsCfg)
  172. opts.AddBroker(server + ":1883") // TODO get the appropriate port of the comms mq server
  173. opts.ClientID = ncutils.MakeRandomString(23) // helps avoid id duplication on broker
  174. opts.SetDefaultPublishHandler(All)
  175. opts.SetAutoReconnect(true)
  176. opts.SetConnectRetry(true)
  177. opts.SetConnectRetryInterval(time.Second << 2)
  178. opts.SetKeepAlive(time.Minute >> 1)
  179. opts.SetWriteTimeout(time.Minute)
  180. opts.SetOnConnectHandler(func(client mqtt.Client) {
  181. if !publish {
  182. networks, err := ncutils.GetSystemNetworks()
  183. if err != nil {
  184. ncutils.Log("error retriving networks " + err.Error())
  185. }
  186. for _, network := range networks {
  187. var currNodeCfg config.ClientConfig
  188. currNodeCfg.Network = network
  189. currNodeCfg.ReadConfig()
  190. setSubscriptions(client, &currNodeCfg)
  191. }
  192. }
  193. })
  194. opts.SetOrderMatters(true)
  195. opts.SetResumeSubs(true)
  196. opts.SetConnectionLostHandler(func(c mqtt.Client, e error) {
  197. ncutils.Log("detected broker connection lost, running pull for " + commsCfg.Node.Network)
  198. _, err := Pull(commsCfg.Node.Network, true)
  199. if err != nil {
  200. ncutils.Log("could not run pull, server unreachable: " + err.Error())
  201. ncutils.Log("waiting to retry...")
  202. }
  203. ncutils.Log("connection re-established with mqtt server")
  204. })
  205. client := mqtt.NewClient(opts)
  206. tperiod := time.Now().Add(12 * time.Second)
  207. for {
  208. //if after 12 seconds, try a gRPC pull on the last try
  209. if time.Now().After(tperiod) {
  210. ncutils.Log("running pull for " + commsCfg.Node.Network)
  211. _, err := Pull(commsCfg.Node.Network, true)
  212. if err != nil {
  213. ncutils.Log("could not run pull, exiting " + commsCfg.Node.Network + " setup: " + err.Error())
  214. return client
  215. }
  216. time.Sleep(time.Second)
  217. }
  218. if token := client.Connect(); token.Wait() && token.Error() != nil {
  219. ncutils.Log("unable to connect to broker, retrying ...")
  220. if time.Now().After(tperiod) {
  221. ncutils.Log("could not connect to broker, exiting " + commsCfg.Node.Network + " setup: " + token.Error().Error())
  222. if strings.Contains(token.Error().Error(), "connectex") || strings.Contains(token.Error().Error(), "i/o timeout") {
  223. ncutils.PrintLog("connection issue detected.. pulling and restarting daemon", 0)
  224. Pull(commsCfg.Node.Network, true)
  225. daemon.Restart()
  226. }
  227. return client
  228. }
  229. } else {
  230. break
  231. }
  232. time.Sleep(2 * time.Second)
  233. }
  234. return client
  235. }
  236. // publishes a message to server to update peers on this peer's behalf
  237. func publishSignal(commsCfg, nodeCfg *config.ClientConfig, signal byte) error {
  238. if err := publish(commsCfg, nodeCfg, fmt.Sprintf("signal/%s", nodeCfg.Node.ID), []byte{signal}, 1); err != nil {
  239. return err
  240. }
  241. return nil
  242. }
  243. func initialPull(network string) {
  244. ncutils.Log("pulling latest config for " + network)
  245. var configPath = fmt.Sprintf("%snetconfig-%s", ncutils.GetNetclientPathSpecific(), network)
  246. fileInfo, err := os.Stat(configPath)
  247. if err != nil {
  248. ncutils.Log("could not stat config file: " + configPath)
  249. return
  250. }
  251. // speed up UDP rest
  252. if !fileInfo.ModTime().IsZero() && time.Now().After(fileInfo.ModTime().Add(time.Minute)) {
  253. sleepTime := 2
  254. for {
  255. _, err := Pull(network, true)
  256. if err == nil {
  257. break
  258. }
  259. if sleepTime > 3600 {
  260. sleepTime = 3600
  261. }
  262. ncutils.Log("failed to pull for network " + network)
  263. ncutils.Log(fmt.Sprintf("waiting %d seconds to retry...", sleepTime))
  264. time.Sleep(time.Second * time.Duration(sleepTime))
  265. sleepTime = sleepTime * 2
  266. }
  267. time.Sleep(time.Second << 1)
  268. }
  269. }
  270. func parseNetworkFromTopic(topic string) string {
  271. return strings.Split(topic, "/")[1]
  272. }
  273. // should only ever use node client configs
  274. func decryptMsg(nodeCfg *config.ClientConfig, msg []byte) ([]byte, error) {
  275. if len(msg) <= 24 { // make sure message is of appropriate length
  276. return nil, fmt.Errorf("recieved invalid message from broker %v", msg)
  277. }
  278. // setup the keys
  279. diskKey, keyErr := auth.RetrieveTrafficKey(nodeCfg.Node.Network)
  280. if keyErr != nil {
  281. return nil, keyErr
  282. }
  283. serverPubKey, err := ncutils.ConvertBytesToKey(nodeCfg.Node.TrafficKeys.Server)
  284. if err != nil {
  285. return nil, err
  286. }
  287. return ncutils.DeChunk(msg, serverPubKey, diskKey)
  288. }
  289. func getServerAddress(cfg *config.ClientConfig) string {
  290. var server models.ServerAddr
  291. for _, server = range cfg.Node.NetworkSettings.DefaultServerAddrs {
  292. if server.Address != "" && server.IsLeader {
  293. break
  294. }
  295. }
  296. return server.Address
  297. }
  298. func getCommsNetworks(networks []string) (map[string]bool, error) {
  299. var cfg config.ClientConfig
  300. var response = make(map[string]bool, 1)
  301. for _, network := range networks {
  302. cfg.Network = network
  303. cfg.ReadConfig()
  304. response[cfg.Node.CommID] = true
  305. }
  306. return response, nil
  307. }
  308. func getCommsCfgByNode(node *models.Node) config.ClientConfig {
  309. var commsCfg config.ClientConfig
  310. commsCfg.Network = node.Network
  311. commsCfg.ReadConfig()
  312. return commsCfg
  313. }
  314. // == Message Caches ==
  315. func insert(network, which, cache string) {
  316. var newMessage = cachedMessage{
  317. Message: cache,
  318. LastSeen: time.Now(),
  319. }
  320. messageCache.Store(fmt.Sprintf("%s%s", network, which), newMessage)
  321. }
  322. func read(network, which string) string {
  323. val, isok := messageCache.Load(fmt.Sprintf("%s%s", network, which))
  324. if isok {
  325. var readMessage = val.(cachedMessage) // fetch current cached message
  326. if readMessage.LastSeen.IsZero() {
  327. return ""
  328. }
  329. if time.Now().After(readMessage.LastSeen.Add(time.Minute * 10)) { // check if message has been there over a minute
  330. messageCache.Delete(fmt.Sprintf("%s%s", network, which)) // remove old message if expired
  331. return ""
  332. }
  333. return readMessage.Message // return current message if not expired
  334. }
  335. return ""
  336. }
  337. // == End Message Caches ==