daemon.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package functions
  2. import (
  3. "context"
  4. "encoding/json"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "runtime"
  9. "syscall"
  10. "time"
  11. mqtt "github.com/eclipse/paho.mqtt.golang"
  12. "github.com/gravitl/netmaker/models"
  13. "github.com/gravitl/netmaker/netclient/config"
  14. "github.com/gravitl/netmaker/netclient/ncutils"
  15. "github.com/gravitl/netmaker/netclient/wireguard"
  16. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  17. )
  18. // Daemon runs netclient daemon from command line
  19. func Daemon() error {
  20. ctx, cancel := context.WithCancel(context.Background())
  21. networks, err := ncutils.GetSystemNetworks()
  22. if err != nil {
  23. cancel()
  24. return err
  25. }
  26. for _, network := range networks {
  27. go MessageQueue(ctx, network)
  28. }
  29. quit := make(chan os.Signal, 1)
  30. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  31. <-quit
  32. cancel()
  33. ncutils.Log("all done")
  34. return nil
  35. }
  36. // SetupMQTT creates a connection to broker and return client
  37. func SetupMQTT(cfg config.ClientConfig) mqtt.Client {
  38. opts := mqtt.NewClientOptions()
  39. ncutils.Log("setting broker to " + cfg.Server.CoreDNSAddr + ":1883")
  40. opts.AddBroker(cfg.Server.CoreDNSAddr + ":1883")
  41. opts.SetDefaultPublishHandler(All)
  42. client := mqtt.NewClient(opts)
  43. if token := client.Connect(); token.Wait() && token.Error() != nil {
  44. log.Fatal(token.Error())
  45. }
  46. return client
  47. }
  48. // MessageQueue sets up Message Queue and subsribes/publishes updates to/from server
  49. func MessageQueue(ctx context.Context, network string) {
  50. ncutils.Log("netclient go routine started for " + network)
  51. var cfg config.ClientConfig
  52. cfg.Network = network
  53. cfg.ReadConfig()
  54. ncutils.Log("daemon started for network:" + network)
  55. client := SetupMQTT(cfg)
  56. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  57. log.Fatal(token.Error())
  58. }
  59. client.AddRoute("update/"+cfg.Node.ID, NodeUpdate)
  60. client.AddRoute("update/peers/"+cfg.Node.ID, UpdatePeers)
  61. //handle key updates in node update
  62. //client.AddRoute("update/keys/"+cfg.Node.ID, UpdateKeys)
  63. defer client.Disconnect(250)
  64. go Checkin(ctx, cfg, network)
  65. <-ctx.Done()
  66. ncutils.Log("shutting down daemon")
  67. }
  68. // All -- mqtt message hander for all ('#') topics
  69. var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  70. ncutils.Log("Topic: " + string(msg.Topic()))
  71. ncutils.Log("Message: " + string(msg.Payload()))
  72. }
  73. // NodeUpdate -- mqtt message handler for /update/<NodeID> topic
  74. var NodeUpdate mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  75. ncutils.Log("received message to update node " + string(msg.Payload()))
  76. //potentiall blocking i/o so do this in a go routine
  77. go func() {
  78. var newNode models.Node
  79. var cfg config.ClientConfig
  80. cfg.Network = newNode.Network
  81. cfg.ReadConfig()
  82. err := json.Unmarshal(msg.Payload(), &newNode)
  83. if err != nil {
  84. ncutils.Log("error unmarshalling node update data" + err.Error())
  85. return
  86. }
  87. //check if interface name has changed if so delete.
  88. if cfg.Node.Interface != newNode.Interface {
  89. if err = wireguard.RemoveConf(cfg.Node.Interface, true); err != nil {
  90. ncutils.PrintLog("could not delete old interface "+cfg.Node.Interface+": "+err.Error(), 1)
  91. }
  92. }
  93. newNode.PullChanges = "no"
  94. //ensure that OS never changes
  95. newNode.OS = runtime.GOOS
  96. cfg.Node = newNode
  97. switch newNode.Action {
  98. case models.NODE_DELETE:
  99. if err := RemoveLocalInstance(&cfg, cfg.Network); err != nil {
  100. ncutils.PrintLog("error deleting local instance: "+err.Error(), 1)
  101. return
  102. }
  103. case models.NODE_UPDATE_KEY:
  104. UpdateKeys(&cfg, client)
  105. case models.NODE_NOOP:
  106. default:
  107. }
  108. //Save new config
  109. if err := config.Write(&cfg, cfg.Network); err != nil {
  110. ncutils.PrintLog("error updating node configuration: "+err.Error(), 1)
  111. }
  112. nameserver := cfg.Server.CoreDNSAddr
  113. privateKey, err := wireguard.RetrievePrivKey(newNode.Network)
  114. if err != nil {
  115. ncutils.Log("error reading PrivateKey " + err.Error())
  116. return
  117. }
  118. if err := wireguard.UpdateWgInterface(cfg.Node.Interface, privateKey, nameserver, newNode); err != nil {
  119. ncutils.Log("error updating wireguard config " + err.Error())
  120. return
  121. }
  122. // path hardcoded for now... should be updated
  123. err = wireguard.ApplyWGQuickConf("/etc/netclient/config/" + cfg.Node.Interface + ".conf")
  124. if err != nil {
  125. ncutils.Log("error restarting wg after node update " + err.Error())
  126. return
  127. }
  128. }()
  129. }
  130. // UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
  131. var UpdatePeers mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  132. ncutils.Log("received message to update peers " + string(msg.Payload()))
  133. go func() {
  134. var peerUpdate models.PeerUpdate
  135. err := json.Unmarshal(msg.Payload(), &peerUpdate)
  136. if err != nil {
  137. ncutils.Log("error unmarshalling peer data")
  138. return
  139. }
  140. var cfg config.ClientConfig
  141. cfg.Network = peerUpdate.Network
  142. cfg.ReadConfig()
  143. err = wireguard.UpdateWgPeers(cfg.Node.Interface, peerUpdate.Peers)
  144. if err != nil {
  145. ncutils.Log("error updating wireguard peers" + err.Error())
  146. return
  147. }
  148. // path hardcoded for now... should be updated
  149. err = wireguard.ApplyWGQuickConf("/etc/netclient/config/" + cfg.Node.Interface + ".conf")
  150. if err != nil {
  151. ncutils.Log("error restarting wg after peer update " + err.Error())
  152. return
  153. }
  154. }()
  155. }
  156. // UpdateKeys -- updates private key and returns new publickey
  157. func UpdateKeys(cfg *config.ClientConfig, client mqtt.Client) (*config.ClientConfig, error) {
  158. ncutils.Log("received message to update keys")
  159. //potentiall blocking i/o so do this in a go routine
  160. key, err := wgtypes.GeneratePrivateKey()
  161. if err != nil {
  162. ncutils.Log("error generating privatekey " + err.Error())
  163. return cfg, err
  164. }
  165. if err := wireguard.UpdatePrivateKey(cfg.Node.Interface, key.String()); err != nil {
  166. ncutils.Log("error updating wireguard key " + err.Error())
  167. return cfg, err
  168. }
  169. publicKey := key.PublicKey()
  170. if token := client.Publish("update/publickey/"+cfg.Node.ID, 0, false, publicKey.String()); token.Wait() && token.Error() != nil {
  171. ncutils.Log("error publishing publickey update " + token.Error().Error())
  172. client.Disconnect(250)
  173. return cfg, err
  174. }
  175. if err := config.ModConfig(&cfg.Node); err != nil {
  176. ncutils.Log("error updating local config " + err.Error())
  177. }
  178. return cfg, nil
  179. }
  180. // Checkin -- go routine that checks for public or local ip changes, publishes changes
  181. // if there are no updates, simply "pings" the server as a checkin
  182. func Checkin(ctx context.Context, cfg config.ClientConfig, network string) {
  183. for {
  184. select {
  185. case <-ctx.Done():
  186. ncutils.Log("Checkin cancelled")
  187. return
  188. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  189. case <-time.After(time.Second * 60):
  190. ncutils.Log("Checkin running")
  191. //read latest config
  192. cfg.ReadConfig()
  193. if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
  194. extIP, err := ncutils.GetPublicIP()
  195. if err != nil {
  196. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  197. }
  198. if cfg.Node.Endpoint != extIP && extIP != "" {
  199. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
  200. UpdateEndpoint(cfg, network, extIP)
  201. }
  202. intIP, err := getPrivateAddr()
  203. if err != nil {
  204. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  205. }
  206. if cfg.Node.LocalAddress != intIP && intIP != "" {
  207. ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
  208. UpdateLocalAddress(cfg, network, intIP)
  209. }
  210. } else {
  211. localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
  212. if err != nil {
  213. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  214. }
  215. if cfg.Node.Endpoint != localIP && localIP != "" {
  216. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
  217. UpdateEndpoint(cfg, network, localIP)
  218. }
  219. }
  220. Hello(cfg, network)
  221. ncutils.Log("Checkin complete")
  222. }
  223. }
  224. }
  225. // UpdateEndpoint -- publishes an endpoint update to broker
  226. func UpdateEndpoint(cfg config.ClientConfig, network, ip string) {
  227. ncutils.Log("Updating endpoint")
  228. client := SetupMQTT(cfg)
  229. if token := client.Publish("update/ip/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
  230. ncutils.Log("error publishing endpoint update " + token.Error().Error())
  231. }
  232. cfg.Node.Endpoint = ip
  233. if err := config.Write(&cfg, cfg.Network); err != nil {
  234. ncutils.Log("error updating local config " + err.Error())
  235. }
  236. client.Disconnect(250)
  237. }
  238. // UpdateLocalAddress -- publishes a local address update to broker
  239. func UpdateLocalAddress(cfg config.ClientConfig, network, ip string) {
  240. ncutils.Log("Updating local address")
  241. client := SetupMQTT(cfg)
  242. if token := client.Publish("update/localaddress/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
  243. ncutils.Log("error publishing local address update " + token.Error().Error())
  244. }
  245. cfg.Node.LocalAddress = ip
  246. ncutils.Log("updating local address in local config to: " + cfg.Node.LocalAddress)
  247. if err := config.Write(&cfg, cfg.Network); err != nil {
  248. ncutils.Log("error updating local config " + err.Error())
  249. }
  250. client.Disconnect(250)
  251. }
  252. // Hello -- ping the broker to let server know node is alive and doing fine
  253. func Hello(cfg config.ClientConfig, network string) {
  254. client := SetupMQTT(cfg)
  255. ncutils.Log("sending ping " + cfg.Node.ID)
  256. if token := client.Publish("ping/"+cfg.Node.ID, 2, false, "hello world!"); token.Wait() && token.Error() != nil {
  257. ncutils.Log("error publishing ping " + token.Error().Error())
  258. }
  259. client.Disconnect(250)
  260. }