Parcourir la source

add config management for other containers, switch version struct to Channel type

reid il y a 2 ans
Parent
commit
b730370396
6 fichiers modifiés avec 91 ajouts et 72 suppressions
  1. 31 54
      config/config.go
  2. 27 6
      config/wireguard.go
  3. 1 1
      docker/docker.go
  4. 9 5
      docker/urbit.go
  5. 1 1
      main.go
  6. 22 5
      structs/structs.go

+ 31 - 54
config/config.go

@@ -3,6 +3,7 @@ package config
 import (
 	"encoding/json"
 	"fmt"
+	"goseg/defaults"
 	"goseg/structs"
 	"io/ioutil"
 	"log/slog"
@@ -18,13 +19,12 @@ import (
 var (
 	globalConfig       structs.SysConfig
 	logger             = slog.New(slog.NewJSONHandler(os.Stdout, nil))
-	BasePath           = "/opt/nativeplanet/groundseg"
-	Version            = "v2.0.0"
+	BasePath           = os.Getenv("GS_BASE_PATH")
 	Architecture       = getArchitecture()
 	DebugMode          = false
 	Ready              = false
 	VersionServerReady = false
-	VersionInfo        structs.Version
+	VersionInfo        structs.Channel
 	GSContainers       = make(map[string]structs.ContainerState)
 	checkInterval      = 5 * time.Minute
 	confMutex          sync.Mutex
@@ -41,6 +41,10 @@ func init() {
 			DebugMode = true
 		}
 	}
+	if BasePath == "" {
+		// default base path
+		BasePath = "/opt/nativeplanet/groundseg"
+	}
 	pathMsg := fmt.Sprintf("Loading configs from %s", BasePath)
 	logger.Info(pathMsg)
 	confPath := filepath.Join(BasePath, "settings", "system.json")
@@ -50,12 +54,13 @@ func init() {
 		err = createDefaultConf()
 		if err != nil {
 			// panic if we can't create it
-			errmsg := fmt.Sprintf("Unable to create config! %v", err)
+			errmsg := fmt.Sprintf("Unable to create config! Please elevate permissions. %v", err)
 			logger.Error(errmsg)
 			panic(errmsg)
 		}
 	}
 	defer file.Close()
+	// read the sysconfig to memory
 	decoder := json.NewDecoder(file)
 	err = decoder.Decode(&globalConfig)
 	if err != nil {
@@ -146,48 +151,7 @@ func GetContainerState() map[string]structs.ContainerState {
 
 // write a default conf to disk
 func createDefaultConf() error {
-	defaultConfig := structs.SysConfig{
-		Setup:        "start",
-		EndpointUrl:  "api.startram.io",
-		ApiVersion:   "v1",
-		Piers:        []string{},
-		NetCheck:     "1.1.1.1:53",
-		UpdateMode:   "auto",
-		UpdateUrl:    "https://version.groundseg.app",
-		UpdateBranch: "latest",
-		SwapVal:      16,
-		SwapFile:     filepath.Join(BasePath, "settings", "swapfile"),
-		KeyFile:      filepath.Join(BasePath, "settings", "session.key"),
-		Sessions: struct {
-			Authorized   map[string]structs.SessionInfo `json:"authorized"`
-			Unauthorized map[string]structs.SessionInfo `json:"unauthorized"`
-		}{
-			Authorized:   make(map[string]structs.SessionInfo),
-			Unauthorized: make(map[string]structs.SessionInfo),
-		},
-		LinuxUpdates: struct {
-			Value    int    `json:"value"`
-			Interval string `json:"interval"`
-			Previous bool   `json:"previous"`
-		}{
-			Value:    1,
-			Interval: "week",
-			Previous: false,
-		},
-		DockerData:     "/var/lib/docker",
-		WgOn:           false,
-		WgRegistered:   false,
-		PwHash:         "",
-		C2cInterval:    0,
-		FirstBoot:      true,
-		GsVersion:      Version,
-		CfgDir:         "",
-		UpdateInterval: 0,
-		BinHash:        "",
-		Pubkey:         "",
-		Privkey:        "",
-		Salt:           "",
-	}
+	defaultConfig := defaults.SysConfig(BasePath)
 	path := filepath.Join(BasePath, "settings", "system.json")
 	if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
 		return err
@@ -222,13 +186,16 @@ func NetCheck(netCheck string) bool {
 	return internet
 }
 
-// check the version server and return unmarshaled result
-func CheckVersion() (structs.Version, bool) {
+// check the version server and return struct
+func CheckVersion() (structs.Channel, bool) {
 	versMutex.Lock()
 	defer versMutex.Unlock()
+	conf := Conf()
+	releaseChannel := conf.UpdateBranch
 	const retries = 10
 	const delay = time.Second
 	url := globalConfig.UpdateUrl
+	var fetchedVersion structs.Version
 	for i := 0; i < retries; i++ {
 		resp, err := http.Get(url)
 		if err != nil {
@@ -238,6 +205,7 @@ func CheckVersion() (structs.Version, bool) {
 				time.Sleep(delay)
 				continue
 			} else {
+				VersionServerReady = false
 				return VersionInfo, false
 			}
 		}
@@ -251,11 +219,12 @@ func CheckVersion() (structs.Version, bool) {
 				time.Sleep(delay)
 				continue
 			} else {
+				VersionServerReady = false
 				return VersionInfo, false
 			}
 		}
 		// unmarshal values into Version struct
-		err = json.Unmarshal(body, &VersionInfo)
+		err = json.Unmarshal(body, &fetchedVersion)
 		if err != nil {
 			errmsg := fmt.Sprintf("Error unmarshalling JSON: %v", err)
 			logger.Warn(errmsg)
@@ -263,38 +232,46 @@ func CheckVersion() (structs.Version, bool) {
 				time.Sleep(delay)
 				continue
 			} else {
+				VersionServerReady = false
 				return VersionInfo, false
 			}
 		}
-		// debug: re-marshal and write to disk
+		VersionInfo = fetchedVersion.Groundseg[releaseChannel]
+		// debug: re-marshal and write the entire fetched version to disk
 		confPath := filepath.Join(BasePath, "settings", "version_info.json")
 		file, err := os.Create(confPath)
 		if err != nil {
 			errmsg := fmt.Sprintf("Failed to create file: %v", err)
 			logger.Error(errmsg)
+			VersionServerReady = false
 			return VersionInfo, false
 		}
 		defer file.Close()
 		encoder := json.NewEncoder(file)
 		encoder.SetIndent("", "    ")
-		if err := encoder.Encode(&VersionInfo); err != nil {
+		if err := encoder.Encode(&fetchedVersion); err != nil {
 			errmsg := fmt.Sprintf("Failed to write JSON: %v", err)
 			logger.Error(errmsg)
 		}
+		VersionServerReady = true
 		return VersionInfo, true
 	}
+	VersionServerReady = false
 	return VersionInfo, false
 }
 
 func CheckVersionLoop() {
 	ticker := time.NewTicker(checkInterval)
+	conf := Conf()
+	releaseChannel := conf.UpdateBranch
 	for {
 		select {
 		case <-ticker.C:
 			latestVersion, _ := CheckVersion()
-			currentVersion := VersionInfo
-			if latestVersion != currentVersion {
-				fmt.Printf("New version available! Current: %s, Latest: %s\n", currentVersion, latestVersion)
+			currentChannelVersion := VersionInfo
+			latestChannelVersion := latestVersion
+			if latestChannelVersion != currentChannelVersion {
+				fmt.Printf("New version available in %s channel! Current: %+v, Latest: %+v\n", releaseChannel, currentChannelVersion, latestChannelVersion)
 				VersionInfo = latestVersion
 				// Handle the update logic here
 			}

+ 27 - 6
config/wireguard.go

@@ -2,19 +2,40 @@ package config
 
 import (
 	"encoding/json"
+	"goseg/defaults"
 	"goseg/structs"
 	"os"
 	"path/filepath"
 )
 
-// write a conf to disk
+// write a hardcoded default conf to disk
 func CreateDefaultWGConf() error {
+	defaultConfig := defaults.WgConfig
+	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
+}
+
+// write a conf to disk from version server info
+func UpdateWGConf() 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{
+	wgRepo := VersionInfo.Wireguard.Repo
+	amdHash := VersionInfo.Wireguard.Amd64Sha256
+	armHash := VersionInfo.Wireguard.Arm64Sha256
+	newConfig := structs.WgConfig{
 		WireguardName:    "wireguard",
 		WireguardVersion: releaseChannel,
 		Repo:             wgRepo,
@@ -39,7 +60,7 @@ func CreateDefaultWGConf() error {
 	defer file.Close()
 	encoder := json.NewEncoder(file)
 	encoder.SetIndent("", "    ")
-	if err := encoder.Encode(&defaultConfig); err != nil {
+	if err := encoder.Encode(&newConfig); err != nil {
 		return err
 	}
 	return nil

+ 1 - 1
docker/docker.go

@@ -109,7 +109,7 @@ func GetContainerStats(containerName string) (structs.ContainerStats, error) {
 	}, nil
 }
 
-// start a container by name + tag
+// start a container by name + type
 // not for booting new ships
 func StartContainer(containerName string, containerType string) (structs.ContainerState, error) {
 	var containerState structs.ContainerState

+ 9 - 5
docker/urbit.go

@@ -17,12 +17,16 @@ func LoadUrbits() error {
 			logger.Error(fmt.Sprintf("Error loading %s config: %v", pier, err))
 			continue
 		}
-		info, err := StartContainer(pier, "vere")
-		if err != nil {
-			logger.Error(fmt.Sprintf("Error starting %s: %v", pier, err))
-			continue
+		shipConf := config.UrbitConf(pier)
+		// don't bootstrap if it's busted
+		if shipConf.BootStatus != "noboot" {
+			info, err := StartContainer(pier, "vere")
+			if err != nil {
+				logger.Error(fmt.Sprintf("Error starting %s: %v", pier, err))
+				continue
+			}
+			config.UpdateContainerState(pier, info)
 		}
-		config.UpdateContainerState(pier, info)
 	}
 	return nil
 }

+ 1 - 1
main.go

@@ -22,7 +22,7 @@ import (
 // Under development: reimplementing all pyseg functionality.
 // Advantages:
 // - Really, really fast
-// - Event-driven rather than cron poll-driven
+// - Event-driven
 // - First-class support for concurrent operations
 // - Very good golang Docker libraries
 

+ 22 - 5
structs/structs.go

@@ -92,11 +92,7 @@ type LoginKeys struct {
 
 // version server payload root struct
 type Version struct {
-	Groundseg struct {
-		Canary Channel `json:"canary"`
-		Edge   Channel `json:"edge"`
-		Latest Channel `json:"latest"`
-	} `json:"groundseg"`
+	Groundseg map[string]Channel `json:"groundseg"`
 }
 
 // version server payload substruct
@@ -311,3 +307,24 @@ type WgConfig struct {
 		NetIpv4ConfAllSrcValidMark int `json:"net.ipv4.conf.all.src_valid_mark"`
 	} `json:"sysctls"`
 }
+
+type McConfig struct {
+	McName      string `json:"mc_name"`
+	McVersion   string `json:"mc_version"`
+	Repo        string `json:"repo"`
+	Amd64Sha256 string `json:"amd64_sha256"`
+	Arm64Sha256 string `json:"arm64_sha256"`
+}
+
+type NetdataConfig struct {
+	NetdataName    string   `json:"netdata_name"`
+	Repo           string   `json:"repo"`
+	NetdataVersion string   `json:"netdata_version"`
+	Amd64Sha256    string   `json:"amd64_sha256"`
+	Arm64Sha256    string   `json:"arm64_sha256"`
+	CapAdd         []string `json:"cap_add"`
+	Port           int      `json:"port"`
+	Restart        string   `json:"restart"`
+	SecurityOpt    string   `json:"security_opt"`
+	Volumes        []string `json:"volumes"`
+}