daemon.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 != nil {
  94. ncutils.Log("error generating PrivateKey " + err.Error())
  95. return
  96. }
  97. if err := wireguard.UpdateWgInterface(cfg.Node.Interface, privateKey, nameserver, data); err != nil {
  98. ncutils.Log("error updating wireguard config " + err.Error())
  99. return
  100. }
  101. // path hardcoded for now... should be updated
  102. err = wireguard.ApplyWGQuickConf("/etc/netclient/config/" + cfg.Node.Interface + ".conf")
  103. if err != nil {
  104. ncutils.Log("error restarting wg after peer update " + err.Error())
  105. return
  106. }
  107. }()
  108. }
  109. // UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
  110. var UpdatePeers mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  111. ncutils.Log("received message to update peers " + string(msg.Payload()))
  112. //potentiall blocking i/o so do this in a go routine
  113. go func() {
  114. var peerUpdate models.PeerUpdate
  115. err := json.Unmarshal(msg.Payload(), &peerUpdate)
  116. if err != nil {
  117. ncutils.Log("error unmarshalling peer data")
  118. return
  119. }
  120. var cfg config.ClientConfig
  121. cfg.Network = peerUpdate.Network
  122. cfg.ReadConfig()
  123. err = wireguard.UpdateWgPeers(cfg.Node.Interface, peerUpdate.Peers)
  124. if err != nil {
  125. ncutils.Log("error updating peers" + err.Error())
  126. return
  127. }
  128. // path hardcoded for now... should be updated
  129. err = wireguard.ApplyWGQuickConf("/etc/netclient/config/" + cfg.Node.Interface + ".conf")
  130. if err != nil {
  131. ncutils.Log("error restarting wg after peer update " + err.Error())
  132. return
  133. }
  134. }()
  135. }
  136. // UpdateKeys -- mqtt message handler for /update/keys/<NodeID> topic
  137. var UpdateKeys mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  138. ncutils.Log("received message to update keys " + string(msg.Payload()))
  139. //potentiall blocking i/o so do this in a go routine
  140. go func() {
  141. var data models.KeyUpdate
  142. if err := json.Unmarshal(msg.Payload(), &data); err != nil {
  143. ncutils.Log("error unmarshalling key update data" + err.Error())
  144. return
  145. }
  146. var cfg config.ClientConfig
  147. cfg.Network = data.Network
  148. cfg.ReadConfig()
  149. key, err := wgtypes.GeneratePrivateKey()
  150. if err != nil {
  151. ncutils.Log("error generating privatekey " + err.Error())
  152. return
  153. }
  154. if err := wireguard.UpdatePrivateKey(data.Interface, key.String()); err != nil {
  155. ncutils.Log("error updating wireguard key " + err.Error())
  156. return
  157. }
  158. publicKey := key.PublicKey()
  159. if token := client.Publish("update/publickey/"+cfg.Node.ID, 0, false, publicKey.String()); token.Wait() && token.Error() != nil {
  160. ncutils.Log("error publishing publickey update " + token.Error().Error())
  161. }
  162. client.Disconnect(250)
  163. }()
  164. }
  165. // Checkin -- go routine that checks for public or local ip changes, publishes changes
  166. // if there are no updates, simply "pings" the server as a checkin
  167. func Checkin(ctx context.Context, cfg config.ClientConfig, network string) {
  168. for {
  169. select {
  170. case <-ctx.Done():
  171. ncutils.Log("Checkin cancelled")
  172. return
  173. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  174. case <-time.After(time.Second * 10):
  175. ncutils.Log("Checkin running")
  176. if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
  177. extIP, err := ncutils.GetPublicIP()
  178. if err != nil {
  179. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  180. }
  181. if cfg.Node.Endpoint != extIP && extIP != "" {
  182. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
  183. UpdateEndpoint(cfg, network, extIP)
  184. }
  185. intIP, err := getPrivateAddr()
  186. if err != nil {
  187. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  188. }
  189. if cfg.Node.LocalAddress != intIP && intIP != "" {
  190. ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
  191. UpdateLocalAddress(cfg, network, intIP)
  192. }
  193. } else {
  194. localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
  195. if err != nil {
  196. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  197. }
  198. if cfg.Node.Endpoint != localIP && localIP != "" {
  199. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
  200. UpdateEndpoint(cfg, network, localIP)
  201. }
  202. }
  203. Hello(cfg, network)
  204. ncutils.Log("Checkin complete")
  205. }
  206. }
  207. }
  208. // UpdateEndpoint -- publishes an endpoint update to broker
  209. func UpdateEndpoint(cfg config.ClientConfig, network, ip string) {
  210. ncutils.Log("Updating endpoint")
  211. client := SetupMQTT(cfg)
  212. if token := client.Publish("update/ip/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
  213. ncutils.Log("error publishing endpoint update " + token.Error().Error())
  214. }
  215. client.Disconnect(250)
  216. }
  217. // UpdateLocalAddress -- publishes a local address update to broker
  218. func UpdateLocalAddress(cfg config.ClientConfig, network, ip string) {
  219. ncutils.Log("Updating local address")
  220. client := SetupMQTT(cfg)
  221. if token := client.Publish("update/localaddress/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
  222. ncutils.Log("error publishing local address update " + token.Error().Error())
  223. }
  224. client.Disconnect(250)
  225. }
  226. // Hello -- ping the broker to let server know node is alive and doing fine
  227. func Hello(cfg config.ClientConfig, network string) {
  228. client := SetupMQTT(cfg)
  229. if token := client.Publish("ping/"+cfg.Node.ID, 0, false, "hello world!"); token.Wait() && token.Error() != nil {
  230. ncutils.Log("error publishing ping " + token.Error().Error())
  231. }
  232. client.Disconnect(250)
  233. }
  234. // Metics -- go routine that collects wireguard metrics and publishes to broker
  235. func Metrics(ctx context.Context, cfg config.ClientConfig, network string) {
  236. for {
  237. select {
  238. case <-ctx.Done():
  239. ncutils.Log("Metrics collection cancelled")
  240. return
  241. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  242. case <-time.After(time.Second * 60):
  243. ncutils.Log("Metrics collection running")
  244. ncutils.Log("Metrics running")
  245. wg, err := wgctrl.New()
  246. if err != nil {
  247. ncutils.Log("error getting devices " + err.Error())
  248. break
  249. }
  250. device, err := wg.Device(cfg.Node.Interface)
  251. if err != nil {
  252. ncutils.Log("error readind wg device " + err.Error())
  253. break
  254. }
  255. bytes, err := json.Marshal(device.Peers)
  256. if err != nil {
  257. ncutils.Log("error marshaling peers " + err.Error())
  258. break
  259. }
  260. client := SetupMQTT(cfg)
  261. if token := client.Publish("metrics/"+cfg.Node.ID, 1, false, bytes); token.Wait() && token.Error() != nil {
  262. ncutils.Log("error publishing metrics " + token.Error().Error())
  263. }
  264. wg.Close()
  265. client.Disconnect(250)
  266. ncutils.Log("metrics collection complete")
  267. }
  268. }
  269. }