You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
922 lines
37 KiB
Go
922 lines
37 KiB
Go
package hypervisor
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/netip"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"libvirt.org/go/libvirtxml"
|
|
)
|
|
|
|
var (
|
|
uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)
|
|
namePattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,80}$`)
|
|
netPattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,64}$`)
|
|
templateIDPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
|
|
generationTokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
|
|
poolKeyPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
|
digestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
|
hostnamePattern = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$`)
|
|
policyIdentifier = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,63}$`)
|
|
shortVolumeHashPattern = regexp.MustCompile(`^[0-9a-f]{16}$`)
|
|
)
|
|
|
|
// isVMOwnedRootVolumeName recognizes only root-volume names that the Agent
|
|
// itself can derive for one VM. Metadata is not sufficient ownership proof:
|
|
// without this check a corrupted marker could make deletion remove another
|
|
// tenant's volume.
|
|
func isVMOwnedRootVolumeName(uuid, name string) bool {
|
|
if !uuidPattern.MatchString(uuid) || name != strings.ToLower(name) {
|
|
return false
|
|
}
|
|
canonicalUUID := strings.ToLower(uuid)
|
|
if name == canonicalUUID+"-root.qcow2" {
|
|
return true
|
|
}
|
|
compactUUID := strings.ReplaceAll(canonicalUUID, "-", "")
|
|
for _, prefix := range []string{"vreinstall-" + compactUUID + "-", "vrestore-" + compactUUID + "-"} {
|
|
if !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, ".qcow2") {
|
|
continue
|
|
}
|
|
digest := strings.TrimSuffix(strings.TrimPrefix(name, prefix), ".qcow2")
|
|
if shortVolumeHashPattern.MatchString(digest) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func isVMOwnedManagedVolumeName(uuid, name string) bool {
|
|
if isVMOwnedRootVolumeName(uuid, name) {
|
|
return true
|
|
}
|
|
if !uuidPattern.MatchString(uuid) || name != strings.ToLower(name) {
|
|
return false
|
|
}
|
|
compactUUID := strings.ReplaceAll(strings.ToLower(uuid), "-", "")
|
|
for _, prefix := range []string{
|
|
"vsnap-" + compactUUID + "-",
|
|
"vbackup-" + compactUUID + "-",
|
|
} {
|
|
if !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, ".qcow2") {
|
|
continue
|
|
}
|
|
key := strings.TrimSuffix(strings.TrimPrefix(name, prefix), ".qcow2")
|
|
return catalogIDPattern.MatchString(key)
|
|
}
|
|
return false
|
|
}
|
|
|
|
func BuildDomainXML(definition DomainDefinition) (string, error) {
|
|
if err := ValidateDomainDefinition(definition); err != nil {
|
|
return "", err
|
|
}
|
|
format := definition.RootDiskFormat
|
|
if format == "" {
|
|
format = "qcow2"
|
|
}
|
|
domain := libvirtxml.Domain{
|
|
Type: "kvm",
|
|
Name: definition.Name,
|
|
UUID: strings.ToLower(definition.UUID),
|
|
Description: definition.Description,
|
|
Memory: &libvirtxml.DomainMemory{Value: uint(definition.MemoryMiB), Unit: "MiB"},
|
|
VCPU: &libvirtxml.DomainVCPU{Placement: "static", Value: definition.VCPUs},
|
|
OS: &libvirtxml.DomainOS{
|
|
Type: &libvirtxml.DomainOSType{Arch: "x86_64", Machine: "q35", Type: "hvm"},
|
|
Loader: &libvirtxml.DomainLoader{
|
|
Path: definition.Firmware.Loader, Readonly: "yes", Secure: "no", Type: "pflash",
|
|
},
|
|
NVRam: &libvirtxml.DomainNVRam{
|
|
NVRam: definition.Firmware.NVRAMPath, Template: definition.Firmware.NVRAMTemplate,
|
|
},
|
|
// FirmwareInfo is intentionally omitted. Its feature list is only
|
|
// valid with libvirt firmware autoselection, while this agent pins a
|
|
// host-validated loader and NVRAM template explicitly.
|
|
BootDevices: []libvirtxml.DomainBootDevice{{Dev: "hd"}},
|
|
},
|
|
Features: &libvirtxml.DomainFeatureList{
|
|
ACPI: &libvirtxml.DomainFeature{},
|
|
APIC: &libvirtxml.DomainFeatureAPIC{},
|
|
SMM: &libvirtxml.DomainFeatureSMM{State: "off"},
|
|
},
|
|
CPU: &libvirtxml.DomainCPU{Mode: "host-passthrough"},
|
|
OnPoweroff: "destroy",
|
|
OnReboot: "restart",
|
|
OnCrash: "destroy",
|
|
Devices: &libvirtxml.DomainDeviceList{
|
|
Disks: []libvirtxml.DomainDisk{{
|
|
Device: "disk",
|
|
Driver: &libvirtxml.DomainDiskDriver{Name: "qemu", Type: format, Cache: "none", Discard: "unmap"},
|
|
Source: &libvirtxml.DomainDiskSource{File: &libvirtxml.DomainDiskSourceFile{File: definition.RootDiskPath}},
|
|
Target: &libvirtxml.DomainDiskTarget{Dev: "vda", Bus: "virtio"},
|
|
}},
|
|
Interfaces: make([]libvirtxml.DomainInterface, 0, len(definition.Network)),
|
|
Graphics: []libvirtxml.DomainGraphic{{
|
|
VNC: &libvirtxml.DomainGraphicVNC{AutoPort: "yes", Listen: "127.0.0.1"},
|
|
}},
|
|
Videos: []libvirtxml.DomainVideo{{Model: libvirtxml.DomainVideoModel{Type: "vga"}}},
|
|
Inputs: []libvirtxml.DomainInput{{Type: "tablet", Bus: "usb"}},
|
|
Channels: []libvirtxml.DomainChannel{{
|
|
Source: &libvirtxml.DomainChardevSource{UNIX: &libvirtxml.DomainChardevSourceUNIX{}},
|
|
Target: &libvirtxml.DomainChannelTarget{VirtIO: &libvirtxml.DomainChannelTargetVirtIO{Name: "org.qemu.guest_agent.0"}},
|
|
}},
|
|
MemBalloon: &libvirtxml.DomainMemBalloon{
|
|
Model: "virtio", FreePageReporting: "on", Stats: &libvirtxml.DomainMemBalloonStats{Period: 10},
|
|
},
|
|
},
|
|
}
|
|
metadata, err := marshalDomainMetadata(definition)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
domain.Metadata = &libvirtxml.DomainMetadata{XML: metadata}
|
|
if definition.SeedDiskPath != "" {
|
|
domain.Devices.Disks = append(domain.Devices.Disks, libvirtxml.DomainDisk{
|
|
Device: "cdrom",
|
|
Driver: &libvirtxml.DomainDiskDriver{Name: "qemu", Type: "raw"},
|
|
Source: &libvirtxml.DomainDiskSource{File: &libvirtxml.DomainDiskSourceFile{File: definition.SeedDiskPath}},
|
|
Target: &libvirtxml.DomainDiskTarget{Dev: "sda", Bus: "sata"},
|
|
ReadOnly: &libvirtxml.DomainDiskReadOnly{},
|
|
})
|
|
}
|
|
for index, attachment := range definition.Network {
|
|
iface := libvirtxml.DomainInterface{
|
|
Model: &libvirtxml.DomainInterfaceModel{Type: "virtio"},
|
|
Source: &libvirtxml.DomainInterfaceSource{},
|
|
Driver: &libvirtxml.DomainInterfaceDriver{Queues: min(definition.VCPUs, 16)},
|
|
}
|
|
if definition.BandwidthMbps > 0 {
|
|
rate := int((definition.BandwidthMbps*1_000_000 + 8191) / 8192)
|
|
iface.Bandwidth = &libvirtxml.DomainInterfaceBandwidth{
|
|
Inbound: &libvirtxml.DomainInterfaceBandwidthParams{Average: &rate, Peak: &rate},
|
|
Outbound: &libvirtxml.DomainInterfaceBandwidthParams{Average: &rate, Peak: &rate},
|
|
}
|
|
}
|
|
// The first attachment is the public interface owned by the platform
|
|
// firewall. The optional VPC interface deliberately does not inherit
|
|
// user ACLs, but it does bind libvirt's clean-traffic baseline to its
|
|
// exact private IPv4 address so the guest cannot spoof another VPC
|
|
// endpoint on the routed fabric.
|
|
if definition.FilterName != "" && index == 0 {
|
|
filterRef, err := newManagedInterfaceFilterRef(definition.FilterName, definition.PublicIPCIDR)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
iface.FilterRef = filterRef
|
|
} else if definition.VPCPort != nil && index == 1 {
|
|
iface.FilterRef = newManagedVPCInterfaceFilterRef(
|
|
definition.VPCPort.PrivateIP,
|
|
)
|
|
}
|
|
if attachment.MAC != "" {
|
|
iface.MAC = &libvirtxml.DomainInterfaceMAC{Address: strings.ToLower(attachment.MAC)}
|
|
}
|
|
if attachment.LinkDown {
|
|
iface.Link = &libvirtxml.DomainInterfaceLink{State: "down"}
|
|
}
|
|
if attachment.Bridge != "" {
|
|
iface.Source.Bridge = &libvirtxml.DomainInterfaceSourceBridge{Bridge: attachment.Bridge}
|
|
} else {
|
|
iface.Source.Network = &libvirtxml.DomainInterfaceSourceNetwork{Network: attachment.Network}
|
|
}
|
|
domain.Devices.Interfaces = append(domain.Devices.Interfaces, iface)
|
|
}
|
|
document, err := domain.Marshal()
|
|
if err != nil {
|
|
return "", fmt.Errorf("marshal libvirt domain XML: %w", err)
|
|
}
|
|
return document, nil
|
|
}
|
|
|
|
const managedInterfaceIPParameter = "IP"
|
|
const managedVPCInterfaceFilterName = "clean-traffic"
|
|
|
|
func newManagedInterfaceFilterRef(filterName, publicIPCIDR string) (*libvirtxml.DomainInterfaceFilterRef, error) {
|
|
address, err := publicIPv4Address(publicIPCIDR)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &libvirtxml.DomainInterfaceFilterRef{
|
|
Filter: filterName,
|
|
Parameters: []libvirtxml.DomainInterfaceFilterParam{{
|
|
Name: managedInterfaceIPParameter, Value: address,
|
|
}},
|
|
}, nil
|
|
}
|
|
|
|
func publicIPv4Address(publicIPCIDR string) (string, error) {
|
|
prefix, err := netip.ParsePrefix(publicIPCIDR)
|
|
if err != nil || !prefix.Addr().Is4() {
|
|
return "", NewError(ErrInvalid, "invalid_public_ip", "public_ip_cidr must contain an IPv4 address and prefix", err)
|
|
}
|
|
return prefix.Addr().String(), nil
|
|
}
|
|
|
|
func managedInterfaceFilterIPMatches(iface *libvirtxml.DomainInterface, filterName, publicIPCIDR string) bool {
|
|
address, err := publicIPv4Address(publicIPCIDR)
|
|
if err != nil || iface == nil || iface.FilterRef == nil || iface.FilterRef.Filter != filterName || len(iface.FilterRef.Parameters) != 1 {
|
|
return false
|
|
}
|
|
parameter := iface.FilterRef.Parameters[0]
|
|
return parameter.Name == managedInterfaceIPParameter && parameter.Value == address
|
|
}
|
|
|
|
func newManagedVPCInterfaceFilterRef(privateIP string) *libvirtxml.DomainInterfaceFilterRef {
|
|
return &libvirtxml.DomainInterfaceFilterRef{
|
|
Filter: managedVPCInterfaceFilterName,
|
|
Parameters: []libvirtxml.DomainInterfaceFilterParam{{
|
|
Name: managedInterfaceIPParameter, Value: privateIP,
|
|
}},
|
|
}
|
|
}
|
|
|
|
func managedVPCInterfaceFilterIPMatches(iface *libvirtxml.DomainInterface,
|
|
privateIP string) bool {
|
|
address, err := netip.ParseAddr(privateIP)
|
|
if err != nil || !address.Is4() || address.String() != privateIP ||
|
|
iface == nil || iface.FilterRef == nil ||
|
|
iface.FilterRef.Filter != managedVPCInterfaceFilterName ||
|
|
len(iface.FilterRef.Parameters) != 1 {
|
|
return false
|
|
}
|
|
parameter := iface.FilterRef.Parameters[0]
|
|
return parameter.Name == managedInterfaceIPParameter &&
|
|
parameter.Value == privateIP
|
|
}
|
|
|
|
func updateManagedInterfaceFilterIP(iface *libvirtxml.DomainInterface, filterName, currentIPCIDR, targetIPCIDR string) error {
|
|
if !managedInterfaceFilterIPMatches(iface, filterName, currentIPCIDR) {
|
|
return NewError(ErrConflict, "network_filter_binding_changed", "managed VM network filter IP binding does not match its recorded public address", nil)
|
|
}
|
|
address, err := publicIPv4Address(targetIPCIDR)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
iface.FilterRef.Parameters[0].Value = address
|
|
return nil
|
|
}
|
|
|
|
const domainMetadataNamespace = "https://virt.example/schema/domain/1"
|
|
|
|
type domainMetadataXML struct {
|
|
XMLName xml.Name `xml:"virt-cloud"`
|
|
XMLNS string `xml:"xmlns,attr"`
|
|
DisplayName string `xml:"display-name,omitempty"`
|
|
DiskGiB uint64 `xml:"disk-gib"`
|
|
BandwidthMbps uint64 `xml:"bandwidth-mbps"`
|
|
Hostname string `xml:"hostname,omitempty"`
|
|
PublicIPCIDR string `xml:"public-ip-cidr"`
|
|
PublicPoolKey string `xml:"public-pool-key,omitempty"`
|
|
PublicPoolCIDR string `xml:"public-pool-cidr,omitempty"`
|
|
Gateway string `xml:"gateway,omitempty"`
|
|
DNSServers []string `xml:"dns-server,omitempty"`
|
|
NetworkSelector string `xml:"network-selector,omitempty"`
|
|
SettingsTransitionID string `xml:"settings-transition-id,omitempty"`
|
|
ResourcesTransitionID string `xml:"resources-transition-id,omitempty"`
|
|
ResourcesOriginalPower string `xml:"resources-transition-original-power,omitempty"`
|
|
ResourcesOriginalAutostart string `xml:"resources-transition-original-autostart,omitempty"`
|
|
NetworkTransitionID string `xml:"network-transition-id,omitempty"`
|
|
VPCTransitionID string `xml:"vpc-transition-id,omitempty"`
|
|
VPCPort *domainVPCPortMetadataXML `xml:"vpc-port,omitempty"`
|
|
FirewallTransitionID string `xml:"firewall-transition-id,omitempty"`
|
|
TemplateID string `xml:"template-id"`
|
|
RootVolumeName string `xml:"root-volume"`
|
|
PlatformPolicyJSON string `xml:"platform-policy-json"`
|
|
PendingCleanupVolume string `xml:"pending-cleanup-volume,omitempty"`
|
|
DiskTransitionKind string `xml:"disk-transition-kind,omitempty"`
|
|
DiskTransitionID string `xml:"disk-transition-id,omitempty"`
|
|
DiskTransitionRunning bool `xml:"disk-transition-was-running,omitempty"`
|
|
Snapshots []domainSnapshotMetadataXML `xml:"snapshot,omitempty"`
|
|
Firewall *domainFirewallMetadataXML `xml:"firewall,omitempty"`
|
|
RescueTemplateID string `xml:"rescue-template-id,omitempty"`
|
|
RescueTemplateRevision uint64 `xml:"rescue-template-revision,omitempty"`
|
|
RescueTemplateGeneration string `xml:"rescue-template-generation,omitempty"`
|
|
RescueWasRunning bool `xml:"rescue-was-running,omitempty"`
|
|
RescueAutostart bool `xml:"rescue-original-autostart,omitempty"`
|
|
}
|
|
|
|
type domainVPCPortMetadataXML struct {
|
|
PortKey string `xml:"port-key,attr"`
|
|
VPCKey string `xml:"vpc-key,attr"`
|
|
PrivateIP string `xml:"private-ip,attr"`
|
|
CIDR string `xml:"cidr,attr"`
|
|
Gateway string `xml:"gateway,attr"`
|
|
MAC string `xml:"mac,attr"`
|
|
Bridge string `xml:"bridge,attr"`
|
|
HostRevision uint64 `xml:"host-revision,attr"`
|
|
HostDigest string `xml:"host-digest,attr"`
|
|
}
|
|
|
|
type domainSnapshotMetadataXML struct {
|
|
Key string `xml:"key,attr"`
|
|
Name string `xml:"name,attr"`
|
|
Description string `xml:"description,omitempty"`
|
|
Consistency string `xml:"consistency,attr"`
|
|
SizeBytes uint64 `xml:"size-bytes,attr"`
|
|
CreatedAt int64 `xml:"created-at,attr"`
|
|
}
|
|
|
|
type domainFirewallMetadataXML struct {
|
|
Revision uint64 `xml:"revision,attr"`
|
|
Digest string `xml:"digest,attr"`
|
|
DefaultIn string `xml:"default-in,attr"`
|
|
DefaultOut string `xml:"default-out,attr"`
|
|
Rules []domainFirewallRuleMetadataXML `xml:"rule"`
|
|
}
|
|
|
|
type domainFirewallRuleMetadataXML struct {
|
|
Direction string `xml:"direction,attr"`
|
|
Action string `xml:"action,attr"`
|
|
Protocol string `xml:"protocol,attr"`
|
|
CIDR string `xml:"cidr,attr"`
|
|
PortFrom uint16 `xml:"port-from,attr,omitempty"`
|
|
PortTo uint16 `xml:"port-to,attr,omitempty"`
|
|
}
|
|
|
|
func marshalDomainMetadata(definition DomainDefinition) (string, error) {
|
|
policyJSON, err := json.Marshal(definition.PlatformNetworkPolicy)
|
|
if err != nil {
|
|
return "", fmt.Errorf("marshal platform network policy metadata: %w", err)
|
|
}
|
|
var vpcPort *domainVPCPortMetadataXML
|
|
if definition.VPCPort != nil {
|
|
value := domainVPCPortFromPublic(*definition.VPCPort)
|
|
vpcPort = &value
|
|
}
|
|
encoded, err := xml.Marshal(domainMetadataXML{
|
|
XMLNS: domainMetadataNamespace, DisplayName: definition.DisplayName, DiskGiB: definition.DiskGiB,
|
|
BandwidthMbps: definition.BandwidthMbps, Hostname: definition.Hostname,
|
|
PublicIPCIDR: definition.PublicIPCIDR, PublicPoolKey: definition.PublicPoolKey,
|
|
PublicPoolCIDR: definition.PublicPoolCIDR, Gateway: definition.Gateway,
|
|
DNSServers: append([]string(nil), definition.DNSServers...),
|
|
NetworkSelector: definition.NetworkSelector, TemplateID: definition.TemplateID,
|
|
RootVolumeName: definition.RootVolumeName, PlatformPolicyJSON: string(policyJSON),
|
|
VPCPort: vpcPort,
|
|
Snapshots: append([]domainSnapshotMetadataXML(nil), definition.Snapshots...),
|
|
})
|
|
if err != nil {
|
|
return "", fmt.Errorf("marshal domain metadata: %w", err)
|
|
}
|
|
return string(encoded), nil
|
|
}
|
|
|
|
func ValidateCreateVM(request CreateVMRequest) error {
|
|
if request.UUID != "" && !uuidPattern.MatchString(request.UUID) {
|
|
return NewError(ErrInvalid, "invalid_uuid", "uuid must be a canonical RFC 4122 value", nil)
|
|
}
|
|
if err := validateLibvirtDomainName(request.DomainName, request.UUID); err != nil {
|
|
return err
|
|
}
|
|
if request.Source != "cloud" {
|
|
return NewError(ErrInvalid, "invalid_source", "source must be cloud", nil)
|
|
}
|
|
if !namePattern.MatchString(request.Name) {
|
|
return NewError(ErrInvalid, "invalid_name", "name must contain 1-80 safe characters", nil)
|
|
}
|
|
if len(request.Description) > 1024 || strings.ContainsRune(request.Description, 0) {
|
|
return NewError(ErrInvalid, "invalid_description", "description is too long or contains NUL", nil)
|
|
}
|
|
if request.VCPUs == 0 || request.VCPUs > 512 {
|
|
return NewError(ErrInvalid, "invalid_vcpus", "vcpus must be between 1 and 512", nil)
|
|
}
|
|
if request.MemoryMiB < 128 || request.MemoryMiB > 16*1024*1024 {
|
|
return NewError(ErrInvalid, "invalid_memory", "memory_mib must be between 128 and 16777216", nil)
|
|
}
|
|
if request.DiskGiB < 1 || request.DiskGiB > 4096 {
|
|
return NewError(ErrInvalid, "invalid_disk", "disk_gib must be between 1 and 4096", nil)
|
|
}
|
|
if request.BandwidthMbps < 1 || request.BandwidthMbps > 100000 {
|
|
return NewError(ErrInvalid, "invalid_bandwidth", "bandwidth_mbps must be between 1 and 100000", nil)
|
|
}
|
|
if request.TemplateID == "" {
|
|
return NewError(ErrInvalid, "invalid_template_id", "template_id is required", nil)
|
|
}
|
|
if err := ValidateTemplateSnapshot(request.TemplateID, request.TemplateRevision, request.TemplateGenerationToken); err != nil {
|
|
return err
|
|
}
|
|
if request.Hostname != "" && (!hostnamePattern.MatchString(request.Hostname) || strings.Contains(request.Hostname, "..")) {
|
|
return NewError(ErrInvalid, "invalid_hostname", "hostname must be a lower-case DNS name", nil)
|
|
}
|
|
if err := validateGuestCredentials(request.GuestSSHPublicKey, request.RootPassword); err != nil {
|
|
return err
|
|
}
|
|
if err := ValidatePublicNetworkIntent(
|
|
request.NetworkSelector, request.PublicPoolKey, request.PublicPoolCIDR,
|
|
request.PublicIPCIDR, request.Gateway, request.DNSServers,
|
|
); err != nil {
|
|
return err
|
|
}
|
|
if _, err := NormalizeStartupScript(request.StartupScript); err != nil {
|
|
return err
|
|
}
|
|
if err := ValidatePlatformNetworkPolicy(request.PlatformNetworkPolicy); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidatePublicNetworkIntent verifies a signed PHP/IPAM allocation without
|
|
// making the host agent a second pool authority.
|
|
func ValidatePublicNetworkIntent(selector, poolKey, poolCIDR, publicIPCIDR, gateway string, dnsServers []string) error {
|
|
if _, err := ParseNetworkSelector(selector); err != nil {
|
|
return err
|
|
}
|
|
if !poolKeyPattern.MatchString(poolKey) {
|
|
return NewError(ErrInvalid, "invalid_public_pool_key", "public_pool_key must contain 32 lowercase hexadecimal characters", nil)
|
|
}
|
|
pool, err := netip.ParsePrefix(poolCIDR)
|
|
if err != nil || !pool.Addr().Is4() || pool.Bits() < 1 || pool.Bits() > 30 || pool != pool.Masked() {
|
|
return NewError(ErrInvalid, "invalid_public_pool_cidr", "public_pool_cidr must be a canonical IPv4 network with /1 through /30 prefix", err)
|
|
}
|
|
requested, err := netip.ParsePrefix(publicIPCIDR)
|
|
if err != nil || !requested.Addr().Is4() || requested.Bits() != pool.Bits() || !pool.Contains(requested.Addr()) {
|
|
return NewError(ErrInvalid, "public_ip_outside_pool", "public_ip_cidr must be an IPv4 host inside public_pool_cidr with the same prefix", err)
|
|
}
|
|
gatewayAddr, err := netip.ParseAddr(gateway)
|
|
if err != nil || !gatewayAddr.Is4() || !pool.Contains(gatewayAddr) {
|
|
return NewError(ErrInvalid, "invalid_gateway", "gateway must be an IPv4 address inside public_pool_cidr", err)
|
|
}
|
|
if len(dnsServers) < 1 || len(dnsServers) > 4 {
|
|
return NewError(ErrInvalid, "invalid_dns_servers", "dns_servers must contain 1-4 IP addresses", nil)
|
|
}
|
|
seen := make(map[netip.Addr]struct{}, len(dnsServers))
|
|
for _, raw := range dnsServers {
|
|
address, parseErr := netip.ParseAddr(raw)
|
|
if parseErr != nil || address.IsUnspecified() || address.IsLoopback() || address.IsMulticast() {
|
|
return NewError(ErrInvalid, "invalid_dns_servers", "dns_servers contains an invalid address", parseErr)
|
|
}
|
|
if _, exists := seen[address]; exists {
|
|
return NewError(ErrInvalid, "invalid_dns_servers", "dns_servers must not contain duplicates", nil)
|
|
}
|
|
seen[address] = struct{}{}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func BuildPlatformFilterXML(name string, policy PlatformNetworkPolicySnapshot) (string, error) {
|
|
if !namePattern.MatchString(name) {
|
|
return "", NewError(ErrInvalid, "invalid_filter_name", "network filter name is invalid", nil)
|
|
}
|
|
if err := ValidatePlatformNetworkPolicy(policy); err != nil {
|
|
return "", err
|
|
}
|
|
filter := libvirtxml.NWFilter{
|
|
Name: name, Chain: "root",
|
|
Entries: []libvirtxml.NWFilterEntry{{Ref: &libvirtxml.NWFilterRef{Filter: "clean-traffic"}}},
|
|
}
|
|
priority := -500
|
|
for _, policyRule := range policy.Rules {
|
|
for _, direction := range policyRule.Directions {
|
|
wireDirection := "in"
|
|
if direction == "egress" {
|
|
wireDirection = "out"
|
|
}
|
|
for _, protocol := range policyRule.Protocols {
|
|
from, to := uint(policyRule.PortFrom), uint(policyRule.PortTo)
|
|
rule := &libvirtxml.NWFilterRule{
|
|
Action: "drop", Direction: wireDirection, Priority: priority, StateMatch: "false",
|
|
}
|
|
ports := libvirtxml.NWFilterRuleCommonPort{
|
|
DstPortStart: libvirtxml.NWFilterField{Uint: &from},
|
|
DstPortEnd: libvirtxml.NWFilterField{Uint: &to},
|
|
}
|
|
switch protocol {
|
|
case "tcp":
|
|
rule.TCP = &libvirtxml.NWFilterRuleTCP{NWFilterRuleCommonPort: ports, Comment: policyRule.ID}
|
|
case "udp":
|
|
rule.UDP = &libvirtxml.NWFilterRuleUDP{NWFilterRuleCommonPort: ports, Comment: policyRule.ID}
|
|
}
|
|
filter.Entries = append(filter.Entries, libvirtxml.NWFilterEntry{Rule: rule})
|
|
priority++
|
|
}
|
|
}
|
|
}
|
|
filter.Entries = append(filter.Entries, libvirtxml.NWFilterEntry{Rule: &libvirtxml.NWFilterRule{
|
|
Action: "accept", Direction: "inout", Priority: 900,
|
|
All: &libvirtxml.NWFilterRuleAll{},
|
|
}})
|
|
return filter.Marshal()
|
|
}
|
|
|
|
func ValidateDomainDefinition(definition DomainDefinition) error {
|
|
if !uuidPattern.MatchString(definition.UUID) {
|
|
return NewError(ErrInvalid, "invalid_uuid", "uuid must be a canonical RFC 4122 value", nil)
|
|
}
|
|
if err := validateLibvirtDomainName(definition.Name, definition.UUID); err != nil {
|
|
return err
|
|
}
|
|
if !namePattern.MatchString(definition.DisplayName) {
|
|
return NewError(ErrInvalid, "invalid_name", "display name must contain 1-80 safe characters", nil)
|
|
}
|
|
if definition.VCPUs == 0 || definition.VCPUs > 512 || definition.MemoryMiB < 128 || definition.MemoryMiB > 16*1024*1024 {
|
|
return NewError(ErrInvalid, "invalid_resources", "domain CPU or memory is invalid", nil)
|
|
}
|
|
if err := validateAbsolutePath(definition.RootDiskPath, "root_disk_path"); err != nil {
|
|
return err
|
|
}
|
|
if !isVMOwnedRootVolumeName(definition.UUID, definition.RootVolumeName) || filepath.Base(definition.RootDiskPath) != definition.RootVolumeName {
|
|
return NewError(ErrInvalid, "invalid_root_volume", "root volume identity must match the managed root disk path", nil)
|
|
}
|
|
if definition.RootDiskFormat != "" && definition.RootDiskFormat != "qcow2" && definition.RootDiskFormat != "raw" {
|
|
return NewError(ErrInvalid, "invalid_disk_format", "root disk format must be qcow2 or raw", nil)
|
|
}
|
|
if definition.SeedDiskPath != "" {
|
|
if err := validateAbsolutePath(definition.SeedDiskPath, "seed_disk_path"); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if definition.Firmware.Mode != "uefi" || definition.Firmware.SecureBoot {
|
|
return NewError(ErrInvalid, "secure_boot_disabled", "UEFI is required and secure boot must remain disabled", nil)
|
|
}
|
|
for name, path := range map[string]string{
|
|
"firmware.loader": definition.Firmware.Loader, "firmware.nvram_template": definition.Firmware.NVRAMTemplate,
|
|
"firmware.nvram_path": definition.Firmware.NVRAMPath,
|
|
} {
|
|
if err := validateAbsolutePath(path, name); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if len(definition.Network) < 1 || len(definition.Network) > 2 ||
|
|
(definition.VPCPort == nil && len(definition.Network) != 1) ||
|
|
(definition.VPCPort != nil && len(definition.Network) != 2) {
|
|
return NewError(ErrInvalid, "invalid_network", "domain must contain one public interface and at most one declared VPC interface", nil)
|
|
}
|
|
for index, attachment := range definition.Network {
|
|
if (attachment.Bridge == "") == (attachment.Network == "") {
|
|
return NewError(ErrInvalid, "invalid_network", fmt.Sprintf("network[%d] must select exactly one bridge or network", index), nil)
|
|
}
|
|
selected := attachment.Bridge
|
|
if selected == "" {
|
|
selected = attachment.Network
|
|
}
|
|
if !netPattern.MatchString(selected) {
|
|
return NewError(ErrInvalid, "invalid_network", fmt.Sprintf("network[%d] has an invalid source", index), nil)
|
|
}
|
|
if attachment.MAC != "" {
|
|
parsed, err := net.ParseMAC(attachment.MAC)
|
|
if err != nil || len(parsed) != 6 {
|
|
return NewError(ErrInvalid, "invalid_mac", fmt.Sprintf("network[%d] has an invalid MAC address", index), err)
|
|
}
|
|
}
|
|
}
|
|
if definition.VPCPort != nil {
|
|
if err := validateVPCPortMetadata(*definition.VPCPort); err != nil {
|
|
return err
|
|
}
|
|
private := definition.Network[1]
|
|
if private.Bridge != definition.VPCPort.Bridge || private.Network != "" ||
|
|
!strings.EqualFold(private.MAC, definition.VPCPort.MAC) ||
|
|
strings.EqualFold(definition.Network[0].MAC, private.MAC) {
|
|
return NewError(ErrInvalid, "invalid_vpc_interface", "domain VPC interface does not match its durable metadata", nil)
|
|
}
|
|
}
|
|
if definition.FilterName != "" && !namePattern.MatchString(definition.FilterName) {
|
|
return NewError(ErrInvalid, "invalid_filter_name", "network filter name is invalid", nil)
|
|
}
|
|
if err := ValidatePlatformNetworkPolicy(definition.PlatformNetworkPolicy); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// LibvirtDomainName derives the host-local libvirt identity from authenticated
|
|
// ownership and the canonical VM UUID. It is never accepted from request JSON.
|
|
func LibvirtDomainName(userID int64, uuid string) (string, error) {
|
|
if userID <= 0 {
|
|
return "", NewError(ErrInvalid, "invalid_owner_id", "authenticated owner id must be positive", nil)
|
|
}
|
|
if !uuidPattern.MatchString(uuid) {
|
|
return "", NewError(ErrInvalid, "invalid_uuid", "uuid must be a canonical RFC 4122 value", nil)
|
|
}
|
|
compactUUID := strings.ReplaceAll(strings.ToLower(uuid), "-", "")
|
|
return strconv.FormatInt(userID, 10) + ":vm-" + compactUUID[:12], nil
|
|
}
|
|
|
|
func validateLibvirtDomainName(name, uuid string) error {
|
|
if !uuidPattern.MatchString(uuid) {
|
|
return NewError(ErrInvalid, "invalid_uuid", "uuid must be a canonical RFC 4122 value", nil)
|
|
}
|
|
owner, suffix, found := strings.Cut(name, ":")
|
|
ownerID, err := strconv.ParseInt(owner, 10, 64)
|
|
compactUUID := strings.ReplaceAll(strings.ToLower(uuid), "-", "")
|
|
if !found || err != nil || ownerID <= 0 || owner != strconv.FormatInt(ownerID, 10) || suffix != "vm-"+compactUUID[:12] {
|
|
return NewError(ErrInvalid, "invalid_domain_name", "libvirt domain name must match the authenticated owner and VM UUID", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ValidatePlatformNetworkPolicy(policy PlatformNetworkPolicySnapshot) error {
|
|
if policy.SchemaVersion != 1 || policy.BasePolicyVersion == 0 || len(policy.Rules) == 0 || len(policy.Rules) > 70 || !digestPattern.MatchString(policy.Digest) {
|
|
return NewError(ErrInvalid, "invalid_platform_network_policy", "platform network policy snapshot is invalid", nil)
|
|
}
|
|
seen := make(map[string]struct{}, len(policy.Rules))
|
|
for _, rule := range policy.Rules {
|
|
if !policyIdentifier.MatchString(rule.ID) || len(rule.Label) == 0 || len(rule.Label) > 120 || len(rule.Reason) == 0 || len(rule.Reason) > 500 || rule.PortFrom < 1 || rule.PortTo < rule.PortFrom {
|
|
return NewError(ErrInvalid, "invalid_platform_network_policy", "platform network policy rule is invalid", nil)
|
|
}
|
|
if _, exists := seen[rule.ID]; exists {
|
|
return NewError(ErrInvalid, "invalid_platform_network_policy", "platform network policy rule IDs must be unique", nil)
|
|
}
|
|
seen[rule.ID] = struct{}{}
|
|
if rule.Category != "permanent" && rule.Category != "default" && rule.Category != "test" {
|
|
return NewError(ErrInvalid, "invalid_platform_network_policy", "platform network policy rule category is invalid", nil)
|
|
}
|
|
if !validPolicyValues(rule.Protocols, "tcp", "udp") || !validPolicyValues(rule.Directions, "ingress", "egress") {
|
|
return NewError(ErrInvalid, "invalid_platform_network_policy", "platform network policy protocols or directions are invalid", nil)
|
|
}
|
|
}
|
|
document := struct {
|
|
SchemaVersion uint64 `json:"schema_version"`
|
|
BasePolicyVersion uint64 `json:"base_policy_version"`
|
|
CatalogRevision uint64 `json:"catalog_revision"`
|
|
Rules []PlatformNetworkPolicyRule `json:"rules"`
|
|
}{
|
|
SchemaVersion: policy.SchemaVersion, BasePolicyVersion: policy.BasePolicyVersion,
|
|
CatalogRevision: policy.CatalogRevision, Rules: policy.Rules,
|
|
}
|
|
encoded, err := json.Marshal(document)
|
|
if err != nil {
|
|
return NewError(ErrInvalid, "invalid_platform_network_policy", "platform network policy cannot be encoded", err)
|
|
}
|
|
digest := sha256.Sum256(encoded)
|
|
if hex.EncodeToString(digest[:]) != policy.Digest {
|
|
return NewError(ErrInvalid, "invalid_platform_network_policy_digest", "platform network policy digest does not match its content", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateGuestCredentials(publicKey, password string) error {
|
|
if publicKey == "" && password == "" {
|
|
return NewError(ErrInvalid, "guest_credentials_required", "root_password or guest_ssh_public_key is required", nil)
|
|
}
|
|
if len(publicKey) > 16384 || strings.ContainsAny(publicKey, "\r\n\x00") {
|
|
return NewError(ErrInvalid, "invalid_ssh_public_key", "guest SSH public key must be one bounded line", nil)
|
|
}
|
|
if password != "" {
|
|
if len(password) < 12 || len(password) > 128 {
|
|
return NewError(ErrInvalid, "invalid_root_password", "root password must contain 12-128 printable ASCII characters", nil)
|
|
}
|
|
var upper, lower, digit, symbol bool
|
|
for _, value := range []byte(password) {
|
|
if value < 0x21 || value > 0x7e {
|
|
return NewError(ErrInvalid, "invalid_root_password", "root password must contain printable ASCII without spaces", nil)
|
|
}
|
|
switch {
|
|
case value >= 'A' && value <= 'Z':
|
|
upper = true
|
|
case value >= 'a' && value <= 'z':
|
|
lower = true
|
|
case value >= '0' && value <= '9':
|
|
digit = true
|
|
default:
|
|
symbol = true
|
|
}
|
|
}
|
|
if !upper || !lower || !digit || !symbol {
|
|
return NewError(ErrInvalid, "invalid_root_password", "root password must contain upper, lower, digit, and symbol characters", nil)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validPolicyValues(values []string, allowed ...string) bool {
|
|
if len(values) == 0 {
|
|
return false
|
|
}
|
|
allow := make(map[string]struct{}, len(allowed))
|
|
for _, value := range allowed {
|
|
allow[value] = struct{}{}
|
|
}
|
|
seen := make(map[string]struct{}, len(values))
|
|
for _, value := range values {
|
|
if _, ok := allow[value]; !ok {
|
|
return false
|
|
}
|
|
if _, duplicate := seen[value]; duplicate {
|
|
return false
|
|
}
|
|
seen[value] = struct{}{}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func ValidateTemplateSnapshot(templateID string, revision uint64, generationToken string) error {
|
|
if !templateIDPattern.MatchString(templateID) {
|
|
return NewError(ErrInvalid, "invalid_template_id", "template_id is invalid", nil)
|
|
}
|
|
if revision == 0 {
|
|
return NewError(ErrInvalid, "invalid_template_revision", "template_revision must be positive", nil)
|
|
}
|
|
if !generationTokenPattern.MatchString(generationToken) {
|
|
return NewError(ErrInvalid, "invalid_template_generation_token", "template_generation_token must contain 16-128 URL-safe characters", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// NormalizeStartupScript implements the immutable image-template contract:
|
|
// UTF-8, no NUL, CRLF converted to LF, no trimming, and at most 32 KiB after
|
|
// newline normalization.
|
|
func NormalizeStartupScript(script string) (string, error) {
|
|
if !utf8.ValidString(script) {
|
|
return "", NewError(ErrInvalid, "startup_script_invalid_utf8", "startup_script must be valid UTF-8", nil)
|
|
}
|
|
if strings.ContainsRune(script, 0) {
|
|
return "", NewError(ErrInvalid, "startup_script_contains_nul", "startup_script cannot contain NUL", nil)
|
|
}
|
|
normalized := strings.ReplaceAll(script, "\r\n", "\n")
|
|
if len(normalized) > 32<<10 {
|
|
return "", NewError(ErrInvalid, "startup_script_too_large", "startup_script exceeds 32768 bytes", nil)
|
|
}
|
|
return normalized, nil
|
|
}
|
|
|
|
func validateAbsolutePath(path, field string) error {
|
|
if path == "" || strings.ContainsRune(path, 0) || !filepath.IsAbs(path) || filepath.Clean(path) != path {
|
|
return NewError(ErrInvalid, "invalid_path", field+" must be a clean absolute path", nil)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func metadataFromXML(document string) (VMMetadata, error) {
|
|
var domain libvirtxml.Domain
|
|
if err := domain.Unmarshal(document); err != nil {
|
|
return VMMetadata{}, fmt.Errorf("parse libvirt domain XML: %w", err)
|
|
}
|
|
if domain.OS == nil || domain.OS.Type == nil {
|
|
return VMMetadata{}, errors.New("domain XML is missing OS type")
|
|
}
|
|
metadata := VMMetadata{
|
|
UUID: domain.UUID, Name: domain.Name, Description: domain.Description,
|
|
Machine: domain.OS.Type.Machine, Firmware: "bios",
|
|
}
|
|
if domain.Metadata != nil && domain.Metadata.XML != "" {
|
|
var stored domainMetadataXML
|
|
if err := xml.Unmarshal([]byte(domain.Metadata.XML), &stored); err != nil {
|
|
return VMMetadata{}, fmt.Errorf("parse virt-cloud domain metadata: %w", err)
|
|
}
|
|
if stored.DisplayName != "" {
|
|
metadata.Name = stored.DisplayName
|
|
}
|
|
metadata.DiskGiB = stored.DiskGiB
|
|
metadata.BandwidthMbps = stored.BandwidthMbps
|
|
metadata.Hostname = stored.Hostname
|
|
metadata.PublicIPCIDR = stored.PublicIPCIDR
|
|
metadata.PublicPoolKey = stored.PublicPoolKey
|
|
metadata.PublicPoolCIDR = stored.PublicPoolCIDR
|
|
metadata.Gateway = stored.Gateway
|
|
metadata.DNSServers = append([]string(nil), stored.DNSServers...)
|
|
metadata.NetworkSelector = stored.NetworkSelector
|
|
metadata.TemplateID = stored.TemplateID
|
|
if stored.VPCPort != nil {
|
|
value := stored.VPCPort.public()
|
|
metadata.VPCPort = &value
|
|
}
|
|
}
|
|
if domain.VCPU != nil {
|
|
metadata.VCPUs = domain.VCPU.Value
|
|
}
|
|
if domain.Memory != nil {
|
|
metadata.MemoryMiB = memoryToMiB(domain.Memory.Value, domain.Memory.Unit)
|
|
}
|
|
if domain.OS.Loader != nil {
|
|
metadata.Firmware = "uefi"
|
|
metadata.SecureBoot = strings.EqualFold(domain.OS.Loader.Secure, "yes")
|
|
}
|
|
if domain.Devices != nil {
|
|
for _, disk := range domain.Devices.Disks {
|
|
item := Disk{}
|
|
if disk.Source != nil && disk.Source.File != nil {
|
|
item.Path = disk.Source.File.File
|
|
}
|
|
if disk.Target != nil {
|
|
item.Device = disk.Target.Dev
|
|
}
|
|
if disk.Driver != nil {
|
|
item.Format = disk.Driver.Type
|
|
}
|
|
metadata.Disks = append(metadata.Disks, item)
|
|
}
|
|
for _, iface := range domain.Devices.Interfaces {
|
|
item := Interface{LinkUp: iface.Link == nil || iface.Link.State != "down"}
|
|
if iface.MAC != nil {
|
|
item.MAC = iface.MAC.Address
|
|
}
|
|
if iface.Source != nil {
|
|
if iface.Source.Bridge != nil {
|
|
item.Bridge = iface.Source.Bridge.Bridge
|
|
}
|
|
if iface.Source.Network != nil {
|
|
item.Network = iface.Source.Network.Network
|
|
}
|
|
}
|
|
metadata.Interfaces = append(metadata.Interfaces, item)
|
|
}
|
|
}
|
|
return metadata, nil
|
|
}
|
|
|
|
func domainVPCPortFromPublic(value VPCPortMetadata) domainVPCPortMetadataXML {
|
|
return domainVPCPortMetadataXML{
|
|
PortKey: value.PortKey, VPCKey: value.VPCKey, PrivateIP: value.PrivateIP,
|
|
CIDR: value.CIDR, Gateway: value.Gateway, MAC: value.MAC,
|
|
Bridge: value.Bridge, HostRevision: value.HostRevision,
|
|
HostDigest: value.HostDigest,
|
|
}
|
|
}
|
|
|
|
func (value domainVPCPortMetadataXML) public() VPCPortMetadata {
|
|
return VPCPortMetadata{
|
|
PortKey: value.PortKey, VPCKey: value.VPCKey, PrivateIP: value.PrivateIP,
|
|
CIDR: value.CIDR, Gateway: value.Gateway, MAC: value.MAC,
|
|
Bridge: value.Bridge, HostRevision: value.HostRevision,
|
|
HostDigest: value.HostDigest,
|
|
}
|
|
}
|
|
|
|
func managedPublicInterfaceIndex(definition *libvirtxml.Domain,
|
|
filterName, publicIPCIDR string) (int, bool) {
|
|
if definition == nil || definition.Devices == nil {
|
|
return -1, false
|
|
}
|
|
match := -1
|
|
for index := range definition.Devices.Interfaces {
|
|
if !managedInterfaceFilterIPMatches(
|
|
&definition.Devices.Interfaces[index], filterName, publicIPCIDR,
|
|
) {
|
|
continue
|
|
}
|
|
if match >= 0 {
|
|
return -1, false
|
|
}
|
|
match = index
|
|
}
|
|
return match, match >= 0
|
|
}
|
|
|
|
func managedVPCInterfaceIndex(definition *libvirtxml.Domain,
|
|
port *domainVPCPortMetadataXML) (int, bool) {
|
|
if definition == nil || definition.Devices == nil || port == nil {
|
|
return -1, false
|
|
}
|
|
match := -1
|
|
for index := range definition.Devices.Interfaces {
|
|
iface := &definition.Devices.Interfaces[index]
|
|
if iface.MAC == nil || !strings.EqualFold(iface.MAC.Address, port.MAC) ||
|
|
iface.Source == nil || iface.Source.Bridge == nil ||
|
|
iface.Source.Bridge.Bridge != port.Bridge || iface.Source.Network != nil ||
|
|
!managedVPCInterfaceFilterIPMatches(iface, port.PrivateIP) {
|
|
continue
|
|
}
|
|
if match >= 0 {
|
|
return -1, false
|
|
}
|
|
match = index
|
|
}
|
|
return match, match >= 0
|
|
}
|
|
|
|
func managedNetworkLayoutMatches(definition *libvirtxml.Domain,
|
|
metadata *domainMetadataXML) bool {
|
|
if definition == nil || definition.Devices == nil || metadata == nil {
|
|
return false
|
|
}
|
|
publicIndex, publicFound := managedPublicInterfaceIndex(
|
|
definition, networkFilterName(definition.UUID), metadata.PublicIPCIDR,
|
|
)
|
|
if !publicFound {
|
|
return false
|
|
}
|
|
if metadata.VPCPort == nil {
|
|
return len(definition.Devices.Interfaces) == 1 && publicIndex == 0
|
|
}
|
|
privateIndex, privateFound := managedVPCInterfaceIndex(definition, metadata.VPCPort)
|
|
return privateFound && len(definition.Devices.Interfaces) == 2 &&
|
|
publicIndex != privateIndex
|
|
}
|
|
|
|
func memoryToMiB(value uint, unit string) uint64 {
|
|
switch strings.ToLower(unit) {
|
|
case "b", "bytes":
|
|
return uint64(value) / (1024 * 1024)
|
|
case "kb", "kib", "":
|
|
return uint64(value) / 1024
|
|
case "mb", "mib":
|
|
return uint64(value)
|
|
case "gb", "gib":
|
|
return uint64(value) * 1024
|
|
default:
|
|
return 0
|
|
}
|
|
}
|