content

package
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package content manages the cluster-wide content library for VirtoMir (ADR-0063). This file implements zero-touch machine deployment from any library item (template, cloud image, ISO) on any cluster host without manual copying.

Package content manages the cluster-wide content library for VirtoMir (ADR-0063). This file implements cluster-wide replication of library definitions and automatic propagation of new versions to subscribed hosts.

Package content manages the cluster-wide content library for VirtoMir (ADR-0063). This file implements resumable, checksum-verified file transfers between cluster peers.

Package content manages the cluster-wide content library for VirtoMir (ADR-0063). It maintains a versioned catalog of VM templates, installation ISOs, and cloud images, tracking metadata, SHA-256 checksums, storage pools, and host synchronization configurations across cluster nodes.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("not found")
	ErrInvalid  = errors.New("invalid")
	ErrConflict = errors.New("conflict")
)

Classed errors for API and operational mapping (404 Not Found, 422 Unprocessable Entity, 409 Conflict).

View Source
var ErrChecksumMismatch = errors.New("checksum mismatch")

ErrChecksumMismatch indicates that a downloaded item version does not match its expected SHA-256 digest.

View Source
var (
	// ErrRefused indicates that an operation was refused because the state or configuration is inappropriate.
	ErrRefused = errors.New("refused")
)

Functions

func Deploy

func Deploy(
	ctx context.Context,
	client *virt.Client,
	store *Store,
	peers PeerResolver,
	req DeployRequest,
	selfHostID string,
	report func(string),
) (string, error)

Deploy deploys a machine from any library item (template, cloud image, ISO) on any cluster host.

func DetectDiskFormat

func DetectDiskFormat(path string, fallback string) string

DetectDiskFormat inspects the first 4 bytes of path to recognize qcow2 magic bytes, falling back to the specified fallback or "raw".

func DownloadPath

func DownloadPath(itemID, versionID string) string

DownloadPath returns the canonical API endpoint path for downloading a content version.

func HasDeployHooks

func HasDeployHooks(ctx context.Context) bool

HasDeployHooks reports whether deployHooks are attached to ctx.

func HasDomainLookupHook

func HasDomainLookupHook(ctx context.Context) bool

HasDomainLookupHook checks if a custom domain lookup hook is attached to ctx.

func HasVolumeListHook

func HasVolumeListHook(ctx context.Context) bool

HasVolumeListHook checks if a custom volume list hook is attached to ctx.

func PruneLocalFile

func PruneLocalFile(targetPoolPath, itemName, versionStr, format string) error

PruneLocalFile deletes the local volume file when an older version is pruned.

func Pull

func Pull(ctx context.Context, peer *cluster.Peer, item Item, version ItemVersion, targetPoolPath string, report func(string)) (string, error)

Pull downloads a content item version from a cluster peer into targetPoolPath with resume support and SHA-256 verification.

func RandomHex

func RandomHex(bytes int) string

RandomHex returns a cryptographically random hexadecimal string of length 2*bytes.

func ReplicateToMembers

func ReplicateToMembers(ctx context.Context, cl *cluster.Store, peers PeerResolver, user, role, token, method, path string, body any) []string

ReplicateToMembers repeats a content library definition change on all other cluster members. It skips replication if the host is standalone or if ?local=1 is already set. It iterates over all cluster members except self, calling each peer at path+"?local=1" via peer.As(user, role, token).Call() with a 10s timeout. It logs warnings on unreachable members and returns a list of failed member names.

func SanitizeDomain

func SanitizeDomain(x *libvirtxml.Domain)

SanitizeDomain applies in-place portability sanitization to a libvirtxml.Domain struct.

func SanitizeDomainXML

func SanitizeDomainXML(doc string) (string, error)

SanitizeDomainXML sanitizes domain XML for portable distribution across hosts: strips UUID/ID/HWUUID/GenID, drops MAC addresses and targets from <interface> elements, removes <nvram> path references (while preserving template attributes), resets graphics ports to automatic, and removes fixed PCI/bus slot addresses.

func ServeContent

func ServeContent(w http.ResponseWriter, r *http.Request, filePath string, totalSize int64)

ServeContent streams a file to the response writer, honoring HTTP Range requests for resumable downloads.

func StreamFileSHA256

func StreamFileSHA256(ctx context.Context, path string) (checksum string, size int64, err error)

StreamFileSHA256 streams the file at path through sha256.New() via io.Copy with context cancellation check. It returns the hex-encoded checksum and the exact byte size.

func WithDeployHooks

func WithDeployHooks(ctx context.Context, h *deployHooks) context.Context

WithDeployHooks attaches custom deployHooks to ctx for unit testing.

func WithDomainLookup

func WithDomainLookup(ctx context.Context, fn domainLookupFunc) context.Context

WithDomainLookup attaches a custom domain lookup function to ctx for testing.

func WithVolumeList

func WithVolumeList(ctx context.Context, fn volumeListFunc) context.Context

WithVolumeList attaches a custom volume list function to ctx for testing.

Types

type DeployRequest

type DeployRequest struct {
	ItemID    string          `json:"itemId"`
	VersionID string          `json:"versionId,omitempty"`
	Name      string          `json:"name"`
	Pool      string          `json:"pool"`
	Network   string          `json:"network,omitempty"`
	VCPUs     int             `json:"vcpus,omitempty"`
	MemoryMiB uint64          `json:"memoryMiB,omitempty"`
	DiskGiB   uint64          `json:"diskGiB,omitempty"`
	CloudInit *virt.CloudInit `json:"cloudInit,omitempty"`
	Start     bool            `json:"start"`
}

DeployRequest specifies parameters for deploying a new machine from a content library item.

type HostConfig

type HostConfig struct {
	HostID     string `json:"hostId"`
	TargetPool string `json:"targetPool"`
	AutoSync   bool   `json:"autoSync"`
}

HostConfig stores per-host subscription and storage target preferences.

type HostSyncState

type HostSyncState struct {
	Host    string    `json:"host"`
	State   string    `json:"state"` // synced, syncing, failed, pending
	Error   string    `json:"error,omitempty"`
	Updated time.Time `json:"updated,omitempty"`
}

HostSyncState represents the synchronization state of an item on a specific cluster host.

type Item

type Item struct {
	ID           string          `json:"id"`
	Name         string          `json:"name"`
	Type         ItemType        `json:"type"`
	Description  string          `json:"description,omitempty"`
	SourceHost   string          `json:"sourceHost"`
	KeepVersions int             `json:"keepVersions"`
	SyncPolicy   SyncPolicy      `json:"syncPolicy"`
	Created      time.Time       `json:"created"`
	Updated      time.Time       `json:"updated"`
	Versions     []ItemVersion   `json:"versions"`
	Hosts        []HostSyncState `json:"hosts,omitempty"`
}

Item represents a catalog entry in the content library.

func PublishArtifact

func PublishArtifact(store *Store, item Item, version ItemVersion) (Item, error)

PublishArtifact registers or updates a content library item and its version directly. If an item with matching name or ID exists, the version is appended; otherwise a new item is created.

func PublishTemplate

func PublishTemplate(ctx context.Context, client *virt.Client, store *Store, selfHostID string, req PublishTemplateReq) (Item, error)

PublishTemplate publishes a local VM template to the content library catalog.

func PublishVolume

func PublishVolume(ctx context.Context, client *virt.Client, store *Store, selfHostID string, req PublishVolumeReq) (Item, error)

PublishVolume publishes a local storage volume (ISO or cloud image) to the content library catalog.

func (Item) LatestVersion

func (it Item) LatestVersion() *ItemVersion

LatestVersion returns the version with the newest Created timestamp, or nil when the item has no versions. Version slices are not guaranteed to be time-ordered, so callers must use this instead of indexing the last element. On equal timestamps the last element wins, matching the historical behaviour for items persisted without per-version times.

type ItemType

type ItemType string

ItemType classifies a content library item.

const (
	// TypeTemplate represents a virtual machine template.
	TypeTemplate ItemType = "template"
	// TypeISO represents an installation ISO or bootable image.
	TypeISO ItemType = "iso"
	// TypeImage represents a pre-installed cloud image (e.g. qcow2).
	TypeImage ItemType = "image"
)

type ItemVersion

type ItemVersion struct {
	ID          string    `json:"id"`
	Version     string    `json:"version"`
	Description string    `json:"description,omitempty"`
	SHA256      string    `json:"sha256"`
	Size        int64     `json:"size"`
	Format      string    `json:"format"`
	SourceHost  string    `json:"sourceHost"`
	SourcePool  string    `json:"sourcePool,omitempty"`
	SourceVol   string    `json:"sourceVol,omitempty"`
	TemplateXML string    `json:"templateXml,omitempty"`
	Created     time.Time `json:"created"`
}

ItemVersion represents a specific immutable version of a library item.

type MapPeerResolver

type MapPeerResolver map[string]*cluster.Peer

MapPeerResolver adapts a map[string]*cluster.Peer to the PeerResolver interface.

func (MapPeerResolver) PeerFor

func (m MapPeerResolver) PeerFor(hostID string) (*cluster.Peer, bool)

PeerFor looks up the peer for hostID.

type PeerCaller

type PeerCaller interface {
	Call(ctx context.Context, method, path string, in, out any) error
}

PeerCaller sends an RPC request to a cluster peer.

type PeerResolver

type PeerResolver interface {
	PeerFor(hostID string) (*cluster.Peer, bool)
}

PeerResolver resolves a cluster host ID to an active peer connection.

type PublishTemplateReq

type PublishTemplateReq struct {
	TemplateUUID string     `json:"templateUuid"`
	Name         string     `json:"name"`
	Version      string     `json:"version"`
	Description  string     `json:"description,omitempty"`
	KeepVersions int        `json:"keepVersions,omitempty"`
	SyncPolicy   SyncPolicy `json:"syncPolicy,omitempty"`
}

PublishTemplateReq specifies parameters for publishing an existing local VM template to the content library.

type PublishVolumeReq

type PublishVolumeReq struct {
	Pool         string     `json:"pool"`
	Volume       string     `json:"volume"`
	Type         ItemType   `json:"type"`
	Name         string     `json:"name"`
	Version      string     `json:"version"`
	Description  string     `json:"description,omitempty"`
	KeepVersions int        `json:"keepVersions,omitempty"`
	SyncPolicy   SyncPolicy `json:"syncPolicy,omitempty"`
}

PublishVolumeReq specifies parameters for publishing a storage volume to the content library.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store manages the persistence and lifecycle of content library items and per-host configs.

func Open

func Open(path string) (*Store, error)

Open loads or initializes the content library store from the given JSON file path. If the path is empty, an in-memory store is returned. Missing file returns an empty store without error.

func (*Store) AddVersion

func (s *Store) AddVersion(itemID string, v ItemVersion) (Item, []string, error)

AddVersion appends a new version to an item and automatically prunes older versions beyond KeepVersions. It returns the updated Item, the list of pruned version IDs, and any error encountered.

func (*Store) CreateItem

func (s *Store) CreateItem(item Item) (Item, error)

CreateItem validates and registers a new content library item. It generates a 16-hex ID if empty, ensures KeepVersions >= 1 (defaults to 3), and rejects duplicate names or invalid item types.

func (*Store) DeleteItem

func (s *Store) DeleteItem(id string) error

DeleteItem removes an item from the store. Returns ErrNotFound if missing.

func (*Store) DeleteVersion

func (s *Store) DeleteVersion(itemID, versionID string) error

DeleteVersion deletes a specific version from an item. Returns ErrNotFound if the item or version is missing, and refuses deletion if it is the only version.

func (*Store) GetHostConfig

func (s *Store) GetHostConfig(hostID string) (HostConfig, bool)

GetHostConfig retrieves storage and auto-sync preferences for a host.

func (*Store) GetItem

func (s *Store) GetItem(id string) (Item, bool)

GetItem retrieves an item by its ID.

func (*Store) ListHostConfigs

func (s *Store) ListHostConfigs() []HostConfig

ListHostConfigs returns all saved host configurations sorted by host ID.

func (*Store) ListItems

func (s *Store) ListItems() []Item

ListItems returns all catalog items sorted by name.

func (*Store) SetHostConfig

func (s *Store) SetHostConfig(cfg HostConfig) error

SetHostConfig saves the storage and auto-sync preferences for a host.

func (*Store) SetHostSyncState

func (s *Store) SetHostSyncState(itemID string, state HostSyncState) (Item, error)

SetHostSyncState updates or appends the sync state for a host on an item.

func (*Store) UpdateItem

func (s *Store) UpdateItem(item Item) (Item, error)

UpdateItem updates name, description, keepVersions, syncPolicy, versions, and hosts of an existing item.

type SyncManager

type SyncManager struct {
	// contains filtered or unexported fields
}

SyncManager manages automated synchronization of content library items across cluster hosts.

func NewSyncManager

func NewSyncManager(store *Store, jm *jobs.Manager, client *virt.Client, cl *cluster.Store, peers PeerResolver, log *slog.Logger) *SyncManager

NewSyncManager creates a SyncManager responsible for cluster-wide content synchronization.

func (*SyncManager) IsSubscribed

func (m *SyncManager) IsSubscribed(hostID string, item Item) bool

IsSubscribed reports whether hostID is subscribed to item and has a configured TargetPool in HostConfig.

func (*SyncManager) OnItemUpdated

func (m *SyncManager) OnItemUpdated(ctx context.Context, item Item, selfID string)

OnItemUpdated checks whether selfID is subscribed to item and triggers an automated sync job if the newest version is not yet present in the local TargetPool.

func (*SyncManager) Reconcile

func (m *SyncManager) Reconcile(ctx context.Context, selfID string)

Reconcile sweeps all items in store and triggers OnItemUpdated for each subscribed item where the newest version is missing locally and not currently syncing.

func (*SyncManager) SetPeers

func (m *SyncManager) SetPeers(peers PeerResolver)

SetPeers configures the peer resolver used to connect to cluster hosts.

func (*SyncManager) SetPoolPathResolver

func (m *SyncManager) SetPoolPathResolver(fn func(poolName string) (string, error))

SetPoolPathResolver configures a custom pool path resolution function (useful for tests).

func (*SyncManager) SetRefreshPoolHook

func (m *SyncManager) SetRefreshPoolHook(fn func(poolName string) error)

SetRefreshPoolHook configures a custom storage pool refresh hook (useful for tests).

func (*SyncManager) Start

func (m *SyncManager) Start(ctx context.Context)

Start starts periodic content reconciliation in the background.

func (*SyncManager) StartPeriodicReconcile

func (m *SyncManager) StartPeriodicReconcile(ctx context.Context, selfID string, interval time.Duration)

StartPeriodicReconcile triggers Reconcile immediately and then periodically at interval until ctx is cancelled.

type SyncMode

type SyncMode string

SyncMode determines how an item is synchronized across cluster hosts.

const (
	// SyncAll synchronizes this item to all cluster hosts automatically.
	SyncAll SyncMode = "all"
	// SyncSelected synchronizes this item to a specific list of hosts.
	SyncSelected SyncMode = "selected"
	// SyncManual replicates this item only on-demand.
	SyncManual SyncMode = "manual"
)

type SyncPolicy

type SyncPolicy struct {
	Mode  SyncMode `json:"mode"`
	Hosts []string `json:"hosts,omitempty"`
}

SyncPolicy defines replication rules for a content library item.

Jump to

Keyboard shortcuts

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