ovirtclient

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2021 License: BSD-3-Clause Imports: 18 Imported by: 2

README

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

⚠⚠⚠ This library is work-in-progress. Do not use. ⚠⚠⚠

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-ovirt-client"

func main() {
    // Create a logger that logs to the standard Go log here:
    logger := ovirtclient.NewGoLogLogger()
    // 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",
        // Provide the path to the CA certificate here:
        "/path/to/ca.crt",
        // Alternatively, provide the certificate directly:
        []byte("ca-cert-here in PEM format"),
        // Disable certificate verification. This is a bad idea:
        false,
        // Extra headers map:
        map[string]string{},
        logger,
    )
    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

This library also provides a test helper for integration testing against the oVirt engine. It allows for automatically discovering a usable storage domain, host, clusters, etc:

package main

import (
  "os"
  "testing"

  "github.com/ovirt/go-ovirt-client"
)

func TestSomething(t *testing.T) {
    // Create a logger that logs to the standard Go log here:
    logger := ovirtclient.NewGoTestLogger(t)
    // Set to true to use in-memory mock, see below
    mock := false
    // Create the test helper
    helper, err := ovirtclient.NewTestHelper(
        os.Getenv("OVIRT_URL"),
        os.Getenv("OVIRT_USER"),
        os.Getenv("OVIRT_PASSWORD"),
        os.Getenv("OVIRT_CAFILE"),
        []byte(os.Getenv("OVIRT_CABUNDLE")),
        os.Getenv("OVIRT_INSECURE") != "",
        os.Getenv("OVIRT_CLUSTER_ID"),
        os.Getenv("OVIRT_BLANK_TEMPLATE_ID"),
        os.Getenv("OVIRT_STORAGE_DOMAIN_ID"),
        mock,
        logger,
    )
    if err != nil {
        t.Fatal(err)
    }
    // Fetch the cluster ID for testing
    clusterID := helper.GetClusterID()
    //...
}

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

Index

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 Client

type Client interface {
	// GetURL returns the oVirt engine base URL.
	GetURL() string

	DiskClient
	VMClient
	ClusterClient
	StorageDomainClient
	HostClient
	TemplateClient
}

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 request 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,
	caFile string,
	caCert []byte,
	insecure bool,
	extraHeaders map[string]string,
	logger Logger,
) (ClientWithLegacySupport, error)

New creates a new copy of the enhanced oVirt client.

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() ([]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) (Cluster, error)
}

ClusterClient is a part of the Client that deals with clusters in the oVirt Engine.

type Disk

type Disk interface {
	ID() string
	Alias() string
	ProvisionedSize() uint64
	Format() ImageFormat
	StorageDomainID() string
}

type DiskClient

type DiskClient interface {
	// UploadImage 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:
	//
	// - ctx: this context can be used to abort the upload if it takes too long.
	// - 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.
	//
	// 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(
		ctx context.Context,
		alias string,
		storageDomainID string,
		sparse bool,
		size uint64,
		reader io.Reader,
	) (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(
		ctx context.Context,
		alias string,
		storageDomainID string,
		sparse bool,
		size uint64,
		reader io.Reader,
	) (UploadImageResult, error)

	// ListDisks lists all disks.
	ListDisks() ([]Disk, error)
	// GetDisk fetches a disk with a specific ID from the
	GetDisk(diskID string) (Disk, error)
	// RemoveDisk removes a disk with a specific ID.
	RemoveDisk(diskID string) error
}

type Host

type Host interface {
	ID() string
	ClusterID() string
	Status() HostStatus
}

Host is the representation of a host returned from the oVirt Engine API.

type HostClient

type HostClient interface {
	ListHosts() ([]Host, error)
	GetHost(id string) (Host, error)
}

HostClient contains the API portion that deals with hosts.

type HostStatus

type HostStatus string
const (
	HostStatusConnecting              HostStatus = "connecting"
	HostStatusDown                    HostStatus = "down"
	HostStatusError                   HostStatus = "error"
	HostStatusInitializing            HostStatus = "initializing"
	HostStatusInstallFailed           HostStatus = "install_failed"
	HostStatusInstalling              HostStatus = "installing"
	HostStatusInstallingOS            HostStatus = "installing_os"
	HostStatusKDumping                HostStatus = "kdumping"
	HostStatusMaintenance             HostStatus = "maintenance"
	HostStatusNonOperational          HostStatus = "non_operational"
	HostStatusNonResponsive           HostStatus = "non_responsive"
	HostStatusPendingApproval         HostStatus = "pending_approval"
	HostStatusPreparingForMaintenance HostStatus = "preparing_for_maintenance"
	HostStatusReboot                  HostStatus = "reboot"
	HostStatusUnassigned              HostStatus = "unassigned"
	HostStatusUp                      HostStatus = "up"
)

type ImageFormat

type ImageFormat string

ImageFormat is a constant for representing the format that images can be in.

const (
	ImageFormatCow ImageFormat = "cow"
	ImageFormatRaw ImageFormat = "raw"
)

type Logger

type Logger interface {
	Log(v ...interface{})
	Logf(format string, v ...interface{})
}

func NewGoLogLogger

func NewGoLogLogger() Logger

func NewGoTestLogger

func NewGoTestLogger(t *testing.T) Logger

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 StorageDomain

type StorageDomain interface {
	ID() string
	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() ([]StorageDomain, error)
	GetStorageDomain(id string) (StorageDomain, error)
}

StorageDomainClient contains the portion of the goVirt API that deals with storage domains.

type StorageDomainExternalStatus

type StorageDomainExternalStatus string
const (
	StorageDomainExternalStatusNA      StorageDomainExternalStatus = ""
	StorageDomainExternalStatusError   StorageDomainExternalStatus = "error"
	StorageDomainExternalStatusFailure StorageDomainExternalStatus = "failure"
	StorageDomainExternalStatusInfo    StorageDomainExternalStatus = "info"
	StorageDomainExternalStatusOk      StorageDomainExternalStatus = "ok"
	StorageDomainExternalStatusWarning StorageDomainExternalStatus = "warning"
)

type StorageDomainStatus

type StorageDomainStatus string
const (
	StorageDomainStatusActivating              StorageDomainStatus = "activating"
	StorageDomainStatusActive                  StorageDomainStatus = "active"
	StorageDomainStatusDetaching               StorageDomainStatus = "detaching"
	StorageDomainStatusInactive                StorageDomainStatus = "inactive"
	StorageDomainStatusLocked                  StorageDomainStatus = "locked"
	StorageDomainStatusMaintenance             StorageDomainStatus = "maintenance"
	StorageDomainStatusMixed                   StorageDomainStatus = "mixed"
	StorageDomainStatusPreparingForMaintenance StorageDomainStatus = "preparing_for_maintenance"
	StorageDomainStatusUnattached              StorageDomainStatus = "unattached"
	StorageDomainStatusUnknown                 StorageDomainStatus = "unknown"
	StorageDomainStatusNA                      StorageDomainStatus = ""
)

type Template

type Template interface {
	ID() string
	Name() string
	Description() string
}

type TemplateClient

type TemplateClient interface {
	ListTemplates() ([]Template, error)
	GetTemplate(id string) (Template, error)
}

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
}

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,
	insecure bool,
	caFile string,
	caBundle []byte,
	clusterID string,
	blankTemplateID string,
	storageDomainID string,
	mock bool,
	logger Logger,
) TestHelper

func NewTestHelper

func NewTestHelper(
	url string,
	username string,
	password string,
	caFile string,
	caBundle []byte,
	insecure bool,
	clusterID string,
	blankTemplateID string,
	storageDomainID string,
	mock bool,
	logger Logger,
) (TestHelper, error)

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() Disk
	CorrelationID() string
}

type VMBlockDevice

type VMBlockDevice interface {
	DiskID() string
	Bootable() bool

	StorageDomainID() string
}

type VMCPUTopo

type VMCPUTopo interface {
	Cores() uint
	Threads() uint
	Sockets() uint
}

func MustNewVMCPUTopo

func MustNewVMCPUTopo(cores uint, threads uint, sockets uint) VMCPUTopo

MustNewVMCPUTopo is identical to NewVMCPUTopo, but panics instead of returning an error if cores, threads, or sockets is zero.

func NewVMCPUTopo

func NewVMCPUTopo(cores uint, threads uint, sockets uint) (VMCPUTopo, error)

NewVMCPUTopo creates a new CPU topology with the given parameters. It returns an error if cores, threads, or sockets is 0. If the parameters are guaranteed to be non-zero MustNewVMCPUTopo should be used.

type VMClient

type VMClient interface {
	CreateVM(
		ctx context.Context,
		clusterID string,
		cpuTopo VMCPUTopo,
		templateID string,
		blockDevices []VMBlockDevice,
	)
}

Jump to

Keyboard shortcuts

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