daemon.go 11 KB

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