ovirtclient

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 23, 2021 License: BSD-3-Clause Imports: 23 Imported by: 2

README

goVirt: an easy-to-use overlay for the oVirt Go SDK

🚧 This library is early in development. 🚧

This library is early in development, and the API may change at any time until version 1.0.0. We hope to stabilize the API soon, providing the core functionality on an as-needed basis. If you need an API integrated, please open an issue.

This library provides an easy-to-use overlay for the automatically generated Go SDK for oVirt. It does not replace the Go SDK. It implements the functions of the SDK only partially and is primarily used by the oVirt Terraform provider.

Using this library

To use this library you will have to include it as a Go module dependency:

go get github.com/ovirt/go-ovirt-client

You can then create a client instance like this:

package main

import (
    "github.com/ovirt/go-client-log"
    "github.com/ovirt/go-ovirt-client"
)

func main() {
    // Create a logger that logs to the standard Go log here:
    logger := ovirtclientlog.NewGoLogLogger(nil)

    // Create an ovirtclient.TLSProvider implementation. This allows for simple
    // TLS configuration.
	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, please don't do this.
	tls.Insecure()

    // Create a new goVirt instance:
    client, err := ovirtclient.New(
        // URL to your oVirt engine API here:
        "https://your-ovirt-engine/ovirt-engine/api/",
        // Username here:
        "admin@internal",
        // Password here:
        "password-here",
        // Pass the TLS provider here:
        tls,
        // Pass the logger here:
        logger,
        // Pass in extra settings here. Must implement the ovirtclient.ExtraSettings interface.
        nil,
    )
    if err != nil {
        // Handle error, here in a really crude way:
        panic(err)
    }
    // Use client. Please use the code completion in your IDE to
    // discover the functions. Each is well documented.
    upload, err := client.StartImageUpload(
        //...
    )
    //....
}

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 estabilshed. 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()
    //...
}

Tip: You can use any logger that satisfies the Logger interface described in go-ovirt-client-log

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.

Mock client

This library also provides a mock oVirt client that doesn't need working oVirt engine to function. It stores all information in-memory and simulates a working oVirt system. You can instantiate the mock client like so:

client := ovirtclient.NewMock()

We recommend using the ovirtclient.Client interface as a means to declare it as a dependency in your factory so you can pass both the mock and the real connection as a parameter:

func NewMyoVirtUsingUtility(
    client ovirtclient.Client,
) *myOVirtUsingUtility {
    return &myOVirtUsingUtility{
        client: client,
    }
}

FAQ

Why doesn't the library return the underlying oVirt SDK objects?

It's a painful decision we made. We want to encourage anyone who needs a certain function to submit a PR instead of simply relying on the SDK objects. This will lead to some overhead when a new function needs to be added, but leads to cleaner code in the end and makes this library more comprehensive. It also makes it possible to create the mock client, which would not be possibly if we had to simulate all parts of the oVirt engine.

If you need to access the oVirt SDK client you can do so from the ovirtclient.New() function:

client, err := ovirtclient.New(
    //...
)
if err != nil {
    //...
}
sdkClient := client.GetSDKClient()

You can also get a properly preconfigured HTTP client if you need it:

httpClient := client.GetHTTPClient()

🚧 Warning: If you code relies on the SDK or HTTP clients you will not be able to use the mock functionality described above for testing.

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

Examples

Constants

View Source
const BlankTemplateID = "00000000-0000-0000-0000-000000000000"

BlankTemplateID is the blank template in oVirt.

Variables

This section is empty.

Functions

This section is empty.

Types

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

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 BuildableVMParameters added in v0.6.0

type BuildableVMParameters interface {
	OptionalVMParameters
}

BuildableVMParameters is a variant of OptionalVMParameters that can be changed using the supplied builder functions. This is placed here for future use.

func VMParams added in v0.6.0

func VMParams() BuildableVMParameters

VMParams creates a set of BuildableVMParameters that can be used to construct the optional VM parameters.

type Client

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 Datacenter added in v0.6.0

type Datacenter interface {
	ID() string
	Name() string

	// 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 Disk

type Disk 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
}

Disk is a disk in oVirt.

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 {
	//         //...
	//     }
	//
	StartImageUpload(
		alias string,
		storageDomainID string,
		sparse bool,
		size uint64,
		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.
	UploadImage(
		alias string,
		storageDomainID string,
		sparse bool,
		size uint64,
		reader readSeekCloser,
		retries ...RetryStrategy,
	) (UploadImageResult, 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.
	// The passed context is observed only for the initialization phase.
	StartImageDownload(
		diskID string,
		format ImageFormat,
		retries ...RetryStrategy,
	) (ImageDownload, error)

	// DownloadImage runs StartImageDownload, 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.
	DownloadImage(
		diskID string,
		format ImageFormat,
		retries ...RetryStrategy,
	) (ImageDownloadReader, 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)
	// 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.UploadImage(
		imageName,
		helper.GetStorageDomainID(),
		true,
		uint64(stat.Size()),
		fh,
	)
	if err != nil {
		panic(fmt.Errorf("failed to upload image (%w)", err))
	}
	fmt.Printf("Uploaded as disk %s\n", uploadResult.Disk().ID())
}
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.StartImageUpload(
		imageName,
		helper.GetStorageDomainID(),
		true,
		uint64(stat.Size()),
		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())
}

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 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 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

func (e ErrorCode) CanAutoRetry() bool

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 Host

type Host 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
}

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 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 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"
)

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 {
	// 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

	// 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)
	// 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, name string, vnicProfileID string, 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 Network added in v0.6.0

type Network 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

	// 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 OptionalVMParameters added in v0.6.0

type OptionalVMParameters interface{}

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 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 {
	// 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
	// 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
}

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 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 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 = ""
)

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 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
	// CorrelationID returns the correlation ID for the upload.
	CorrelationID() string
	// UploadedBytes returns the number of bytes already uploaded.
	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
	// CorrelationID returns the opaque correlation ID for the upload.
	CorrelationID() string
}

UploadImageResult represents the completed image upload.

type VM added in v0.6.0

type VM 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

	// 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, 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)
}

VM is the implementation of the virtual machine in oVirt.

type VMClient

type VMClient interface {
	// CreateVM creates a virtual machine.
	CreateVM(
		name string,
		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)
	// 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 will be the VM name
	vmName := "test"
	// 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.VMParams()

	// Create the VM...
	vm, err := client.CreateVM(vmName, 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))
	}
}
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())
	}
}

type VNICProfile added in v0.6.0

type VNICProfile 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

	// Network fetches the network object from the oVirt engine. This is an API call and may be slow.
	Network(retries ...RetryStrategy) (Network, 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 {
	// 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)
}

VNICProfileClient defines the methods related to dealing with virtual NIC profiles.

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL