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/",
// Username
"admin@internal",
// Password
"super-secret",
// Pull CA certificates from the operating system.
// This won't work on Windows. 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 easiest way to set up the test helper is using environment variables. To do that, you can use the ovirtclient.NewTestHelperFromEnv() function:
helper := ovirtclient.NewTestHelperFromEnv(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.
OVIRT_USERNAME
The username for the oVirt engine.
OVIRT_PASSWORD
The password for the oVirt engine
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.
mock := false
// Create the test helper
helper, err := ovirtclient.NewTestHelper(
"https://localhost/ovirt-engine/",
"admin@internal",
"super-secret",
ovirtclient.TLS().CACertsFromSystem(),
// The following parameters define which infrastructure parts to use for testing.
// Leave these empty for auto-detection / fixture setup.
os.Getenv("OVIRT_CLUSTER_ID"),
os.Getenv("OVIRT_BLANK_TEMPLATE_ID"),
os.Getenv("OVIRT_STORAGE_DOMAIN_ID"),
os.Getenv("OVIRT_VNIC_PROFILE_ID"),
mock,
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:
type Logger interface {
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warningf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
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() functionL
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 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 BuildableCreateDiskAttachmentParams
- type BuildableCreateDiskParameters
- type BuildableNICParameters
- type BuildableTLSProvider
- type BuildableUpdateDiskParameters
- type BuildableUpdateNICParameters
- type BuildableUpdateVMParameters
- type BuildableVMParameters
- type BuildableVNICProfileParameters
- type Client
- type ClientWithLegacySupport
- type Cluster
- type ClusterClient
- type CreateDiskAttachmentOptionalParams
- type CreateDiskOptionalParameters
- type Datacenter
- type DatacenterClient
- type DatacenterData
- type Disk
- type DiskAttachment
- type DiskAttachmentClient
- type DiskClient
- type DiskCreation
- type DiskData
- type DiskInterface
- type DiskInterfaceList
- type DiskStatus
- type DiskStatusList
- type DiskUpdate
- type EngineError
- type ErrorCode
- type ExtraSettings
- type FileStorageDomainTypeList
- type Host
- type HostClient
- type HostData
- type HostStatus
- type HostStatusList
- type ImageDownload
- type ImageDownloadReader
- type ImageFormat
- type ImageFormatList
- type Logger
- type MockClient
- type NIC
- type NICClient
- type NICData
- type Network
- type NetworkClient
- type NetworkData
- type OptionalNICParameters
- type OptionalVMParameters
- type OptionalVNICProfileParameters
- type RetryInstance
- type RetryStrategy
- type StorageDomain
- type StorageDomainClient
- type StorageDomainData
- type StorageDomainExternalStatus
- type StorageDomainExternalStatusList
- type StorageDomainStatus
- type StorageDomainStatusList
- type StorageDomainType
- type StorageDomainTypeList
- type TLSProvider
- type Template
- type TemplateClient
- type TestConnectionClient
- type TestHelper
- func MustNewTestHelper(username string, password string, url string, tlsProvider TLSProvider, ...) TestHelper
- func NewLiveTestHelperFromEnv(logger ovirtclientlog.Logger) (TestHelper, error)
- func NewTestHelper(url string, username string, password string, tlsProvider TLSProvider, ...) (TestHelper, error)
- func NewTestHelperFromEnv(logger ovirtclientlog.Logger) TestHelper
- type UpdateDiskParameters
- type UpdateNICParameters
- type UpdateVMParameters
- type UploadImageProgress
- type UploadImageResult
- type VM
- type VMClient
- type VMData
- type VMStatus
- type VMStatusList
- type VNICProfile
- type VNICProfileClient
- type VNICProfileData
Examples ¶
Constants ¶
const BlankTemplateID = "00000000-0000-0000-0000-000000000000"
BlankTemplateID is the blank template in oVirt.
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 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 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
}
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
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 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 string) (BuildableUpdateNICParameters, error)
// MustWithVNICPRofileID is identical to WithVNICProfileID, but panics instead of returning an error.
MustWithVNICProfileID(id string) 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 BuildableVMParameters ¶ added in v0.6.0
type BuildableVMParameters interface {
OptionalVMParameters
// WithName adds a name to the VM.
WithName(name string) (BuildableVMParameters, error)
// MustWithName is identical to WithName, but panics instead of returning an error.
MustWithName(name string) BuildableVMParameters
// 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
}
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.
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 Client ¶
type Client interface {
// GetURL returns the oVirt engine base URL.
GetURL() string
DiskClient
DiskAttachmentClient
VMClient
NICClient
VNICProfileClient
NetworkClient
DatacenterClient
ClusterClient
StorageDomainClient
HostClient
TemplateClient
TestConnectionClient
}
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( url string, username string, password string, tls TLSProvider, logger Logger, extraSettings ExtraSettings, verify func(connection *ovirtsdk4.Connection) 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() string
// 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 string, 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 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 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 string, 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 string, 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 string, 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
DatacenterData is the core of a Datacenter when client functions are not required.
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 string,
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)
}
Disk is a disk in oVirt.
type DiskAttachment ¶ added in v0.7.0
type DiskAttachment interface {
// ID returns the identifier of the attachment.
ID() string
// VMID returns the ID of the virtual machine this attachment belongs to.
VMID() string
// DiskID returns the ID of the disk in this attachment.
DiskID() string
// 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 string, diskID string, diskInterface DiskInterface, params CreateDiskAttachmentOptionalParams, retries ...RetryStrategy) (DiskAttachment, error)
// GetDiskAttachment returns a single disk attachment in a virtual machine.
GetDiskAttachment(vmID string, id string, retries ...RetryStrategy) (DiskAttachment, error)
// ListDiskAttachments lists all disk attachments for a virtual machine.
ListDiskAttachments(vmID string, retries ...RetryStrategy) ([]DiskAttachment, error)
// RemoveDiskAttachment removes the disk attachment in question.
RemoveDiskAttachment(vmID string, diskAttachmentID string, retries ...RetryStrategy) error
}
DiskAttachmentClient contains the methods required for handling disk attachments.
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 string,
sparse bool,
size uint64,
reader 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 string,
format ImageFormat,
size uint64,
params CreateDiskOptionalParameters,
reader 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 string,
sparse bool,
size uint64,
reader 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 string,
format ImageFormat,
size uint64,
params CreateDiskOptionalParameters,
reader 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 string,
size uint64,
reader 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 string,
size uint64,
reader 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 string,
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 string,
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 string,
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 string,
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 string,
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 string,
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 string,
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 string,
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 string, 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 string, retries ...RetryStrategy) 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/v2"
)
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() {
_ = fh.Close()
}()
// 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 := ovirtclient.NewTestHelperFromEnv(ovirtclientlog.NewNOOPLogger())
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/v2"
)
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() {
_ = fh.Close()
}()
// 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 := ovirtclient.NewTestHelperFromEnv(ovirtclientlog.NewNOOPLogger())
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() string
// 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
// StorageDomainID is the ID of the storage system used for this disk.
StorageDomainID() string
// 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
// 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
// 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 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 ELocalIO ErrorCode = "local_io_error"
ELocalIO indicates an input/output error on the client side. For example, a disk could not be read.
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.
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.
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
}
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 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 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 string, 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() string
// ClusterID returns the ID of the cluster this host belongs to.
ClusterID() string
// 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 Logger ¶
type Logger interface {
ovirtclientlog.Logger
}
Logger is a thin wrapper around ovirtclientlog.Logger for convenience.
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.
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 string,
vnicProfileID string,
name string,
optional OptionalNICParameters,
retries ...RetryStrategy,
) (NIC, error)
// UpdateNIC allows updating the NIC.
UpdateNIC(
vmid string,
nicID string,
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 string, id string, retries ...RetryStrategy) (NIC, error)
// ListNICs lists all NICs attached to the VM specified in vmid.
ListNICs(vmid string, retries ...RetryStrategy) ([]NIC, error)
// RemoveNIC removes the network interface specified.
RemoveNIC(vmid string, id string, 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() string
// 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() string
// VNICProfileID returns the ID of the VNIC profile in use by the NIC.
VNICProfileID() string
}
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 string, 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() string
// Name returns the user-give nname for this network.
Name() string
// DatacenterID is the identifier of the datacenter object.
DatacenterID() string
}
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 OptionalVMParameters ¶ added in v0.6.0
type OptionalVMParameters interface {
// Name returns the name for the new VM.
Name() string
// Comment returns the comment for the VM.
Comment() string
}
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
// 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
}
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 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 string, retries ...RetryStrategy) (StorageDomain, 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() string
// 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 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 Template ¶
type Template interface {
// ID returns the identifier of the template. This is typically a UUID.
ID() string
// Name is the human-readable name for the template.
Name() string
// Description is a longer description for the template.
Description() string
}
Template is a set of prepared configurations for VMs.
type TemplateClient ¶
type TemplateClient interface {
ListTemplates(retries ...RetryStrategy) ([]Template, error)
GetTemplate(id string, retries ...RetryStrategy) (Template, error)
}
TemplateClient represents the portion of the client that deals with VM templates.
type TestConnectionClient ¶ added in v0.5.0
type TestConnectionClient interface {
// Test tests if the connection is alive or not.
Test() 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() string
// GetBlankTemplateID returns the ID of the blank template that can be used for creating dummy VMs.
GetBlankTemplateID() string
// GetStorageDomainID returns the ID of the storage domain to create the images on.
GetStorageDomainID() string
// GenerateRandomID generates a random ID for testing.
GenerateRandomID(length uint) string
// GetVNICProfileID returns a VNIC profile ID for testing.
GetVNICProfileID() string
// GetTLS returns the TLS provider used for this test helper.
GetTLS() TLSProvider
}
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, clusterID string, blankTemplateID string, storageDomainID string, vnicProfileID string, mock bool, logger ovirtclientlog.Logger, ) 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.
OVIRT_USERNAME
The username for the oVirt engine.
OVIRT_PASSWORD
The password for the oVirt engine
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 NewTestHelper ¶
func NewTestHelper( url string, username string, password string, tlsProvider TLSProvider, clusterID string, blankTemplateID string, storageDomainID string, vnicProfileID string, 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.
func NewTestHelperFromEnv ¶ added in v0.6.0
func NewTestHelperFromEnv(logger ovirtclientlog.Logger) TestHelper
NewTestHelperFromEnv attempts to create a live test helper from environment variables and falls back to the internal mock implementation if it fails.
OVIRT_URL
URL of the oVirt engine.
OVIRT_USERNAME
The username for the oVirt engine.
OVIRT_PASSWORD
The password for the oVirt engine
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.
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() *string
}
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
// CreateNIC creates a network interface on the current VM. This involves an API call and may be slow.
CreateNIC(name string, vnicProfileID string, 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 string, 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 string,
diskInterface DiskInterface,
params CreateDiskAttachmentOptionalParams,
retries ...RetryStrategy,
) (DiskAttachment, error)
// GetDiskAttachment returns a specific disk attachment for the current VM by ID.
GetDiskAttachment(diskAttachmentID string, 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 string,
retries ...RetryStrategy,
) error
}
VM is the implementation of the virtual machine in oVirt.
type VMClient ¶
type VMClient interface {
// CreateVM creates a virtual machine.
CreateVM(
clusterID string,
templateID string,
optional OptionalVMParameters,
retries ...RetryStrategy,
) (VM, error)
// GetVM returns a single virtual machine based on an ID.
GetVM(id 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 string, params UpdateVMParameters, retries ...RetryStrategy) (VM, error)
// ListVMs returns a list of all virtual machines.
ListVMs(retries ...RetryStrategy) ([]VM, error)
// RemoveVM removes a virtual machine specified by id.
RemoveVM(id string, retries ...RetryStrategy) 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/v2"
)
func main() {
// Create the helper for testing. Alternatively, you could create a production client with ovirtclient.New()
helper := ovirtclient.NewTestHelperFromEnv(ovirtclientlog.NewNOOPLogger())
// 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()
// Create the optional parameters.
params := ovirtclient.CreateVMParams()
// Create the VM...
vm, err := client.CreateVM(clusterID, templateID, 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/v2"
)
func main() {
// Create the helper for testing. Alternatively, you could create a production client with ovirtclient.New()
helper := ovirtclient.NewTestHelperFromEnv(ovirtclientlog.NewNOOPLogger())
// 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() string
// 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() string
// TemplateID returns the ID of the base template for this machine.
TemplateID() string
// Status returns the current status of the VM.
Status() VMStatus
}
VMData is the core of VM providing only data access functions.
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) Strings ¶ added in v0.7.0
func (l VMStatusList) Strings() []string
Strings creates a string list of the values.
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 string, params OptionalVNICProfileParameters, retries ...RetryStrategy) (VNICProfile, error)
// GetVNICProfile returns a single VNIC Profile based on the ID
GetVNICProfile(id string, retries ...RetryStrategy) (VNICProfile, error)
// ListVNICProfiles lists all VNIC Profiles.
ListVNICProfiles(retries ...RetryStrategy) ([]VNICProfile, error)
// RemoveVNICProfile removes a VNIC profile
RemoveVNICProfile(id string, 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() string
// Name returns the human-readable name of the VNIC profile.
Name() string
// NetworkID returns the network ID the VNICProfile is attached to.
NetworkID() string
}
VNICProfileData is the core of VNICProfile, providing only data access functions.
Source Files
¶
- client.go
- client_cluster.go
- client_cluster_get.go
- client_cluster_list.go
- client_datacenter.go
- client_datacenter_get.go
- client_datacenter_list.go
- client_datacenter_list_clusters.go
- client_disk.go
- client_disk_attachment.go
- client_disk_attachment_create.go
- client_disk_attachment_get.go
- client_disk_attachment_list.go
- client_disk_attachment_remove.go
- client_disk_create.go
- client_disk_downloadimage.go
- client_disk_get.go
- client_disk_helper_imagetransfer.go
- client_disk_list.go
- client_disk_list_by_alias.go
- client_disk_remove.go
- client_disk_update.go
- client_disk_uploadimage.go
- client_host.go
- client_host_get.go
- client_host_list.go
- client_network.go
- client_network_get.go
- client_network_list.go
- client_nic.go
- client_nic_create.go
- client_nic_get.go
- client_nic_list.go
- client_nic_remove.go
- client_nic_update.go
- client_storagedomain.go
- client_storagedomain_get.go
- client_storagedomain_list.go
- client_template.go
- client_template_get.go
- client_template_list.go
- client_testconnection.go
- client_util.go
- client_vm.go
- client_vm_create.go
- client_vm_get.go
- client_vm_list.go
- client_vm_remove.go
- client_vm_update.go
- client_vnicprofile.go
- client_vnicprofile_create.go
- client_vnicprofile_get.go
- client_vnicprofile_list.go
- client_vnicprofile_remove.go
- const.go
- consts.go
- doc.go
- errors.go
- logger.go
- mock.go
- mock_cluster_get.go
- mock_cluster_list.go
- mock_datacenter.go
- mock_datacenter_get.go
- mock_datacenter_list.go
- mock_datacenter_list_clusters.go
- mock_disk.go
- mock_disk_attachment_create.go
- mock_disk_attachment_get.go
- mock_disk_attachment_list.go
- mock_disk_attachment_remove.go
- mock_disk_create.go
- mock_disk_downloadimage.go
- mock_disk_get.go
- mock_disk_get_internal.go
- mock_disk_list.go
- mock_disk_list_by_alias.go
- mock_disk_remove.go
- mock_disk_update.go
- mock_disk_uploadimage.go
- mock_host_get.go
- mock_host_list.go
- mock_network_get.go
- mock_network_list.go
- mock_nic_create.go
- mock_nic_get.go
- mock_nic_list.go
- mock_nic_remove.go
- mock_nic_update.go
- mock_storagedomain_get.go
- mock_storagedomain_list.go
- mock_template_get.go
- mock_template_list.go
- mock_vm_create.go
- mock_vm_get.go
- mock_vm_list.go
- mock_vm_remove.go
- mock_vm_update.go
- mock_vnicprofile_create.go
- mock_vnicprofile_get.go
- mock_vnicprofile_list.go
- mock_vnicprofile_remove.go
- new.go
- newmock.go
- random.go
- retry.go
- test_helper.go
- tls.go
- util_go.go
- util_qcow.go