reid 2 anni fa
parent
commit
6f7721f44d
5 ha cambiato i file con 457 aggiunte e 80 eliminazioni
  1. 224 0
      config/config.go
  2. 93 0
      main-old.go
  3. 32 80
      main.go
  4. 2 0
      setup/setup.go
  5. 106 0
      structs/structs.go

+ 224 - 0
config/config.go

@@ -0,0 +1,224 @@
+package config
+
+import (
+	"encoding/json"
+	"goseg/structs"
+	"log/slog"
+	"os"
+	"path/filepath"
+	"sync"
+	"net/http"
+	"io/ioutil"
+	"net"
+	"time"
+	"fmt"
+)
+
+var (
+	globalConfig 	  structs.SysConfig
+	logger            = slog.New(slog.NewJSONHandler(os.Stdout, nil))
+	basePath		  = "/home/nativeplanet/gits"
+	Version           = "v2.0.0"
+	Ready             = false
+	VersionServerReady = false
+	VersionInfo       structs.Version
+	Ram               int
+	Cpu               int
+	CoreTemp          int
+	Disk              int
+	WifiEnabled       = false
+	ActiveNetwork     string
+	WifiNetworks      []string
+	HttpOpen          = false
+	UploadSecret      string
+	confMutex		  sync.Mutex
+)
+
+
+func init() {
+	confPath := filepath.Join(basePath, "settings", "system2.json")
+	file, err := os.Open(confPath)
+	if err != nil {
+		err = createDefaultConf()
+		if err != nil {
+			logger.Error("Unable to create config!")
+		}
+	}
+	defer file.Close()
+	decoder := json.NewDecoder(file)
+	err = decoder.Decode(&globalConfig)
+	if err != nil {
+		logger.Error("Error decoding JSON: %v", err)
+	}
+}
+
+func Conf() structs.SysConfig {
+	return globalConfig
+}
+
+func UpdateConf(values map[string]interface{}) error {
+	confMutex.Lock()
+	defer confMutex.Unlock()
+	confPath := filepath.Join(basePath, "settings", "system2.json")
+	file, err := ioutil.ReadFile(confPath)
+	if err != nil {
+		logger.Error("Unable to load config")
+		return err
+	}
+	var configMap map[string]interface{}
+	if err := json.Unmarshal(file, &configMap); err != nil {
+		logger.Error("Error decoding JSON: %v", err)
+		return err
+	}
+	for key, value := range values {
+		configMap[key] = value
+	}
+	updatedJSON, err := json.Marshal(configMap)
+	if err != nil {
+		logger.Error("Error encoding JSON: %v", err)
+		return err
+	}
+	if err := json.Unmarshal(updatedJSON, &globalConfig); err != nil {
+		logger.Error("Error updating global config: %v", err)
+		return err
+	}
+	if err := ioutil.WriteFile(confPath, updatedJSON, 0644); err != nil {
+		logger.Error("Error writing to file: %v", err)
+		return err
+	}
+	return nil
+}
+
+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:    false,
+		WgRegisterd:  false,
+		GsVersion:    Version,
+		CfgDir:       "",
+		UpdateInterval: 0,
+		BinHash:      "",
+		Pubkey:       "",
+		Privkey:      "",
+		Salt:         "",
+	}
+	path := filepath.Join(basePath, "settings", "system2.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)
+	if err := encoder.Encode(&defaultConfig); err != nil {
+		return err
+	}
+	return nil
+}
+
+func NetCheck(netCheck string) bool {
+	logger.Info("Checking internet access")
+	internet := false
+	timeout := 3 * time.Second
+	conn, err := net.DialTimeout("tcp", netCheck, timeout)
+	if err != nil {
+		logger.Error("Check internet access error: %v\n", err)
+	} else {
+		internet = true
+		_ = conn.Close()
+		logger.Info("Internet connection is available!")
+	}
+	return internet
+}
+
+func CheckVersion() bool {
+	const retries = 10
+	const delay = time.Second
+	var version structs.Version
+	url := globalConfig.UpdateUrl
+	for i := 0; i < retries; i++ {
+		resp, err := http.Get(url)
+		if err != nil {
+			errmsg := fmt.Sprintf("Unable to connect to update server: %v", err)
+			logger.Warn(errmsg)
+			if i < retries-1 {
+				time.Sleep(delay)
+				continue
+			} else {
+				return false
+			}
+		}
+		body, err := ioutil.ReadAll(resp.Body)
+		resp.Body.Close()
+		if err != nil {
+			errmsg := fmt.Sprintf("Error reading version info: %v", err)
+			logger.Warn(errmsg)
+			if i < retries-1 {
+				time.Sleep(delay)
+				continue
+			} else {
+				return false
+			}
+		}
+		err = json.Unmarshal(body, &version)
+		if err != nil {
+			errmsg := fmt.Sprintf("Error unmarshalling JSON: %v", err)
+			logger.Warn(errmsg)
+			if i < retries-1 {
+				time.Sleep(delay)
+				continue
+			} else {
+				return false
+			}
+		}
+		versionUpdate := map[string]interface{}{
+			"VersionInfo": version,
+		}
+		err = UpdateConf(versionUpdate)
+		if err != nil {
+			errmsg := fmt.Sprintf("Error updating version config: %v", err)
+			logger.Warn(errmsg)
+			if i < retries-1 {
+				time.Sleep(delay)
+				continue
+			} else {
+				return false
+			}
+		}
+		return true
+	}
+	return false
+}

+ 93 - 0
main-old.go

@@ -0,0 +1,93 @@
+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)
+}

+ 32 - 80
main.go

@@ -1,93 +1,45 @@
 package main
 
 import (
-	"context"
+	"goseg/config"
+	"log/slog"
+	"os"
 	"fmt"
-	"github.com/docker/docker/api/types"
-	"github.com/docker/docker/client"
-	"sync"
-	"time"
 )
 
-// var counter int
-var lock sync.Mutex
+var (
+	logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
+)
 
-/*
-	{
-	  "<patp>":{
-	    "status":<container-status>
-	  }
+func main() {
+	for _, arg := range os.Args[1:] { 
+		if arg == "dev" {
+			logger.Info("Starting GroundSeg in debug mode")
+		}
 	}
-*/
-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)
+	logger.Info("Starting GroundSeg")
+	logger.Info("Urbit is love <3")
+	conf := config.Conf()
+	internetAvailable := config.NetCheck("1.1.1.1:53")
+	availMsg := fmt.Sprintf("Internet available: %t",internetAvailable)
+	logger.Info(availMsg)
+	versionUpdateChannel := make(chan bool)
+	if conf.UpdateMode == "auto" {
+		go func() {
+			versionUpdate := config.CheckVersion()
+			versionUpdateChannel <- versionUpdate
+		}()
 	}
-}
-
-// 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
-						}
-					}
-				}
-			}
+	if conf.UpdateMode == "auto" {
+		versionUpdate := <-versionUpdateChannel
+		if versionUpdate {
+			logger.Info("Version info retrieved")
+			fmt.Println(config.GsVersion)
 		}
-
-		// 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)
+	var pierList string
+	for _, pier := range conf.Piers {
+		pierList = pierList + ", " + pier
 	}
-
-	// Waiting for the goroutines to complete
-	var input string
-	fmt.Scanln(&input)
+	logger.Info(pierList)
 }

+ 2 - 0
setup/setup.go

@@ -0,0 +1,2 @@
+package setup
+

+ 106 - 0
structs/structs.go

@@ -0,0 +1,106 @@
+package structs
+
+import (
+	"time"
+)
+
+type SessionInfo struct {
+	Hash    string `json:"hash"`
+	Created string `json:"created"`
+}
+
+type SysConfig struct {
+	Setup        string   `json:"setup"`
+	EndpointUrl  string   `json:"endpointUrl"`
+	ApiVersion   string   `json:"apiVersion"`
+	Piers        []string `json:"piers"`
+	NetCheck     string   `json:"netCheck"`
+	UpdateMode   string   `json:"updateMode"`
+	UpdateUrl    string   `json:"updateUrl"`
+	UpdateBranch string   `json:"updateBranch"`
+	SwapVal      int      `json:"swapVal"`
+	SwapFile     string   `json:"swapFile"`
+	KeyFile      string   `json:"keyFile"`
+	Sessions struct {
+		Authorized   map[string]SessionInfo `json:"authorized"`
+		Unauthorized map[string]SessionInfo `json:"unauthorized"`
+	} `json:"sessions"`
+	LinuxUpdates struct {
+		Value    int    `json:"value"`
+		Interval string `json:"interval"`
+		Previous bool   `json:"previous"`
+	} `json:"linuxUpdates"`
+	DockerData     string `json:"dockerData"`
+	WgOn           bool   `json:"wgOn"`
+	WgRegistered   bool   `json:"wgRegistered"`
+	PwHash         string `json:"pwHash"`
+	C2cInterval    int    `json:"c2cInterval"`
+	FirstBoot      bool   `json:"firstBoot"`
+	WgRegisterd    bool   `json:"wgRegisterd"`
+	GsVersion      string `json:"gsVersion"`
+	CfgDir         string `json:"CFG_DIR"`
+	UpdateInterval int    `json:"updateInterval"`
+	BinHash        string `json:"binHash"`
+	Pubkey         string `json:"pubkey"`
+	Privkey        string `json:"privkey"`
+	Salt           string `json:"salt"`
+}
+
+type LoginStatus struct {
+	Locked		bool
+	End			time.Time
+	Attempts	int	
+}
+
+type LoginKeys struct {
+	Old	struct {
+		Pub 	string
+		Priv	string
+	}
+	Cur struct {
+		Pub		string
+		Priv	string
+	}
+}
+
+type Version struct {
+	Groundseg struct {
+		Canary Channel `json:"canary"`
+		Edge   Channel `json:"edge"`
+		Latest Channel `json:"latest"`
+	} `json:"groundseg"`
+}
+
+type Channel struct {
+	Groundseg Component `json:"groundseg"`
+	Manual    Component `json:"manual"`
+	Minio     Component `json:"minio"`
+	Miniomc   Component `json:"miniomc"`
+	Netdata   Component `json:"netdata"`
+	Vere      Component `json:"vere"`
+	Webui     Component `json:"webui"`
+	Wireguard Component `json:"wireguard"`
+}
+
+type Component struct {
+	Groundseg VersionDetails `json:"groundseg"`
+	Manual    VersionDetails `json:"manual"`
+	Minio     VersionDetails `json:"minio"`
+	Miniomc   VersionDetails `json:"miniomc"`
+	Netdata   VersionDetails `json:"netdata"`
+	Vere      VersionDetails `json:"vere"`
+	Webui     VersionDetails `json:"webui"`
+	Wireguard VersionDetails `json:"wireguard"`
+}
+
+type VersionDetails struct {
+	Amd64Sha256 string `json:"amd64_sha256"`
+	Amd64URL    string `json:"amd64_url,omitempty"`
+	Arm64Sha256 string `json:"arm64_sha256"`
+	Arm64URL    string `json:"arm64_url,omitempty"`
+	Major       int    `json:"major,omitempty"`
+	Minor       int    `json:"minor,omitempty"`
+	Patch       int    `json:"patch,omitempty"`
+	Repo        string `json:"repo,omitempty"`
+	Tag         string `json:"tag,omitempty"`
+}