Переглянути джерело

Merge pull request #594 from mattkasun/feature-messageQueue

Feature message queue
Matthew R Kasun 3 роки тому
батько
коміт
105e83f987

+ 1 - 1
.gitignore

@@ -15,5 +15,5 @@ netclient/netclient32
 netclient/netclient.exe
 config/dnsconfig/
 data/
-.vscode/
 .idea/
+

+ 11 - 0
compose/docker-compose.contained.yml

@@ -68,9 +68,20 @@ services:
       # - $PWD/site:/srv # you could also serve a static site in site folder
       - caddy_data:/data
       - caddy_conf:/config
+  mosquitto:
+    image: eclipse-mosquitto:2.0.14
+    container_name: broker
+    restart: unless-stopped
+    network_mode: host
+    volumes:
+      - /root/mosquitto.conf:/mosquitto/config/mosquitto.conf
+      - mosquitto_data:/mosquitto/data
+      - mosquitto_logs:/mosquitto/log 
 volumes:
   caddy_data: {}
   caddy_conf: {}
   sqldata: {}
   dnsconfig: {}
+  mosquitto_data: {}
+  mosquitto_logs: {}
 

+ 11 - 0
docker/mosquitto.conf

@@ -0,0 +1,11 @@
+persistence true
+persistence file mosquitto.db
+persistance_location mosquitto/data
+
+log_dest_file mosquitto/log/mosquitto.log
+
+per_listener_settings true
+listener 1883
+allow_anonymous true
+#bind_interface SERVER_PUBLIC_IP
+

+ 6 - 0
go.mod

@@ -32,10 +32,14 @@ require (
 	cloud.google.com/go v0.34.0 // indirect
 	github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d // indirect
 	github.com/davecgh/go-spew v1.1.1 // indirect
+	github.com/eclipse/paho.mqtt.golang v1.3.5 // indirect
 	github.com/felixge/httpsnoop v1.0.1 // indirect
+	github.com/go-ping/ping v0.0.0-20211130115550-779d1e919534 // indirect
 	github.com/go-playground/locales v0.14.0 // indirect
 	github.com/go-playground/universal-translator v0.18.0 // indirect
 	github.com/google/go-cmp v0.5.5 // indirect
+	github.com/google/uuid v1.2.0 // indirect
+	github.com/gorilla/websocket v1.4.2 // indirect
 	github.com/josharian/native v0.0.0-20200817173448-b6b71def0850 // indirect
 	github.com/leodido/go-urn v1.2.1 // indirect
 	github.com/mdlayher/genetlink v1.0.0 // indirect
@@ -43,5 +47,7 @@ require (
 	github.com/pmezard/go-difflib v1.0.0 // indirect
 	github.com/russross/blackfriday/v2 v2.0.1 // indirect
 	github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
+	golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
 	google.golang.org/appengine v1.4.0 // indirect
+	gopkg.in/ini.v1 v1.66.2 // indirect
 )

+ 15 - 0
go.sum

@@ -24,6 +24,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/eclipse/paho.mqtt.golang v1.3.5 h1:sWtmgNxYM9P2sP+xEItMozsR3w0cqZFlqnNN1bdl41Y=
+github.com/eclipse/paho.mqtt.golang v1.3.5/go.mod h1:eTzb4gxwwyWpqBUHGQZ4ABAV7+Jgm1PklsYT/eo8Hcc=
 github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
 github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
 github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
@@ -34,6 +36,8 @@ github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8S
 github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
 github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
 github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
+github.com/go-ping/ping v0.0.0-20211130115550-779d1e919534 h1:dhy9OQKGBh4zVXbjwbxxHjRxMJtLXj3zfgpBYQaR4Q4=
+github.com/go-ping/ping v0.0.0-20211130115550-779d1e919534/go.mod h1:xIFjORFzTxqIV/tDVGO4eDy/bLuSyawEeojSm3GfRGk=
 github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
 github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
 github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU=
@@ -70,10 +74,14 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
 github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
 github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
 github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
+github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
 github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4=
 github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q=
 github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
 github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
+github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
+github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
 github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
 github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
 github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
@@ -178,6 +186,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
 golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
 golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
 golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20200425230154-ff2c4b7c35a0/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
 golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
 golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
 golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
@@ -185,6 +194,7 @@ golang.org/x/net v0.0.0-20201216054612-986b41b23924/go.mod h1:m0MpNAwzfU5UDzcl9v
 golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
 golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
 golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
 golang.org/x/net v0.0.0-20210504132125-bbd867fde50d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
 golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985 h1:4CSI6oo7cOjJKajidEljs9h+uP0rRZBPPPhcCbj5mw8=
 golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
@@ -195,6 +205,8 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJ
 golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
+golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -216,6 +228,7 @@ golang.org/x/sys v0.0.0-20210123111255-9b0068b26619/go.mod h1:h1NjWce9XRLGQEsW7w
 golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210216163648-f7da38b97c65/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210309040221-94ec62e08169/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210503173754-0981d6026fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -279,6 +292,8 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8
 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
 gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
+gopkg.in/ini.v1 v1.66.2 h1:XfR1dOYubytKy4Shzc2LHrrGhU0lDCfDGG1yLPmpgsI=
+gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
 gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
 gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
 gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

+ 14 - 0
models/mqtt.go

@@ -0,0 +1,14 @@
+package models
+
+import "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
+
+type PeerUpdate struct {
+	Network   string
+	Interface string
+	Peers     []wgtypes.Peer
+}
+
+type KeyUpdate struct {
+	Network   string
+	Interface string
+}

+ 9 - 0
netclient/cli_options/cmds.go

@@ -118,5 +118,14 @@ func GetCommands(cliFlags []cli.Flag) []*cli.Command {
 				return err
 			},
 		},
+		{
+			Name:  "daemon",
+			Usage: "run netclient as daemon",
+			Flags: cliFlags,
+			Action: func(c *cli.Context) error {
+				err := command.Daemon()
+				return err
+			},
+		},
 	}
 }

+ 5 - 0
netclient/command/commands.go

@@ -210,3 +210,8 @@ func Uninstall() error {
 	ncutils.PrintLog("uninstalled netclient", 0)
 	return err
 }
+
+func Daemon() error {
+	err := functions.Daemon()
+	return err
+}

+ 283 - 0
netclient/functions/daemon.go

@@ -0,0 +1,283 @@
+package functions
+
+import (
+	"context"
+	"encoding/json"
+	"log"
+	"os"
+	"os/signal"
+	"strings"
+	"syscall"
+	"time"
+
+	mqtt "github.com/eclipse/paho.mqtt.golang"
+	"github.com/gravitl/netmaker/models"
+	"github.com/gravitl/netmaker/netclient/config"
+	"github.com/gravitl/netmaker/netclient/ncutils"
+	"github.com/gravitl/netmaker/netclient/wireguard"
+	"golang.zx2c4.com/wireguard/wgctrl"
+	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
+)
+
+// Daemon runs netclient daemon from command line
+func Daemon() error {
+	ctx, cancel := context.WithCancel(context.Background())
+	networks, err := ncutils.GetSystemNetworks()
+	if err != nil {
+		cancel()
+		return err
+	}
+	for _, network := range networks {
+		go Netclient(ctx, network)
+	}
+	quit := make(chan os.Signal, 1)
+	signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
+	<-quit
+	cancel()
+	ncutils.Log("all done")
+	return nil
+}
+
+// SetupMQTT creates a connection to broker and return client
+func SetupMQTT(cfg config.ClientConfig) mqtt.Client {
+	opts := mqtt.NewClientOptions()
+	ncutils.Log("setting broker to " + cfg.Server.CoreDNSAddr + ":1883")
+	opts.AddBroker(cfg.Server.CoreDNSAddr + ":1883")
+	opts.SetDefaultPublishHandler(All)
+	client := mqtt.NewClient(opts)
+	if token := client.Connect(); token.Wait() && token.Error() != nil {
+		log.Fatal(token.Error())
+	}
+	return client
+}
+
+// Netclient sets up Message Queue and subsribes/publishes updates to/from server
+func Netclient(ctx context.Context, network string) {
+	ncutils.Log("netclient go routine started for " + network)
+	var cfg config.ClientConfig
+	cfg.Network = network
+	cfg.ReadConfig()
+	//fix NodeID to remove ### so NodeID can be used as message topic
+	//remove with GRA-73
+	cfg.Node.ID = strings.Replace(cfg.Node.ID, "###", "-", 1)
+	ncutils.Log("daemon started for network:" + network)
+	client := SetupMQTT(cfg)
+	if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
+		log.Fatal(token.Error())
+	}
+	client.AddRoute("update/"+cfg.Node.ID, NodeUpdate)
+	client.AddRoute("update/peers/"+cfg.Node.ID, UpdatePeers)
+	client.AddRoute("update/keys/"+cfg.Node.ID, UpdateKeys)
+	defer client.Disconnect(250)
+	go Checkin(ctx, cfg, network)
+	go Metrics(ctx, cfg, network)
+	<-ctx.Done()
+	ncutils.Log("shutting down daemon")
+}
+
+// All -- mqtt message hander for all ('#') topics
+var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
+	ncutils.Log("Topic: " + string(msg.Topic()))
+	ncutils.Log("Message: " + string(msg.Payload()))
+}
+
+// NodeUpdate -- mqtt message handler for /update/<NodeID> topic
+var NodeUpdate mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
+	ncutils.Log("received message to update node " + string(msg.Payload()))
+	//potentiall blocking i/o so do this in a go routine
+	go func() {
+		var data models.Node
+		err := json.Unmarshal(msg.Payload(), &data)
+		if err != nil {
+			ncutils.Log("error unmarshalling node update data" + err.Error())
+			return
+		}
+		var cfg config.ClientConfig
+		cfg.Network = data.Network
+		cfg.ReadConfig()
+		nameserver := cfg.Server.CoreDNSAddr
+		privateKey, err := wireguard.RetrievePrivKey(data.Network)
+		if err != nil {
+			ncutils.Log("error generating PrivateKey " + err.Error())
+			return
+		}
+		if err := wireguard.UpdateWgInterface(cfg.Node.Interface, privateKey, nameserver, data); err != nil {
+			ncutils.Log("error updating wireguard config " + err.Error())
+			return
+		}
+		// path hardcoded for now... should be updated
+		err = wireguard.ApplyWGQuickConf("/etc/netclient/config/" + cfg.Node.Interface + ".conf")
+		if err != nil {
+			ncutils.Log("error restarting wg after peer update " + err.Error())
+			return
+		}
+	}()
+}
+
+// UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
+var UpdatePeers mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
+	ncutils.Log("received message to update peers " + string(msg.Payload()))
+	//potentiall blocking i/o so do this in a go routine
+	go func() {
+		var peerUpdate models.PeerUpdate
+		err := json.Unmarshal(msg.Payload(), &peerUpdate)
+		if err != nil {
+			ncutils.Log("error unmarshalling peer data")
+			return
+		}
+		var cfg config.ClientConfig
+		cfg.Network = peerUpdate.Network
+		cfg.ReadConfig()
+		err = wireguard.UpdateWgPeers(cfg.Node.Interface, peerUpdate.Peers)
+		if err != nil {
+			ncutils.Log("error updating peers" + err.Error())
+			return
+		}
+		// path hardcoded for now... should be updated
+		err = wireguard.ApplyWGQuickConf("/etc/netclient/config/" + cfg.Node.Interface + ".conf")
+		if err != nil {
+			ncutils.Log("error restarting wg after peer update " + err.Error())
+			return
+		}
+	}()
+}
+
+// UpdateKeys -- mqtt message handler for /update/keys/<NodeID> topic
+var UpdateKeys mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
+	ncutils.Log("received message to update keys " + string(msg.Payload()))
+	//potentiall blocking i/o so do this in a go routine
+	go func() {
+		var data models.KeyUpdate
+		if err := json.Unmarshal(msg.Payload(), &data); err != nil {
+			ncutils.Log("error unmarshalling key update data" + err.Error())
+			return
+		}
+		var cfg config.ClientConfig
+		cfg.Network = data.Network
+		cfg.ReadConfig()
+		key, err := wgtypes.GeneratePrivateKey()
+		if err != nil {
+			ncutils.Log("error generating privatekey " + err.Error())
+			return
+		}
+		if err := wireguard.UpdatePrivateKey(data.Interface, key.String()); err != nil {
+			ncutils.Log("error updating wireguard key " + err.Error())
+			return
+		}
+		publicKey := key.PublicKey()
+		if token := client.Publish("update/publickey/"+cfg.Node.ID, 0, false, publicKey.String()); token.Wait() && token.Error() != nil {
+			ncutils.Log("error publishing publickey update " + token.Error().Error())
+		}
+		client.Disconnect(250)
+	}()
+}
+
+// Checkin  -- go routine that checks for public or local ip changes, publishes changes
+//   if there are no updates, simply "pings" the server as a checkin
+func Checkin(ctx context.Context, cfg config.ClientConfig, network string) {
+	for {
+		select {
+		case <-ctx.Done():
+			ncutils.Log("Checkin cancelled")
+			return
+			//delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
+		case <-time.After(time.Second * 10):
+			ncutils.Log("Checkin running")
+			if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
+				extIP, err := ncutils.GetPublicIP()
+				if err != nil {
+					ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
+				}
+				if cfg.Node.Endpoint != extIP && extIP != "" {
+					ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
+					UpdateEndpoint(cfg, network, extIP)
+				}
+				intIP, err := getPrivateAddr()
+				if err != nil {
+					ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
+				}
+				if cfg.Node.LocalAddress != intIP && intIP != "" {
+					ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
+					UpdateLocalAddress(cfg, network, intIP)
+				}
+			} else {
+				localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
+				if err != nil {
+					ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
+				}
+				if cfg.Node.Endpoint != localIP && localIP != "" {
+					ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
+					UpdateEndpoint(cfg, network, localIP)
+				}
+			}
+			Hello(cfg, network)
+			ncutils.Log("Checkin complete")
+		}
+	}
+}
+
+// UpdateEndpoint -- publishes an endpoint update to broker
+func UpdateEndpoint(cfg config.ClientConfig, network, ip string) {
+	ncutils.Log("Updating endpoint")
+	client := SetupMQTT(cfg)
+	if token := client.Publish("update/ip/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
+		ncutils.Log("error publishing endpoint update " + token.Error().Error())
+	}
+	client.Disconnect(250)
+}
+
+// UpdateLocalAddress -- publishes a local address update to broker
+func UpdateLocalAddress(cfg config.ClientConfig, network, ip string) {
+	ncutils.Log("Updating local address")
+	client := SetupMQTT(cfg)
+	if token := client.Publish("update/localaddress/"+cfg.Node.ID, 0, false, ip); token.Wait() && token.Error() != nil {
+		ncutils.Log("error publishing local address update " + token.Error().Error())
+	}
+	client.Disconnect(250)
+}
+
+// Hello -- ping the broker to let server know node is alive and doing fine
+func Hello(cfg config.ClientConfig, network string) {
+	client := SetupMQTT(cfg)
+	if token := client.Publish("ping/"+cfg.Node.ID, 0, false, "hello world!"); token.Wait() && token.Error() != nil {
+		ncutils.Log("error publishing ping " + token.Error().Error())
+	}
+	client.Disconnect(250)
+}
+
+// Metics --  go routine that collects wireguard metrics and publishes to broker
+func Metrics(ctx context.Context, cfg config.ClientConfig, network string) {
+	for {
+		select {
+		case <-ctx.Done():
+			ncutils.Log("Metrics collection cancelled")
+			return
+			//delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
+		case <-time.After(time.Second * 60):
+			ncutils.Log("Metrics collection running")
+			ncutils.Log("Metrics running")
+			wg, err := wgctrl.New()
+			if err != nil {
+				ncutils.Log("error getting devices " + err.Error())
+				break
+			}
+			device, err := wg.Device(cfg.Node.Interface)
+			if err != nil {
+				ncutils.Log("error readind wg device " + err.Error())
+				break
+			}
+			bytes, err := json.Marshal(device.Peers)
+			if err != nil {
+				ncutils.Log("error marshaling peers " + err.Error())
+				break
+			}
+			client := SetupMQTT(cfg)
+			if token := client.Publish("metrics/"+cfg.Node.ID, 1, false, bytes); token.Wait() && token.Error() != nil {
+				ncutils.Log("error publishing metrics " + token.Error().Error())
+			}
+			wg.Close()
+			client.Disconnect(250)
+			ncutils.Log("metrics collection complete")
+		}
+	}
+}

+ 128 - 0
netclient/wireguard/common.go

@@ -16,6 +16,12 @@ import (
 	"github.com/gravitl/netmaker/netclient/server"
 	"golang.zx2c4.com/wireguard/wgctrl"
 	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
+	"gopkg.in/ini.v1"
+)
+
+const (
+	section_interface = "Interface"
+	section_peers     = "Peer"
 )
 
 // SetPeers - sets peers on a given WireGuard interface
@@ -280,3 +286,125 @@ func ApplyConf(confPath string) error {
 	}
 	return err
 }
+
+// WriteWgConfig - creates a wireguard config file
+func WriteWgConfig(cfg config.ClientConfig, privateKey string, peers []wgtypes.Peer) error {
+	options := ini.LoadOptions{
+		AllowNonUniqueSections: true,
+		AllowShadows:           true,
+	}
+	wireguard := ini.Empty(options)
+	wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
+	wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(cfg.Node.ListenPort)))
+	if cfg.Node.Address != "" {
+		wireguard.Section(section_interface).Key("Address").SetValue(cfg.Node.Address)
+	}
+	if cfg.Node.Address6 != "" {
+		wireguard.Section(section_interface).Key("Address").SetValue(cfg.Node.Address6)
+	}
+	if cfg.Node.DNSOn == "yes" {
+		wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
+	}
+	if cfg.Node.PostUp != "" {
+		wireguard.Section(section_interface).Key("PostUp").SetValue(cfg.Node.PostUp)
+	}
+	if cfg.Node.PostDown != "" {
+		wireguard.Section(section_interface).Key("PostDown").SetValue(cfg.Node.PostDown)
+	}
+	for i, peer := range peers {
+		wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
+		if peer.PresharedKey.String() != "" {
+			wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
+		}
+		if peer.AllowedIPs != nil {
+			var allowedIPs string
+			for _, ip := range peer.AllowedIPs {
+				allowedIPs = allowedIPs + ", " + ip.String()
+			}
+			wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
+		}
+		if peer.Endpoint != nil {
+			wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
+		}
+	}
+	if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"); err != nil {
+		return err
+	}
+	return nil
+}
+
+// UpdateWgPeers - updates the peers of a network
+func UpdateWgPeers(wgInterface string, peers []wgtypes.Peer) error {
+	//update to get path properly
+	file := ncutils.GetNetclientPathSpecific() + wgInterface + ".conf"
+	wireguard, err := ini.ShadowLoad(file)
+	if err != nil {
+		return err
+	}
+	for i, peer := range peers {
+		wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
+		if peer.PresharedKey.String() != "" {
+			wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
+		}
+		if peer.AllowedIPs != nil {
+			var allowedIPs string
+			for _, ip := range peer.AllowedIPs {
+				allowedIPs = allowedIPs + ", " + ip.String()
+			}
+			wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
+		}
+		if peer.Endpoint != nil {
+			wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
+		}
+	}
+	if err := wireguard.SaveTo(file); err != nil {
+		return err
+	}
+	return nil
+}
+
+// UpdateWgInterface - updates the interface section of a wireguard config file
+func UpdateWgInterface(wgInterface, privateKey, nameserver string, node models.Node) error {
+	//update to get path properly
+	file := ncutils.GetNetclientPathSpecific() + wgInterface + ".conf"
+	wireguard, err := ini.ShadowLoad(file)
+	if err != nil {
+		return err
+	}
+	wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
+	wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
+	if node.Address != "" {
+		wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
+	}
+	if node.Address6 != "" {
+		wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
+	}
+	if node.DNSOn == "yes" {
+		wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
+	}
+	if node.PostUp != "" {
+		wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
+	}
+	if node.PostDown != "" {
+		wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
+	}
+	if err := wireguard.SaveTo(file); err != nil {
+		return err
+	}
+	return nil
+}
+
+// UpdatePrivateKey - updates the private key of a wireguard config file
+func UpdatePrivateKey(wgInterface, privateKey string) error {
+	//update to get path properly
+	file := ncutils.GetNetclientPathSpecific() + wgInterface + ".conf"
+	wireguard, err := ini.ShadowLoad(file)
+	if err != nil {
+		return err
+	}
+	wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
+	if err := wireguard.SaveTo(file); err != nil {
+		return err
+	}
+	return nil
+}

+ 3 - 0
scripts/install-netmaker.sh

@@ -136,6 +136,9 @@ echo "Setting Caddyfile..."
 sed -i "s/NETMAKER_BASE_DOMAIN/$NETMAKER_BASE_DOMAIN/g" /root/Caddyfile
 sed -i "s/YOUR_EMAIL/$EMAIL/g" /root/Caddyfile
 
+echo "Setting Broker..."
+sed -i "s/SERVER_PBLIC_IP/$SERVER_PUBLIC_IP/g" /root/mosquitto.conf
+
 echo "Setting docker-compose..."
 
 sed -i "s/NETMAKER_BASE_DOMAIN/$NETMAKER_BASE_DOMAIN/g" /root/docker-compose.yml

+ 4 - 0
scripts/nm-quick.sh

@@ -135,6 +135,10 @@ wget -q -O /root/Caddyfile https://raw.githubusercontent.com/gravitl/netmaker/ma
 sed -i "s/NETMAKER_BASE_DOMAIN/$NETMAKER_BASE_DOMAIN/g" /root/Caddyfile
 sed -i "s/YOUR_EMAIL/$EMAIL/g" /root/Caddyfile
 
+echo "setting mosquitto.conf..."
+
+wget -q -O /root/mosquitto.conf https://raw.githubusercontent.com/gravil/netmaker/master/docker/mosquitto.conf
+sed -i "s/SERVER_PUBLIC_IP/$SERVER_PUBLIC_IP/g" /root/mosquitto.conf
 
 echo "setting docker-compose..."