node

package
v1.21.0-pre.1 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: Apache-2.0 Imports: 36 Imported by: 111

Documentation

Overview

Package node provides functionality related to the local and remote node addresses

Index

Constants

View Source
const (
	LocalNodeTableInitializerName = "local"
)
View Source
const (
	NodeTableName = "nodes"
)

Variables

View Source
var (
	NodeNameIndex = statedb.Index[*Node, string]{
		Name: "name",
		FromObject: func(obj *LocalNode) index.KeySet {
			return index.NewKeySet(index.String(obj.Fullname()))
		},
		FromKey:    index.String,
		FromString: index.FromString,
		Unique:     true,
	}
	NodeByName = NodeNameIndex.Query

	// NodeAddressIndex indexes every address of the node. The index is non-unique
	// because configured Cilium internal router addresses may legitimately be
	// shared by every node. Writer resolves all other conflicts according to
	// source priority.
	NodeAddressIndex = statedb.Index[*Node, cmtypes.AddrCluster]{
		Name: "address",
		FromObject: func(obj *Node) index.KeySet {
			keys := make([]index.Key, 0, len(obj.IPAddresses)+4)
			for addr := range obj.addressClusters(nil) {
				keys = append(keys, nodeAddressKey(addr))
			}
			return index.NewKeySet(keys...)
		},
		FromKey:    nodeAddressKey,
		FromString: nodeAddressKeyString,
		Unique:     false,
	}
	NodeByAddress = NodeAddressIndex.Query

	NodeLocalIndex = statedb.Index[*Node, bool]{
		Name: "local",
		FromObject: func(obj *LocalNode) index.KeySet {
			if obj.Local == nil {

				return index.KeySet{}
			}
			return index.NewKeySet(index.Bool(true))
		},
		FromKey:    index.Bool,
		FromString: index.BoolString,
		Unique:     true,
	}

	NodeByLocal    = NodeLocalIndex.Query
	LocalNodeQuery = NodeByLocal(true)
)
View Source
var LocalNodeStoreCell = cell.Module(
	"local-node-store",
	"Provides LocalNodeStore for observing and updating local node info",

	cell.ProvidePrivate(NewNodeTable),
	cell.Provide(provideWriter),
	cell.Provide(NewNodeTableAndLocalNodeStore),
	cell.Provide(NewClusterSizeDependantInterval),
)

LocalNodeStoreCell provides the LocalNodeStore instance. The LocalNodeStore is the canonical owner of `types.Node` for the local node and provides a reactive API for observing and updating it.

LocalNodeStoreTestCell is a convenience for tests that provides a no-op LocalNodeSynchronizer. Use LocalNodeStoreCell in tests when you want to provide your own LocalNodeSynchronizer.

Functions

func FirstGlobalV4Addr added in v1.20.0

func FirstGlobalV4Addr(intf string, preferredIP net.IP) (net.IP, error)

firstGlobalV4Addr returns the first IPv4 global IP of an interface, where the IPs are sorted in creation order (oldest to newest).

All secondary IPs, except the preferredIP, are filtered out.

Public IPs are preferred over private ones. When intf is defined only IPs belonging to that interface are considered.

If preferredIP is present in the IP list it is returned irrespective of the sort order. However, if preferredIP is a private IP, a public IP will be returned if it is assigned to the intf

Passing intf and preferredIP will only return preferredIP if it is in the IPs that belong to intf.

In all cases, if intf is not found all interfaces are considered.

If a intf-specific global address couldn't be found, we retry to find an address with reduced scope (site, custom) on that particular device.

If the latter fails as well, we retry on all interfaces beginning with universe scope again (and then falling back to reduced scope).

In case none of the above helped, we bail out with error.

func FirstGlobalV6Addr added in v1.20.0

func FirstGlobalV6Addr(intf string, preferredIP net.IP) (net.IP, error)

firstGlobalV6Addr returns first IPv6 global IP of an interface, see firstGlobalV4Addr for more details.

func GetBootID added in v1.13.14

func GetBootID(logger *slog.Logger) string

func GetCiliumEndpointNodeIP added in v0.15.7

func GetCiliumEndpointNodeIP(localNode LocalNode) string

GetCiliumEndpointNodeIP is the node IP that will be referenced by CiliumEndpoints with endpoints running on this node.

func GetEndpointEncryptKeyIndex added in v1.14.7

func GetEndpointEncryptKeyIndex(localNode LocalNode, wgEnabled, ipsecEnabled bool) uint8

GetEndpointEncryptKeyIndex returns the encryption key value for an endpoint owned by the given local node. With IPSec encryption, this is the ID of the currently loaded key. With WireGuard, this returns a non-zero static value. Note that the key index returned by this function is only valid for _endpoints_ of the local node. If you want to obtain the key index of the local node itself, access the `EncryptionKey` field via the LocalNodeStore.

func GetEndpointID added in v0.15.7

func GetEndpointID() (uint64, bool)

GetEndpointID returns the ID of the host endpoint for this node. The boolean return value indicates whether the host endpoint ID has been set (true) or is still the uninitialized template value (false).

func GetExcludedIPs added in v0.15.7

func GetExcludedIPs() []net.IP

GetExcludedIPs returns a list of IPs from netdevices that Cilium needs to exclude to operate

func NewNodeTable

func NewNodeTable(db *statedb.DB) (statedb.RWTable[*Node], error)

func NewNodeTableAndLocalNodeStore

func NewNodeTableAndLocalNodeStore(params LocalNodeStoreParams) (
	*LocalNodeStore, NodeGetter, statedb.Table[*Node], error,
)

NewNodeTableAndLocalNodeStore constructs LocalNodeStore and the node table. Ensures that the local node object is present in the table.

func SetEndpointID added in v0.15.7

func SetEndpointID(id uint64)

SetEndpointID sets the ID of the host endpoint for this node.

func SetRouterInfo added in v0.15.7

func SetRouterInfo(info RouterInfo)

SetRouterInfo sets additional information for the router, the cilium_host interface.

func WaitForLocalNodeInit

func WaitForLocalNodeInit(ctx context.Context, db *statedb.DB, nodes statedb.Table[*Node]) (statedb.ReadTxn, error)

WaitForLocalNodeInit waits until the local-node initializer has completed. The nodes table may have other pending initializers, so callers interested only in the local node need not wait for the whole table to initialize.

Types

type Addressing added in v1.20.0

type Addressing interface {
	IPv6() AddressingFamily
	IPv4() AddressingFamily
}

Addressing implements addressing of a node

type AddressingFamily added in v1.20.0

type AddressingFamily interface {
	// Router is the address that will act as the router on each node where
	// an agent is running on. Endpoints have a default route that points
	// to this address.
	Router() net.IP

	// PrimaryExternal is the primary external address of the node. Nodes
	// must be able to reach each other via this address.
	PrimaryExternal() net.IP

	// AllocationCIDR is the CIDR used for IP allocation of all endpoints
	// on the node
	AllocationCIDR() netip.Prefix
}

AddressingFamily is the node addressing information for a particular address family

type ClusterSizeDependantIntervalFunc

type ClusterSizeDependantIntervalFunc func(time.Duration) time.Duration

ClusterSizeDependantIntervalFunc returns a time.Duration that is dependent on the cluster size, i.e. the number of nodes that have been discovered. This can be used to control sync intervals of shared or centralized resources to avoid overloading these resources as the cluster grows.

Example sync interval with baseInterval = 1 * time.Minute

nodes | sync interval ------+----------------- 1 | 41.588830833s 2 | 1m05.916737320s 4 | 1m36.566274746s 8 | 2m11.833474640s 16 | 2m49.992800643s 32 | 3m29.790453687s 64 | 4m10.463236193s 128 | 4m51.588744261s 256 | 5m32.944565093s 512 | 6m14.416550710s 1024 | 6m55.946873494s 2048 | 7m37.506428894s 4096 | 8m19.080616652s 8192 | 9m00.662124608s 16384 | 9m42.247293667s

func NewClusterSizeDependantInterval

func NewClusterSizeDependantInterval(
	db *statedb.DB,
	nodes statedb.Table[*Node],
) ClusterSizeDependantIntervalFunc

NewClusterSizeDependantInterval returns a function that computes intervals from the current size of the node table.

type Handler added in v1.20.0

type Handler interface {
	// Name identifies the handler, this is used in logging/reporting handler
	// reconciliation errors.
	Name() string

	// NodeAdd is called when a node is discovered for the first time.
	NodeAdd(newNode types.Node) error

	// NodeUpdate is called when a node definition changes. Both the old
	// and new node definition is provided. NodeUpdate() is never called
	// before NodeAdd() is called for a particular node.
	NodeUpdate(oldNode, newNode types.Node) error

	// NodeDelete is called after a node has been deleted
	NodeDelete(node types.Node) error

	// AllNodeValidateImplementation is called to validate the implementation
	// of all nodes in the node cache.
	AllNodeValidateImplementation()

	// NodeValidateImplementation is called to validate the implementation of
	// the node in the datapath. This function is intended to be run on an
	// interval to ensure that the datapath is consistently converged.
	NodeValidateImplementation(node types.Node) error
}

Handler handles node related events such as addition, update or deletion of nodes or changes to the local node configuration.

Node events apply to the local node as well as to remote nodes. The implementation can differ between the own local node and remote nodes by calling node.IsLocal().

type IDHandler added in v1.20.0

type IDHandler interface {
	// GetNodeIP returns the string node IP that was previously registered as the given node ID.
	GetNodeIP(uint16) string

	// GetNodeID gets the node ID for the given node IP. If none is found, exists is false.
	GetNodeID(nodeIP netip.Addr) (nodeID uint16, exists bool)

	// DumpNodeIDs returns all node IDs and their associated IP addresses.
	DumpNodeIDs() []*models.NodeID

	// RestoreNodeIDs restores node IDs and their associated IP addresses from the
	// BPF map and into the node handler in-memory copy.
	RestoreNodeIDs()
}

type LocalNode added in v0.15.7

type LocalNode = Node

LocalNode is an alias for the Node type to mark that we expect this to be the local node.

func (*LocalNode) RemoteSNATDstAddrExclusionCIDRv4 added in v1.20.0

func (n *LocalNode) RemoteSNATDstAddrExclusionCIDRv4() netip.Prefix

RemoteSNATDstAddrExclusionCIDRv4 returns a CIDR for SNAT exclusion. Any packet sent from a local endpoint to an IP address belonging to the CIDR should not be SNAT'd. The zero Prefix is returned if no CIDR is known.

func (*LocalNode) RemoteSNATDstAddrExclusionCIDRv6 added in v1.20.0

func (n *LocalNode) RemoteSNATDstAddrExclusionCIDRv6() netip.Prefix

RemoteSNATDstAddrExclusionCIDRv6 returns a IPv6 CIDR for SNAT exclusion. Any packet sent from a local endpoint to an IP address belonging to the CIDR should not be SNAT'd. The zero Prefix is returned if no CIDR is known.

type LocalNodeInfo added in v1.19.0

type LocalNodeInfo struct {
	// OptOutNodeEncryption will make the local node opt-out of node-to-node
	// encryption
	OptOutNodeEncryption bool
	// Unique identifier of the Kubernetes node, used to construct the
	// corresponding owner reference.
	UID k8stypes.UID
	// ID of the node assigned by the cloud provider.
	ProviderID string
	// v4 CIDR in which pod IPs are routable
	IPv4NativeRoutingCIDR netip.Prefix
	// v6 CIDR in which pod IPs are routable
	IPv6NativeRoutingCIDR netip.Prefix
	// ServiceLoopbackIPv4 is the source address used for SNAT when a Pod talks to
	// itself through a Service.
	ServiceLoopbackIPv4 netip.Addr
	// ServiceLoopbackIPv6 is the source address used for SNAT when a Pod talks to
	// itself through a Service.
	ServiceLoopbackIPv6 netip.Addr
	// IsBeingDeleted indicates that the local node is being deleted.
	IsBeingDeleted bool
	// UnderlayProtocol is the IP family of our underlay.
	UnderlayProtocol tunnel.UnderlayProtocol
}

LocalNodeInfo is the additional information about the local node that is only used internally.

Every field is a comparable value type, which lets DeepCopyInto and DeepEqual below be a plain assignment and a plain comparison.

+k8s:deepcopy-gen=false +deepequal-gen=false

func (*LocalNodeInfo) DeepCopy added in v1.19.0

func (in *LocalNodeInfo) DeepCopy() *LocalNodeInfo

DeepCopy creates a deep copy of the LocalNodeInfo.

func (*LocalNodeInfo) DeepCopyInto added in v1.19.0

func (in *LocalNodeInfo) DeepCopyInto(out *LocalNodeInfo)

DeepCopyInto copies the receiver into out. in must be non-nil.

func (*LocalNodeInfo) DeepEqual added in v1.19.0

func (in *LocalNodeInfo) DeepEqual(other *LocalNodeInfo) bool

DeepEqual compares two LocalNodeInfo structs for equality. in must be non-nil.

type LocalNodeStore added in v0.15.7

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

LocalNodeStore is the canonical owner for the local node object and provides a reactive API for observing and updating the state.

func NewTestLocalNodeStore added in v0.15.7

func NewTestLocalNodeStore(mockNode LocalNode) *LocalNodeStore

func (*LocalNodeStore) Get added in v0.15.7

func (s *LocalNodeStore) Get(ctx context.Context) (LocalNode, error)

Get retrieves the current local node. Use Get() only for inspecting the state, e.g. in API handlers. Do not assume the value does not change over time. Blocks until the store has been initialized.

func (*LocalNodeStore) Observe added in v1.13.0

func (s *LocalNodeStore) Observe(ctx context.Context, next func(LocalNode), complete func(error))

Observe changes to the local node state.

func (*LocalNodeStore) Update added in v0.15.7

func (s *LocalNodeStore) Update(update func(*LocalNode))

Update modifies the local node with a mutator.

func (*LocalNodeStore) WaitForNodeInformation added in v1.20.0

func (s *LocalNodeStore) WaitForNodeInformation(ctx context.Context) error

type LocalNodeStoreParams added in v0.15.7

type LocalNodeStoreParams struct {
	cell.In

	Logger      *slog.Logger
	Lifecycle   cell.Lifecycle
	Sync        LocalNodeSynchronizer
	DB          *statedb.DB
	Jobs        job.Group
	ClusterInfo cmtypes.ClusterInfo
	Nodes       statedb.RWTable[*LocalNode]
	NodeWriter  *Writer
}

LocalNodeStoreParams are the inputs needed for constructing LocalNodeStore.

type LocalNodeSynchronizer added in v1.15.0

type LocalNodeSynchronizer interface {
	InitLocalNode(context.Context, *LocalNode) error
	SyncLocalNode(context.Context, *LocalNodeStore)
	WaitForNodeInformation(context.Context, *LocalNodeStore) error
}

LocalNodeSynchronizer specifies how to build, and keep synchronized the local node object.

func NewNopLocalNodeSynchronizer added in v1.19.0

func NewNopLocalNodeSynchronizer() LocalNodeSynchronizer

type Node

type Node struct {
	types.Node

	// Local is non-nil if this is the local node. This carries additional
	// information about the local node that is not shared outside.
	Local *LocalNodeInfo

	// Statuses for reconcilers acting on this object.
	// DeepEqual is reserved for comparing the desired node data.
	// +deepequal-gen=false
	Statuses reconciler.StatusSet
	// contains filtered or unexported fields
}

Node is a Cilium node. It is the local node if Node.Local is non-nil.

+deepequal-gen=true

func (*Node) DeepCopy added in v1.5.0

func (n *Node) DeepCopy() *Node

DeepCopy returns a deep copy of the node.

func (*Node) DeepEqual

func (in *Node) DeepEqual(other *Node) bool

DeepEqual is an autogenerated deepequal function, deeply comparing the receiver with other. in must be non-nil.

func (*Node) TableHeader

func (n *Node) TableHeader() []string

TableHeader implements statedb.TableWritable.

func (*Node) TableRow

func (n *Node) TableRow() []string

TableRow implements statedb.TableWritable.

type NodeGetter added in v1.20.0

type NodeGetter interface {
	Get(ctx context.Context) (LocalNode, error)
}

NodeGetter describes the behavior of a node store used for retrieving the local node.

type NodeReconciler

type NodeReconciler string

NodeReconciler identifies a reconciler operating on the node table.

const (
	// LinuxNodeReconciler realizes nodes in the Linux datapath.
	LinuxNodeReconciler NodeReconciler = "linux"
	// WireGuardNodeReconciler realizes nodes in the WireGuard datapath.
	WireGuardNodeReconciler NodeReconciler = "wireguard"
)

func (NodeReconciler) String

func (r NodeReconciler) String() string

type PrefixClusterMutatorFn

type PrefixClusterMutatorFn = func(*nodeTypes.Node) []cmtypes.PrefixClusterOpts

PrefixClusterMutatorFn derives cluster-aware addressing options from a serialized node.

type RouterInfo added in v0.15.7

type RouterInfo interface {
	GetCIDRs() []netip.Prefix
}

func GetRouterInfo added in v0.15.7

func GetRouterInfo() RouterInfo

GetRouterInfo returns additional information for the router, the cilium_host interface.

type Writer

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

Writer provides source-aware write access to the node table.

func NewWriter

func NewWriter(log *slog.Logger, db *statedb.DB, nodes statedb.RWTable[*Node]) *Writer

NewWriter constructs a node table writer.

func (*Writer) Delete

func (w *Writer) Delete(txn statedb.WriteTxn, src source.Source, identity nodeTypes.Identity) bool

Delete removes a remote node if this writer's source still owns it. It reports whether the table changed.

func (*Writer) Refresh

func (w *Writer) Refresh(ctx context.Context, reconcilers ...NodeReconciler) error

Refresh marks the selected reconcilers pending for every node and waits for them to attempt processing the nodes (status is either Done or Error). If no reconcilers are specified, all registered reconcilers are refreshed. The error is [ctx.Err()] if context is cancelled.

func (*Writer) RegisterInitializer

func (w *Writer) RegisterInitializer(txn statedb.WriteTxn, name string) func(statedb.WriteTxn)

RegisterInitializer registers a producer that must finish its initial node listing before the table is considered initialized.

func (*Writer) RegisterReconciler

func (w *Writer) RegisterReconciler(name NodeReconciler)

RegisterReconciler adds the named reconciler to the list of required reconcilers and marks existing nodes pending for it. This list is passed to reconciler.StatusSet.Pending when nodes are created or updated. Panics if the reconciler has already been registered.

func (*Writer) SetPrefixClusterMutatorFn

func (w *Writer) SetPrefixClusterMutatorFn(mutator PrefixClusterMutatorFn)

SetPrefixClusterMutatorFn installs the cluster-address qualification hook. This hook must be set during Hive invoke time.

func (*Writer) Table

func (w *Writer) Table() statedb.Table[*Node]

Table returns read-only access to the node table.

func (*Writer) UnregisterReconciler

func (w *Writer) UnregisterReconciler(name NodeReconciler)

UnregisterReconciler removes the reconciler from the list of required reconcilers and removes its status from every node. The reconciler must be stopped before it is unregistered so it cannot write its status back.

func (*Writer) Upsert

func (w *Writer) Upsert(txn statedb.WriteTxn, n *nodeTypes.Node) bool

Upsert takes ownership of n and inserts or updates it if its source is allowed to overwrite the current owner. The caller must not modify n after calling Upsert. It reports whether the table changed. Conflicting weaker objects are not retained, so their producer must upsert them again if the winning object is later deleted.

func (*Writer) WaitUntilReconciled

func (w *Writer) WaitUntilReconciled(
	ctx context.Context,
	txn statedb.ReadTxn,
	requireDone bool,
) error

WaitUntilReconciled waits until all nodes present in txn have been reconciled. When requireDone is false, both done and error statuses are considered finished. When it is true, every status must be done.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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