localdb

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package localdb provides database models and operations for local nstance-server state.

Index

Constants

View Source
const (
	LBStatusPending      = "pending"
	LBStatusRegistered   = "registered"
	LBStatusDeregistered = "deregistered"
	LBStatusFailed       = "failed"
)

LBInstanceStatus represents the status of an instance's load balancer registration

Variables

This section is empty.

Functions

This section is empty.

Types

type DB

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

DB manages local SQLite database operations

func Open

func Open(file string) (*DB, error)

Open opens a SQLite database and initializes the schema

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection

func (*DB) CreateAgentRegistrationRecord

func (db *DB) CreateAgentRegistrationRecord(instanceID, nonce string, publicKeyPEM []byte) error

CreateAgentRegistrationRecord updates an existing instance record to mark it as registered

func (*DB) CreateInstance

func (db *DB) CreateInstance(instance *Instance) error

func (*DB) CreateOperatorRegistrationRecord

func (db *DB) CreateOperatorRegistrationRecord(clusterID, tenant, nonce string, publicKeyPEM []byte) error

CreateOperatorRegistrationRecord inserts a new record for operator registration

func (*DB) DeleteInstance

func (db *DB) DeleteInstance(instanceID string) error

func (*DB) DeleteLBInstancesForInstance

func (db *DB) DeleteLBInstancesForInstance(instanceID string) error

DeleteLBInstancesForInstance deletes all load balancer registrations for an instance

func (*DB) FindDanglingInstances

func (db *DB) FindDanglingInstances(maxAge time.Duration) ([]*Instance, error)

FindDanglingInstances finds unregistered instances past timeout. These are instances where the agent never registered before maxAge elapsed. SQLite is already filtered to our shard (populated from S3 + provider on leader election).

func (*DB) FindDeletedInstancesPastRetention

func (db *DB) FindDeletedInstancesPastRetention(cutoff time.Time) ([]*Instance, error)

FindDeletedInstancesPastRetention returns instances that were deleted before the cutoff time. These instances are eligible for S3 record cleanup.

func (*DB) FindStalePreInserts

func (db *DB) FindStalePreInserts(maxAge time.Duration) ([]*Instance, error)

FindStalePreInserts finds pre-inserted instance records where the provider call never completed. These are identified by: - ProviderID IS NULL (provider never created the instance) - IssuedAt < (now - maxAge) (older than threshold) - DeletedAt IS NULL (not already deleted)

func (*DB) FindUnhealthyProviderInstances

func (db *DB) FindUnhealthyProviderInstances() ([]*Instance, error)

FindUnhealthyProviderInstances finds instances where the provider reports an unhealthy status.

func (*DB) GetAllGroups

func (db *DB) GetAllGroups(tenant string) (map[string]*Group, error)

GetAllGroups retrieves all groups for a specific tenant

func (*DB) GetGroup

func (db *DB) GetGroup(tenant, groupKey string) (*Group, error)

GetGroup retrieves a group by tenant and key

func (*DB) GetImage

func (db *DB) GetImage(name string) (string, time.Time, error)

GetImage retrieves a single cached image resolution

func (*DB) GetImages

func (db *DB) GetImages() (map[string]string, error)

GetImages retrieves all cached image resolutions

func (*DB) GetInstance

func (db *DB) GetInstance(instanceID string) (*Instance, error)

func (*DB) GetInstanceByNonce

func (db *DB) GetInstanceByNonce(nonce string) (*Instance, error)

GetInstanceByNonce returns an instance by its registration nonce JWT

func (*DB) GetInstanceByProviderID

func (db *DB) GetInstanceByProviderID(providerID string) (*Instance, error)

func (*DB) GetInstanceCountByGroup

func (db *DB) GetInstanceCountByGroup(groupKey string, excludeOnDemand bool) (int, error)

GetInstanceCountByGroup returns the count of active instances for a group If excludeOnDemand is true, on-demand instances are excluded from the count

func (*DB) GetInstancesByGroup

func (db *DB) GetInstancesByGroup(groupKey string, excludeOnDemand bool) ([]string, error)

GetInstancesByGroup returns all active instances for a group, ordered by creation time (oldest first) If excludeOnDemand is true, on-demand instances are excluded from the results

func (*DB) GetInstancesOlderThan

func (db *DB) GetInstancesOlderThan(maxAge time.Duration, ondemandOnly bool) ([]*Instance, error)

GetInstancesOlderThan returns instances older than the specified duration If ondemandOnly is true, only on-demand instances are returned; if false, only managed instances are returned

func (*DB) GetInstancesPendingDrain

func (db *DB) GetInstancesPendingDrain(tenant string) ([]*Instance, error)

func (*DB) GetLBInstance

func (db *DB) GetLBInstance(lbKey, instanceID string) (*LBInstance, error)

GetLBInstance returns a specific load balancer registration

func (*DB) GetLBInstancesForInstance

func (db *DB) GetLBInstancesForInstance(instanceID string) ([]*LBInstance, error)

GetLBInstancesForInstance returns all load balancer registrations for an instance

func (*DB) GetOldestManagedInstanceByGroup

func (db *DB) GetOldestManagedInstanceByGroup(groupKey string) (*Instance, error)

GetOldestManagedInstanceByGroup returns the oldest non-draining managed (not on-demand) instance for a group Returns nil if no eligible instances exist

func (*DB) GetOperator

func (db *DB) GetOperator(id string) (*Operator, error)

GetOperator returns an operator by ID

func (*DB) GetOperatorByClusterID

func (db *DB) GetOperatorByClusterID(clusterID string) (*Operator, error)

GetOperatorByClusterID returns the most recent operator for a cluster

func (*DB) GetPendingOrFailedLBInstances

func (db *DB) GetPendingOrFailedLBInstances() ([]*LBInstance, error)

GetPendingOrFailedLBInstances returns all instances with pending or failed LB registrations

func (*DB) GetPendingPublicKeys

func (db *DB) GetPendingPublicKeys(instanceID string) ([]*PublicKey, error)

GetPendingPublicKeys retrieves all unprocessed public keys for an instance

func (*DB) GetProviderIDsByGroup

func (db *DB) GetProviderIDsByGroup(groupKey string, excludeOnDemand bool) ([]string, error)

GetProviderIDsByGroup returns sorted provider IDs for all active instances in a group. If excludeOnDemand is true, on-demand instances (created via CreateInstance/Machine) are excluded since their lifecycle is managed by individual Machine/NstanceMachine resources.

func (*DB) GetPublicKeyByFilename

func (db *DB) GetPublicKeyByFilename(instanceID, filename string) (*PublicKey, error)

GetPublicKeyByFilename retrieves a specific public key by instance ID and filename

func (*DB) HighestProviderID

func (db *DB) HighestProviderID(ctx context.Context) (int64, error)

HighestProviderID returns the highest numeric provider_id across all instances (including soft-deleted ones). Where the provider uses numeric provider instance IDs, and allows the client to specify the provider ID (i.e. in Proxmox VE), this can be used to seed provider ID counters so that recently deleted VM IDs are not immediately reused

func (*DB) ListInstances

func (db *DB) ListInstances() ([]*Instance, error)

func (*DB) MarkDrainAcked

func (db *DB) MarkDrainAcked(instanceID string) error

func (*DB) MarkDrainStarted

func (db *DB) MarkDrainStarted(instanceID string) error

func (*DB) MarkInstanceRegistered

func (db *DB) MarkInstanceRegistered(instanceID string, publicKeyPEM []byte, privateIPv4, privateIPv6, hostname string) error

MarkInstanceRegistered marks an instance as registered with authoritative IPs/hostname from agent

func (*DB) MarkInstancesDeleted

func (db *DB) MarkInstancesDeleted(instanceIDs []string) error

MarkInstancesDeleted marks the given instance IDs as deleted

func (*DB) MarkInstancesDeletedIfProviderMissing

func (db *DB) MarkInstancesDeletedIfProviderMissing(providerOwnership map[string]string) ([]string, error)

MarkInstancesDeletedIfProviderMissing marks instances as deleted if their provider_id is not in the provided set of existing provider IDs. This handles the case where VM instances were terminated while nstance-server was down.

func (*DB) MarkPublicKeysProcessed

func (db *DB) MarkPublicKeysProcessed(instanceID string, filenames []string, serialNumbers []string) error

MarkPublicKeysProcessed marks public keys as processed with certificate serial numbers

func (*DB) PurgeDeletedInstance

func (db *DB) PurgeDeletedInstance(instanceID string) error

PurgeDeletedInstance permanently removes a deleted instance record from the database. This should only be called after the S3 record has been deleted.

func (*DB) QueryStaleHealthInstances

func (db *DB) QueryStaleHealthInstances(threshold time.Time) ([]*Instance, error)

QueryStaleHealthInstances returns instances with stale health_at timestamps

func (*DB) SeedFromProviderData

func (db *DB) SeedFromProviderData(instances []*Instance) error

SeedFromProviderData updates existing instance records with current IP/hostname from provider.

func (*DB) SeedFromS3Data

func (db *DB) SeedFromS3Data(instances []*Instance) error

func (*DB) StorePublicKeys

func (db *DB) StorePublicKeys(instanceID string, keys []*PublicKeySubmission) error

StorePublicKeys stores public keys transactionally - all keys must be stored successfully or none are stored

func (*DB) UpdateInstance

func (db *DB) UpdateInstance(instance *Instance) error

func (*DB) UpdateInstanceHealth

func (db *DB) UpdateInstanceHealth(instanceID string, health []byte) error

func (*DB) UpdateInstanceProviderState

func (db *DB) UpdateInstanceProviderState(instanceID string, providerState []byte) error

UpdateInstanceProviderState updates only the provider_state field for an instance. This is used to sync the latest status from the provider before making decisions based on it.

func (*DB) UpdateOperatorRegistration

func (db *DB) UpdateOperatorRegistration(clusterID, publicKey string) error

UpdateOperatorRegistration updates the public key for an existing operator registration This is used during certificate renewal to update the cached registration data

func (*DB) UpsertGroup

func (db *DB) UpsertGroup(tenant, groupKey, runtimeHash, infraHash string) error

UpsertGroup inserts or updates a group's config hashes

func (*DB) UpsertImages

func (db *DB) UpsertImages(images map[string]string, resolvedAt time.Time) error

UpsertImages batch inserts or updates multiple image resolutions

func (*DB) UpsertLBInstance

func (db *DB) UpsertLBInstance(lbKey, instanceID, status string) error

UpsertLBInstance creates or updates a load balancer instance record

func (*DB) ValidateAgentNonce

func (db *DB) ValidateAgentNonce(nonce string) error

ValidateAgentNonce checks if an agent nonce is valid Agent nonces must exist in instances table (server created the record) and not be registered yet

func (*DB) ValidateOperatorNonce

func (db *DB) ValidateOperatorNonce(nonce string) error

ValidateOperatorNonce checks if an operator nonce is valid. Operator nonces must NOT exist in operators table (external nonce, first use).

type Group

type Group struct {
	Tenant            string
	GroupKey          string
	RuntimeConfigHash *string
	InfraConfigHash   *string
	HashesUpdatedAt   *time.Time
	CreatedAt         time.Time
	UpdatedAt         *time.Time
}

Group represents a group record with config hashes

type Image

type Image struct {
	Name       string
	ImageID    string
	ResolvedAt time.Time
}

Image represents a cached image resolution

type Instance

type Instance struct {
	ID              string     `json:"id"`                // Instance ID (puidv7)
	Tenant          string     `json:"tenant"`            // Tenant identifier
	Group           string     `json:"group"`             // Group key (from config groups map)
	OnDemand        bool       `json:"on_demand"`         // Whether this is an on-demand instance (not managed by group reconciliation)
	ProviderID      *string    `json:"provider_id"`       // Provider's instance ID (e.g., i-1234567890abcdef0)
	ProviderAt      *time.Time `json:"provider_at"`       // When provider data was last cached
	Hostname        *string    `json:"hostname"`          // Instance hostname
	FQDN            *string    `json:"fqdn"`              // Fully qualified domain name
	IP4             *string    `json:"ip4"`               // IPv4 address
	IP6             *string    `json:"ip6"`               // IPv6 address
	ProviderState   []byte     `json:"provider_state"`    // Provider-specific state data (JSON)
	Nonce           string     `json:"nonce"`             // Registration nonce JWT
	IssuedAt        *time.Time `json:"issued_at"`         // When nonce was issued (nullable)
	InstancePub     *string    `json:"instance_pub"`      // Instance public key
	RegisteredAt    *time.Time `json:"registered_at"`     // When agent registered
	CertificatesAt  *time.Time `json:"certificates_at"`   // When certificates were issued
	HealthAt        *time.Time `json:"health_at"`         // When health was last updated
	Health          []byte     `json:"health"`            // Latest health report (JSON)
	InfraConfigHash *string    `json:"infra_config_hash"` // Infra config hash at provision time
	DrainStartedAt  *time.Time `json:"drain_started_at"`  // When marked for deletion (waiting for drain)
	DrainAckedAt    *time.Time `json:"drain_acked_at"`    // When operator acknowledged drain complete
	CreatedAt       time.Time  `json:"created_at"`        // When record was created
	UpdatedAt       *time.Time `json:"updated_at"`        // Last update time
	DeletedAt       *time.Time `json:"deleted_at"`        // When marked for deletion
}

Instance represents an instance record in the local database

type LBInstance

type LBInstance struct {
	LBKey      string    `json:"lb_key"`
	InstanceID string    `json:"instance_id"`
	Status     string    `json:"status"`
	UpdatedAt  time.Time `json:"updated_at"`
}

LBInstance represents a load balancer instance registration record

type Operator

type Operator struct {
	ID           string     `json:"id"`
	ClusterID    string     `json:"cluster_id"`
	Tenant       string     `json:"tenant"`
	Nonce        string     `json:"nonce"`
	PublicKey    *string    `json:"public_key"`
	RegisteredAt time.Time  `json:"registered_at"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    *time.Time `json:"updated_at"`
}

Operator represents an operator registration record in the local database

type PublicKey

type PublicKey struct {
	ID                  int64      `json:"id"`
	InstanceID          string     `json:"instance_id"`
	Filename            string     `json:"filename"`
	PublicKeyPEM        string     `json:"public_key_pem"`
	CertificateName     *string    `json:"certificate_name"`
	SubmittedAt         time.Time  `json:"submitted_at"`
	ProcessedAt         *time.Time `json:"processed_at"`
	CertificateSerial   *string    `json:"certificate_serial"`
	CertificateIssuedAt *time.Time `json:"certificate_issued_at"`
	CreatedAt           time.Time  `json:"created_at"`
	UpdatedAt           *time.Time `json:"updated_at"`
}

PublicKey represents a stored public key waiting for certificate generation

type PublicKeySubmission

type PublicKeySubmission struct {
	Filename     string `json:"filename"`
	PublicKeyPEM string `json:"public_key_pem"`
}

PublicKeySubmission represents a public key submitted by an agent

Jump to

Keyboard shortcuts

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