daemon.go 9.4 KB

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