daemon.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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, os.Kill)
  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 wireguard keys for network " + nodeCfg.Network)
  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. if storeErr := wireguard.StorePrivKey(key.String(), nodeCfg.Network); storeErr != nil {
  85. ncutils.Log("failed to save private key" + storeErr.Error())
  86. return storeErr
  87. }
  88. nodeCfg.Node.PublicKey = key.PublicKey().String()
  89. var commsCfg = getCommsCfgByNode(&nodeCfg.Node)
  90. PublishNodeUpdate(&commsCfg, nodeCfg)
  91. return nil
  92. }
  93. // PingServer -- checks if server is reachable
  94. // use commsCfg only*
  95. func PingServer(commsCfg *config.ClientConfig) error {
  96. node := getServerAddress(commsCfg)
  97. pinger, err := ping.NewPinger(node)
  98. if err != nil {
  99. return err
  100. }
  101. pinger.Timeout = 2 * time.Second
  102. pinger.Run()
  103. stats := pinger.Statistics()
  104. if stats.PacketLoss == 100 {
  105. return errors.New("ping error")
  106. }
  107. return nil
  108. }
  109. // == Private ==
  110. // sets MQ client subscriptions for a specific node config
  111. // should be called for each node belonging to a given comms network
  112. func setSubscriptions(client mqtt.Client, nodeCfg *config.ClientConfig) {
  113. if nodeCfg.DebugOn {
  114. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  115. ncutils.Log(token.Error().Error())
  116. return
  117. }
  118. ncutils.Log("subscribed to all topics for debugging purposes")
  119. }
  120. if token := client.Subscribe(fmt.Sprintf("update/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID), 0, mqtt.MessageHandler(NodeUpdate)); token.Wait() && token.Error() != nil {
  121. ncutils.Log(token.Error().Error())
  122. return
  123. }
  124. if nodeCfg.DebugOn {
  125. ncutils.Log(fmt.Sprintf("subscribed to node updates for node %s update/%s/%s", nodeCfg.Node.Name, nodeCfg.Node.Network, nodeCfg.Node.ID))
  126. }
  127. if token := client.Subscribe(fmt.Sprintf("peers/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID), 0, mqtt.MessageHandler(UpdatePeers)); token.Wait() && token.Error() != nil {
  128. ncutils.Log(token.Error().Error())
  129. return
  130. }
  131. if nodeCfg.DebugOn {
  132. ncutils.Log(fmt.Sprintf("subscribed to peer updates for node %s peers/%s/%s", nodeCfg.Node.Name, nodeCfg.Node.Network, nodeCfg.Node.ID))
  133. }
  134. }
  135. // on a delete usually, pass in the nodecfg to unsubscribe client broker communications
  136. // for the node in nodeCfg
  137. func unsubscribeNode(client mqtt.Client, nodeCfg *config.ClientConfig) {
  138. client.Unsubscribe(fmt.Sprintf("update/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID))
  139. var ok = true
  140. if token := client.Unsubscribe(fmt.Sprintf("update/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID)); token.Wait() && token.Error() != nil {
  141. ncutils.PrintLog("unable to unsubscribe from updates for node "+nodeCfg.Node.Name+"\n"+token.Error().Error(), 1)
  142. ok = false
  143. }
  144. if token := client.Unsubscribe(fmt.Sprintf("peers/%s/%s", nodeCfg.Node.Network, nodeCfg.Node.ID)); token.Wait() && token.Error() != nil {
  145. ncutils.PrintLog("unable to unsubscribe from peer updates for node "+nodeCfg.Node.Name+"\n"+token.Error().Error(), 1)
  146. ok = false
  147. }
  148. if ok {
  149. ncutils.PrintLog("successfully unsubscribed node "+nodeCfg.Node.ID+" : "+nodeCfg.Node.Name, 0)
  150. }
  151. }
  152. // sets up Message Queue and subsribes/publishes updates to/from server
  153. // the client should subscribe to ALL nodes that exist on unique comms network locally
  154. func messageQueue(ctx context.Context, commsNet string) {
  155. var commsCfg config.ClientConfig
  156. commsCfg.Network = commsNet
  157. commsCfg.ReadConfig()
  158. ncutils.Log("netclient daemon started for network: " + commsNet)
  159. client := setupMQTT(&commsCfg, false)
  160. defer client.Disconnect(250)
  161. <-ctx.Done()
  162. ncutils.Log("shutting down daemon for comms network " + commsNet)
  163. }
  164. // setupMQTT creates a connection to broker and return client
  165. // utilizes comms client configs to setup connections
  166. func setupMQTT(commsCfg *config.ClientConfig, publish bool) mqtt.Client {
  167. opts := mqtt.NewClientOptions()
  168. server := getServerAddress(commsCfg)
  169. opts.AddBroker(server + ":1883") // TODO get the appropriate port of the comms mq server
  170. opts.ClientID = ncutils.MakeRandomString(23) // helps avoid id duplication on broker
  171. opts.SetDefaultPublishHandler(All)
  172. opts.SetAutoReconnect(true)
  173. opts.SetConnectRetry(true)
  174. opts.SetConnectRetryInterval(time.Second << 2)
  175. opts.SetKeepAlive(time.Minute >> 1)
  176. opts.SetWriteTimeout(time.Minute)
  177. opts.SetOnConnectHandler(func(client mqtt.Client) {
  178. if !publish {
  179. networks, err := ncutils.GetSystemNetworks()
  180. if err != nil {
  181. ncutils.Log("error retriving networks " + err.Error())
  182. }
  183. for _, network := range networks {
  184. var currNodeCfg config.ClientConfig
  185. currNodeCfg.Network = network
  186. currNodeCfg.ReadConfig()
  187. setSubscriptions(client, &currNodeCfg)
  188. }
  189. }
  190. })
  191. opts.SetOrderMatters(true)
  192. opts.SetResumeSubs(true)
  193. opts.SetConnectionLostHandler(func(c mqtt.Client, e error) {
  194. ncutils.Log("detected broker connection lost, running pull for " + commsCfg.Node.Network)
  195. _, err := Pull(commsCfg.Node.Network, true)
  196. if err != nil {
  197. ncutils.Log("could not run pull, server unreachable: " + err.Error())
  198. ncutils.Log("waiting to retry...")
  199. }
  200. ncutils.Log("connection re-established with mqtt server")
  201. })
  202. client := mqtt.NewClient(opts)
  203. tperiod := time.Now().Add(12 * time.Second)
  204. for {
  205. //if after 12 seconds, try a gRPC pull on the last try
  206. if time.Now().After(tperiod) {
  207. ncutils.Log("running pull for " + commsCfg.Node.Network)
  208. _, err := Pull(commsCfg.Node.Network, true)
  209. if err != nil {
  210. ncutils.Log("could not run pull, exiting " + commsCfg.Node.Network + " setup: " + err.Error())
  211. return client
  212. }
  213. time.Sleep(time.Second)
  214. }
  215. if token := client.Connect(); token.Wait() && token.Error() != nil {
  216. ncutils.Log("unable to connect to broker, retrying ...")
  217. if time.Now().After(tperiod) {
  218. ncutils.Log("could not connect to broker, exiting " + commsCfg.Node.Network + " setup: " + token.Error().Error())
  219. if strings.Contains(token.Error().Error(), "connectex") || strings.Contains(token.Error().Error(), "i/o timeout") {
  220. ncutils.PrintLog("connection issue detected.. pulling and restarting daemon", 0)
  221. Pull(commsCfg.Node.Network, true)
  222. daemon.Restart()
  223. }
  224. return client
  225. }
  226. } else {
  227. break
  228. }
  229. time.Sleep(2 * time.Second)
  230. }
  231. return client
  232. }
  233. // publishes a message to server to update peers on this peer's behalf
  234. func publishSignal(commsCfg, nodeCfg *config.ClientConfig, signal byte) error {
  235. if err := publish(commsCfg, nodeCfg, fmt.Sprintf("signal/%s", nodeCfg.Node.ID), []byte{signal}, 1); err != nil {
  236. return err
  237. }
  238. return nil
  239. }
  240. func initialPull(network string) {
  241. ncutils.Log("pulling latest config for " + network)
  242. var configPath = fmt.Sprintf("%snetconfig-%s", ncutils.GetNetclientPathSpecific(), network)
  243. fileInfo, err := os.Stat(configPath)
  244. if err != nil {
  245. ncutils.Log("could not stat config file: " + configPath)
  246. return
  247. }
  248. // speed up UDP rest
  249. if !fileInfo.ModTime().IsZero() && time.Now().After(fileInfo.ModTime().Add(time.Minute)) {
  250. sleepTime := 2
  251. for {
  252. _, err := Pull(network, true)
  253. if err == nil {
  254. break
  255. }
  256. if sleepTime > 3600 {
  257. sleepTime = 3600
  258. }
  259. ncutils.Log("failed to pull for network " + network)
  260. ncutils.Log(fmt.Sprintf("waiting %d seconds to retry...", sleepTime))
  261. time.Sleep(time.Second * time.Duration(sleepTime))
  262. sleepTime = sleepTime * 2
  263. }
  264. time.Sleep(time.Second << 1)
  265. }
  266. }
  267. func parseNetworkFromTopic(topic string) string {
  268. return strings.Split(topic, "/")[1]
  269. }
  270. // should only ever use node client configs
  271. func decryptMsg(nodeCfg *config.ClientConfig, msg []byte) ([]byte, error) {
  272. if len(msg) <= 24 { // make sure message is of appropriate length
  273. return nil, fmt.Errorf("recieved invalid message from broker %v", msg)
  274. }
  275. // setup the keys
  276. diskKey, keyErr := auth.RetrieveTrafficKey(nodeCfg.Node.Network)
  277. if keyErr != nil {
  278. return nil, keyErr
  279. }
  280. serverPubKey, err := ncutils.ConvertBytesToKey(nodeCfg.Node.TrafficKeys.Server)
  281. if err != nil {
  282. return nil, err
  283. }
  284. return ncutils.DeChunk(msg, serverPubKey, diskKey)
  285. }
  286. func getServerAddress(cfg *config.ClientConfig) string {
  287. var server models.ServerAddr
  288. for _, server = range cfg.Node.NetworkSettings.DefaultServerAddrs {
  289. if server.Address != "" && server.IsLeader {
  290. break
  291. }
  292. }
  293. return server.Address
  294. }
  295. func getCommsNetworks(networks []string) (map[string]bool, error) {
  296. var cfg config.ClientConfig
  297. var response = make(map[string]bool, 1)
  298. for _, network := range networks {
  299. cfg.Network = network
  300. cfg.ReadConfig()
  301. response[cfg.Node.CommID] = true
  302. }
  303. return response, nil
  304. }
  305. func getCommsCfgByNode(node *models.Node) config.ClientConfig {
  306. var commsCfg config.ClientConfig
  307. commsCfg.Network = node.CommID
  308. commsCfg.ReadConfig()
  309. return commsCfg
  310. }
  311. // == Message Caches ==
  312. func insert(network, which, cache string) {
  313. var newMessage = cachedMessage{
  314. Message: cache,
  315. LastSeen: time.Now(),
  316. }
  317. messageCache.Store(fmt.Sprintf("%s%s", network, which), newMessage)
  318. }
  319. func read(network, which string) string {
  320. val, isok := messageCache.Load(fmt.Sprintf("%s%s", network, which))
  321. if isok {
  322. var readMessage = val.(cachedMessage) // fetch current cached message
  323. if readMessage.LastSeen.IsZero() {
  324. return ""
  325. }
  326. if time.Now().After(readMessage.LastSeen.Add(time.Minute * 10)) { // check if message has been there over a minute
  327. messageCache.Delete(fmt.Sprintf("%s%s", network, which)) // remove old message if expired
  328. return ""
  329. }
  330. return readMessage.Message // return current message if not expired
  331. }
  332. return ""
  333. }
  334. // == End Message Caches ==