Procházet zdrojové kódy

add wireguard conf func

reid před 2 roky
rodič
revize
80d1645288
10 změnil soubory, kde provedl 149 přidání a 144 odebrání
  1. 2 2
      broadcast/broadcast.go
  2. 13 4
      config/config.go
  3. 42 0
      config/urbit.go
  4. 46 0
      config/wireguard.go
  5. 1 1
      docker/docker.go
  6. 0 37
      docker/urbit.go
  7. 19 0
      docker/wireguard.go
  8. 0 93
      main-old.go
  9. 13 7
      main.go
  10. 13 0
      structs/structs.go

+ 2 - 2
broadcast/broadcast.go

@@ -134,13 +134,13 @@ func constructPierInfo(piers []string) (map[string]structs.Urbit, error) {
 	// convert the running status into bools
 	for pier, status := range pierStatus {
 		// pull urbit info from json
-		err := docker.LoadConfig(pier)
+		err := config.LoadUrbitConfig(pier)
 		if err != nil {
 			errmsg := fmt.Sprintf("Unable to load %s config: %v", pier, err)
 			logger.Error(errmsg)
 			continue
 		}
-		dockerConfig := docker.Conf(pier)
+		dockerConfig := config.UrbitConf(pier)
 		// get container stats from docker
 		var dockerStats structs.ContainerStats
 		dockerStats, err = docker.GetContainerStats(pier)

+ 13 - 4
config/config.go

@@ -20,7 +20,8 @@ var (
 	logger             = slog.New(slog.NewJSONHandler(os.Stdout, nil))
 	BasePath           = "/opt/nativeplanet/groundseg"
 	Version            = "v2.0.0"
-	Architecture       string
+	Architecture       = getArchitecture()
+	DebugMode          = false
 	Ready              = false
 	VersionServerReady = false
 	VersionInfo        structs.Version
@@ -33,6 +34,13 @@ var (
 
 // try initializing from system.json on disk
 func init() {
+	for _, arg := range os.Args[1:] {
+		// trigger this with `./groundseg dev`
+		if arg == "dev" {
+			logger.Info("Starting GroundSeg in debug mode")
+			DebugMode = true
+		}
+	}
 	pathMsg := fmt.Sprintf("Loading configs from %s", BasePath)
 	logger.Info(pathMsg)
 	confPath := filepath.Join(BasePath, "settings", "system.json")
@@ -41,8 +49,10 @@ func init() {
 		// create a default if it doesn't exist
 		err = createDefaultConf()
 		if err != nil {
+			// panic if we can't create it
 			errmsg := fmt.Sprintf("Unable to create config! %v", err)
 			logger.Error(errmsg)
+			panic(errmsg)
 		}
 	}
 	defer file.Close()
@@ -52,7 +62,6 @@ func init() {
 		errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
 		logger.Error(errmsg)
 	}
-	Architecture = getArchitecture()
 }
 
 // return the global conf var
@@ -167,8 +176,7 @@ func createDefaultConf() error {
 		WgRegistered:   false,
 		PwHash:         "",
 		C2cInterval:    0,
-		FirstBoot:      false,
-		WgRegisterd:    false,
+		FirstBoot:      true,
 		GsVersion:      Version,
 		CfgDir:         "",
 		UpdateInterval: 0,
@@ -284,6 +292,7 @@ func CheckVersionLoop() {
 			currentVersion := VersionInfo
 			if latestVersion != currentVersion {
 				fmt.Printf("New version available! Current: %s, Latest: %s\n", currentVersion, latestVersion)
+				VersionInfo = latestVersion
 				// Handle the update logic here
 			}
 		}

+ 42 - 0
config/urbit.go

@@ -0,0 +1,42 @@
+package config
+
+import (
+	"encoding/json"
+	"fmt"
+	"goseg/structs"
+	"io/ioutil"
+	"path/filepath"
+	"sync"
+)
+
+var (
+	UrbitsConfig = make(map[string]structs.UrbitDocker)
+	urbitMutex   sync.RWMutex
+)
+
+func UrbitConf(pier string) structs.UrbitDocker {
+	urbitMutex.Lock()
+	defer urbitMutex.Unlock()
+	return UrbitsConfig[pier]
+}
+
+func LoadUrbitConfig(pier string) error {
+	urbitMutex.Lock()
+	defer urbitMutex.Unlock()
+	// pull docker info from json
+	confPath := filepath.Join(BasePath, "settings", "pier", pier+".json")
+	file, err := ioutil.ReadFile(confPath)
+	if err != nil {
+		errmsg := fmt.Sprintf("Unable to load %s config: %v", pier, err)
+		return fmt.Errorf(errmsg) // Return an error instead of a string
+	}
+	// Unmarshal JSON
+	var targetStruct structs.UrbitDocker
+	if err := json.Unmarshal(file, &targetStruct); err != nil {
+		errmsg := fmt.Sprintf("Error decoding %s JSON: %v", pier, err)
+		return fmt.Errorf(errmsg)
+	}
+	// Store in var
+	UrbitsConfig[pier] = targetStruct
+	return nil
+}

+ 46 - 0
config/wireguard.go

@@ -0,0 +1,46 @@
+package config
+
+import (
+	"encoding/json"
+	"goseg/structs"
+	"os"
+	"path/filepath"
+)
+
+// write a conf to disk
+func CreateDefaultWGConf() error {
+	conf := Conf()
+	releaseChannel := conf.UpdateBranch
+	wgRepo := VersionInfo.Groundseg.Latest.Wireguard.Repo
+	amdHash := VersionInfo.Groundseg.Latest.Wireguard.Amd64Sha256
+	armHash := VersionInfo.Groundseg.Latest.Wireguard.Arm64Sha256
+	defaultConfig := structs.WgConfig{
+		WireguardName:    "wireguard",
+		WireguardVersion: releaseChannel,
+		Repo:             wgRepo,
+		Amd64Sha256:      amdHash,
+		Arm64Sha256:      armHash,
+		CapAdd:           []string{"NET_ADMIN", "SYS_MODULE"},
+		Volumes:          []string{"/lib/modules:/lib/modules"},
+		Sysctls: struct {
+			NetIpv4ConfAllSrcValidMark int `json:"net.ipv4.conf.all.src_valid_mark"`
+		}{
+			NetIpv4ConfAllSrcValidMark: 1,
+		},
+	}
+	path := filepath.Join(BasePath, "settings", "wireguard.json")
+	if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
+		return err
+	}
+	file, err := os.Create(path)
+	if err != nil {
+		return err
+	}
+	defer file.Close()
+	encoder := json.NewEncoder(file)
+	encoder.SetIndent("", "    ")
+	if err := encoder.Encode(&defaultConfig); err != nil {
+		return err
+	}
+	return nil
+}

+ 1 - 1
docker/docker.go

@@ -231,7 +231,7 @@ func StartContainer(containerName string, containerType string) (structs.Contain
 		ID:            containerDetails.ID,           // container id hash
 		Name:          containerName,                 // name (eg @p)
 		Image:         desiredImage,                  // full repo:tag@hash string
-		Type:          containerType,                 // eg `vere`
+		Type:          containerType,                 // eg `vere` (corresponds with version server label)
 		DesiredStatus: desiredStatus,                 // what the user sets
 		ActualStatus:  containerDetails.State.Status, // what the daemon reports
 		CreatedAt:     containerDetails.Created,      // this is a string

+ 0 - 37
docker/urbit.go

@@ -1,18 +1,8 @@
 package docker
 
 import (
-	"encoding/json"
 	"fmt"
 	"goseg/config"
-	"goseg/structs"
-	"io/ioutil"
-	"path/filepath"
-	"sync"
-)
-
-var (
-	UrbitsConfig = make(map[string]structs.UrbitDocker)
-	urbitMutex   sync.RWMutex
 )
 
 func LoadUrbits() error {
@@ -30,30 +20,3 @@ func LoadUrbits() error {
 	}
 	return nil
 }
-
-func Conf(pier string) structs.UrbitDocker {
-	urbitMutex.Lock()
-	defer urbitMutex.Unlock()
-	return UrbitsConfig[pier]
-}
-
-func LoadConfig(pier string) error {
-	urbitMutex.Lock()
-	defer urbitMutex.Unlock()
-	// pull docker info from json
-	confPath := filepath.Join(config.BasePath, "settings", "pier", pier+".json")
-	file, err := ioutil.ReadFile(confPath)
-	if err != nil {
-		errmsg := fmt.Sprintf("Unable to load %s config: %v", pier, err)
-		return fmt.Errorf(errmsg) // Return an error instead of a string
-	}
-	// Unmarshal JSON
-	var targetStruct structs.UrbitDocker
-	if err := json.Unmarshal(file, &targetStruct); err != nil {
-		errmsg := fmt.Sprintf("Error decoding %s JSON: %v", pier, err)
-		return fmt.Errorf(errmsg)
-	}
-	// Store in var
-	UrbitsConfig[pier] = targetStruct
-	return nil
-}

+ 19 - 0
docker/wireguard.go

@@ -1,7 +1,26 @@
 package docker
 
+import (
+	"fmt"
+	"goseg/config"
+	"os"
+	"path/filepath"
+)
+
 func LoadWireguard() error {
 	logger.Info("Loading Startram Wireguard container")
+	confPath := filepath.Join(config.BasePath, "settings", "wireguard.json")
+	_, err := os.Open(confPath)
+	if err != nil {
+		// create a default if it doesn't exist
+		err = config.CreateDefaultWGConf()
+		if err != nil {
+			// panic if we can't create it
+			errmsg := fmt.Sprintf("Unable to create WG config! %v", err)
+			logger.Error(errmsg)
+			panic(errmsg)
+		}
+	}
 	// apply latest version info
 	// start container
 	return nil

+ 0 - 93
main-old.go

@@ -1,93 +0,0 @@
-package main
-
-import (
-	"context"
-	"fmt"
-	"github.com/docker/docker/api/types"
-	"github.com/docker/docker/client"
-	"sync"
-	"time"
-)
-
-// var counter int
-var lock sync.Mutex
-
-/*
-	{
-	  "<patp>":{
-	    "status":<container-status>
-	  }
-	}
-*/
-var urbitBroadcast = make(map[string]map[string]string)
-
-func broadcast() {
-	for {
-		fmt.Println(urbitBroadcast) // send to websocket as json blob
-		time.Sleep(250 * time.Millisecond)
-	}
-}
-
-// Example
-func getStatus(i int, patp string) {
-	for {
-		// Locking the shared state
-		lock.Lock()
-
-		// Create submap
-		_, exist := urbitBroadcast[patp]
-		if !exist {
-			urbitBroadcast[patp] = make(map[string]string)
-		}
-
-		//Get container running status
-		cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
-		if err != nil {
-			//panic(err)
-			fmt.Println(err)
-		} else {
-			containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
-			if err != nil {
-				urbitBroadcast[patp]["status"] = "error"
-			} else {
-				for _, container := range containers {
-					for _, name := range container.Names {
-						fasPatp := "/" + patp
-						if name == fasPatp {
-							urbitBroadcast[patp]["status"] = container.Status
-						}
-					}
-				}
-			}
-		}
-
-		// Unlocking the shared state
-		lock.Unlock()
-
-		// Arbitary sleep
-		time.Sleep(5 * time.Second)
-	}
-}
-
-func main() {
-	/*
-	  Temporary Hardcode -- from config file
-	*/
-	piers := []string{"widwet-mornev-nallux-dozryl",
-		"hocfur-wicnym-nallux-dozryl",
-		"pinlyd-mattyd-nallux-dozryl",
-		"solnys-dibmyn-nallux-dozryl",
-		"wormun-fadwyl-nallux-dozryl",
-		"nopmul-pollyt",
-		"nalruc-nallux-dozryl",
-	}
-
-	go broadcast()
-	for i, patp := range piers {
-		go getStatus(i, patp)
-	}
-
-	// Waiting for the goroutines to complete
-	var input string
-	fmt.Scanln(&input)
-}

+ 13 - 7
main.go

@@ -13,6 +13,19 @@ import (
 	"github.com/gorilla/mux"
 )
 
+// NativePlanet GroundSeg: Go Edition (goseg)
+// This is a Golang rewrite of GroundSeg that serves the v2 json
+// object via websocket.
+// The v2 rewrite decouples the frontend and backend, which makes it
+// straightforward to implement alternative backends.
+//
+// Under development: reimplementing all pyseg functionality.
+// Advantages:
+// - Really, really fast
+// - Event-driven rather than cron poll-driven
+// - First-class support for concurrent operations
+// - Very good golang Docker libraries
+
 var (
 	logger  = slog.New(slog.NewJSONHandler(os.Stdout, nil))
 	DevMode = false
@@ -27,13 +40,6 @@ func loadService(loadFunc func() error, errMsg string) {
 }
 
 func main() {
-	for _, arg := range os.Args[1:] {
-		// trigger this with `./groundseg dev`
-		if arg == "dev" {
-			logger.Info("Starting GroundSeg in debug mode")
-			DevMode = true
-		}
-	}
 	logger.Info("Starting GroundSeg")
 	logger.Info("Urbit is love <3")
 	// global SysConfig var is managed through config package

+ 13 - 0
structs/structs.go

@@ -298,3 +298,16 @@ type UrbitDocker struct {
 	DevMode          bool   `json:"dev_mode"`
 	Click            bool   `json:"click"`
 }
+
+type WgConfig struct {
+	WireguardName    string   `json:"wireguard_name"`
+	WireguardVersion string   `json:"wireguard_version"`
+	Repo             string   `json:"repo"`
+	Amd64Sha256      string   `json:"amd64_sha256"`
+	Arm64Sha256      string   `json:"arm64_sha256"`
+	CapAdd           []string `json:"cap_add"`
+	Volumes          []string `json:"volumes"`
+	Sysctls          struct {
+		NetIpv4ConfAllSrcValidMark int `json:"net.ipv4.conf.all.src_valid_mark"`
+	} `json:"sysctls"`
+}