@ -30,6 +30,61 @@ type Libvirt struct {
traffic * trafficStore
}
type createVMFailureStage struct {
code string
message string
}
var (
createVMTemplateLookupStage = createVMFailureStage {
code : "template_lookup_failed" , message : "template metadata or volume could not be located" ,
}
createVMTemplateCapacityStage = createVMFailureStage {
code : "template_capacity_failed" , message : "template capacity could not satisfy the requested disk" ,
}
createVMStorageCloneStage = createVMFailureStage {
code : "storage_clone_failed" , message : "system disk could not be cloned from the template" ,
}
createVMSeedCreateStage = createVMFailureStage {
code : "seed_create_failed" , message : "cloud-init seed volume could not be created" ,
}
createVMSeedUploadStage = createVMFailureStage {
code : "seed_upload_failed" , message : "cloud-init seed data could not be uploaded" ,
}
createVMNWFilterDefineStage = createVMFailureStage {
code : "nwfilter_define_failed" , message : "virtual machine network filter could not be defined" ,
}
createVMDomainDefineStage = createVMFailureStage {
code : "domain_define_failed" , message : "virtual machine definition could not be created" ,
}
createVMDomainAutostartStage = createVMFailureStage {
code : "domain_autostart_failed" , message : "virtual machine autostart could not be enabled" ,
}
createVMDomainStartStage = createVMFailureStage {
code : "domain_start_failed" , message : "virtual machine could not be started" ,
}
)
type createVMStageError struct {
stage createVMFailureStage
cause error
}
func ( e * createVMStageError ) Error ( ) string { return e . stage . message }
func ( e * createVMStageError ) Unwrap ( ) error { return e . cause }
func ( e * createVMStageError ) PublicCode ( ) string { return e . stage . code }
func ( e * createVMStageError ) PublicMessage ( ) string { return e . stage . message }
// wrap exposes only a stable stage code and bounded public message. The full
// cause remains in the error chain for local diagnostics and, importantly,
// preserves operation uncertainty and the original hypervisor error kind.
func ( stage createVMFailureStage ) wrap ( cause error ) error {
if cause == nil {
return nil
}
return & createVMStageError { stage : stage , cause : cause }
}
func OpenLibvirt ( uri string , local LocalConfig ) ( Hypervisor , error ) {
if uri != "qemu:///system" {
return nil , NewError ( ErrInvalid , "invalid_libvirt_uri" , "only qemu:///system is allowed" , nil )
@ -192,7 +247,7 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
attachment . MAC = mac
templateRecord , err := l . loadImageTemplate ( request . TemplateID )
if err != nil {
return VMMetadata { } , err
return VMMetadata { } , createVMTemplateLookupStage. wrap ( err)
}
if templateRecord . GenerationToken != request . TemplateGenerationToken {
return VMMetadata { } , NewError ( ErrConflict , "template_generation_changed" , "template generation token no longer matches" , nil )
@ -220,12 +275,13 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
cleanupErr := root . Delete ( libvirt . STORAGE_VOL_DELETE_NORMAL )
_ = root . Free ( )
if cleanupErr != nil {
return VMMetadata { } , operation . MarkUncertain ( errors. Join (
return VMMetadata { } , operation . MarkUncertain ( createVMStorageCloneStage. wrap ( errors. Join (
mutationLibvirtError ( "resolve cloned root volume path" , err ) ,
mutationLibvirtError ( "roll back cloned root volume" , cleanupErr ) ,
) )
) ) )
}
return VMMetadata { } , mutationLibvirtError ( "resolve cloned root volume path" , err )
return VMMetadata { } , createVMStorageCloneStage . wrap (
mutationLibvirtError ( "resolve cloned root volume path" , err ) )
}
rootOwned := true
defer func ( ) {
@ -247,12 +303,13 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
cleanupErr := seedVolume . Delete ( libvirt . STORAGE_VOL_DELETE_NORMAL )
_ = seedVolume . Free ( )
if cleanupErr != nil {
return VMMetadata { } , operation . MarkUncertain ( errors. Join (
return VMMetadata { } , operation . MarkUncertain ( createVMSeedCreateStage. wrap ( errors. Join (
mutationLibvirtError ( "resolve NoCloud volume path" , err ) ,
mutationLibvirtError ( "roll back NoCloud seed volume" , cleanupErr ) ,
) )
) ) )
}
return VMMetadata { } , mutationLibvirtError ( "resolve NoCloud volume path" , err )
return VMMetadata { } , createVMSeedCreateStage . wrap (
mutationLibvirtError ( "resolve NoCloud volume path" , err ) )
}
seedOwned := true
defer func ( ) {
@ -268,11 +325,19 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
filterName := networkFilterName ( request . UUID )
filterDocument , err := BuildPlatformFilterXML ( filterName , request . PlatformNetworkPolicy )
if err != nil {
return VMMetadata { } , err
return VMMetadata { } , createVMNWFilterDefineStage. wrap ( err)
}
filter , err := l . conn . NWFilterDefineXML ( filterDocument )
if err != nil {
return VMMetadata { } , operation . MarkUncertain ( mutationLibvirtError ( "define VM network filter" , err ) )
observed , inspectErr := l . lookupOptionalNetworkFilter ( filterName )
artifactExists := observed != nil
if observed != nil {
_ = observed . Free ( )
}
return VMMetadata { } , createVMNWFilterDefineStage . wrap (
deterministicArtifactCreateFailure (
"define VM network filter" , err , inspectErr , artifactExists ,
) )
}
filterOwned := true
defer func ( ) {
@ -302,7 +367,7 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
PlatformNetworkPolicy : request . PlatformNetworkPolicy ,
} )
if err != nil {
return VMMetadata { } , err
return VMMetadata { } , createVMDomainDefineStage. wrap ( err)
}
trafficCreated , err := l . traffic . initialize ( request . UUID , time . Now ( ) . UTC ( ) )
if err != nil {
@ -333,12 +398,12 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
// not let deferred cleanup remove disks, firewall, or accounting
// state that the possibly-defined domain owns.
preserveDefinedDomainArtifacts ( )
return VMMetadata { } , operation . MarkUncertain ( errors. Join (
return VMMetadata { } , operation . MarkUncertain ( createVMDomainDefineStage. wrap ( errors. Join (
mutationLibvirtError ( "define domain" , err ) ,
translateOptionalLibvirtError ( "inspect domain after define failure" , inspectErr ) ,
) )
) ) )
}
return VMMetadata { } , mutationLibvirtError ( "define domain" , err )
return VMMetadata { } , createVMDomainDefineStage . wrap ( mutationLibvirtError ( "define domain" , err ) )
}
defer domain . Free ( )
if err := domain . SetAutostart ( true ) ; err != nil {
@ -346,26 +411,28 @@ func (l *Libvirt) CreateVM(ctx context.Context, request CreateVMRequest) (_ VMMe
absent , inspectErr := l . deleteDomainAbsent ( ctx , request . UUID )
if inspectErr != nil || ! absent {
preserveDefinedDomainArtifacts ( )
return VMMetadata { } , operation . MarkUncertain ( errors. Join (
return VMMetadata { } , operation . MarkUncertain ( createVMDomainAutostartStage. wrap ( errors. Join (
mutationLibvirtError ( "enable domain autostart" , err ) ,
optionalMutationLibvirtError ( "roll back domain definition" , rollbackErr ) ,
inspectErr ,
) )
) ) )
}
if rollbackErr != nil {
return VMMetadata { } , operation . MarkUncertain ( errors. Join (
return VMMetadata { } , operation . MarkUncertain ( createVMDomainAutostartStage. wrap ( errors. Join (
mutationLibvirtError ( "enable domain autostart" , err ) ,
mutationLibvirtError ( "roll back domain definition" , rollbackErr ) ,
) )
) ) )
}
return VMMetadata { } , mutationLibvirtError ( "enable domain autostart" , err )
return VMMetadata { } , createVMDomainAutostartStage . wrap (
mutationLibvirtError ( "enable domain autostart" , err ) )
}
preserveDefinedDomainArtifacts ( )
// From this point onward Domain.Create may have taken effect even if its
// response is lost. Retain the zero baseline so reconciliation and the
// first successful sample account for all traffic since initial boot.
if err := domain . Create ( ) ; err != nil {
return VMMetadata { } , operation . MarkUncertain ( mutationLibvirtError ( "start newly defined domain" , err ) )
return VMMetadata { } , operation . MarkUncertain ( createVMDomainStartStage . wrap (
mutationLibvirtError ( "start newly defined domain" , err ) ) )
}
if err := l . verifyCreatedDomain ( domain , request , filterName , mac ) ; err != nil {
return VMMetadata { } , operation . MarkUncertain ( err )
@ -421,32 +488,37 @@ func (l *Libvirt) resolvePublicNetwork(ctx context.Context,
func ( l * Libvirt ) cloneRootVolume ( request CreateVMRequest ) ( * libvirt . StorageVol , error ) {
templateRecord , err := l . loadImageTemplate ( request . TemplateID )
if err != nil {
return nil , err
return nil , createVMTemplateLookupStage. wrap ( err)
}
if templateRecord . GenerationToken != request . TemplateGenerationToken {
return nil , NewError ( ErrConflict , "template_generation_changed" , "template generation token no longer matches" , nil )
}
templatePool , err := l . conn . LookupStoragePoolByName ( l . local . TemplateStoragePool )
if err != nil {
return nil , translateLibvirtError ( "lookup template storage pool" , err )
return nil , createVMTemplateLookupStage . wrap (
translateLibvirtError ( "lookup template storage pool" , err ) )
}
defer templatePool . Free ( )
template , err := templatePool . LookupStorageVolByName ( templateVolumeName ( request . TemplateID ) )
if err != nil {
return nil , translateLibvirtError ( "lookup template volume" , err )
return nil , createVMTemplateLookupStage . wrap (
translateLibvirtError ( "lookup template volume" , err ) )
}
defer template . Free ( )
templateInfo , err := template . GetInfo ( )
if err != nil {
return nil , translateLibvirtError ( "read template volume size" , err )
return nil , createVMTemplateCapacityStage . wrap (
translateLibvirtError ( "read template volume size" , err ) )
}
capacity := request . DiskGiB << 30
if capacity < templateInfo . Capacity {
return nil , NewError ( ErrInvalid , "disk_smaller_than_template" , "disk_gib is smaller than the selected template" , nil )
return nil , createVMTemplateCapacityStage . wrap ( NewError (
ErrInvalid , "disk_smaller_than_template" , "disk_gib is smaller than the selected template" , nil ) )
}
managedPool , err := l . conn . LookupStoragePoolByName ( l . local . ManagedStoragePool )
if err != nil {
return nil , translateLibvirtError ( "lookup managed storage pool" , err )
return nil , createVMStorageCloneStage . wrap (
translateLibvirtError ( "lookup managed storage pool" , err ) )
}
defer managedPool . Free ( )
definition := libvirtxml . StorageVolume {
@ -458,11 +530,16 @@ func (l *Libvirt) cloneRootVolume(request CreateVMRequest) (*libvirt.StorageVol,
}
document , err := definition . Marshal ( )
if err != nil {
return nil , fmt. Errorf ( "marshal root volume XML: %w" , err )
return nil , createVMStorageCloneStage. wrap ( fmt. Errorf ( "marshal root volume XML: %w" , err ) )
}
volume , err := managedPool . StorageVolCreateXMLFrom ( document , template , 0 )
if err != nil {
return nil , operation . MarkUncertain ( mutationLibvirtError ( "clone template volume" , err ) )
artifactAbsent , inspectErr := l . dirPoolVolumeAbsent (
managedPool , rootVolumeName ( request . UUID ) ,
)
return nil , createVMStorageCloneStage . wrap ( deterministicArtifactCreateFailure (
"clone template volume" , err , inspectErr , ! artifactAbsent ,
) )
}
return volume , nil
}
@ -470,7 +547,8 @@ func (l *Libvirt) cloneRootVolume(request CreateVMRequest) (*libvirt.StorageVol,
func ( l * Libvirt ) createSeedVolume ( uuid string , contents [ ] byte ) ( * libvirt . StorageVol , error ) {
pool , err := l . conn . LookupStoragePoolByName ( l . local . SeedStoragePool )
if err != nil {
return nil , translateLibvirtError ( "lookup seed storage pool" , err )
return nil , createVMSeedCreateStage . wrap (
translateLibvirtError ( "lookup seed storage pool" , err ) )
}
defer pool . Free ( )
definition := libvirtxml . StorageVolume {
@ -480,20 +558,24 @@ func (l *Libvirt) createSeedVolume(uuid string, contents []byte) (*libvirt.Stora
}
document , err := definition . Marshal ( )
if err != nil {
return nil , fmt. Errorf ( "marshal seed volume XML: %w" , err )
return nil , createVMSeedCreateStage. wrap ( fmt. Errorf ( "marshal seed volume XML: %w" , err ) )
}
volume , err := pool . StorageVolCreateXML ( document , 0 )
if err != nil {
return nil , operation . MarkUncertain ( mutationLibvirtError ( "create NoCloud volume" , err ) )
artifactAbsent , inspectErr := l . dirPoolVolumeAbsent ( pool , seedVolumeName ( uuid ) )
return nil , createVMSeedCreateStage . wrap ( deterministicArtifactCreateFailure (
"create NoCloud volume" , err , inspectErr , ! artifactAbsent ,
) )
}
if err := l . uploadVolume ( volume , contents ) ; err != nil {
uploadErr := createVMSeedUploadStage . wrap ( err )
cleanupErr := volume . Delete ( libvirt . STORAGE_VOL_DELETE_NORMAL )
_ = volume . Free ( )
if cleanupErr != nil {
return nil , operation . MarkUncertain ( errors . Join ( e rr,
return nil , operation . MarkUncertain ( errors . Join ( uploadE rr,
mutationLibvirtError ( "roll back NoCloud seed volume" , cleanupErr ) ) )
}
return nil , e rr
return nil , uploadE rr
}
return volume , nil
}
@ -1015,10 +1097,7 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
// These reconciliation paths can continue only target-state or cleanup
// steps uniquely owned by the original operation. Serialize them with
// normal domain mutations; the journal already holds the per-VM lock.
if record . Action == "delete-vm" || record . Action == "reinstall-vm" ||
strings . HasPrefix ( record . Action , "create-snapshot:" ) ||
strings . HasPrefix ( record . Action , "delete-snapshot:" ) ||
strings . HasPrefix ( record . Action , "restore-snapshot:" ) {
if reconciliationNeedsDomainMutationLock ( record . Action ) {
domainMutationMu . Lock ( )
defer domainMutationMu . Unlock ( )
}
@ -1093,6 +1172,13 @@ func (l *Libvirt) Reconcile(ctx context.Context, record operation.Record) (opera
return operation . Resolution { } , nil
}
func reconciliationNeedsDomainMutationLock ( action string ) bool {
return action == "create-vm" || action == "delete-vm" || action == "reinstall-vm" ||
strings . HasPrefix ( action , "create-snapshot:" ) ||
strings . HasPrefix ( action , "delete-snapshot:" ) ||
strings . HasPrefix ( action , "restore-snapshot:" )
}
func ( l * Libvirt ) reconcileExistingDelete ( ctx context . Context , uuid string ,
domain * libvirt . Domain ) ( operation . Resolution , error ) {
_ , managed , err := requireManagedDomain ( domain )
@ -1271,11 +1357,21 @@ func (l *Libvirt) cleanupDeletedVMArtifacts(ctx context.Context, uuid string) er
}
func ( l * Libvirt ) deleteArtifactsAbsent ( uuid string ) ( bool , error ) {
if ! uuidPattern . MatchString ( uuid ) {
return false , NewError ( ErrInvalid , "invalid_uuid" , "uuid must be canonical" , nil )
}
pool , err := l . conn . LookupStoragePoolByName ( l . local . ManagedStoragePool )
if err != nil {
return false , translateLibvirtError ( "lookup managed storage pool" , err )
}
defer pool . Free ( )
rootAbsent , err := l . dirPoolVolumeAbsent ( pool , rootVolumeName ( uuid ) )
if err != nil {
return false , err
}
if ! rootAbsent {
return false , nil
}
inventory , err := pool . ListStorageVolumes ( )
if err != nil {
return false , translateLibvirtError ( "list managed volumes for reconciliation" , err )
@ -1287,12 +1383,16 @@ func (l *Libvirt) deleteArtifactsAbsent(uuid string) (bool, error) {
if len ( owned ) != 0 {
return false , nil
}
seed , err := l . lookupOptionalManagedVolume ( l . local . SeedStoragePool , seedVolumeName ( uuid ) )
seedPool , err := l . conn . LookupStoragePoolByName ( l . local . SeedStoragePool )
if err != nil {
return false , translateLibvirtError ( "lookup seed storage pool" , err )
}
defer seedPool . Free ( )
seedAbsent , err := l . dirPoolVolumeAbsent ( seedPool , seedVolumeName ( uuid ) )
if err != nil {
return false , err
}
if seed != nil {
_ = seed . Free ( )
if ! seedAbsent {
return false , nil
}
filter , err := l . lookupOptionalNetworkFilter ( networkFilterName ( uuid ) )