mkvm/volumes/pools/qcow2.go
2024-12-02 20:23:28 -08:00

108 lines
2.4 KiB
Go

// Copyright Entanglement Garden Developers
// SPDX-License-Identifier: AGPL-3.0-only
package pools
import (
"fmt"
"libvirt.org/go/libvirt"
"libvirt.org/go/libvirtxml"
)
const (
StoragePoolTypeDir StoragePoolType = "dir"
ImageFormatQcow2 ImageFormat = "qcow2"
)
// DirPool is a StoragePool of type "dir"
type DirPool struct {
pool *libvirt.StoragePool
name string
}
func (p DirPool) Type() StoragePoolType {
return StoragePoolTypeDir
}
func (p DirPool) ImageFormat() ImageFormat {
return ImageFormatQcow2
}
func (p DirPool) CreateVolume(name string, sizeGB uint64) (*libvirt.StorageVol, error) {
volumeXML := &libvirtxml.StorageVolume{
Name: p.GetVolumeName(name),
Capacity: &libvirtxml.StorageVolumeSize{
Unit: "GB",
Value: sizeGB,
},
Target: &libvirtxml.StorageVolumeTarget{
Format: &libvirtxml.StorageVolumeTargetFormat{Type: "qcow2"},
},
}
xmlstr, err := volumeXML.Marshal()
if err != nil {
return nil, err
}
return p.pool.StorageVolCreateXML(xmlstr, 0)
}
func (p DirPool) DeleteVolume(name string) error {
vol, err := p.lookupVolumeByName(name)
if err != nil {
return err
}
return vol.Delete(libvirt.STORAGE_VOL_DELETE_NORMAL)
}
func (p DirPool) GetVolumeName(name string) string {
return fmt.Sprintf("%s.qcow2", name)
}
func (p DirPool) ResizeVolume(name string, newDiskSizeGB uint64) error {
vol, err := p.lookupVolumeByName(p.GetVolumeName(name))
if err != nil {
return err
}
return vol.Resize((newDiskSizeGB*1000*1000*1000)+512, 0)
}
func (p DirPool) lookupVolumeByName(name string) (*libvirt.StorageVol, error) {
return p.pool.LookupStorageVolByName(name)
}
func (p DirPool) GetDomainDiskXML(name string) libvirtxml.DomainDisk {
return libvirtxml.DomainDisk{
Device: "disk",
Driver: &libvirtxml.DomainDiskDriver{Name: "qemu", Type: "qcow2"},
Source: &libvirtxml.DomainDiskSource{
Volume: &libvirtxml.DomainDiskSourceVolume{Pool: p.name, Volume: p.GetVolumeName(name)},
},
Target: &libvirtxml.DomainDiskTarget{Dev: "vda"},
}
}
func (p DirPool) LookupVolume(name string) (*libvirt.StorageVol, error) {
return p.pool.LookupStorageVolByName(p.GetVolumeName(name))
}
func (p DirPool) Free() error {
return p.pool.Free()
}
// NewDirPool creates a storage pool of type dir
func NewDirPool(pool *libvirt.StoragePool) (StoragePool, error) {
name, err := pool.GetName()
if err != nil {
return DirPool{}, err
}
return DirPool{pool: pool, name: name}, nil
}
func init() {
drivers["dir"] = NewDirPool
}