package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strconv" "strings" "time" "golang.org/x/crypto/ssh" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" metrics "k8s.io/metrics/pkg/client/clientset/versioned" "gopkg.in/yaml.v3" ) // Node and NodePool structs type Node struct { Name string `yaml:"name" json:"name"` IP string `yaml:"ip" json:"ip"` Status string `yaml:"status" json:"status"` CPU int `yaml:"cpu" json:"cpu"` Memory int `yaml:"memory" json:"memory"` Role string `yaml:"role" json:"role"` Cluster string `yaml:"cluster" json:"cluster"` LastActive string `yaml:"last_active" json:"last_active"` Pods int `yaml:"pods,omitempty" json:"pods,omitempty"` Temperature float64 `yaml:"temperature,omitempty" json:"temperature,omitempty"` } type NodePool struct { Nodes []Node `yaml:"nodes" json:"nodes"` } // --- ENV helpers --- func mustIntEnv(name string, def int) int { if val := os.Getenv(name); val != "" { if i, err := strconv.Atoi(val); err == nil { return i } } return def } func mustEnv(key, def string) string { if val := os.Getenv(key); val != "" { return val } return def } // --- YAML load/save --- func loadPool(file string) (*NodePool, error) { data, err := ioutil.ReadFile(file) if err != nil { return nil, err } var pool NodePool err = yaml.Unmarshal(data, &pool) if err != nil { return nil, err } return &pool, nil } func savePool(file string, pool *NodePool) error { data, err := yaml.Marshal(pool) if err != nil { return err } return ioutil.WriteFile(file, data, 0644) } func initNodePool(clientset *kubernetes.Clientset, poolFile string) error { ctx := context.Background() // Load pool from file — fail if cannot read pool, err := loadPool(poolFile) if err != nil { return fmt.Errorf("cannot load existing node pool file %q: %w", poolFile, err) } // Map current cluster nodes for quick lookup clusterNodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err != nil { return fmt.Errorf("failed to list nodes: %w", err) } clusterMap := map[string]v1.Node{} for _, n := range clusterNodes.Items { clusterMap[n.Name] = n } // 🟧 Update pool in place, preserving order for i := range pool.Nodes { n := &pool.Nodes[i] if kn, ok := clusterMap[n.Name]; ok { // Update only cluster nodes n.IP = nodeIP(&kn) n.Status = "online" n.Cluster = os.Getenv("CLUSTER_NAME") n.LastActive = time.Now().Format(time.RFC3339) if isControlPlane(&kn) { n.Role = "microk8s-controlplane" } else { n.Role = "worker" } // Preserve CPU, Memory, Pods, Temperature if previously set } // else: node not in cluster → leave everything untouched } // Save back to disk return savePool(poolFile, pool) } // --- SSH --- func runSSH(host, user, pass, cmd string) (string, error) { config := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.Password(pass)}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), Timeout: 10 * time.Second, } client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", host), config) if err != nil { return "", err } defer client.Close() session, err := client.NewSession() if err != nil { return "", err } defer session.Close() out, err := session.CombinedOutput(cmd) return string(out), err } // --- Node helpers --- func isControlPlane(n *v1.Node) bool { if _, ok := n.Labels["node.kubernetes.io/microk8s-controlplane"]; ok { return true } if _, ok := n.Labels["node-role.kubernetes.io/control-plane"]; ok { return true } return false } func nodeIP(n *v1.Node) string { for _, addr := range n.Status.Addresses { if addr.Type == v1.NodeInternalIP { return addr.Address } } return "" } // --- Utilization --- // --- Utilization --- // updateNodePoolupdates CPU, Memory, Pods, Temperature, Status, and Role // only for nodes present in the current Kubernetes cluster. // Nodes not in the cluster remain untouched. func updateNodePool(clientset *kubernetes.Clientset, metricsClient *metrics.Clientset, poolFile, sshUser, sshPass string) error { ctx := context.Background() // 1️⃣ Load the pool file from disk pool, err := loadPool(poolFile) if err != nil { return fmt.Errorf("failed to load node pool: %w", err) } // 2️⃣ List cluster nodes clusterNodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err != nil { return fmt.Errorf("failed to list cluster nodes: %w", err) } // Map cluster nodes for quick lookup clusterMap := map[string]*v1.Node{} for i := range clusterNodes.Items { clusterMap[clusterNodes.Items[i].Name] = &clusterNodes.Items[i] } // 3️⃣ List metrics metricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{}) if err != nil { return fmt.Errorf("failed to get node metrics: %w", err) } usageCPU := map[string]int64{} usageMem := map[string]int64{} for _, m := range metricsList.Items { usageCPU[m.Name] = m.Usage.Cpu().MilliValue() usageMem[m.Name] = m.Usage.Memory().Value() } // Node capacities capCPU := map[string]int64{} capMem := map[string]int64{} for _, n := range clusterNodes.Items { capCPU[n.Name] = n.Status.Capacity.Cpu().MilliValue() capMem[n.Name] = n.Status.Capacity.Memory().Value() } // Pods per node pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{}) if err != nil { return err } podCount := map[string]int{} for _, p := range pods.Items { if p.Spec.NodeName != "" { podCount[p.Spec.NodeName]++ } } // 4️⃣ Update pool in place for i := range pool.Nodes { n := &pool.Nodes[i] if kn, ok := clusterMap[n.Name]; ok { // Update CPU and Memory % if cpuCap, ok1 := capCPU[n.Name]; ok1 { if memCap, ok2 := capMem[n.Name]; ok2 { if cpuUse, ok3 := usageCPU[n.Name]; ok3 { if memUse, ok4 := usageMem[n.Name]; ok4 { if cpuCap > 0 && memCap > 0 { n.CPU = int((cpuUse * 100) / cpuCap) n.Memory = int((memUse * 100) / memCap) } } } } } // Update pod count n.Pods = podCount[n.Name] // Update temperature via SSH n.Temperature = getNodeTemp(kn, sshUser, sshPass) // Update status/role/cluster/last_active n.Status = "online" n.Cluster = os.Getenv("CLUSTER_NAME") n.LastActive = time.Now().Format(time.RFC3339) if isControlPlane(kn) { n.Role = "microk8s-controlplane" } else { n.Role = "worker" } } // else: node not in cluster → leave all fields untouched } // 5️⃣ Save pool back to disk return savePool(poolFile, pool) } // --- Temperature --- func getNodeTemp(node *v1.Node, sshUser, sshPass string) float64 { ip := nodeIP(node) out, err := runSSH(ip, sshUser, sshPass, "cat /proc/device-tree/model") if err != nil { log.Printf("getNodeTemp: failed to read model from %s: %v", ip, err) return 0 } hw := strings.ToUpper(strings.TrimSpace(out)) var cmd string switch { case strings.Contains(hw, "RASPBERRY"): cmd = "vcgencmd measure_temp | egrep -o '[0-9]+\\.[0-9]+'" case strings.Contains(hw, "ODROID"): cmd = "awk '{printf \"%3.1f\", $1/1000}' /sys/class/thermal/thermal_zone0/temp" default: return 0 } tempStr, err := runSSH(ip, sshUser, sshPass, cmd) if err != nil { log.Printf("getNodeTemp: failed to read temperature from %s: %v", ip, err) return 0 } t, err := strconv.ParseFloat(strings.TrimSpace(tempStr), 64) if err != nil { return 0 } return t } // --- Control-plane management --- func ensureControlPlanes(cs *kubernetes.Clientset, poolFile, sshUser, sshPass, clusterName string, desired int) { // Load the current node pool from disk pool, err := loadPool(poolFile) if err != nil { log.Println("Cannot load pool in ensureControlPlanes:", err) return } ctx := context.Background() // List nodes currently in this Kubernetes cluster nodes, err := cs.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err != nil { log.Println("failed to list nodes:", err) return } // Count current control-plane nodes cpCount := 0 var seedIP string for _, n := range nodes.Items { if isControlPlane(&n) { cpCount++ if seedIP == "" { seedIP = nodeIP(&n) } } } // Nothing to do if enough control-planes if cpCount >= desired { return } if seedIP == "" { log.Println("no available control-plane node found") return } // Find an offline node in the pool to activate for i := range pool.Nodes { n := &pool.Nodes[i] if n.Status != "offline" { continue } log.Printf("Attempting to activate node %s as control-plane", n.Name) // Generate join command from seed control-plane out, err := runSSH(seedIP, sshUser, sshPass, "microk8s add-node") if err != nil { log.Println("add-node failed:", err) return } var joinCmd string for _, line := range strings.Split(out, "\n") { if strings.HasPrefix(strings.TrimSpace(line), "microk8s join") { joinCmd = strings.TrimSpace(line) break } } if joinCmd == "" { log.Println("no join command found") return } // Run join on offline node _, err = runSSH(n.IP, sshUser, sshPass, joinCmd) if err != nil { log.Println("join failed:", err) return } // Update node in pool n.Status = "online" n.Cluster = clusterName n.Role = "microk8s-controlplane" n.LastActive = time.Now().Format(time.RFC3339) log.Printf("Control-plane %s activated", n.Name) // Save back updated pool to disk if err := savePool(poolFile, pool); err != nil { log.Println("Failed to save pool after activating control-plane:", err) } return } } // --- Worker management --- func activateOneWorker(cs *kubernetes.Clientset, pool *NodePool, poolFile, sshUser, sshPass, clusterName string) { ctx := context.Background() var workerNode *Node for i := range pool.Nodes { n := &pool.Nodes[i] if n.Status == "offline" { workerNode = &pool.Nodes[i] break } } if workerNode == nil { log.Println("No offline nodes available — skipping activation") return } log.Printf("Attempting to activate %s node as worker node", workerNode.Name) nodes, err := cs.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err != nil { log.Println("Failed to list nodes:", err) return } var seedIP string for _, n := range nodes.Items { if isControlPlane(&n) { seedIP = nodeIP(&n) break } } if seedIP == "" { log.Println("No control-plane node available to generate join command") return } out, err := runSSH(seedIP, sshUser, sshPass, "microk8s add-node") if err != nil { log.Println("add-node failed:", err) return } var joinCmd string for _, line := range strings.Split(out, "\n") { if strings.HasPrefix(strings.TrimSpace(line), "microk8s join") { joinCmd = strings.TrimSpace(line) break } } if joinCmd == "" { log.Println("No join command found from seed control-plane") return } joinCmd += " --worker" _, err = runSSH(workerNode.IP, sshUser, sshPass, joinCmd) if err != nil { log.Println("Worker join failed:", err) return } workerNode.Status = "online" workerNode.Cluster = clusterName workerNode.Role = "worker" workerNode.LastActive = time.Now().Format(time.RFC3339) log.Printf("Node %s successfully activated as worker node", workerNode.Name) } func deactivateOneWorkerSafe(cs *kubernetes.Clientset, pool *NodePool, poolFile, sshUser, sshPass, clusterName string, waitSec int) { ctx := context.Background() nodes, err := cs.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err != nil { log.Println("failed to list nodes:", err) return } var workerNode *v1.Node for _, n := range nodes.Items { if !isControlPlane(&n) && !n.Spec.Unschedulable { workerNode = &n break } } if workerNode == nil { log.Println("No worker nodes available for deactivation") return } log.Printf("Deactivating node: %s", workerNode.Name) ip := nodeIP(workerNode) patch := []byte(`{"spec":{"unschedulable":true}}`) _, err = cs.CoreV1().Nodes().Patch(ctx, workerNode.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{}) if err != nil { log.Println("Failed to cordon node:", err) return } err = drainNode(cs, workerNode.Name) if err != nil { log.Println("Drain failed, uncordoning node") patch = []byte(`{"spec":{"unschedulable":false}}`) _, _ = cs.CoreV1().Nodes().Patch(ctx, workerNode.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{}) return } _, err = runSSH(ip, sshUser, sshPass, "microk8s leave") if err != nil { log.Println("microk8s leave failed, keeping node object in cluster") return } _ = cs.CoreV1().Nodes().Delete(ctx, workerNode.Name, metav1.DeleteOptions{}) for i := range pool.Nodes { if pool.Nodes[i].Name == workerNode.Name { pool.Nodes[i].Status = "offline" pool.Nodes[i].Cluster = "none" pool.Nodes[i].Role = "none" pool.Nodes[i].CPU = 0 pool.Nodes[i].Memory = 0 pool.Nodes[i].LastActive = time.Now().Format(time.RFC3339) } } } // --- Drain node --- func drainNode(cs *kubernetes.Clientset, nodeName string) error { ctx := context.Background() pods, err := cs.CoreV1().Pods("").List(ctx, metav1.ListOptions{ FieldSelector: fmt.Sprintf("spec.nodeName=%s", nodeName), }) if err != nil { return err } for _, pod := range pods.Items { if _, ok := pod.ObjectMeta.Annotations["kubernetes.io/config.mirror"]; ok { continue } if pod.Namespace == "kube-system" { continue } grace := int64(60) _ = cs.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{ GracePeriodSeconds: &grace, }) } for { remaining, _ := cs.CoreV1().Pods("").List(ctx, metav1.ListOptions{ FieldSelector: fmt.Sprintf("spec.nodeName=%s", nodeName), }) active := 0 for _, p := range remaining.Items { if p.Namespace != "kube-system" && p.DeletionTimestamp == nil { active++ } } if active == 0 { break } time.Sleep(5 * time.Second) } return nil } // --- Cluster utilization --- func clusterUtilization(cs *kubernetes.Clientset, ms *metrics.Clientset) (cpuPct int, memPct int, err error) { ctx := context.Background() nodes, err := cs.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) if err != nil { return 0, 0, err } metricsList, err := ms.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{}) if err != nil { return 0, 0, err } var totalCPUCap, totalMemCap, totalCPUUse, totalMemUse int64 for _, n := range nodes.Items { totalCPUCap += n.Status.Capacity.Cpu().MilliValue() totalMemCap += n.Status.Capacity.Memory().Value() } for _, m := range metricsList.Items { totalCPUUse += m.Usage.Cpu().MilliValue() totalMemUse += m.Usage.Memory().Value() } cpuPct = int((totalCPUUse * 100) / totalCPUCap) memPct = int((totalMemUse * 100) / totalMemCap) return cpuPct, memPct, nil } // --- Web GUI --- // startWebGUI starts a simple HTTP server showing the node pool func startWebGUI(poolFile string) { // API endpoint for JSON status http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) { pool, err := loadPool(poolFile) // always fresh from disk if err != nil { log.Println("Cannot load node pool:", err) http.Error(w, "cannot load node pool", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(pool) }) // Serve index.html and static assets (single file) http.Handle("/", http.FileServer(http.Dir("/app/web"))) go func() { log.Println("Web GUI running at :8080") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } }() } // --- Main --- func main() { poolFile := mustEnv("NODE_POOL_FILE", "node-pool.yaml") sshUser := mustEnv("SSH_USER", "ubuntu") sshPass := mustEnv("SSH_PASS", "") // read thresholds from environment minCPU := mustIntEnv("MIN_CPU", 40) minMem := mustIntEnv("MIN_MEM", 50) maxCPU := mustIntEnv("MAX_CPU", 90) maxMem := mustIntEnv("MAX_MEM", 90) clusterName := mustEnv("CLUSTER_NAME", "cluster1") desiredCP := mustIntEnv("DESIRED_CONTROLPLANES", 1) // Kubernetes client config, err := rest.InClusterConfig() if err != nil { log.Fatal("Cannot create in-cluster config:", err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { log.Fatal("Cannot create clientset:", err) } metricsClient, err := metrics.NewForConfig(config) if err != nil { log.Fatal("Cannot create metrics client:", err) } // Web GUI startWebGUI(poolFile) // Main control loop for { // Always load pool fresh from disk pool, err := loadPool(poolFile) if err != nil { log.Println("Cannot load node pool:", err) time.Sleep(10 * time.Second) continue } // Update ONLY nodes that exist in THIS cluster err = updateNodePool( clientset, metricsClient, poolFile, sshUser, sshPass, ) if err != nil { log.Println("updateNodePool error:", err) } // Ensure control-plane count ensureControlPlanes( clientset, poolFile, sshUser, sshPass, clusterName, desiredCP, ) // inside the main loop, after computing cluster utilization cpuPct, memPct, err := clusterUtilization(clientset, metricsClient) if err == nil { log.Printf("Cluster utilization: CPU %d%%, MEM %d%%", cpuPct, memPct) // decide worker activation/deactivation based on thresholds if cpuPct > maxCPU || memPct > maxMem { activateOneWorker(clientset, pool, poolFile, sshUser, sshPass, clusterName) } else if cpuPct < minCPU && memPct < minMem { deactivateOneWorkerSafe(clientset, pool, poolFile, sshUser, sshPass, clusterName, 60) } } // Cluster-wide utilization (read-only) cpuPct, memPct, err = clusterUtilization(clientset, metricsClient) if err == nil { log.Printf( "Cluster utilization: CPU %d%%, MEM %d%%", cpuPct, memPct, ) } // 💾 Persist pool back to disk (ALL nodes preserved) if err := savePool(poolFile, pool); err != nil { log.Println("Failed to save node pool:", err) } time.Sleep(10 * time.Second) } }