types

package
v3.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: AGPL-3.0 Imports: 25 Imported by: 8

Documentation

Index

Constants

View Source
const UserAgentNotifier = "lxd-cluster-notifier"

UserAgentNotifier is the user agent used for cluster wide notifications. It's using the "lxd-" prefix for backwards compatibility with older cluster members as originally the constant from LXD's client package was used.

Variables

View Source
var EmptySyncResponse = &syncResponse{success: true, metadata: make(map[string]any)}

EmptySyncResponse represents an empty success response.

Functions

func ContextWithLogger

func ContextWithLogger(ctx context.Context, logger ...*slog.Logger) context.Context

ContextWithLogger returns a new context with the given logger. If no logger is provided, the default logger is used.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError returns true if the error is considered a Not Found error.

func IsNotification

func IsNotification(r *http.Request) bool

IsNotification determines if this request is to be considered a cluster-wide notification.

func ParseResponse

func ParseResponse(resp *http.Response) (*api.Response, error)

ParseResponse takes an HTTP response, parses it and returns the extracted result.

func ResponseInit

func ResponseInit(smartErrors map[int][]error)

ResponseInit registers smart error mappings.

Types

type AddrPort

type AddrPort struct {
	netip.AddrPort
}

AddrPort is a wrapper for netip.AddrPort for which (json/yaml).(Marshaller/Unmarshaller) are implemented.

func ParseAddrPort

func ParseAddrPort(addrPortStr string) (AddrPort, error)

ParseAddrPort parses an IPv4/IPv6 address and port string into an AddrPort.

func (AddrPort) MarshalJSON

func (a AddrPort) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for the AddrPort type.

func (AddrPort) MarshalYAML

func (a AddrPort) MarshalYAML() (any, error)

MarshalYAML implements yaml.Marshaler for the AddrPort type. Note that for yaml we just need to return a yaml marshallable type (if we return []byte as in the json implementation it is written as an int array).

func (AddrPort) String

func (a AddrPort) String() string

String returns the string representation of the AddrPort, or an empty string if it is empty.

func (*AddrPort) UnmarshalJSON

func (a *AddrPort) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler for AddrPort.

func (*AddrPort) UnmarshalYAML

func (a *AddrPort) UnmarshalYAML(unmarshal func(v any) error) error

UnmarshalYAML implements yaml.Unmarshaler for AddrPort.

func (AddrPort) WithZone

func (a AddrPort) WithZone(zone string) AddrPort

WithZone returns an AddrPort that's the same as the receiver AddrPort but with the provided zone. If zone is empty, the zone is removed. If IP of AddrPort is an IPv4 address, WithZone is a no-op and returns AddrPort unchanged.

type AddrPorts

type AddrPorts []AddrPort

AddrPorts is a defined type for a slice of AddrPort. This facilitates convenience functions.

func ParseAddrPorts

func ParseAddrPorts(addrPortStrs []string) (AddrPorts, error)

ParseAddrPorts parses a list of IPv4/IPv6 address and port strings into an AddrPorts.

func (AddrPorts) Strings

func (a AddrPorts) Strings() []string

Strings returns a string slice of the AddrPorts.

type CertificateName

type CertificateName string

CertificateName represents the name of a certificate.

const (
	// ClusterCertificateName represents the name of the cluster certificate used by the core API.
	ClusterCertificateName CertificateName = "cluster"

	// ServerCertificateName represents the name of the identifying certificate of a cluster member.
	ServerCertificateName CertificateName = "server"
)

type Client

type Client interface {
	// Generic functions for the client interface.
	// They allow adding custom client functions.
	URL() *url.URL
	HTTP() *http.Client
	Query(ctx context.Context, method string, prefix EndpointPrefix, path *url.URL, in any, out any) error
	QueryRaw(ctx context.Context, method string, prefix EndpointPrefix, path *url.URL, in any) (*http.Response, error)
	Websocket(ctx context.Context, prefix EndpointPrefix, path *url.URL) (*websocket.Conn, error)

	// Microcluster specific client functions.
	SetClusterNotification()
	UseTarget(name string) Client
}

Client represents a client allowing to communicate with a specific cluster member.

type Clients

type Clients []Client

Clients represents a list of clients allowing to communicate with multiple cluster members.

func (Clients) Query

func (c Clients) Query(ctx context.Context, concurrent bool, query func(context.Context, Client) error) error

Query executes the given hook across all members of the cluster.

type ClusterCertificatePut

type ClusterCertificatePut struct {
	PublicKey  string `json:"public_key"  yaml:"public_key"`
	PrivateKey string `json:"private_key" yaml:"private_key"`
	CA         string `json:"ca"          yaml:"ca"`
}

ClusterCertificatePut represents the content of a new cluster keypair and CA.

type ClusterMember

type ClusterMember struct {
	ClusterMemberLocal
	Role                  string       `json:"role" yaml:"role"`
	SchemaInternalVersion uint64       `json:"schema_internal_version" yaml:"schema_internal_version"`
	SchemaExternalVersion uint64       `json:"schema_external_version" yaml:"schema_external_version"`
	LastHeartbeat         time.Time    `json:"last_heartbeat" yaml:"last_heartbeat"`
	Status                MemberStatus `json:"status" yaml:"status"`
	Extensions            Extensions   `json:"extensions" yaml:"extensions"`
	Secret                string       `json:"secret" yaml:"secret"`
}

ClusterMember represents information about a dqlite cluster member.

type ClusterMemberLocal

type ClusterMemberLocal struct {
	Name        string          `json:"name" yaml:"name"`
	Address     AddrPort        `json:"address" yaml:"address"`
	Certificate X509Certificate `json:"certificate" yaml:"certificate"`
}

ClusterMemberLocal represents local information about a new cluster member.

type Connector

type Connector interface {
	// Cluster returns a client to every cluster member according to dqlite.
	Cluster(isNotification bool) (Clients, error)

	// Leader returns a client to the dqlite cluster leader.
	Leader(isNotification bool) (Client, error)

	// Member returns a client to the specified member.
	Member(url *url.URL, isNotification bool, cert *x509.Certificate) (Client, error)

	// RandomMember returns a client to a random member.
	RandomMember(isNotification bool) (Client, error)
}

Connector represents various entry points to communicate with specific or multiple cluster members.

type Control

type Control struct {
	Bootstrap  bool              `json:"bootstrap" yaml:"bootstrap"`
	InitConfig map[string]string `json:"config" yaml:"config"`
	JoinToken  string            `json:"join_token" yaml:"join_token"`
	Address    AddrPort          `json:"address" yaml:"address"`
	Name       string            `json:"name" yaml:"name"`
}

Control represents the arguments that can be used to initialize/shutdown the daemon.

type CtxKey

type CtxKey string
const CtxLogger CtxKey = "logger"

CtxLogger is the name of the context value for the central logger.

type DB

type DB interface {
	// Transaction handles performing a transaction on the dqlite database.
	Transaction(outerCtx context.Context, f func(context.Context, *sql.Tx) error) error

	// Leader returns a client connected to the leader of the dqlite cluster.
	Leader(ctx context.Context) (*dqliteClient.Client, error)

	// Cluster returns information about dqlite cluster members.
	Cluster(ctx context.Context, client *dqliteClient.Client) ([]dqliteClient.NodeInfo, error)

	// Status returns the current status of the database.
	Status() DatabaseStatus

	// IsOpen returns nil  only if the DB has been opened and the schema loaded.
	// Otherwise, it returns an error describing why the database is offline.
	// The returned error may have the http status 503, indicating that the database is in a valid but unavailable state.
	IsOpen(ctx context.Context) error

	// SchemaVersion returns the current internal and external schema version, as well as all API extensions in memory.
	SchemaVersion() (versionInternal uint64, versionExternal uint64, apiExtensions Extensions)
}

DB exposes the internal database for use with external projects.

type DaemonConfig

type DaemonConfig struct {
	Name          string                  `json:"name" yaml:"name"`
	Address       AddrPort                `json:"address" yaml:"address"`
	Servers       map[string]ServerConfig `json:"servers" yaml:"servers"`
	FailureDomain uint64                  `json:"failure-domain" yaml:"failure-domain"`
}

DaemonConfig is the in memory version of the local daemon.yaml file.

type DaemonConfigPatch added in v3.0.3

type DaemonConfigPatch struct {
	Servers       *map[string]ServerConfig `json:"servers,omitempty" yaml:"servers,omitempty"`
	FailureDomain *uint64                  `json:"failure-domain,omitempty" yaml:"failure-domain,omitempty"`
}

DaemonConfigPatch is the request body for PATCH /core/1.0/daemon/config. Optional fields preserve existing values when omitted.

type DatabaseStatus

type DatabaseStatus string

DatabaseStatus is the current status of the database.

const (
	// DatabaseReady indicates the database is open for use.
	DatabaseReady DatabaseStatus = "Database is online"

	// DatabaseWaiting indicates the database is blocked on a schema or API extension upgrade.
	DatabaseWaiting DatabaseStatus = "Database is waiting for an upgrade"

	// DatabaseStarting indicates the daemon is running, but dqlite is still in the process of starting up.
	DatabaseStarting DatabaseStatus = "Database is still starting"

	// DatabaseNotReady indicates the database is not yet ready for use.
	DatabaseNotReady DatabaseStatus = "Database is not yet initialized"

	// DatabaseOffline indicates that the database is offline.
	DatabaseOffline DatabaseStatus = "Database is offline"
)

type DqliteMember

type DqliteMember struct {
	// dqlite.NodeInfo fields
	DqliteID uint64 `json:"id" yaml:"id"`
	Address  string `json:"address" yaml:"address"`
	Role     string `json:"role" yaml:"role"`

	Name string `json:"name" yaml:"name"`
}

DqliteMember is the information that can be derived locally about a cluster member without access to the dqlite database.

func (DqliteMember) NodeInfo

func (m DqliteMember) NodeInfo() (*dqlite.NodeInfo, error)

NodeInfo is used for interop with go-dqlite.

type Endpoint

type Endpoint struct {
	Name    string          // Name for this endpoint.
	Path    string          // Path pattern for this endpoint.
	Aliases []EndpointAlias // Any aliases for this endpoint.
	Get     EndpointAction
	Put     EndpointAction
	Post    EndpointAction
	Delete  EndpointAction
	Patch   EndpointAction

	AllowedDuringShutdown bool // Whether we should return Unavailable Error (503) if daemon is shutting down.
	AllowedBeforeInit     bool // Whether we should return Unavailabel Error (503) if the daemon has not been initialized (is not yet part of a cluster).
}

Endpoint represents a URL in our API.

type EndpointAction

type EndpointAction struct {
	Handler        func(state State, r *http.Request) Response
	AccessHandler  func(state State, r *http.Request) (trusted bool, resp Response)
	AllowUntrusted bool
	ProxyTarget    bool // Allow forwarding of the request to a target if ?target=name is specified.
}

EndpointAction represents an action on an API endpoint.

type EndpointAlias

type EndpointAlias struct {
	Name string // Name for this alias.
	Path string // Path pattern for this alias.
}

EndpointAlias represents an alias URL of and Endpoint in our API.

type EndpointPrefix

type EndpointPrefix string

EndpointPrefix is a type specifying the endpoint on which the resource exists.

const (
	// PublicEndpoint - All external endpoints.
	PublicEndpoint EndpointPrefix = "core/1.0"

	// InternalEndpoint - All internal endpoints.
	InternalEndpoint EndpointPrefix = "core/internal"

	// ControlEndpoint - All internal endpoints available on the local unix socket.
	ControlEndpoint EndpointPrefix = "core/control"
)

type Extensions

type Extensions []string

Extensions represents a registry of extensions.

`internal` extensions are related to MicroCluster capabilities, not capabilities of MicroCluster-backed services.

To distinguish between `internal` and `external` extensions, `internal` extensions are prefixed with a `internal:` value. e.g, `internal:runtime_extension_v1`, `internal:runtime_extension_v2`, ...

External extensions are related to capabilities of MicroCluster-backed services. e.g, `microovn_custom_encapsulation_ip`.

func NewExtensionRegistry

func NewExtensionRegistry(populateInternal bool) (Extensions, error)

NewExtensionRegistry creates a new instance of the Extensions struct, which represents a registry of extensions. We have the option to populate the internal extensions or not. Having s option becomes handy when we want to create a custom registry of extensions (see `NewExtensionRegistryFromList`).

func NewExtensionRegistryFromList

func NewExtensionRegistryFromList(extensions []string) (Extensions, error)

NewExtensionRegistryFromList creates a new instance of the Extensions struct, from a list of extensions. The passed extensions could be internal or external or just invalid. The function is typically used to create a registry from an API response in order to compare the source and the target systems' extensions for compatibility. The returned registry is always sorted with internal extensions first.

func (Extensions) HasExtension

func (e Extensions) HasExtension(ext string) bool

HasExtension reports whether the extension set supports the given extension.

func (Extensions) IsSameVersion

func (e Extensions) IsSameVersion(t Extensions) error

IsSameVersion checks if the source registry supports the target registry.

func (Extensions) MarshalJSON

func (e Extensions) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for the Extensions type.

func (Extensions) MarshalYAML

func (e Extensions) MarshalYAML() (any, error)

MarshalYAML implements yaml.Marshaler for the Extensions type.

func (*Extensions) Register

func (e *Extensions) Register(newExtensions []string) error

Register registers new external extensions to the Extensions struct.

func (*Extensions) Scan

func (e *Extensions) Scan(value any) error

Scan implements the sql.Scanner interface to deserialize the Extensions struct from database storage.

func (*Extensions) UnmarshalJSON

func (e *Extensions) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Extensions) UnmarshalYAML

func (e *Extensions) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface.

func (Extensions) Value

func (e Extensions) Value() (driver.Value, error)

Value implements the driver.Valuer interface to serialize the Extensions struct for database storage.

func (Extensions) Version

func (e Extensions) Version() int

Version returns the number of extensions in the set, representing its version number.

type HeartbeatInfo

type HeartbeatInfo struct {
	BeginRound        bool                     `json:"begin_round"         yaml:"begin_round"`
	MaxSchemaInternal uint64                   `json:"max_schema_internal" yaml:"max_schema_internal"`
	MaxSchemaExternal uint64                   `json:"max_schema_external" yaml:"max_schema_external"`
	ClusterMembers    map[string]ClusterMember `json:"cluster_members"     yaml:"cluster_members"`
	LeaderAddress     string                   `json:"leader_address"      yaml:"leader_address"`
	DqliteRoles       map[string]string        `json:"dqlite_roles"        yaml:"dqlite_roles"`
}

HeartbeatInfo represents information about the cluster sent out by the leader of the cluster to other members. If BeginRound is set, a new heartbeat will initiate.

type HookNewMemberOptions

type HookNewMemberOptions struct {
	// Name is the name of the new cluster member that joined the cluster, triggering this hook.
	NewMember ClusterMemberLocal `json:"new_member" yaml:"new_member"`
}

HookNewMemberOptions holds configuration pertaining to the OnNewMember hook.

type HookRemoveMemberOptions

type HookRemoveMemberOptions struct {
	// Force represents whether to run the hook with the `force` option.
	Force bool `json:"force" yaml:"force"`
}

HookRemoveMemberOptions holds configuration pertaining to the PreRemove and PostRemove hooks.

type HookType

type HookType string

HookType represents the various types of hooks available to microcluster.

const (
	// OnStart is run after the daemon is started.
	OnStart HookType = "on-start"

	// PreBootstrap is run before the daemon is initialized and bootstrapped.
	PreBootstrap HookType = "pre-bootstrap"

	// PostBootstrap is run after the daemon is initialized and bootstrapped.
	PostBootstrap HookType = "post-bootstrap"

	// PreJoin is run after the daemon is initialized and joined the cluster but before existing members triggered
	// their 'OnNewMember' hooks.
	PreJoin HookType = "pre-join"

	// PostJoin is run after the daemon is initialized, joined the cluster and existing members triggered
	// their 'OnNewMember' hooks.
	PostJoin HookType = "post-join"

	// PreRemove is run on a cluster member just before it is removed from the cluster.
	PreRemove HookType = "pre-remove"

	// PostRemove is run on all other peers after one is removed from the cluster.
	PostRemove HookType = "post-remove"

	// OnNewMember is run on each peer after a new cluster member has joined and executed their 'PreJoin' hook.
	OnNewMember HookType = "on-new-member"

	// OnHeartbeat is run after a successful heartbeat round.
	OnHeartbeat HookType = "on-heartbeat"

	// OnDaemonConfigUpdate is run after the local daemon received a config update.
	OnDaemonConfigUpdate HookType = "on-daemon-config-update"
)

type Hooks

type Hooks struct {
	// PreInit is run before the daemon is initialized.
	PreInit func(ctx context.Context, s State, bootstrap bool, initConfig map[string]string) error

	// PostBootstrap is run after the daemon is initialized and bootstrapped.
	PostBootstrap func(ctx context.Context, s State, initConfig map[string]string) error

	// OnStart is run after the daemon is started. Its context will not be cancelled until the daemon is shutting down.
	OnStart func(ctx context.Context, s State) error

	// OnStop is run after the daemon is stopped. Its context is already cancelled but allows access to the logger.
	// The daemon will wait for this hook to complete before exiting.
	OnStop func(ctx context.Context, s State) error

	// PostJoin is run after the daemon is initialized, joined the cluster and existing members triggered
	// their 'OnNewMember' hooks.
	PostJoin func(ctx context.Context, s State, initConfig map[string]string) error

	// PreJoin is run after the daemon is initialized and joined the cluster but before existing members triggered
	// their 'OnNewMember' hooks.
	PreJoin func(ctx context.Context, s State, initConfig map[string]string) error

	// PreRemove is run on a cluster member just before it is removed from the cluster.
	PreRemove func(ctx context.Context, s State, force bool) error

	// PostRemove is run on all other peers after one is removed from the cluster.
	PostRemove func(ctx context.Context, s State, force bool) error

	// OnHeartbeat is run after a successful heartbeat round.
	OnHeartbeat func(ctx context.Context, s State, roleStatus map[string]RoleStatus) error

	// OnNewMember is run on each peer after a new cluster member has joined and executed their 'PreJoin' hook.
	OnNewMember func(ctx context.Context, s State, newMember ClusterMemberLocal) error

	// OnDaemonConfigUpdate is a post-action hook that is run on all cluster members when any cluster member receives a local configuration update.
	OnDaemonConfigUpdate func(ctx context.Context, s State, config DaemonConfig) error
}

Hooks holds customizable functions that can be called at varying points by the daemon to integrate with other tools.

type KeyPair

type KeyPair struct {
	Cert string `json:"cert" yaml:"cert"`
	Key  string `json:"key" yaml:"key"`
	CA   string `json:"ca" yaml:"ca"`
}

KeyPair holds a certificate together with its private key and optional CA.

type Location

type Location struct {
	Name    string   `yaml:"name"`
	Address AddrPort `yaml:"address"`
}

Location represents configurable identifying information about a remote.

type MemberStatus

type MemberStatus string

MemberStatus represents the online status of a cluster member.

const (
	// MemberOnline should be the MemberStatus when the node is online and reachable.
	MemberOnline MemberStatus = "ONLINE"

	// MemberUnreachable should be the MemberStatus when we were not able to connect to the node.
	MemberUnreachable MemberStatus = "UNREACHABLE"

	// MemberNotTrusted should be the MemberStatus when there is no local yaml entry for this node.
	MemberNotTrusted MemberStatus = "NOT TRUSTED"

	// MemberNotFound should be the MemberStatus when the node was not found in dqlite.
	MemberNotFound MemberStatus = "NOT FOUND"

	// MemberUpgrading should be the MemberStatus if the system is awaiting or performing a schema upgrade.
	MemberUpgrading MemberStatus = "UPGRADING"

	// MemberNeedsUpgrade should be the MemberStatus if the system needs to receive a schema upgrade to be compatible with other cluster members.
	MemberNeedsUpgrade MemberStatus = "NEEDS UPGRADE"
)

type OS

type OS interface {
	StateDir() string
	DatabaseDir() string
	TrustDir() string
	CertificatesDir() string
	DatabasePath() string
	ControlSocket() *url.URL
	ControlSocketPath() string
	IsControlSocketPresent() (bool, error)
	ServerCert() (*shared.CertInfo, error)
	ClusterCert() (*shared.CertInfo, error)
}

OS represents Microcluster's state on disk.

type Remote

type Remote struct {
	Location    `yaml:",inline"`
	Certificate X509Certificate `yaml:"certificate"`
}

Remote represents a yaml file with credentials to be read by the daemon.

func (*Remote) URL

func (r *Remote) URL() *url.URL

URL returns the parsed URL of the Remote.

type Resources

type Resources struct {
	PathPrefix EndpointPrefix
	Endpoints  []Endpoint
}

Resources represents all the resources served over the same path.

type Response

type Response interface {
	Render(w http.ResponseWriter, r *http.Request) error
	String() string
}

Response represents an API response.

func BadRequest

func BadRequest(err error) Response

BadRequest returns a bad request response (400) with the given error.

func ErrorResponse

func ErrorResponse(code int, msg string) Response

ErrorResponse returns an error response with the given code and msg.

func Forbidden

func Forbidden(err error) Response

Forbidden returns a forbidden response (403) with the given error.

func InternalError

func InternalError(err error) Response

InternalError returns an internal error response (500) with the given error.

func ManualResponse

func ManualResponse(hook func(w http.ResponseWriter) error) Response

ManualResponse creates a new manual response.

func NotFound

func NotFound(err error) Response

NotFound returns a not found response (404) with the given error.

func NotImplemented

func NotImplemented(err error) Response

NotImplemented returns a not implemented response (501) with the given error.

func SmartError

func SmartError(err error) Response

SmartError returns the right error message based on err. It uses the stdlib errors package to unwrap the error and find the cause.

func SyncResponse

func SyncResponse(success bool, metadata any) Response

SyncResponse returns a new syncResponse with the success and metadata fields set.

func Unauthorized

func Unauthorized(err error) Response

Unauthorized returns an unauthorized response (401) with the given error.

func Unavailable

func Unavailable(err error) Response

Unavailable returns an unavailable response (503) with the given error.

type RoleStatus

type RoleStatus struct {
	Old string
	New string
}

RoleStatus represents the previous and current role of a cluster member.

func (RoleStatus) RoleChanged

func (rs RoleStatus) RoleChanged() bool

RoleChanged returns whether there has been a role change.

type SQLBatch

type SQLBatch struct {
	Results []SQLResult
}

SQLBatch represents a batch of SQL results.

type SQLDump

type SQLDump struct {
	Text string `json:"text" yaml:"text"`
}

SQLDump represents the text of a SQL dump.

type SQLQuery

type SQLQuery struct {
	Query string `json:"query" yaml:"query"`
}

SQLQuery represents a SQL query.

type SQLResult

type SQLResult struct {
	Type         string   `json:"type" yaml:"type"`
	Columns      []string `json:"columns" yaml:"columns"`
	Rows         [][]any  `json:"rows" yaml:"rows"`
	RowsAffected int64    `json:"rows_affected" yaml:"rows_affected"`
}

SQLResult represents the result of executing a SQL command.

type Server

type Server struct {
	ServerConfig

	// CoreAPI determines whether the the resources of the server should be served over the default cluster API.
	CoreAPI bool

	// PreInit determines whether the Server should be available prior to initializing the daemon.
	PreInit bool

	// ServeUnix sets whether the resources of this endpoint should also be served over the unix socket.
	ServeUnix bool

	// DedicatedCertificate sets whether the additional listener should use its own self signed certificate.
	// If false it tries to use a custom certificate from the daemon's state `/certificates` directory
	// based on the name provided when creating the server.
	// In case there isn't any custom certificate it falls back to the cluster certificate of the core API.
	DedicatedCertificate bool

	// Resources is the list of resources offered by this server.
	Resources []Resources

	// DrainConnectionsTimeout is the amount of time to allow for all connections to drain when shutting down.
	// If it's 0, the connections are not drained when shutting down.
	DrainConnectionsTimeout time.Duration
}

Server contains configuration and handlers for additional listeners to be instantiated after app startup.

type ServerConfig

type ServerConfig struct {
	// Address is the server listen address.
	// Example: 127.0.0.1:9000
	Address AddrPort `json:"address" yaml:"address"`
}

ServerConfig represents the mutable fields of an additional network listener.

type State

type State interface {
	// Listen Address.
	Address() *url.URL

	// Name of the cluster member.
	Name() string

	// Version is provided by the MicroCluster consumer.
	Version() string

	// Server certificate is used for server-to-server connection.
	ServerCert() *shared.CertInfo

	// Cluster certificate is used for downstream connections within a cluster.
	ClusterCert() *shared.CertInfo

	// HasExtension returns whether the given API extension is supported.
	HasExtension(ext string) bool

	// ExtensionServers returns an immutable list of the daemon's additional listeners.
	ExtensionServers() []string

	// FileSystem structure.
	FileSystem() OS

	// Database.
	Database() DB

	// Local truststore access.
	Truststore() Store

	// Returns a connector for interconnection with the cluster.
	Connect() Connector
}

State exposes the internal daemon state for use with extended API handlers.

type Status

type Status struct {
	Name       string     `json:"name"    yaml:"name"`
	Address    AddrPort   `json:"address" yaml:"address"`
	Version    string     `json:"version" yaml:"version"`
	Ready      bool       `json:"ready"   yaml:"ready"`
	Extensions Extensions `json:"extensions" yaml:"extensions"`
}

Status represents server status information.

type Store

type Store interface {
	// A list of clients for each of the remotes.
	RemoteClients(isNotification bool, serverCert *shared.CertInfo, publicKey *x509.Certificate) (Clients, error)

	// All remotes keyed by their name.
	RemotesByName() map[string]Remote

	// A specific remote filtered by its address.
	RemoteByAddress(addrPort AddrPort) *Remote

	// All remotes' addresses keyed by their name.
	RemoteAddresses() map[string]AddrPort

	// All remotes' certificates keyed by their name.
	RemoteCertificates() map[string]X509Certificate

	// Same as RemoteCertificates but using the standard libraries type.
	RemoteCertificatesNative() map[string]x509.Certificate

	// The total amount of remotes in the truststore.
	Count() int

	// Add a new remote to the truststore.
	Add(dir string, remotes ...Remote) error

	// Replace remotes in the truststore.
	Replace(dir string, newRemotes ...ClusterMember) error
}

Store represents a local truststore.

type Token

type Token struct {
	// Secret is the underlying secret string used to authenticate the token.
	Secret string `json:"secret" yaml:"secret"`

	// Fingerprint is the fingerprint of the cluster certificate,
	// so that the joiner can verify that the public key of the cluster matches this request.
	Fingerprint string `json:"fingerprint" yaml:"fingerprint"`

	// JoinAddresses is the list of addresses of the existing cluster members that the joiner may supply the token to.
	// Internally, the first system to accept the token will forward it to the dqlite leader.
	JoinAddresses []AddrPort `json:"join_addresses" yaml:"join_addresses"`
}

Token holds the information that is presented to the joining node when requesting a token.

func DecodeToken

func DecodeToken(tokenString string) (*Token, error)

DecodeToken decodes a base64-encoded token string.

func (Token) String

func (t Token) String() (string, error)

type TokenRecord

type TokenRecord struct {
	Name      string    `json:"name" yaml:"name"`
	Token     string    `json:"token" yaml:"token"`
	ExpiresAt time.Time `json:"expires_at" yaml:"expires_at"`
}

TokenRecord represents the internal record of a join token.

type TokenRequest

type TokenRequest struct {
	Name        string        `json:"name" yaml:"name"`
	ExpireAfter time.Duration `json:"expire_after" yaml:"expire_after"`
}

TokenRequest holds information for requesting a join token.

type TokenResponse

type TokenResponse struct {
	// ClusterCert is the public key used across the cluster.
	ClusterCert X509Certificate `json:"cluster_cert" yaml:"cluster_cert"`

	// ClusterKey is the private key used across the cluster.
	ClusterKey string `json:"cluster_key" yaml:"cluster_key"`

	// ClusterMembers is the full list of cluster members that are currently present and available in the cluster.
	// The joiner supplies this list to dqlite so that it can start its database.
	ClusterMembers []ClusterMemberLocal `json:"cluster_members" yaml:"cluster_members"`

	// ClusterAdditionalCerts is the full list of certificates added for additional listeners.
	ClusterAdditionalCerts map[string]KeyPair

	// TrustedMember contains the address of the existing cluster member
	// who was dqlite leader at the time that the joiner supplied its join token.
	//
	// The trusted member will have already recorded the joiner's information in
	// its local truststore, and thus will trust requests from the joiner prior to fully joining.
	TrustedMember ClusterMemberLocal `json:"trusted_member" yaml:"trusted_member"`
}

TokenResponse holds the information for connecting to a cluster by a node with a valid join token.

type X509Certificate

type X509Certificate struct {
	*x509.Certificate
}

X509Certificate is a json/yaml marshallable/unmarshallable type wrapper for x509.Certificate.

func ParseX509Certificate

func ParseX509Certificate(certStr string) (*X509Certificate, error)

ParseX509Certificate decodes the given PEM encoded string and parses it into an X509Certificate.

func (X509Certificate) MarshalJSON

func (c X509Certificate) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for X509Certificate.

func (X509Certificate) MarshalYAML

func (c X509Certificate) MarshalYAML() (any, error)

MarshalYAML implements yaml.Marshaller for X509Certificate.

func (X509Certificate) String

func (c X509Certificate) String() string

String returns the x509.Certificate as a PEM encoded string.

func (*X509Certificate) UnmarshalJSON

func (c *X509Certificate) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler for X509Certificate.

func (*X509Certificate) UnmarshalYAML

func (c *X509Certificate) UnmarshalYAML(unmarshal func(v any) error) error

UnmarshalYAML implements yaml.Unmarshaler for X509Certificate.

Jump to

Keyboard shortcuts

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