-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
78 lines (67 loc) · 2.61 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"os"
"path/filepath"
"time"
"context"
"github.com/chaoscypher/kube-save-restore/internal/backup"
"github.com/chaoscypher/kube-save-restore/internal/config"
"github.com/chaoscypher/kube-save-restore/internal/kubernetes"
"github.com/chaoscypher/kube-save-restore/internal/logger"
"github.com/chaoscypher/kube-save-restore/internal/restore"
)
// main is the entry point of the application.
func main() {
config := config.ParseFlags()
logger := logger.SetupLogger(config)
if err := run(config, logger); err != nil {
logger.Error("Error:", err)
os.Exit(1)
}
}
// run executes the main logic based on the provided configuration and logger.
func run(config *config.Config, logger logger.LoggerInterface) error {
kubeconfigPath := getKubeconfigPath(config.KubeConfig, logger)
k8sClient, err := kubernetes.NewClient(kubeconfigPath, config.Context, kubernetes.DefaultConfigModifier)
if err != nil {
return fmt.Errorf("failed to create Kubernetes client: %w", err)
}
switch config.Mode {
case "backup":
return handleBackup(config, k8sClient, logger)
case "restore":
return handleRestore(config, k8sClient, logger)
default:
return fmt.Errorf("invalid mode: %s. Use 'backup' or 'restore'", config.Mode)
}
}
// getKubeconfigPath returns the path to the kubeconfig file.
// If the kubeconfig path is not provided, it defaults to the user's home directory.
func getKubeconfigPath(kubeconfig string, logger logger.LoggerInterface) string {
if kubeconfig != "" {
return kubeconfig
}
homeDir, err := os.UserHomeDir()
if err != nil {
logger.Errorf("Error getting user home directory: %v", err)
os.Exit(1)
}
return filepath.Join(homeDir, ".kube", "config")
}
// handleBackup performs the backup operation using the provided configuration and Kubernetes client.
func handleBackup(config *config.Config, k8sClient *kubernetes.Client, logger logger.LoggerInterface) error {
if config.BackupDir == "" {
config.BackupDir = filepath.Join(".", fmt.Sprintf("k8s-backup-%s", time.Now().Format("20060102-150405")))
}
backupManager := backup.NewManager(k8sClient, config.BackupDir, config.DryRun, logger)
return backupManager.PerformBackup(context.Background())
}
// handleRestore performs the restore operation using the provided configuration and Kubernetes client.
func handleRestore(config *config.Config, k8sClient *kubernetes.Client, logger logger.LoggerInterface) error {
if config.RestoreDir == "" {
return fmt.Errorf("--restore-dir flag is required for restore mode")
}
restoreManager := restore.NewManager(k8sClient, logger)
return restoreManager.PerformRestore(config.RestoreDir, config.DryRun)
}