Rename the CLI binary and all references from `wild` to `wildcloud` across Go source, packaging scripts, docs, and e2e tests. Add missing CLI commands: app restart, operation cancel.
875 lines
24 KiB
Go
875 lines
24 KiB
Go
package cmd
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"text/tabwriter"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// Backup main command (with subcommands)
|
|
var backupCmd = &cobra.Command{
|
|
Use: "backup [<app>]",
|
|
Short: "Manage app backups",
|
|
Long: `Backup and manage Wild Cloud application data including databases, persistent volumes, and configuration.
|
|
|
|
When called with an app name directly (e.g., 'wildcloud backup myapp'), it starts a backup.
|
|
Use subcommands for other operations (list, verify, delete, etc.).`,
|
|
Args: cobra.MaximumNArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
// If an app name is provided, run backup start
|
|
if len(args) == 1 {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/backup", inst, args[0]), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("✓ Backup started for app: %s\n", args[0])
|
|
if opID := resp.GetString("operation_id"); opID != "" {
|
|
fmt.Printf(" Operation ID: %s\n", opID)
|
|
fmt.Printf("\nUse 'wildcloud operation status %s' to monitor progress\n", opID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Otherwise show help
|
|
return cmd.Help()
|
|
},
|
|
}
|
|
|
|
// Backup list command
|
|
var backupListCmd = &cobra.Command{
|
|
Use: "list <app>",
|
|
Short: "List all backups for an app",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/apps/%s/backup", inst, args[0]))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Parse the response
|
|
var result struct {
|
|
Data struct {
|
|
Backups []struct {
|
|
Timestamp string `json:"timestamp"`
|
|
Status string `json:"status"`
|
|
Size int64 `json:"size"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
Verified bool `json:"verified"`
|
|
VerifiedAt *time.Time `json:"verified_at"`
|
|
} `json:"backups"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// Marshal resp.Data to JSON then unmarshal to our struct
|
|
dataBytes, err := json.Marshal(resp.Data)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal response data: %w", err)
|
|
}
|
|
if err := json.Unmarshal(dataBytes, &result); err != nil {
|
|
return fmt.Errorf("failed to parse response: %w", err)
|
|
}
|
|
|
|
if len(result.Data.Backups) == 0 {
|
|
fmt.Printf("No backups found for app: %s\n", args[0])
|
|
return nil
|
|
}
|
|
|
|
// Display in a table
|
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
|
fmt.Fprintf(w, "TIMESTAMP\tSTATUS\tSIZE\tCREATED\tVERIFIED\n")
|
|
fmt.Fprintf(w, "---------\t------\t----\t-------\t--------\n")
|
|
|
|
for _, backup := range result.Data.Backups {
|
|
sizeStr := formatBytes(backup.Size)
|
|
createdStr := backup.CreatedAt.Format("2006-01-02 15:04")
|
|
verifiedStr := "No"
|
|
if backup.Verified {
|
|
verifiedStr = "Yes"
|
|
if backup.VerifiedAt != nil {
|
|
verifiedStr = fmt.Sprintf("Yes (%s)", backup.VerifiedAt.Format("2006-01-02"))
|
|
}
|
|
}
|
|
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n",
|
|
backup.Timestamp, backup.Status, sizeStr, createdStr, verifiedStr)
|
|
}
|
|
w.Flush()
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Backup verify command
|
|
var backupVerifyCmd = &cobra.Command{
|
|
Use: "verify <app> [timestamp]",
|
|
Short: "Verify a backup can be restored",
|
|
Long: `Verify that a backup is complete and can be successfully restored. If no timestamp is provided, verifies the most recent backup.`,
|
|
Args: cobra.RangeArgs(1, 2),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
appName := args[0]
|
|
endpoint := fmt.Sprintf("/api/v1/instances/%s/apps/%s/backup/verify", inst, appName)
|
|
|
|
// If timestamp provided, add it to the request
|
|
var body map[string]any
|
|
if len(args) > 1 {
|
|
endpoint = fmt.Sprintf("%s/%s", endpoint, args[1])
|
|
}
|
|
|
|
resp, err := apiClient.Post(endpoint, body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Parse verification result
|
|
var result struct {
|
|
Data struct {
|
|
Success bool `json:"success"`
|
|
Components []struct {
|
|
Type string `json:"type"`
|
|
Success bool `json:"success"`
|
|
Error string `json:"error,omitempty"`
|
|
} `json:"components"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// Marshal resp.Data to JSON then unmarshal to our struct
|
|
dataBytes, err := json.Marshal(resp.Data)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal response data: %w", err)
|
|
}
|
|
if err := json.Unmarshal(dataBytes, &result); err != nil {
|
|
return fmt.Errorf("failed to parse response: %w", err)
|
|
}
|
|
|
|
if result.Data.Success {
|
|
fmt.Printf("✓ Backup verification successful for app: %s\n", appName)
|
|
} else {
|
|
fmt.Printf("✗ Backup verification failed for app: %s\n", appName)
|
|
}
|
|
|
|
if len(result.Data.Components) > 0 {
|
|
fmt.Println("\nComponent verification results:")
|
|
for _, comp := range result.Data.Components {
|
|
status := "✓"
|
|
if !comp.Success {
|
|
status = "✗"
|
|
}
|
|
fmt.Printf(" %s %s", status, comp.Type)
|
|
if comp.Error != "" {
|
|
fmt.Printf(" - %s", comp.Error)
|
|
}
|
|
fmt.Println()
|
|
}
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Backup delete command
|
|
var backupDeleteCmd = &cobra.Command{
|
|
Use: "delete <app> <timestamp>",
|
|
Short: "Delete a specific backup",
|
|
Args: cobra.ExactArgs(2),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if !confirmDelete {
|
|
fmt.Printf("Are you sure you want to delete backup %s for app %s? (y/N): ", args[1], args[0])
|
|
var response string
|
|
fmt.Scanln(&response)
|
|
if response != "y" && response != "Y" {
|
|
fmt.Println("Backup deletion cancelled")
|
|
return nil
|
|
}
|
|
}
|
|
|
|
_, err = apiClient.Delete(fmt.Sprintf("/api/v1/instances/%s/apps/%s/backup/%s", inst, args[0], args[1]))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("✓ Backup deleted: %s (timestamp: %s)\n", args[0], args[1])
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Backup all command
|
|
var backupAllCmd = &cobra.Command{
|
|
Use: "all",
|
|
Short: "Backup all deployed apps",
|
|
Long: `Start backup operations for all currently deployed applications in the instance.`,
|
|
Args: cobra.NoArgs,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Get list of deployed apps
|
|
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/apps", inst))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var result struct {
|
|
Data []struct {
|
|
Name string `json:"name"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// Marshal resp.Data to JSON then unmarshal to our struct
|
|
dataBytes, err := json.Marshal(resp.Data)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal response data: %w", err)
|
|
}
|
|
if err := json.Unmarshal(dataBytes, &result); err != nil {
|
|
return fmt.Errorf("failed to parse response: %w", err)
|
|
}
|
|
|
|
if len(result.Data) == 0 {
|
|
fmt.Println("No deployed apps found to backup")
|
|
return nil
|
|
}
|
|
|
|
fmt.Printf("Starting backups for %d apps...\n\n", len(result.Data))
|
|
|
|
successCount := 0
|
|
failCount := 0
|
|
|
|
for _, app := range result.Data {
|
|
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/backup", inst, app.Name), nil)
|
|
if err != nil {
|
|
fmt.Printf("✗ Failed to start backup for %s: %v\n", app.Name, err)
|
|
failCount++
|
|
continue
|
|
}
|
|
|
|
fmt.Printf("✓ Backup started for %s", app.Name)
|
|
if opID := resp.GetString("operation_id"); opID != "" {
|
|
fmt.Printf(" (Operation: %s)", opID)
|
|
}
|
|
fmt.Println()
|
|
successCount++
|
|
}
|
|
|
|
fmt.Printf("\nBackup summary: %d successful, %d failed\n", successCount, failCount)
|
|
|
|
if successCount > 0 {
|
|
fmt.Println("\nUse 'wildcloud operation list' to monitor backup progress")
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Backup discover command (auto-discovery of backup resources)
|
|
var backupDiscoverCmd = &cobra.Command{
|
|
Use: "discover <app>",
|
|
Short: "Discover backup resources for an app",
|
|
Long: `Auto-discover databases, persistent volumes, and configuration that can be backed up for an application.`,
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/apps/%s/backup/discover", inst, args[0]))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var result struct {
|
|
Data struct {
|
|
App string `json:"app"`
|
|
Resources []struct {
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Plugin string `json:"plugin"`
|
|
Source map[string]any `json:"source"`
|
|
ShouldBackup bool `json:"shouldBackup"`
|
|
Reason string `json:"reason,omitempty"`
|
|
} `json:"resources"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// Marshal resp.Data to JSON then unmarshal to our struct
|
|
dataBytes, err := json.Marshal(resp.Data)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal response data: %w", err)
|
|
}
|
|
if err := json.Unmarshal(dataBytes, &result); err != nil {
|
|
return fmt.Errorf("failed to parse response: %w", err)
|
|
}
|
|
|
|
fmt.Printf("Discovered backup resources for app: %s\n\n", result.Data.App)
|
|
|
|
if len(result.Data.Resources) == 0 {
|
|
fmt.Println("No backup resources discovered")
|
|
return nil
|
|
}
|
|
|
|
// Group by type
|
|
byType := make(map[string][]struct {
|
|
Name string
|
|
Plugin string
|
|
ShouldBackup bool
|
|
Reason string
|
|
Source map[string]any
|
|
})
|
|
|
|
for _, r := range result.Data.Resources {
|
|
byType[r.Type] = append(byType[r.Type], struct {
|
|
Name string
|
|
Plugin string
|
|
ShouldBackup bool
|
|
Reason string
|
|
Source map[string]any
|
|
}{
|
|
Name: r.Name,
|
|
Plugin: r.Plugin,
|
|
ShouldBackup: r.ShouldBackup,
|
|
Reason: r.Reason,
|
|
Source: r.Source,
|
|
})
|
|
}
|
|
|
|
// Display grouped resources
|
|
for resType, resources := range byType {
|
|
fmt.Printf("%s:\n", capitalize(resType))
|
|
for _, r := range resources {
|
|
status := "✓ Will backup"
|
|
if !r.ShouldBackup {
|
|
status = "✗ Excluded"
|
|
if r.Reason != "" {
|
|
status += fmt.Sprintf(" (%s)", r.Reason)
|
|
}
|
|
}
|
|
|
|
fmt.Printf(" • %s [%s] - %s\n", r.Name, r.Plugin, status)
|
|
|
|
// Show relevant source details
|
|
switch resType {
|
|
case "pvc":
|
|
if size, ok := r.Source["size"].(string); ok {
|
|
fmt.Printf(" Size: %s\n", size)
|
|
}
|
|
case "database":
|
|
if dbType, ok := r.Source["type"].(string); ok {
|
|
fmt.Printf(" Type: %s\n", dbType)
|
|
}
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Restore command
|
|
var restoreCmd = &cobra.Command{
|
|
Use: "restore <app> [timestamp]",
|
|
Short: "Restore an app from backup",
|
|
Long: `Restore an application from a backup using blue-green deployment.
|
|
If no timestamp is provided, restores from the most recent backup.
|
|
|
|
By default, the restore deploys to a standby namespace. After verifying,
|
|
use 'wildcloud restore switch <app>' to switch traffic, then 'wildcloud restore cleanup <app>'
|
|
to remove the previous deployment.
|
|
|
|
With --auto, the entire cycle (restore, switch, cleanup) runs as one operation.`,
|
|
Args: cobra.RangeArgs(1, 2),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
body := make(map[string]any)
|
|
if len(args) > 1 {
|
|
body["timestamp"] = args[1]
|
|
}
|
|
if skipData {
|
|
body["skip_data"] = true
|
|
}
|
|
if len(components) > 0 {
|
|
body["components"] = components
|
|
}
|
|
if autoComplete {
|
|
body["auto_complete"] = true
|
|
}
|
|
|
|
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/restore", inst, args[0]), body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("✓ Restore started for app: %s\n", args[0])
|
|
if opID := resp.GetString("operation_id"); opID != "" {
|
|
fmt.Printf(" Operation ID: %s\n", opID)
|
|
fmt.Printf("\nUse 'wildcloud operation status %s' to monitor progress\n", opID)
|
|
}
|
|
|
|
if autoComplete {
|
|
fmt.Println("\nRunning full restore cycle (restore → switch → cleanup)")
|
|
} else {
|
|
fmt.Println("\nAfter restore completes:")
|
|
fmt.Printf(" 1. Verify the standby deployment\n")
|
|
fmt.Printf(" 2. Run 'wildcloud restore switch %s' to switch traffic\n", args[0])
|
|
fmt.Printf(" 3. Run 'wildcloud restore cleanup %s' to remove previous deployment\n", args[0])
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Restore switch command
|
|
var restoreSwitchCmd = &cobra.Command{
|
|
Use: "switch <app>",
|
|
Short: "Switch traffic from active to standby deployment",
|
|
Long: `Switch traffic to the standby deployment after a successful restore. This updates the active deployment color.`,
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/restore/switch", inst, args[0]), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("✓ Switch started for app: %s\n", args[0])
|
|
if opID := resp.GetString("operation_id"); opID != "" {
|
|
fmt.Printf(" Operation ID: %s\n", opID)
|
|
fmt.Printf("\nUse 'wildcloud operation status %s' to monitor progress\n", opID)
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Restore cleanup command
|
|
var restoreCleanupCmd = &cobra.Command{
|
|
Use: "cleanup <app>",
|
|
Short: "Remove previous active deployment after a successful switch",
|
|
Long: `Clean up the previous active deployment resources (namespace, databases, volumes) after a successful switch.`,
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/restore/cleanup", inst, args[0]), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("✓ Cleanup started for app: %s\n", args[0])
|
|
if opID := resp.GetString("operation_id"); opID != "" {
|
|
fmt.Printf(" Operation ID: %s\n", opID)
|
|
fmt.Printf("\nUse 'wildcloud operation status %s' to monitor progress\n", opID)
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// Restore plan command
|
|
var restorePlanCmd = &cobra.Command{
|
|
Use: "plan <app>",
|
|
Short: "Show the latest recovery plan for an app",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/apps/%s/restore/plan", inst, args[0]))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
dataBytes, err := json.Marshal(resp.Data)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal response data: %w", err)
|
|
}
|
|
|
|
var result struct {
|
|
App string `json:"app"`
|
|
Instance string `json:"instance"`
|
|
Timestamp string `json:"timestamp"`
|
|
Status string `json:"status"`
|
|
Error string `json:"error,omitempty"`
|
|
StandbyColor string `json:"standbyColor"`
|
|
Source struct {
|
|
ActiveColor string `json:"activeColor"`
|
|
Namespace string `json:"namespace"`
|
|
} `json:"source"`
|
|
Standby struct {
|
|
Namespace string `json:"namespace"`
|
|
} `json:"standby"`
|
|
Strategies []struct {
|
|
Name string `json:"name"`
|
|
Status string `json:"status"`
|
|
Error string `json:"error,omitempty"`
|
|
} `json:"strategies"`
|
|
}
|
|
|
|
if err := json.Unmarshal(dataBytes, &result); err != nil {
|
|
return fmt.Errorf("failed to parse response: %w", err)
|
|
}
|
|
|
|
fmt.Printf("Recovery Plan for %s\n", result.App)
|
|
fmt.Printf(" Instance: %s\n", result.Instance)
|
|
fmt.Printf(" Timestamp: %s\n", result.Timestamp)
|
|
fmt.Printf(" Status: %s\n", result.Status)
|
|
fmt.Printf(" Active Color: %s\n", result.Source.ActiveColor)
|
|
fmt.Printf(" Standby Color: %s\n", result.StandbyColor)
|
|
|
|
if result.Source.Namespace != "" {
|
|
fmt.Printf(" Source NS: %s\n", result.Source.Namespace)
|
|
}
|
|
if result.Standby.Namespace != "" {
|
|
fmt.Printf(" Standby NS: %s\n", result.Standby.Namespace)
|
|
}
|
|
if result.Error != "" {
|
|
fmt.Printf(" Error: %s\n", result.Error)
|
|
}
|
|
|
|
if len(result.Strategies) > 0 {
|
|
fmt.Println("\n Strategies:")
|
|
for _, s := range result.Strategies {
|
|
status := s.Status
|
|
if s.Error != "" {
|
|
status += fmt.Sprintf(" (%s)", s.Error)
|
|
}
|
|
fmt.Printf(" %-20s %s\n", s.Name, status)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// --- Schedule commands ---
|
|
|
|
var scheduleCmd = &cobra.Command{
|
|
Use: "schedule",
|
|
Short: "Manage backup schedules",
|
|
Long: `Create, list, update, and delete automatic backup schedules for your apps.`,
|
|
}
|
|
|
|
var scheduleListCmd = &cobra.Command{
|
|
Use: "list",
|
|
Short: "List all backup schedules",
|
|
Args: cobra.NoArgs,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/backup/schedules", inst))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
dataBytes, err := json.Marshal(resp.Data)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal response data: %w", err)
|
|
}
|
|
|
|
var schedules []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
TargetName string `json:"target_name"`
|
|
Frequency string `json:"frequency"`
|
|
Time string `json:"time"`
|
|
Enabled bool `json:"enabled"`
|
|
NextRun *string `json:"next_run"`
|
|
LastRun *string `json:"last_run"`
|
|
}
|
|
if err := json.Unmarshal(dataBytes, &schedules); err != nil {
|
|
return fmt.Errorf("failed to parse response: %w", err)
|
|
}
|
|
|
|
if len(schedules) == 0 {
|
|
fmt.Println("No backup schedules configured")
|
|
fmt.Println("\nCreate one with: wild backup schedule create <app> --frequency daily")
|
|
return nil
|
|
}
|
|
|
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
|
fmt.Fprintf(w, "ID\tNAME\tAPP\tFREQUENCY\tTIME\tENABLED\tNEXT RUN\n")
|
|
fmt.Fprintf(w, "--\t----\t---\t---------\t----\t-------\t--------\n")
|
|
|
|
for _, s := range schedules {
|
|
enabled := "Yes"
|
|
if !s.Enabled {
|
|
enabled = "No"
|
|
}
|
|
nextRun := "-"
|
|
if s.NextRun != nil {
|
|
if t, err := time.Parse(time.RFC3339, *s.NextRun); err == nil {
|
|
nextRun = t.Format("2006-01-02 15:04")
|
|
}
|
|
}
|
|
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
|
|
s.ID, s.Name, s.TargetName, s.Frequency, s.Time, enabled, nextRun)
|
|
}
|
|
w.Flush()
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var (
|
|
schedFrequency string
|
|
schedTime string
|
|
schedDayOfWeek int
|
|
schedDayOfMonth int
|
|
)
|
|
|
|
var scheduleCreateCmd = &cobra.Command{
|
|
Use: "create <app>",
|
|
Short: "Create a backup schedule for an app",
|
|
Long: `Create an automatic backup schedule for an application.
|
|
|
|
Examples:
|
|
wildcloud backup schedule create gitea --frequency daily --time 02:00
|
|
wildcloud backup schedule create immich --frequency weekly --time 03:00 --day-of-week 0
|
|
wildcloud backup schedule create nextcloud --frequency monthly --day-of-month 1`,
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
appName := args[0]
|
|
body := map[string]any{
|
|
"name": fmt.Sprintf("%s %s", appName, schedFrequency),
|
|
"target_type": "app",
|
|
"target_name": appName,
|
|
"frequency": schedFrequency,
|
|
"time": schedTime,
|
|
"enabled": true,
|
|
}
|
|
if schedDayOfWeek >= 0 {
|
|
body["day_of_week"] = schedDayOfWeek
|
|
}
|
|
if schedDayOfMonth > 0 {
|
|
body["day_of_month"] = schedDayOfMonth
|
|
}
|
|
|
|
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/backup/schedules", inst), body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
dataBytes, _ := json.Marshal(resp.Data)
|
|
var sched struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
NextRun *string `json:"next_run"`
|
|
}
|
|
json.Unmarshal(dataBytes, &sched)
|
|
|
|
fmt.Printf("Schedule created: %s (%s)\n", sched.Name, sched.ID)
|
|
if sched.NextRun != nil {
|
|
if t, err := time.Parse(time.RFC3339, *sched.NextRun); err == nil {
|
|
fmt.Printf(" Next run: %s\n", t.Format("2006-01-02 15:04"))
|
|
}
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var scheduleDeleteCmd = &cobra.Command{
|
|
Use: "delete <schedule-id>",
|
|
Short: "Delete a backup schedule",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = apiClient.Delete(fmt.Sprintf("/api/v1/instances/%s/backup/schedules/%s", inst, args[0]))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("Schedule deleted: %s\n", args[0])
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var scheduleEnableCmd = &cobra.Command{
|
|
Use: "enable <schedule-id>",
|
|
Short: "Enable a backup schedule",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
return toggleSchedule(args[0], true)
|
|
},
|
|
}
|
|
|
|
var scheduleDisableCmd = &cobra.Command{
|
|
Use: "disable <schedule-id>",
|
|
Short: "Disable a backup schedule",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
return toggleSchedule(args[0], false)
|
|
},
|
|
}
|
|
|
|
var scheduleRunCmd = &cobra.Command{
|
|
Use: "run <schedule-id>",
|
|
Short: "Manually trigger a scheduled backup",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/backup/schedules/%s/run", inst, args[0]), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("Backup triggered for schedule: %s\n", args[0])
|
|
if opID := resp.GetString("operation_id"); opID != "" {
|
|
fmt.Printf(" Operation ID: %s\n", opID)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
func toggleSchedule(scheduleID string, enabled bool) error {
|
|
inst, err := getInstanceName()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
body := map[string]any{
|
|
"enabled": enabled,
|
|
}
|
|
|
|
_, err = apiClient.Put(fmt.Sprintf("/api/v1/instances/%s/backup/schedules/%s", inst, scheduleID), body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
action := "enabled"
|
|
if !enabled {
|
|
action = "disabled"
|
|
}
|
|
fmt.Printf("Schedule %s: %s\n", action, scheduleID)
|
|
return nil
|
|
}
|
|
|
|
// Helper variables for flags
|
|
var (
|
|
confirmDelete bool
|
|
skipData bool
|
|
autoComplete bool
|
|
components []string
|
|
)
|
|
|
|
// Helper function to format bytes
|
|
func formatBytes(bytes int64) string {
|
|
const unit = 1024
|
|
if bytes < unit {
|
|
return fmt.Sprintf("%d B", bytes)
|
|
}
|
|
div, exp := int64(unit), 0
|
|
for n := bytes / unit; n >= unit; n /= unit {
|
|
div *= unit
|
|
exp++
|
|
}
|
|
return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
|
|
}
|
|
|
|
// Helper function to capitalize strings
|
|
func capitalize(s string) string {
|
|
if s == "" {
|
|
return ""
|
|
}
|
|
// Handle special cases
|
|
switch s {
|
|
case "pvc":
|
|
return "Persistent Volumes"
|
|
case "database":
|
|
return "Databases"
|
|
case "config":
|
|
return "Configuration"
|
|
default:
|
|
return string(s[0]-32) + s[1:]
|
|
}
|
|
}
|
|
|
|
// init registers all backup subcommands and flags
|
|
func init() {
|
|
// Add subcommands to backup
|
|
backupCmd.AddCommand(backupListCmd)
|
|
backupCmd.AddCommand(backupVerifyCmd)
|
|
backupCmd.AddCommand(backupDeleteCmd)
|
|
backupCmd.AddCommand(backupAllCmd)
|
|
backupCmd.AddCommand(backupDiscoverCmd)
|
|
|
|
// Add flags to backup delete command
|
|
backupDeleteCmd.Flags().BoolVarP(&confirmDelete, "yes", "y", false, "Skip confirmation prompt")
|
|
|
|
// Schedule subcommands
|
|
backupCmd.AddCommand(scheduleCmd)
|
|
scheduleCmd.AddCommand(scheduleListCmd)
|
|
scheduleCmd.AddCommand(scheduleCreateCmd)
|
|
scheduleCmd.AddCommand(scheduleDeleteCmd)
|
|
scheduleCmd.AddCommand(scheduleEnableCmd)
|
|
scheduleCmd.AddCommand(scheduleDisableCmd)
|
|
scheduleCmd.AddCommand(scheduleRunCmd)
|
|
|
|
// Schedule create flags
|
|
scheduleCreateCmd.Flags().StringVar(&schedFrequency, "frequency", "daily", "Backup frequency: daily, weekly, monthly")
|
|
scheduleCreateCmd.Flags().StringVar(&schedTime, "time", "02:00", "Time of day for backup (HH:MM)")
|
|
scheduleCreateCmd.Flags().IntVar(&schedDayOfWeek, "day-of-week", -1, "Day of week for weekly backups (0=Sun..6=Sat)")
|
|
scheduleCreateCmd.Flags().IntVar(&schedDayOfMonth, "day-of-month", 0, "Day of month for monthly backups (1-28)")
|
|
|
|
// Add subcommands to restore
|
|
restoreCmd.AddCommand(restoreSwitchCmd)
|
|
restoreCmd.AddCommand(restoreCleanupCmd)
|
|
restoreCmd.AddCommand(restorePlanCmd)
|
|
|
|
// Add flags to restore command
|
|
restoreCmd.Flags().BoolVar(&skipData, "skip-data", false, "Skip data restoration, only restore configuration")
|
|
restoreCmd.Flags().StringSliceVarP(&components, "components", "c", nil, "Specific components to restore (e.g., postgres,pvc,config)")
|
|
restoreCmd.Flags().BoolVar(&autoComplete, "auto", false, "Run full restore cycle: restore, switch traffic, and cleanup in one operation")
|
|
}
|