Compare commits

...

3 Commits

Author SHA1 Message Date
Paul Payne
77571e8062 ISOs need version AND schema 2025-11-08 22:23:57 +00:00
Paul Payne
7a4b283ebe Refactor node discovery command to accept subnet input and improve help documentation 2025-11-04 17:16:36 +00:00
Paul Payne
3f546053f7 Allow cancelling of node discovery. 2025-11-04 16:45:39 +00:00
2 changed files with 185 additions and 107 deletions

View File

@@ -26,9 +26,9 @@ var (
var isoListCmd = &cobra.Command{
Use: "list",
Short: "List all downloaded ISO images",
Long: `List all downloaded ISO images across all schematics with their versions and platforms.`,
Long: `List all downloaded ISO images with their schematic IDs, versions, and platforms.`,
RunE: func(cmd *cobra.Command, args []string) error {
resp, err := apiClient.Get("/api/v1/assets")
resp, err := apiClient.Get("/api/v1/pxe/assets")
if err != nil {
return err
}
@@ -37,9 +37,9 @@ var isoListCmd = &cobra.Command{
return printJSON(resp.Data)
}
schematics := resp.GetArray("schematics")
if len(schematics) == 0 {
fmt.Println("No ISOs found")
assets := resp.GetArray("assets")
if len(assets) == 0 {
fmt.Println("No assets found")
return nil
}
@@ -48,22 +48,21 @@ var isoListCmd = &cobra.Command{
SchematicID string
Version string
Platform string
Path string
Size int64
}
var isos []isoInfo
for _, schematic := range schematics {
if m, ok := schematic.(map[string]interface{}); ok {
for _, asset := range assets {
if m, ok := asset.(map[string]interface{}); ok {
schematicID := fmt.Sprintf("%v", m["schematic_id"])
assets := m["assets"]
if assetsList, ok := assets.([]interface{}); ok {
for _, asset := range assetsList {
if assetMap, ok := asset.(map[string]interface{}); ok {
version := fmt.Sprintf("%v", m["version"])
assetsList := m["assets"]
if assetsArray, ok := assetsList.([]interface{}); ok {
for _, assetItem := range assetsArray {
if assetMap, ok := assetItem.(map[string]interface{}); ok {
if assetType, _ := assetMap["type"].(string); assetType == "iso" {
if downloaded, _ := assetMap["downloaded"].(bool); downloaded {
path := fmt.Sprintf("%v", assetMap["path"])
version := extractVersion(path)
platform := extractPlatform(path)
size := int64(0)
if s, ok := assetMap["size"].(float64); ok {
@@ -74,7 +73,6 @@ var isoListCmd = &cobra.Command{
SchematicID: schematicID,
Version: version,
Platform: platform,
Path: path,
Size: size,
})
}
@@ -90,11 +88,11 @@ var isoListCmd = &cobra.Command{
return nil
}
fmt.Printf("%-10s %-10s %-66s %-10s\n", "VERSION", "PLATFORM", "SCHEMATIC ID", "SIZE")
fmt.Printf("%-66s %-10s %-10s %-10s\n", "SCHEMATIC ID", "VERSION", "PLATFORM", "SIZE")
fmt.Println("--------------------------------------------------------------------------------------------------------")
for _, iso := range isos {
sizeMB := float64(iso.Size) / 1024 / 1024
fmt.Printf("%-10s %-10s %-66s %.2f MB\n", iso.Version, iso.Platform, iso.SchematicID, sizeMB)
fmt.Printf("%-66s %-10s %-10s %.2f MB\n", iso.SchematicID, iso.Version, iso.Platform, sizeMB)
}
return nil
@@ -112,7 +110,6 @@ The ISO can be used to boot bare metal machines.`,
version := args[1]
payload := map[string]interface{}{
"version": version,
"platform": isoPlatform,
"asset_types": []string{"iso"},
}
@@ -121,12 +118,13 @@ The ISO can be used to boot bare metal machines.`,
payload["force"] = true
}
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/assets/%s/download", schematicID), payload)
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/pxe/assets/%s/%s/download", schematicID, version), payload)
if err != nil {
return err
}
fmt.Printf("Downloading ISO for schematic: %s\n", schematicID)
fmt.Printf("Downloading ISO:\n")
fmt.Printf(" Schematic: %s\n", schematicID)
fmt.Printf(" Version: %s\n", version)
fmt.Printf(" Platform: %s\n", isoPlatform)
@@ -139,17 +137,18 @@ The ISO can be used to boot bare metal machines.`,
}
var isoDeleteCmd = &cobra.Command{
Use: "delete <schematic-id>",
Short: "Delete a schematic and all its assets",
Long: `Delete a schematic and all its downloaded assets including ISOs.
Use: "delete <schematic-id> <version>",
Short: "Delete an asset and all its files",
Long: `Delete a specific schematic@version asset and all its downloaded files including ISOs.
This operation cannot be undone.`,
Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
schematicID := args[0]
version := args[1]
// Prompt for confirmation unless --force is used
if !isoForce {
fmt.Printf("Are you sure you want to delete schematic %s and all its assets? (yes/no): ", schematicID)
fmt.Printf("Are you sure you want to delete %s@%s and all its assets? (yes/no): ", schematicID, version)
reader := bufio.NewReader(cmd.InOrStdin())
response, err := reader.ReadString('\n')
if err != nil {
@@ -162,12 +161,12 @@ This operation cannot be undone.`,
}
}
resp, err := apiClient.Delete(fmt.Sprintf("/api/v1/assets/%s", schematicID))
resp, err := apiClient.Delete(fmt.Sprintf("/api/v1/pxe/assets/%s/%s", schematicID, version))
if err != nil {
return err
}
fmt.Printf("Schematic deleted: %s\n", schematicID)
fmt.Printf("Asset deleted: %s@%s\n", schematicID, version)
if msg := resp.GetString("message"); msg != "" {
fmt.Printf("Status: %s\n", msg)
}
@@ -177,13 +176,14 @@ This operation cannot be undone.`,
}
var isoInfoCmd = &cobra.Command{
Use: "info <schematic-id>",
Short: "Show detailed information about ISOs for a schematic",
Args: cobra.ExactArgs(1),
Use: "info <schematic-id> <version>",
Short: "Show detailed information about a specific asset",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
schematicID := args[0]
version := args[1]
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/assets/%s", schematicID))
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/pxe/assets/%s/%s", schematicID, version))
if err != nil {
return err
}
@@ -194,25 +194,15 @@ var isoInfoCmd = &cobra.Command{
fmt.Printf("Schematic ID: %s\n", resp.GetString("schematic_id"))
fmt.Printf("Version: %s\n", resp.GetString("version"))
if instances := resp.GetArray("instances"); len(instances) > 0 {
fmt.Printf("\nInstances using this schematic:\n")
for _, inst := range instances {
fmt.Printf(" - %s\n", inst)
}
}
fmt.Printf("Path: %s\n", resp.GetString("path"))
if assets := resp.GetArray("assets"); len(assets) > 0 {
fmt.Println("\nISO Images:")
hasISO := false
fmt.Println("\nAssets:")
for _, asset := range assets {
if a, ok := asset.(map[string]interface{}); ok {
if assetType, _ := a["type"].(string); assetType == "iso" {
hasISO = true
assetType, _ := a["type"].(string)
downloaded, _ := a["downloaded"].(bool)
path := fmt.Sprintf("%v", a["path"])
version := extractVersion(path)
platform := extractPlatform(path)
if downloaded {
size := int64(0)
@@ -220,38 +210,29 @@ var isoInfoCmd = &cobra.Command{
size = int64(s)
}
sizeMB := float64(size) / 1024 / 1024
fmt.Printf(" ✓ %s / %s (%.2f MB)\n", version, platform, sizeMB)
if assetType == "iso" {
platform := extractPlatform(path)
fmt.Printf(" ✓ ISO (%s): %.2f MB\n", platform, sizeMB)
} else {
fmt.Printf(" ✓ %s: %.2f MB\n", assetType, sizeMB)
}
fmt.Printf(" Path: %s\n", path)
} else {
fmt.Printf(" ✗ Not downloaded\n")
fmt.Printf(" ✗ %s: Not downloaded\n", assetType)
}
}
}
}
if !hasISO {
fmt.Println(" No ISO images found")
}
}
return nil
},
}
// extractVersion extracts version from ISO filename (e.g., "talos-v1.11.2-metal-amd64.iso" -> "v1.11.2")
func extractVersion(path string) string {
filename := filepath.Base(path)
re := regexp.MustCompile(`talos-(v\d+\.\d+\.\d+)-metal`)
matches := re.FindStringSubmatch(filename)
if len(matches) > 1 {
return matches[1]
}
return "unknown"
}
// extractPlatform extracts platform from ISO filename (e.g., "talos-v1.11.2-metal-amd64.iso" -> "amd64")
// extractPlatform extracts platform from filename (e.g., "metal-amd64.iso" -> "amd64")
func extractPlatform(path string) string {
filename := filepath.Base(path)
re := regexp.MustCompile(`-(amd64|arm64)\.iso$`)
re := regexp.MustCompile(`-(amd64|arm64)\.`)
matches := re.FindStringSubmatch(filename)
if len(matches) > 1 {
return matches[1]

View File

@@ -1,7 +1,11 @@
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/spf13/cobra"
@@ -14,27 +18,83 @@ var nodeCmd = &cobra.Command{
}
var nodeDiscoverCmd = &cobra.Command{
Use: "discover <ip>...",
Use: "discover [subnet]",
Short: "Discover nodes on network",
Long: "Discover nodes on the network by scanning the provided IP addresses or ranges",
Args: cobra.MinimumNArgs(1),
Long: `Discover nodes on the network by scanning a subnet or auto-detecting local networks.
If a subnet is provided (e.g., 192.168.1.0/24), only that subnet will be scanned.
If no subnet is provided, all local networks will be automatically detected and scanned.
Examples:
wild node discover # Auto-detect local networks
wild node discover 192.168.1.0/24 # Scan specific subnet`,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
inst, err := getInstanceName()
if err != nil {
return err
}
fmt.Printf("Starting discovery for %d IP(s)...\n", len(args))
_, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/nodes/discover", inst), map[string]interface{}{
"ip_list": args,
})
// Check if --cancel flag is set
shouldCancel, _ := cmd.Flags().GetBool("cancel")
if shouldCancel {
// Cancel any running discovery first
_, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/discovery/cancel", inst), nil)
if err != nil {
// Ignore error if no discovery is running
fmt.Println("No active discovery to cancel, starting new discovery...")
} else {
fmt.Println("Cancelled previous discovery, starting new discovery...")
}
}
// Build request body
body := map[string]interface{}{}
if len(args) > 0 {
body["subnet"] = args[0]
fmt.Printf("Starting discovery for subnet %s...\n", args[0])
} else {
fmt.Println("Starting discovery (auto-detecting local networks)...")
}
_, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/nodes/discover", inst), body)
if err != nil {
return err
}
// Set up signal handling for Ctrl-C
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Handle signals in a goroutine
go func() {
<-sigChan
fmt.Println("\n\nCancelling discovery...")
cancel()
// Call cancel API
_, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/discovery/cancel", inst), nil)
if err != nil {
fmt.Printf("Failed to cancel discovery: %v\n", err)
} else {
fmt.Println("Discovery cancelled successfully")
}
os.Exit(0)
}()
// Poll for completion
fmt.Println("Scanning nodes...")
fmt.Println("Scanning nodes... (Press Ctrl-C to cancel)")
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/discovery", inst))
if err != nil {
return err
@@ -49,21 +109,29 @@ var nodeDiscoverCmd = &cobra.Command{
return nil
}
fmt.Printf("\nFound %d node(s):\n\n", len(nodesFound))
fmt.Printf("%-15s %-12s %-10s\n", "IP", "INTERFACE", "VERSION")
fmt.Println("-----------------------------------------------")
fmt.Printf("\nFound %d node(s) in maintenance mode:\n\n", len(nodesFound))
fmt.Printf("%-15s %-15s %-15s\n", "IP", "VERSION", "HOSTNAME")
fmt.Println("-----------------------------------------------------")
for _, node := range nodesFound {
if m, ok := node.(map[string]interface{}); ok {
fmt.Printf("%-15s %-12s %-10s\n",
m["ip"], m["interface"], m["version"])
version := m["version"]
if version == nil {
version = ""
}
hostname := m["hostname"]
if hostname == nil {
hostname = ""
}
fmt.Printf("%-15s %-15s %-15s\n",
m["ip"], version, hostname)
}
}
return nil
}
// Still running, wait a bit
// Still running, show progress
fmt.Print(".")
time.Sleep(500 * time.Millisecond)
}
}
},
}
@@ -431,6 +499,31 @@ You can use it manually to update templates.`,
},
}
var nodeCancelDiscoveryCmd = &cobra.Command{
Use: "cancel-discovery",
Short: "Cancel active node discovery",
Long: `Cancel an active node discovery operation.
Use this if discovery gets stuck or you want to stop a running scan.
Example:
wild node cancel-discovery`,
RunE: func(cmd *cobra.Command, args []string) error {
inst, err := getInstanceName()
if err != nil {
return err
}
_, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/discovery/cancel", inst), nil)
if err != nil {
return err
}
fmt.Println("Discovery cancelled successfully")
return nil
},
}
var nodeDeleteCmd = &cobra.Command{
Use: "delete <hostname>",
Short: "Delete a node",
@@ -453,6 +546,7 @@ var nodeDeleteCmd = &cobra.Command{
func init() {
nodeCmd.AddCommand(nodeDiscoverCmd)
nodeCmd.AddCommand(nodeCancelDiscoveryCmd)
nodeCmd.AddCommand(nodeDetectCmd)
nodeCmd.AddCommand(nodeListCmd)
nodeCmd.AddCommand(nodeShowCmd)
@@ -462,6 +556,9 @@ func init() {
nodeCmd.AddCommand(nodeFetchTemplatesCmd)
nodeCmd.AddCommand(nodeDeleteCmd)
// Add flags to node discover command
nodeDiscoverCmd.Flags().Bool("cancel", false, "Cancel any running discovery before starting")
// Add flags to node add command
nodeAddCmd.Flags().String("target-ip", "", "Target IP address for production")
nodeAddCmd.Flags().String("current-ip", "", "Current IP address (for maintenance mode)")