kubevirt.io/api@v1.2.0/core/v1/types.go (about)

     1  /*
     2   * This file is part of the KubeVirt project
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   * Copyright 2017 Red Hat, Inc.
    17   *
    18   */
    19  
    20  package v1
    21  
    22  /*
    23   ATTENTION: Rerun code generators when comments on structs or fields are modified.
    24  */
    25  
    26  import (
    27  	"encoding/json"
    28  	"fmt"
    29  
    30  	k8sv1 "k8s.io/api/core/v1"
    31  	"k8s.io/apimachinery/pkg/api/resource"
    32  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    33  	"k8s.io/apimachinery/pkg/runtime/schema"
    34  	"k8s.io/apimachinery/pkg/types"
    35  
    36  	cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
    37  )
    38  
    39  const DefaultGracePeriodSeconds int64 = 30
    40  
    41  // VirtualMachineInstance is *the* VirtualMachineInstance Definition. It represents a virtual machine in the runtime environment of kubernetes.
    42  //
    43  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
    44  // +genclient
    45  type VirtualMachineInstance struct {
    46  	metav1.TypeMeta   `json:",inline"`
    47  	metav1.ObjectMeta `json:"metadata,omitempty"`
    48  	// VirtualMachineInstance Spec contains the VirtualMachineInstance specification.
    49  	Spec VirtualMachineInstanceSpec `json:"spec" valid:"required"`
    50  	// Status is the high level overview of how the VirtualMachineInstance is doing. It contains information available to controllers and users.
    51  	Status VirtualMachineInstanceStatus `json:"status,omitempty"`
    52  }
    53  
    54  func (v *VirtualMachineInstance) MarshalBinary() (data []byte, err error) {
    55  	return json.Marshal(*v)
    56  }
    57  
    58  func (v *VirtualMachineInstance) UnmarshalBinary(data []byte) error {
    59  	return json.Unmarshal(data, v)
    60  }
    61  
    62  // VirtualMachineInstanceList is a list of VirtualMachines
    63  //
    64  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
    65  type VirtualMachineInstanceList struct {
    66  	metav1.TypeMeta `json:",inline"`
    67  	metav1.ListMeta `json:"metadata,omitempty"`
    68  	Items           []VirtualMachineInstance `json:"items"`
    69  }
    70  
    71  type EvictionStrategy string
    72  
    73  type StartStrategy string
    74  
    75  const (
    76  	StartStrategyPaused StartStrategy = "Paused"
    77  )
    78  
    79  // VirtualMachineInstanceSpec is a description of a VirtualMachineInstance.
    80  type VirtualMachineInstanceSpec struct {
    81  
    82  	// If specified, indicates the pod's priority.
    83  	// If not specified, the pod priority will be default or zero if there is no
    84  	// default.
    85  	// +optional
    86  	PriorityClassName string `json:"priorityClassName,omitempty"`
    87  
    88  	// Specification of the desired behavior of the VirtualMachineInstance on the host.
    89  	Domain DomainSpec `json:"domain"`
    90  	// NodeSelector is a selector which must be true for the vmi to fit on a node.
    91  	// Selector which must match a node's labels for the vmi to be scheduled on that node.
    92  	// More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
    93  	// +optional
    94  	NodeSelector map[string]string `json:"nodeSelector,omitempty"`
    95  	// If affinity is specifies, obey all the affinity rules
    96  	Affinity *k8sv1.Affinity `json:"affinity,omitempty"`
    97  	// If specified, the VMI will be dispatched by specified scheduler.
    98  	// If not specified, the VMI will be dispatched by default scheduler.
    99  	// +optional
   100  	SchedulerName string `json:"schedulerName,omitempty"`
   101  	// If toleration is specified, obey all the toleration rules.
   102  	Tolerations []k8sv1.Toleration `json:"tolerations,omitempty"`
   103  	// TopologySpreadConstraints describes how a group of VMIs will be spread across a given topology
   104  	// domains. K8s scheduler will schedule VMI pods in a way which abides by the constraints.
   105  	// +optional
   106  	// +patchMergeKey=topologyKey
   107  	// +patchStrategy=merge
   108  	// +listType=map
   109  	// +listMapKey=topologyKey
   110  	// +listMapKey=whenUnsatisfiable
   111  	TopologySpreadConstraints []k8sv1.TopologySpreadConstraint `json:"topologySpreadConstraints,omitempty" patchStrategy:"merge" patchMergeKey:"topologyKey"`
   112  	// EvictionStrategy describes the strategy to follow when a node drain occurs.
   113  	// The possible options are:
   114  	// - "None": No action will be taken, according to the specified 'RunStrategy' the VirtualMachine will be restarted or shutdown.
   115  	// - "LiveMigrate": the VirtualMachineInstance will be migrated instead of being shutdown.
   116  	// - "LiveMigrateIfPossible": the same as "LiveMigrate" but only if the VirtualMachine is Live-Migratable, otherwise it will behave as "None".
   117  	// - "External": the VirtualMachineInstance will be protected by a PDB and `vmi.Status.EvacuationNodeName` will be set on eviction. This is mainly useful for cluster-api-provider-kubevirt (capk) which needs a way for VMI's to be blocked from eviction, yet signal capk that eviction has been called on the VMI so the capk controller can handle tearing the VMI down. Details can be found in the commit description https://github.com/kubevirt/kubevirt/commit/c1d77face705c8b126696bac9a3ee3825f27f1fa.
   118  	// +optional
   119  	EvictionStrategy *EvictionStrategy `json:"evictionStrategy,omitempty"`
   120  	// StartStrategy can be set to "Paused" if Virtual Machine should be started in paused state.
   121  	//
   122  	// +optional
   123  	StartStrategy *StartStrategy `json:"startStrategy,omitempty"`
   124  	// Grace period observed after signalling a VirtualMachineInstance to stop after which the VirtualMachineInstance is force terminated.
   125  	TerminationGracePeriodSeconds *int64 `json:"terminationGracePeriodSeconds,omitempty"`
   126  	// List of volumes that can be mounted by disks belonging to the vmi.
   127  	Volumes []Volume `json:"volumes,omitempty"`
   128  	// Periodic probe of VirtualMachineInstance liveness.
   129  	// VirtualmachineInstances will be stopped if the probe fails.
   130  	// Cannot be updated.
   131  	// More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
   132  	// +optional
   133  	LivenessProbe *Probe `json:"livenessProbe,omitempty"`
   134  	// Periodic probe of VirtualMachineInstance service readiness.
   135  	// VirtualmachineInstances will be removed from service endpoints if the probe fails.
   136  	// Cannot be updated.
   137  	// More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
   138  	// +optional
   139  	ReadinessProbe *Probe `json:"readinessProbe,omitempty"`
   140  	// Specifies the hostname of the vmi
   141  	// If not specified, the hostname will be set to the name of the vmi, if dhcp or cloud-init is configured properly.
   142  	// +optional
   143  	Hostname string `json:"hostname,omitempty"`
   144  	// If specified, the fully qualified vmi hostname will be "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>".
   145  	// If not specified, the vmi will not have a domainname at all. The DNS entry will resolve to the vmi,
   146  	// no matter if the vmi itself can pick up a hostname.
   147  	// +optional
   148  	Subdomain string `json:"subdomain,omitempty"`
   149  	// List of networks that can be attached to a vm's virtual interface.
   150  	Networks []Network `json:"networks,omitempty"`
   151  	// Set DNS policy for the pod.
   152  	// Defaults to "ClusterFirst".
   153  	// Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'.
   154  	// DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy.
   155  	// To have DNS options set along with hostNetwork, you have to specify DNS policy
   156  	// explicitly to 'ClusterFirstWithHostNet'.
   157  	// +optional
   158  	DNSPolicy k8sv1.DNSPolicy `json:"dnsPolicy,omitempty" protobuf:"bytes,6,opt,name=dnsPolicy,casttype=DNSPolicy"`
   159  	// Specifies the DNS parameters of a pod.
   160  	// Parameters specified here will be merged to the generated DNS
   161  	// configuration based on DNSPolicy.
   162  	// +optional
   163  	DNSConfig *k8sv1.PodDNSConfig `json:"dnsConfig,omitempty" protobuf:"bytes,26,opt,name=dnsConfig"`
   164  	// Specifies a set of public keys to inject into the vm guest
   165  	// +listType=atomic
   166  	// +optional
   167  	AccessCredentials []AccessCredential `json:"accessCredentials,omitempty"`
   168  	// Specifies the architecture of the vm guest you are attempting to run. Defaults to the compiled architecture of the KubeVirt components
   169  	Architecture string `json:"architecture,omitempty"`
   170  }
   171  
   172  func (vmiSpec *VirtualMachineInstanceSpec) UnmarshalJSON(data []byte) error {
   173  	type VMISpecAlias VirtualMachineInstanceSpec
   174  	var vmiSpecAlias VMISpecAlias
   175  
   176  	if err := json.Unmarshal(data, &vmiSpecAlias); err != nil {
   177  		return err
   178  	}
   179  
   180  	if vmiSpecAlias.DNSConfig != nil {
   181  		for i, ns := range vmiSpecAlias.DNSConfig.Nameservers {
   182  			if sanitizedIP, err := sanitizeIP(ns); err == nil {
   183  				vmiSpecAlias.DNSConfig.Nameservers[i] = sanitizedIP
   184  			}
   185  		}
   186  	}
   187  
   188  	*vmiSpec = VirtualMachineInstanceSpec(vmiSpecAlias)
   189  	return nil
   190  }
   191  
   192  // VirtualMachineInstancePhaseTransitionTimestamp gives a timestamp in relation to when a phase is set on a vmi
   193  type VirtualMachineInstancePhaseTransitionTimestamp struct {
   194  	// Phase is the status of the VirtualMachineInstance in kubernetes world. It is not the VirtualMachineInstance status, but partially correlates to it.
   195  	Phase VirtualMachineInstancePhase `json:"phase,omitempty"`
   196  	// PhaseTransitionTimestamp is the timestamp of when the phase change occurred
   197  	PhaseTransitionTimestamp metav1.Time `json:"phaseTransitionTimestamp,omitempty"`
   198  }
   199  
   200  type TopologyHints struct {
   201  	TSCFrequency *int64 `json:"tscFrequency,omitempty"`
   202  }
   203  
   204  // VirtualMachineInstanceStatus represents information about the status of a VirtualMachineInstance. Status may trail the actual
   205  // state of a system.
   206  type VirtualMachineInstanceStatus struct {
   207  	// NodeName is the name where the VirtualMachineInstance is currently running.
   208  	NodeName string `json:"nodeName,omitempty"`
   209  	// A brief CamelCase message indicating details about why the VMI is in this state. e.g. 'NodeUnresponsive'
   210  	// +optional
   211  	Reason string `json:"reason,omitempty"`
   212  	// Conditions are specific points in VirtualMachineInstance's pod runtime.
   213  	Conditions []VirtualMachineInstanceCondition `json:"conditions,omitempty"`
   214  	// Phase is the status of the VirtualMachineInstance in kubernetes world. It is not the VirtualMachineInstance status, but partially correlates to it.
   215  	Phase VirtualMachineInstancePhase `json:"phase,omitempty"`
   216  	// PhaseTransitionTimestamp is the timestamp of when the last phase change occurred
   217  	// +listType=atomic
   218  	// +optional
   219  	PhaseTransitionTimestamps []VirtualMachineInstancePhaseTransitionTimestamp `json:"phaseTransitionTimestamps,omitempty"`
   220  	// Interfaces represent the details of available network interfaces.
   221  	Interfaces []VirtualMachineInstanceNetworkInterface `json:"interfaces,omitempty"`
   222  	// Guest OS Information
   223  	GuestOSInfo VirtualMachineInstanceGuestOSInfo `json:"guestOSInfo,omitempty"`
   224  	// Represents the status of a live migration
   225  	MigrationState *VirtualMachineInstanceMigrationState `json:"migrationState,omitempty"`
   226  	// Represents the method using which the vmi can be migrated: live migration or block migration
   227  	MigrationMethod VirtualMachineInstanceMigrationMethod `json:"migrationMethod,omitempty"`
   228  	// This represents the migration transport
   229  	MigrationTransport VirtualMachineInstanceMigrationTransport `json:"migrationTransport,omitempty"`
   230  	// The Quality of Service (QOS) classification assigned to the virtual machine instance based on resource requirements
   231  	// See PodQOSClass type for available QOS classes
   232  	// More info: https://git.k8s.io/community/contributors/design-proposals/node/resource-qos.md
   233  	// +optional
   234  	QOSClass *k8sv1.PodQOSClass `json:"qosClass,omitempty"`
   235  
   236  	// LauncherContainerImageVersion indicates what container image is currently active for the vmi.
   237  	LauncherContainerImageVersion string `json:"launcherContainerImageVersion,omitempty"`
   238  
   239  	// EvacuationNodeName is used to track the eviction process of a VMI. It stores the name of the node that we want
   240  	// to evacuate. It is meant to be used by KubeVirt core components only and can't be set or modified by users.
   241  	// +optional
   242  	EvacuationNodeName string `json:"evacuationNodeName,omitempty"`
   243  
   244  	// ActivePods is a mapping of pod UID to node name.
   245  	// It is possible for multiple pods to be running for a single VMI during migration.
   246  	ActivePods map[types.UID]string `json:"activePods,omitempty"`
   247  
   248  	// VolumeStatus contains the statuses of all the volumes
   249  	// +optional
   250  	// +listType=atomic
   251  	VolumeStatus []VolumeStatus `json:"volumeStatus,omitempty"`
   252  
   253  	// KernelBootStatus contains info about the kernelBootContainer
   254  	// +optional
   255  	KernelBootStatus *KernelBootStatus `json:"kernelBootStatus,omitempty"`
   256  
   257  	// FSFreezeStatus is the state of the fs of the guest
   258  	// it can be either frozen or thawed
   259  	// +optional
   260  	FSFreezeStatus string `json:"fsFreezeStatus,omitempty"`
   261  
   262  	// +optional
   263  	TopologyHints *TopologyHints `json:"topologyHints,omitempty"`
   264  
   265  	//VirtualMachineRevisionName is used to get the vm revision of the vmi when doing
   266  	// an online vm snapshot
   267  	// +optional
   268  	VirtualMachineRevisionName string `json:"virtualMachineRevisionName,omitempty"`
   269  
   270  	// RuntimeUser is used to determine what user will be used in launcher
   271  	// +optional
   272  	RuntimeUser uint64 `json:"runtimeUser"`
   273  
   274  	// VSOCKCID is used to track the allocated VSOCK CID in the VM.
   275  	// +optional
   276  	VSOCKCID *uint32 `json:"VSOCKCID,omitempty"`
   277  
   278  	// SELinuxContext is the actual SELinux context of the virt-launcher pod
   279  	// +optional
   280  	SelinuxContext string `json:"selinuxContext,omitempty"`
   281  
   282  	// Machine shows the final resulting qemu machine type. This can be different
   283  	// than the machine type selected in the spec, due to qemus machine type alias mechanism.
   284  	// +optional
   285  	Machine *Machine `json:"machine,omitempty"`
   286  	// CurrentCPUTopology specifies the current CPU topology used by the VM workload.
   287  	// Current topology may differ from the desired topology in the spec while CPU hotplug
   288  	// takes place.
   289  	CurrentCPUTopology *CPUTopology `json:"currentCPUTopology,omitempty"`
   290  
   291  	// Memory shows various informations about the VirtualMachine memory.
   292  	// +optional
   293  	Memory *MemoryStatus `json:"memory,omitempty"`
   294  }
   295  
   296  // PersistentVolumeClaimInfo contains the relavant information virt-handler needs cached about a PVC
   297  type PersistentVolumeClaimInfo struct {
   298  	// AccessModes contains the desired access modes the volume should have.
   299  	// More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1
   300  	// +listType=atomic
   301  	// +optional
   302  	AccessModes []k8sv1.PersistentVolumeAccessMode `json:"accessModes,omitempty"`
   303  
   304  	// VolumeMode defines what type of volume is required by the claim.
   305  	// Value of Filesystem is implied when not included in claim spec.
   306  	// +optional
   307  	VolumeMode *k8sv1.PersistentVolumeMode `json:"volumeMode,omitempty"`
   308  
   309  	// Capacity represents the capacity set on the corresponding PVC status
   310  	// +optional
   311  	Capacity k8sv1.ResourceList `json:"capacity,omitempty"`
   312  
   313  	// Requests represents the resources requested by the corresponding PVC spec
   314  	// +optional
   315  	Requests k8sv1.ResourceList `json:"requests,omitempty"`
   316  
   317  	// Preallocated indicates if the PVC's storage is preallocated or not
   318  	// +optional
   319  	Preallocated bool `json:"preallocated,omitempty"`
   320  
   321  	// Percentage of filesystem's size to be reserved when resizing the PVC
   322  	// +optional
   323  	FilesystemOverhead *cdiv1.Percent `json:"filesystemOverhead,omitempty"`
   324  }
   325  
   326  // VolumeStatus represents information about the status of volumes attached to the VirtualMachineInstance.
   327  type VolumeStatus struct {
   328  	// Name is the name of the volume
   329  	Name string `json:"name"`
   330  	// Target is the target name used when adding the volume to the VM, eg: vda
   331  	Target string `json:"target"`
   332  	// Phase is the phase
   333  	Phase VolumePhase `json:"phase,omitempty"`
   334  	// Reason is a brief description of why we are in the current hotplug volume phase
   335  	Reason string `json:"reason,omitempty"`
   336  	// Message is a detailed message about the current hotplug volume phase
   337  	Message string `json:"message,omitempty"`
   338  	// PersistentVolumeClaimInfo is information about the PVC that handler requires during start flow
   339  	PersistentVolumeClaimInfo *PersistentVolumeClaimInfo `json:"persistentVolumeClaimInfo,omitempty"`
   340  	// If the volume is hotplug, this will contain the hotplug status.
   341  	HotplugVolume *HotplugVolumeStatus `json:"hotplugVolume,omitempty"`
   342  	// Represents the size of the volume
   343  	Size int64 `json:"size,omitempty"`
   344  	// If the volume is memorydump volume, this will contain the memorydump info.
   345  	MemoryDumpVolume *DomainMemoryDumpInfo `json:"memoryDumpVolume,omitempty"`
   346  	// ContainerDiskVolume shows info about the containerdisk, if the volume is a containerdisk
   347  	ContainerDiskVolume *ContainerDiskInfo `json:"containerDiskVolume,omitempty"`
   348  }
   349  
   350  // KernelInfo show info about the kernel image
   351  type KernelInfo struct {
   352  	// Checksum is the checksum of the kernel image
   353  	Checksum uint32 `json:"checksum,omitempty"`
   354  }
   355  
   356  // InitrdInfo show info about the initrd file
   357  type InitrdInfo struct {
   358  	// Checksum is the checksum of the initrd file
   359  	Checksum uint32 `json:"checksum,omitempty"`
   360  }
   361  
   362  // KernelBootStatus contains info about the kernelBootContainer
   363  type KernelBootStatus struct {
   364  	// KernelInfo show info about the kernel image
   365  	KernelInfo *KernelInfo `json:"kernelInfo,omitempty"`
   366  	// InitrdInfo show info about the initrd file
   367  	InitrdInfo *InitrdInfo `json:"initrdInfo,omitempty"`
   368  }
   369  
   370  // DomainMemoryDumpInfo represents the memory dump information
   371  type DomainMemoryDumpInfo struct {
   372  	// StartTimestamp is the time when the memory dump started
   373  	StartTimestamp *metav1.Time `json:"startTimestamp,omitempty"`
   374  	// EndTimestamp is the time when the memory dump completed
   375  	EndTimestamp *metav1.Time `json:"endTimestamp,omitempty"`
   376  	// ClaimName is the name of the pvc the memory was dumped to
   377  	ClaimName string `json:"claimName,omitempty"`
   378  	// TargetFileName is the name of the memory dump output
   379  	TargetFileName string `json:"targetFileName,omitempty"`
   380  }
   381  
   382  // HotplugVolumeStatus represents the hotplug status of the volume
   383  type HotplugVolumeStatus struct {
   384  	// AttachPodName is the name of the pod used to attach the volume to the node.
   385  	AttachPodName string `json:"attachPodName,omitempty"`
   386  	// AttachPodUID is the UID of the pod used to attach the volume to the node.
   387  	AttachPodUID types.UID `json:"attachPodUID,omitempty"`
   388  }
   389  
   390  // ContainerDiskInfo shows info about the containerdisk
   391  type ContainerDiskInfo struct {
   392  	// Checksum is the checksum of the rootdisk or kernel artifacts inside the containerdisk
   393  	Checksum uint32 `json:"checksum,omitempty"`
   394  }
   395  
   396  // VolumePhase indicates the current phase of the hotplug process.
   397  type VolumePhase string
   398  
   399  const (
   400  	// VolumePending means the Volume is pending and cannot be attached to the node yet.
   401  	VolumePending VolumePhase = "Pending"
   402  	// VolumeBound means the Volume is bound and can be attach to the node.
   403  	VolumeBound VolumePhase = "Bound"
   404  	// HotplugVolumeAttachedToNode means the volume has been attached to the node.
   405  	HotplugVolumeAttachedToNode VolumePhase = "AttachedToNode"
   406  	// HotplugVolumeMounted means the volume has been attached to the node and is mounted to the virt-launcher pod.
   407  	HotplugVolumeMounted VolumePhase = "MountedToPod"
   408  	// VolumeReady means the volume is ready to be used by the VirtualMachineInstance.
   409  	VolumeReady VolumePhase = "Ready"
   410  	// HotplugVolumeDetaching means the volume is being detached from the node, and the attachment pod is being removed.
   411  	HotplugVolumeDetaching VolumePhase = "Detaching"
   412  	// HotplugVolumeUnMounted means the volume has been unmounted from the virt-launcer pod.
   413  	HotplugVolumeUnMounted VolumePhase = "UnMountedFromPod"
   414  	// MemoryDumpVolumeCompleted means that the requested memory dump was completed and the dump is ready in the volume
   415  	MemoryDumpVolumeCompleted VolumePhase = "MemoryDumpCompleted"
   416  	// MemoryDumpVolumeInProgress means that the volume for the memory dump was attached, and now the command is being triggered
   417  	MemoryDumpVolumeInProgress VolumePhase = "MemoryDumpInProgress"
   418  	// MemoryDumpVolumeInProgress means that the volume for the memory dump was attached, and now the command is being triggered
   419  	MemoryDumpVolumeFailed VolumePhase = "MemoryDumpFailed"
   420  )
   421  
   422  func (v *VirtualMachineInstance) IsScheduling() bool {
   423  	return v.Status.Phase == Scheduling
   424  }
   425  
   426  func (v *VirtualMachineInstance) IsScheduled() bool {
   427  	return v.Status.Phase == Scheduled
   428  }
   429  
   430  func (v *VirtualMachineInstance) IsRunning() bool {
   431  	return v.Status.Phase == Running
   432  }
   433  
   434  func (v *VirtualMachineInstance) IsMarkedForEviction() bool {
   435  	return v.Status.EvacuationNodeName != ""
   436  }
   437  
   438  func (v *VirtualMachineInstance) IsMigratable() bool {
   439  	for _, cond := range v.Status.Conditions {
   440  		if cond.Type == VirtualMachineInstanceIsMigratable && cond.Status == k8sv1.ConditionTrue {
   441  			return true
   442  		}
   443  	}
   444  	return false
   445  }
   446  
   447  func (v *VirtualMachineInstance) IsFinal() bool {
   448  	return v.Status.Phase == Failed || v.Status.Phase == Succeeded
   449  }
   450  
   451  func (v *VirtualMachineInstance) IsMarkedForDeletion() bool {
   452  	return v.ObjectMeta.DeletionTimestamp != nil
   453  }
   454  
   455  func (v *VirtualMachineInstance) IsUnknown() bool {
   456  	return v.Status.Phase == Unknown
   457  }
   458  
   459  func (v *VirtualMachineInstance) IsUnprocessed() bool {
   460  	return v.Status.Phase == Pending || v.Status.Phase == VmPhaseUnset
   461  }
   462  
   463  // Checks if CPU pinning has been requested
   464  func (v *VirtualMachineInstance) IsCPUDedicated() bool {
   465  	return v.Spec.Domain.CPU != nil && v.Spec.Domain.CPU.DedicatedCPUPlacement
   466  }
   467  
   468  func (v *VirtualMachineInstance) IsBootloaderEFI() bool {
   469  	return v.Spec.Domain.Firmware != nil && v.Spec.Domain.Firmware.Bootloader != nil &&
   470  		v.Spec.Domain.Firmware.Bootloader.EFI != nil
   471  }
   472  
   473  // WantsToHaveQOSGuaranteed checks if cpu and memoyr limits and requests are identical on the VMI.
   474  // This is the indicator that people want a VMI with QOS of guaranteed
   475  func (v *VirtualMachineInstance) WantsToHaveQOSGuaranteed() bool {
   476  	resources := v.Spec.Domain.Resources
   477  	return !resources.Requests.Memory().IsZero() && resources.Requests.Memory().Cmp(*resources.Limits.Memory()) == 0 &&
   478  		!resources.Requests.Cpu().IsZero() && resources.Requests.Cpu().Cmp(*resources.Limits.Cpu()) == 0
   479  }
   480  
   481  // ShouldStartPaused returns true if VMI should be started in paused state
   482  func (v *VirtualMachineInstance) ShouldStartPaused() bool {
   483  	return v.Spec.StartStrategy != nil && *v.Spec.StartStrategy == StartStrategyPaused
   484  }
   485  
   486  func (v *VirtualMachineInstance) IsRealtimeEnabled() bool {
   487  	return v.Spec.Domain.CPU != nil && v.Spec.Domain.CPU.Realtime != nil
   488  }
   489  
   490  // IsHighPerformanceVMI returns true if the VMI is considered as high performance.
   491  // A VMI is considered as high performance if one of the following is true:
   492  // - the vmi requests a dedicated cpu
   493  // - the realtime flag is enabled
   494  // - the vmi requests hugepages
   495  func (v *VirtualMachineInstance) IsHighPerformanceVMI() bool {
   496  	if v.Spec.Domain.CPU != nil {
   497  		if v.Spec.Domain.CPU.DedicatedCPUPlacement || v.Spec.Domain.CPU.Realtime != nil {
   498  			return true
   499  		}
   500  	}
   501  
   502  	if v.Spec.Domain.Memory != nil && v.Spec.Domain.Memory.Hugepages != nil {
   503  		return true
   504  	}
   505  
   506  	return false
   507  }
   508  
   509  type VirtualMachineInstanceConditionType string
   510  
   511  // These are valid conditions of VMIs.
   512  const (
   513  	// Provisioning means, a VMI depends on DataVolumes which are in Pending/WaitForFirstConsumer status,
   514  	// and some actions are taken to provision the PVCs for the DataVolumes
   515  	VirtualMachineInstanceProvisioning VirtualMachineInstanceConditionType = "Provisioning"
   516  
   517  	// Ready means the VMI is able to service requests and should be added to the
   518  	// load balancing pools of all matching services.
   519  	VirtualMachineInstanceReady VirtualMachineInstanceConditionType = "Ready"
   520  
   521  	// If there happens any error while trying to synchronize the VirtualMachineInstance with the Domain,
   522  	// this is reported as false.
   523  	VirtualMachineInstanceSynchronized VirtualMachineInstanceConditionType = "Synchronized"
   524  
   525  	// If the VMI was paused by the user, this is reported as true.
   526  	VirtualMachineInstancePaused VirtualMachineInstanceConditionType = "Paused"
   527  
   528  	// Reflects whether the QEMU guest agent is connected through the channel
   529  	VirtualMachineInstanceAgentConnected VirtualMachineInstanceConditionType = "AgentConnected"
   530  
   531  	// Reflects whether the QEMU guest agent updated access credentials successfully
   532  	VirtualMachineInstanceAccessCredentialsSynchronized VirtualMachineInstanceConditionType = "AccessCredentialsSynchronized"
   533  
   534  	// Reflects whether the QEMU guest agent is connected through the channel
   535  	VirtualMachineInstanceUnsupportedAgent VirtualMachineInstanceConditionType = "AgentVersionNotSupported"
   536  
   537  	// Indicates whether the VMI is live migratable
   538  	VirtualMachineInstanceIsMigratable VirtualMachineInstanceConditionType = "LiveMigratable"
   539  	// Reason means that VMI is not live migratioable because of it's disks collection
   540  	VirtualMachineInstanceReasonDisksNotMigratable = "DisksNotLiveMigratable"
   541  	// Reason means that VMI is not live migratioable because of it's network interfaces collection
   542  	VirtualMachineInstanceReasonInterfaceNotMigratable = "InterfaceNotLiveMigratable"
   543  	// Reason means that VMI is not live migratioable because it uses hotplug
   544  	VirtualMachineInstanceReasonHotplugNotMigratable = "HotplugNotLiveMigratable"
   545  	// Reason means that VMI is not live migratioable because of it's CPU mode
   546  	VirtualMachineInstanceReasonCPUModeNotMigratable = "CPUModeLiveMigratable"
   547  	// Reason means that VMI is not live migratable because it uses virtiofs
   548  	VirtualMachineInstanceReasonVirtIOFSNotMigratable = "VirtIOFSNotLiveMigratable"
   549  	// Reason means that VMI is not live migratable because it uses PCI host devices
   550  	VirtualMachineInstanceReasonHostDeviceNotMigratable = "HostDeviceNotLiveMigratable"
   551  	// Reason means that VMI is not live migratable because it uses Secure Encrypted Virtualization (SEV)
   552  	VirtualMachineInstanceReasonSEVNotMigratable = "SEVNotLiveMigratable"
   553  	// Reason means that VMI is not live migratable because it uses HyperV Reenlightenment while TSC Frequency is not available
   554  	VirtualMachineInstanceReasonNoTSCFrequencyMigratable = "NoTSCFrequencyNotLiveMigratable"
   555  	// Reason means that VMI is not live migratable because it requested SCSI persitent reservation
   556  	VirtualMachineInstanceReasonPRNotMigratable = "PersistentReservationNotLiveMigratable"
   557  	// Indicates that the VMI is in progress of Hot vCPU Plug/UnPlug
   558  	VirtualMachineInstanceVCPUChange = "HotVCPUChange"
   559  	// Indicates that the VMI is hot(un)plugging memory
   560  	VirtualMachineInstanceMemoryChange = "HotMemoryChange"
   561  
   562  	// Summarizes that all the DataVolumes attached to the VMI are Ready or not
   563  	VirtualMachineInstanceDataVolumesReady = "DataVolumesReady"
   564  
   565  	// Reason means that not all of the VMI's DVs are ready
   566  	VirtualMachineInstanceReasonNotAllDVsReady = "NotAllDVsReady"
   567  	// Reason means that all of the VMI's DVs are bound and not running
   568  	VirtualMachineInstanceReasonAllDVsReady = "AllDVsReady"
   569  )
   570  
   571  const (
   572  	// PodTerminatingReason indicates on the Ready condition on the VMI if the underlying pod is terminating
   573  	PodTerminatingReason = "PodTerminating"
   574  
   575  	// PodNotExistsReason indicates on the Ready condition on the VMI if the underlying pod does not exist
   576  	PodNotExistsReason = "PodNotExists"
   577  
   578  	// PodConditionMissingReason indicates on the Ready condition on the VMI if the underlying pod does not report a Ready condition
   579  	PodConditionMissingReason = "PodConditionMissing"
   580  
   581  	// GuestNotRunningReason indicates on the Ready condition on the VMI if the underlying guest VM is not running
   582  	GuestNotRunningReason = "GuestNotRunning"
   583  )
   584  
   585  type VirtualMachineInstanceMigrationConditionType string
   586  
   587  // These are valid conditions of VMIs.
   588  const (
   589  	// VirtualMachineInstanceMigrationAbortRequested indicates that live migration abort has been requested
   590  	VirtualMachineInstanceMigrationAbortRequested          VirtualMachineInstanceMigrationConditionType = "migrationAbortRequested"
   591  	VirtualMachineInstanceMigrationRejectedByResourceQuota VirtualMachineInstanceMigrationConditionType = "migrationRejectedByResourceQuota"
   592  )
   593  
   594  type VirtualMachineInstanceCondition struct {
   595  	Type   VirtualMachineInstanceConditionType `json:"type"`
   596  	Status k8sv1.ConditionStatus               `json:"status"`
   597  	// +nullable
   598  	LastProbeTime metav1.Time `json:"lastProbeTime,omitempty"`
   599  	// +nullable
   600  	LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"`
   601  	Reason             string      `json:"reason,omitempty"`
   602  	Message            string      `json:"message,omitempty"`
   603  }
   604  
   605  type VirtualMachineInstanceMigrationCondition struct {
   606  	Type   VirtualMachineInstanceMigrationConditionType `json:"type"`
   607  	Status k8sv1.ConditionStatus                        `json:"status"`
   608  	// +nullable
   609  	LastProbeTime metav1.Time `json:"lastProbeTime,omitempty"`
   610  	// +nullable
   611  	LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"`
   612  	Reason             string      `json:"reason,omitempty"`
   613  	Message            string      `json:"message,omitempty"`
   614  }
   615  
   616  // The migration phase indicates that the job has completed
   617  func (m *VirtualMachineInstanceMigration) IsFinal() bool {
   618  	return m.Status.Phase == MigrationFailed || m.Status.Phase == MigrationSucceeded
   619  }
   620  
   621  func (m *VirtualMachineInstanceMigration) IsRunning() bool {
   622  	switch m.Status.Phase {
   623  	case MigrationFailed, MigrationPending, MigrationPhaseUnset, MigrationSucceeded:
   624  		return false
   625  	}
   626  	return true
   627  }
   628  
   629  // The migration phase indicates that the target pod should have already been created
   630  func (m *VirtualMachineInstanceMigration) TargetIsCreated() bool {
   631  	return m.Status.Phase != MigrationPhaseUnset &&
   632  		m.Status.Phase != MigrationPending
   633  }
   634  
   635  // The migration phase indicates that job has been handed off to the VMI controllers to complete.
   636  func (m *VirtualMachineInstanceMigration) TargetIsHandedOff() bool {
   637  	return m.Status.Phase != MigrationPhaseUnset &&
   638  		m.Status.Phase != MigrationPending &&
   639  		m.Status.Phase != MigrationScheduling &&
   640  		m.Status.Phase != MigrationScheduled
   641  }
   642  
   643  type VirtualMachineInstanceNetworkInterface struct {
   644  	// IP address of a Virtual Machine interface. It is always the first item of
   645  	// IPs
   646  	IP string `json:"ipAddress,omitempty"`
   647  	// Hardware address of a Virtual Machine interface
   648  	MAC string `json:"mac,omitempty"`
   649  	// Name of the interface, corresponds to name of the network assigned to the interface
   650  	Name string `json:"name,omitempty"`
   651  	// List of all IP addresses of a Virtual Machine interface
   652  	IPs []string `json:"ipAddresses,omitempty"`
   653  	// The interface name inside the Virtual Machine
   654  	InterfaceName string `json:"interfaceName,omitempty"`
   655  	// Specifies the origin of the interface data collected. values: domain, guest-agent, multus-status.
   656  	InfoSource string `json:"infoSource,omitempty"`
   657  	// Specifies how many queues are allocated by MultiQueue
   658  	QueueCount int32 `json:"queueCount,omitempty"`
   659  }
   660  
   661  type VirtualMachineInstanceGuestOSInfo struct {
   662  	// Name of the Guest OS
   663  	Name string `json:"name,omitempty"`
   664  	// Guest OS Kernel Release
   665  	KernelRelease string `json:"kernelRelease,omitempty"`
   666  	// Guest OS Version
   667  	Version string `json:"version,omitempty"`
   668  	// Guest OS Pretty Name
   669  	PrettyName string `json:"prettyName,omitempty"`
   670  	// Version ID of the Guest OS
   671  	VersionID string `json:"versionId,omitempty"`
   672  	// Kernel version of the Guest OS
   673  	KernelVersion string `json:"kernelVersion,omitempty"`
   674  	// Machine type of the Guest OS
   675  	Machine string `json:"machine,omitempty"`
   676  	// Guest OS Id
   677  	ID string `json:"id,omitempty"`
   678  }
   679  
   680  // MigrationConfigSource indicates the source of migration configuration.
   681  //
   682  // +k8s:openapi-gen=true
   683  type MigrationConfigSource string
   684  
   685  // +k8s:openapi-gen=true
   686  type VirtualMachineInstanceMigrationState struct {
   687  	// The time the migration action began
   688  	// +nullable
   689  	StartTimestamp *metav1.Time `json:"startTimestamp,omitempty"`
   690  	// The time the migration action ended
   691  	// +nullable
   692  	EndTimestamp *metav1.Time `json:"endTimestamp,omitempty"`
   693  
   694  	// The timestamp at which the target node detects the domain is active
   695  	TargetNodeDomainReadyTimestamp *metav1.Time `json:"targetNodeDomainReadyTimestamp,omitempty"`
   696  	// The Target Node has seen the Domain Start Event
   697  	TargetNodeDomainDetected bool `json:"targetNodeDomainDetected,omitempty"`
   698  	// The address of the target node to use for the migration
   699  	TargetNodeAddress string `json:"targetNodeAddress,omitempty"`
   700  	// The list of ports opened for live migration on the destination node
   701  	TargetDirectMigrationNodePorts map[string]int `json:"targetDirectMigrationNodePorts,omitempty"`
   702  	// The target node that the VMI is moving to
   703  	TargetNode string `json:"targetNode,omitempty"`
   704  	// The target pod that the VMI is moving to
   705  	TargetPod string `json:"targetPod,omitempty"`
   706  	// The UID of the target attachment pod for hotplug volumes
   707  	TargetAttachmentPodUID types.UID `json:"targetAttachmentPodUID,omitempty"`
   708  	// The source node that the VMI originated on
   709  	SourceNode string `json:"sourceNode,omitempty"`
   710  	// Indicates the migration completed
   711  	Completed bool `json:"completed,omitempty"`
   712  	// Indicates that the migration failed
   713  	Failed bool `json:"failed,omitempty"`
   714  	// Indicates that the migration has been requested to abort
   715  	AbortRequested bool `json:"abortRequested,omitempty"`
   716  	// Indicates the final status of the live migration abortion
   717  	AbortStatus MigrationAbortStatus `json:"abortStatus,omitempty"`
   718  	// The VirtualMachineInstanceMigration object associated with this migration
   719  	MigrationUID types.UID `json:"migrationUid,omitempty"`
   720  	// Lets us know if the vmi is currently running pre or post copy migration
   721  	Mode MigrationMode `json:"mode,omitempty"`
   722  	// Name of the migration policy. If string is empty, no policy is matched
   723  	MigrationPolicyName *string `json:"migrationPolicyName,omitempty"`
   724  	// Migration configurations to apply
   725  	MigrationConfiguration *MigrationConfiguration `json:"migrationConfiguration,omitempty"`
   726  	// If the VMI requires dedicated CPUs, this field will
   727  	// hold the dedicated CPU set on the target node
   728  	// +listType=atomic
   729  	TargetCPUSet []int `json:"targetCPUSet,omitempty"`
   730  	// If the VMI requires dedicated CPUs, this field will
   731  	// hold the numa topology on the target node
   732  	TargetNodeTopology string `json:"targetNodeTopology,omitempty"`
   733  }
   734  
   735  type MigrationAbortStatus string
   736  
   737  const (
   738  	// MigrationAbortSucceeded means that the VirtualMachineInstance live migration has been aborted
   739  	MigrationAbortSucceeded MigrationAbortStatus = "Succeeded"
   740  	// MigrationAbortFailed means that the vmi live migration has failed to be abort
   741  	MigrationAbortFailed MigrationAbortStatus = "Failed"
   742  	// MigrationAbortInProgress mean that the vmi live migration is aborting
   743  	MigrationAbortInProgress MigrationAbortStatus = "Aborting"
   744  )
   745  
   746  type MigrationMode string
   747  
   748  const (
   749  	// MigrationPreCopy means the VMI migrations that is currently running is in pre copy mode
   750  	MigrationPreCopy MigrationMode = "PreCopy"
   751  	// MigrationPostCopy means the VMI migrations that is currently running is in post copy mode
   752  	MigrationPostCopy MigrationMode = "PostCopy"
   753  )
   754  
   755  type VirtualMachineInstanceMigrationTransport string
   756  
   757  const (
   758  	// MigrationTransportUnix means that the VMI will be migrated using the unix URI
   759  	MigrationTransportUnix VirtualMachineInstanceMigrationTransport = "Unix"
   760  )
   761  
   762  type VirtualMachineInstanceMigrationMethod string
   763  
   764  const (
   765  	// BlockMigration means that all VirtualMachineInstance disks should be copied over to the destination host
   766  	BlockMigration VirtualMachineInstanceMigrationMethod = "BlockMigration"
   767  	// LiveMigration means that VirtualMachineInstance disks will not be copied over to the destination host
   768  	LiveMigration VirtualMachineInstanceMigrationMethod = "LiveMigration"
   769  )
   770  
   771  // VirtualMachineInstancePhase is a label for the condition of a VirtualMachineInstance at the current time.
   772  type VirtualMachineInstancePhase string
   773  
   774  // These are the valid statuses of pods.
   775  const (
   776  	//When a VirtualMachineInstance Object is first initialized and no phase, or Pending is present.
   777  	VmPhaseUnset VirtualMachineInstancePhase = ""
   778  	// Pending means the VirtualMachineInstance has been accepted by the system.
   779  	Pending VirtualMachineInstancePhase = "Pending"
   780  	// A target Pod exists but is not yet scheduled and in running state.
   781  	Scheduling VirtualMachineInstancePhase = "Scheduling"
   782  	// A target pod was scheduled and the system saw that Pod in runnig state.
   783  	// Here is where the responsibility of virt-controller ends and virt-handler takes over.
   784  	Scheduled VirtualMachineInstancePhase = "Scheduled"
   785  	// Running means the pod has been bound to a node and the VirtualMachineInstance is started.
   786  	Running VirtualMachineInstancePhase = "Running"
   787  	// Succeeded means that the VirtualMachineInstance stopped voluntarily, e.g. reacted to SIGTERM or shutdown was invoked from
   788  	// inside the VirtualMachineInstance.
   789  	Succeeded VirtualMachineInstancePhase = "Succeeded"
   790  	// Failed means that the vmi crashed, disappeared unexpectedly or got deleted from the cluster before it was ever started.
   791  	Failed VirtualMachineInstancePhase = "Failed"
   792  	// Unknown means that for some reason the state of the VirtualMachineInstance could not be obtained, typically due
   793  	// to an error in communicating with the host of the VirtualMachineInstance.
   794  	Unknown VirtualMachineInstancePhase = "Unknown"
   795  )
   796  
   797  const (
   798  	// AppLabel and AppName labels marks resources that belong to KubeVirt. An optional value
   799  	// may indicate which specific KubeVirt component a resource belongs to.
   800  	AppLabel string = "kubevirt.io"
   801  	AppName  string = "name"
   802  	// This annotation is used to match virtual machine instances represented as
   803  	// libvirt XML domains with their pods. Among other things, the annotation is
   804  	// used to detect virtual machines with dead pods. Used on Pod.
   805  	DomainAnnotation string = "kubevirt.io/domain"
   806  	// Represents the name of the migration job this target pod is associated with
   807  	MigrationJobNameAnnotation                    string = "kubevirt.io/migrationJobName"
   808  	ControllerAPILatestVersionObservedAnnotation  string = "kubevirt.io/latest-observed-api-version"
   809  	ControllerAPIStorageVersionObservedAnnotation string = "kubevirt.io/storage-observed-api-version"
   810  	// Used by functional tests to force a VMI to fail the migration internally within launcher
   811  	FuncTestForceLauncherMigrationFailureAnnotation string = "kubevirt.io/func-test-force-launcher-migration-failure"
   812  	// Used by functional tests to prevent virt launcher from finishing the target pod preparation.
   813  	FuncTestBlockLauncherPrepareMigrationTargetAnnotation string = "kubevirt.io/func-test-block-migration-target-preparation"
   814  
   815  	// Used by functional tests set custom image on migration target pod
   816  	FuncTestMigrationTargetImageOverrideAnnotation string = "kubevirt.io/func-test-migration-target-image-override"
   817  
   818  	// Used by functional tests to simulate virt-launcher crash looping
   819  	FuncTestLauncherFailFastAnnotation string = "kubevirt.io/func-test-virt-launcher-fail-fast"
   820  
   821  	// Used by functional tests to ignore backoff applied to migrations
   822  	FuncTestForceIgnoreMigrationBackoffAnnotation string = "kubevirt.io/func-test-ignore-migration-backoff"
   823  
   824  	// This label is used to match virtual machine instance IDs with pods.
   825  	// Similar to kubevirt.io/domain. Used on Pod.
   826  	// Internal use only.
   827  	CreatedByLabel string = "kubevirt.io/created-by"
   828  	// This label is used to indicate that this pod is the target of a migration job.
   829  	MigrationJobLabel string = "kubevirt.io/migrationJobUID"
   830  	// This label indicates the migration name that a PDB is protecting.
   831  	MigrationNameLabel string = "kubevirt.io/migrationName"
   832  	// This label describes which cluster node runs the virtual machine
   833  	// instance. Needed because with CRDs we can't use field selectors. Used on
   834  	// VirtualMachineInstance.
   835  	NodeNameLabel string = "kubevirt.io/nodeName"
   836  	// This label describes which cluster node runs the target Pod for a Virtual
   837  	// Machine Instance migration job. Needed because with CRDs we can't use field
   838  	// selectors. Used on VirtualMachineInstance.
   839  	MigrationTargetNodeNameLabel string = "kubevirt.io/migrationTargetNodeName"
   840  	// This annotation indicates that a migration is the result of an
   841  	// automated evacuation
   842  	EvacuationMigrationAnnotation string = "kubevirt.io/evacuationMigration"
   843  	// This annotation indicates that a migration is the result of an
   844  	// automated workload update
   845  	WorkloadUpdateMigrationAnnotation string = "kubevirt.io/workloadUpdateMigration"
   846  	// This label declares whether a particular node is available for
   847  	// scheduling virtual machine instances on it. Used on Node.
   848  	NodeSchedulable string = "kubevirt.io/schedulable"
   849  	// This annotation is regularly updated by virt-handler to help determine
   850  	// if a particular node is alive and hence should be available for new
   851  	// virtual machine instance scheduling. Used on Node.
   852  	VirtHandlerHeartbeat string = "kubevirt.io/heartbeat"
   853  	// This label indicates what launcher image a VMI is currently running with.
   854  	OutdatedLauncherImageLabel string = "kubevirt.io/outdatedLauncherImage"
   855  	// Namespace recommended by Kubernetes for commonly recognized labels
   856  	AppLabelPrefix = "app.kubernetes.io"
   857  	// This label is commonly used by 3rd party management tools to identify
   858  	// an application's name.
   859  	AppNameLabel = AppLabelPrefix + "/name"
   860  	// This label is commonly used by 3rd party management tools to identify
   861  	// an application's version.
   862  	AppVersionLabel = AppLabelPrefix + "/version"
   863  	// This label is commonly used by 3rd party management tools to identify
   864  	// a higher level application.
   865  	AppPartOfLabel = AppLabelPrefix + "/part-of"
   866  	// This label is commonly used by 3rd party management tools to identify
   867  	// the component this application is a part of.
   868  	AppComponentLabel = AppLabelPrefix + "/component"
   869  	// This label identifies each resource as part of KubeVirt
   870  	AppComponent = "kubevirt"
   871  	// This label will be set on all resources created by the operator
   872  	ManagedByLabel                 = AppLabelPrefix + "/managed-by"
   873  	ManagedByLabelOperatorValue    = "virt-operator"
   874  	ManagedByLabelOperatorOldValue = "kubevirt-operator"
   875  	// This annotation represents the kubevirt version for an install strategy configmap.
   876  	InstallStrategyVersionAnnotation = "kubevirt.io/install-strategy-version"
   877  	// This annotation represents the kubevirt registry used for an install strategy configmap.
   878  	InstallStrategyRegistryAnnotation = "kubevirt.io/install-strategy-registry"
   879  	// This annotation represents the kubevirt deployment identifier used for an install strategy configmap.
   880  	InstallStrategyIdentifierAnnotation = "kubevirt.io/install-strategy-identifier"
   881  	// This annotation shows the enconding used for the manifests in the Install Strategy ConfigMap.
   882  	InstallStrategyConfigMapEncoding = "kubevirt.io/install-strategy-cm-encoding"
   883  	// This annotation is a hash of all customizations that live under spec.CustomizeComponents
   884  	KubeVirtCustomizeComponentAnnotationHash = "kubevirt.io/customizer-identifier"
   885  	// This annotation represents the kubevirt generation that was used to create a resource
   886  	KubeVirtGenerationAnnotation = "kubevirt.io/generation"
   887  	// This annotation represents that this object is for temporary use during updates
   888  	EphemeralBackupObject = "kubevirt.io/ephemeral-backup-object"
   889  	// This annotation represents that the annotated object is for temporary use during pod/volume provisioning
   890  	EphemeralProvisioningObject string = "kubevirt.io/ephemeral-provisioning"
   891  
   892  	// This label indicates the object is a part of the install strategy retrieval process.
   893  	InstallStrategyLabel = "kubevirt.io/install-strategy"
   894  
   895  	// Set by virt-operator to coordinate component deletion
   896  	VirtOperatorComponentFinalizer string = "kubevirt.io/virtOperatorFinalizer"
   897  
   898  	// Set by VMI controller to ensure VMIs are processed during deletion
   899  	VirtualMachineInstanceFinalizer string = "foregroundDeleteVirtualMachine"
   900  	// Set By VM controller on VMIs to ensure VMIs are processed by VM controller during deletion
   901  	VirtualMachineControllerFinalizer        string = "kubevirt.io/virtualMachineControllerFinalize"
   902  	VirtualMachineInstanceMigrationFinalizer string = "kubevirt.io/migrationJobFinalize"
   903  	CPUManager                               string = "cpumanager"
   904  	// This annotation is used to inject ignition data
   905  	// Used on VirtualMachineInstance.
   906  	IgnitionAnnotation           string = "kubevirt.io/ignitiondata"
   907  	PlacePCIDevicesOnRootComplex string = "kubevirt.io/placePCIDevicesOnRootComplex"
   908  
   909  	// This label represents supported cpu features on the node
   910  	CPUFeatureLabel = "cpu-feature.node.kubevirt.io/"
   911  	// This label represents supported cpu models on the node
   912  	CPUModelLabel                  = "cpu-model.node.kubevirt.io/"
   913  	SupportedHostModelMigrationCPU = "cpu-model-migration.node.kubevirt.io/"
   914  	CPUTimerLabel                  = "cpu-timer.node.kubevirt.io/"
   915  	// This label represents supported HyperV features on the node
   916  	HypervLabel = "hyperv.node.kubevirt.io/"
   917  	// This label represents vendor of cpu model on the node
   918  	CPUModelVendorLabel = "cpu-vendor.node.kubevirt.io/"
   919  
   920  	VirtIO = "virtio"
   921  
   922  	// This label represents the host model CPU name
   923  	HostModelCPULabel = "host-model-cpu.node.kubevirt.io/"
   924  	// This label represents the host model required features
   925  	HostModelRequiredFeaturesLabel = "host-model-required-features.node.kubevirt.io/"
   926  	NodeHostModelIsObsoleteLabel   = "node-labeller.kubevirt.io/obsolete-host-model"
   927  
   928  	LabellerSkipNodeAnnotation        = "node-labeller.kubevirt.io/skip-node"
   929  	VirtualMachineLabel               = AppLabel + "/vm"
   930  	MemfdMemoryBackend         string = "kubevirt.io/memfd"
   931  
   932  	MigrationSelectorLabel = "kubevirt.io/vmi-name"
   933  
   934  	// This annotation represents vmi running nonroot implementation
   935  	DeprecatedNonRootVMIAnnotation = "kubevirt.io/nonroot"
   936  
   937  	// This annotation is to keep virt launcher container alive when an VMI encounters a failure for debugging purpose
   938  	KeepLauncherAfterFailureAnnotation string = "kubevirt.io/keep-launcher-alive-after-failure"
   939  
   940  	// MigrationTransportUnixAnnotation means that the VMI will be migrated using the unix URI
   941  	MigrationTransportUnixAnnotation string = "kubevirt.io/migrationTransportUnix"
   942  
   943  	// MigrationUnschedulablePodTimeoutSecondsAnnotation represents a custom timeout period used for unschedulable target pods
   944  	// This exists for functional testing
   945  	MigrationUnschedulablePodTimeoutSecondsAnnotation string = "kubevirt.io/migrationUnschedulablePodTimeoutSeconds"
   946  
   947  	// MigrationPendingPodTimeoutSecondsAnnotation represents a custom timeout period used for target pods stuck in pending for any reason
   948  	// This exists for functional testing
   949  	MigrationPendingPodTimeoutSecondsAnnotation string = "kubevirt.io/migrationPendingPodTimeoutSeconds"
   950  
   951  	// CustomLibvirtLogFiltersAnnotation can be used to customized libvirt log filters. Example value could be
   952  	// "3:remote 4:event 3:util.json 3:util.object 3:util.dbus 3:util.netlink 3:node_device 3:rpc 3:access 1:*".
   953  	// For more info: https://libvirt.org/kbase/debuglogs.html
   954  	CustomLibvirtLogFiltersAnnotation string = "kubevirt.io/libvirt-log-filters"
   955  
   956  	// RealtimeLabel marks the node as capable of running realtime workloads
   957  	RealtimeLabel string = "kubevirt.io/realtime"
   958  
   959  	// VirtualMachineUnpaused is a custom pod condition set for the virt-launcher pod.
   960  	// It's used as a readiness gate to prevent paused VMs from being marked as ready.
   961  	VirtualMachineUnpaused k8sv1.PodConditionType = "kubevirt.io/virtual-machine-unpaused"
   962  
   963  	// SEVLabel marks the node as capable of running workloads with SEV
   964  	SEVLabel string = "kubevirt.io/sev"
   965  
   966  	// SEVESLabel marks the node as capable of running workloads with SEV-ES
   967  	SEVESLabel string = "kubevirt.io/sev-es"
   968  
   969  	// KSMEnabledLabel marks the node as KSM enabled
   970  	KSMEnabledLabel string = "kubevirt.io/ksm-enabled"
   971  
   972  	// KSMHandlerManagedAnnotation is an annotation used to mark the nodes where the virt-handler has enabled the ksm
   973  	KSMHandlerManagedAnnotation string = "kubevirt.io/ksm-handler-managed"
   974  
   975  	// KSM debug annotations to override default constants
   976  	KSMPagesBoostOverride      string = "kubevirt.io/ksm-pages-boost-override"
   977  	KSMPagesDecayOverride      string = "kubevirt.io/ksm-pages-decay-override"
   978  	KSMPagesMinOverride        string = "kubevirt.io/ksm-pages-min-override"
   979  	KSMPagesMaxOverride        string = "kubevirt.io/ksm-pages-max-override"
   980  	KSMPagesInitOverride       string = "kubevirt.io/ksm-pages-init-override"
   981  	KSMSleepMsBaselineOverride string = "kubevirt.io/ksm-sleep-ms-baseline-override"
   982  	KSMFreePercentOverride     string = "kubevirt.io/ksm-free-percent-override"
   983  
   984  	// InstancetypeAnnotation is the name of a VirtualMachineInstancetype
   985  	InstancetypeAnnotation string = "kubevirt.io/instancetype-name"
   986  
   987  	// ClusterInstancetypeAnnotation is the name of a VirtualMachineClusterInstancetype
   988  	ClusterInstancetypeAnnotation string = "kubevirt.io/cluster-instancetype-name"
   989  
   990  	// InstancetypeAnnotation is the name of a VirtualMachinePreference
   991  	PreferenceAnnotation string = "kubevirt.io/preference-name"
   992  
   993  	// ClusterInstancetypeAnnotation is the name of a VirtualMachinePreferenceInstancetype
   994  	ClusterPreferenceAnnotation string = "kubevirt.io/cluster-preference-name"
   995  
   996  	// VirtualMachinePoolRevisionName is used to store the vmpool revision's name this object
   997  	// originated from.
   998  	VirtualMachinePoolRevisionName string = "kubevirt.io/vm-pool-revision-name"
   999  
  1000  	// VirtualMachineNameLabel is the name of the Virtual Machine
  1001  	VirtualMachineNameLabel string = "vm.kubevirt.io/name"
  1002  
  1003  	// PVCMemoryDumpAnnotation is the name of the memory dump representing the vm name,
  1004  	// pvc name and the timestamp the memory dump was collected
  1005  	PVCMemoryDumpAnnotation string = "kubevirt.io/memory-dump"
  1006  
  1007  	// AllowPodBridgeNetworkLiveMigrationAnnotation allow to run live migration when the
  1008  	// vm has the pod networking bind with a bridge
  1009  	AllowPodBridgeNetworkLiveMigrationAnnotation string = "kubevirt.io/allow-pod-bridge-network-live-migration"
  1010  
  1011  	// VirtualMachineGenerationAnnotation is the generation of a Virtual Machine.
  1012  	VirtualMachineGenerationAnnotation string = "kubevirt.io/vm-generation"
  1013  
  1014  	// MigrationTargetReadyTimestamp indicates the time at which the target node
  1015  	// detected that the VMI became active on the target during live migration.
  1016  	MigrationTargetReadyTimestamp string = "kubevirt.io/migration-target-ready-timestamp"
  1017  
  1018  	// FreePageReportingDisabledAnnotation indicates if the the vmi wants to explicitly disable
  1019  	// the freePageReporting feature of the memballooning.
  1020  	// This annotation only allows to opt-out from freePageReporting in those cases where it is
  1021  	// enabled (no high performance vmis).
  1022  	// This annotation does not allow to enable freePageReporting for high performance vmis,
  1023  	// in which freePageReporting is always disabled.
  1024  	FreePageReportingDisabledAnnotation string = "kubevirt.io/free-page-reporting-disabled"
  1025  
  1026  	// VirtualMachinePodCPULimitsLabel indicates VMI pod CPU resource limits
  1027  	VirtualMachinePodCPULimitsLabel string = "kubevirt.io/vmi-pod-cpu-resource-limits"
  1028  	// VirtualMachinePodMemoryRequestsLabel indicates VMI pod Memory resource requests
  1029  	VirtualMachinePodMemoryRequestsLabel string = "kubevirt.io/vmi-pod-memory-resource-requests"
  1030  	// MemoryHotplugOverheadRatioLabel indicates the guest memory overhead ratio required
  1031  	// to correctly compute the target pod memory requests when doing memory hotplug.
  1032  	// The label is used to store this value when memory hotplug is requested as it may change
  1033  	// between the creation of the target pod and when the evaluation of `MemoryHotplugReadyLabel`
  1034  	// happens.
  1035  	MemoryHotplugOverheadRatioLabel string = "kubevirt.io/memory-hotplug-overhead-ratio"
  1036  
  1037  	// AutoMemoryLimitsRatioLabel allows to use a custom ratio for auto memory limits calculation.
  1038  	// Must be a float >= 1.
  1039  	AutoMemoryLimitsRatioLabel string = "alpha.kubevirt.io/auto-memory-limits-ratio"
  1040  
  1041  	// MigrationInterfaceName is an arbitrary name used in virt-handler to connect it to a dedicated migration network
  1042  	MigrationInterfaceName string = "migration0"
  1043  
  1044  	// EmulatorThreadCompleteToEvenParity alpha annotation will cause Kubevirt to complete the VMI's CPU count to an even parity when IsolateEmulatorThread options are requested
  1045  	EmulatorThreadCompleteToEvenParity string = "alpha.kubevirt.io/EmulatorThreadCompleteToEvenParity"
  1046  )
  1047  
  1048  func NewVMI(name string, uid types.UID) *VirtualMachineInstance {
  1049  	return &VirtualMachineInstance{
  1050  		Spec: VirtualMachineInstanceSpec{},
  1051  		ObjectMeta: metav1.ObjectMeta{
  1052  			Name:      name,
  1053  			UID:       uid,
  1054  			Namespace: k8sv1.NamespaceDefault,
  1055  		},
  1056  		Status: VirtualMachineInstanceStatus{},
  1057  		TypeMeta: metav1.TypeMeta{
  1058  			APIVersion: GroupVersion.String(),
  1059  			Kind:       VirtualMachineInstanceGroupVersionKind.Kind,
  1060  		},
  1061  	}
  1062  }
  1063  
  1064  type SyncEvent string
  1065  
  1066  const (
  1067  	Created                      SyncEvent = "Created"
  1068  	Deleted                      SyncEvent = "Deleted"
  1069  	PresetFailed                 SyncEvent = "PresetFailed"
  1070  	Override                     SyncEvent = "Override"
  1071  	Started                      SyncEvent = "Started"
  1072  	ShuttingDown                 SyncEvent = "ShuttingDown"
  1073  	Stopped                      SyncEvent = "Stopped"
  1074  	PreparingTarget              SyncEvent = "PreparingTarget"
  1075  	Migrating                    SyncEvent = "Migrating"
  1076  	Migrated                     SyncEvent = "Migrated"
  1077  	SyncFailed                   SyncEvent = "SyncFailed"
  1078  	Resumed                      SyncEvent = "Resumed"
  1079  	AccessCredentialsSyncFailed  SyncEvent = "AccessCredentialsSyncFailed"
  1080  	AccessCredentialsSyncSuccess SyncEvent = "AccessCredentialsSyncSuccess"
  1081  )
  1082  
  1083  func (s SyncEvent) String() string {
  1084  	return string(s)
  1085  }
  1086  
  1087  // TODO Namespace could be different, also store it somewhere in the domain, so that we can report deletes on handler startup properly
  1088  func NewVMIReferenceFromName(name string) *VirtualMachineInstance {
  1089  	return NewVMIReferenceFromNameWithNS(k8sv1.NamespaceDefault, name)
  1090  }
  1091  
  1092  func NewVMIReferenceFromNameWithNS(namespace string, name string) *VirtualMachineInstance {
  1093  	vmi := &VirtualMachineInstance{
  1094  		ObjectMeta: metav1.ObjectMeta{
  1095  			Name:      name,
  1096  			Namespace: namespace,
  1097  			SelfLink:  fmt.Sprintf("/apis/%s/namespaces/%s/virtualmachineinstances/%s", GroupVersion.String(), namespace, name),
  1098  		},
  1099  	}
  1100  	vmi.SetGroupVersionKind(schema.GroupVersionKind{Group: GroupVersion.Group, Kind: "VirtualMachineInstance", Version: GroupVersion.Version})
  1101  	return vmi
  1102  }
  1103  
  1104  func NewVMIReferenceWithUUID(namespace string, name string, uuid types.UID) *VirtualMachineInstance {
  1105  	vmi := NewVMIReferenceFromNameWithNS(namespace, name)
  1106  	vmi.UID = uuid
  1107  	return vmi
  1108  }
  1109  
  1110  type VMISelector struct {
  1111  	// Name of the VirtualMachineInstance to migrate
  1112  	Name string `json:"name" valid:"required"`
  1113  }
  1114  
  1115  func NewVMReferenceFromNameWithNS(namespace string, name string) *VirtualMachine {
  1116  	vm := &VirtualMachine{
  1117  		ObjectMeta: metav1.ObjectMeta{
  1118  			Name:      name,
  1119  			Namespace: namespace,
  1120  			SelfLink:  fmt.Sprintf("/apis/%s/namespaces/%s/virtualmachines/%s", GroupVersion.String(), namespace, name),
  1121  		},
  1122  	}
  1123  	vm.SetGroupVersionKind(schema.GroupVersionKind{Group: GroupVersion.Group, Kind: "VirtualMachine", Version: GroupVersion.Version})
  1124  	return vm
  1125  }
  1126  
  1127  // Given a VirtualMachineInstance, update all NodeSelectorTerms with anti-affinity for that VirtualMachineInstance's node.
  1128  // This is useful for the case when a migration away from a node must occur.
  1129  // This method returns the full Affinity structure updated the anti affinity terms
  1130  func UpdateAntiAffinityFromVMINode(pod *k8sv1.Pod, vmi *VirtualMachineInstance) *k8sv1.Affinity {
  1131  	if pod.Spec.Affinity == nil {
  1132  		pod.Spec.Affinity = &k8sv1.Affinity{}
  1133  	}
  1134  
  1135  	if pod.Spec.Affinity.NodeAffinity == nil {
  1136  		pod.Spec.Affinity.NodeAffinity = &k8sv1.NodeAffinity{}
  1137  	}
  1138  
  1139  	if pod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {
  1140  		pod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution = &k8sv1.NodeSelector{}
  1141  	}
  1142  
  1143  	selector := pod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution
  1144  	terms := selector.NodeSelectorTerms
  1145  
  1146  	if len(terms) == 0 {
  1147  		selector.NodeSelectorTerms = append(terms, k8sv1.NodeSelectorTerm{})
  1148  		terms = selector.NodeSelectorTerms
  1149  	}
  1150  
  1151  	for idx, term := range terms {
  1152  		if term.MatchExpressions == nil {
  1153  			term.MatchExpressions = []k8sv1.NodeSelectorRequirement{}
  1154  		}
  1155  
  1156  		term.MatchExpressions = append(term.MatchExpressions, PrepareVMINodeAntiAffinitySelectorRequirement(vmi))
  1157  		selector.NodeSelectorTerms[idx] = term
  1158  	}
  1159  
  1160  	return pod.Spec.Affinity
  1161  }
  1162  
  1163  // Given a VirtualMachineInstance, create a NodeSelectorTerm with anti-affinity for that VirtualMachineInstance's node.
  1164  // This is useful for the case when a migration away from a node must occur.
  1165  func PrepareVMINodeAntiAffinitySelectorRequirement(vmi *VirtualMachineInstance) k8sv1.NodeSelectorRequirement {
  1166  	return k8sv1.NodeSelectorRequirement{
  1167  		Key:      "kubernetes.io/hostname",
  1168  		Operator: k8sv1.NodeSelectorOpNotIn,
  1169  		Values:   []string{vmi.Status.NodeName},
  1170  	}
  1171  }
  1172  
  1173  // VirtualMachineInstance is *the* VirtualMachineInstance Definition. It represents a virtual machine in the runtime environment of kubernetes.
  1174  //
  1175  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1176  // +genclient
  1177  type VirtualMachineInstanceReplicaSet struct {
  1178  	metav1.TypeMeta   `json:",inline"`
  1179  	metav1.ObjectMeta `json:"metadata,omitempty"`
  1180  	// VirtualMachineInstance Spec contains the VirtualMachineInstance specification.
  1181  	Spec VirtualMachineInstanceReplicaSetSpec `json:"spec" valid:"required"`
  1182  	// Status is the high level overview of how the VirtualMachineInstance is doing. It contains information available to controllers and users.
  1183  	// +nullable
  1184  	Status VirtualMachineInstanceReplicaSetStatus `json:"status,omitempty"`
  1185  }
  1186  
  1187  // VMIList is a list of VMIs
  1188  //
  1189  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1190  type VirtualMachineInstanceReplicaSetList struct {
  1191  	metav1.TypeMeta `json:",inline"`
  1192  	metav1.ListMeta `json:"metadata,omitempty"`
  1193  	Items           []VirtualMachineInstanceReplicaSet `json:"items"`
  1194  }
  1195  
  1196  type VirtualMachineInstanceReplicaSetSpec struct {
  1197  	// Number of desired pods. This is a pointer to distinguish between explicit
  1198  	// zero and not specified. Defaults to 1.
  1199  	// +optional
  1200  	Replicas *int32 `json:"replicas,omitempty"`
  1201  
  1202  	// Label selector for pods. Existing ReplicaSets whose pods are
  1203  	// selected by this will be the ones affected by this deployment.
  1204  	Selector *metav1.LabelSelector `json:"selector" valid:"required"`
  1205  
  1206  	// Template describes the pods that will be created.
  1207  	Template *VirtualMachineInstanceTemplateSpec `json:"template" valid:"required"`
  1208  
  1209  	// Indicates that the replica set is paused.
  1210  	// +optional
  1211  	Paused bool `json:"paused,omitempty" protobuf:"varint,7,opt,name=paused"`
  1212  }
  1213  
  1214  type VirtualMachineInstanceReplicaSetStatus struct {
  1215  	// Total number of non-terminated pods targeted by this deployment (their labels match the selector).
  1216  	// +optional
  1217  	Replicas int32 `json:"replicas,omitempty" protobuf:"varint,2,opt,name=replicas"`
  1218  
  1219  	// The number of ready replicas for this replica set.
  1220  	// +optional
  1221  	ReadyReplicas int32 `json:"readyReplicas,omitempty" protobuf:"varint,4,opt,name=readyReplicas"`
  1222  
  1223  	Conditions []VirtualMachineInstanceReplicaSetCondition `json:"conditions,omitempty" optional:"true"`
  1224  
  1225  	// Canonical form of the label selector for HPA which consumes it through the scale subresource.
  1226  	LabelSelector string `json:"labelSelector,omitempty"`
  1227  }
  1228  
  1229  type VirtualMachineInstanceReplicaSetCondition struct {
  1230  	Type   VirtualMachineInstanceReplicaSetConditionType `json:"type"`
  1231  	Status k8sv1.ConditionStatus                         `json:"status"`
  1232  	// +nullable
  1233  	LastProbeTime metav1.Time `json:"lastProbeTime,omitempty"`
  1234  	// +nullable
  1235  	LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"`
  1236  	Reason             string      `json:"reason,omitempty"`
  1237  	Message            string      `json:"message,omitempty"`
  1238  }
  1239  
  1240  type VirtualMachineInstanceReplicaSetConditionType string
  1241  
  1242  const (
  1243  	// VirtualMachineInstanceReplicaSetReplicaFailure is added in a replica set when one of its vmis
  1244  	// fails to be created due to insufficient quota, limit ranges, pod security policy, node selectors,
  1245  	// etc. or deleted due to kubelet being down or finalizers are failing.
  1246  	VirtualMachineInstanceReplicaSetReplicaFailure VirtualMachineInstanceReplicaSetConditionType = "ReplicaFailure"
  1247  
  1248  	// VirtualMachineInstanceReplicaSetReplicaPaused is added in a replica set when the replica set got paused by the controller.
  1249  	// After this condition was added, it is safe to remove or add vmis by hand and adjust the replica count by hand.
  1250  	VirtualMachineInstanceReplicaSetReplicaPaused VirtualMachineInstanceReplicaSetConditionType = "ReplicaPaused"
  1251  )
  1252  
  1253  type DataVolumeTemplateDummyStatus struct{}
  1254  
  1255  type DataVolumeTemplateSpec struct {
  1256  	// TypeMeta only exists on DataVolumeTemplate for API backwards compatibility
  1257  	// this field is not used by our controllers and is a no-op.
  1258  	// +nullable
  1259  	metav1.TypeMeta `json:",inline"`
  1260  	// +kubebuilder:pruning:PreserveUnknownFields
  1261  	// +nullable
  1262  	metav1.ObjectMeta `json:"metadata,omitempty"`
  1263  	// DataVolumeSpec contains the DataVolume specification.
  1264  	Spec cdiv1.DataVolumeSpec `json:"spec"`
  1265  
  1266  	// DataVolumeTemplateDummyStatus is here simply for backwards compatibility with
  1267  	// a previous API.
  1268  	// +nullable
  1269  	// +optional
  1270  	Status *DataVolumeTemplateDummyStatus `json:"status,omitempty"`
  1271  }
  1272  
  1273  type VirtualMachineInstanceTemplateSpec struct {
  1274  	// +kubebuilder:pruning:PreserveUnknownFields
  1275  	// +nullable
  1276  	ObjectMeta metav1.ObjectMeta `json:"metadata,omitempty"`
  1277  	// VirtualMachineInstance Spec contains the VirtualMachineInstance specification.
  1278  	Spec VirtualMachineInstanceSpec `json:"spec,omitempty" valid:"required"`
  1279  }
  1280  
  1281  // VirtualMachineInstanceMigration represents the object tracking a VMI's migration
  1282  // to another host in the cluster
  1283  //
  1284  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1285  // +genclient
  1286  type VirtualMachineInstanceMigration struct {
  1287  	metav1.TypeMeta   `json:",inline"`
  1288  	metav1.ObjectMeta `json:"metadata,omitempty"`
  1289  	Spec              VirtualMachineInstanceMigrationSpec   `json:"spec" valid:"required"`
  1290  	Status            VirtualMachineInstanceMigrationStatus `json:"status,omitempty"`
  1291  }
  1292  
  1293  // VirtualMachineInstanceMigrationList is a list of VirtualMachineMigrations
  1294  //
  1295  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1296  type VirtualMachineInstanceMigrationList struct {
  1297  	metav1.TypeMeta `json:",inline"`
  1298  	metav1.ListMeta `json:"metadata,omitempty"`
  1299  	Items           []VirtualMachineInstanceMigration `json:"items"`
  1300  }
  1301  
  1302  type VirtualMachineInstanceMigrationSpec struct {
  1303  	// The name of the VMI to perform the migration on. VMI must exist in the migration objects namespace
  1304  	VMIName string `json:"vmiName,omitempty" valid:"required"`
  1305  }
  1306  
  1307  // VirtualMachineInstanceMigrationPhaseTransitionTimestamp gives a timestamp in relation to when a phase is set on a vmi
  1308  type VirtualMachineInstanceMigrationPhaseTransitionTimestamp struct {
  1309  	// Phase is the status of the VirtualMachineInstanceMigrationPhase in kubernetes world. It is not the VirtualMachineInstanceMigrationPhase status, but partially correlates to it.
  1310  	Phase VirtualMachineInstanceMigrationPhase `json:"phase,omitempty"`
  1311  	// PhaseTransitionTimestamp is the timestamp of when the phase change occurred
  1312  	PhaseTransitionTimestamp metav1.Time `json:"phaseTransitionTimestamp,omitempty"`
  1313  }
  1314  
  1315  // VirtualMachineInstanceMigration reprents information pertaining to a VMI's migration.
  1316  type VirtualMachineInstanceMigrationStatus struct {
  1317  	Phase      VirtualMachineInstanceMigrationPhase       `json:"phase,omitempty"`
  1318  	Conditions []VirtualMachineInstanceMigrationCondition `json:"conditions,omitempty"`
  1319  	// PhaseTransitionTimestamp is the timestamp of when the last phase change occurred
  1320  	// +listType=atomic
  1321  	// +optional
  1322  	PhaseTransitionTimestamps []VirtualMachineInstanceMigrationPhaseTransitionTimestamp `json:"phaseTransitionTimestamps,omitempty"`
  1323  	// Represents the status of a live migration
  1324  	MigrationState *VirtualMachineInstanceMigrationState `json:"migrationState,omitempty"`
  1325  }
  1326  
  1327  // VirtualMachineInstanceMigrationPhase is a label for the condition of a VirtualMachineInstanceMigration at the current time.
  1328  type VirtualMachineInstanceMigrationPhase string
  1329  
  1330  // These are the valid migration phases
  1331  const (
  1332  	MigrationPhaseUnset VirtualMachineInstanceMigrationPhase = ""
  1333  	// The migration is accepted by the system
  1334  	MigrationPending VirtualMachineInstanceMigrationPhase = "Pending"
  1335  	// The migration's target pod is being scheduled
  1336  	MigrationScheduling VirtualMachineInstanceMigrationPhase = "Scheduling"
  1337  	// The migration's target pod is running
  1338  	MigrationScheduled VirtualMachineInstanceMigrationPhase = "Scheduled"
  1339  	// The migration's target pod is being prepared for migration
  1340  	MigrationPreparingTarget VirtualMachineInstanceMigrationPhase = "PreparingTarget"
  1341  	// The migration's target pod is prepared and ready for migration
  1342  	MigrationTargetReady VirtualMachineInstanceMigrationPhase = "TargetReady"
  1343  	// The migration is in progress
  1344  	MigrationRunning VirtualMachineInstanceMigrationPhase = "Running"
  1345  	// The migration passed
  1346  	MigrationSucceeded VirtualMachineInstanceMigrationPhase = "Succeeded"
  1347  	// The migration failed
  1348  	MigrationFailed VirtualMachineInstanceMigrationPhase = "Failed"
  1349  )
  1350  
  1351  // Deprecated for removal in v2, please use VirtualMachineInstanceType and VirtualMachinePreference instead.
  1352  //
  1353  // VirtualMachineInstancePreset defines a VMI spec.domain to be applied to all VMIs that match the provided label selector
  1354  // More info: https://kubevirt.io/user-guide/virtual_machines/presets/#overrides
  1355  //
  1356  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1357  // +genclient
  1358  type VirtualMachineInstancePreset struct {
  1359  	metav1.TypeMeta   `json:",inline"`
  1360  	metav1.ObjectMeta `json:"metadata,omitempty"`
  1361  	// VirtualMachineInstance Spec contains the VirtualMachineInstance specification.
  1362  	Spec VirtualMachineInstancePresetSpec `json:"spec,omitempty" valid:"required"`
  1363  }
  1364  
  1365  // VirtualMachineInstancePresetList is a list of VirtualMachinePresets
  1366  //
  1367  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1368  type VirtualMachineInstancePresetList struct {
  1369  	metav1.TypeMeta `json:",inline"`
  1370  	metav1.ListMeta `json:"metadata,omitempty"`
  1371  	Items           []VirtualMachineInstancePreset `json:"items"`
  1372  }
  1373  
  1374  type VirtualMachineInstancePresetSpec struct {
  1375  	// Selector is a label query over a set of VMIs.
  1376  	// Required.
  1377  	Selector metav1.LabelSelector `json:"selector"`
  1378  	// Domain is the same object type as contained in VirtualMachineInstanceSpec
  1379  	Domain *DomainSpec `json:"domain,omitempty"`
  1380  }
  1381  
  1382  func NewVirtualMachinePreset(name string, selector metav1.LabelSelector) *VirtualMachineInstancePreset {
  1383  	return &VirtualMachineInstancePreset{
  1384  		Spec: VirtualMachineInstancePresetSpec{
  1385  			Selector: selector,
  1386  			Domain:   &DomainSpec{},
  1387  		},
  1388  		ObjectMeta: metav1.ObjectMeta{
  1389  			Name:      name,
  1390  			Namespace: k8sv1.NamespaceDefault,
  1391  		},
  1392  		TypeMeta: metav1.TypeMeta{
  1393  			APIVersion: GroupVersion.String(),
  1394  			Kind:       VirtualMachineInstancePresetGroupVersionKind.Kind,
  1395  		},
  1396  	}
  1397  }
  1398  
  1399  // VirtualMachine handles the VirtualMachines that are not running
  1400  // or are in a stopped state
  1401  // The VirtualMachine contains the template to create the
  1402  // VirtualMachineInstance. It also mirrors the running state of the created
  1403  // VirtualMachineInstance in its status.
  1404  //
  1405  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1406  // +genclient
  1407  type VirtualMachine struct {
  1408  	metav1.TypeMeta   `json:",inline"`
  1409  	metav1.ObjectMeta `json:"metadata,omitempty"`
  1410  	// Spec contains the specification of VirtualMachineInstance created
  1411  	Spec VirtualMachineSpec `json:"spec" valid:"required"`
  1412  	// Status holds the current state of the controller and brief information
  1413  	// about its associated VirtualMachineInstance
  1414  	Status VirtualMachineStatus `json:"status,omitempty"`
  1415  }
  1416  
  1417  // Return the current runStrategy for the VirtualMachine
  1418  // if vm.spec.running is set, that will be mapped to runStrategy:
  1419  //
  1420  //	false: RunStrategyHalted
  1421  //	true: RunStrategyAlways
  1422  func (vm *VirtualMachine) RunStrategy() (VirtualMachineRunStrategy, error) {
  1423  	if vm.Spec.Running != nil && vm.Spec.RunStrategy != nil {
  1424  		return RunStrategyUnknown, fmt.Errorf("running and runstrategy are mutually exclusive")
  1425  	}
  1426  	RunStrategy := RunStrategyHalted
  1427  	if vm.Spec.Running != nil {
  1428  		if (*vm.Spec.Running) == true {
  1429  			RunStrategy = RunStrategyAlways
  1430  		}
  1431  	} else if vm.Spec.RunStrategy != nil {
  1432  		RunStrategy = *vm.Spec.RunStrategy
  1433  	}
  1434  	return RunStrategy, nil
  1435  }
  1436  
  1437  // VirtualMachineList is a list of virtualmachines
  1438  //
  1439  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1440  type VirtualMachineList struct {
  1441  	metav1.TypeMeta `json:",inline"`
  1442  	metav1.ListMeta `json:"metadata,omitempty"`
  1443  	Items           []VirtualMachine `json:"items"`
  1444  }
  1445  
  1446  // VirtualMachineRunStrategy is a label for the requested VirtualMachineInstance Running State at the current time.
  1447  type VirtualMachineRunStrategy string
  1448  
  1449  // These are the valid VMI run strategies
  1450  const (
  1451  	// Placeholder. Not a valid RunStrategy.
  1452  	RunStrategyUnknown VirtualMachineRunStrategy = ""
  1453  	// VMI should always be running.
  1454  	RunStrategyAlways VirtualMachineRunStrategy = "Always"
  1455  	// VMI should never be running.
  1456  	RunStrategyHalted VirtualMachineRunStrategy = "Halted"
  1457  	// VMI can be started/stopped using API endpoints.
  1458  	RunStrategyManual VirtualMachineRunStrategy = "Manual"
  1459  	// VMI will initially be running--and restarted if a failure occurs.
  1460  	// It will not be restarted upon successful completion.
  1461  	RunStrategyRerunOnFailure VirtualMachineRunStrategy = "RerunOnFailure"
  1462  	// VMI will run once and not be restarted upon completion regardless
  1463  	// if the completion is of phase Failure or Success
  1464  	RunStrategyOnce VirtualMachineRunStrategy = "Once"
  1465  )
  1466  
  1467  // VirtualMachineSpec describes how the proper VirtualMachine
  1468  // should look like
  1469  type VirtualMachineSpec struct {
  1470  	// Running controls whether the associatied VirtualMachineInstance is created or not
  1471  	// Mutually exclusive with RunStrategy
  1472  	Running *bool `json:"running,omitempty" optional:"true"`
  1473  
  1474  	// Running state indicates the requested running state of the VirtualMachineInstance
  1475  	// mutually exclusive with Running
  1476  	RunStrategy *VirtualMachineRunStrategy `json:"runStrategy,omitempty" optional:"true"`
  1477  
  1478  	// InstancetypeMatcher references a instancetype that is used to fill fields in Template
  1479  	Instancetype *InstancetypeMatcher `json:"instancetype,omitempty" optional:"true"`
  1480  
  1481  	// PreferenceMatcher references a set of preference that is used to fill fields in Template
  1482  	Preference *PreferenceMatcher `json:"preference,omitempty" optional:"true"`
  1483  
  1484  	// Template is the direct specification of VirtualMachineInstance
  1485  	Template *VirtualMachineInstanceTemplateSpec `json:"template"`
  1486  
  1487  	// dataVolumeTemplates is a list of dataVolumes that the VirtualMachineInstance template can reference.
  1488  	// DataVolumes in this list are dynamically created for the VirtualMachine and are tied to the VirtualMachine's life-cycle.
  1489  	DataVolumeTemplates []DataVolumeTemplateSpec `json:"dataVolumeTemplates,omitempty"`
  1490  }
  1491  
  1492  // StateChangeRequestType represents the existing state change requests that are possible
  1493  type StateChangeRequestAction string
  1494  
  1495  // These are the currently defined state change requests
  1496  const (
  1497  	StartRequest StateChangeRequestAction = "Start"
  1498  	StopRequest  StateChangeRequestAction = "Stop"
  1499  )
  1500  
  1501  // VirtualMachinePrintableStatus is a human readable, high-level representation of the status of the virtual machine.
  1502  type VirtualMachinePrintableStatus string
  1503  
  1504  // A list of statuses defined for virtual machines
  1505  const (
  1506  	// VirtualMachineStatusStopped indicates that the virtual machine is currently stopped and isn't expected to start.
  1507  	VirtualMachineStatusStopped VirtualMachinePrintableStatus = "Stopped"
  1508  	// VirtualMachineStatusProvisioning indicates that cluster resources associated with the virtual machine
  1509  	// (e.g., DataVolumes) are being provisioned and prepared.
  1510  	VirtualMachineStatusProvisioning VirtualMachinePrintableStatus = "Provisioning"
  1511  	// VirtualMachineStatusStarting indicates that the virtual machine is being prepared for running.
  1512  	VirtualMachineStatusStarting VirtualMachinePrintableStatus = "Starting"
  1513  	// VirtualMachineStatusRunning indicates that the virtual machine is running.
  1514  	VirtualMachineStatusRunning VirtualMachinePrintableStatus = "Running"
  1515  	// VirtualMachineStatusPaused indicates that the virtual machine is paused.
  1516  	VirtualMachineStatusPaused VirtualMachinePrintableStatus = "Paused"
  1517  	// VirtualMachineStatusStopping indicates that the virtual machine is in the process of being stopped.
  1518  	VirtualMachineStatusStopping VirtualMachinePrintableStatus = "Stopping"
  1519  	// VirtualMachineStatusTerminating indicates that the virtual machine is in the process of deletion,
  1520  	// as well as its associated resources (VirtualMachineInstance, DataVolumes, …).
  1521  	VirtualMachineStatusTerminating VirtualMachinePrintableStatus = "Terminating"
  1522  	// VirtualMachineStatusCrashLoopBackOff indicates that the virtual machine is currently in a crash loop waiting to be retried.
  1523  	VirtualMachineStatusCrashLoopBackOff VirtualMachinePrintableStatus = "CrashLoopBackOff"
  1524  	// VirtualMachineStatusMigrating indicates that the virtual machine is in the process of being migrated
  1525  	// to another host.
  1526  	VirtualMachineStatusMigrating VirtualMachinePrintableStatus = "Migrating"
  1527  	// VirtualMachineStatusUnknown indicates that the state of the virtual machine could not be obtained,
  1528  	// typically due to an error in communicating with the host on which it's running.
  1529  	VirtualMachineStatusUnknown VirtualMachinePrintableStatus = "Unknown"
  1530  	// VirtualMachineStatusUnschedulable indicates that an error has occurred while scheduling the virtual machine,
  1531  	// e.g. due to unsatisfiable resource requests or unsatisfiable scheduling constraints.
  1532  	VirtualMachineStatusUnschedulable VirtualMachinePrintableStatus = "ErrorUnschedulable"
  1533  	// VirtualMachineStatusErrImagePull indicates that an error has occured while pulling an image for
  1534  	// a containerDisk VM volume.
  1535  	VirtualMachineStatusErrImagePull VirtualMachinePrintableStatus = "ErrImagePull"
  1536  	// VirtualMachineStatusImagePullBackOff indicates that an error has occured while pulling an image for
  1537  	// a containerDisk VM volume, and that kubelet is backing off before retrying.
  1538  	VirtualMachineStatusImagePullBackOff VirtualMachinePrintableStatus = "ImagePullBackOff"
  1539  	// VirtualMachineStatusPvcNotFound indicates that the virtual machine references a PVC volume which doesn't exist.
  1540  	VirtualMachineStatusPvcNotFound VirtualMachinePrintableStatus = "ErrorPvcNotFound"
  1541  	// VirtualMachineStatusDataVolumeError indicates that an error has been reported by one of the DataVolumes
  1542  	// referenced by the virtual machines.
  1543  	VirtualMachineStatusDataVolumeError VirtualMachinePrintableStatus = "DataVolumeError"
  1544  	// VirtualMachineStatusWaitingForVolumeBinding indicates that some PersistentVolumeClaims backing
  1545  	// the virtual machine volume are still not bound.
  1546  	VirtualMachineStatusWaitingForVolumeBinding VirtualMachinePrintableStatus = "WaitingForVolumeBinding"
  1547  )
  1548  
  1549  // VirtualMachineStartFailure tracks VMIs which failed to transition successfully
  1550  // to running using the VM status
  1551  type VirtualMachineStartFailure struct {
  1552  	ConsecutiveFailCount int          `json:"consecutiveFailCount,omitempty"`
  1553  	LastFailedVMIUID     types.UID    `json:"lastFailedVMIUID,omitempty"`
  1554  	RetryAfterTimestamp  *metav1.Time `json:"retryAfterTimestamp,omitempty"`
  1555  }
  1556  
  1557  // VirtualMachineStatus represents the status returned by the
  1558  // controller to describe how the VirtualMachine is doing
  1559  type VirtualMachineStatus struct {
  1560  	// SnapshotInProgress is the name of the VirtualMachineSnapshot currently executing
  1561  	SnapshotInProgress *string `json:"snapshotInProgress,omitempty"`
  1562  	// RestoreInProgress is the name of the VirtualMachineRestore currently executing
  1563  	RestoreInProgress *string `json:"restoreInProgress,omitempty"`
  1564  	// Created indicates if the virtual machine is created in the cluster
  1565  	Created bool `json:"created,omitempty"`
  1566  	// Ready indicates if the virtual machine is running and ready
  1567  	Ready bool `json:"ready,omitempty"`
  1568  	// PrintableStatus is a human readable, high-level representation of the status of the virtual machine
  1569  	// +kubebuilder:default=Stopped
  1570  	PrintableStatus VirtualMachinePrintableStatus `json:"printableStatus,omitempty"`
  1571  	// Hold the state information of the VirtualMachine and its VirtualMachineInstance
  1572  	Conditions []VirtualMachineCondition `json:"conditions,omitempty" optional:"true"`
  1573  	// StateChangeRequests indicates a list of actions that should be taken on a VMI
  1574  	// e.g. stop a specific VMI then start a new one.
  1575  	StateChangeRequests []VirtualMachineStateChangeRequest `json:"stateChangeRequests,omitempty" optional:"true"`
  1576  	// VolumeRequests indicates a list of volumes add or remove from the VMI template and
  1577  	// hotplug on an active running VMI.
  1578  	// +listType=atomic
  1579  	VolumeRequests []VirtualMachineVolumeRequest `json:"volumeRequests,omitempty" optional:"true"`
  1580  
  1581  	// VolumeSnapshotStatuses indicates a list of statuses whether snapshotting is
  1582  	// supported by each volume.
  1583  	VolumeSnapshotStatuses []VolumeSnapshotStatus `json:"volumeSnapshotStatuses,omitempty" optional:"true"`
  1584  
  1585  	// StartFailure tracks consecutive VMI startup failures for the purposes of
  1586  	// crash loop backoffs
  1587  	// +nullable
  1588  	// +optional
  1589  	StartFailure *VirtualMachineStartFailure `json:"startFailure,omitempty" optional:"true"`
  1590  
  1591  	// MemoryDumpRequest tracks memory dump request phase and info of getting a memory
  1592  	// dump to the given pvc
  1593  	// +nullable
  1594  	// +optional
  1595  	MemoryDumpRequest *VirtualMachineMemoryDumpRequest `json:"memoryDumpRequest,omitempty" optional:"true"`
  1596  
  1597  	// ObservedGeneration is the generation observed by the vmi when started.
  1598  	// +optional
  1599  	ObservedGeneration int64 `json:"observedGeneration,omitempty" optional:"true"`
  1600  
  1601  	// DesiredGeneration is the generation which is desired for the VMI.
  1602  	// This will be used in comparisons with ObservedGeneration to understand when
  1603  	// the VMI is out of sync. This will be changed at the same time as
  1604  	// ObservedGeneration to remove errors which could occur if Generation is
  1605  	// updated through an Update() before ObservedGeneration in Status.
  1606  	// +optional
  1607  	DesiredGeneration int64 `json:"desiredGeneration,omitempty" optional:"true"`
  1608  }
  1609  
  1610  type VolumeSnapshotStatus struct {
  1611  	// Volume name
  1612  	Name string `json:"name"`
  1613  	// True if the volume supports snapshotting
  1614  	Enabled bool `json:"enabled"`
  1615  	// Empty if snapshotting is enabled, contains reason otherwise
  1616  	Reason string `json:"reason,omitempty" optional:"true"`
  1617  }
  1618  
  1619  type VirtualMachineVolumeRequest struct {
  1620  	// AddVolumeOptions when set indicates a volume should be added. The details
  1621  	// within this field specify how to add the volume
  1622  	AddVolumeOptions *AddVolumeOptions `json:"addVolumeOptions,omitempty" optional:"true"`
  1623  	// RemoveVolumeOptions when set indicates a volume should be removed. The details
  1624  	// within this field specify how to add the volume
  1625  	RemoveVolumeOptions *RemoveVolumeOptions `json:"removeVolumeOptions,omitempty" optional:"true"`
  1626  }
  1627  
  1628  type VirtualMachineStateChangeRequest struct {
  1629  	// Indicates the type of action that is requested. e.g. Start or Stop
  1630  	Action StateChangeRequestAction `json:"action"`
  1631  	// Provides additional data in order to perform the Action
  1632  	Data map[string]string `json:"data,omitempty" optional:"true"`
  1633  	// Indicates the UUID of an existing Virtual Machine Instance that this change request applies to -- if applicable
  1634  	UID *types.UID `json:"uid,omitempty" optional:"true" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"`
  1635  }
  1636  
  1637  // VirtualMachineCondition represents the state of VirtualMachine
  1638  type VirtualMachineCondition struct {
  1639  	Type   VirtualMachineConditionType `json:"type"`
  1640  	Status k8sv1.ConditionStatus       `json:"status"`
  1641  	// +nullable
  1642  	LastProbeTime metav1.Time `json:"lastProbeTime,omitempty"`
  1643  	// +nullable
  1644  	LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"`
  1645  	Reason             string      `json:"reason,omitempty"`
  1646  	Message            string      `json:"message,omitempty"`
  1647  }
  1648  
  1649  type VirtualMachineConditionType string
  1650  
  1651  const (
  1652  	// VirtualMachineFailure is added in a virtual machine when its vmi
  1653  	// fails to be created due to insufficient quota, limit ranges, pod security policy, node selectors,
  1654  	// etc. or deleted due to kubelet being down or finalizers are failing.
  1655  	VirtualMachineFailure VirtualMachineConditionType = "Failure"
  1656  
  1657  	// VirtualMachineReady is copied to the virtual machine from its vmi
  1658  	VirtualMachineReady VirtualMachineConditionType = "Ready"
  1659  
  1660  	// VirtualMachinePaused is added in a virtual machine when its vmi
  1661  	// signals with its own condition that it is paused.
  1662  	VirtualMachinePaused VirtualMachineConditionType = "Paused"
  1663  
  1664  	// VirtualMachineInitialized means the virtual machine object has been seen by the VM controller
  1665  	VirtualMachineInitialized VirtualMachineConditionType = "Initialized"
  1666  
  1667  	// VirtualMachineRestartRequired is added when changes made to the VM can't be live-propagated to the VMI
  1668  	VirtualMachineRestartRequired VirtualMachineConditionType = "RestartRequired"
  1669  )
  1670  
  1671  type HostDiskType string
  1672  
  1673  const (
  1674  	// if disk does not exist at the given path,
  1675  	// a disk image will be created there
  1676  	HostDiskExistsOrCreate HostDiskType = "DiskOrCreate"
  1677  	// a disk image must exist at given disk path
  1678  	HostDiskExists HostDiskType = "Disk"
  1679  )
  1680  
  1681  type NetworkInterfaceType string
  1682  
  1683  const (
  1684  	// Virtual machine instance bride interface
  1685  	BridgeInterface NetworkInterfaceType = "bridge"
  1686  	// Virtual machine instance slirp interface
  1687  	SlirpInterface NetworkInterfaceType = "slirp"
  1688  	// Virtual machine instance masquerade interface
  1689  	MasqueradeInterface NetworkInterfaceType = "masquerade"
  1690  	// Virtual machine instance passt interface
  1691  	PasstInterface NetworkInterfaceType = "passt"
  1692  )
  1693  
  1694  type DriverCache string
  1695  
  1696  type DriverIO string
  1697  
  1698  const (
  1699  	// CacheNone - I/O from the guest is not cached on the host, but may be kept in a writeback disk cache.
  1700  	CacheNone DriverCache = "none"
  1701  	// CacheWriteThrough - I/O from the guest is cached on the host but written through to the physical medium.
  1702  	CacheWriteThrough DriverCache = "writethrough"
  1703  	// CacheWriteBack - I/O from the guest is cached on the host.
  1704  	CacheWriteBack DriverCache = "writeback"
  1705  
  1706  	// IOThreads - User mode based threads with a shared lock that perform I/O tasks. Can impact performance but offers
  1707  	// more predictable behaviour. This method is also takes fewer CPU cycles to submit I/O requests.
  1708  	IOThreads DriverIO = "threads"
  1709  	// IONative - Kernel native I/O tasks (AIO) offer a better performance but can block the VM if the file is not fully
  1710  	// allocated so this method recommended only when the backing file/disk/etc is fully preallocated.
  1711  	IONative DriverIO = "native"
  1712  )
  1713  
  1714  // Handler defines a specific action that should be taken
  1715  // TODO: pass structured data to these actions, and document that data here.
  1716  type Handler struct {
  1717  	// One and only one of the following should be specified.
  1718  	// Exec specifies the action to take, it will be executed on the guest through the qemu-guest-agent.
  1719  	// If the guest agent is not available, this probe will fail.
  1720  	// +optional
  1721  	Exec *k8sv1.ExecAction `json:"exec,omitempty" protobuf:"bytes,1,opt,name=exec"`
  1722  	// GuestAgentPing contacts the qemu-guest-agent for availability checks.
  1723  	// +optional
  1724  	GuestAgentPing *GuestAgentPing `json:"guestAgentPing,omitempty"`
  1725  	// HTTPGet specifies the http request to perform.
  1726  	// +optional
  1727  	HTTPGet *k8sv1.HTTPGetAction `json:"httpGet,omitempty"`
  1728  	// TCPSocket specifies an action involving a TCP port.
  1729  	// TCP hooks not yet supported
  1730  	// TODO: implement a realistic TCP lifecycle hook
  1731  	// +optional
  1732  	TCPSocket *k8sv1.TCPSocketAction `json:"tcpSocket,omitempty"`
  1733  }
  1734  
  1735  // Probe describes a health check to be performed against a VirtualMachineInstance to determine whether it is
  1736  // alive or ready to receive traffic.
  1737  type Probe struct {
  1738  	// The action taken to determine the health of a VirtualMachineInstance
  1739  	Handler `json:",inline"`
  1740  	// Number of seconds after the VirtualMachineInstance has started before liveness probes are initiated.
  1741  	// More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
  1742  	// +optional
  1743  	InitialDelaySeconds int32 `json:"initialDelaySeconds,omitempty"`
  1744  	// Number of seconds after which the probe times out.
  1745  	// For exec probes the timeout fails the probe but does not terminate the command running on the guest.
  1746  	// This means a blocking command can result in an increasing load on the guest.
  1747  	// A small buffer will be added to the resulting workload exec probe to compensate for delays
  1748  	// caused by the qemu guest exec mechanism.
  1749  	// Defaults to 1 second. Minimum value is 1.
  1750  	// More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
  1751  	// +optional
  1752  	TimeoutSeconds int32 `json:"timeoutSeconds,omitempty"`
  1753  	// How often (in seconds) to perform the probe.
  1754  	// Default to 10 seconds. Minimum value is 1.
  1755  	// +optional
  1756  	PeriodSeconds int32 `json:"periodSeconds,omitempty"`
  1757  	// Minimum consecutive successes for the probe to be considered successful after having failed.
  1758  	// Defaults to 1. Must be 1 for liveness. Minimum value is 1.
  1759  	// +optional
  1760  	SuccessThreshold int32 `json:"successThreshold,omitempty"`
  1761  	// Minimum consecutive failures for the probe to be considered failed after having succeeded.
  1762  	// Defaults to 3. Minimum value is 1.
  1763  	// +optional
  1764  	FailureThreshold int32 `json:"failureThreshold,omitempty"`
  1765  }
  1766  
  1767  // KubeVirt represents the object deploying all KubeVirt resources
  1768  //
  1769  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1770  // +genclient
  1771  type KubeVirt struct {
  1772  	metav1.TypeMeta   `json:",inline"`
  1773  	metav1.ObjectMeta `json:"metadata,omitempty"`
  1774  	Spec              KubeVirtSpec   `json:"spec" valid:"required"`
  1775  	Status            KubeVirtStatus `json:"status,omitempty"`
  1776  }
  1777  
  1778  // KubeVirtList is a list of KubeVirts
  1779  //
  1780  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  1781  type KubeVirtList struct {
  1782  	metav1.TypeMeta `json:",inline"`
  1783  	metav1.ListMeta `json:"metadata,omitempty"`
  1784  	Items           []KubeVirt `json:"items"`
  1785  }
  1786  
  1787  type KubeVirtSelfSignConfiguration struct {
  1788  	// Deprecated. Use CA.Duration instead
  1789  	CARotateInterval *metav1.Duration `json:"caRotateInterval,omitempty"`
  1790  	// Deprecated. Use Server.Duration instead
  1791  	CertRotateInterval *metav1.Duration `json:"certRotateInterval,omitempty"`
  1792  	// Deprecated. Use CA.Duration and CA.RenewBefore instead
  1793  	CAOverlapInterval *metav1.Duration `json:"caOverlapInterval,omitempty"`
  1794  
  1795  	// CA configuration
  1796  	// CA certs are kept in the CA bundle as long as they are valid
  1797  	CA *CertConfig `json:"ca,omitempty"`
  1798  
  1799  	// Server configuration
  1800  	// Certs are rotated and discarded
  1801  	Server *CertConfig `json:"server,omitempty"`
  1802  }
  1803  
  1804  // CertConfig contains the tunables for TLS certificates
  1805  type CertConfig struct {
  1806  	// The requested 'duration' (i.e. lifetime) of the Certificate.
  1807  	Duration *metav1.Duration `json:"duration,omitempty"`
  1808  
  1809  	// The amount of time before the currently issued certificate's "notAfter"
  1810  	// time that we will begin to attempt to renew the certificate.
  1811  	RenewBefore *metav1.Duration `json:"renewBefore,omitempty"`
  1812  }
  1813  
  1814  type KubeVirtCertificateRotateStrategy struct {
  1815  	SelfSigned *KubeVirtSelfSignConfiguration `json:"selfSigned,omitempty"`
  1816  }
  1817  
  1818  type WorkloadUpdateMethod string
  1819  
  1820  const (
  1821  	// WorkloadUpdateMethodLiveMigrate allows VMIs which are capable of being
  1822  	// migrated to automatically migrate during automated workload updates.
  1823  	WorkloadUpdateMethodLiveMigrate WorkloadUpdateMethod = "LiveMigrate"
  1824  	// WorkloadUpdateMethodEvict results in a VMI's pod being evicted. Unless the
  1825  	// pod has a pod disruption budget allocated, the eviction will usually result in
  1826  	// the VMI being shutdown.
  1827  	// Depending on whether a VMI is backed by a VM or not, this will either result
  1828  	// in a restart of the VM by rescheduling a new VMI, or the shutdown via eviction
  1829  	// of a standalone VMI object.
  1830  	WorkloadUpdateMethodEvict WorkloadUpdateMethod = "Evict"
  1831  )
  1832  
  1833  // KubeVirtWorkloadUpdateStrategy defines options related to updating a KubeVirt install
  1834  type KubeVirtWorkloadUpdateStrategy struct {
  1835  	// WorkloadUpdateMethods defines the methods that can be used to disrupt workloads
  1836  	// during automated workload updates.
  1837  	// When multiple methods are present, the least disruptive method takes
  1838  	// precedence over more disruptive methods. For example if both LiveMigrate and Shutdown
  1839  	// methods are listed, only VMs which are not live migratable will be restarted/shutdown
  1840  	//
  1841  	// An empty list defaults to no automated workload updating
  1842  	//
  1843  	// +listType=atomic
  1844  	// +optional
  1845  	WorkloadUpdateMethods []WorkloadUpdateMethod `json:"workloadUpdateMethods,omitempty"`
  1846  
  1847  	// BatchEvictionSize Represents the number of VMIs that can be forced updated per
  1848  	// the BatchShutdownInteral interval
  1849  	//
  1850  	// Defaults to 10
  1851  	//
  1852  	// +optional
  1853  	BatchEvictionSize *int `json:"batchEvictionSize,omitempty"`
  1854  
  1855  	// BatchEvictionInterval Represents the interval to wait before issuing the next
  1856  	// batch of shutdowns
  1857  	//
  1858  	// Defaults to 1 minute
  1859  	//
  1860  	// +optional
  1861  	BatchEvictionInterval *metav1.Duration `json:"batchEvictionInterval,omitempty"`
  1862  }
  1863  
  1864  type KubeVirtSpec struct {
  1865  	// The image tag to use for the continer images installed.
  1866  	// Defaults to the same tag as the operator's container image.
  1867  	ImageTag string `json:"imageTag,omitempty"`
  1868  	// The image registry to pull the container images from
  1869  	// Defaults to the same registry the operator's container image is pulled from.
  1870  	ImageRegistry string `json:"imageRegistry,omitempty"`
  1871  
  1872  	// The ImagePullPolicy to use.
  1873  	ImagePullPolicy k8sv1.PullPolicy `json:"imagePullPolicy,omitempty" valid:"required"`
  1874  
  1875  	// The imagePullSecrets to pull the container images from
  1876  	// Defaults to none
  1877  	// +listType=atomic
  1878  	ImagePullSecrets []k8sv1.LocalObjectReference `json:"imagePullSecrets,omitempty"`
  1879  
  1880  	// The namespace Prometheus is deployed in
  1881  	// Defaults to openshift-monitor
  1882  	MonitorNamespace string `json:"monitorNamespace,omitempty"`
  1883  
  1884  	// The namespace the service monitor will be deployed
  1885  	//  When ServiceMonitorNamespace is set, then we'll install the service monitor object in that namespace
  1886  	// otherwise we will use the monitoring namespace.
  1887  	ServiceMonitorNamespace string `json:"serviceMonitorNamespace,omitempty"`
  1888  
  1889  	// The name of the Prometheus service account that needs read-access to KubeVirt endpoints
  1890  	// Defaults to prometheus-k8s
  1891  	MonitorAccount string `json:"monitorAccount,omitempty"`
  1892  
  1893  	// WorkloadUpdateStrategy defines at the cluster level how to handle
  1894  	// automated workload updates
  1895  	WorkloadUpdateStrategy KubeVirtWorkloadUpdateStrategy `json:"workloadUpdateStrategy,omitempty"`
  1896  
  1897  	// Specifies if kubevirt can be deleted if workloads are still present.
  1898  	// This is mainly a precaution to avoid accidental data loss
  1899  	UninstallStrategy KubeVirtUninstallStrategy `json:"uninstallStrategy,omitempty"`
  1900  
  1901  	CertificateRotationStrategy KubeVirtCertificateRotateStrategy `json:"certificateRotateStrategy,omitempty"`
  1902  
  1903  	// Designate the apps.kubevirt.io/version label for KubeVirt components.
  1904  	// Useful if KubeVirt is included as part of a product.
  1905  	// If ProductVersion is not specified, KubeVirt's version will be used.
  1906  	ProductVersion string `json:"productVersion,omitempty"`
  1907  
  1908  	// Designate the apps.kubevirt.io/part-of label for KubeVirt components.
  1909  	// Useful if KubeVirt is included as part of a product.
  1910  	// If ProductName is not specified, the part-of label will be omitted.
  1911  	ProductName string `json:"productName,omitempty"`
  1912  
  1913  	// Designate the apps.kubevirt.io/component label for KubeVirt components.
  1914  	// Useful if KubeVirt is included as part of a product.
  1915  	// If ProductComponent is not specified, the component label default value is kubevirt.
  1916  	ProductComponent string `json:"productComponent,omitempty"`
  1917  
  1918  	// holds kubevirt configurations.
  1919  	// same as the virt-configMap
  1920  	Configuration KubeVirtConfiguration `json:"configuration,omitempty"`
  1921  
  1922  	// selectors and tolerations that should apply to KubeVirt infrastructure components
  1923  	// +optional
  1924  	Infra *ComponentConfig `json:"infra,omitempty"`
  1925  
  1926  	// selectors and tolerations that should apply to KubeVirt workloads
  1927  	// +optional
  1928  	Workloads *ComponentConfig `json:"workloads,omitempty"`
  1929  
  1930  	CustomizeComponents CustomizeComponents `json:"customizeComponents,omitempty"`
  1931  }
  1932  
  1933  type CustomizeComponents struct {
  1934  	// +listType=atomic
  1935  	Patches []CustomizeComponentsPatch `json:"patches,omitempty"`
  1936  
  1937  	// Configure the value used for deployment and daemonset resources
  1938  	Flags *Flags `json:"flags,omitempty"`
  1939  }
  1940  
  1941  // Flags will create a patch that will replace all flags for the container's
  1942  // command field. The only flags that will be used are those define. There are no
  1943  // guarantees around forward/backward compatibility.  If set incorrectly this will
  1944  // cause the resource when rolled out to error until flags are updated.
  1945  type Flags struct {
  1946  	API        map[string]string `json:"api,omitempty"`
  1947  	Controller map[string]string `json:"controller,omitempty"`
  1948  	Handler    map[string]string `json:"handler,omitempty"`
  1949  }
  1950  
  1951  type CustomizeComponentsPatch struct {
  1952  	// +kubebuilder:validation:MinLength=1
  1953  	ResourceName string `json:"resourceName"`
  1954  	// +kubebuilder:validation:MinLength=1
  1955  	ResourceType string    `json:"resourceType"`
  1956  	Patch        string    `json:"patch"`
  1957  	Type         PatchType `json:"type"`
  1958  }
  1959  
  1960  type PatchType string
  1961  
  1962  const (
  1963  	JSONPatchType           PatchType = "json"
  1964  	MergePatchType          PatchType = "merge"
  1965  	StrategicMergePatchType PatchType = "strategic"
  1966  )
  1967  
  1968  type KubeVirtUninstallStrategy string
  1969  
  1970  const (
  1971  	KubeVirtUninstallStrategyRemoveWorkloads                KubeVirtUninstallStrategy = "RemoveWorkloads"
  1972  	KubeVirtUninstallStrategyBlockUninstallIfWorkloadsExist KubeVirtUninstallStrategy = "BlockUninstallIfWorkloadsExist"
  1973  )
  1974  
  1975  // GenerationStatus keeps track of the generation for a given resource so that decisions about forced updates can be made.
  1976  type GenerationStatus struct {
  1977  	// group is the group of the thing you're tracking
  1978  	Group string `json:"group"`
  1979  	// resource is the resource type of the thing you're tracking
  1980  	Resource string `json:"resource"`
  1981  	// namespace is where the thing you're tracking is
  1982  	// +optional
  1983  	Namespace string `json:"namespace,omitempty" optional:"true"`
  1984  	// name is the name of the thing you're tracking
  1985  	Name string `json:"name"`
  1986  	// lastGeneration is the last generation of the workload controller involved
  1987  	LastGeneration int64 `json:"lastGeneration"`
  1988  	// hash is an optional field set for resources without generation that are content sensitive like secrets and configmaps
  1989  	// +optional
  1990  	Hash string `json:"hash,omitempty" optional:"true"`
  1991  }
  1992  
  1993  // KubeVirtStatus represents information pertaining to a KubeVirt deployment.
  1994  type KubeVirtStatus struct {
  1995  	Phase                                   KubeVirtPhase       `json:"phase,omitempty"`
  1996  	Conditions                              []KubeVirtCondition `json:"conditions,omitempty" optional:"true"`
  1997  	OperatorVersion                         string              `json:"operatorVersion,omitempty" optional:"true"`
  1998  	TargetKubeVirtRegistry                  string              `json:"targetKubeVirtRegistry,omitempty" optional:"true"`
  1999  	TargetKubeVirtVersion                   string              `json:"targetKubeVirtVersion,omitempty" optional:"true"`
  2000  	TargetDeploymentConfig                  string              `json:"targetDeploymentConfig,omitempty" optional:"true"`
  2001  	TargetDeploymentID                      string              `json:"targetDeploymentID,omitempty" optional:"true"`
  2002  	ObservedKubeVirtRegistry                string              `json:"observedKubeVirtRegistry,omitempty" optional:"true"`
  2003  	ObservedKubeVirtVersion                 string              `json:"observedKubeVirtVersion,omitempty" optional:"true"`
  2004  	ObservedDeploymentConfig                string              `json:"observedDeploymentConfig,omitempty" optional:"true"`
  2005  	ObservedDeploymentID                    string              `json:"observedDeploymentID,omitempty" optional:"true"`
  2006  	OutdatedVirtualMachineInstanceWorkloads *int                `json:"outdatedVirtualMachineInstanceWorkloads,omitempty" optional:"true"`
  2007  	ObservedGeneration                      *int64              `json:"observedGeneration,omitempty"`
  2008  	DefaultArchitecture                     string              `json:"defaultArchitecture,omitempty"`
  2009  	// +listType=atomic
  2010  	Generations []GenerationStatus `json:"generations,omitempty" optional:"true"`
  2011  }
  2012  
  2013  // KubeVirtPhase is a label for the phase of a KubeVirt deployment at the current time.
  2014  type KubeVirtPhase string
  2015  
  2016  // These are the valid KubeVirt deployment phases
  2017  const (
  2018  	// The deployment is processing
  2019  	KubeVirtPhaseDeploying KubeVirtPhase = "Deploying"
  2020  	// The deployment succeeded
  2021  	KubeVirtPhaseDeployed KubeVirtPhase = "Deployed"
  2022  	// The deletion is processing
  2023  	KubeVirtPhaseDeleting KubeVirtPhase = "Deleting"
  2024  	// The deletion succeeeded
  2025  	KubeVirtPhaseDeleted KubeVirtPhase = "Deleted"
  2026  )
  2027  
  2028  // KubeVirtCondition represents a condition of a KubeVirt deployment
  2029  type KubeVirtCondition struct {
  2030  	Type   KubeVirtConditionType `json:"type"`
  2031  	Status k8sv1.ConditionStatus `json:"status"`
  2032  	// +optional
  2033  	// +nullable
  2034  	LastProbeTime metav1.Time `json:"lastProbeTime,omitempty"`
  2035  	// +optional
  2036  	// +nullable
  2037  	LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"`
  2038  	Reason             string      `json:"reason,omitempty"`
  2039  	Message            string      `json:"message,omitempty"`
  2040  }
  2041  
  2042  type KubeVirtConditionType string
  2043  
  2044  // These are the valid KubeVirt condition types
  2045  const (
  2046  	// Whether the deployment or deletion was successful (only used if false)
  2047  	KubeVirtConditionSynchronized KubeVirtConditionType = "Synchronized"
  2048  	// Whether all resources were created and up-to-date
  2049  	KubeVirtConditionCreated KubeVirtConditionType = "Created"
  2050  
  2051  	// Conditions for HCO, see https://github.com/kubevirt/hyperconverged-cluster-operator/blob/master/docs/conditions.md
  2052  	// Whether KubeVirt is functional and available in the cluster.
  2053  	KubeVirtConditionAvailable KubeVirtConditionType = "Available"
  2054  	// Whether the operator is actively making changes to KubeVirt
  2055  	KubeVirtConditionProgressing KubeVirtConditionType = "Progressing"
  2056  	// Whether KubeVirt is not functioning completely
  2057  	KubeVirtConditionDegraded KubeVirtConditionType = "Degraded"
  2058  )
  2059  
  2060  const (
  2061  	EvictionStrategyNone                  EvictionStrategy = "None"
  2062  	EvictionStrategyLiveMigrate           EvictionStrategy = "LiveMigrate"
  2063  	EvictionStrategyLiveMigrateIfPossible EvictionStrategy = "LiveMigrateIfPossible"
  2064  	EvictionStrategyExternal              EvictionStrategy = "External"
  2065  )
  2066  
  2067  // RestartOptions may be provided when deleting an API object.
  2068  type RestartOptions struct {
  2069  	metav1.TypeMeta `json:",inline"`
  2070  
  2071  	// The duration in seconds before the object should be force-restarted. Value must be non-negative integer.
  2072  	// The value zero indicates, restart immediately. If this value is nil, the default grace period for deletion of the corresponding VMI for the
  2073  	// specified type will be used to determine on how much time to give the VMI to restart.
  2074  	// Defaults to a per object value if not specified. zero means restart immediately.
  2075  	// Allowed Values: nil and 0
  2076  	// +optional
  2077  	GracePeriodSeconds *int64 `json:"gracePeriodSeconds,omitempty" protobuf:"varint,1,opt,name=gracePeriodSeconds"`
  2078  
  2079  	// When present, indicates that modifications should not be
  2080  	// persisted. An invalid or unrecognized dryRun directive will
  2081  	// result in an error response and no further processing of the
  2082  	// request. Valid values are:
  2083  	// - All: all dry run stages will be processed
  2084  	// +optional
  2085  	// +listType=atomic
  2086  	DryRun []string `json:"dryRun,omitempty" protobuf:"bytes,2,rep,name=dryRun"`
  2087  }
  2088  
  2089  // StartOptions may be provided on start request.
  2090  type StartOptions struct {
  2091  	metav1.TypeMeta `json:",inline"`
  2092  
  2093  	// Indicates that VM will be started in paused state.
  2094  	// +optional
  2095  	Paused bool `json:"paused,omitempty" protobuf:"varint,7,opt,name=paused"`
  2096  	// When present, indicates that modifications should not be
  2097  	// persisted. An invalid or unrecognized dryRun directive will
  2098  	// result in an error response and no further processing of the
  2099  	// request. Valid values are:
  2100  	// - All: all dry run stages will be processed
  2101  	// +optional
  2102  	// +listType=atomic
  2103  	DryRun []string `json:"dryRun,omitempty" protobuf:"bytes,5,rep,name=dryRun"`
  2104  }
  2105  
  2106  // PauseOptions may be provided on pause request.
  2107  type PauseOptions struct {
  2108  	metav1.TypeMeta `json:",inline"`
  2109  
  2110  	// When present, indicates that modifications should not be
  2111  	// persisted. An invalid or unrecognized dryRun directive will
  2112  	// result in an error response and no further processing of the
  2113  	// request. Valid values are:
  2114  	// - All: all dry run stages will be processed
  2115  	// +optional
  2116  	// +listType=atomic
  2117  	DryRun []string `json:"dryRun,omitempty" protobuf:"bytes,1,rep,name=dryRun"`
  2118  }
  2119  
  2120  // UnpauseOptions may be provided on unpause request.
  2121  type UnpauseOptions struct {
  2122  	metav1.TypeMeta `json:",inline"`
  2123  
  2124  	// When present, indicates that modifications should not be
  2125  	// persisted. An invalid or unrecognized dryRun directive will
  2126  	// result in an error response and no further processing of the
  2127  	// request. Valid values are:
  2128  	// - All: all dry run stages will be processed
  2129  	// +optional
  2130  	// +listType=atomic
  2131  	DryRun []string `json:"dryRun,omitempty" protobuf:"bytes,1,rep,name=dryRun"`
  2132  }
  2133  
  2134  const (
  2135  	StartRequestDataPausedKey  string = "paused"
  2136  	StartRequestDataPausedTrue string = "true"
  2137  )
  2138  
  2139  // StopOptions may be provided when deleting an API object.
  2140  type StopOptions struct {
  2141  	metav1.TypeMeta `json:",inline"`
  2142  
  2143  	// this updates the VMIs terminationGracePeriodSeconds during shutdown
  2144  	// +optional
  2145  	GracePeriod *int64 `json:"gracePeriod,omitempty" protobuf:"varint,1,opt,name=gracePeriod"`
  2146  	// When present, indicates that modifications should not be
  2147  	// persisted. An invalid or unrecognized dryRun directive will
  2148  	// result in an error response and no further processing of the
  2149  	// request. Valid values are:
  2150  	// - All: all dry run stages will be processed
  2151  	// +optional
  2152  	// +listType=atomic
  2153  	DryRun []string `json:"dryRun,omitempty" protobuf:"bytes,2,rep,name=dryRun"`
  2154  }
  2155  
  2156  // MigrateOptions may be provided on migrate request.
  2157  type MigrateOptions struct {
  2158  	metav1.TypeMeta `json:",inline"`
  2159  	// When present, indicates that modifications should not be
  2160  	// persisted. An invalid or unrecognized dryRun directive will
  2161  	// result in an error response and no further processing of the
  2162  	// request. Valid values are:
  2163  	// - All: all dry run stages will be processed
  2164  	// +optional
  2165  	// +listType=atomic
  2166  	DryRun []string `json:"dryRun,omitempty" protobuf:"bytes,1,rep,name=dryRun"`
  2167  }
  2168  
  2169  // VirtualMachineInstanceGuestAgentInfo represents information from the installed guest agent
  2170  //
  2171  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  2172  type VirtualMachineInstanceGuestAgentInfo struct {
  2173  	metav1.TypeMeta `json:",inline"`
  2174  	// GAVersion is a version of currently installed guest agent
  2175  	GAVersion string `json:"guestAgentVersion,omitempty"`
  2176  	// Return command list the guest agent supports
  2177  	// +listType=atomic
  2178  	SupportedCommands []GuestAgentCommandInfo `json:"supportedCommands,omitempty"`
  2179  	// Hostname represents FQDN of a guest
  2180  	Hostname string `json:"hostname,omitempty"`
  2181  	// OS contains the guest operating system information
  2182  	OS VirtualMachineInstanceGuestOSInfo `json:"os,omitempty"`
  2183  	// Timezone is guest os current timezone
  2184  	Timezone string `json:"timezone,omitempty"`
  2185  	// UserList is a list of active guest OS users
  2186  	UserList []VirtualMachineInstanceGuestOSUser `json:"userList,omitempty"`
  2187  	// FSInfo is a guest os filesystem information containing the disk mapping and disk mounts with usage
  2188  	FSInfo VirtualMachineInstanceFileSystemInfo `json:"fsInfo,omitempty"`
  2189  	// FSFreezeStatus is the state of the fs of the guest
  2190  	// it can be either frozen or thawed
  2191  	FSFreezeStatus string `json:"fsFreezeStatus,omitempty"`
  2192  }
  2193  
  2194  // List of commands that QEMU guest agent supports
  2195  type GuestAgentCommandInfo struct {
  2196  	Name    string `json:"name"`
  2197  	Enabled bool   `json:"enabled,omitempty"`
  2198  }
  2199  
  2200  // VirtualMachineInstanceGuestOSUserList comprises the list of all active users on guest machine
  2201  //
  2202  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  2203  type VirtualMachineInstanceGuestOSUserList struct {
  2204  	metav1.TypeMeta `json:",inline"`
  2205  	metav1.ListMeta `json:"metadata,omitempty"`
  2206  	Items           []VirtualMachineInstanceGuestOSUser `json:"items"`
  2207  }
  2208  
  2209  // VirtualMachineGuestOSUser is the single user of the guest os
  2210  type VirtualMachineInstanceGuestOSUser struct {
  2211  	UserName  string  `json:"userName"`
  2212  	Domain    string  `json:"domain,omitempty"`
  2213  	LoginTime float64 `json:"loginTime,omitempty"`
  2214  }
  2215  
  2216  // VirtualMachineInstanceFileSystemInfo represents information regarding single guest os filesystem
  2217  type VirtualMachineInstanceFileSystemInfo struct {
  2218  	Filesystems []VirtualMachineInstanceFileSystem `json:"disks"`
  2219  }
  2220  
  2221  // VirtualMachineInstanceFileSystemList comprises the list of all filesystems on guest machine
  2222  //
  2223  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  2224  type VirtualMachineInstanceFileSystemList struct {
  2225  	metav1.TypeMeta `json:",inline"`
  2226  	metav1.ListMeta `json:"metadata,omitempty"`
  2227  	Items           []VirtualMachineInstanceFileSystem `json:"items"`
  2228  }
  2229  
  2230  // VirtualMachineInstanceFileSystemDisk represents the guest os FS disks
  2231  type VirtualMachineInstanceFileSystemDisk struct {
  2232  	Serial  string `json:"serial,omitempty"`
  2233  	BusType string `json:"busType"`
  2234  }
  2235  
  2236  // VirtualMachineInstanceFileSystem represents guest os disk
  2237  type VirtualMachineInstanceFileSystem struct {
  2238  	DiskName       string                                 `json:"diskName"`
  2239  	MountPoint     string                                 `json:"mountPoint"`
  2240  	FileSystemType string                                 `json:"fileSystemType"`
  2241  	UsedBytes      int                                    `json:"usedBytes"`
  2242  	TotalBytes     int                                    `json:"totalBytes"`
  2243  	Disk           []VirtualMachineInstanceFileSystemDisk `json:"disk,omitempty"`
  2244  }
  2245  
  2246  // FreezeUnfreezeTimeout represent the time unfreeze will be triggered if guest was not unfrozen by unfreeze command
  2247  type FreezeUnfreezeTimeout struct {
  2248  	UnfreezeTimeout *metav1.Duration `json:"unfreezeTimeout"`
  2249  }
  2250  
  2251  // VirtualMachineMemoryDumpRequest represent the memory dump request phase and info
  2252  type VirtualMachineMemoryDumpRequest struct {
  2253  	// ClaimName is the name of the pvc that will contain the memory dump
  2254  	ClaimName string `json:"claimName"`
  2255  	// Phase represents the memory dump phase
  2256  	Phase MemoryDumpPhase `json:"phase"`
  2257  	// Remove represents request of dissociating the memory dump pvc
  2258  	// +optional
  2259  	Remove bool `json:"remove,omitempty"`
  2260  	// StartTimestamp represents the time the memory dump started
  2261  	// +optional
  2262  	StartTimestamp *metav1.Time `json:"startTimestamp,omitempty"`
  2263  	// EndTimestamp represents the time the memory dump was completed
  2264  	// +optional
  2265  	EndTimestamp *metav1.Time `json:"endTimestamp,omitempty"`
  2266  	// FileName represents the name of the output file
  2267  	// +optional
  2268  	FileName *string `json:"fileName,omitempty"`
  2269  	// Message is a detailed message about failure of the memory dump
  2270  	// +optional
  2271  	Message string `json:"message,omitempty"`
  2272  }
  2273  
  2274  type MemoryDumpPhase string
  2275  
  2276  const (
  2277  	// The memorydump is during pvc Associating
  2278  	MemoryDumpAssociating MemoryDumpPhase = "Associating"
  2279  	// The memorydump is in progress
  2280  	MemoryDumpInProgress MemoryDumpPhase = "InProgress"
  2281  	// The memorydump is being unmounted
  2282  	MemoryDumpUnmounting MemoryDumpPhase = "Unmounting"
  2283  	// The memorydump is completed
  2284  	MemoryDumpCompleted MemoryDumpPhase = "Completed"
  2285  	// The memorydump is being unbound
  2286  	MemoryDumpDissociating MemoryDumpPhase = "Dissociating"
  2287  	// The memorydump failed
  2288  	MemoryDumpFailed MemoryDumpPhase = "Failed"
  2289  )
  2290  
  2291  // AddVolumeOptions is provided when dynamically hot plugging a volume and disk
  2292  type AddVolumeOptions struct {
  2293  	// Name represents the name that will be used to map the
  2294  	// disk to the corresponding volume. This overrides any name
  2295  	// set inside the Disk struct itself.
  2296  	Name string `json:"name"`
  2297  	// Disk represents the hotplug disk that will be plugged into the running VMI
  2298  	Disk *Disk `json:"disk"`
  2299  	// VolumeSource represents the source of the volume to map to the disk.
  2300  	VolumeSource *HotplugVolumeSource `json:"volumeSource"`
  2301  	// When present, indicates that modifications should not be
  2302  	// persisted. An invalid or unrecognized dryRun directive will
  2303  	// result in an error response and no further processing of the
  2304  	// request. Valid values are:
  2305  	// - All: all dry run stages will be processed
  2306  	// +optional
  2307  	// +listType=atomic
  2308  	DryRun []string `json:"dryRun,omitempty"`
  2309  }
  2310  
  2311  type ScreenshotOptions struct {
  2312  	MoveCursor bool `json:"moveCursor"`
  2313  }
  2314  
  2315  type VSOCKOptions struct {
  2316  	TargetPort uint32 `json:"targetPort"`
  2317  	UseTLS     *bool  `json:"useTLS,omitempty"`
  2318  }
  2319  
  2320  // RemoveVolumeOptions is provided when dynamically hot unplugging volume and disk
  2321  type RemoveVolumeOptions struct {
  2322  	// Name represents the name that maps to both the disk and volume that
  2323  	// should be removed
  2324  	Name string `json:"name"`
  2325  	// When present, indicates that modifications should not be
  2326  	// persisted. An invalid or unrecognized dryRun directive will
  2327  	// result in an error response and no further processing of the
  2328  	// request. Valid values are:
  2329  	// - All: all dry run stages will be processed
  2330  	// +optional
  2331  	// +listType=atomic
  2332  	DryRun []string `json:"dryRun,omitempty"`
  2333  }
  2334  
  2335  type TokenBucketRateLimiter struct {
  2336  	// QPS indicates the maximum QPS to the apiserver from this client.
  2337  	// If it's zero, the component default will be used
  2338  	QPS float32 `json:"qps"`
  2339  
  2340  	// Maximum burst for throttle.
  2341  	// If it's zero, the component default will be used
  2342  	Burst int `json:"burst"`
  2343  }
  2344  
  2345  type RateLimiter struct {
  2346  	TokenBucketRateLimiter *TokenBucketRateLimiter `json:"tokenBucketRateLimiter,omitempty"`
  2347  }
  2348  
  2349  // RESTClientConfiguration allows configuring certain aspects of the k8s rest client.
  2350  type RESTClientConfiguration struct {
  2351  	//RateLimiter allows selecting and configuring different rate limiters for the k8s client.
  2352  	RateLimiter *RateLimiter `json:"rateLimiter,omitempty"`
  2353  }
  2354  
  2355  // ReloadableComponentConfiguration holds all generic k8s configuration options which can
  2356  // be reloaded by components without requiring a restart.
  2357  type ReloadableComponentConfiguration struct {
  2358  	//RestClient can be used to tune certain aspects of the k8s client in use.
  2359  	RestClient *RESTClientConfiguration `json:"restClient,omitempty"`
  2360  }
  2361  
  2362  // KubeVirtConfiguration holds all kubevirt configurations
  2363  type KubeVirtConfiguration struct {
  2364  	CPUModel               string                  `json:"cpuModel,omitempty"`
  2365  	CPURequest             *resource.Quantity      `json:"cpuRequest,omitempty"`
  2366  	DeveloperConfiguration *DeveloperConfiguration `json:"developerConfiguration,omitempty"`
  2367  	EmulatedMachines       []string                `json:"emulatedMachines,omitempty"`
  2368  	ImagePullPolicy        k8sv1.PullPolicy        `json:"imagePullPolicy,omitempty"`
  2369  	MigrationConfiguration *MigrationConfiguration `json:"migrations,omitempty"`
  2370  	// Deprecated. Use architectureConfiguration instead.
  2371  	MachineType               string                `json:"machineType,omitempty"`
  2372  	NetworkConfiguration      *NetworkConfiguration `json:"network,omitempty"`
  2373  	OVMFPath                  string                `json:"ovmfPath,omitempty"`
  2374  	SELinuxLauncherType       string                `json:"selinuxLauncherType,omitempty"`
  2375  	DefaultRuntimeClass       string                `json:"defaultRuntimeClass,omitempty"`
  2376  	SMBIOSConfig              *SMBiosConfiguration  `json:"smbios,omitempty"`
  2377  	ArchitectureConfiguration *ArchConfiguration    `json:"architectureConfiguration,omitempty"`
  2378  	// EvictionStrategy defines at the cluster level if the VirtualMachineInstance should be
  2379  	// migrated instead of shut-off in case of a node drain. If the VirtualMachineInstance specific
  2380  	// field is set it overrides the cluster level one.
  2381  	EvictionStrategy *EvictionStrategy `json:"evictionStrategy,omitempty"`
  2382  
  2383  	// AdditionalGuestMemoryOverheadRatio can be used to increase the virtualization infrastructure
  2384  	// overhead. This is useful, since the calculation of this overhead is not accurate and cannot
  2385  	// be entirely known in advance. The ratio that is being set determines by which factor to increase
  2386  	// the overhead calculated by Kubevirt. A higher ratio means that the VMs would be less compromised
  2387  	// by node pressures, but would mean that fewer VMs could be scheduled to a node.
  2388  	// If not set, the default is 1.
  2389  	AdditionalGuestMemoryOverheadRatio *string `json:"additionalGuestMemoryOverheadRatio,omitempty"`
  2390  
  2391  	// +listType=map
  2392  	// +listMapKey=type
  2393  	// SupportContainerResources specifies the resource requirements for various types of supporting containers such as container disks/virtiofs/sidecars and hotplug attachment pods. If omitted a sensible default will be supplied.
  2394  	SupportContainerResources []SupportContainerResources `json:"supportContainerResources,omitempty"`
  2395  
  2396  	// deprecated
  2397  	SupportedGuestAgentVersions    []string                          `json:"supportedGuestAgentVersions,omitempty"`
  2398  	MemBalloonStatsPeriod          *uint32                           `json:"memBalloonStatsPeriod,omitempty"`
  2399  	PermittedHostDevices           *PermittedHostDevices             `json:"permittedHostDevices,omitempty"`
  2400  	MediatedDevicesConfiguration   *MediatedDevicesConfiguration     `json:"mediatedDevicesConfiguration,omitempty"`
  2401  	MinCPUModel                    string                            `json:"minCPUModel,omitempty"`
  2402  	ObsoleteCPUModels              map[string]bool                   `json:"obsoleteCPUModels,omitempty"`
  2403  	VirtualMachineInstancesPerNode *int                              `json:"virtualMachineInstancesPerNode,omitempty"`
  2404  	APIConfiguration               *ReloadableComponentConfiguration `json:"apiConfiguration,omitempty"`
  2405  	WebhookConfiguration           *ReloadableComponentConfiguration `json:"webhookConfiguration,omitempty"`
  2406  	ControllerConfiguration        *ReloadableComponentConfiguration `json:"controllerConfiguration,omitempty"`
  2407  	HandlerConfiguration           *ReloadableComponentConfiguration `json:"handlerConfiguration,omitempty"`
  2408  	TLSConfiguration               *TLSConfiguration                 `json:"tlsConfiguration,omitempty"`
  2409  	SeccompConfiguration           *SeccompConfiguration             `json:"seccompConfiguration,omitempty"`
  2410  
  2411  	// VMStateStorageClass is the name of the storage class to use for the PVCs created to preserve VM state, like TPM.
  2412  	// The storage class must support RWX in filesystem mode.
  2413  	VMStateStorageClass   string                 `json:"vmStateStorageClass,omitempty"`
  2414  	VirtualMachineOptions *VirtualMachineOptions `json:"virtualMachineOptions,omitempty"`
  2415  
  2416  	// KSMConfiguration holds the information regarding the enabling the KSM in the nodes (if available).
  2417  	KSMConfiguration *KSMConfiguration `json:"ksmConfiguration,omitempty"`
  2418  
  2419  	// When set, AutoCPULimitNamespaceLabelSelector will set a CPU limit on virt-launcher for VMIs running inside
  2420  	// namespaces that match the label selector.
  2421  	// The CPU limit will equal the number of requested vCPUs.
  2422  	// This setting does not apply to VMIs with dedicated CPUs.
  2423  	AutoCPULimitNamespaceLabelSelector *metav1.LabelSelector `json:"autoCPULimitNamespaceLabelSelector,omitempty"`
  2424  	// LiveUpdateConfiguration holds defaults for live update features
  2425  	LiveUpdateConfiguration *LiveUpdateConfiguration `json:"liveUpdateConfiguration,omitempty"`
  2426  
  2427  	// VMRolloutStrategy defines how changes to a VM object propagate to its VMI
  2428  	// +nullable
  2429  	// +kubebuilder:validation:Enum=Stage;LiveUpdate
  2430  	VMRolloutStrategy *VMRolloutStrategy `json:"vmRolloutStrategy,omitempty"`
  2431  }
  2432  
  2433  type VMRolloutStrategy string
  2434  
  2435  const (
  2436  	// VMRolloutStrategyStage is the default strategy. It means changes to VM objects will be staged until the next VM reboot
  2437  	VMRolloutStrategyStage VMRolloutStrategy = "Stage"
  2438  	// VMRolloutStrategyLiveUpdate means changes to VM objects will be propagated to their VMI when possible
  2439  	VMRolloutStrategyLiveUpdate VMRolloutStrategy = "LiveUpdate"
  2440  )
  2441  
  2442  type ArchConfiguration struct {
  2443  	Amd64               *ArchSpecificConfiguration `json:"amd64,omitempty"`
  2444  	Arm64               *ArchSpecificConfiguration `json:"arm64,omitempty"`
  2445  	Ppc64le             *ArchSpecificConfiguration `json:"ppc64le,omitempty"`
  2446  	DefaultArchitecture string                     `json:"defaultArchitecture,omitempty"`
  2447  }
  2448  
  2449  type ArchSpecificConfiguration struct {
  2450  	OVMFPath string `json:"ovmfPath,omitempty"`
  2451  	// +listType=atomic
  2452  	EmulatedMachines []string `json:"emulatedMachines,omitempty,flow"`
  2453  	MachineType      string   `json:"machineType,omitempty"`
  2454  }
  2455  
  2456  type SMBiosConfiguration struct {
  2457  	Manufacturer string `json:"manufacturer,omitempty"`
  2458  	Product      string `json:"product,omitempty"`
  2459  	Version      string `json:"version,omitempty"`
  2460  	Sku          string `json:"sku,omitempty"`
  2461  	Family       string `json:"family,omitempty"`
  2462  }
  2463  
  2464  type SupportContainerType string
  2465  
  2466  const (
  2467  	// HotplugAttachment is the container resources of the hotplug attachment pod used to hotplug a disk
  2468  	HotplugAttachment SupportContainerType = "hotplug-disk"
  2469  	// ContainerDisk is the container resources used to attach a container disk to the Virtual Machine
  2470  	ContainerDisk SupportContainerType = "container-disk"
  2471  	// VirtioFS is the container resources used to attach a virtio-fs volume to the Virtual Machine
  2472  	VirtioFS SupportContainerType = "virtiofs"
  2473  	// SideCar is the container resources for a side car
  2474  	SideCar SupportContainerType = "sidecar"
  2475  	// VMExport is the container resources for a vm exporter pod
  2476  	VMExport SupportContainerType = "vmexport"
  2477  	// GuestConsoleLog is the container resources for a guest console log streaming container
  2478  	GuestConsoleLog SupportContainerType = "guest-console-log"
  2479  )
  2480  
  2481  // SupportContainerResources are used to specify the cpu/memory request and limits for the containers that support various features of Virtual Machines. These containers are usually idle and don't require a lot of memory or cpu.
  2482  type SupportContainerResources struct {
  2483  	Type      SupportContainerType       `json:"type"`
  2484  	Resources k8sv1.ResourceRequirements `json:"resources"`
  2485  }
  2486  
  2487  type TLSProtocolVersion string
  2488  
  2489  const (
  2490  	// VersionTLS10 is version 1.0 of the TLS security protocol.
  2491  	VersionTLS10 TLSProtocolVersion = "VersionTLS10"
  2492  	// VersionTLS11 is version 1.1 of the TLS security protocol.
  2493  	VersionTLS11 TLSProtocolVersion = "VersionTLS11"
  2494  	// VersionTLS12 is version 1.2 of the TLS security protocol.
  2495  	VersionTLS12 TLSProtocolVersion = "VersionTLS12"
  2496  	// VersionTLS13 is version 1.3 of the TLS security protocol.
  2497  	VersionTLS13 TLSProtocolVersion = "VersionTLS13"
  2498  )
  2499  
  2500  type CustomProfile struct {
  2501  	LocalhostProfile      *string `json:"localhostProfile,omitempty"`
  2502  	RuntimeDefaultProfile bool    `json:"runtimeDefaultProfile,omitempty"`
  2503  }
  2504  
  2505  type VirtualMachineInstanceProfile struct {
  2506  	// CustomProfile allows to request arbitrary profile for virt-launcher
  2507  	CustomProfile *CustomProfile `json:"customProfile,omitempty"`
  2508  }
  2509  
  2510  // SeccompConfiguration holds Seccomp configuration for Kubevirt components
  2511  type SeccompConfiguration struct {
  2512  	// VirtualMachineInstanceProfile defines what profile should be used with virt-launcher. Defaults to none
  2513  	VirtualMachineInstanceProfile *VirtualMachineInstanceProfile `json:"virtualMachineInstanceProfile,omitempty"`
  2514  }
  2515  
  2516  // VirtualMachineOptions holds the cluster level information regarding the virtual machine.
  2517  type VirtualMachineOptions struct {
  2518  	// DisableFreePageReporting disable the free page reporting of
  2519  	// memory balloon device https://libvirt.org/formatdomain.html#memory-balloon-device.
  2520  	// This will have effect only if AutoattachMemBalloon is not false and the vmi is not
  2521  	// requesting any high performance feature (dedicatedCPU/realtime/hugePages), in which free page reporting is always disabled.
  2522  	DisableFreePageReporting *DisableFreePageReporting `json:"disableFreePageReporting,omitempty"`
  2523  
  2524  	// DisableSerialConsoleLog disables logging the auto-attached default serial console.
  2525  	// If not set, serial console logs will be written to a file and then streamed from a container named `guest-console-log`.
  2526  	// The value can be individually overridden for each VM, not relevant if AutoattachSerialConsole is disabled.
  2527  	DisableSerialConsoleLog *DisableSerialConsoleLog `json:"disableSerialConsoleLog,omitempty"`
  2528  }
  2529  
  2530  type DisableFreePageReporting struct{}
  2531  
  2532  type DisableSerialConsoleLog struct{}
  2533  
  2534  // TLSConfiguration holds TLS options
  2535  type TLSConfiguration struct {
  2536  	// MinTLSVersion is a way to specify the minimum protocol version that is acceptable for TLS connections.
  2537  	// Protocol versions are based on the following most common TLS configurations:
  2538  	//
  2539  	//   https://ssl-config.mozilla.org/
  2540  	//
  2541  	// Note that SSLv3.0 is not a supported protocol version due to well known
  2542  	// vulnerabilities such as POODLE: https://en.wikipedia.org/wiki/POODLE
  2543  	// +kubebuilder:validation:Enum=VersionTLS10;VersionTLS11;VersionTLS12;VersionTLS13
  2544  	MinTLSVersion TLSProtocolVersion `json:"minTLSVersion,omitempty"`
  2545  	// +listType=set
  2546  	Ciphers []string `json:"ciphers,omitempty"`
  2547  }
  2548  
  2549  // MigrationConfiguration holds migration options.
  2550  // Can be overridden for specific groups of VMs though migration policies.
  2551  // Visit https://kubevirt.io/user-guide/operations/migration_policies/ for more information.
  2552  type MigrationConfiguration struct {
  2553  	// NodeDrainTaintKey defines the taint key that indicates a node should be drained.
  2554  	// Note: this option relies on the deprecated node taint feature. Default: kubevirt.io/drain
  2555  	NodeDrainTaintKey *string `json:"nodeDrainTaintKey,omitempty"`
  2556  	// ParallelOutboundMigrationsPerNode is the maximum number of concurrent outgoing live migrations
  2557  	// allowed per node. Defaults to 2
  2558  	ParallelOutboundMigrationsPerNode *uint32 `json:"parallelOutboundMigrationsPerNode,omitempty"`
  2559  	// ParallelMigrationsPerCluster is the total number of concurrent live migrations
  2560  	// allowed cluster-wide. Defaults to 5
  2561  	ParallelMigrationsPerCluster *uint32 `json:"parallelMigrationsPerCluster,omitempty"`
  2562  	// AllowAutoConverge allows the platform to compromise performance/availability of VMIs to
  2563  	// guarantee successful VMI live migrations. Defaults to false
  2564  	AllowAutoConverge *bool `json:"allowAutoConverge,omitempty"`
  2565  	// BandwidthPerMigration limits the amount of network bandwidth live migrations are allowed to use.
  2566  	// The value is in quantity per second. Defaults to 0 (no limit)
  2567  	BandwidthPerMigration *resource.Quantity `json:"bandwidthPerMigration,omitempty"`
  2568  	// CompletionTimeoutPerGiB is the maximum number of seconds per GiB a migration is allowed to take.
  2569  	// If a live-migration takes longer to migrate than this value multiplied by the size of the VMI,
  2570  	// the migration will be cancelled, unless AllowPostCopy is true. Defaults to 800
  2571  	CompletionTimeoutPerGiB *int64 `json:"completionTimeoutPerGiB,omitempty"`
  2572  	// ProgressTimeout is the maximum number of seconds a live migration is allowed to make no progress.
  2573  	// Hitting this timeout means a migration transferred 0 data for that many seconds. The migration is
  2574  	// then considered stuck and therefore cancelled. Defaults to 150
  2575  	ProgressTimeout *int64 `json:"progressTimeout,omitempty"`
  2576  	// UnsafeMigrationOverride allows live migrations to occur even if the compatibility check
  2577  	// indicates the migration will be unsafe to the guest. Defaults to false
  2578  	UnsafeMigrationOverride *bool `json:"unsafeMigrationOverride,omitempty"`
  2579  	// AllowPostCopy enables post-copy live migrations. Such migrations allow even the busiest VMIs
  2580  	// to successfully live-migrate. However, events like a network failure can cause a VMI crash.
  2581  	// If set to true, migrations will still start in pre-copy, but switch to post-copy when
  2582  	// CompletionTimeoutPerGiB triggers. Defaults to false
  2583  	AllowPostCopy *bool `json:"allowPostCopy,omitempty"`
  2584  	// When set to true, DisableTLS will disable the additional layer of live migration encryption
  2585  	// provided by KubeVirt. This is usually a bad idea. Defaults to false
  2586  	DisableTLS *bool `json:"disableTLS,omitempty"`
  2587  	// Network is the name of the CNI network to use for live migrations. By default, migrations go
  2588  	// through the pod network.
  2589  	Network *string `json:"network,omitempty"`
  2590  	// By default, the SELinux level of target virt-launcher pods is forced to the level of the source virt-launcher.
  2591  	// When set to true, MatchSELinuxLevelOnMigration lets the CRI auto-assign a random level to the target.
  2592  	// That will ensure the target virt-launcher doesn't share categories with another pod on the node.
  2593  	// However, migrations will fail when using RWX volumes that don't automatically deal with SELinux levels.
  2594  	MatchSELinuxLevelOnMigration *bool `json:"matchSELinuxLevelOnMigration,omitempty"`
  2595  }
  2596  
  2597  // DiskVerification holds container disks verification limits
  2598  type DiskVerification struct {
  2599  	MemoryLimit *resource.Quantity `json:"memoryLimit"`
  2600  }
  2601  
  2602  // DeveloperConfiguration holds developer options
  2603  type DeveloperConfiguration struct {
  2604  	// FeatureGates is the list of experimental features to enable. Defaults to none
  2605  	FeatureGates []string `json:"featureGates,omitempty"`
  2606  	// LessPVCSpaceToleration determines how much smaller, in percentage, disk PVCs are
  2607  	// allowed to be compared to the requested size (to account for various overheads).
  2608  	// Defaults to 10
  2609  	LessPVCSpaceToleration int `json:"pvcTolerateLessSpaceUpToPercent,omitempty"`
  2610  	// MinimumReservePVCBytes is the amount of space, in bytes, to leave unused on disks.
  2611  	// Defaults to 131072 (128KiB)
  2612  	MinimumReservePVCBytes uint64 `json:"minimumReservePVCBytes,omitempty"`
  2613  	// MemoryOvercommit is the percentage of memory we want to give VMIs compared to the amount
  2614  	// given to its parent pod (virt-launcher). For example, a value of 102 means the VMI will
  2615  	// "see" 2% more memory than its parent pod. Values under 100 are effectively "undercommits".
  2616  	// Overcommits can lead to memory exhaustion, which in turn can lead to crashes. Use carefully.
  2617  	// Defaults to 100
  2618  	MemoryOvercommit int `json:"memoryOvercommit,omitempty"`
  2619  	// NodeSelectors allows restricting VMI creation to nodes that match a set of labels.
  2620  	// Defaults to none
  2621  	NodeSelectors map[string]string `json:"nodeSelectors,omitempty"`
  2622  	// UseEmulation can be set to true to allow fallback to software emulation
  2623  	// in case hardware-assisted emulation is not available. Defaults to false
  2624  	UseEmulation bool `json:"useEmulation,omitempty"`
  2625  	// For each requested virtual CPU, CPUAllocationRatio defines how much physical CPU to request per VMI
  2626  	// from the hosting node. The value is in fraction of a CPU thread (or core on non-hyperthreaded nodes).
  2627  	// For example, a value of 1 means 1 physical CPU thread per VMI CPU thread.
  2628  	// A value of 100 would be 1% of a physical thread allocated for each requested VMI thread.
  2629  	// This option has no effect on VMIs that request dedicated CPUs. More information at:
  2630  	// https://kubevirt.io/user-guide/operations/node_overcommit/#node-cpu-allocation-ratio
  2631  	// Defaults to 10
  2632  	CPUAllocationRatio int `json:"cpuAllocationRatio,omitempty"`
  2633  	// Allow overriding the automatically determined minimum TSC frequency of the cluster
  2634  	// and fixate the minimum to this frequency.
  2635  	MinimumClusterTSCFrequency *int64            `json:"minimumClusterTSCFrequency,omitempty"`
  2636  	DiskVerification           *DiskVerification `json:"diskVerification,omitempty"`
  2637  	LogVerbosity               *LogVerbosity     `json:"logVerbosity,omitempty"`
  2638  }
  2639  
  2640  // LogVerbosity sets log verbosity level of  various components
  2641  type LogVerbosity struct {
  2642  	VirtAPI        uint `json:"virtAPI,omitempty"`
  2643  	VirtController uint `json:"virtController,omitempty"`
  2644  	VirtHandler    uint `json:"virtHandler,omitempty"`
  2645  	VirtLauncher   uint `json:"virtLauncher,omitempty"`
  2646  	VirtOperator   uint `json:"virtOperator,omitempty"`
  2647  	// NodeVerbosity represents a map of nodes with a specific verbosity level
  2648  	NodeVerbosity map[string]uint `json:"nodeVerbosity,omitempty"`
  2649  }
  2650  
  2651  const (
  2652  	PCIResourcePrefix  = "PCI_RESOURCE"
  2653  	MDevResourcePrefix = "MDEV_PCI_RESOURCE"
  2654  	USBResourcePrefix  = "USB_RESOURCE"
  2655  )
  2656  
  2657  // PermittedHostDevices holds information about devices allowed for passthrough
  2658  type PermittedHostDevices struct {
  2659  	// +listType=atomic
  2660  	PciHostDevices []PciHostDevice `json:"pciHostDevices,omitempty"`
  2661  	// +listType=atomic
  2662  	MediatedDevices []MediatedHostDevice `json:"mediatedDevices,omitempty"`
  2663  	// +listType=atomic
  2664  	USB []USBHostDevice `json:"usb,omitempty"`
  2665  }
  2666  
  2667  type USBHostDevice struct {
  2668  	// Identifies the list of USB host devices.
  2669  	// e.g: kubevirt.io/storage, kubevirt.io/bootable-usb, etc
  2670  	ResourceName string `json:"resourceName"`
  2671  	// +listType=atomic
  2672  	Selectors []USBSelector `json:"selectors,omitempty"`
  2673  	// If true, KubeVirt will leave the allocation and monitoring to an
  2674  	// external device plugin
  2675  	ExternalResourceProvider bool `json:"externalResourceProvider,omitempty"`
  2676  }
  2677  
  2678  type USBSelector struct {
  2679  	Vendor  string `json:"vendor"`
  2680  	Product string `json:"product"`
  2681  }
  2682  
  2683  // PciHostDevice represents a host PCI device allowed for passthrough
  2684  type PciHostDevice struct {
  2685  	// The vendor_id:product_id tuple of the PCI device
  2686  	PCIVendorSelector string `json:"pciVendorSelector"`
  2687  	// The name of the resource that is representing the device. Exposed by
  2688  	// a device plugin and requested by VMs. Typically of the form
  2689  	// vendor.com/product_name
  2690  	ResourceName string `json:"resourceName"`
  2691  	// If true, KubeVirt will leave the allocation and monitoring to an
  2692  	// external device plugin
  2693  	ExternalResourceProvider bool `json:"externalResourceProvider,omitempty"`
  2694  }
  2695  
  2696  // MediatedHostDevice represents a host mediated device allowed for passthrough
  2697  type MediatedHostDevice struct {
  2698  	MDEVNameSelector         string `json:"mdevNameSelector"`
  2699  	ResourceName             string `json:"resourceName"`
  2700  	ExternalResourceProvider bool   `json:"externalResourceProvider,omitempty"`
  2701  }
  2702  
  2703  // MediatedDevicesConfiguration holds information about MDEV types to be defined, if available
  2704  type MediatedDevicesConfiguration struct {
  2705  	// Deprecated. Use mediatedDeviceTypes instead.
  2706  	// +optional
  2707  	// +listType=atomic
  2708  	MediatedDevicesTypes []string `json:"mediatedDevicesTypes,omitempty"`
  2709  	// +optional
  2710  	// +listType=atomic
  2711  	MediatedDeviceTypes []string `json:"mediatedDeviceTypes,omitempty"`
  2712  	// +optional
  2713  	// +listType=atomic
  2714  	NodeMediatedDeviceTypes []NodeMediatedDeviceTypesConfig `json:"nodeMediatedDeviceTypes,omitempty"`
  2715  }
  2716  
  2717  // NodeMediatedDeviceTypesConfig holds information about MDEV types to be defined in a specific node that matches the NodeSelector field.
  2718  // +k8s:openapi-gen=true
  2719  type NodeMediatedDeviceTypesConfig struct {
  2720  	// NodeSelector is a selector which must be true for the vmi to fit on a node.
  2721  	// Selector which must match a node's labels for the vmi to be scheduled on that node.
  2722  	// More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
  2723  	NodeSelector map[string]string `json:"nodeSelector"`
  2724  	// Deprecated. Use mediatedDeviceTypes instead.
  2725  	// +optional
  2726  	// +listType=atomic
  2727  	MediatedDevicesTypes []string `json:"mediatedDevicesTypes,omitempty"`
  2728  	// +optional
  2729  	// +listType=atomic
  2730  	MediatedDeviceTypes []string `json:"mediatedDeviceTypes"`
  2731  }
  2732  
  2733  // KSMConfiguration holds information about KSM.
  2734  // +k8s:openapi-gen=true
  2735  type KSMConfiguration struct {
  2736  	// NodeLabelSelector is a selector that filters in which nodes the KSM will be enabled.
  2737  	// Empty NodeLabelSelector will enable ksm for every node.
  2738  	// +optional
  2739  	NodeLabelSelector *metav1.LabelSelector `json:"nodeLabelSelector,omitempty"`
  2740  }
  2741  
  2742  // NetworkConfiguration holds network options
  2743  type NetworkConfiguration struct {
  2744  	NetworkInterface                  string                            `json:"defaultNetworkInterface,omitempty"`
  2745  	PermitSlirpInterface              *bool                             `json:"permitSlirpInterface,omitempty"`
  2746  	PermitBridgeInterfaceOnPodNetwork *bool                             `json:"permitBridgeInterfaceOnPodNetwork,omitempty"`
  2747  	Binding                           map[string]InterfaceBindingPlugin `json:"binding,omitempty"`
  2748  }
  2749  
  2750  type InterfaceBindingPlugin struct {
  2751  	// SidecarImage references a container image that runs in the virt-launcher pod.
  2752  	// The sidecar handles (libvirt) domain configuration and optional services.
  2753  	// version: 1alphav1
  2754  	SidecarImage string `json:"sidecarImage,omitempty"`
  2755  	// NetworkAttachmentDefinition references to a NetworkAttachmentDefinition CR object.
  2756  	// Format: <name>, <namespace>/<name>.
  2757  	// If namespace is not specified, VMI namespace is assumed.
  2758  	// version: 1alphav1
  2759  	NetworkAttachmentDefinition string `json:"networkAttachmentDefinition,omitempty"`
  2760  	// DomainAttachmentType is a standard domain network attachment method kubevirt supports.
  2761  	// Supported values: "tap".
  2762  	// The standard domain attachment can be used instead or in addition to the sidecarImage.
  2763  	// version: 1alphav1
  2764  	DomainAttachmentType DomainAttachmentType `json:"domainAttachmentType,omitempty"`
  2765  	// Migration means the VM using the plugin can be safely migrated
  2766  	// version: 1alphav1
  2767  	Migration *InterfaceBindingMigration `json:"migration,omitempty"`
  2768  }
  2769  
  2770  type DomainAttachmentType string
  2771  
  2772  const (
  2773  	// Tap domain attachment type is a generic way to bind ethernet connection into guests using tap device
  2774  	// https://libvirt.org/formatdomain.html#generic-ethernet-connection.
  2775  	Tap DomainAttachmentType = "tap"
  2776  )
  2777  
  2778  type InterfaceBindingMigration struct {
  2779  	// Method defines a pre-defined migration methodology
  2780  	// version: 1alphav1
  2781  	Method MigrationMethod `json:"method,omitempty"`
  2782  }
  2783  
  2784  type MigrationMethod string
  2785  
  2786  const (
  2787  	// LinkRefresh method will invoke link down -> link up interface to give a chance to the guest to request new IP address and routes from DHCP
  2788  	LinkRefresh MigrationMethod = "link-refresh"
  2789  )
  2790  
  2791  // GuestAgentPing configures the guest-agent based ping probe
  2792  type GuestAgentPing struct {
  2793  }
  2794  
  2795  type ProfilerResult struct {
  2796  	PprofData map[string][]byte `json:"pprofData,omitempty"`
  2797  }
  2798  
  2799  type ClusterProfilerResults struct {
  2800  	ComponentResults map[string]ProfilerResult `json:"componentResults"`
  2801  	Continue         string                    `json:"continue,omitempty"`
  2802  }
  2803  
  2804  type ClusterProfilerRequest struct {
  2805  	LabelSelector string `json:"labelSelector,omitempty"`
  2806  	Continue      string `json:"continue,omitempty"`
  2807  	PageSize      int64  `json:"pageSize"`
  2808  }
  2809  
  2810  type Matcher interface {
  2811  	GetName() string
  2812  	GetRevisionName() string
  2813  }
  2814  
  2815  type InferFromVolumeFailurePolicy string
  2816  
  2817  const (
  2818  	RejectInferFromVolumeFailure InferFromVolumeFailurePolicy = "Reject"
  2819  	IgnoreInferFromVolumeFailure InferFromVolumeFailurePolicy = "Ignore"
  2820  )
  2821  
  2822  // InstancetypeMatcher references a instancetype that is used to fill fields in the VMI template.
  2823  type InstancetypeMatcher struct {
  2824  	// Name is the name of the VirtualMachineInstancetype or VirtualMachineClusterInstancetype
  2825  	//
  2826  	// +optional
  2827  	Name string `json:"name,omitempty"`
  2828  
  2829  	// Kind specifies which instancetype resource is referenced.
  2830  	// Allowed values are: "VirtualMachineInstancetype" and "VirtualMachineClusterInstancetype".
  2831  	// If not specified, "VirtualMachineClusterInstancetype" is used by default.
  2832  	//
  2833  	// +optional
  2834  	Kind string `json:"kind,omitempty"`
  2835  
  2836  	// RevisionName specifies a ControllerRevision containing a specific copy of the
  2837  	// VirtualMachineInstancetype or VirtualMachineClusterInstancetype to be used. This is initially
  2838  	// captured the first time the instancetype is applied to the VirtualMachineInstance.
  2839  	//
  2840  	// +optional
  2841  	RevisionName string `json:"revisionName,omitempty"`
  2842  
  2843  	// InferFromVolume lists the name of a volume that should be used to infer or discover the instancetype
  2844  	// to be used through known annotations on the underlying resource. Once applied to the InstancetypeMatcher
  2845  	// this field is removed.
  2846  	//
  2847  	// +optional
  2848  	InferFromVolume string `json:"inferFromVolume,omitempty"`
  2849  
  2850  	// InferFromVolumeFailurePolicy controls what should happen on failure when inferring the instancetype.
  2851  	// Allowed values are: "RejectInferFromVolumeFailure" and "IgnoreInferFromVolumeFailure".
  2852  	// If not specified, "RejectInferFromVolumeFailure" is used by default.
  2853  	//
  2854  	// +optional
  2855  	InferFromVolumeFailurePolicy *InferFromVolumeFailurePolicy `json:"inferFromVolumeFailurePolicy,omitempty"`
  2856  }
  2857  
  2858  func (i InstancetypeMatcher) GetName() string {
  2859  	return i.Name
  2860  }
  2861  
  2862  func (i InstancetypeMatcher) GetRevisionName() string {
  2863  	return i.RevisionName
  2864  }
  2865  
  2866  // PreferenceMatcher references a set of preference that is used to fill fields in the VMI template.
  2867  type PreferenceMatcher struct {
  2868  	// Name is the name of the VirtualMachinePreference or VirtualMachineClusterPreference
  2869  	//
  2870  	// +optional
  2871  	Name string `json:"name,omitempty"`
  2872  
  2873  	// Kind specifies which preference resource is referenced.
  2874  	// Allowed values are: "VirtualMachinePreference" and "VirtualMachineClusterPreference".
  2875  	// If not specified, "VirtualMachineClusterPreference" is used by default.
  2876  	//
  2877  	// +optional
  2878  	Kind string `json:"kind,omitempty"`
  2879  
  2880  	// RevisionName specifies a ControllerRevision containing a specific copy of the
  2881  	// VirtualMachinePreference or VirtualMachineClusterPreference to be used. This is
  2882  	// initially captured the first time the instancetype is applied to the VirtualMachineInstance.
  2883  	//
  2884  	// +optional
  2885  	RevisionName string `json:"revisionName,omitempty"`
  2886  
  2887  	// InferFromVolume lists the name of a volume that should be used to infer or discover the preference
  2888  	// to be used through known annotations on the underlying resource. Once applied to the PreferenceMatcher
  2889  	// this field is removed.
  2890  	//
  2891  	// +optional
  2892  	InferFromVolume string `json:"inferFromVolume,omitempty"`
  2893  
  2894  	// InferFromVolumeFailurePolicy controls what should happen on failure when preference the instancetype.
  2895  	// Allowed values are: "RejectInferFromVolumeFailure" and "IgnoreInferFromVolumeFailure".
  2896  	// If not specified, "RejectInferFromVolumeFailure" is used by default.
  2897  	//
  2898  	// +optional
  2899  	InferFromVolumeFailurePolicy *InferFromVolumeFailurePolicy `json:"inferFromVolumeFailurePolicy,omitempty"`
  2900  }
  2901  
  2902  func (p PreferenceMatcher) GetName() string {
  2903  	return p.Name
  2904  }
  2905  
  2906  func (p PreferenceMatcher) GetRevisionName() string {
  2907  	return p.RevisionName
  2908  }
  2909  
  2910  type LiveUpdateAffinity struct{}
  2911  
  2912  type LiveUpdateCPU struct {
  2913  	// The maximum amount of sockets that can be hot-plugged to the Virtual Machine
  2914  	MaxSockets *uint32 `json:"maxSockets,omitempty" optional:"true"`
  2915  }
  2916  
  2917  type LiveUpdateConfiguration struct {
  2918  	// MaxHotplugRatio is the ratio used to define the max amount
  2919  	// of a hotplug resource that can be made available to a VM
  2920  	// when the specific Max* setting is not defined (MaxCpuSockets, MaxGuest)
  2921  	// Example: VM is configured with 512Mi of guest memory, if MaxGuest is not
  2922  	// defined and MaxHotplugRatio is 2 then MaxGuest = 1Gi
  2923  	// defaults to 4
  2924  	MaxHotplugRatio uint32 `json:"maxHotplugRatio,omitempty"`
  2925  	// MaxCpuSockets holds the maximum amount of sockets that can be hotplugged
  2926  	MaxCpuSockets *uint32 `json:"maxCpuSockets,omitempty"`
  2927  	// MaxGuest defines the maximum amount memory that can be allocated
  2928  	// to the guest using hotplug.
  2929  	MaxGuest *resource.Quantity `json:"maxGuest,omitempty"`
  2930  }
  2931  
  2932  type LiveUpdateMemory struct {
  2933  	// MaxGuest defines the maximum amount memory that can be allocated for the VM.
  2934  	// +optional
  2935  	MaxGuest *resource.Quantity `json:"maxGuest,omitempty"`
  2936  }
  2937  
  2938  // SEVPlatformInfo contains information about the AMD SEV features for the node.
  2939  //
  2940  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  2941  type SEVPlatformInfo struct {
  2942  	metav1.TypeMeta `json:",inline"`
  2943  	// Base64 encoded platform Diffie-Hellman key.
  2944  	PDH string `json:"pdh,omitempty"`
  2945  	// Base64 encoded SEV certificate chain.
  2946  	CertChain string `json:"certChain,omitempty"`
  2947  }
  2948  
  2949  // SEVMeasurementInfo contains information about the guest launch measurement.
  2950  //
  2951  // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
  2952  type SEVMeasurementInfo struct {
  2953  	metav1.TypeMeta `json:",inline"`
  2954  	// Base64 encoded launch measurement of the SEV guest.
  2955  	Measurement string `json:"measurement,omitempty"`
  2956  	// API major version of the SEV host.
  2957  	APIMajor uint `json:"apiMajor,omitempty"`
  2958  	// API minor version of the SEV host.
  2959  	APIMinor uint `json:"apiMinor,omitempty"`
  2960  	// Build ID of the SEV host.
  2961  	BuildID uint `json:"buildID,omitempty"`
  2962  	// Policy of the SEV guest.
  2963  	Policy uint `json:"policy,omitempty"`
  2964  	// SHA256 of the loader binary
  2965  	LoaderSHA string `json:"loaderSHA,omitempty"`
  2966  }
  2967  
  2968  // SEVSessionOptions is used to provide SEV session parameters.
  2969  type SEVSessionOptions struct {
  2970  	// Base64 encoded session blob.
  2971  	Session string `json:"session,omitempty"`
  2972  	// Base64 encoded guest owner's Diffie-Hellman key.
  2973  	DHCert string `json:"dhCert,omitempty"`
  2974  }
  2975  
  2976  // SEVSecretOptions is used to provide a secret for a running guest.
  2977  type SEVSecretOptions struct {
  2978  	// Base64 encoded header needed to decrypt the secret.
  2979  	Header string `json:"header,omitempty"`
  2980  	// Base64 encoded encrypted launch secret.
  2981  	Secret string `json:"secret,omitempty"`
  2982  }