forked from Telmate/proxmox-api-go
/
util.go
105 lines (92 loc) · 2.18 KB
/
util.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
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
105
package proxmox
import (
"regexp"
"strconv"
"strings"
)
func inArray(arr []string, str string) bool {
for _, elem := range arr {
if elem == str {
return true
}
}
return false
}
func Itob(i int) bool {
return i == 1
}
// ParseSubConf - Parse standard sub-conf strings `key=value`.
func ParseSubConf(
element string,
separator string,
) (key string, value interface{}) {
if strings.Contains(element, separator) {
conf := strings.Split(element, separator)
key, value := conf[0], conf[1]
var interValue interface{}
// Make sure to add value in right type,
// because all subconfig are returned as strings from Proxmox API.
if iValue, err := strconv.ParseInt(value, 10, 64); err == nil {
interValue = int(iValue)
} else if bValue, err := strconv.ParseBool(value); err == nil {
interValue = bValue
} else {
interValue = value
}
return key, interValue
}
return
}
// ParseConf - Parse standard device conf string `key1=val1,key2=val2`.
func ParseConf(
kvString string,
confSeparator string,
subConfSeparator string,
implicitFirstKey string,
) QemuDevice {
var confMap = QemuDevice{}
confList := strings.Split(kvString, confSeparator)
if implicitFirstKey != "" {
if !strings.Contains(confList[0], "=") {
confMap[implicitFirstKey] = confList[0]
confList = confList[1:]
}
}
for _, item := range confList {
key, value := ParseSubConf(item, subConfSeparator)
confMap[key] = value
}
return confMap
}
func ParsePMConf(
kvString string,
implicitFirstKey string,
) QemuDevice {
return ParseConf(kvString, ",", "=", implicitFirstKey)
}
// Convert a disk-size string to a GB float
func DiskSizeGB(dcSize interface{}) float64 {
var diskSize float64
switch dcSize := dcSize.(type) {
case string:
diskString := strings.ToUpper(dcSize)
re := regexp.MustCompile("([0-9]+)([A-Z]*)")
diskArray := re.FindStringSubmatch(diskString)
diskSize, _ = strconv.ParseFloat(diskArray[1], 64)
if len(diskArray) >= 3 {
switch diskArray[2] {
case "T", "TB":
diskSize *= 1024
case "G", "GB":
//Nothing to do
case "M", "MB":
diskSize /= 1024
case "K", "KB":
diskSize /= 1048576
}
}
case float64:
diskSize = dcSize
}
return diskSize
}