瀏覽代碼

work on sub handler

reid 2 年之前
父節點
當前提交
1956023501
共有 6 個文件被更改,包括 103 次插入37 次删除
  1. 1 9
      config/config.go
  2. 14 0
      docker/docker.go
  3. 1 1
      main.go
  4. 38 12
      rectify/rectify.go
  5. 48 15
      structs/structs.go
  6. 1 0
      system/system.go

+ 1 - 9
config/config.go

@@ -24,15 +24,7 @@ var (
 	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
+	GSContainers = make(map[string]structs.ContainerState)
 	checkInterval      = 5 * time.Minute
 	confMutex          sync.Mutex
 	versMutex          sync.Mutex

+ 14 - 0
docker/docker.go

@@ -9,6 +9,7 @@ import (
 	"log/slog"
 	"os"
 	"strings"
+	"time"
 
 	"github.com/docker/docker/api/types"
 	"github.com/docker/docker/client"
@@ -318,3 +319,16 @@ func DockerListener() {
 		}
 	}
 }
+
+func DockerPoller() {
+	ticker := time.NewTicker(10 * time.Second)
+	for {
+		select {
+		case <-ticker.C:
+			logger.Info("polling docker")
+			// fetch the status of all containers and compare with app's state
+			// if there's a change, send an event to the EventBus
+			return
+		}
+	}
+}

+ 1 - 1
main.go

@@ -57,7 +57,7 @@ func main() {
 	// listen to docker daemon
 	go docker.DockerListener()
 	// digest docker events from eventbus
-	go rectify.HandleDockerEvents()
+	go rectify.DockerSubscriptionHandler()
 	// just making sure we can parse (debug)
 	var pierList string
 	for _, pier := range conf.Piers {

+ 38 - 12
rectify/rectify.go

@@ -5,24 +5,50 @@ package rectify
 import (
 	"fmt"
 	"goseg/broadcast"
+	"goseg/config"
 	"goseg/docker"
 	"log/slog"
 	"os"
+
+	"github.com/docker/docker/api/types/events"
 )
 
 var (
 	logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
 )
 
-func HandleDockerEvents() {
-	for {
-		event := <-docker.EventBus
-		switch event.Type {
-		case "container_stopped":
-			logger.Info(fmt.Sprintf("Docker event: container stopped"))
-		default:
-			logger.Info(fmt.Sprintf("Docker event: %s",event.Type))
-		}
-		broadcast.BroadcastToClients()
-	}
-}
+func DockerSubscriptionHandler() {
+    for {
+        event := <-docker.EventBus
+        dockerEvent, ok := event.Data.(events.Message)  // assert the type
+        if !ok {
+            logger.Error("Failed to assert Docker event data type")
+            continue
+        }
+        switch dockerEvent.Action {
+        case "stop":
+            contID := dockerEvent.Actor.ID
+            contName := dockerEvent.Actor.Attributes["name"]
+            logger.Info(fmt.Sprintf("Docker: %s stopped", contName))
+            
+            if containerState, exists := config.GSContainers[contID]; exists {
+                containerState.Status = "stopped"
+                config.GSContainers[contID] = containerState
+            }
+
+        case "start":
+            contID := dockerEvent.Actor.ID
+            contName := dockerEvent.Actor.Attributes["name"]
+            logger.Info(fmt.Sprintf("Docker: %s started", contName))
+            
+            if containerState, exists := config.GSContainers[contID]; exists {
+                containerState.Status = "started"
+                config.GSContainers[contID] = containerState
+            }
+
+        default:
+            logger.Info(fmt.Sprintf("Docker event: %s", dockerEvent.Action))
+        }
+        broadcast.BroadcastToClients()
+    }
+}

+ 48 - 15
structs/structs.go

@@ -4,21 +4,34 @@ import (
 	"time"
 )
 
+// incoming websocket payloads
 type WsPayload struct {
 	Type   string `json:"type"`
 	Action string `json:"action"`
 }
 
+// eventbus event payloads
 type Event struct {
 	Type string
 	Data interface{}
 }
 
+// for keeping track of container desired/actual state
+type ContainerState struct {
+    ID        string
+    Name      string
+    Image     string
+    Status    string
+    CreatedAt time.Time
+}
+
+// authenticated browser sessions
 type SessionInfo struct {
 	Hash    string `json:"hash"`
 	Created string `json:"created"`
 }
 
+// system.json config struct
 type SysConfig struct {
 	Setup        string   `json:"setup"`
 	EndpointUrl  string   `json:"endpointUrl"`
@@ -56,12 +69,14 @@ type SysConfig struct {
 	Salt           string `json:"salt"`
 }
 
+// broadcast subobject
 type LoginStatus struct {
 	Locked   bool
 	End      time.Time
 	Attempts int
 }
 
+// broadcast subobject
 type LoginKeys struct {
 	Old struct {
 		Pub  string
@@ -73,6 +88,7 @@ type LoginKeys struct {
 	}
 }
 
+// version server payload root struct
 type Version struct {
 	Groundseg struct {
 		Canary Channel `json:"canary"`
@@ -81,6 +97,7 @@ type Version struct {
 	} `json:"groundseg"`
 }
 
+// version server payload substruct
 type Channel struct {
 	Groundseg VersionDetails `json:"groundseg"`
 	Manual    VersionDetails `json:"manual"`
@@ -92,6 +109,7 @@ type Channel struct {
 	Wireguard VersionDetails `json:"wireguard"`
 }
 
+// version server payload substruct
 type VersionDetails struct {
 	Amd64Sha256 string `json:"amd64_sha256"`
 	Amd64URL    string `json:"amd64_url,omitempty"`
@@ -104,6 +122,18 @@ type VersionDetails struct {
 	Tag         string `json:"tag,omitempty"`
 }
 
+// broadcast payload object struct
+type AuthBroadcast struct {
+	Type      string           `json:"type"`
+	AuthLevel string           `json:"auth_level"`
+	Upload    Upload           `json:"upload"`
+	Logs      Logs             `json:"logs"`
+	System    SystemInfo       `json:"system"`
+	Profile   Profile          `json:"profile"`
+	Urbits    map[string]Urbit `json:"urbits"`
+}
+
+// broadcast payload subobject
 type SystemUsage struct {
 	RAM      []uint64 `json:"ram"`
 	CPU      int      `json:"cpu"`
@@ -112,6 +142,7 @@ type SystemUsage struct {
 	SwapFile int      `json:"swap"`
 }
 
+// broadcast payload subobject
 type SystemUpdates struct {
 	Linux struct {
 		State   string `json:"state"`
@@ -122,22 +153,26 @@ type SystemUpdates struct {
 	} `json:"linux"`
 }
 
+// broadcast payload subobject
 type SystemWifi struct {
 	Status   string   `json:"status"`
 	Active   string   `json:"active"`
 	Networks []string `json:"networks"`
 }
 
+// broadcast payload subobject
 type SystemInfo struct {
 	Usage   SystemUsage   `json:"usage"`
 	Updates SystemUpdates `json:"updates"`
 	Wifi    SystemWifi    `json:"wifi"`
 }
 
+// broadcast payload subobject
 type Profile struct {
 	Startram Startram `json:"startram"`
 }
 
+// broadcast payload subobject
 type Startram struct {
 	Info struct {
 		Registered bool                      `json:"registered"`
@@ -154,6 +189,7 @@ type Startram struct {
 	} `json:"transition"`
 }
 
+// broadcast payload subobject
 type Urbit struct {
 	Info struct {
 		Network          string `json:"network"`
@@ -176,6 +212,13 @@ type Urbit struct {
 	} `json:"transition"`
 }
 
+// used to construct broadcast pier info subobject
+type ContainerStats struct {
+	MemoryUsage uint64
+	DiskUsage   int64
+}
+
+// broadcast payload subobject
 type Logs struct {
 	Containers struct {
 		Wireguard struct {
@@ -188,16 +231,7 @@ type Logs struct {
 	} `json:"system"`
 }
 
-type AuthBroadcast struct {
-	Type      string           `json:"type"`
-	AuthLevel string           `json:"auth_level"`
-	Upload    Upload           `json:"upload"`
-	Logs      Logs             `json:"logs"`
-	System    SystemInfo       `json:"system"`
-	Profile   Profile          `json:"profile"`
-	Urbits    map[string]Urbit `json:"urbits"`
-}
-
+// broadcast payload subobject
 type Upload struct {
 	Status   string `json:"status"`
 	Size     int    `json:"size"`
@@ -205,6 +239,7 @@ type Upload struct {
 	Patp     any    `json:"patp"`
 }
 
+// broadcast payload subobject
 type UnauthBroadcast struct {
 	Type      string `json:"type"`
 	AuthLevel string `json:"auth_level"`
@@ -213,6 +248,7 @@ type UnauthBroadcast struct {
 	} `json:"login"`
 }
 
+// broadcast payload subobject
 type SetupBroadcast struct {
 	Type      string                    `json:"type"`
 	AuthLevel string                    `json:"auth_level"`
@@ -221,11 +257,13 @@ type SetupBroadcast struct {
 	Regions   map[string]StartramRegion `json:"regions"`
 }
 
+// startram region server subobject
 type StartramRegion struct {
 	Country string `json:"country"`
 	Desc    string `json:"desc"`
 }
 
+// pier json struct
 type UrbitDocker struct {
 	PierName         string `json:"pier_name"`
 	HTTPPort         int    `json:"http_port"`
@@ -258,8 +296,3 @@ type UrbitDocker struct {
 	DevMode          bool   `json:"dev_mode"`
 	Click            bool   `json:"click"`
 }
-
-type ContainerStats struct {
-	MemoryUsage uint64
-	DiskUsage   int64
-}

+ 1 - 0
system/system.go

@@ -1,4 +1,5 @@
 package system
+// for retrieving hw info and managing host
 
 import (
 	"fmt"