cidrallocator

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: May 14, 2025 License: Apache-2.0 Imports: 45 Imported by: 0

Documentation

Overview

Package cidrallocator implements the CIDR allocation controller for Aquanaut IPAM. It provides automatic allocation of CIDR blocks for clusters using a bitmap-based allocation algorithm with conflict resolution and retry mechanisms.

Package cidrallocator - centralized index registration for CIDR allocation

Package cidrallocator implements paged list operations

Index

Constants

View Source
const (
	// AllocationMaxRetries is the maximum number of retries for CIDR allocation
	// Increased from 10 to 50 in Allocation-First design for better concurrency handling
	AllocationMaxRetries = 50

	// AllocationBackoffBaseMs is the base value for retry backoff in milliseconds
	// Reduced from 50ms to 20ms for performance improvement
	AllocationBackoffBaseMs = 20

	// AllocationBackoffFactor is the multiplier for exponential backoff
	// Reduced from 2.0 to 1.5 for better distribution during contention
	AllocationBackoffFactor = 1.5

	// AllocationJitterRatio is the fixed ratio for jitter calculation (10%)
	// Used to add random jitter to backoff duration to prevent thundering herd
	AllocationJitterRatio = 0.1
)

Constants for allocation retry and backoff configuration

View Source
const (
	// IPAMLabel is the label added to all IPAM resources
	IPAMLabel = "plexaubnet.io/ipam"

	// IPAMFinalizer is the finalizer added to all IPAM resources
	IPAMFinalizer = "ipam.plexaubnet.io/finalizer"

	// MaxConcurrentReconciles is the maximum number of concurrent reconciles
	MaxConcurrentReconciles = 1
)

Constants for common metadata and configuration

View Source
const (
	// EventReasonAllocated is the reason for allocation success events
	EventReasonAllocated = "SubnetAllocated"

	// EventReasonPoolExhausted is the reason for pool exhaustion events
	EventReasonPoolExhausted = "SubnetPoolExhausted"

	// EventReasonConflict is the reason for allocation conflict events
	EventReasonConflict = "AllocationConflict"

	// EventReasonValidationFailed is the reason for validation failure events
	EventReasonValidationFailed = "ValidationFailed"
)

Event reasons

View Source
const (
	// PoolRefField is the field index for spec.poolRef
	PoolRefField = "spec.poolRef"
	// ParentPoolLabelIndex is the field index for metadata.labels[plexaubnet.io/parent]
	ParentPoolLabelIndex = "metadata.labels[plexaubnet.io/parent]"
	// PageSize is the default page size for List operations to limit memory usage
	PageSize = 1000
)
View Source
const (
	// ReadyCondition is the type for CIDR claim readiness
	ReadyCondition = "Ready"
	// MaxRetries is the maximum number of allocation retries
	MaxRetries = 65
	// DefaultRequeueAfter is the default requeue period
	DefaultRequeueAfter = time.Second * 10
	// ClaimStatusMaxRetries is the maximum number of status update retries
	ClaimStatusMaxRetries = 10
)
View Source
const (
	AsyncTimeoutDefaultSec = 3
)

Default number of retries Note: This is kept for compatibility and used only if Config is not available

View Source
const NotFoundRetryMax = 3

NotFoundRetryMax is the maximum number of retries for NotFound errors

Variables

View Source
var (

	// Pagination related metrics
	// SubnetListPagesTotal counts the number of pages retrieved by pagination
	SubnetListPagesTotal = prometheus.NewCounter(
		prometheus.CounterOpts{
			Name: "subnet_list_pages_total",
			Help: "Total pages fetched while listing Subnets with pager",
		},
	)

	// SubnetListContinueSkippedTotal counts the number of times Continue token was skipped
	SubnetListContinueSkippedTotal = prometheus.NewCounter(
		prometheus.CounterOpts{
			Name: "subnet_list_continue_skipped_total",
			Help: "Times a continue token was empty (end-of-list)",
		},
	)
)

Functions

func CalculatePoolStatus

func CalculatePoolStatus(poolCIDR string, allocations []string) (int, map[string]int, error)

CalculatePoolStatus calculates comprehensive pool statistics in one pass This helps avoid double-counting issues and improves accuracy of Pool.Status

func DeletionOnly

func DeletionOnly() predicate.Predicate

DeletionOnly returns a predicate that only allows deletion events.

func EncodeAllocationName

func EncodeAllocationName(pool, cidr string) string

EncodeAllocationName creates a deterministic name for a Subnet based on pool and CIDR Format: <pool>-<cidr> with '/' replaced by '-' Example: test-pool-10.0.49.0-24

Note: Currently this function is not used as we directly use ClusterID as the name, but it's kept for future use if a different naming scheme is needed.

func IsConflictError

func IsConflictError(err error) bool

IsConflictError checks if an error is a conflict error Returns true if the error indicates a conflict or if it's an AlreadyExists error

func IsExhaustedError

func IsExhaustedError(err error) bool

IsExhaustedError checks if an error is a pool exhausted error Returns true if the error indicates the pool is exhausted

func NewConflictError

func NewConflictError(msg string) error

NewConflictError creates a new conflict error Used when there's a conflict during allocation (e.g., concurrent allocation)

func NewExhaustedError

func NewExhaustedError(msg string) error

NewExhaustedError creates a new pool exhausted error Used when no more CIDRs are available in the pool

func NewPoolGaugePredicate

func NewPoolGaugePredicate() predicate.Predicate

NewPoolGaugePredicate creates a new PoolGaugeEventHandler.

func NewTestScheme

func NewTestScheme() *runtime.Scheme

NewTestScheme creates a new scheme for testing purposes. This avoids race conditions where multiple test suites try to register types to the global scheme.Scheme concurrently.

func ParseCIDRSize

func ParseCIDRSize(cidr string) (int, error)

ParseCIDRSize extracts the prefix length from a CIDR string

func PoolStatusPred

func PoolStatusPred() predicate.Predicate

PoolStatusPred returns a predicate that passes Pool's own updates only when generation changes, while passing all external events (Create/Delete/Generic). This avoids infinite loops on Pool's status-only updates while ensuring events from other resources are processed.

func RecordParentPoolReconcileDuration

func RecordParentPoolReconcileDuration(result string, duration time.Duration)

RecordParentPoolReconcileDuration records parent Pool processing time in metrics. Caller is DummyPoolReconciler or PoolStatusReconciler.

func RecordParentPoolRequeue

func RecordParentPoolRequeue(eventType string)

RecordParentPoolRequeue records parent Pool re-queue events in metrics. Caller is mapSubnetToParentPool function of SubnetReconciler. Event types include create, update, delete, rename, child_delete, etc.

func RegisterAllPoolGauges

func RegisterAllPoolGauges(ctx context.Context, c client.Client) error

RegisterAllPoolGauges registers static gauges for all existing SubnetPools. Used when batch registration is needed, such as at controller startup.

func RegisterControllers

func RegisterControllers(mgr ctrl.Manager, ipamConfig *config.IPAMConfig, recorder record.EventRecorder) error

RegisterControllers registers all controllers with the manager

func RegisterPoolGauges

func RegisterPoolGauges(poolName string)

RegisterPoolGauges is called when a pool is created. Ensures concurrency safety and immediately registers gauges for frequently used sizes of each pool.

func SetupFieldIndexes

func SetupFieldIndexes(ctx context.Context, mgr ctrl.Manager, log logr.Logger) error

SetupFieldIndexes registers all FieldIndexers once. Safe to call exactly one time during manager startup.

func SubnetEvents

func SubnetEvents() predicate.Predicate

SubnetEvents returns a predicate that allows Create/Update/Delete events for Subnet resources. Status-only changes are excluded (by GenerationChangedPredicate).

func UnregisterPoolGauges

func UnregisterPoolGauges(poolName string)

UnregisterPoolGauges is called when a pool is deleted, and unregisters gauges of all sizes.

Types

type CIDRAllocatorReconciler

type CIDRAllocatorReconciler struct {
	client.Client
	Scheme   *runtime.Scheme
	Recorder record.EventRecorder

	Config         *config.IPAMConfig
	ControllerName string // For avoiding controller name duplication (mainly for testing)
	// contains filtered or unexported fields
}

CIDRAllocatorReconciler reconciles IPAM resources

func NewCIDRAllocatorReconciler

func NewCIDRAllocatorReconciler(client client.Client, scheme *runtime.Scheme, recorder record.EventRecorder, ipamConfig *config.IPAMConfig, controllerName ...string) *CIDRAllocatorReconciler

NewCIDRAllocatorReconciler creates a new reconciler

func (*CIDRAllocatorReconciler) Reconcile

func (r *CIDRAllocatorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile handles SubnetClaim reconciliation

func (*CIDRAllocatorReconciler) RegisterEventHandlers

func (r *CIDRAllocatorReconciler) RegisterEventHandlers()

RegisterEventHandlers updates the reconciler with event handling capabilities

func (*CIDRAllocatorReconciler) SetupWithManager

func (r *CIDRAllocatorReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager.

type CIDRMap

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

CIDRMap provides CIDR allocation tracking with bitmap-based implementation

func NewCIDRMap

func NewCIDRMap(cidr string) (*CIDRMap, error)

NewCIDRMap creates a CIDRMap from a CIDR string

func (*CIDRMap) AllocateNextAvailable

func (c *CIDRMap) AllocateNextAvailable(size int) (string, error)

AllocateNextAvailable finds and allocates the next available CIDR block of given size

func (*CIDRMap) GetFreeBlockCount

func (c *CIDRMap) GetFreeBlockCount() map[string]int

GetFreeBlockCount returns the number of free blocks for each size

func (*CIDRMap) MarkAllocated

func (c *CIDRMap) MarkAllocated(cidr string) error

MarkAllocated marks a CIDR as allocated

type EventEmitter

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

EventEmitter provides methods to emit standardized Kubernetes events

func NewEventEmitter

func NewEventEmitter(recorder record.EventRecorder, scheme *runtime.Scheme) *EventEmitter

NewEventEmitter creates a new EventEmitter

func (*EventEmitter) EmitAllocationConflict

func (e *EventEmitter) EmitAllocationConflict(claim *ipamv1.SubnetClaim, details string)

EmitAllocationConflict emits an event for an allocation conflict

func (*EventEmitter) EmitAllocationSuccess

func (e *EventEmitter) EmitAllocationSuccess(claim *ipamv1.SubnetClaim, cidr string)

EmitAllocationSuccess emits an event for a successful allocation

func (*EventEmitter) EmitPoolEvent

func (e *EventEmitter) EmitPoolEvent(pool *ipamv1.SubnetPool, eventType string, reason string, msg string)

EmitPoolEvent emits an event associated with a pool

func (*EventEmitter) EmitPoolExhausted

func (e *EventEmitter) EmitPoolExhausted(claim *ipamv1.SubnetClaim, poolName string)

EmitPoolExhausted emits an event for a pool exhaustion

func (*EventEmitter) EmitValidationFailed

func (e *EventEmitter) EmitValidationFailed(claim *ipamv1.SubnetClaim, details string)

EmitValidationFailed emits an event for validation failure

type PoolGaugeEventHandler

type PoolGaugeEventHandler struct {
}

PoolGaugeEventHandler is a Predicate handler that monitors SubnetPool create/delete events to register/unregister static gauges.

func (*PoolGaugeEventHandler) Create

Create registers static gauges when a SubnetPool is created.

func (*PoolGaugeEventHandler) Delete

Delete unregisters static gauges when a SubnetPool is deleted.

func (*PoolGaugeEventHandler) Generic

Generic ignores Generic events.

func (*PoolGaugeEventHandler) Update

Update ignores Update events.

type PoolStatusReconciler

type PoolStatusReconciler struct {
	client.Client
	Scheme *runtime.Scheme

	// ControllerName is used to specify a unique controller name during testing.
	// If not specified, the default name "poolstatus-controller" is used.
	ControllerName string
}

PoolStatusReconciler reconciles SubnetPool status based on allocations and child pools

func (*PoolStatusReconciler) Reconcile

func (r *PoolStatusReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile handles SubnetPool status reconciliation

func (*PoolStatusReconciler) SetupWithManager

func (r *PoolStatusReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager.

type StaticGauge

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

StaticGauge is a struct that holds pre-registered gauges with fixed labels.

type SubnetPoolClaimReconciler

type SubnetPoolClaimReconciler struct {
	client.Client
	Scheme *runtime.Scheme
	Config *config.IPAMConfig
}

SubnetPoolClaimReconciler reconciles a SubnetPoolClaim object

func NewSubnetPoolClaimReconciler

func NewSubnetPoolClaimReconciler(
	client client.Client,
	scheme *runtime.Scheme,
	config *config.IPAMConfig,
) *SubnetPoolClaimReconciler

NewSubnetPoolClaimReconciler creates a new SubnetPoolClaimReconciler

func (*SubnetPoolClaimReconciler) Reconcile

Reconcile handles SubnetPoolClaim reconciliation

func (*SubnetPoolClaimReconciler) SetupWithManager

func (r *SubnetPoolClaimReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the manager

type SubnetReconciler

type SubnetReconciler struct {
	client.Client
	Scheme *runtime.Scheme

	// Config controller configuration
	Config *config.IPAMConfig

	// ControllerName is used to specify a unique controller name during testing.
	// If not specified, the default name "subnet-controller" is used.
	ControllerName string
}

SubnetReconciler reconciles a Subnet object

func NewSubnetReconciler

func NewSubnetReconciler(
	client client.Client,
	scheme *runtime.Scheme,
	config *config.IPAMConfig,
) *SubnetReconciler

NewSubnetReconciler creates a new SubnetReconciler

func (*SubnetReconciler) Reconcile

func (r *SubnetReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)

Reconcile adjusts Subnet resources. Main roles: 1. Get/check existence of Subnet.

func (*SubnetReconciler) SetupWithManager

func (r *SubnetReconciler) SetupWithManager(mgr ctrl.Manager) error

SetupWithManager sets up the controller with the Manager.

Directories

Path Synopsis
Package statuscalc provides utilities for calculating SubnetPool status metrics
Package statuscalc provides utilities for calculating SubnetPool status metrics

Jump to

Keyboard shortcuts

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