yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/proxmox/util.go (about)

     1  package proxmox
     2  
     3  import (
     4  	"regexp"
     5  	"strconv"
     6  	"strings"
     7  )
     8  
     9  func Itob(i int) bool {
    10  	return i == 1
    11  }
    12  
    13  // ParseSubConf - Parse standard sub-conf strings `key=value`.
    14  func ParseSubConf(
    15  	element string,
    16  	separator string,
    17  ) (key string, value interface{}) {
    18  	if strings.Contains(element, separator) {
    19  		conf := strings.Split(element, separator)
    20  		key, value := conf[0], conf[1]
    21  		var interValue interface{}
    22  
    23  		// Make sure to add value in right type,
    24  		// because all subconfig are returned as strings from Proxmox API.
    25  		if iValue, err := strconv.ParseInt(value, 10, 64); err == nil {
    26  			interValue = int(iValue)
    27  		} else if bValue, err := strconv.ParseBool(value); err == nil {
    28  			interValue = bValue
    29  		} else {
    30  			interValue = value
    31  		}
    32  		return key, interValue
    33  	}
    34  	return
    35  }
    36  
    37  // ParseConf - Parse standard device conf string `key1=val1,key2=val2`.
    38  func ParseConf(
    39  	kvString string,
    40  	confSeparator string,
    41  	subConfSeparator string,
    42  	implicitFirstKey string,
    43  ) QemuDevice {
    44  	var confMap = QemuDevice{}
    45  	confList := strings.Split(kvString, confSeparator)
    46  
    47  	if implicitFirstKey != "" {
    48  		if !strings.Contains(confList[0], "=") {
    49  			confMap[implicitFirstKey] = confList[0]
    50  			confList = confList[1:]
    51  		}
    52  	}
    53  
    54  	for _, item := range confList {
    55  		key, value := ParseSubConf(item, subConfSeparator)
    56  		confMap[key] = value
    57  	}
    58  	return confMap
    59  }
    60  
    61  func ParsePMConf(
    62  	kvString string,
    63  	implicitFirstKey string,
    64  ) QemuDevice {
    65  	return ParseConf(kvString, ",", "=", implicitFirstKey)
    66  }
    67  
    68  // Convert a disk-size string to a GB float
    69  func DiskSizeGB(dcSize interface{}) float64 {
    70  	var diskSize float64
    71  	switch dcSize := dcSize.(type) {
    72  	case string:
    73  		diskString := strings.ToUpper(dcSize)
    74  		re := regexp.MustCompile("([0-9]+)([A-Z]*)")
    75  		diskArray := re.FindStringSubmatch(diskString)
    76  
    77  		diskSize, _ = strconv.ParseFloat(diskArray[1], 64)
    78  
    79  		if len(diskArray) >= 3 {
    80  			switch diskArray[2] {
    81  			case "T", "TB":
    82  				diskSize *= 1024
    83  			case "G", "GB":
    84  				//Nothing to do
    85  			case "M", "MB":
    86  				diskSize /= 1024
    87  			case "K", "KB":
    88  				diskSize /= 1048576
    89  			}
    90  		}
    91  	case float64:
    92  		diskSize = dcSize
    93  	}
    94  	return diskSize
    95  }