Skip to content

Commit

Permalink
Add size unit for easier string formatting of proxmox related disk st…
Browse files Browse the repository at this point in the history
…orage units

Add create disk
  • Loading branch information
Steven committed Aug 14, 2018
1 parent 6ca01f8 commit d6f3707
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
14 changes: 14 additions & 0 deletions proxmox/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/Telmate/proxmox-api-go/sizeunit"
"io"
"net/http"
"regexp"
Expand Down Expand Up @@ -345,6 +346,19 @@ func (c *Client) ResizeQemuDisk(vmr *VmRef, disk string, moreSizeGB int) (exitSt
return
}

func (c *Client) CreateQemuDisk(vmr *VmRef, vmId int, diskName string, diskSize int, unit sizeUnit.SizeUnit,
format string) error {
reqBody := ParamsToBody(map[string]string{
"filename": diskName,
"size": sizeUnit.FormatToShortString(diskSize, unit),
"format": format,
"vmid": strconv.Itoa(vmId),
})
url := fmt.Sprintf("/nodes/%s/storage/local/content", vmr.node)
_, err := c.session.Post(url, nil, nil, &reqBody)
return err
}

// GetNextID - Get next free VMID
func (c *Client) GetNextID(currentID int) (nextID int, err error) {
var data map[string]interface{}
Expand Down
44 changes: 44 additions & 0 deletions sizeunit/size_unit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package sizeUnit

import (
"fmt"
"strconv"
)

type SizeUnit uint64

const (
KB SizeUnit = 1 << (10 * (iota + 1))
MB
GB
)

var shortUnitMap = map[SizeUnit]string{
KB: "K",
MB: "M",
GB: "G",
}

var longUnitMap = map[SizeUnit]string{
KB: "kilobyte",
MB: "megabyte",
GB: "gigabyte",
}

func FormatToShortString(size int, sizeUnit SizeUnit) string {
return strconv.Itoa(size) + shortUnitMap[sizeUnit]
}

func FormatToLongString(size int, sizeUnit SizeUnit) string {
return fmt.Sprintf("%s %s", strconv.Itoa(size), longUnitMap[sizeUnit])
}

func ConvertTo(size int, oldSizeUnit SizeUnit, newSizeUnit SizeUnit) (newSize int, newUnit SizeUnit) {
if oldSizeUnit < newSizeUnit {
return size / int(newSizeUnit), newSizeUnit
} else if newSizeUnit > oldSizeUnit {
return size * int(newSizeUnit), newSizeUnit
} else {
return size, newSizeUnit
}
}

0 comments on commit d6f3707

Please sign in to comment.