-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
104 lines (83 loc) · 2.19 KB
/
utils.go
File metadata and controls
104 lines (83 loc) · 2.19 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"log"
"math/rand"
"os"
"sync"
"time"
"gopkg.in/yaml.v3"
)
// Global config cache with thread safety
var (
vmsConfig *VMsConfig
configMutex sync.RWMutex
configLoaded bool
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// GenerateUniqueID generates a random string for VM name
func GenerateUniqueID(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, length)
for i := range result {
result[i] = charset[rand.Intn(len(charset))]
}
return string(result)
}
// FormatDuration formats a duration to a human-readable string
func FormatDuration(d time.Duration) string {
d = d.Round(time.Minute)
h := d / time.Hour
d -= h * time.Hour
m := d / time.Minute
if h > 0 {
return time.Duration(h).String() + " " + time.Duration(m*time.Minute).String()
}
return time.Duration(m * time.Minute).String()
}
// Load VMs configurations from file
func loadVMsConfig() (*VMsConfig, error) {
configMutex.Lock()
defer configMutex.Unlock()
// Return cached config if already loaded
if configLoaded && vmsConfig != nil {
return vmsConfig, nil
}
configPath := os.Getenv("VMS_CONFIG_PATH")
if configPath == "" {
configPath = "/etc/config/vms.yaml"
}
log.Printf("Loading VMs configuration from: %s", configPath)
data, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %v", err)
}
var config VMsConfig
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to parse YAML config: %v", err)
}
// Validate configuration
if len(config.AvailableVMs) == 0 {
return nil, fmt.Errorf("no vms configured")
}
vmsConfig = &config
configLoaded = true
log.Printf("Successfully loaded VMs configuration %v", config.AvailableVMs)
return vmsConfig, nil
}
// Get VM configuration by type
func getVMConfig(vmtype string) (*VMConfig, error) {
// Load config if not already loaded
config, err := loadVMsConfig()
if err != nil {
return nil, err
}
configMutex.RLock()
defer configMutex.RUnlock()
if vm, exists := config.AvailableVMs[vmtype]; exists {
return &vm, nil
}
return nil, fmt.Errorf("VM of type %s not found in configuration", vmtype)
}