ipam

package
v1.11.0-cni-plu...-01d9c3b Latest Latest
Warning

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

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

Documentation

Overview

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (

	// Common attributes which may be set on allocations by clients.  Moved to the model package so they can be used
	// by the AllocationBlock code too.
	AttributePod             = model.IPAMBlockAttributePod
	AttributeNamespace       = model.IPAMBlockAttributeNamespace
	AttributeNode            = model.IPAMBlockAttributeNode
	AttributeTimestamp       = model.IPAMBlockAttributeTimestamp
	AttributeType            = model.IPAMBlockAttributeType
	AttributeService         = model.IPAMBlockAttributeService
	AttributeTypeIPIP        = model.IPAMBlockAttributeTypeIPIP
	AttributeTypeVXLAN       = model.IPAMBlockAttributeTypeVXLAN
	AttributeTypeVXLANV6     = model.IPAMBlockAttributeTypeVXLANV6
	AttributeTypeWireguard   = model.IPAMBlockAttributeTypeWireguard
	AttributeTypeWireguardV6 = model.IPAMBlockAttributeTypeWireguardV6

	// KubeVirt VM pod attributes
	AttributeVMIName = model.IPAMBlockAttributeVMIName
	AttributeVMIUID  = model.IPAMBlockAttributeVMIUID
	AttributeVMUID   = model.IPAMBlockAttributeVMUID
	AttributeVMIMUID = model.IPAMBlockAttributeVMIMUID
)
View Source
const EmptyBlockMinReclaimAge = time.Minute

EmptyBlockMinReclaimAge is the minimum time since a block was claimed before another node will consider reclaiming that block if the node needs a block and the block is empty. Prevents a block from ping-ponging between two nodes with no chance for either node to actually allocate an IP from it.

View Source
const WindowsReservedHandle = "windows-reserved-ipam-handle"

windowsReservedHandle is the handle used to reserve addresses required for Windows networking so that workloads do not get assigned these addresses.

Variables

View Source
var (
	ErrBlockLimit      = errors.New("cannot allocate new block due to per host block limit")
	ErrNoQualifiedPool = errors.New("cannot find a qualified ippool")
	ErrStrictAffinity  = errors.New("global strict affinity should not be false for Windows node")
)
View Source
var ErrUseRequired = errors.New("must specify the intended use when assigning an IP")

Functions

func SelectsNamespace

func SelectsNamespace(pool v3.IPPool, namespace *corev1.Namespace) (bool, error)

SelectsNamespace determines whether or not the IPPool's namespaceSelector matches the labels on the given namespace.

func SelectsNode

func SelectsNode(pool v3.IPPool, n internalapi.Node) (bool, error)

SelectsNode determines whether or not the IPPool's nodeSelector matches the labels on the given node.

Types

type AffinityConfig

type AffinityConfig struct {
	AffinityType AffinityType
	Host         string
}

type AffinityType

type AffinityType string
const (
	AffinityTypeHost    AffinityType = "host"
	AffinityTypeVirtual AffinityType = "virtual"
)

type AssignIPArgs

type AssignIPArgs struct {
	// The IP address to assign.
	IP cnet.IP

	// If specified, a handle which can be used to retrieve / release
	// the allocated IP addresses in the future.
	HandleID *string

	// A key/value mapping of metadata to store with the allocations.
	Attrs map[string]string

	// If specified, the hostname of the host on which IP addresses
	// will be allocated.  If not specified, this will default
	// to the value provided by os.Hostname.
	Hostname string

	// If specified, the attributes of reserved IPv4 addresses in the block.
	HostReservedAttr *HostReservedAttr

	// The intended use for the IP address.  Used to determine the affinityType of the host.
	IntendedUse v3.IPPoolAllowedUse

	// MaxAllocToHandlePerIPVersion specifies the maximum number of IPs per IP version (IPv4/IPv6)
	// that can be allocated for this handle. If 0, no limit is enforced.
	// Used for KubeVirt VMI pods to ensure only one IP allocation per VMI per IP version.
	MaxAllocToHandlePerIPVersion int
}

AssignIPArgs defines the set of arguments for assigning a specific IP address.

type AttributeOwner

type AttributeOwner struct {
	// Namespace is the Kubernetes namespace of the pod.
	Namespace string
	// Name is the name of the pod.
	Name string
}

AttributeOwner represents the owner of an IP allocation attribute.

func EmptyAttributeOwner

func EmptyAttributeOwner() *AttributeOwner

EmptyAttributeOwner returns an AttributeOwner with empty namespace and name. This can be used with Matches to check if attributes are empty.

func (*AttributeOwner) Matches

func (o *AttributeOwner) Matches(attrs map[string]string) bool

Matches checks if the given attributes match this owner.

type AutoAssignArgs

type AutoAssignArgs struct {
	// The number of IPv4 addresses to automatically assign.
	Num4 int

	// The number of IPv6 addresses to automatically assign.
	Num6 int

	// If specified, a handle which can be used to retrieve / release
	// the allocated IP addresses in the future.
	HandleID *string

	// A key/value mapping of metadata to store with the allocations.
	Attrs map[string]string

	// If specified, the hostname of the host on which IP addresses
	// will be allocated.  If not specified, this will default
	// to the value provided by os.Hostname.
	Hostname string

	// If specified, the previously configured IPv4 pools from which
	// to assign IPv4 addresses.  If not specified, this defaults to all IPv4 pools.
	IPv4Pools []cnet.IPNet

	// If specified, the previously configured IPv6 pools from which
	// to assign IPv6 addresses.  If not specified, this defaults to all IPv6 pools.
	IPv6Pools []cnet.IPNet

	// If non-zero, limit on the number of affine blocks this host is allowed to claim
	// (per IP version).
	MaxBlocksPerHost int

	// If specified, the attributes of reserved IPv4 addresses in the block.
	HostReservedAttrIPv4s *HostReservedAttr

	// If specified, the attributes of reserved IPv6 addresses in the block.
	HostReservedAttrIPv6s *HostReservedAttr

	// The intended use for the IP address.  Used to filter the available IP pools on their AllowedUses field.
	// This field is required.
	IntendedUse v3.IPPoolAllowedUse

	// MaxAllocToHandlePerIPVersion specifies the maximum number of IPs per IP version (IPv4/IPv6)
	// that can be allocated across all blocks for this handle. If 0, no limit is enforced.
	// Used for KubeVirt VMI pods to ensure only one IP allocation per VMI per IP version.
	MaxAllocToHandlePerIPVersion int

	// The namespace object for namespaceSelector support.
	Namespace *corev1.Namespace
}

AutoAssignArgs defines the set of arguments for assigning one or more IP addresses.

type BlockArgs

type BlockArgs struct {
	// If specified, the hostname of the host on which blocks
	// will be allocated.  If not specified, this will default
	// to the value provided by os.Hostname.
	Hostname string

	// If specified, the previously configured IPv4 pools from which
	// to assign IPv4 addresses.  If not specified, this defaults to all IPv4 pools.
	IPv4Pools []cnet.IPNet

	// If specified, the previously configured IPv6 pools from which
	// to assign IPv6 addresses.  If not specified, this defaults to all IPv6 pools.
	IPv6Pools []cnet.IPNet

	// If specified, the attributes of reserved IPv4 addresses in this block.
	HostReservedAttrIPv4s *HostReservedAttr

	// If specified, the attributes of reserved IPv6 addresses in this block.
	HostReservedAttrIPv6s *HostReservedAttr
}

BlockArgs defines the set of arguments for allocating one block.

type BlockUtilization

type BlockUtilization struct {
	// This block's CIDR.
	CIDR net.IPNet

	// Number of possible IPs in this block.
	Capacity int

	// Number of available IPs in this block.
	Available int
}

BlockUtilization reports IP utilization for a single allocation block.

type ErrInsufficientIPsByHandle

type ErrInsufficientIPsByHandle struct {
	HandleID      string
	ExistingCount int
	RequiredCount int
}

ErrInsufficientIPsByHandle is returned when a handle has some IPs allocated but not enough yet. This indicates a concurrent operation is in progress and the caller should retry.

func (ErrInsufficientIPsByHandle) Error

type ErrMaxAllocReached

type ErrMaxAllocReached struct {
	HandleID     string
	CurrentCount int
	MaxAlloc     int
}

ErrMaxAllocReached is returned when a handle already has the maximum number of allocations.

func (ErrMaxAllocReached) Error

func (e ErrMaxAllocReached) Error() string

type GetUtilizationArgs

type GetUtilizationArgs struct {
	// If specified, the pools whose utilization should be reported.  Each string here
	// can be a pool name or CIDR.  If not specified, this defaults to all pools.
	Pools []string
}

GetUtilizationArgs defines the set of arguments for requesting IP utilization.

type HostReservedAttr

type HostReservedAttr struct {
	// Number of addresses reserved from start of the block.
	StartOfBlock int

	// Number of addresses reserved from end of the block.
	EndOfBlock int

	// Handle for reserved addresses.
	Handle string

	// A description about the reserves.
	Note string
}

type IPAMAssignments

type IPAMAssignments struct {
	IPs              []net.IPNet       // assigned IP addresses
	IPVersion        int               // IP version (4 or 6)
	NumRequested     int               // number of requested IP addresses (not all may be assigned)
	HostReservedAttr *HostReservedAttr // reserved addresses at start and/or end of blocks
	Msgs             []string          // warning/error messages to be rendered in case there are any issues with the assignment
}

func (*IPAMAssignments) AddMsg

func (i *IPAMAssignments) AddMsg(msg string)

func (*IPAMAssignments) PartialFulfillmentError

func (i *IPAMAssignments) PartialFulfillmentError() error

type IPAMConfig

type IPAMConfig struct {
	// When StrictAffinity is true, addresses from a given block can only be
	// assigned by hosts with the blocks affinity.  If false, then AutoAllocateBlocks
	// must be true.  The default value is false.
	StrictAffinity bool

	// When AutoAllocateBlocks is true, Calico will automatically
	// allocate blocks of IP address to hosts as needed to assign addresses.
	// If false, then StrictAffinity must be true.  The default value is true.
	AutoAllocateBlocks bool

	// If non-zero, MaxBlocksPerHost specifies the max number of blocks that may
	// be affine to a node.
	MaxBlocksPerHost int

	// KubeVirtVMAddressPersistence controls whether KubeVirt VirtualMachine workloads
	// maintain persistent IP addresses across VM lifecycle events.
	// When set to VMAddressPersistenceEnabled, Calico automatically ensures that KubeVirt VMs retain their
	// IP addresses when their underlying pods are recreated during VM operations such as
	// reboot, live migration, or pod eviction. IP persistency is ensured when the
	// VirtualMachineInstance (VMI) resource is deleted and recreated by the VM controller.
	// When set to VMAddressPersistenceDisabled, VMs receive new IP addresses whenever their pods are recreated,
	// following standard pod IP allocation behavior. Live migration target pods are not allowed
	// when this is set to VMAddressPersistenceDisabled and will result in an error.
	// If nil, defaults to VMAddressPersistenceEnabled (IP persistence enabled if not specified).
	KubeVirtVMAddressPersistence *VMAddressPersistence
}

IPAMConfig contains global configuration options for Calico IPAM. This IPAM configuration is stored in the datastore and configures the behavior of Calico IPAM across an entire Calico cluster.

type IPReservationInterface

type IPReservationInterface interface {
	List(ctx context.Context, opts options.ListOptions) (*v3.IPReservationList, error)
}

IPReservationInterface is the subset of clientv3.IPReservationInterface that we need.

type Interface

type Interface interface {
	// AssignIP assigns the provided IP address to the provided host.  The IP address
	// must fall within a configured pool.  AssignIP will claim block affinity as needed
	// in order to satisfy the assignment.  An error will be returned if the IP address
	// is already assigned, or if StrictAffinity is enabled and the address is within
	// a block that does not have affinity for the given host.
	AssignIP(ctx context.Context, args AssignIPArgs) error

	// AutoAssign automatically assigns one or more IP addresses as specified by the
	// provided AutoAssignArgs.  AutoAssign returns the list of the assigned IPv4 addresses,
	// and the list of the assigned IPv6 addresses in IPNet format.
	// The returned IPNet represents the allocation block from which the IP was allocated,
	// which is useful for dataplanes that need to know the subnet (such as Windows).
	//
	// In case of error, returns the IPs allocated so far along with the error.
	AutoAssign(ctx context.Context, args AutoAssignArgs) (*IPAMAssignments, *IPAMAssignments, error)

	// ReleaseIPs releases any of the given IP addresses that are currently assigned,
	// so that they are available to be used in another assignment.
	ReleaseIPs(ctx context.Context, ips ...ReleaseOptions) ([]cnet.IP, []ReleaseOptions, error)

	// GetAssignmentAttributes returns the AllocationAttribute for the given IP address,
	// which includes the handle ID, ActiveOwnerAttrs, and AlternateOwnerAttrs.
	// This provides an atomic snapshot of all allocation attributes for the IP.
	// If the IP is not assigned, it returns a nil *model.AllocationAttribute and an
	// ErrorResourceDoesNotExist error.
	GetAssignmentAttributes(ctx context.Context, addr cnet.IP) (*model.AllocationAttribute, error)

	// IPsByHandle returns a list of all IP addresses that have been
	// assigned using the provided handle.
	IPsByHandle(ctx context.Context, handleID string) ([]cnet.IP, error)

	// ReleaseByHandle releases all IP addresses that have been assigned
	// using the provided handle.  Returns an error if no addresses
	// are assigned with the given handle.
	ReleaseByHandle(ctx context.Context, handleID string) error

	// ClaimAffinity claims affinity to the given host for all blocks
	// within the given CIDR.  The given CIDR must fall within a configured
	// pool. If an empty string is passed as the host, then the value returned by os.Hostname is used.
	ClaimAffinity(ctx context.Context, cidr cnet.IPNet, affinityCfg AffinityConfig) ([]cnet.IPNet, []cnet.IPNet, error)

	// ReleaseAffinity releases affinity for all blocks within the given CIDR
	// on the given host.  If an empty string is passed as the host, then the
	// value returned by os.Hostname will be used. If mustBeEmpty is true, then an error
	// will be returned if any blocks within the CIDR are not empty - in this case, this
	// function may release some but not all blocks within the given CIDR.
	ReleaseAffinity(ctx context.Context, cidr cnet.IPNet, host string, mustBeEmpty bool) error

	// ReleaseHostAffinities releases affinity for all blocks that are affine
	// to the given host.  If an empty string is passed as the host, the value returned by
	// os.Hostname will be used. If mustBeEmpty is true, then an error
	// will be returned if any blocks within the CIDR are not empty - in this case, this
	// function may release some but not all blocks attached to this host.
	ReleaseHostAffinities(ctx context.Context, affinityCfg AffinityConfig, mustBeEmpty bool) error

	// ReleasePoolAffinities releases affinity for all blocks within
	// the specified pool across all hosts.
	ReleasePoolAffinities(ctx context.Context, pool cnet.IPNet) error

	// ReleaseBlockAffinity releases the affinity of the exact block provided.
	ReleaseBlockAffinity(ctx context.Context, block *model.AllocationBlock, mustBeEmpty bool) error

	// GetIPAMConfig returns the global IPAM configuration.  If no IPAM configuration
	// has been set, returns a default configuration with StrictAffinity disabled
	// and AutoAllocateBlocks enabled.
	GetIPAMConfig(ctx context.Context) (*IPAMConfig, error)

	// SetIPAMConfig sets global IPAM configuration.  This can only
	// be done when there are no allocated blocks and IP addresses.
	SetIPAMConfig(ctx context.Context, cfg IPAMConfig) error

	// RemoveIPAMHost releases affinity for all blocks on the given host,
	// and removes all host-specific IPAM data from the datastore.
	// RemoveIPAMHost does not release any IP addresses claimed on the given host.
	// If an empty string is passed as the host then the value returned by os.Hostname is used.
	RemoveIPAMHost(ctx context.Context, affinityCfg AffinityConfig) error

	// GetUtilization returns IP utilization info for the specified pools, or for all pools.
	GetUtilization(ctx context.Context, args GetUtilizationArgs) ([]*PoolUtilization, error)

	// EnsureBlock returns single IPv4/IPv6 IPAM block for a host as specified by the provided BlockArgs.
	// If there is no block allocated already for this host, allocate one and return its CIDR.
	// Otherwise, return the CIDR of the IPAM block allocated for this host.
	// It returns IPv4, IPv6 block CIDR and any error encountered.
	EnsureBlock(ctx context.Context, args BlockArgs) (*cnet.IPNet, *cnet.IPNet, error)

	// UpgradeHost checks the resources related to the given node and, if it
	// finds any that are in older formats, upgrades them.  It is idempotent.
	UpgradeHost(ctx context.Context, nodeName string) error

	// SetOwnerAttributes sets ActiveOwnerAttrs and/or AlternateOwnerAttrs for an IP atomically.
	//
	// Parameters:
	//   - updates: Specifies the attribute values to set. See OwnerAttributeUpdates for details.
	//   - preconditions: Optional verification of expected owners before setting attributes.
	//     If nil, no verification is performed.
	//
	// Use cases:
	//   - Set AlternateOwnerAttrs only: updates.AlternateOwnerAttrs=<target pod attrs>
	//   - Clear ActiveOwnerAttrs: updates.ClearActiveOwner=true
	//   - Swap attributes: updates.ActiveOwnerAttrs=<current alternate>, updates.AlternateOwnerAttrs=<current active>
	//   - Set both: updates.ActiveOwnerAttrs=<new active>, updates.AlternateOwnerAttrs=<new alternate>
	SetOwnerAttributes(ctx context.Context, ip cnet.IP, handleID string, updates *OwnerAttributeUpdates, preconditions *OwnerAttributePreconditions) error
}

ipam.Interface has methods to perform IP address management.

func NewIPAMClient

func NewIPAMClient(client bapi.Client, pools PoolAccessorInterface, reservations IPReservationInterface) Interface

NewIPAMClient returns a new ipamClient, which implements Interface. Consumers of the Calico API should not create this directly, but should access IPAM through the main client IPAM accessor (e.g. clientv3.IPAM())

type OwnerAttributePreconditions

type OwnerAttributePreconditions struct {
	// ExpectedActiveOwner verifies current ActiveOwnerAttrs matches the specified owner before setting.
	// If nil, no match on ExpectedActiveOwner is performed.
	// Verification can still occur via VerifyActiveOwnerEmpty if that field is true.
	// An error is returned if both ExpectedActiveOwner and VerifyActiveOwnerEmpty are set.
	ExpectedActiveOwner *AttributeOwner

	// VerifyActiveOwnerEmpty verifies that ActiveOwnerAttrs is empty (nil or empty map) before setting.
	// If true, ActiveOwnerAttrs must be empty for the operation to proceed.
	// An error is returned if both ExpectedActiveOwner and VerifyActiveOwnerEmpty are set.
	VerifyActiveOwnerEmpty bool

	// ExpectedAlternateOwner verifies current AlternateOwnerAttrs matches the specified owner before setting.
	// If nil, no match on ExpectedAlternateOwner is performed.
	// Verification can still occur via VerifyAlternateOwnerEmpty if that field is true.
	// An error is returned if both ExpectedAlternateOwner and VerifyAlternateOwnerEmpty are set.
	ExpectedAlternateOwner *AttributeOwner

	// VerifyAlternateOwnerEmpty verifies that AlternateOwnerAttrs is empty (nil or empty map) before setting.
	// If true, AlternateOwnerAttrs must be empty for the operation to proceed.
	// An error is returned if both ExpectedAlternateOwner and VerifyAlternateOwnerEmpty are set.
	VerifyAlternateOwnerEmpty bool
}

OwnerAttributePreconditions specifies expected owners for verification before setting attributes. These are used to prevent overwriting attributes that belong to a different pod.

type OwnerAttributeUpdates

type OwnerAttributeUpdates struct {
	// ActiveOwnerAttrs specifies attributes to set for ActiveOwnerAttrs.
	// If nil and ClearActiveOwner is false, ActiveOwnerAttrs is not modified.
	// If ClearActiveOwner is true, ActiveOwnerAttrs must be nil (error if both are set).
	ActiveOwnerAttrs map[string]string

	// ClearActiveOwner indicates that ActiveOwnerAttrs should be cleared (set to nil).
	// If true, ActiveOwnerAttrs must be nil. An error is returned if both are set.
	ClearActiveOwner bool

	// AlternateOwnerAttrs specifies attributes to set for AlternateOwnerAttrs.
	// If nil and ClearAlternateOwner is false, AlternateOwnerAttrs is not modified.
	// If ClearAlternateOwner is true, AlternateOwnerAttrs must be nil (error if both are set).
	AlternateOwnerAttrs map[string]string

	// ClearAlternateOwner indicates that AlternateOwnerAttrs should be cleared (set to nil).
	// If true, AlternateOwnerAttrs must be nil. An error is returned if both are set.
	ClearAlternateOwner bool
}

OwnerAttributeUpdates specifies the attribute values to set for ActiveOwnerAttrs and/or AlternateOwnerAttrs. These are the actual values that will be written to the IP allocation.

type PoolAccessorInterface

type PoolAccessorInterface interface {
	// Returns a list of enabled pools sorted in alphanumeric name order.
	GetEnabledPools(ctx context.Context, ipVersion int) ([]v3.IPPool, error)
	// Returns a list of all pools sorted in alphanumeric name order.
	GetAllPools(ctx context.Context) ([]v3.IPPool, error)
}

Interface used to access the enabled IPPools.

type PoolUtilization

type PoolUtilization struct {
	// This pool's name.
	Name string

	// This pool's CIDR.
	CIDR net.IPNet

	// Utilization for each of this pool's blocks.
	Blocks []BlockUtilization
}

PoolUtilization reports IP utilization for a single IP pool.

type ReleaseOptions

type ReleaseOptions struct {
	// Address to release.
	Address string

	// If provided, handle and sequence number will be used to
	// check for race conditions with other users of the IPAM API. It is
	// highly recommended that both values be set on release requests.
	Handle         string
	SequenceNumber *uint64
}

func (*ReleaseOptions) AsNetIP

func (opts *ReleaseOptions) AsNetIP() (*cnet.IP, error)

type VMAddressPersistence

type VMAddressPersistence string

VMAddressPersistence controls whether KubeVirt VirtualMachine workloads maintain persistent IP addresses across VM lifecycle events.

const (
	// VMAddressPersistenceEnabled enables IP persistence for KubeVirt VMs.
	VMAddressPersistenceEnabled VMAddressPersistence = "Enabled"
	// VMAddressPersistenceDisabled disables IP persistence for KubeVirt VMs.
	VMAddressPersistenceDisabled VMAddressPersistence = "Disabled"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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