daemon.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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/netclient/config"
  13. "github.com/gravitl/netmaker/netclient/ncutils"
  14. "golang.zx2c4.com/wireguard/wgctrl"
  15. )
  16. //Daemon runs netclient daemon from command line
  17. func Daemon() error {
  18. ctx, cancel := context.WithCancel(context.Background())
  19. networks, err := ncutils.GetSystemNetworks()
  20. if err != nil {
  21. return err
  22. }
  23. for _, network := range networks {
  24. go Netclient(ctx, network)
  25. }
  26. quit := make(chan os.Signal, 1)
  27. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  28. <-quit
  29. cancel()
  30. return nil
  31. }
  32. //SetupMQTT creates a connection to broker and return client
  33. func SetupMQTT(cfg config.ClientConfig) mqtt.Client {
  34. opts := mqtt.NewClientOptions()
  35. ncutils.Log("setting broker to " + cfg.Server.CoreDNSAddr + ":1883")
  36. opts.AddBroker(cfg.Server.CoreDNSAddr + ":1883")
  37. opts.SetDefaultPublishHandler(All)
  38. client := mqtt.NewClient(opts)
  39. if token := client.Connect(); token.Wait() && token.Error() != nil {
  40. log.Fatal(token.Error())
  41. }
  42. return client
  43. }
  44. //Netclient sets up Message Queue and subsribes/publishes updates to/from server
  45. func Netclient(ctx context.Context, network string) {
  46. select {
  47. case <-ctx.Done():
  48. ncutils.Log("shutting down daemon")
  49. return
  50. default:
  51. var cfg config.ClientConfig
  52. cfg.Network = network
  53. cfg.ReadConfig()
  54. //fix NodeID to remove ### so NodeID can be used as message topic
  55. //remove with GRA-73
  56. cfg.Node.ID = strings.ReplaceAll(cfg.Node.ID, "###", "-")
  57. ncutils.Log("daemon started for network:" + network)
  58. client := SetupMQTT(cfg)
  59. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  60. log.Fatal(token.Error())
  61. }
  62. client.AddRoute("update/"+cfg.Node.ID, NodeUpdate)
  63. client.AddRoute("update/peers/"+cfg.Node.ID, UpdatePeers)
  64. client.AddRoute("update/keys/"+cfg.Node.ID, UpdateKeys)
  65. defer client.Disconnect(250)
  66. go Checkin(ctx, cfg, network)
  67. go Metrics(ctx, cfg, network)
  68. }
  69. }
  70. //All -- mqtt message hander for all ('#') topics
  71. var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  72. ncutils.Log("Topic: " + string(msg.Topic()))
  73. ncutils.Log("Message: " + string(msg.Payload()))
  74. }
  75. //NodeUpdate -- mqtt message handler for /update/<NodeID> topic
  76. var NodeUpdate mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  77. ncutils.Log("received message to update node " + string(msg.Payload()))
  78. }
  79. //UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
  80. var UpdatePeers mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  81. ncutils.Log("received message to update peers " + string(msg.Payload()))
  82. }
  83. //UpdateKeys -- mqtt message handler for /update/keys/<NodeID> topic
  84. var UpdateKeys mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  85. ncutils.Log("received message to update keys " + string(msg.Payload()))
  86. }
  87. //Checkin -- go routine that checks for public or local ip changes, publishes changes
  88. // if there are no updates, simply "pings" the server as a checkin
  89. func Checkin(ctx context.Context, cfg config.ClientConfig, network string) {
  90. select {
  91. case <-ctx.Done():
  92. ncutils.Log("Checkin cancelled")
  93. return
  94. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  95. case <-time.After(time.Second * 10):
  96. ncutils.Log("Checkin running")
  97. if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
  98. extIP, err := ncutils.GetPublicIP()
  99. if err != nil {
  100. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  101. }
  102. if cfg.Node.Endpoint != extIP && extIP != "" {
  103. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
  104. UpdateEndpoint(cfg, network, extIP)
  105. }
  106. intIP, err := getPrivateAddr()
  107. if err != nil {
  108. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  109. }
  110. if cfg.Node.LocalAddress != intIP && intIP != "" {
  111. ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
  112. UpdateLocalAddress(cfg, network, intIP)
  113. }
  114. } else {
  115. localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
  116. if err != nil {
  117. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  118. }
  119. if cfg.Node.Endpoint != localIP && localIP != "" {
  120. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
  121. UpdateEndpoint(cfg, network, localIP)
  122. }
  123. }
  124. Hello(cfg, network)
  125. ncutils.Log("Checkin complete")
  126. }
  127. }
  128. //UpdateEndpoint -- publishes an endpoint update to broker
  129. func UpdateEndpoint(cfg config.ClientConfig, network, ip string) {
  130. ncutils.Log("Updating endpoint")
  131. client := SetupMQTT(cfg)
  132. if token := client.Publish("update/ip/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
  133. ncutils.Log("error publishing endpoint update " + token.Error().Error())
  134. }
  135. client.Disconnect(250)
  136. }
  137. //UpdateLocalAddress -- publishes a local address update to broker
  138. func UpdateLocalAddress(cfg config.ClientConfig, network, ip string) {
  139. ncutils.Log("Updating local address")
  140. client := SetupMQTT(cfg)
  141. if token := client.Publish("update/localaddress/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
  142. ncutils.Log("error publishing local address update " + token.Error().Error())
  143. }
  144. client.Disconnect(250)
  145. }
  146. //Hello -- ping the broker to let server know node is alive and doing fine
  147. func Hello(cfg config.ClientConfig, network string) {
  148. client := SetupMQTT(cfg)
  149. if token := client.Publish("ping/"+network+"/"+cfg.Node.ID, 0, false, "hello world!"); token.Wait() && token.Error() != nil {
  150. ncutils.Log("error publishing ping " + token.Error().Error())
  151. }
  152. client.Disconnect(250)
  153. }
  154. //Metics -- go routine that collects wireguard metrics and publishes to broker
  155. func Metrics(ctx context.Context, cfg config.ClientConfig, network string) {
  156. select {
  157. case <-ctx.Done():
  158. ncutils.Log("Metrics collection cancelled")
  159. return
  160. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  161. case <-time.After(time.Second * 60):
  162. ncutils.Log("Metrics collection running")
  163. ncutils.Log("Metrics running")
  164. wg, err := wgctrl.New()
  165. if err != nil {
  166. ncutils.Log("error getting devices " + err.Error())
  167. break
  168. }
  169. device, err := wg.Device(cfg.Node.Interface)
  170. if err != nil {
  171. ncutils.Log("error readind wg device " + err.Error())
  172. break
  173. }
  174. bytes, err := json.Marshal(device.Peers)
  175. if err != nil {
  176. ncutils.Log("error marshaling peers " + err.Error())
  177. break
  178. }
  179. client := SetupMQTT(cfg)
  180. if token := client.Publish("metrics/"+cfg.Node.ID, 1, false, bytes); token.Wait() && token.Error() != nil {
  181. ncutils.Log("error publishing metrics " + token.Error().Error())
  182. }
  183. wg.Close()
  184. client.Disconnect(250)
  185. ncutils.Log("metrics collection complete")
  186. }
  187. }