Documentation ¶
Overview ¶
Package ovirtclient provides a human-friendly Go client for the oVirt Engine. It provides an abstraction layer for the oVirt API, as well as a mocking facility for testing purposes.
Reading this documentation ¶
This documentation contains two parts. This introduction explains setting up the client with the credentials. The API doc contains the individual API calls.
When reading the API doc, start with the Client interface: it contains all components of the API. The individual API's, their documentation and examples are located in subinterfaces, such as DiskClient.
Creating a client ¶
There are several ways to create a client instance. The most basic way is to use the New() function as follows:
// Create the client client, err := ovirtclient.New( // URL "https://localhost/ovirt-engine/api", // Username "admin@internal", // Password "super-secret", // Pull CA certificates from the operating system. // This won't work on Windows before Go 1.18. See below for an extended example. ovirtclient.TLS().CACertsFromSystem(), // Don't log. ovirtclientlog.NewNOOPLogger(), // No extra connection settings. nil, ) if err != nil { panic(fmt.Errorf("failed to create oVirt client (%w)", err)) }
Mock client ¶
The mock client simulates the oVirt engine behavior in-memory without needing an actual running engine. This is a good way to provide a testing facility.
It can be created using the NewMock method:
client := ovirtclient.NewMock()
That's it! However, to make it really useful, you will need the test helper which can set up test fixtures.
Test helper ¶
The test helper can work in two ways:
Either it sets up test fixtures in the mock client, or it sets up a live connection and identifies a usable storage domain, cluster, etc. for testing purposes.
The ovirtclient.NewMockTestHelper() function can be used to create a test helper with a mock client in the backend:
helper := ovirtclient.NewMockTestHelper(ovirtclientlog.NewNOOPLogger())
The easiest way to set up the test helper for a live connection is by using environment variables. To do that, you can use the ovirtclient.NewLiveTestHelperFromEnv() function:
helper := ovirtclient.NewLiveTestHelperFromEnv(ovirtclientlog.NewNOOPLogger())
This function will inspect environment variables to determine if a connection to a live oVirt engine can be established. The following environment variables are supported:
OVIRT_URL
URL of the oVirt engine API. Mandatory.
OVIRT_USERNAME
The username for the oVirt engine. Mandatory.
OVIRT_PASSWORD
The password for the oVirt engine. Mandatory.
OVIRT_CAFILE
A file containing the CA certificate in PEM format.
OVIRT_CA_BUNDLE
Provide the CA certificate in PEM format directly.
OVIRT_INSECURE
Disable certificate verification if set. Not recommended.
OVIRT_CLUSTER_ID
The cluster to use for testing. Will be automatically chosen if not provided.
OVIRT_BLANK_TEMPLATE_ID
ID of the blank template. Will be automatically chosen if not provided.
OVIRT_STORAGE_DOMAIN_ID
Storage domain to use for testing. Will be automatically chosen if not provided.
OVIRT_VNIC_PROFILE_ID
VNIC profile to use for testing. Will be automatically chosen if not provided.
You can also create the test helper manually:
import ( "os" "testing" ovirtclient "github.com/ovirt/go-ovirt-client" ovirtclientlog "github.com/ovirt/go-ovirt-client-log" ) func TestSomething(t *testing.T) { // Create a logger that logs to the standard Go log here logger := ovirtclientlog.NewTestLogger(t) // Set to true to use in-memory mock, otherwise this will use a live connection isMock := true // The following parameters define which infrastructure parts to use for testing params := ovirtclient.TestHelperParams(). WithClusterID(ovirtclient.ClusterID(os.Getenv("OVIRT_CLUSTER_ID"))). WithBlankTemplateID(ovirtclient.TemplateID(os.Getenv("OVIRT_BLANK_TEMPLATE_ID"))). WithStorageDomainID(ovirtclient.StorageDomainID(os.Getenv("OVIRT_STORAGE_DOMAIN_ID"))). WithSecondaryStorageDomainID(ovirtclient.StorageDomainID(os.Getenv("OVIRT_SECONDARY_STORAGE_DOMAIN_ID"))). WithVNICProfileID(ovirtclient.VNICProfileID(os.Getenv("OVIRT_VNIC_PROFILE_ID"))) // Create the test helper helper, err := ovirtclient.NewTestHelper( "https://localhost/ovirt-engine/api", "admin@internal", "super-secret", // Leave these empty for auto-detection / fixture setup params, ovirtclient.TLS().CACertsFromSystem(), isMock, logger, ) if err != nil { t.Fatal(err) } // Fetch the cluster ID for testing clusterID := helper.GetClusterID() //... }
Logging ¶
This library provides extensive logging. Each API interaction is logged on the debug level, and other messages are added on other levels. In order to provide logging this library uses the go-ovirt-client-log (https://github.com/oVirt/go-ovirt-client-log) interface definition.
As long as your logger implements this interface, you will be able to receive log messages. The logging library also provides a few built-in loggers. For example, you can log via the default Go log interface:
logger := ovirtclientlog.NewGoLogger()
Or, you can also log in tests:
logger := ovirtclientlog.NewTestLogger(t)
You can also disable logging:
logger := ovirtclientlog.NewNOOPLogger()
Finally, we also provide an adapter library for klog here: https://github.com/oVirt/go-ovirt-client-log-klog
TLS verification ¶
Modern-day oVirt engines run secured with TLS. This means that the client needs a way to verify the certificate the server is presenting. This is controlled by the tls parameter of the New() function. You can implement your own source by implementing the TLSProvider interface, but the package also includes a ready-to-use provider.
Create the provider using the TLS() function:
tls := ovirtclient.TLS()
This provider has several functions. The easiest to set up is using the system trust root for certificates. However, this won't work own Windows:
tls.CACertsFromSystem()
Now you need to add your oVirt engine certificate to your system trust root.
If you don't want to, or can't add the certificate to the system trust root, you can also directly provide it to the client.
// Add certificates from a certificate pool you have previously initialized. tls.CACertsFromCertPool(certpool) // Add certificates from an in-memory byte slice. Certificates must be in PEM format. tls.CACertsFromMemory([]byte("-----BEGIN CERTIFICATE-----\n...")) // Add certificates from a single file. Certificates must be in PEM format. tls.CACertsFromFile("/path/to/file.pem") // Add certificates from a directory. Optionally, regular expressions can be passed that must match the file // names. tls.CACertsFromDir("/path/to/certs", regexp.MustCompile(`\.pem`))
Finally, you can also disable certificate verification. Do we need to say that this is a very, very bad idea?
tls.Insecure()
The configured tls variable can then be passed to the New() function to create an oVirt client.
Retries ¶
This library attempts to retry API calls that can be retried if possible. Each function has a sensible retry policy. However, you may want to customize the retries by passing one or more retry flags. The following retry flags are supported:
ovirtclient.ContextStrategy(ctx)
This strategy will stop retries when the context parameter is canceled.
ovirtclient.ExponentialBackoff(factor)
This strategy adds a wait time after each time, which is increased by the given factor on each try. The default is a backoff with a factor of 2.
ovirtclient.AutoRetry()
This strategy will cancel retries if the error in question is a permanent error. This is enabled by default.
ovirtclient.MaxTries(tries)
This strategy will abort retries if a maximum number of tries is reached. On complex calls the retries are counted per underlying API call.
ovirtclient.Timeout(duration)
This strategy will abort retries if a certain time has been elapsed for the higher level call.
ovirtclient.CallTimeout(duration)
This strategy will abort retries if a certain underlying API call takes longer than the specified duration.
Index ¶
- Constants
- func HasErrorCode(err error, code ErrorCode) bool
- type Affinity
- type AffinityGroup
- type AffinityGroupClient
- type AffinityGroupData
- type AffinityGroupID
- type AffinityGroupPriority
- type AffinityHostsRule
- type AffinityRule
- type AffinityVMsRule
- type BuildableCreateAffinityGroupOptionalParams
- type BuildableCreateDiskAttachmentParams
- type BuildableCreateDiskParameters
- type BuildableInitialization
- type BuildableMemoryPolicyParameters
- type BuildableNICParameters
- type BuildableTLSProvider
- type BuildableTagParams
- type BuildableTemplateCreateParameters
- type BuildableTestHelperParameters
- type BuildableUpdateDiskParameters
- type BuildableUpdateNICParameters
- type BuildableUpdateVMParameters
- type BuildableVMCPUParams
- type BuildableVMCPUTopoParams
- type BuildableVMDiskParameters
- type BuildableVMIPSearchParams
- type BuildableVMOSParameters
- type BuildableVMParameters
- type BuildableVMPlacementPolicyParameters
- type BuildableVMSearchParameters
- type BuildableVNICProfileParameters
- type CPUMode
- type Client
- type ClientWithLegacySupport
- type Cluster
- type ClusterClient
- type ClusterID
- type CreateAffinityGroupOptionalParams
- type CreateDiskAttachmentOptionalParams
- type CreateDiskOptionalParameters
- type CreateTagParams
- type Datacenter
- type DatacenterClient
- type DatacenterData
- type DatacenterID
- type Disk
- type DiskAttachment
- type DiskAttachmentClient
- type DiskAttachmentID
- type DiskClient
- type DiskCreation
- type DiskData
- type DiskID
- type DiskInterface
- type DiskInterfaceList
- type DiskStatus
- type DiskStatusList
- type DiskUpdate
- type EngineError
- type ErrorCode
- type ExtraSettings
- type ExtraSettingsBuilder
- type Feature
- type FeatureClient
- type FileStorageDomainTypeList
- type GraphicsConsoleClient
- type Host
- type HostClient
- type HostData
- type HostID
- type HostStatus
- type HostStatusList
- type ImageDownload
- type ImageDownloadReader
- type ImageFormat
- type ImageFormatList
- type Initialization
- type InstanceType
- type InstanceTypeClient
- type InstanceTypeData
- type InstanceTypeID
- type Logger
- type MemoryPolicy
- type MemoryPolicyParameters
- type MockClient
- type NIC
- type NICClient
- type NICData
- type NICID
- type Network
- type NetworkClient
- type NetworkData
- type NetworkID
- type OptionalNICParameters
- type OptionalTemplateCreateParameters
- type OptionalVMDiskParameters
- type OptionalVMParameters
- type OptionalVNICProfileParameters
- type RetryInstance
- type RetryStrategy
- func AutoRetry() RetryStrategy
- func CallTimeout(timeout time.Duration) RetryStrategy
- func ContextStrategy(ctx context.Context) RetryStrategy
- func ExponentialBackoff(factor uint8) RetryStrategy
- func MaxTries(tries uint16) RetryStrategy
- func ReconnectStrategy(client Client) RetryStrategy
- func Timeout(timeout time.Duration) RetryStrategy
- type StorageDomain
- type StorageDomainClient
- type StorageDomainData
- type StorageDomainExternalStatus
- type StorageDomainExternalStatusList
- type StorageDomainID
- type StorageDomainStatus
- type StorageDomainStatusList
- type StorageDomainType
- type StorageDomainTypeList
- type TLSProvider
- type Tag
- type TagClient
- type TagData
- type TagID
- type Template
- type TemplateClient
- type TemplateData
- type TemplateDiskAttachment
- type TemplateDiskAttachmentData
- type TemplateDiskAttachmentID
- type TemplateDiskClient
- type TemplateID
- type TemplateStatus
- type TestConnectionClient
- type TestHelper
- func MustNewTestHelper(username string, password string, url string, tlsProvider TLSProvider, ...) TestHelper
- func NewLiveTestHelperFromEnv(logger ovirtclientlog.Logger) (TestHelper, error)
- func NewMockTestHelper(logger ovirtclientlog.Logger) (TestHelper, error)
- func NewTestHelper(url string, username string, password string, params TestHelperParameters, ...) (TestHelper, error)
- type TestHelperParameters
- type UpdateDiskParameters
- type UpdateNICParameters
- type UpdateVMParameters
- type UploadImageProgress
- type UploadImageResult
- type VM
- type VMAffinity
- type VMCPU
- type VMCPUParams
- type VMCPUTopo
- type VMCPUTopoParams
- type VMClient
- type VMData
- type VMGraphicsConsole
- type VMGraphicsConsoleData
- type VMGraphicsConsoleID
- type VMHugePages
- type VMHugePagesList
- type VMID
- type VMIPSearchParams
- type VMOS
- type VMOSParameters
- type VMPlacementPolicy
- type VMPlacementPolicyParameters
- type VMSearchParameters
- type VMStatus
- type VMStatusList
- type VMType
- type VNICProfile
- type VNICProfileClient
- type VNICProfileData
- type VNICProfileID
Examples ¶
Constants ¶
const MinDiskSizeOVirt uint64 = 1048576
MinDiskSizeOVirt defines the minimum size of 1M for disks in oVirt. Smaller disks can be created, but they lead to bugs in oVirt when creating disks from templates and changing the format.
Variables ¶
This section is empty.
Functions ¶
func HasErrorCode ¶ added in v0.7.0
HasErrorCode returns true if the specified error has the specified error code.
Types ¶
type Affinity ¶ added in v0.9.0
type Affinity bool
Affinity signals if the affinity is positive (attracting VMs to each other) or negative (pushing VMs from each other to different hosts).
const ( // AffinityPositive attracts VMs to each other, they are placed on the same host if enforcing is true, or are // attempted to place on the same host if possible in case enforcing is false. AffinityPositive Affinity = true // AffinityNegative pushes VMs from each other, they are placed on different hosts if enforcing is true, or are // attempted to place on different hosts if possible in case enforcing is false. AffinityNegative Affinity = false )
type AffinityGroup ¶ added in v0.9.0
type AffinityGroup interface { AffinityGroupData // Cluster fetches the cluster this affinity group belongs to. Cluster(retries ...RetryStrategy) (Cluster, error) // Remove removes the current affinity group. Remove(retries ...RetryStrategy) error // AddVM adds the specified VM to the current affinity group. AddVM(id VMID, retries ...RetryStrategy) error // RemoveVM removes the specified VM from the current affinity group. RemoveVM(id VMID, retries ...RetryStrategy) error }
AffinityGroup labels virtual machines, so they run / don't run on the same host.
type AffinityGroupClient ¶ added in v0.9.0
type AffinityGroupClient interface { // CreateAffinityGroup creates an affinity group with the specified parameters. CreateAffinityGroup( clusterID ClusterID, name string, params CreateAffinityGroupOptionalParams, retries ...RetryStrategy, ) ( AffinityGroup, error, ) // ListAffinityGroups returns a list of all affinity groups in the oVirt engine. ListAffinityGroups(clusterID ClusterID, retries ...RetryStrategy) ([]AffinityGroup, error) // GetAffinityGroup returns a specific affinity group based on its ID. An error is returned if the affinity label // doesn't exist. GetAffinityGroup(clusterID ClusterID, id AffinityGroupID, retries ...RetryStrategy) (AffinityGroup, error) // GetAffinityGroupByName returns an affinity group by name. GetAffinityGroupByName(clusterID ClusterID, name string, retries ...RetryStrategy) (AffinityGroup, error) // RemoveAffinityGroup removes the affinity group specified. RemoveAffinityGroup(clusterID ClusterID, id AffinityGroupID, retries ...RetryStrategy) error AddVMToAffinityGroup(clusterID ClusterID, vmID VMID, agID AffinityGroupID, retries ...RetryStrategy) error RemoveVMFromAffinityGroup(clusterID ClusterID, vmID VMID, agID AffinityGroupID, retries ...RetryStrategy) error }
AffinityGroupClient describes the methods required for working with affinity groups.
type AffinityGroupData ¶ added in v0.9.0
type AffinityGroupData interface { // ID returns the oVirt identifier of the affinity group. ID() AffinityGroupID // Name is the user-readable oVirt name of the affinity group. Name() string // Description returns the description of the affinity group. Description() string // ClusterID is the identifier of the cluster this affinity group belongs to. ClusterID() ClusterID // Priority indicates in which order the affinity groups should be evaluated. Priority() AffinityGroupPriority // Enforcing indicates if the deployment should fail if the affinity group cannot be respected. Enforcing() bool // HostsRule contains the rules for hosts. HostsRule() AffinityHostsRule // VMsRule contains the rule for the virtual machines. VMsRule() AffinityVMsRule // VMIDs returns the list of current virtual machine IDs assigned to this affinity group. VMIDs() []VMID }
AffinityGroupData contains the base data for the AffinityGroup.
type AffinityGroupID ¶ added in v0.9.0
type AffinityGroupID string
AffinityGroupID is the identifier for affinity groups.
type AffinityGroupPriority ¶ added in v0.9.0
type AffinityGroupPriority float64
AffinityGroupPriority is a type alias for the type indicating affinity group priority.
type AffinityHostsRule ¶ added in v0.9.0
type AffinityHostsRule AffinityRule
AffinityHostsRule is an alias for hosts rules to avoid mixups.
type AffinityRule ¶ added in v0.9.0
type AffinityRule interface { // Enabled indicates if the rule is enabled. Enabled() bool // Affinity indicates if the affinity is positive (attracting VMs) or negative (pushes VMs from each other). Affinity() Affinity // Enforcing indicates if the deployment should fail if the affinity group cannot be respected. Enforcing() bool }
AffinityRule is a rule for either hosts or virtual machines.
type AffinityVMsRule ¶ added in v0.9.0
type AffinityVMsRule AffinityRule
AffinityVMsRule is an alias for VM rules to avoid mixups.
type BuildableCreateAffinityGroupOptionalParams ¶ added in v0.9.0
type BuildableCreateAffinityGroupOptionalParams interface { CreateAffinityGroupOptionalParams // WithPriority adds a priority to the affinity group. WithPriority(priority AffinityGroupPriority) (BuildableCreateAffinityGroupOptionalParams, error) // MustWithPriority is equivalent to WithPriority, but panics instead of returning an error. MustWithPriority(priority AffinityGroupPriority) BuildableCreateAffinityGroupOptionalParams WithHostsRule(rule AffinityHostsRule) (BuildableCreateAffinityGroupOptionalParams, error) MustWithHostsRule(rule AffinityHostsRule) BuildableCreateAffinityGroupOptionalParams WithHostsRuleParameters( enabled bool, affinity Affinity, enforcing bool, ) (BuildableCreateAffinityGroupOptionalParams, error) MustWithHostsRuleParameters( enabled bool, affinity Affinity, enforcing bool, ) BuildableCreateAffinityGroupOptionalParams WithVMsRule(rule AffinityVMsRule) (BuildableCreateAffinityGroupOptionalParams, error) MustWithVMsRule(rule AffinityVMsRule) BuildableCreateAffinityGroupOptionalParams WithVMsRuleParameters(enabled bool, affinity Affinity, enforcing bool) ( BuildableCreateAffinityGroupOptionalParams, error, ) MustWithVMsRuleParameters( enabled bool, affinity Affinity, enforcing bool, ) BuildableCreateAffinityGroupOptionalParams WithEnforcing(enforcing bool) (BuildableCreateAffinityGroupOptionalParams, error) MustWithEnforcing(enforcing bool) BuildableCreateAffinityGroupOptionalParams WithDescription(description string) (BuildableCreateAffinityGroupOptionalParams, error) MustWithDescription(description string) BuildableCreateAffinityGroupOptionalParams }
BuildableCreateAffinityGroupOptionalParams is a buildable version of CreateAffinityGroupOptionalParams.
func CreateAffinityGroupParams ¶ added in v0.9.0
func CreateAffinityGroupParams() BuildableCreateAffinityGroupOptionalParams
CreateAffinityGroupParams creates a buildable set of parameters for creating an affinity group.
type BuildableCreateDiskAttachmentParams ¶ added in v0.7.0
type BuildableCreateDiskAttachmentParams interface { CreateDiskAttachmentOptionalParams // WithBootable sets whether the disk is bootable. WithBootable(bootable bool) (BuildableCreateDiskAttachmentParams, error) // MustWithBootable is the same as WithBootable, but panics instead of returning an error. MustWithBootable(bootable bool) BuildableCreateDiskAttachmentParams // WithActive sets whether the disk is active is visible to the virtual machine or not. default is true WithActive(active bool) (BuildableCreateDiskAttachmentParams, error) // MustWithActive is the same as WithActive, but panics instead of returning an error. MustWithActive(active bool) BuildableCreateDiskAttachmentParams }
BuildableCreateDiskAttachmentParams is a buildable version of CreateDiskAttachmentOptionalParams.
func CreateDiskAttachmentParams ¶ added in v0.7.0
func CreateDiskAttachmentParams() BuildableCreateDiskAttachmentParams
CreateDiskAttachmentParams creates a buildable set of parameters for creating a disk attachment.
type BuildableCreateDiskParameters ¶ added in v0.7.0
type BuildableCreateDiskParameters interface { CreateDiskOptionalParameters // WithAlias sets the alias of the disk. WithAlias(alias string) (BuildableCreateDiskParameters, error) // MustWithAlias is the same as WithAlias, but panics instead of returning an error. MustWithAlias(alias string) BuildableCreateDiskParameters // WithSparse sets sparse provisioning for the disk. WithSparse(sparse bool) (BuildableCreateDiskParameters, error) // MustWithSparse is the same as WithSparse, but panics instead of returning an error. MustWithSparse(sparse bool) BuildableCreateDiskParameters }
BuildableCreateDiskParameters is a buildable version of CreateDiskOptionalParameters.
func CreateDiskParams ¶ added in v0.7.0
func CreateDiskParams() BuildableCreateDiskParameters
CreateDiskParams creates a buildable set of CreateDiskOptionalParameters for use with Client.CreateDisk.
type BuildableInitialization ¶ added in v0.9.0
type BuildableInitialization interface { Initialization WithCustomScript(customScript string) BuildableInitialization WithHostname(hostname string) BuildableInitialization }
BuildableInitialization is a buildable version of Initialization.
type BuildableMemoryPolicyParameters ¶ added in v0.9.0
type BuildableMemoryPolicyParameters interface { MemoryPolicyParameters WithGuaranteed(guaranteed int64) (BuildableMemoryPolicyParameters, error) MustWithGuaranteed(guaranteed int64) BuildableMemoryPolicyParameters WithMax(max int64) (BuildableMemoryPolicyParameters, error) MustWithMax(max int64) BuildableMemoryPolicyParameters WithBallooning(ballooning bool) (BuildableMemoryPolicyParameters, error) MustWithBallooning(ballooning bool) BuildableMemoryPolicyParameters }
BuildableMemoryPolicyParameters is a buildable version of MemoryPolicyParameters.
func NewMemoryPolicyParameters ¶ added in v0.9.0
func NewMemoryPolicyParameters() BuildableMemoryPolicyParameters
NewMemoryPolicyParameters creates a new instance of BuildableMemoryPolicyParameters.
type BuildableNICParameters ¶ added in v0.7.0
type BuildableNICParameters interface { OptionalNICParameters }
BuildableNICParameters is a modifiable version of OptionalNICParameters. You can use CreateNICParams() to create a new copy, or implement your own.
func CreateNICParams ¶ added in v0.7.0
func CreateNICParams() BuildableNICParameters
CreateNICParams returns a buildable structure of OptionalNICParameters.
type BuildableTLSProvider ¶ added in v0.6.0
type BuildableTLSProvider interface { TLSProvider // Insecure disables CA certificate verification. This cannot be chained as any further option doesn't make any // sense. Insecure() TLSProvider // CACertsFromMemory adds one or more CA certificate from an in-memory byte slice containing PEM-encoded // certificates. This function can be called multiple times to add multiple certificates. The function will fail if // no certificates have been added. CACertsFromMemory(caCert []byte) BuildableTLSProvider // CACertsFromFile adds certificates from a single file. The certificate must be in PEM format. This function can // be called multiple times to add multiple files. CACertsFromFile(file string) BuildableTLSProvider // CACertsFromDir adds all PEM-encoded certificates from a directory. If one or more patterns are passed, the // files will only be added if the files match at least one of the patterns. The certificate will fail if one or // more matching files don't contain a valid certificate. CACertsFromDir(dir string, patterns ...*regexp.Regexp) BuildableTLSProvider // CACertsFromSystem adds the system certificate store. This may fail because the certificate store is not available // or not supported on the platform. CACertsFromSystem() BuildableTLSProvider // CACertsFromCertPool sets a certificate pool to use as a source for certificates. This is incompatible with the // CACertsFromSystem call as both create a certificate pool. This function must not be called twice. CACertsFromCertPool(*x509.CertPool) BuildableTLSProvider }
BuildableTLSProvider is a TLSProvider that allows adding configuration options.
func TLS ¶ added in v0.6.0
func TLS() BuildableTLSProvider
TLS creates a BuildableTLSProvider that can be used to easily add trusted CA certificates and generally follows best practices in terms of TLS settings.
Example ¶
This example shows how to set up TLS verification in a variety of ways.
package main import ( "fmt" "regexp" ovirtclient "github.com/ovirt/go-ovirt-client" ) func main() { tls := ovirtclient.TLS() // Add certificates from an in-memory byte slice. Certificates must be in PEM format. tls.CACertsFromMemory([]byte("-----BEGIN CERTIFICATE-----\n...")) // Add certificates from a single file. Certificates must be in PEM format. tls.CACertsFromFile("/path/to/file.pem") // Add certificates from a directory. Optionally, regular expressions can be passed that must match the file // names. tls.CACertsFromDir("/path/to/certs", regexp.MustCompile(`\.pem`)) // Add system certificates. This does not work on Windows before Go 1.18. tls.CACertsFromSystem() // Disable certificate verification. This is a bad idea. tls.Insecure() // This will typically be called by the ovirtclient.New() function to create a TLS certificate. tlsConfig, err := tls.CreateTLSConfig() if err != nil { panic(fmt.Errorf("failed to create TLS config (%w)", err)) } if tlsConfig.InsecureSkipVerify { fmt.Printf("Certificate verification is disabled.") } else { fmt.Printf("Certificate verification is enabled.") } }
Output: Certificate verification is disabled.
type BuildableTagParams ¶ added in v1.0.0
type BuildableTagParams interface { CreateTagParams WithDescription(description string) (BuildableTagParams, error) MustWithDescription(description string) BuildableTagParams }
BuildableTagParams is an buildable version of CreateTagParams.
func NewCreateTagParams ¶ added in v1.0.0
func NewCreateTagParams() BuildableTagParams
NewCreateTagParams creates a buildable set of CreateTagParams to pass to the CreateTag function.
type BuildableTemplateCreateParameters ¶ added in v0.9.0
type BuildableTemplateCreateParameters interface { OptionalTemplateCreateParameters // WithDescription sets the description of a template. WithDescription(description string) (BuildableTemplateCreateParameters, error) // MustWithDescription is identical to WithDescription, but panics instead of returning an error. MustWithDescription(description string) BuildableTemplateCreateParameters }
BuildableTemplateCreateParameters is a buildable version of OptionalTemplateCreateParameters.
func TemplateCreateParams ¶ added in v0.9.0
func TemplateCreateParams() BuildableTemplateCreateParameters
TemplateCreateParams creates a builder for the parameters of the template creation.
type BuildableTestHelperParameters ¶ added in v0.9.0
type BuildableTestHelperParameters interface { TestHelperParameters // WithClusterID sets the cluster ID usable for testing. WithClusterID(ClusterID) BuildableTestHelperParameters // WithStorageDomainID sets the storage domain that can be used for testing. WithStorageDomainID(StorageDomainID) BuildableTestHelperParameters // WithSecondaryStorageDomainID sets the storage domain that can be used for testing, which is not identical to // the primary storage domain ID. WithSecondaryStorageDomainID(StorageDomainID) BuildableTestHelperParameters // WithBlankTemplateID sets the blank template that can be used for testing. WithBlankTemplateID(TemplateID) BuildableTestHelperParameters // WithVNICProfileID sets the ID of the VNIC profile that can be used for testing. WithVNICProfileID(VNICProfileID) BuildableTestHelperParameters }
BuildableTestHelperParameters is a buildable version of the TestHelperParameters.
func TestHelperParams ¶ added in v0.9.0
func TestHelperParams() BuildableTestHelperParameters
TestHelperParams creates a new copy of BuildableTestHelperParameters usable for building test parameters.
type BuildableUpdateDiskParameters ¶ added in v0.7.0
type BuildableUpdateDiskParameters interface { UpdateDiskParameters // WithAlias changes the params structure to set the alias to the specified value. It returns an error // if the alias is invalid. WithAlias(alias string) (BuildableUpdateDiskParameters, error) // MustWithAlias is identical to WithAlias, but panics instead of returning an error. MustWithAlias(alias string) BuildableUpdateDiskParameters // WithProvisionedSize changes the params structure to set the provisioned size to the specified value. // It returns an error if the provisioned size is invalid. WithProvisionedSize(size uint64) (BuildableUpdateDiskParameters, error) // MustWithProvisionedSize is identical to WithProvisionedSize, but panics instead of returning an error. MustWithProvisionedSize(size uint64) BuildableUpdateDiskParameters }
BuildableUpdateDiskParameters is a buildable version of UpdateDiskParameters.
func UpdateDiskParams ¶ added in v0.7.0
func UpdateDiskParams() BuildableUpdateDiskParameters
UpdateDiskParams creates a builder for the params for updating a disk.
type BuildableUpdateNICParameters ¶ added in v0.7.0
type BuildableUpdateNICParameters interface { UpdateNICParameters // WithName sets the name of a NIC for the UpdateNIC method. WithName(name string) (BuildableUpdateNICParameters, error) // MustWithName is identical to WithName, but panics instead of returning an error. MustWithName(name string) BuildableUpdateNICParameters // WithVNICProfileID sets the VNIC profile ID of a NIC for the UpdateNIC method. WithVNICProfileID(id VNICProfileID) (BuildableUpdateNICParameters, error) // MustWithVNICProfileID is identical to WithVNICProfileID, but panics instead of returning an error. MustWithVNICProfileID(id VNICProfileID) BuildableUpdateNICParameters }
BuildableUpdateNICParameters is a buildable version of UpdateNICParameters.
func UpdateNICParams ¶ added in v0.7.0
func UpdateNICParams() BuildableUpdateNICParameters
UpdateNICParams creates a buildable UpdateNICParameters.
type BuildableUpdateVMParameters ¶ added in v0.7.0
type BuildableUpdateVMParameters interface { UpdateVMParameters // WithName adds an updated name to the request. WithName(name string) (BuildableUpdateVMParameters, error) // MustWithName is identical to WithName, but panics instead of returning an error MustWithName(name string) BuildableUpdateVMParameters // WithComment adds a comment to the request WithComment(comment string) (BuildableUpdateVMParameters, error) // MustWithComment is identical to WithComment, but panics instead of returning an error. MustWithComment(comment string) BuildableUpdateVMParameters }
BuildableUpdateVMParameters is a buildable version of UpdateVMParameters.
func UpdateVMParams ¶ added in v0.7.0
func UpdateVMParams() BuildableUpdateVMParameters
UpdateVMParams returns a buildable set of update parameters.
type BuildableVMCPUParams ¶ added in v1.0.0
type BuildableVMCPUParams interface { VMCPUParams WithMode(mode CPUMode) (BuildableVMCPUParams, error) MustWithMode(mode CPUMode) BuildableVMCPUParams WithTopo(topo VMCPUTopoParams) (BuildableVMCPUParams, error) MustWithTopo(topo VMCPUTopoParams) BuildableVMCPUParams }
BuildableVMCPUParams is a buildable version of VMCPUParams.
func NewVMCPUParams ¶ added in v1.0.0
func NewVMCPUParams() BuildableVMCPUParams
NewVMCPUParams creates a new VMCPUParams object.
type BuildableVMCPUTopoParams ¶ added in v1.0.0
type BuildableVMCPUTopoParams interface { VMCPUTopoParams WithSockets(sockets uint) (BuildableVMCPUTopoParams, error) MustWithSockets(sockets uint) BuildableVMCPUTopoParams WithCores(cores uint) (BuildableVMCPUTopoParams, error) MustWithCores(cores uint) BuildableVMCPUTopoParams WithThreads(threads uint) (BuildableVMCPUTopoParams, error) MustWithThreads(threads uint) BuildableVMCPUTopoParams }
BuildableVMCPUTopoParams is a buildable version of VMCPUTopoParams.
func NewVMCPUTopoParams ¶ added in v1.0.0
func NewVMCPUTopoParams() BuildableVMCPUTopoParams
NewVMCPUTopoParams creates a new BuildableVMCPUTopoParams.
type BuildableVMDiskParameters ¶ added in v0.9.0
type BuildableVMDiskParameters interface { OptionalVMDiskParameters // WithSparse enables or disables sparse disk provisioning. Note, that Sparse is only supported in oVirt on block // devices with QCOW2 images. On NFS you MUST use raw images to use sparse. See WithFormat. WithSparse(sparse bool) (BuildableVMDiskParameters, error) // MustWithSparse is identical to WithSparse, but panics instead of returning an error. MustWithSparse(sparse bool) BuildableVMDiskParameters // WithFormat adds a disk format to the VM on creation. Note, that QCOW2 is only supported in conjunction with // Sparse on block devices. On NFS you MUST use raw images to use sparse. See WithSparse. WithFormat(format ImageFormat) (BuildableVMDiskParameters, error) // MustWithFormat is identical to WithFormat, but panics instead of returning an error. MustWithFormat(format ImageFormat) BuildableVMDiskParameters // WithStorageDomainID adds a storage domain to use for the disk. WithStorageDomainID(storageDomainID StorageDomainID) (BuildableVMDiskParameters, error) // MustWithStorageDomainID is identical to WithStorageDomainID but panics instead of returning an error. MustWithStorageDomainID(storageDomainID StorageDomainID) BuildableVMDiskParameters }
BuildableVMDiskParameters is a buildable version of OptionalVMDiskParameters.
func MustNewBuildableVMDiskParameters ¶ added in v0.9.0
func MustNewBuildableVMDiskParameters(diskID DiskID) BuildableVMDiskParameters
MustNewBuildableVMDiskParameters is identical to NewBuildableVMDiskParameters but panics instead of returning an error.
func NewBuildableVMDiskParameters ¶ added in v0.9.0
func NewBuildableVMDiskParameters(diskID DiskID) (BuildableVMDiskParameters, error)
NewBuildableVMDiskParameters creates a new buildable OptionalVMDiskParameters.
type BuildableVMIPSearchParams ¶ added in v0.9.0
type BuildableVMIPSearchParams interface { VMIPSearchParams WithIncludedRange(ipRange net.IPNet) BuildableVMIPSearchParams WithExcludedRange(ipRange net.IPNet) BuildableVMIPSearchParams WithIncludedInterface(interfaceName string) BuildableVMIPSearchParams WithExcludedInterface(interfaceName string) BuildableVMIPSearchParams WithIncludedInterfacePattern(interfaceNamePattern *regexp.Regexp) BuildableVMIPSearchParams WithExcludedInterfacePattern(interfaceNamePattern *regexp.Regexp) BuildableVMIPSearchParams }
BuildableVMIPSearchParams is a buildable version of VMIPSearchParams.
func NewVMIPSearchParams ¶ added in v0.9.0
func NewVMIPSearchParams() BuildableVMIPSearchParams
NewVMIPSearchParams returns a buildable parameter set for VM IP searches.
type BuildableVMOSParameters ¶ added in v1.0.0
type BuildableVMOSParameters interface { VMOSParameters WithType(t string) (BuildableVMOSParameters, error) MustWithType(t string) BuildableVMOSParameters }
BuildableVMOSParameters is a buildable version of VMOSParameters.
func NewVMOSParameters ¶ added in v1.0.0
func NewVMOSParameters() BuildableVMOSParameters
NewVMOSParameters creates a new VMOSParameters structure.
type BuildableVMParameters ¶ added in v0.6.0
type BuildableVMParameters interface { OptionalVMParameters // WithComment adds a common to the VM. WithComment(comment string) (BuildableVMParameters, error) // MustWithComment is identical to WithComment, but panics instead of returning an error. MustWithComment(comment string) BuildableVMParameters // WithCPU adds a VMCPUTopo to the VM. WithCPU(cpu VMCPUParams) (BuildableVMParameters, error) // MustWithCPU adds a VMCPUTopo and panics if an error happens. MustWithCPU(cpu VMCPUParams) BuildableVMParameters // WithCPUParameters is a simplified function that calls NewVMCPUTopo and adds the CPU topology to // the VM. // Deprecated: use WithCPU instead. WithCPUParameters(cores, threads, sockets uint) (BuildableVMParameters, error) // MustWithCPUParameters is a simplified function that calls MustNewVMCPUTopo and adds the CPU topology to // the VM. // Deprecated: use MustWithCPU instead. MustWithCPUParameters(cores, threads, sockets uint) BuildableVMParameters // WithHugePages sets the HugePages setting for the VM. WithHugePages(hugePages VMHugePages) (BuildableVMParameters, error) // MustWithHugePages is identical to WithHugePages, but panics instead of returning an error. MustWithHugePages(hugePages VMHugePages) BuildableVMParameters // WithMemory sets the Memory setting for the VM. WithMemory(memory int64) (BuildableVMParameters, error) // MustWithMemory is identical to WithMemory, but panics instead of returning an error. MustWithMemory(memory int64) BuildableVMParameters // WithMemoryPolicy sets the memory policy parameters for the VM. WithMemoryPolicy(memory MemoryPolicyParameters) BuildableVMParameters // WithInitialization sets the virtual machine’s initialization configuration. WithInitialization(initialization Initialization) (BuildableVMParameters, error) // MustWithInitialization is identical to WithInitialization, but panics instead of returning an error. MustWithInitialization(initialization Initialization) BuildableVMParameters // MustWithInitializationParameters is a simplified function that calls MustNewInitialization and adds customScript MustWithInitializationParameters(customScript, hostname string) BuildableVMParameters // WithClone sets the clone flag. If the clone flag is true the VM is cloned from the template instead of linking to // it. This means the template can be deleted while the VM still exists. WithClone(clone bool) (BuildableVMParameters, error) // MustWithClone is identical to WithClone, but panics instead of returning an error. MustWithClone(clone bool) BuildableVMParameters // WithDisks adds disk configurations to the VM creation to manipulate the disks inherited from templates. WithDisks(disks []OptionalVMDiskParameters) (BuildableVMParameters, error) // MustWithDisks is identical to WithDisks, but panics instead of returning an error. MustWithDisks(disks []OptionalVMDiskParameters) BuildableVMParameters // WithPlacementPolicy adds a placement policy dictating which hosts the VM can be migrated to. WithPlacementPolicy(placementPolicy VMPlacementPolicyParameters) BuildableVMParameters // WithInstanceTypeID sets the instance type ID on the VM. WithInstanceTypeID(instanceTypeID InstanceTypeID) (BuildableVMParameters, error) // MustWithInstanceTypeID is identical to WithInstanceTypeID but panics instead of returning an error. MustWithInstanceTypeID(instanceTypeID InstanceTypeID) BuildableVMParameters // WithVMType sets the virtual machine type. WithVMType(vmType VMType) (BuildableVMParameters, error) // MustWithVMType is identical to WithVMType, but panics instead of returning an error. MustWithVMType(vmType VMType) BuildableVMParameters // WithOS adds the operating system parameters to the VM creation. WithOS(parameters VMOSParameters) BuildableVMParameters // WithSerialConsole adds or removes a serial console to the VM. WithSerialConsole(serialConsole bool) BuildableVMParameters }
BuildableVMParameters is a variant of OptionalVMParameters that can be changed using the supplied builder functions. This is placed here for future use.
func CreateVMParams ¶ added in v0.7.0
func CreateVMParams() BuildableVMParameters
CreateVMParams creates a set of BuildableVMParameters that can be used to construct the optional VM parameters. Deprecated: use NewCreateVMParams instead.
func NewCreateVMParams ¶ added in v1.0.0
func NewCreateVMParams() BuildableVMParameters
NewCreateVMParams creates a set of BuildableVMParameters that can be used to construct the optional VM parameters.
type BuildableVMPlacementPolicyParameters ¶ added in v0.9.0
type BuildableVMPlacementPolicyParameters interface { VMPlacementPolicyParameters // WithAffinity sets the way VMs can be migrated to other hosts. WithAffinity(affinity VMAffinity) (BuildableVMPlacementPolicyParameters, error) // MustWithAffinity is identical to WithAffinity, but panics instead of returning an error. MustWithAffinity(affinity VMAffinity) BuildableVMPlacementPolicyParameters // WithHostIDs sets the list of hosts this VM can be migrated to. WithHostIDs(hostIDs []HostID) (BuildableVMPlacementPolicyParameters, error) // MustWithHostIDs is identical to WithHostIDs, but panics instead of returning an error. MustWithHostIDs(hostIDs []HostID) BuildableVMPlacementPolicyParameters }
BuildableVMPlacementPolicyParameters is a buildable version of the VMPlacementPolicyParameters.
func NewVMPlacementPolicyParameters ¶ added in v0.9.0
func NewVMPlacementPolicyParameters() BuildableVMPlacementPolicyParameters
NewVMPlacementPolicyParameters creates a new BuildableVMPlacementPolicyParameters for use on VM creation.
type BuildableVMSearchParameters ¶ added in v0.9.0
type BuildableVMSearchParameters interface { VMSearchParameters // WithName sets the name to search for. WithName(name string) BuildableVMSearchParameters // WithTag sets the tag to search for. WithTag(name string) BuildableVMSearchParameters // WithStatus adds a single status to the filter. WithStatus(status VMStatus) BuildableVMSearchParameters // WithNotStatus excludes a VM status from the search. WithNotStatus(status VMStatus) BuildableVMSearchParameters // WithStatuses will return the statuses the returned VMs should be in. WithStatuses(list VMStatusList) BuildableVMSearchParameters // WithNotStatuses will return the statuses the returned VMs should not be in. WithNotStatuses(list VMStatusList) BuildableVMSearchParameters }
BuildableVMSearchParameters is a buildable version of VMSearchParameters.
func VMSearchParams ¶ added in v0.9.0
func VMSearchParams() BuildableVMSearchParameters
VMSearchParams creates a buildable set of search parameters for easier use.
type BuildableVNICProfileParameters ¶ added in v0.7.0
type BuildableVNICProfileParameters interface { OptionalVNICProfileParameters }
BuildableVNICProfileParameters is a buildable version of OptionalVNICProfileParameters.
func CreateVNICProfileParams ¶ added in v0.7.0
func CreateVNICProfileParams() BuildableVNICProfileParameters
CreateVNICProfileParams creats a buildable set of optional parameters for VNICProfile creation.
type CPUMode ¶ added in v1.0.0
type CPUMode string
CPUMode is the mode of the CPU on a VM.
const ( // CPUModeCustom contains custom settings for the CPU. CPUModeCustom CPUMode = "custom" // CPUModeHostModel copies the host CPU make and model. CPUModeHostModel CPUMode = "host_model" // CPUModeHostPassthrough passes through the host CPU for nested virtualization. CPUModeHostPassthrough CPUMode = "host_passthrough" )
func CPUModeValues ¶ added in v1.0.0
func CPUModeValues() []CPUMode
CPUModeValues lists all valid CPU modes.
type Client ¶
type Client interface { // GetURL returns the oVirt engine base URL. GetURL() string // Reconnect triggers the client to reauthenticate against the oVirt Engine. Reconnect() (err error) // WithContext creates a subclient with the specified context applied. WithContext(ctx context.Context) Client // GetContext returns the current context of the client. May be nil. GetContext() context.Context AffinityGroupClient DiskClient DiskAttachmentClient VMClient NICClient VNICProfileClient NetworkClient DatacenterClient ClusterClient StorageDomainClient HostClient TemplateClient TemplateDiskClient TestConnectionClient TagClient FeatureClient InstanceTypeClient GraphicsConsoleClient }
Client is a simplified client for the oVirt API.
type ClientWithLegacySupport ¶
type ClientWithLegacySupport interface { // GetSDKClient returns a configured oVirt SDK client for the use cases that are not covered by goVirt. GetSDKClient() *ovirtsdk4.Connection // GetHTTPClient returns a configured HTTP client for the oVirt engine. This can be used to send manual // HTTP requests to the oVirt engine. GetHTTPClient() http.Client Client }
ClientWithLegacySupport is an extension of Client that also offers the ability to retrieve the underlying SDK connection or a configured HTTP client.
func New ¶
func New( url string, username string, password string, tls TLSProvider, logger Logger, extraSettings ExtraSettings, ) (ClientWithLegacySupport, error)
New creates a new copy of the enhanced oVirt client. It accepts the following options:
url
This is the oVirt engine URL. This must start with http:// or https:// and typically ends with /ovirt-engine/.
username
This is the username for the oVirt engine. This must contain the profile separated with an @ sign. For example, admin@internal.
password
This is the password for the oVirt engine. Other authentication mechanisms are not supported.
tls
This is a TLSProvider responsible for supplying TLS configuration to the client. See below for a simple example.
logger
This is an implementation of ovirtclientlog.Logger to provide logging.
extraSettings
This is an implementation of the ExtraSettings interface, allowing for customization of headers and turning on compression.
TLS ¶
This library tries to follow best practices when it comes to connection security. Therefore, you will need to pass a valid implementation of the TLSProvider interface in the tls parameter. The easiest way to do this is calling the ovirtclient.TLS() function and then configuring the resulting variable with the following functions:
tls := ovirtclient.TLS() // Add certificates from an in-memory byte slice. Certificates must be in PEM format. tls.CACertsFromMemory(caCerts) // Add certificates from a single file. Certificates must be in PEM format. tls.CACertsFromFile("/path/to/file.pem") // Add certificates from a directory. Optionally, regular expressions can be passed that must match the file // names. tls.CACertsFromDir("/path/to/certs", regexp.MustCompile(`\.pem`)) // Add system certificates tls.CACertsFromSystem() // Disable certificate verification. This is a bad idea. tls.Insecure() client, err := ovirtclient.New( url, username, password, tls, logger, extraSettings )
Extra settings ¶
This library also supports customizing the connection settings. In order to stay backwards compatible the extraSettings parameter must implement the ovirtclient.ExtraSettings interface. Future versions of this library will add new interfaces (e.g. ExtraSettingsV2) to add new features without breaking compatibility.
func NewWithVerify ¶ added in v0.5.0
func NewWithVerify( u string, username string, password string, tls TLSProvider, logger Logger, extraSettings ExtraSettings, verify func(connection Client) error, ) (ClientWithLegacySupport, error)
NewWithVerify is equivalent to New, but allows customizing the verification function for the connection. Alternatively, a nil can be passed to disable connection verification.
type Cluster ¶
type Cluster interface { // ID returns the UUID of the cluster. ID() ClusterID // Name returns the textual name of the cluster. Name() string }
Cluster represents a cluster returned from a ListClusters or GetCluster call.
type ClusterClient ¶
type ClusterClient interface { // ListClusters returns a list of all clusters in the oVirt engine. ListClusters(retries ...RetryStrategy) ([]Cluster, error) // GetCluster returns a specific cluster based on the cluster ID. An error is returned if the cluster doesn't exist. GetCluster(id ClusterID, retries ...RetryStrategy) (Cluster, error) }
ClusterClient is a part of the Client that deals with clusters in the oVirt Engine. A cluster is a logical grouping of hosts that share the same storage domains and have the same type of CPU (either Intel or AMD). If the hosts have different generations of CPU models, they use only the features present in all models.
See https://www.ovirt.org/documentation/administration_guide/#chap-Clusters for details.
type CreateAffinityGroupOptionalParams ¶ added in v0.9.0
type CreateAffinityGroupOptionalParams interface { // Priority returns the affinity group priority that should be applied, or nil if no explicit priority should be // applied. Priority() *AffinityGroupPriority // HostsRule returns a hosts rule that should be applied, or nil if no hosts rule should explicitly be applied. HostsRule() AffinityHostsRule // VMsRule returns a VMs rule that should be applied, or nil if no VMs rule should explicitly be applied. VMsRule() AffinityVMsRule // Enforcing returns if the affinity group should be enforced. Enforcing() *bool // Description returns the description for the affinity group. Description() string }
CreateAffinityGroupOptionalParams is a list of optional parameters that can be passed for affinity group creation.
type CreateDiskAttachmentOptionalParams ¶ added in v0.7.0
type CreateDiskAttachmentOptionalParams interface { // Bootable defines whether the disk is bootable. Bootable() *bool // Active defines whether the disk is active in the virtual machine it’s attached to. Active() *bool }
CreateDiskAttachmentOptionalParams are the optional parameters for creating a disk attachment.
type CreateDiskOptionalParameters ¶ added in v0.7.0
type CreateDiskOptionalParameters interface { // Alias is a secondary name for the disk. Alias() string // Sparse indicates that the disk should be sparse-provisioned.If it returns nil, the default will be used. Sparse() *bool }
CreateDiskOptionalParameters is a structure that serves to hold the optional parameters for DiskClient.CreateDisk.
type CreateTagParams ¶ added in v1.0.0
type CreateTagParams interface {
Description() *string
}
CreateTagParams contains the optional parameters for tag creation.
type Datacenter ¶ added in v0.6.0
type Datacenter interface { DatacenterData // Clusters lists the clusters for this datacenter. This is a network call and may be slow. Clusters(retries ...RetryStrategy) ([]Cluster, error) // HasCluster returns true if the cluster is in the datacenter. This is a network call and may be slow. HasCluster(clusterID ClusterID, retries ...RetryStrategy) (bool, error) }
Datacenter is a logical entity that defines the set of resources used in a specific environment. See https://www.ovirt.org/documentation/administration_guide/#chap-Data_Centers for details.
type DatacenterClient ¶ added in v0.6.0
type DatacenterClient interface { // GetDatacenter returns a single datacenter by its ID. GetDatacenter(id DatacenterID, retries ...RetryStrategy) (Datacenter, error) // ListDatacenters lists all datacenters in the oVirt engine. ListDatacenters(retries ...RetryStrategy) ([]Datacenter, error) // ListDatacenterClusters lists all clusters in the specified datacenter. ListDatacenterClusters(id DatacenterID, retries ...RetryStrategy) ([]Cluster, error) }
DatacenterClient contains the functions related to handling datacenter objects in oVirt. Datacenters bind together resources of an environment (clusters, storage domains). See https://www.ovirt.org/documentation/administration_guide/#chap-Data_Centers for details.
type DatacenterData ¶ added in v0.7.0
type DatacenterData interface { ID() DatacenterID Name() string }
DatacenterData is the core of a Datacenter when client functions are not required.
type DatacenterID ¶ added in v1.0.0
type DatacenterID string
DatacenterID is the UUID of a datacenter.
type Disk ¶
type Disk interface { DiskData // StartDownload starts the download of the image file the current disk. // The caller can then wait for the initialization using the Initialized() call: // // <-download.Initialized() // // Alternatively, the downloader can use the Read() function to wait for the download to become available // and then read immediately. // // The caller MUST close the returned reader, otherwise the disk will remain locked in the oVirt engine. // The passed context is observed only for the initialization phase. StartDownload( format ImageFormat, retries ...RetryStrategy, ) (ImageDownload, error) // Download runs StartDownload, then waits for the download to be ready before returning the reader. // The caller MUST close the ImageDownloadReader in order to properly unlock the disk in the oVirt engine. Download( format ImageFormat, retries ...RetryStrategy, ) (ImageDownloadReader, error) // Remove removes the current disk in the oVirt engine. Remove(retries ...RetryStrategy) error // AttachToVM attaches a disk to this VM. AttachToVM( vmID VMID, diskInterface DiskInterface, params CreateDiskAttachmentOptionalParams, retries ...RetryStrategy, ) (DiskAttachment, error) // StartUpdate starts an update to the disk. The returned DiskUpdate can be used to wait // for the update to complete. Use UpdateDiskParams() to obtain a buildable structure. StartUpdate( params UpdateDiskParameters, retries ...RetryStrategy, ) (DiskUpdate, error) // Update updates the current disk with the specified parameters. // Use UpdateDiskParams() to obtain a buildable structure. Update( params UpdateDiskParameters, retries ...RetryStrategy, ) (Disk, error) // StorageDomains will fetch and return the storage domains associated with this disk. StorageDomains(retries ...RetryStrategy) ([]StorageDomain, error) // WaitForOK waits for the disk status to return to OK. WaitForOK(retries ...RetryStrategy) (Disk, error) }
Disk is a disk in oVirt.
type DiskAttachment ¶ added in v0.7.0
type DiskAttachment interface { // ID returns the identifier of the attachment. ID() DiskAttachmentID // VMID returns the ID of the virtual machine this attachment belongs to. VMID() VMID // DiskID returns the ID of the disk in this attachment. DiskID() DiskID // DiskInterface describes the means by which a disk will appear to the VM. DiskInterface() DiskInterface // Bootable defines whether the disk is bootable Bootable() bool // Active defines whether the disk is active in the virtual machine it’s attached to. Active() bool // VM fetches the virtual machine this attachment belongs to. VM(retries ...RetryStrategy) (VM, error) // Disk fetches the disk this attachment attaches. Disk(retries ...RetryStrategy) (Disk, error) // Remove removes the current disk attachment. Remove(retries ...RetryStrategy) error }
DiskAttachment links together a Disk and a VM.
type DiskAttachmentClient ¶ added in v0.7.0
type DiskAttachmentClient interface { // CreateDiskAttachment attaches a disk to a VM. CreateDiskAttachment( vmID VMID, diskID DiskID, diskInterface DiskInterface, params CreateDiskAttachmentOptionalParams, retries ...RetryStrategy, ) (DiskAttachment, error) // GetDiskAttachment returns a single disk attachment in a virtual machine. GetDiskAttachment(vmID VMID, id DiskAttachmentID, retries ...RetryStrategy) (DiskAttachment, error) // ListDiskAttachments lists all disk attachments for a virtual machine. ListDiskAttachments(vmID VMID, retries ...RetryStrategy) ([]DiskAttachment, error) // RemoveDiskAttachment removes the disk attachment in question. RemoveDiskAttachment(vmID VMID, diskAttachmentID DiskAttachmentID, retries ...RetryStrategy) error }
DiskAttachmentClient contains the methods required for handling disk attachments.
type DiskAttachmentID ¶ added in v1.0.0
type DiskAttachmentID string
DiskAttachmentID is the identifier for the disk attachment.
type DiskClient ¶
type DiskClient interface { // StartImageUpload uploads an image file into a disk. The actual upload takes place in the // background and can be tracked using the returned UploadImageProgress object. // // Parameters are as follows: // // - alias: this is the name used for the uploaded image. // - storageDomainID: this is the UUID of the storage domain that the image should be uploaded to. // - sparse: use sparse provisioning // - size: this is the file size of the image. This must match the bytes read. // - reader: this is the source of the image data. // - retries: a set of optional retry options. // // You can wait for the upload to complete using the Done() method: // // progress, err := cli.StartImageUpload(...) // if err != nil { // //... // } // <-progress.Done() // // After the upload is complete you can check the Err() method if it completed successfully: // // if err := progress.Err(); err != nil { // //... // } // // Deprecated: Use StartUploadToNewDisk instead. StartImageUpload( alias string, storageDomainID StorageDomainID, sparse bool, size uint64, reader io.ReadSeekCloser, retries ...RetryStrategy, ) (UploadImageProgress, error) // StartUploadToNewDisk uploads an image file into a disk. The actual upload takes place in the // background and can be tracked using the returned UploadImageProgress object. If the process fails a removal // of the created disk is attempted. // // Parameters are as follows: // // - storageDomainID: this is the UUID of the storage domain that the image should be uploaded to. // - format: format of the created disk. This does not necessarily have to be identical to the format of the image // being uploaded as the oVirt engine converts images on upload. // - size: file size of the uploaded image on the disk. // - reader: this is the source of the image data. It is a reader that must support seek and close operations. // - retries: a set of optional retry options. // // You can wait for the upload to complete using the Done() method: // // progress, err := cli.StartUploadToNewDisk(...) // if err != nil { // //... // } // <-progress.Done() // // After the upload is complete you can check the Err() method if it completed successfully: // // if err := progress.Err(); err != nil { // //... // } StartUploadToNewDisk( storageDomainID StorageDomainID, format ImageFormat, size uint64, params CreateDiskOptionalParameters, reader io.ReadSeekCloser, retries ...RetryStrategy, ) (UploadImageProgress, error) // UploadImage is identical to StartImageUpload, but waits until the upload is complete. It returns the disk ID // as a result, or the error if one happened. // // Deprecated: Use UploadToNewDisk instead. UploadImage( alias string, storageDomainID StorageDomainID, sparse bool, size uint64, reader io.ReadSeekCloser, retries ...RetryStrategy, ) (UploadImageResult, error) // UploadToNewDisk is identical to StartUploadToNewDisk, but waits until the upload is complete. It // returns the disk ID as a result, or the error if one happened. UploadToNewDisk( storageDomainID StorageDomainID, format ImageFormat, size uint64, params CreateDiskOptionalParameters, reader io.ReadSeekCloser, retries ...RetryStrategy, ) (UploadImageResult, error) // StartUploadToDisk uploads a disk image to an existing disk. The actual upload takes place in the background // and can be tracked using the returned UploadImageProgress object. Parameters are as follows: // // - diskID: ID of the disk to upload to. // - reader This is the source of the image data. // - retries: A set of optional retry options. // // You can wait for the upload to complete using the Done() method: // // progress, err := cli.StartUploadToDisk(...) // if err != nil { // //... // } // <-progress.Done() // // After the upload is complete you can check the Err() method if it completed successfully: // // if err := progress.Err(); err != nil { // //... // } StartUploadToDisk( diskID DiskID, size uint64, reader io.ReadSeekCloser, retries ...RetryStrategy, ) (UploadImageProgress, error) // UploadToDisk runs StartUploadDisk and then waits for the upload to complete. It returns an error if the upload // failed despite retries. // // Parameters are as follows: // // - diskID: ID of the disk to upload to. // - size: size of the file on disk. // - reader: this is the source of the image data. The format is automatically determined from the file being // uploaded. The reader must support seeking and close. // - retries: a set of optional retry options. UploadToDisk( diskID DiskID, size uint64, reader io.ReadSeekCloser, retries ...RetryStrategy, ) error // StartImageDownload starts the download of the image file of a specific disk. // The caller can then wait for the initialization using the Initialized() call: // // <-download.Initialized() // // Alternatively, the downloader can use the Read() function to wait for the download to become available // and then read immediately. // // The caller MUST close the returned reader, otherwise the disk will remain locked in the oVirt engine. // // Deprecated: please use StartDownloadDisk instead. StartImageDownload( diskID DiskID, format ImageFormat, retries ...RetryStrategy, ) (ImageDownload, error) // StartDownloadDisk starts the download of the image file of a specific disk. // The caller can then wait for the initialization using the Initialized() call: // // <-download.Initialized() // // Alternatively, the downloader can use the Read() function to wait for the download to become available // and then read immediately. // // The caller MUST close the returned reader, otherwise the disk will remain locked in the oVirt engine. StartDownloadDisk( diskID DiskID, format ImageFormat, retries ...RetryStrategy, ) (ImageDownload, error) // DownloadImage runs StartDownloadDisk, then waits for the download to be ready before returning the reader. // The caller MUST close the ImageDownloadReader in order to properly unlock the disk in the oVirt engine. // // Deprecated: please use DownloadDisk instead. DownloadImage( diskID DiskID, format ImageFormat, retries ...RetryStrategy, ) (ImageDownloadReader, error) // DownloadDisk runs StartDownloadDisk, then waits for the download to be ready before returning the reader. // The caller MUST close the ImageDownloadReader in order to properly unlock the disk in the oVirt engine. DownloadDisk( diskID DiskID, format ImageFormat, retries ...RetryStrategy, ) (ImageDownloadReader, error) // StartCreateDisk starts creating an empty disk with the specified parameters and returns a DiskCreation object, // which can be queried for completion. Optional parameters can be created using CreateDiskParams(). StartCreateDisk( storageDomainID StorageDomainID, format ImageFormat, size uint64, params CreateDiskOptionalParameters, retries ...RetryStrategy, ) (DiskCreation, error) // CreateDisk is a shorthand for calling StartCreateDisk, and then waiting for the disk creation to complete. // Optional parameters can be created using CreateDiskParams(). // // Caution! The CreateDisk method may return both an error and a disk that has been created, but has not reached // the ready state. Since the disk is almost certainly in a locked state, this may mean that there is a disk left // behind. CreateDisk( storageDomainID StorageDomainID, format ImageFormat, size uint64, params CreateDiskOptionalParameters, retries ...RetryStrategy, ) (Disk, error) // StartUpdateDisk sends the disk update request to the oVirt API and returns a DiskUpdate // object, which can be used to wait for the update to complete. Use UpdateDiskParams to // obtain a builder for the parameters structure. StartUpdateDisk( id DiskID, params UpdateDiskParameters, retries ...RetryStrategy, ) (DiskUpdate, error) // UpdateDisk updates the specified disk with the specified parameters. Use UpdateDiskParams to // obtain a builder for the parameters structure. UpdateDisk( id DiskID, params UpdateDiskParameters, retries ...RetryStrategy, ) (Disk, error) // ListDisks lists all disks. ListDisks(retries ...RetryStrategy) ([]Disk, error) // GetDisk fetches a disk with a specific ID from the oVirt Engine. GetDisk(diskID DiskID, retries ...RetryStrategy) (Disk, error) // ListDisksByAlias fetches a disks with a specific name from the oVirt Engine. ListDisksByAlias(alias string, retries ...RetryStrategy) ([]Disk, error) // RemoveDisk removes a disk with a specific ID. RemoveDisk(diskID DiskID, retries ...RetryStrategy) error // WaitForDiskOK waits for a disk to be in OK status WaitForDiskOK(diskID DiskID, retries ...RetryStrategy) (Disk, error) }
DiskClient is the client interface part that deals with disks.
Example (UploadImage) ¶
This example demonstrates the simplest way to upload an image without special timeout handling. The call still times out after a built-in timeout.
package main import ( "fmt" "os" ovirtclient "github.com/ovirt/go-ovirt-client" ovirtclientlog "github.com/ovirt/go-ovirt-client-log/v3" ) func main() { // Open image file to upload fh, err := os.Open("/path/to/test.img") if err != nil { panic(fmt.Errorf("failed to open image file (%w)", err)) } defer func() { if err = fh.Close(); err != nil { panic(err) } }() // Get the file size stat, err := fh.Stat() if err != nil { panic(fmt.Errorf("failed to stat image file (%w)", err)) } // Obtain oVirt client. Alternatively, you can call ovirtclient.New() to do this directly. helper, err := ovirtclient.NewLiveTestHelperFromEnv(ovirtclientlog.NewNOOPLogger()) if err != nil { panic(fmt.Errorf("failed to create live test helper (%w)", err)) } client := helper.GetClient() imageName := fmt.Sprintf("client_test_%s", helper.GenerateRandomID(5)) // Upload image and wait for result. uploadResult, err := client.UploadToNewDisk( helper.GetStorageDomainID(), ovirtclient.ImageFormatRaw, uint64(stat.Size()), ovirtclient.CreateDiskParams().MustWithAlias(imageName).MustWithSparse(true), fh, ) if err != nil { panic(fmt.Errorf("failed to upload image (%w)", err)) } fmt.Printf("Uploaded as disk %s\n", uploadResult.Disk().ID()) }
Output:
Example (UploadImageWithCancel) ¶
This example demonstrates how to upload a VM image into a disk while being able to cancel the process manually.
package main import ( "context" "fmt" "os" "time" ovirtclient "github.com/ovirt/go-ovirt-client" ovirtclientlog "github.com/ovirt/go-ovirt-client-log/v3" ) func main() { // Open image file to upload fh, err := os.Open("/path/to/test.img") if err != nil { panic(fmt.Errorf("failed to open image file (%w)", err)) } defer func() { if err = fh.Close(); err != nil { panic(err) } }() // Get the file size stat, err := fh.Stat() if err != nil { panic(fmt.Errorf("failed to stat image file (%w)", err)) } // Obtain oVirt client. Alternatively, you can call ovirtclient.New() to do this directly. helper, err := ovirtclient.NewLiveTestHelperFromEnv(ovirtclientlog.NewNOOPLogger()) if err != nil { panic(fmt.Errorf("failed to create live test helper (%w)", err)) } client := helper.GetClient() imageName := fmt.Sprintf("client_test_%s", helper.GenerateRandomID(5)) // Set up context so we can cancel the upload ctx, cancel := context.WithCancel(context.Background()) defer cancel() uploadResult, err := client.StartUploadToNewDisk( helper.GetStorageDomainID(), ovirtclient.ImageFormatRaw, uint64(stat.Size()), ovirtclient.CreateDiskParams().MustWithSparse(true).MustWithAlias(imageName), fh, ovirtclient.ContextStrategy(ctx), ) if err != nil { panic(fmt.Errorf("failed to upload image (%w)", err)) } // Wait for image upload to initialize. select { case <-time.After(10 * time.Minute): // Cancel upload cancel() // Wait for it to actually finish. <-uploadResult.Done() case <-uploadResult.Done(): } if err := uploadResult.Err(); err != nil { panic(fmt.Errorf("failed to upload image (%w)", err)) } fmt.Printf("Uploaded as disk %s\n", uploadResult.Disk().ID()) }
Output:
type DiskCreation ¶ added in v0.7.0
type DiskCreation interface { // Disk returns the disk that has been created, even if it is not yet ready. Disk() Disk // Wait waits until the disk creation is complete and returns when it is done. It returns the created disk and // an error if one happened. Wait(retries ...RetryStrategy) (Disk, error) }
DiskCreation is a process object that lets you query the status of the disk creation.
type DiskData ¶ added in v0.7.0
type DiskData interface { // ID is the unique ID for this disk. ID() DiskID // Alias is the name for this disk set by the user. Alias() string // ProvisionedSize is the size visible to the virtual machine. ProvisionedSize() uint64 // TotalSize is the size of the image file. // This value can be zero in some cases, for example when the disk upload wasn't properly finalized. TotalSize() uint64 // Format is the format of the image. Format() ImageFormat // StorageDomainIDs returns a list of storage domains this disk is present on. This will typically be a single // disk, but may have multiple disk when the disk has been copied over to other storage domains. The disk is always // present on at least one disk, so this list will never be empty. StorageDomainIDs() []StorageDomainID // Status returns the status the disk is in. Status() DiskStatus // Sparse indicates sparse provisioning on the disk. Sparse() bool }
DiskData is the core of a Disk, only exposing data functions, but not the client functions. This can be used for cases where not a full Disk is required, but only the data functionality.
type DiskInterface ¶ added in v0.7.0
type DiskInterface string
DiskInterface describes the means by which a disk will appear to the VM.
const ( // DiskInterfaceIDE is a legacy controller device. Works with almost all guest operating systems, so it is good for // compatibility. Performance is lower than with the other alternatives. DiskInterfaceIDE DiskInterface = "ide" // DiskInterfaceSATA is a SATA controller device. DiskInterfaceSATA DiskInterface = "sata" // DiskInterfacesPAPRvSCSI is a para-virtualized device supported by the IBM pSeries family of machines, using the // SCSI protocol. DiskInterfacesPAPRvSCSI DiskInterface = "spapr_vscsi" // DiskInterfaceVirtIO is a virtualization interface where just the guest's device driver knows it is running in a // virtual environment. Enables guests to get high performance disk operations. DiskInterfaceVirtIO DiskInterface = "virtio" // DiskInterfaceVirtIOSCSI is a para-virtualized SCSI controller device. Fast interface with the guest via direct // physical storage device address, using the SCSI protocol. DiskInterfaceVirtIOSCSI DiskInterface = "virtio_scsi" )
func (DiskInterface) Validate ¶ added in v0.7.0
func (d DiskInterface) Validate() error
Validate checks if the DiskInterface actually has a valid value.
type DiskInterfaceList ¶ added in v0.7.0
type DiskInterfaceList []DiskInterface
DiskInterfaceList is a list of DiskInterface.
func DiskInterfaceValues ¶ added in v0.7.0
func DiskInterfaceValues() DiskInterfaceList
DiskInterfaceValues returns all possible DiskInterface values.
func (DiskInterfaceList) Strings ¶ added in v0.7.0
func (l DiskInterfaceList) Strings() []string
Strings creates a string list of the values.
type DiskStatus ¶ added in v0.5.0
type DiskStatus string
DiskStatus shows the status of a disk. Certain operations lock a disk, which is important because the disk can then not be changed.
const ( // DiskStatusOK represents a disk status that operations can be performed on. DiskStatusOK DiskStatus = "ok" // DiskStatusLocked represents a disk status where no operations can be performed on the disk. DiskStatusLocked DiskStatus = "locked" // DiskStatusIllegal indicates that the disk cannot be accessed by the virtual machine, and the user needs // to take action to resolve the issue. DiskStatusIllegal DiskStatus = "illegal" )
type DiskStatusList ¶ added in v0.7.0
type DiskStatusList []DiskStatus
DiskStatusList is a list of DiskStatus values.
func DiskStatusValues ¶ added in v0.7.0
func DiskStatusValues() DiskStatusList
DiskStatusValues returns all possible values for DiskStatus.
func (DiskStatusList) Strings ¶ added in v0.7.0
func (l DiskStatusList) Strings() []string
Strings returns a list of strings.
type DiskUpdate ¶ added in v0.7.0
type DiskUpdate interface { // Disk returns the disk as it was during the last update call. Disk() Disk // Wait waits until the disk update is complete and returns when it is done. It returns the created disk and // an error if one happened. Wait(retries ...RetryStrategy) (Disk, error) }
DiskUpdate is an object to monitor the progress of an update.
type EngineError ¶ added in v0.5.0
type EngineError interface { error // Message returns the error message without the error code. Message() string // String returns the string representation for this error. String() string // HasCode returns true if the current error, or any preceding error has the specified error code. HasCode(ErrorCode) bool // Code returns an error code for the failure. Code() ErrorCode // Unwrap returns the underlying error Unwrap() error // CanRecover indicates that this error can be automatically recovered with the use of the proper recovery strategy // passed to the retry function. CanRecover() bool // CanAutoRetry returns false if an automatic retry should not be attempted. CanAutoRetry() bool }
EngineError is an error representation for errors received while interacting with the oVirt engine.
Usage:
if err != nil { var realErr ovirtclient.EngineError if errors.As(err, &realErr) { // deal with EngineError } else { // deal with other errors } }
type ErrorCode ¶ added in v0.5.0
type ErrorCode string
ErrorCode is a code that can be used to identify error types. These errors are identified on a best effort basis from the underlying oVirt connection.
const EAccessDenied ErrorCode = "access_denied"
EAccessDenied signals that the provided credentials for the oVirt engine were incorrect.
const EBadArgument ErrorCode = "bad_argument"
EBadArgument indicates that an input parameter was incorrect.
const EBug ErrorCode = "bug"
EBug signals an error that should never happen. Please report this.
const ECannotRunVM ErrorCode = "cannot_run_vm"
ECannotRunVM indicates an error with the VM configuration which prevents it from being run.
const EConflict ErrorCode = "conflict"
EConflict indicates an error where you tried to create or update a resource which is already in use in a different, conflicting way. For example, you tried to attach a disk that is already attached.
const EConnection ErrorCode = "connection"
EConnection signals a problem with the connection.
const EDiskLocked ErrorCode = "disk_locked"
EDiskLocked indicates that the disk in question is locked.
const EFieldMissing ErrorCode = "field_missing"
EFieldMissing indicates that the oVirt API did not return a specific field. This is most likely a bug, please report it.
const EFileReadFailed ErrorCode = "file_read_failed"
EFileReadFailed indicates that reading a local file failed.
const EHotPlugFailed ErrorCode = "hot_plug_failed"
EHotPlugFailed indicates that a disk could not be hot plugged.
const EInvalidGrant ErrorCode = "invalid_grant"
EInvalidGrant is an error returned from the oVirt Engine when the SSO token expired. In this case we must reconnect and retry the API call.
const ELocalIO ErrorCode = "local_io_error"
ELocalIO indicates an input/output error on the client side. For example, a disk could not be read.
const EMultipleResults ErrorCode = "multiple_results"
EMultipleResults indicates that multiple items were found where only one was expected.
const ENotAnOVirtEngine ErrorCode = "not_ovirt_engine"
ENotAnOVirtEngine signals that the server did not respond with a proper oVirt response.
const ENotFound ErrorCode = "not_found"
ENotFound signals that the resource requested was not found.
const EPending ErrorCode = "pending"
EPending signals that the client library is still waiting for an action to be completed.
const EPermanentHTTPError ErrorCode = "permanent_http_error"
EPermanentHTTPError indicates a HTTP error code that should not be retried.
const ERelatedOperationInProgress ErrorCode = "related_operation_in_progress"
ERelatedOperationInProgress means that the engine is busy working on something else on the same resource.
const ETLSError ErrorCode = "tls_error"
ETLSError signals that the provided CA certificate did not match the server that was attempted to connect.
const ETimeout ErrorCode = "timeout"
ETimeout signals that the client library has timed out waiting for an action to be completed.
const EUnexpectedDiskStatus ErrorCode = "unexpected_disk_status"
EUnexpectedDiskStatus indicates that a disk was in a status that was not expected in this state.
const EUnexpectedImageTransferPhase ErrorCode = "unexpected_image_transfer_phase"
EUnexpectedImageTransferPhase indicates that an image transfer was in an unexpected phase.
const EUnidentified ErrorCode = "generic_error"
EUnidentified is an unidentified oVirt error. When passed to the wrap() function this error code will cause the wrap function to look at the wrapped error and either fetch the error code from that error, or identify the error from its text.
If you see this error type in a log please report this error so we can add an error code for it.
const EUnsupported ErrorCode = "unsupported"
EUnsupported signals that an action is not supported. This can indicate a disk format or a combination of parameters.
const EVMLocked ErrorCode = "vm_locked"
EVMLocked indicates that the virtual machine in question is locked.
func (ErrorCode) CanAutoRetry ¶ added in v0.5.0
CanAutoRetry returns false if the given error code is permanent and an automatic retry should not be attempted.
func (ErrorCode) CanRecover ¶ added in v1.0.0
CanRecover returns true if there is a way to automatically recoverFailure from this error. For the actual recovery an appropriate recovery strategy must be passed to the retry function.
type ExtraSettings ¶ added in v0.6.0
type ExtraSettings interface { // ExtraHeaders adds headers to the request. ExtraHeaders() map[string]string // Compression enables GZIP or DEFLATE compression on HTTP queries Compression() bool // Proxy returns the proxy server to use for connecting the oVirt engine. If none is set, the system settings are // used. If an empty string is passed, no proxy is used. Proxy() *string }
ExtraSettings are the optional settings for the oVirt connection.
For future development, an interface named ExtraSettingsV2, V3, etc. will be added that incorporate this interface. This is done for backwards compatibility.
type ExtraSettingsBuilder ¶ added in v1.0.0
type ExtraSettingsBuilder interface { ExtraSettings // WithExtraHeaders adds extra headers to send along with each request. WithExtraHeaders(map[string]string) ExtraSettingsBuilder // WithCompression enables compression on HTTP requests. WithCompression() ExtraSettingsBuilder // WithProxy explicitly sets a proxy server to use for requests. WithProxy(string) ExtraSettingsBuilder }
ExtraSettingsBuilder is a buildable version of ExtraSettings.
func NewExtraSettings ¶ added in v1.0.0
func NewExtraSettings() ExtraSettingsBuilder
NewExtraSettings creates a builder for ExtraSettings.
type Feature ¶ added in v0.9.0
type Feature string
Feature is a specialized type for feature flags. These can be checked for support by using SupportsFeature in FeatureClient.
const ( // FeatureAutoPinning is a feature flag for autopinning support in the oVirt Engine supported since 4.4.5. FeatureAutoPinning Feature = "autopinning" // FeaturePlacementPolicy is a feature flag to indicate placement policy support in the oVirt Engine. FeaturePlacementPolicy Feature = "placement_policy" )
type FeatureClient ¶ added in v0.9.0
type FeatureClient interface { // SupportsFeature checks the features supported by the oVirt Engine. SupportsFeature(feature Feature, retries ...RetryStrategy) (bool, error) }
FeatureClient provides the functions to determine the capabilities of the oVirt Engine.
type FileStorageDomainTypeList ¶ added in v0.7.0
type FileStorageDomainTypeList []StorageDomainType
FileStorageDomainTypeList is a list of possible StorageDomainTypes which are considered file storage.
func FileStorageDomainTypeValues ¶ added in v0.7.0
func FileStorageDomainTypeValues() FileStorageDomainTypeList
FileStorageDomainTypeValues returns all the StorageDomainTypes values which are considered file storage.
type GraphicsConsoleClient ¶ added in v1.0.0
type GraphicsConsoleClient interface { ListVMGraphicsConsoles(vmID VMID, retries ...RetryStrategy) ([]VMGraphicsConsole, error) RemoveVMGraphicsConsole(vmID VMID, graphicsConsoleID VMGraphicsConsoleID, retries ...RetryStrategy) error }
GraphicsConsoleClient lists the methods to access and manipulate graphics consoles on VMs.
type Host ¶
type Host interface { HostData }
Host is the representation of a host returned from the oVirt Engine API. Hosts, also known as hypervisors, are the physical servers on which virtual machines run. Full virtualization is provided by using a loadable Linux kernel module called Kernel-based Virtual Machine (KVM).
See https://www.ovirt.org/documentation/administration_guide/#chap-Hosts for details.
type HostClient ¶
type HostClient interface { ListHosts(retries ...RetryStrategy) ([]Host, error) GetHost(id HostID, retries ...RetryStrategy) (Host, error) }
HostClient contains the API portion that deals with hosts.
type HostData ¶ added in v0.7.0
type HostData interface { // ID returns the identifier of the host in question. ID() HostID // ClusterID returns the ID of the cluster this host belongs to. ClusterID() ClusterID // Status returns the status of this host. Status() HostStatus }
HostData is the core of Host, providing only data access functions.
type HostStatus ¶
type HostStatus string
HostStatus represents the complex states an oVirt host can be in.
const ( // HostStatusConnecting indicates that the engine cannot currently communicate with the host, so it // is trying to connect it before fencing it. HostStatusConnecting HostStatus = "connecting" // HostStatusDown indicates that the host in question is down. HostStatusDown HostStatus = "down" // HostStatusError indicates that the specified host failed to perform correctly. For example, it // failed to run a virtual machine several times without success. HostStatusError HostStatus = "error" // HostStatusInitializing indicates that the host is shortly before being in HostStatusUp. HostStatusInitializing HostStatus = "initializing" // HostStatusInstallFailed indicates that setting up the host failed. The administrator needs to look // in the log to discover the reason for failure. HostStatusInstallFailed HostStatus = "install_failed" // HostStatusInstalling indicates that the host is currently being set up. HostStatusInstalling HostStatus = "installing" // HostStatusInstallingOS indicates that the operating system is being isntalled using Satellite/Foreman. HostStatusInstallingOS HostStatus = "installing_os" // HostStatusKDumping indicates that the host kernel has crashed and is currently dumping memory. HostStatusKDumping HostStatus = "kdumping" // HostStatusMaintenance indicates that the host is currently under maintenance and can currently not run // virtual machines. HostStatusMaintenance HostStatus = "maintenance" // HostStatusNonOperational indicates that the host is currently not able to perform due to various reasons, // such as a storage not being connected, not supporting a mandatory network, etc. HostStatusNonOperational HostStatus = "non_operational" // HostStatusNonResponsive indicates that the host is not responding to the engine. HostStatusNonResponsive HostStatus = "non_responsive" // HostStatusPendingApproval a deprecated status that a vintage ovirt-node/RHV-H hos is pending // administrator approval. This status is no longer relevant as Vintage Nodes are no longer supported. HostStatusPendingApproval HostStatus = "pending_approval" // HostStatusPreparingForMaintenance indicates that the host is currently being drained of all virtual machines // via live migration to other hosts. Once the migration is complete the host will move into HostStatusMaintenance. HostStatusPreparingForMaintenance HostStatus = "preparing_for_maintenance" // HostStatusReboot indicates that the host is currently undergoing a reboot. HostStatusReboot HostStatus = "reboot" // HostStatusUnassigned indicates that the host is not yet assigned and is in the activation process. HostStatusUnassigned HostStatus = "unassigned" // HostStatusUp indicates that the host is operating normally. HostStatusUp HostStatus = "up" )
type HostStatusList ¶ added in v0.7.0
type HostStatusList []HostStatus
HostStatusList is a list of HostStatus.
func HostStatusValues ¶ added in v0.7.0
func HostStatusValues() HostStatusList
HostStatusValues returns all possible HostStatus values.
func (HostStatusList) Strings ¶ added in v0.7.0
func (l HostStatusList) Strings() []string
Strings creates a string list of the values.
type ImageDownload ¶ added in v0.5.0
type ImageDownload interface { ImageDownloadReader // Err returns the error that happened during initializing the download, or the last error reading from the // image server. Err() error // Initialized returns a channel that will be closed when the initialization is complete. This can be either // in an errored state (check Err()) or when the image is ready. Initialized() <-chan struct{} }
ImageDownload represents an image download in progress. The caller MUST close the image download when it is finished otherwise the disk will not be unlocked.
type ImageDownloadReader ¶ added in v0.5.0
type ImageDownloadReader interface { io.Reader // Read reads the specified bytes from the disk image. This call will block if // the image is not yet ready for download. Read(p []byte) (n int, err error) // Close closes the image download and unlocks the disk. Close() error // BytesRead returns the number of bytes read so far. This can be used to // provide a progress bar. BytesRead() uint64 // Size returns the size of the disk image in bytes. This is ONLY available after the initialization is complete and // MAY return 0 before. Size() uint64 }
ImageDownloadReader is a special reader for reading image downloads. On the first Read call it waits until the image download is ready and then returns the desired bytes. It also tracks how many bytes are read for an async display of a progress bar.
type ImageFormat ¶
type ImageFormat string
ImageFormat is a constant for representing the format that images can be in. This is relevant for both image uploads and image downloads, as the oVirt engine has the capability of converting between these formats.
Note: the mocking facility cannot convert between the formats due to the complexity of the QCOW2 format. It is recommended to write tests only using the raw format as comparing QCOW2 files is complex.
const ( // ImageFormatCow is an image conforming to the QCOW2 image format. This image format can use // compression, supports snapshots, and other features. // See https://github.com/qemu/qemu/blob/master/docs/interop/qcow2.txt for details. ImageFormatCow ImageFormat = "cow" // ImageFormatRaw is not actually a format, it only contains the raw bytes on the block device. ImageFormatRaw ImageFormat = "raw" )
func (ImageFormat) Validate ¶ added in v0.7.0
func (f ImageFormat) Validate() error
Validate returns an error if the image format doesn't have a valid value.
type ImageFormatList ¶ added in v0.7.0
type ImageFormatList []ImageFormat
ImageFormatList is a list of ImageFormat values.
func ImageFormatValues ¶ added in v0.7.0
func ImageFormatValues() ImageFormatList
ImageFormatValues returns all possible ImageFormat values.
func (ImageFormatList) Strings ¶ added in v0.7.0
func (l ImageFormatList) Strings() []string
Strings creates a string list of the values.
type Initialization ¶ added in v0.9.0
Initialization defines to the virtual machine’s initialization configuration.
func NewInitialization ¶ added in v0.9.0
func NewInitialization(customScript, hostname string) Initialization
NewInitialization creates a new Initialization from the specified parameters.
type InstanceType ¶ added in v1.0.0
type InstanceType interface { InstanceTypeData }
InstanceType is a data structure that contains preconfigured instance parameters.
type InstanceTypeClient ¶ added in v1.0.0
type InstanceTypeClient interface { GetInstanceType(id InstanceTypeID, retries ...RetryStrategy) (InstanceType, error) ListInstanceTypes(retries ...RetryStrategy) ([]InstanceType, error) }
InstanceTypeClient lists the methods for working with instance types.
type InstanceTypeData ¶ added in v1.0.0
type InstanceTypeData interface { ID() InstanceTypeID Name() string }
InstanceTypeData is the data segment of the InstanceType type.
type InstanceTypeID ¶ added in v1.0.0
type InstanceTypeID string
InstanceTypeID is a type alias for instance type IDs.
type Logger ¶
type Logger interface { ovirtclientlog.Logger }
Logger is a thin wrapper around ovirtclientlog.Logger for convenience.
type MemoryPolicy ¶ added in v0.9.0
type MemoryPolicy interface { // Guaranteed returns the number of guaranteed bytes to the VM. Guaranteed() *int64 // Max returns the maximum amount of memory given to the VM. Max() *int64 // Ballooning returns true if the VM can give back the memory it is not using to the host OS. Ballooning() bool }
MemoryPolicy is the memory policy set on the VM.
type MemoryPolicyParameters ¶ added in v0.9.0
MemoryPolicyParameters contain the parameters for the memory policy setting on the VM.
type MockClient ¶
type MockClient interface { Client // GenerateUUID generates a UUID for testing purposes. GenerateUUID() string }
MockClient provides in-memory client functions, and additionally provides the ability to inject information.
func NewMock ¶
func NewMock() MockClient
NewMock creates a new in-memory mock client. This client can be used as a testing facility for higher level code.
func NewMockWithLogger ¶ added in v0.9.0
func NewMockWithLogger(logger Logger) MockClient
NewMockWithLogger is identical to NewMock, but accepts a logger.
type NIC ¶ added in v0.6.0
type NIC interface { NICData // GetVM fetches an up to date copy of the virtual machine this NIC is attached to. This involves an API call and // may be slow. GetVM(retries ...RetryStrategy) (VM, error) // GetVNICProfile retrieves the VNIC profile associated with this NIC. This involves an API call and may be slow. GetVNICProfile(retries ...RetryStrategy) (VNICProfile, error) // Update updates the NIC with the specified parameters. It returns the updated NIC as a response. You can use // UpdateNICParams() to obtain a buildable parameter structure. Update(params UpdateNICParameters, retries ...RetryStrategy) (NIC, error) // Remove removes the current network interface. This involves an API call and may be slow. Remove(retries ...RetryStrategy) error }
NIC represents a network interface.
type NICClient ¶ added in v0.6.0
type NICClient interface { // CreateNIC adds a new NIC to a VM specified in vmid. CreateNIC( vmid VMID, vnicProfileID VNICProfileID, name string, optional OptionalNICParameters, retries ...RetryStrategy, ) (NIC, error) // UpdateNIC allows updating the NIC. UpdateNIC( vmid VMID, nicID NICID, params UpdateNICParameters, retries ...RetryStrategy, ) (NIC, error) // GetNIC returns one specific NIC with the ID specified in id, attached to a VM with the ID specified in vmid. GetNIC(vmid VMID, id NICID, retries ...RetryStrategy) (NIC, error) // ListNICs lists all NICs attached to the VM specified in vmid. ListNICs(vmid VMID, retries ...RetryStrategy) ([]NIC, error) // RemoveNIC removes the network interface specified. RemoveNIC(vmid VMID, id NICID, retries ...RetryStrategy) error }
NICClient defines the methods related to dealing with network interfaces.
type NICData ¶ added in v0.7.0
type NICData interface { // ID is the identifier for this network interface. ID() NICID // Name is the user-given name of the network interface. Name() string // VMID is the identified of the VM this NIC is attached to. May be nil if the NIC is not attached. VMID() VMID // VNICProfileID returns the ID of the VNIC profile in use by the NIC. VNICProfileID() VNICProfileID }
NICData is the core of NIC which only provides data-access functions.
type Network ¶ added in v0.6.0
type Network interface { NetworkData // Datacenter fetches the datacenter associated with this network. This is a network call and may be slow. Datacenter(retries ...RetryStrategy) (Datacenter, error) }
Network is the interface defining the fields for networks.
type NetworkClient ¶ added in v0.6.0
type NetworkClient interface { // GetNetwork returns a single network based on its ID. GetNetwork(id NetworkID, retries ...RetryStrategy) (Network, error) // ListNetworks returns all networks on the oVirt engine. ListNetworks(retries ...RetryStrategy) ([]Network, error) }
NetworkClient describes the functions related to oVirt networks.
See https://www.ovirt.org/documentation/administration_guide/#chap-Logical_Networks for details.
type NetworkData ¶ added in v0.7.0
type NetworkData interface { // ID returns the auto-generated identifier for this network. ID() NetworkID // Name returns the user-give nname for this network. Name() string // DatacenterID is the identifier of the datacenter object. DatacenterID() DatacenterID }
NetworkData is the core of Network, providing only the data access functions, but not the client functions.
type OptionalNICParameters ¶ added in v0.7.0
type OptionalNICParameters interface{}
OptionalNICParameters is an interface that declares the source of optional parameters for NIC creation.
type OptionalTemplateCreateParameters ¶ added in v0.9.0
type OptionalTemplateCreateParameters interface {
Description() *string
}
OptionalTemplateCreateParameters contains the optional parameters for creating a template.
type OptionalVMDiskParameters ¶ added in v0.9.0
type OptionalVMDiskParameters interface { // DiskID returns the identifier of the disk that is being changed. DiskID() DiskID // Sparse sets the sparse parameter if set. Note, that Sparse is only supported in oVirt on block devices with QCOW2 // images. On NFS you MUST use raw disks to use sparse. Sparse() *bool // Format returns the image format to be used for the specified disk. Format() *ImageFormat // StorageDomainID returns the optional storage domain ID to use for this disk. StorageDomainID() *StorageDomainID }
OptionalVMDiskParameters describes the disk parameters that can be given to VM creation. These manipulate the disks inherited from the template.
type OptionalVMParameters ¶ added in v0.6.0
type OptionalVMParameters interface { // Comment returns the comment for the VM. Comment() string // CPU contains the CPU topology, if any. CPU() VMCPUParams // HugePages returns the optional value for the HugePages setting for VMs. HugePages() *VMHugePages // Initialization defines the virtual machine’s initialization configuration. Initialization() Initialization // Clone should return true if the VM should be cloned from the template instead of linking it. This means that the // template can be removed while the VM still exists. Clone() *bool // Memory returns the VM memory in Bytes. Memory() *int64 // MemoryPolicy returns the memory policy configuration for this VM, if any. MemoryPolicy() *MemoryPolicyParameters // Disks returns a list of disks that are to be changed from the template. Disks() []OptionalVMDiskParameters // PlacementPolicy returns a VM placement policy to apply, if any. PlacementPolicy() *VMPlacementPolicyParameters // InstanceTypeID returns the instance type ID if set. InstanceTypeID() *InstanceTypeID // VMType is the type of the VM created. VMType() *VMType // OS returns the operating system parameters, and true if the OS parameter has been set. OS() (VMOSParameters, bool) // SerialConsole returns if a serial console should be created or not. SerialConsole() *bool }
OptionalVMParameters are a list of parameters that can be, but must not necessarily be added on VM creation. This interface is expected to be extended in the future.
type OptionalVNICProfileParameters ¶ added in v0.7.0
type OptionalVNICProfileParameters interface{}
OptionalVNICProfileParameters is a set of parameters for creating VNICProfiles that are optional.
type RetryInstance ¶ added in v0.5.0
type RetryInstance interface { // Continue returns an error if no more tries should be attempted. The error will be returned directly from the // retry function. The passed action parameters can be used to create a meaningful error message. Continue(err error, action string) error // Recover gives the strategy a chance to recoverFailure from a failure. This function is called if an execution errored // before the next cycle happens. The recovery method should return nil if the recovery was successful, and an // error otherwise. It may return the same error it received to indicate that it could not do anything with the // error. Recover(err error) error // Wait returns a channel that is closed when the wait time expires. The channel can have any content, so it is // provided as an interface{}. This function may return nil if it doesn't provide a wait time. Wait(err error) interface{} // OnWaitExpired is a hook that gives the strategy the option to return an error if its wait has expired. It will // only be called if it is the first to reach its wait. If no error is returned the loop is continued. The passed // action names can be incorporated into an error message. OnWaitExpired(err error, action string) error }
RetryInstance is an instance created by the RetryStrategy for a single use. It may have internal state and should not be reused.
type RetryStrategy ¶ added in v0.5.0
type RetryStrategy interface { // Get returns an actual copy of the retry strategy. This can be used to initialize individual timers for // separate API calls within a larger call structure. Get() RetryInstance // CanClassifyErrors indicates if the strategy can determine if an error is retryable. At least one strategy with // this capability needs to be passed. CanClassifyErrors() bool // CanWait indicates if the retry strategy can wait in a loop. At least one strategy with this capability // needs to be passed. CanWait() bool // CanTimeout indicates that the retry strategy can properly abort a loop. At least one retry strategy with // this capability needs to be passed. CanTimeout() bool // CanRecover indicates that the retry strategy can recoverFailure from a failure. In this case the Recover method will be // called on errors. CanRecover() bool }
RetryStrategy is a function that creates a new copy of a RetryInstance. It is important because each RetryInstance may have an internal state, so reusing a RetryInstance won't work. RetryStrategy copies can be safely passed around between functions and reused multiple times.
func AutoRetry ¶ added in v0.5.0
func AutoRetry() RetryStrategy
AutoRetry retries an action only if it doesn't return a non-retryable error.
func CallTimeout ¶ added in v0.5.0
func CallTimeout(timeout time.Duration) RetryStrategy
CallTimeout is a strategy that will timeout individual API call retries.
func ContextStrategy ¶ added in v0.5.0
func ContextStrategy(ctx context.Context) RetryStrategy
ContextStrategy provides a timeout based on a context in the ctx parameter. If the context is canceled the retry loop is aborted.
func ExponentialBackoff ¶ added in v0.5.0
func ExponentialBackoff(factor uint8) RetryStrategy
ExponentialBackoff is a retry strategy that increases the wait time after each call by the specified factor.
func MaxTries ¶ added in v0.5.0
func MaxTries(tries uint16) RetryStrategy
MaxTries is a strategy that will timeout individual API calls based on a maximum number of retries. The total number of API calls can be higher in case of a complex functions that involve multiple API calls.
func ReconnectStrategy ¶ added in v1.0.0
func ReconnectStrategy(client Client) RetryStrategy
ReconnectStrategy triggers the client to reconnect if an EInvalidGrant error is encountered.
func Timeout ¶ added in v0.5.0
func Timeout(timeout time.Duration) RetryStrategy
Timeout is a strategy that will time out complex calls based on a timeout from the time the strategy factory was created. This is contrast to CallTimeout, which will evaluate timeouts for each individual API call.
type StorageDomain ¶
type StorageDomain interface { StorageDomainData }
StorageDomain represents a storage domain returned from the oVirt Engine API.
type StorageDomainClient ¶
type StorageDomainClient interface { // ListStorageDomains lists all storage domains. ListStorageDomains(retries ...RetryStrategy) ([]StorageDomain, error) // GetStorageDomain returns a single storage domain, or an error if the storage domain could not be found. GetStorageDomain(id StorageDomainID, retries ...RetryStrategy) (StorageDomain, error) // GetDiskFromStorageDomain returns a single disk from a specific storage domain, or an error if no disk can be found. GetDiskFromStorageDomain(id StorageDomainID, diskID DiskID, retries ...RetryStrategy) (result Disk, err error) // RemoveDiskFromStorageDomain removes a disk from a specific storage domain, but leaves the disk on other storage // domains if any. If the disk is not present on any more storage domains, the entire disk will be removed. RemoveDiskFromStorageDomain(id StorageDomainID, diskID DiskID, retries ...RetryStrategy) error }
StorageDomainClient contains the portion of the goVirt API that deals with storage domains.
type StorageDomainData ¶ added in v0.7.0
type StorageDomainData interface { // ID is the unique identified for the storage system connected to oVirt. ID() StorageDomainID // Name is the user-given name for the storage domain. Name() string // Available returns the number of available bytes on the storage domain Available() uint64 // StorageType returns the type of the storage domain StorageType() StorageDomainType // Status returns the status of the storage domain. This status may be unknown if the storage domain is external. // Check ExternalStatus as well. Status() StorageDomainStatus // ExternalStatus returns the external status of a storage domain. ExternalStatus() StorageDomainExternalStatus }
StorageDomainData is the core of StorageDomain, providing only data access functions.
type StorageDomainExternalStatus ¶
type StorageDomainExternalStatus string
StorageDomainExternalStatus represents the status of an external storage domain. This status is updated externally.
Note: this is not well-defined as the oVirt model has only a very generic description. See https://github.com/oVirt/ovirt-engine-api-model/blob/9869596c298925538d510de5019195b488970738/src/main/java/types/ExternalStatus.java for details.
const ( // StorageDomainExternalStatusNA represents an external status that is not applicable. // Most likely, the status should be obtained from StorageDomainStatus, since the // storage domain in question is not an external storage. StorageDomainExternalStatusNA StorageDomainExternalStatus = "" // StorageDomainExternalStatusError indicates an error state. StorageDomainExternalStatusError StorageDomainExternalStatus = "error" // StorageDomainExternalStatusFailure indicates a failure state. StorageDomainExternalStatusFailure StorageDomainExternalStatus = "failure" // StorageDomainExternalStatusInfo indicates an OK status, but there is information available for the administrator // that might be relevant. StorageDomainExternalStatusInfo StorageDomainExternalStatus = "info" // StorageDomainExternalStatusOk indicates a working status. StorageDomainExternalStatusOk StorageDomainExternalStatus = "ok" // StorageDomainExternalStatusWarning indicates that the storage domain has warnings that may be relevant for the // administrator. StorageDomainExternalStatusWarning StorageDomainExternalStatus = "warning" )
type StorageDomainExternalStatusList ¶ added in v0.7.0
type StorageDomainExternalStatusList []StorageDomainExternalStatus
StorageDomainExternalStatusList is a list of StorageDomainStatus.
func StorageDomainExternalStatusValues ¶ added in v0.7.0
func StorageDomainExternalStatusValues() StorageDomainExternalStatusList
StorageDomainExternalStatusValues returns all possible StorageDomainExternalStatus values.
func (StorageDomainExternalStatusList) Strings ¶ added in v0.7.0
func (l StorageDomainExternalStatusList) Strings() []string
Strings creates a string list of the values.
type StorageDomainID ¶ added in v1.0.0
type StorageDomainID string
StorageDomainID is a specialized type for storage domain IDs.
type StorageDomainStatus ¶
type StorageDomainStatus string
StorageDomainStatus represents the status a domain can be in. Either this status field, or the StorageDomainExternalStatus must be set.
Note: this is not well documented due to missing source documentation. If you know something about these statuses please contribute here: https://github.com/oVirt/ovirt-engine-api-model/blob/master/src/main/java/types/StorageDomainStatus.java
const ( // StorageDomainStatusActivating indicates that the storage domain is currently activating and will soon be active. StorageDomainStatusActivating StorageDomainStatus = "activating" // StorageDomainStatusActive is the normal status for a storage domain when it's working. StorageDomainStatusActive StorageDomainStatus = "active" // StorageDomainStatusDetaching is the status when it is being disconnected. StorageDomainStatusDetaching StorageDomainStatus = "detaching" // StorageDomainStatusInactive is an undocumented status of the storage domain. StorageDomainStatusInactive StorageDomainStatus = "inactive" // StorageDomainStatusLocked is an undocumented status of the storage domain. StorageDomainStatusLocked StorageDomainStatus = "locked" // StorageDomainStatusMaintenance is an undocumented status of the storage domain. StorageDomainStatusMaintenance StorageDomainStatus = "maintenance" // StorageDomainStatusMixed is an undocumented status of the storage domain. StorageDomainStatusMixed StorageDomainStatus = "mixed" // StorageDomainStatusPreparingForMaintenance is an undocumented status of the storage domain. StorageDomainStatusPreparingForMaintenance StorageDomainStatus = "preparing_for_maintenance" // StorageDomainStatusUnattached is an undocumented status of the storage domain. StorageDomainStatusUnattached StorageDomainStatus = "unattached" // StorageDomainStatusUnknown is an undocumented status of the storage domain. StorageDomainStatusUnknown StorageDomainStatus = "unknown" // StorageDomainStatusNA indicates that the storage domain does not have a status. Please check the external status // instead. StorageDomainStatusNA StorageDomainStatus = "" )
func (StorageDomainStatus) Validate ¶ added in v0.7.0
func (s StorageDomainStatus) Validate() error
Validate returns an error if the storage domain status doesn't have a valid value.
type StorageDomainStatusList ¶ added in v0.7.0
type StorageDomainStatusList []StorageDomainStatus
StorageDomainStatusList is a list of StorageDomainStatus.
func StorageDomainStatusValues ¶ added in v0.7.0
func StorageDomainStatusValues() StorageDomainStatusList
StorageDomainStatusValues returns all possible StorageDomainStatus values.
func (StorageDomainStatusList) Strings ¶ added in v0.7.0
func (l StorageDomainStatusList) Strings() []string
Strings creates a string list of the values.
type StorageDomainType ¶ added in v0.7.0
type StorageDomainType string
StorageDomainType represents the type of the storage domain.
const ( // StorageDomainTypeCinder represents a cinder host storage type. StorageDomainTypeCinder StorageDomainType = "cinder" // StorageDomainTypeFCP represents a fcp host storage type. StorageDomainTypeFCP StorageDomainType = "fcp" // StorageDomainTypeGlance represents a glance host storage type. StorageDomainTypeGlance StorageDomainType = "glance" // StorageDomainTypeGlusterFS represents a glusterfs host storage type. StorageDomainTypeGlusterFS StorageDomainType = "glusterfs" // StorageDomainTypeISCSI represents a iscsi host storage type. StorageDomainTypeISCSI StorageDomainType = "iscsi" // StorageDomainTypeLocalFS represents a localfs host storage type. StorageDomainTypeLocalFS StorageDomainType = "localfs" // StorageDomainTypeManagedBlockStorage represents a managed block storage host storage type. StorageDomainTypeManagedBlockStorage StorageDomainType = "managed_block_storage" // StorageDomainTypeNFS represents a nfs host storage type. StorageDomainTypeNFS StorageDomainType = "nfs" // StorageDomainTypePosixFS represents a posixfs host storage type. StorageDomainTypePosixFS StorageDomainType = "posixfs" )
type StorageDomainTypeList ¶ added in v0.7.0
type StorageDomainTypeList []StorageDomainType
StorageDomainTypeList is a list of possible StorageDomainTypes.
func StorageDomainTypeValues ¶ added in v0.7.0
func StorageDomainTypeValues() StorageDomainTypeList
StorageDomainTypeValues returns all possible StorageDomainTypeValues values.
type TLSProvider ¶ added in v0.6.0
type TLSProvider interface { // CreateTLSConfig returns a working TLS configuration for the client, or an error if the configuration cannot be // created. CreateTLSConfig() (*tls.Config, error) }
TLSProvider creates a TLS configuration for use by the oVirt client.
type Tag ¶ added in v0.9.0
type Tag interface { TagData Remove(retries ...RetryStrategy) error }
Tag is the interface defining the fields for tag.
type TagClient ¶ added in v0.9.0
type TagClient interface { // GetTag returns a single tag based on its ID. GetTag(id TagID, retries ...RetryStrategy) (Tag, error) // ListTags returns all tags on the oVirt engine. ListTags(retries ...RetryStrategy) ([]Tag, error) // CreateTag creates a new tag with a name. CreateTag(name string, params CreateTagParams, retries ...RetryStrategy) (result Tag, err error) // RemoveTag removes the tag with the specified ID. RemoveTag(tagID TagID, retries ...RetryStrategy) error }
TagClient describes the functions related to oVirt tags.
type TagData ¶ added in v0.9.0
type TagData interface { // ID returns the auto-generated identifier for this tag. ID() TagID // Name returns the user-give name for this tag. Name() string // Description returns the user-give description for this tag. It may be nil if no decription is set. Description() *string }
TagData is the core of Tag, providing only the data access functions, but not the client functions.
type Template ¶
type Template interface { TemplateData // WaitForStatus waits for a template to enter a specific status. It returns the updated // template as a result. WaitForStatus(status TemplateStatus, retries ...RetryStrategy) (Template, error) // ListDiskAttachments lists all disk attachments for the current template. ListDiskAttachments(retries ...RetryStrategy) ([]TemplateDiskAttachment, error) // Remove removes the specified template. Remove(retries ...RetryStrategy) error }
Template incorporates the TemplateData to provide access to data in a template, but also adds convenience functions to work with templates.
type TemplateClient ¶
type TemplateClient interface { // CreateTemplate creates a new template from an existing VM. CreateTemplate(vmID VMID, name string, params OptionalTemplateCreateParameters, retries ...RetryStrategy) ( Template, error, ) // ListTemplates returns all templates stored in the oVirt engine. ListTemplates(retries ...RetryStrategy) ([]Template, error) // GetTemplateByName returns a template by its Name. GetTemplateByName(templateName string, retries ...RetryStrategy) (Template, error) // GetTemplate returns a template by its ID. GetTemplate(id TemplateID, retries ...RetryStrategy) (Template, error) // GetBlankTemplate finds a blank template in the oVirt engine and returns it. If no blank template is present, // this function will return an error. GetBlankTemplate(retries ...RetryStrategy) (Template, error) // RemoveTemplate removes the template with the specified ID. RemoveTemplate(templateID TemplateID, retries ...RetryStrategy) error // WaitForTemplateStatus waits for a template to enter a specific status. WaitForTemplateStatus(templateID TemplateID, status TemplateStatus, retries ...RetryStrategy) (Template, error) // CopyTemplateDiskToStorageDomain copies template disk to the specified storage domain. CopyTemplateDiskToStorageDomain(diskID DiskID, storageDomainID StorageDomainID, retries ...RetryStrategy) (Disk, error) }
TemplateClient represents the portion of the client that deals with VM templates.
type TemplateData ¶ added in v0.9.0
type TemplateData interface { // ID returns the identifier of the template. This is typically a UUID. ID() TemplateID // Name is the human-readable name for the template. Name() string // Description is a longer description for the template. Description() string // Status returns the status of the template. Status() TemplateStatus // CPU returns the CPU configuration of the template if any. CPU() VMCPU // IsBlank returns true, if the template either has the ID of all zeroes, or if the template has no settings, disks, // or other settings. This function only checks the details supported by go-ovirt-client. IsBlank(...RetryStrategy) (bool, error) }
TemplateData is a set of prepared configurations for VMs.
type TemplateDiskAttachment ¶ added in v0.9.0
type TemplateDiskAttachment interface { TemplateDiskAttachmentData // Template fetches the template object this disk attachment is related to. Template(retries ...RetryStrategy) (Template, error) // Disk fetches the disk this attachment attaches. Disk(retries ...RetryStrategy) (Disk, error) }
TemplateDiskAttachment contains all methods from TemplateDiskAttachmentData and also convenience functions to fetch and work with template disk attachments.
type TemplateDiskAttachmentData ¶ added in v0.9.0
type TemplateDiskAttachmentData interface { // ID returns the identifier of the attachment. ID() TemplateDiskAttachmentID // TemplateID returns the ID of the template the disk is attached to. TemplateID() TemplateID // DiskID returns the ID of the disk in this attachment. DiskID() DiskID // DiskInterface describes the means by which a disk will appear to the VM. DiskInterface() DiskInterface // Bootable defines whether the disk is bootable Bootable() bool // Active defines whether the disk is active in the virtual machine it’s attached to. Active() bool }
TemplateDiskAttachmentData contains the methods to get the details of a disk attached to a template.
type TemplateDiskAttachmentID ¶ added in v0.9.0
type TemplateDiskAttachmentID string
TemplateDiskAttachmentID is a typed string to ensure that these IDs are only used for template disk attachments.
type TemplateDiskClient ¶ added in v0.9.0
type TemplateDiskClient interface { // ListTemplateDiskAttachments lists all disk attachments for a template. ListTemplateDiskAttachments(templateID TemplateID, retries ...RetryStrategy) ([]TemplateDiskAttachment, error) }
TemplateDiskClient contains the methods to work with template disk attachments.
type TemplateID ¶ added in v0.9.0
type TemplateID string
TemplateID is an identifier for a template. It has a special type so the compiler can catch errors when the template ID is erroneously passed elsewhere.
const DefaultBlankTemplateID TemplateID = "00000000-0000-0000-0000-000000000000"
DefaultBlankTemplateID returns the ID for the factory-default blank template. This should not be used as the template may be deleted from the oVirt engine. Instead, use the API call to find the blank template.
type TemplateStatus ¶ added in v0.9.0
type TemplateStatus string
TemplateStatus represents the status the template is in.
const ( // TemplateStatusOK indicates that the template is ready and can be used. TemplateStatusOK TemplateStatus = "ok" // TemplateStatusLocked means that an operation is taking place on the template and cannot // be currently modified. TemplateStatusLocked TemplateStatus = "locked" // TemplateStatusIllegal indicates that the template is invalid and cannot be used. TemplateStatusIllegal TemplateStatus = "illegal" )
type TestConnectionClient ¶ added in v0.5.0
type TestConnectionClient interface { // Test tests if the connection is alive or not. Test(retries ...RetryStrategy) error }
TestConnectionClient defines the functions related to testing the connection.
type TestHelper ¶
type TestHelper interface { // GetClient returns the goVirt client. GetClient() Client // GetClusterID returns the ID for the cluster. GetClusterID() ClusterID // GetBlankTemplateID returns the ID of the blank template that can be used for creating dummy VMs. GetBlankTemplateID() TemplateID // GetStorageDomainID returns the ID of the storage domain to create the images on. GetStorageDomainID() StorageDomainID // GetSecondaryStorageDomainID returns a second ID of a storage domain to create images on. If no secondary // storage domain is available, the test will be skipped. GetSecondaryStorageDomainID(t *testing.T) StorageDomainID // GenerateRandomID generates a random ID for testing. GenerateRandomID(length uint) string // GetVNICProfileID returns a VNIC profile ID for testing. GetVNICProfileID() VNICProfileID // GetTLS returns the TLS provider used for this test helper. GetTLS() TLSProvider // GetUsername returns the oVirt username. GetUsername() string // GetPassword returns the oVirt password. GetPassword() string // GenerateTestResourceName generates a test resource name from the test name. GenerateTestResourceName(t *testing.T) string }
TestHelper is a helper to run tests against an oVirt engine. When created it scans the oVirt Engine and tries to find working resources (hosts, clusters, etc) for running tests against. Tests should clean up after themselves.
func MustNewTestHelper ¶
func MustNewTestHelper( username string, password string, url string, tlsProvider TLSProvider, mock bool, logger ovirtclientlog.Logger, params TestHelperParameters, ) TestHelper
MustNewTestHelper is identical to NewTestHelper, but panics instead of returning an error.
func NewLiveTestHelperFromEnv ¶ added in v0.6.0
func NewLiveTestHelperFromEnv(logger ovirtclientlog.Logger) (TestHelper, error)
NewLiveTestHelperFromEnv is a function that creates a test helper working against a live (not mock) oVirt engine using environment variables. The environment variables are as follows:
OVIRT_URL
URL of the oVirt engine. Mandatory.
OVIRT_USERNAME
The username for the oVirt engine. Mandatory.
OVIRT_PASSWORD
The password for the oVirt engine. Mandatory.
OVIRT_CAFILE
A file containing the CA certificate in PEM format.
OVIRT_CA_BUNDLE
Provide the CA certificate in PEM format directly.
OVIRT_INSECURE
Disable certificate verification if set. Not recommended.
OVIRT_CLUSTER_ID
The cluster to use for testing. Will be automatically chosen if not provided.
OVIRT_BLANK_TEMPLATE_ID
ID of the blank template. Will be automatically chosen if not provided.
OVIRT_STORAGE_DOMAIN_ID
Storage domain to use for testing. Will be automatically chosen if not provided.
OVIRT_VNIC_PROFILE_ID
VNIC profile to use for testing. Will be automatically chosen if not provided.
func NewMockTestHelper ¶ added in v1.0.0
func NewMockTestHelper(logger ovirtclientlog.Logger) (TestHelper, error)
NewMockTestHelper creates a test helper with a mocked oVirt engine in the backend.
func NewTestHelper ¶
func NewTestHelper( url string, username string, password string, params TestHelperParameters, tlsProvider TLSProvider, mock bool, logger ovirtclientlog.Logger, ) (TestHelper, error)
NewTestHelper creates a helper for executing tests. Depending on the mock parameter, this either sets up a mock oVirt client with test fixtures (host, cluster, etc), or connects a real oVirt cluster and finds usable infrastructure to test on. The returned object provides helper functions to access these parameters.
The ID parameters are optional and trigger automatic detection if left empty.
type TestHelperParameters ¶ added in v0.9.0
type TestHelperParameters interface { // ClusterID returns the cluster ID used for testing. It can return an empty string if no // test cluster is designated, in which case a cluster is selected. ClusterID() ClusterID // StorageDomainID returns the storage domain ID usable for testing. It can return an empty // string if no test storage domain is designated for testing, in which case a working // storage domain is selected. StorageDomainID() StorageDomainID // SecondaryStorageDomainID returns a second ID for a storage domain to test features that require // two storage domains. This may be empty, in which case such tests should be skipped. SecondaryStorageDomainID() StorageDomainID // BlankTemplateID returns an ID to a template that is blank and can be used as a basis // for testing. It may return an empty string if no template is provided. BlankTemplateID() TemplateID // VNICProfileID returns an ID to a VNIC profile designated for testing. It may return // an empty string, in which case an arbitrary VNIC profile is selected. VNICProfileID() VNICProfileID }
TestHelperParameters contains the optional parameters for the test helper.
type UpdateDiskParameters ¶ added in v0.7.0
type UpdateDiskParameters interface { // Alias returns the disk alias to set. It can return nil to leave the alias unchanged. Alias() *string // ProvisionedSize returns the disk provisioned size to set. // It can return nil to leave the provisioned size unchanged. ProvisionedSize() *uint64 }
UpdateDiskParameters describes the possible parameters for updating a disk.
type UpdateNICParameters ¶ added in v0.7.0
type UpdateNICParameters interface { // Name potentially returns a changed name for a NIC. Name() *string // VNICProfileID potentially returns a change VNIC profile for a NIC. VNICProfileID() *VNICProfileID }
UpdateNICParameters is an interface that declares methods of changeable parameters for NIC's. Each method can return nil to leave an attribute unchanged, or a new value for the attribute.
type UpdateVMParameters ¶ added in v0.7.0
type UpdateVMParameters interface { // Name returns the name for the VM. Return nil if the name should not be changed. Name() *string // Comment returns the comment for the VM. Return nil if the name should not be changed. Comment() *string }
UpdateVMParameters returns a set of parameters to change on a VM.
type UploadImageProgress ¶
type UploadImageProgress interface { // Disk returns the disk created as part of the upload process once the upload is complete. Before the upload // is complete it will return nil. Disk() Disk // UploadedBytes returns the number of bytes already uploaded. // // Caution! This number may decrease or reset to 0 if the upload has to be retried. UploadedBytes() uint64 // TotalBytes returns the total number of bytes to be uploaded. TotalBytes() uint64 // Err returns the error of the upload once the upload is complete or errored. Err() error // Done returns a channel that will be closed when the upload is complete. Done() <-chan struct{} }
UploadImageProgress is a tracker for the upload progress happening in the background.
type UploadImageResult ¶
type UploadImageResult interface { // Disk returns the disk that has been created as the result of the image upload. Disk() Disk }
UploadImageResult represents the completed image upload.
type VM ¶ added in v0.6.0
type VM interface { VMData // Update updates the virtual machine with the given parameters. Use UpdateVMParams to // get a builder for the parameters. Update(params UpdateVMParameters, retries ...RetryStrategy) (VM, error) // Remove removes the current VM. This involves an API call and may be slow. Remove(retries ...RetryStrategy) error // Start will cause a VM to start. The actual start process takes some time and should be checked via WaitForStatus. Start(retries ...RetryStrategy) error // Stop will cause the VM to power-off. The force parameter will cause the VM to stop even if a backup is currently // running. Stop(force bool, retries ...RetryStrategy) error // Shutdown will cause the VM to shut down. The force parameter will cause the VM to shut down even if a backup // is currently running. Shutdown(force bool, retries ...RetryStrategy) error // WaitForStatus will wait until the VM reaches the desired status. If the status is not reached within the // specified amount of retries, an error will be returned. If the VM enters the desired state, an updated VM // object will be returned. WaitForStatus(status VMStatus, retries ...RetryStrategy) (VM, error) // CreateNIC creates a network interface on the current VM. This involves an API call and may be slow. CreateNIC(name string, vnicProfileID VNICProfileID, params OptionalNICParameters, retries ...RetryStrategy) (NIC, error) // GetNIC fetches a NIC with a specific ID on the current VM. This involves an API call and may be slow. GetNIC(id NICID, retries ...RetryStrategy) (NIC, error) // ListNICs fetches a list of network interfaces attached to this VM. This involves an API call and may be slow. ListNICs(retries ...RetryStrategy) ([]NIC, error) // AttachDisk attaches a disk to this VM. AttachDisk( diskID DiskID, diskInterface DiskInterface, params CreateDiskAttachmentOptionalParams, retries ...RetryStrategy, ) (DiskAttachment, error) // GetDiskAttachment returns a specific disk attachment for the current VM by ID. GetDiskAttachment(diskAttachmentID DiskAttachmentID, retries ...RetryStrategy) (DiskAttachment, error) // ListDiskAttachments lists all disk attachments for the current VM. ListDiskAttachments(retries ...RetryStrategy) ([]DiskAttachment, error) // DetachDisk removes a specific disk attachment by the disk attachment ID. DetachDisk( diskAttachmentID DiskAttachmentID, retries ...RetryStrategy, ) error // Tags list all tags for the current VM Tags(retries ...RetryStrategy) ([]Tag, error) // GetHost retrieves the host object for the current VM. If the VM is not running, nil will be returned. GetHost(retries ...RetryStrategy) (Host, error) // GetIPAddresses fetches the IP addresses and returns a map of the interface name and list of IP addresses. // // The optional parameters let you filter the returned interfaces and IP addresses. GetIPAddresses(params VMIPSearchParams, retries ...RetryStrategy) (map[string][]net.IP, error) // GetNonLocalIPAddresses fetches the IP addresses, filters them for non-local IP addresses, and returns a map of the // interface name and list of IP addresses. GetNonLocalIPAddresses(retries ...RetryStrategy) (map[string][]net.IP, error) // WaitForIPAddresses waits for at least one IP address to be reported that is not in specified ranges. // // The returned result will be a map of network interface names and the list of IP addresses assigned to them, // excluding any IP addresses and interfaces in the specified parameters. WaitForIPAddresses(params VMIPSearchParams, retries ...RetryStrategy) (map[string][]net.IP, error) // WaitForNonLocalIPAddress waits for at least one IP address to be reported that is not in the following ranges: // // - 0.0.0.0/32 // - 127.0.0.0/8 // - 169.254.0.0/15 // - 224.0.0.0/4 // - 255.255.255.255/32 // - ::/128 // - ::1/128 // - fe80::/64 // - ff00::/8 // // It also excludes the following interface names: // // - lo // - dummy* // // The returned result will be a map of network interface names and the list of non-local IP addresses assigned to // them. WaitForNonLocalIPAddress(retries ...RetryStrategy) (map[string][]net.IP, error) // AddTag adds the specified tag to the current VM. AddTag(tagID TagID, retries ...RetryStrategy) (err error) // RemoveTag removes the tag from the current VM. RemoveTag(tagID TagID, retries ...RetryStrategy) (err error) // ListTags lists the tags attached to the current VM. ListTags(retries ...RetryStrategy) (result []Tag, err error) // ListGraphicsConsoles lists the graphics consoles on the VM. ListGraphicsConsoles(retries ...RetryStrategy) ([]VMGraphicsConsole, error) // SerialConsole returns true if the VM has a serial console. SerialConsole() bool }
VM is the implementation of the virtual machine in oVirt.
type VMAffinity ¶ added in v0.9.0
type VMAffinity string
VMAffinity is the affinity used in the placement policy on determining if a VM can be migrated to a different host.
const ( // VMAffinityMigratable allows automatic and manual VM migrations to other hosts. This is the default. VMAffinityMigratable VMAffinity = "migratable" // VMAffinityPinned disallows migrating to other hosts. VMAffinityPinned VMAffinity = "pinned" // VMAffinityUserMigratable allows only manual migrations to different hosts by a user. VMAffinityUserMigratable VMAffinity = "user_migratable" )
func VMAffinityValues ¶ added in v0.9.0
func VMAffinityValues() []VMAffinity
VMAffinityValues returns a list of all valid VMAffinity values.
func (VMAffinity) Validate ¶ added in v0.9.0
func (v VMAffinity) Validate() error
Validate checks the VM affinity for a valid value.
type VMCPU ¶ added in v0.9.0
type VMCPU interface { // Topo is the desired CPU topology for this VM. Topo() VMCPUTopo // Mode returns the mode of the CPU. Mode() *CPUMode }
VMCPU is the CPU configuration of a VM.
type VMCPUParams ¶ added in v1.0.0
type VMCPUParams interface { // Mode is the mode the CPU is used in. See CPUMode for details. Mode() *CPUMode // Topo contains the topology of the CPU. Topo() VMCPUTopoParams }
VMCPUParams contain the CPU parameters for a VM.
type VMCPUTopo ¶
type VMCPUTopo interface { // Cores is the number of CPU cores. Cores() uint // Threads is the number of CPU threads in a core. Threads() uint // Sockets is the number of sockets. Sockets() uint }
VMCPUTopo contains the CPU topology information about a VM.
func MustNewVMCPUTopo ¶
MustNewVMCPUTopo is equivalent to NewVMCPUTopo, but panics instead of returning an error.
type VMCPUTopoParams ¶ added in v1.0.0
type VMCPUTopoParams interface { // Sockets returns the number of sockets to be added to the VM. Must be at least 1. Sockets() uint // Threads returns the number of CPU threads to be added to the VM. Must be at least 1. Threads() uint // Cores returns the number of CPU cores to be added to the VM. Must be at least 1. Cores() uint }
VMCPUTopoParams contain the CPU topology parameters for a VM.
type VMClient ¶
type VMClient interface { // CreateVM creates a virtual machine. CreateVM( clusterID ClusterID, templateID TemplateID, name string, optional OptionalVMParameters, retries ...RetryStrategy, ) (VM, error) // GetVM returns a single virtual machine based on an ID. GetVM(id VMID, retries ...RetryStrategy) (VM, error) // GetVMByName returns a single virtual machine based on a Name. GetVMByName(name string, retries ...RetryStrategy) (VM, error) // UpdateVM updates the virtual machine with the given parameters. // Use UpdateVMParams to obtain a builder for the params. UpdateVM(id VMID, params UpdateVMParameters, retries ...RetryStrategy) (VM, error) // AutoOptimizeVMCPUPinningSettings sets the CPU settings to optimized. AutoOptimizeVMCPUPinningSettings(id VMID, optimize bool, retries ...RetryStrategy) error // StartVM triggers a VM start. The actual VM startup will take time and should be waited for via the // WaitForVMStatus call. StartVM(id VMID, retries ...RetryStrategy) error // StopVM triggers a VM power-off. The actual VM stop will take time and should be waited for via the // WaitForVMStatus call. The force parameter will cause the shutdown to proceed even if a backup is currently // running. StopVM(id VMID, force bool, retries ...RetryStrategy) error // ShutdownVM triggers a VM shutdown. The actual VM shutdown will take time and should be waited for via the // WaitForVMStatus call. The force parameter will cause the shutdown to proceed even if a backup is currently // running. ShutdownVM(id VMID, force bool, retries ...RetryStrategy) error // WaitForVMStatus waits for the VM to reach the desired status. WaitForVMStatus(id VMID, status VMStatus, retries ...RetryStrategy) (VM, error) // ListVMs returns a list of all virtual machines. ListVMs(retries ...RetryStrategy) ([]VM, error) // SearchVMs lists all virtual machines matching a certain criteria specified in params. SearchVMs(params VMSearchParameters, retries ...RetryStrategy) ([]VM, error) // RemoveVM removes a virtual machine specified by id. RemoveVM(id VMID, retries ...RetryStrategy) error // AddTagToVM Add tag specified by id to a VM. AddTagToVM(id VMID, tagID TagID, retries ...RetryStrategy) error // AddTagToVMByName Add tag specified by Name to a VM. AddTagToVMByName(id VMID, tagName string, retries ...RetryStrategy) error // RemoveTagFromVM removes the specified tag from the specified VM. RemoveTagFromVM(id VMID, tagID TagID, retries ...RetryStrategy) error // ListVMTags lists the tags attached to a VM. ListVMTags(id VMID, retries ...RetryStrategy) (result []Tag, err error) // GetVMIPAddresses fetches the IP addresses reported by the guest agent in the VM. // Optional parameters can be passed to filter the result list. // // The returned result will be a map of network interface names and the list of IP addresses assigned to them, // excluding any IP addresses in the specified parameters. GetVMIPAddresses(id VMID, params VMIPSearchParams, retries ...RetryStrategy) (map[string][]net.IP, error) // GetVMNonLocalIPAddresses fetches the IP addresses and filters them to return only non-local IP addresses. // // The returned result will be a map of network interface names and the list of IP addresses assigned to them, // excluding any IP addresses in the specified parameters. GetVMNonLocalIPAddresses(id VMID, retries ...RetryStrategy) (map[string][]net.IP, error) // WaitForVMIPAddresses waits for at least one IP address to be reported that is not in specified ranges. // // The returned result will be a map of network interface names and the list of IP addresses assigned to them, // excluding any IP addresses in the specified parameters. WaitForVMIPAddresses(id VMID, params VMIPSearchParams, retries ...RetryStrategy) (map[string][]net.IP, error) // WaitForNonLocalVMIPAddress waits for at least one IP address to be reported that is not in the following ranges: // // - 0.0.0.0/32 // - 127.0.0.0/8 // - 169.254.0.0/15 // - 224.0.0.0/4 // - 255.255.255.255/32 // - ::/128 // - ::1/128 // - fe80::/64 // - ff00::/8 // // It also excludes the following interface names: // // - lo // - dummy* // // The returned result will be a map of network interface names and the list of non-local IP addresses assigned to // them. WaitForNonLocalVMIPAddress(id VMID, retries ...RetryStrategy) (map[string][]net.IP, error) }
VMClient includes the methods required to deal with virtual machines.
Example (Create) ¶
The following example demonstrates how to create a virtual machine. It is set up using the test helper, but can be easily modified to use the client directly.
package main import ( "fmt" ovirtclient "github.com/ovirt/go-ovirt-client" ovirtclientlog "github.com/ovirt/go-ovirt-client-log/v3" ) func main() { // Create the helper for testing. Alternatively, you could create a production client with ovirtclient.New() helper, err := ovirtclient.NewLiveTestHelperFromEnv(ovirtclientlog.NewNOOPLogger()) if err != nil { panic(fmt.Errorf("failed to create live test helper (%w)", err)) } // Get the oVirt client client := helper.GetClient() // This is the cluster the VM will be created on. clusterID := helper.GetClusterID() // Use the blank template as a starting point. templateID := helper.GetBlankTemplateID() // Set the VM name name := "test-vm" // Create the optional parameters. params := ovirtclient.CreateVMParams() // Create the VM... vm, err := client.CreateVM(clusterID, templateID, name, params) if err != nil { panic(fmt.Sprintf("failed to create VM (%v)", err)) } // ... and then remove it. Alternatively, you could call client.RemoveVM(vm.ID()). if err := vm.Remove(); err != nil { panic(fmt.Sprintf("failed to remove VM (%v)", err)) } }
Output:
Example (List) ¶
The following example demonstrates how to list virtual machines.
package main import ( "fmt" ovirtclient "github.com/ovirt/go-ovirt-client" ovirtclientlog "github.com/ovirt/go-ovirt-client-log/v3" ) func main() { // Create the helper for testing. Alternatively, you could create a production client with ovirtclient.New() helper, err := ovirtclient.NewLiveTestHelperFromEnv(ovirtclientlog.NewNOOPLogger()) if err != nil { panic(fmt.Errorf("failed to create live test helper (%w)", err)) } // Get the oVirt client client := helper.GetClient() vms, err := client.ListVMs() if err != nil { panic(err) } for _, vm := range vms { fmt.Printf("Found VM %s\n", vm.ID()) } }
Output:
type VMData ¶ added in v0.7.0
type VMData interface { // ID returns the unique identifier (UUID) of the current virtual machine. ID() VMID // Name is the user-defined name of the virtual machine. Name() string // Comment is the comment added to the VM. Comment() string // ClusterID returns the cluster this machine belongs to. ClusterID() ClusterID // TemplateID returns the ID of the base template for this machine. TemplateID() TemplateID // Status returns the current status of the VM. Status() VMStatus // CPU returns the CPU structure of a VM. CPU() VMCPU // Memory return the Memory of a VM in Bytes. Memory() int64 // MemoryPolicy returns the memory policy set on the VM. MemoryPolicy() MemoryPolicy // TagIDs returns a list of tags for this VM. TagIDs() []TagID // HugePages returns the hugepage settings for the VM, if any. HugePages() *VMHugePages // Initialization returns the virtual machine’s initialization configuration. Initialization() Initialization // HostID returns the ID of the host if available. HostID() *HostID // PlacementPolicy returns placement policy applied to this VM, if any. It may be nil if no placement policy is set. // The second returned value will be false if no placement policy exists. PlacementPolicy() (placementPolicy VMPlacementPolicy, ok bool) // InstanceTypeID is the source type ID for the instance parameters. InstanceTypeID() *InstanceTypeID // VMType returns the VM type for the current VM. VMType() VMType // OS returns the operating system structure. OS() VMOS }
VMData is the core of VM providing only data access functions.
type VMGraphicsConsole ¶ added in v1.0.0
type VMGraphicsConsole interface { VMGraphicsConsoleData // Remove removes the graphics console. Remove(retries ...RetryStrategy) error }
VMGraphicsConsole is an object representing a graphics console on a virtual machine.
type VMGraphicsConsoleData ¶ added in v1.0.0
type VMGraphicsConsoleData interface { ID() VMGraphicsConsoleID VMID() VMID }
VMGraphicsConsoleData contains the data for VMGraphicsConsole objects.
type VMGraphicsConsoleID ¶ added in v1.0.0
type VMGraphicsConsoleID string
VMGraphicsConsoleID is the identifier for graphics consoles on a VM.
type VMHugePages ¶ added in v0.9.0
type VMHugePages uint64
VMHugePages is the hugepages setting of the VM in bytes.
const ( // VMHugePages2M represents the small value of supported huge pages setting which is 2048 Kib. VMHugePages2M VMHugePages = 2048 // VMHugePages1G represents the large value of supported huge pages setting which is 1048576 Kib. VMHugePages1G VMHugePages = 1048576 )
func (VMHugePages) Validate ¶ added in v0.9.0
func (h VMHugePages) Validate() error
Validate returns an error if the VM hugepages doesn't have a valid value.
type VMHugePagesList ¶ added in v0.9.0
type VMHugePagesList []VMHugePages
VMHugePagesList is a list of VMHugePages.
func VMHugePagesValues ¶ added in v0.9.0
func VMHugePagesValues() VMHugePagesList
VMHugePagesValues returns all possible VMHugepages values.
func (VMHugePagesList) Strings ¶ added in v0.9.0
func (l VMHugePagesList) Strings() []string
Strings creates a string list of the values.
type VMIPSearchParams ¶ added in v0.9.0
type VMIPSearchParams interface { // GetIncludedRanges returns a list of network ranges that the returned IP address must match. GetIncludedRanges() []net.IPNet // GetExcludedRanges returns a list of IP ranges that should not be taken into consideration when returning IP // addresses. GetExcludedRanges() []net.IPNet // GetIncludedInterfaces returns a list of interface names of which the interface name must match at least // one. GetIncludedInterfaces() []string // GetExcludedInterfaces returns a list of interface names that should be excluded from the search. GetExcludedInterfaces() []string // GetIncludedInterfacePatterns returns a list of regular expressions of which at least one must match // the interface name. GetIncludedInterfacePatterns() []*regexp.Regexp // GetExcludedInterfacePatterns returns a list of regular expressions that match interface names needing to be // excluded from the IP address search. GetExcludedInterfacePatterns() []*regexp.Regexp }
VMIPSearchParams contains the parameters for searching or waiting for IP addresses on a VM.
type VMOS ¶ added in v1.0.0
type VMOS interface {
Type() string
}
VMOS is the structure describing the virtual machine operating system, if set.
type VMOSParameters ¶ added in v1.0.0
type VMOSParameters interface { // Type returns the type-string for the operating system. Type() *string }
VMOSParameters contains the VM parameters pertaining to the operating system.
type VMPlacementPolicy ¶ added in v0.9.0
type VMPlacementPolicy interface { Affinity() *VMAffinity HostIDs() []HostID }
VMPlacementPolicy is the structure that holds the rules for VM migration to other hosts.
type VMPlacementPolicyParameters ¶ added in v0.9.0
type VMPlacementPolicyParameters interface { // Affinity dictates how a VM can be migrated to a different host. This can be nil, in which case the engine // default is to set the policy to migratable. Affinity() *VMAffinity // HostIDs returns a list of host IDs to apply as possible migration targets. The default is an empty list, // which means the VM can be migrated to any host. HostIDs() []HostID }
VMPlacementPolicyParameters contains the optional parameters on VM placement.
type VMSearchParameters ¶ added in v0.9.0
type VMSearchParameters interface { // Name will match the name of the virtual machine exactly. Name() *string // Tag will match the tag of the virtual machine. Tag() *string // Statuses will return a list of acceptable statuses for this VM search. Statuses() *VMStatusList // NotStatuses will return a list of not acceptable statuses for this VM search. NotStatuses() *VMStatusList }
VMSearchParameters declares the parameters that can be passed to a VM search. Each parameter is declared as a pointer, where a nil value will mean that parameter will not be searched for. All parameters are used together as an AND filter.
type VMStatus ¶ added in v0.7.0
type VMStatus string
VMStatus represents the status of a VM.
const ( // VMStatusDown indicates that the VM is not running. VMStatusDown VMStatus = "down" // VMStatusImageLocked indicates that the virtual machine process is not running and there is some operation on the // disks of the virtual machine that prevents it from being started. VMStatusImageLocked VMStatus = "image_locked" // VMStatusMigrating indicates that the virtual machine process is running and the virtual machine is being migrated // from one host to another. VMStatusMigrating VMStatus = "migrating" // VMStatusNotResponding indicates that the hypervisor detected that the virtual machine is not responding. VMStatusNotResponding VMStatus = "not_responding" // VMStatusPaused indicates that the virtual machine process is running and the virtual machine is paused. // This may happen in two cases: when running a virtual machine is paused mode and when the virtual machine is being // automatically paused due to an error. VMStatusPaused VMStatus = "paused" // VMStatusPoweringDown indicates that the virtual machine process is running and it is about to stop running. VMStatusPoweringDown VMStatus = "powering_down" // VMStatusPoweringUp indicates that the virtual machine process is running and the guest operating system is being // loaded. Note that if no guest-agent is installed, this status is set for a predefined period of time, that is by // default 60 seconds, when running a virtual machine. VMStatusPoweringUp VMStatus = "powering_up" // VMStatusRebooting indicates that the virtual machine process is running and the guest operating system is being // rebooted. VMStatusRebooting VMStatus = "reboot_in_progress" // VMStatusRestoringState indicates that the virtual machine process is about to run and the virtual machine is // going to awake from hibernation. In this status, the running state of the virtual machine is being restored. VMStatusRestoringState VMStatus = "restoring_state" // VMStatusSavingState indicates that the virtual machine process is running and the virtual machine is being // hibernated. In this status, the running state of the virtual machine is being saved. Note that this status does // not mean that the guest operating system is being hibernated. VMStatusSavingState VMStatus = "saving_state" // VMStatusSuspended indicates that the virtual machine process is not running and a running state of the virtual // machine was saved. This status is similar to Down, but when the VM is started in this status its saved running // state is restored instead of being booted using the normal procedure. VMStatusSuspended VMStatus = "suspended" // VMStatusUnassigned means an invalid status was received. VMStatusUnassigned VMStatus = "unassigned" // VMStatusUnknown indicates that the system failed to determine the status of the virtual machine. // The virtual machine process may be running or not running in this status. // For instance, when host becomes non-responsive the virtual machines that ran on it are set with this status. VMStatusUnknown VMStatus = "unknown" // VMStatusUp indicates that the virtual machine process is running and the guest operating system is loaded. // Note that if no guest-agent is installed, this status is set after a predefined period of time, that is by // default 60 seconds, when running a virtual machine. VMStatusUp VMStatus = "up" // VMStatusWaitForLaunch indicates that the virtual machine process is about to run. // This status is set when a request to run a virtual machine arrives to the host. // It is possible that the virtual machine process will fail to run. VMStatusWaitForLaunch VMStatus = "wait_for_launch" )
type VMStatusList ¶ added in v0.7.0
type VMStatusList []VMStatus
VMStatusList is a list of VMStatus.
func VMStatusValues ¶ added in v0.7.0
func VMStatusValues() VMStatusList
VMStatusValues returns all possible VMStatus values.
func (VMStatusList) Copy ¶ added in v0.9.0
func (l VMStatusList) Copy() VMStatusList
Copy creates a separate copy of the current status list.
func (VMStatusList) Strings ¶ added in v0.7.0
func (l VMStatusList) Strings() []string
Strings creates a string list of the values.
func (VMStatusList) Validate ¶ added in v0.9.0
func (l VMStatusList) Validate() error
Validate validates the list of statuses.
type VMType ¶ added in v1.0.0
type VMType string
VMType contains some preconfigured settings, such as the availability of remote desktop, for the VM.
const ( // VMTypeDesktop indicates that the virtual machine is intended to be used as a desktop and enables the SPICE // virtual console, and a sound device will be added to the VM. VMTypeDesktop VMType = "desktop" // VMTypeServer indicates that the VM will be used as a server. In this case a sound device will not be added to the // VM. VMTypeServer VMType = "server" // VMTypeHighPerformance indicates that the VM should be configured for high performance. This entails the following // options: // // - Enable headless mode. // - Enable pass-through host CPU. // - Enable I/O threads. // - Enable I/O threads pinning and set the pinning topology. // - Enable the paravirtualized random number generator PCI (virtio-rng) device. // - Disable all USB devices. // - Disable the soundcard device. // - Disable the smartcard device. // - Disable the memory balloon device. // - Disable the watchdog device. // - Disable migration. // - Disable high availability. VMTypeHighPerformance VMType = "high_performance" )
func VMTypeValues ¶ added in v1.0.0
func VMTypeValues() []VMType
VMTypeValues returns all possible values for VM types.
type VNICProfile ¶ added in v0.6.0
type VNICProfile interface { VNICProfileData // Network fetches the network object from the oVirt engine. This is an API call and may be slow. Network(retries ...RetryStrategy) (Network, error) // Remove removes the current VNIC profile. Remove(retries ...RetryStrategy) error }
VNICProfile is a collection of settings that can be applied to individual virtual network interface cards in the Engine.
type VNICProfileClient ¶ added in v0.6.0
type VNICProfileClient interface { // CreateVNICProfile creates a new VNIC profile with the specified name and network ID. CreateVNICProfile(name string, networkID NetworkID, params OptionalVNICProfileParameters, retries ...RetryStrategy) (VNICProfile, error) // GetVNICProfile returns a single VNIC Profile based on the ID GetVNICProfile(id VNICProfileID, retries ...RetryStrategy) (VNICProfile, error) // ListVNICProfiles lists all VNIC Profiles. ListVNICProfiles(retries ...RetryStrategy) ([]VNICProfile, error) // RemoveVNICProfile removes a VNIC profile RemoveVNICProfile(id VNICProfileID, retries ...RetryStrategy) error }
VNICProfileClient defines the methods related to dealing with virtual NIC profiles.
type VNICProfileData ¶ added in v0.7.0
type VNICProfileData interface { // ID returns the identifier of the VNICProfile. ID() VNICProfileID // Name returns the human-readable name of the VNIC profile. Name() string // NetworkID returns the network ID the VNICProfile is attached to. NetworkID() NetworkID }
VNICProfileData is the core of VNICProfile, providing only data access functions.
type VNICProfileID ¶ added in v1.0.0
type VNICProfileID string
VNICProfileID is the ID of the VNIC profile.
Source Files ¶
- affinitygroup.go
- affinitygroup_create.go
- affinitygroup_get.go
- affinitygroup_get_by_name.go
- affinitygroup_list.go
- affinitygroup_remove.go
- affinitygroup_vm_add.go
- affinitygroup_vm_remove.go
- client.go
- cluster.go
- cluster_get.go
- cluster_list.go
- const.go
- consts.go
- datacenter.go
- datacenter_get.go
- datacenter_list.go
- datacenter_list_clusters.go
- datacenter_mock.go
- disk.go
- disk_attachment.go
- disk_attachment_create.go
- disk_attachment_get.go
- disk_attachment_list.go
- disk_attachment_remove.go
- disk_create.go
- disk_create_mock.go
- disk_downloadimage.go
- disk_get.go
- disk_get_internal.go
- disk_helper_imagetransfer.go
- disk_list.go
- disk_list_by_alias.go
- disk_mock.go
- disk_remove.go
- disk_remove_mock.go
- disk_update.go
- disk_uploadimage.go
- disk_wait_for_ok.go
- doc.go
- errors.go
- feature.go
- host.go
- host_get.go
- host_list.go
- instancetype.go
- instancetype_get.go
- instancetype_list.go
- logger.go
- mock.go
- network.go
- network_get.go
- network_list.go
- new.go
- newmock.go
- nic.go
- nic_create.go
- nic_get.go
- nic_list.go
- nic_remove.go
- nic_update.go
- retry.go
- storagedomain.go
- storagedomain_get.go
- storagedomain_get_disk.go
- storagedomain_list.go
- storagedomain_remove_disk.go
- tag.go
- tag_create.go
- tag_get.go
- tag_list.go
- tag_remove.go
- template.go
- template_copy_disk.go
- template_create.go
- template_disk.go
- template_disk_list.go
- template_get.go
- template_get_blank.go
- template_get_by_name.go
- template_list.go
- template_remove.go
- template_wait_for_status.go
- testconnection.go
- tls.go
- util_qcow.go
- util_quote_search_string.go
- util_random.go
- util_test_helper.go
- util_wait_for_job_finished.go
- vm.go
- vm_create.go
- vm_get.go
- vm_get_by_name.go
- vm_graphics_console.go
- vm_graphics_console_list.go
- vm_graphics_console_remove.go
- vm_ip_get.go
- vm_ip_get_nonlocal.go
- vm_ip_wait.go
- vm_ip_wait_nonlocal.go
- vm_list.go
- vm_optimize_pinning.go
- vm_remove.go
- vm_search.go
- vm_shutdown.go
- vm_start.go
- vm_stop.go
- vm_tag_add.go
- vm_tag_list.go
- vm_tag_remove.go
- vm_update.go
- vm_wait_for_status.go
- vnicprofile.go
- vnicprofile_create.go
- vnicprofile_get.go
- vnicprofile_list.go
- vnicprofile_remove.go