Files
Terry Howe 46f04ce59e feat: write labels and annotations under nvke.nvidia.com and read both domains (#1713)
* feat(controller): add the keys package for the nvke.nvidia.com label domain

The labels, annotations, taints and node conditions this controller owns
move from nke.nvidia.com to nvke.nvidia.com. The rename is not atomic:
objects labelled by an earlier build keep the old keys until something
rewrites them, and a reboot or terminate request applied by hand arrives
under whichever domain the operator knows.

keys.Key holds the bare name and renders it under either domain. Callers
write Key.String(), always the new one, and read with Get/Value/Has/
Matches, which accept both. Key.All() is the delete form, because
removing only the new key leaves a legacy copy the next read would find.

Both domains are compiled in, as cluster-api-provider-nico did for its
own rename: there is no third domain anything could read, so there is
nothing to configure.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* feat(controller): write object keys under nvke.nvidia.com and read both domains

Routes every label, annotation, taint and node-condition key the
controller owns through internal/keys, and deletes the string constants
that held them. Writes land on nvke.nvidia.com; reads accept either
domain, preferring the new one.

Three places need more than a mechanical swap:

- Node topology labels are rewritten on reconcile, which drops the
  legacy key rather than leaving a node carrying both.
- Taint removal strips both domains. A node joined before the rename
  carries the provisioning taint under the legacy key, and a workflow
  untainting it may now be asking for the new one; removing only the
  requested form would leave the node NoSchedule for good.
- Reboot and terminate completion clears both forms of the request
  label, which an operator or an external automation may have applied
  under either.

Secret ownership labels converge the same way: a rewrite drops the
legacy key so a Secret carries one domain, not two that could drift.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* feat(nico): point the capnico reboot and repair annotations at nvke.nvidia.com

cluster-api-provider-nico watches exactly one Machine annotation for a
reboot and one for a repair, named by --reboot-annotation and
--repair-annotation, and silently ignores a request under any other key.
A mismatch is not an error anywhere: reboot and repair requests are
simply never actioned.

So the controller writes both annotations under both domains until every
deployment has moved, and these manifests move to the new one. Both keys
are owned by the same field manager, so clearing the annotation still
clears both. The dev capd-reboot-controller reads either form.

Sites that deploy capnico from their own manifests can move the flags on
their own schedule; see docs/operations/label-domain-migration.md.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* feat(cli): write the etcd key cluster-name annotation under nvke.nvidia.com

nvkectl writes this annotation onto the etcd encryption key Secret it
saves to disk, and reads it back to match a file to a cluster. The
legacy key stays exported so a file written by an earlier nvkectl is
still readable.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* feat(capp): write the SPIRE agent path annotation under nvke.nvidia.com

The provider owns this Machine annotation, so it is the thing that moves
a Machine over: the write drops the legacy key rather than leaving two
for the controller to choose between.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* docs: describe the nvke.nvidia.com label and annotation domain

What an existing site has to do (check the capnico flags, and anything
outside NVKE that matches on these keys), what it does not (relabel
objects, coordinate the upgrade, change how reboots are requested), and
which nke.nvidia.com names are deliberately not part of this change.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* chore: link the capnico dual-write to the issue that removes it

The two Machine annotations written in both domains are scaffolding for
a rollout, not a design. FIXME them against #1718 so the next reader
knows what has to be true before they go, and say in the migration guide
that a stale --reboot-annotation or --repair-annotation becomes a silent
failure once the dual write is gone.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* fix: address review feedback

- nodestatus: try the current domain before the legacy one when reading
  NeedsRecycle and NeedsRepair. Status.Conditions has no ordering
  guarantee, so matching either form took whichever came first: a stale
  legacy False left by an earlier build could mask a current True and
  drop the recycle or repair request it records.
- nico_spiffe_controller_test: assert absence against the rendered key.
  testify compares map keys without converting types, so a keys.Key
  needle made the NotContains pass even with the annotation present.
- capd-reboot-controller: honour a legacy reboot-complete timestamp.
  It already read a legacy reboot request but checked only the current
  completion key, so it replayed the simulated reboot and overwrote the
  completion it had already recorded.
- management-engine: reserve nvke.nvidia.com in the userParams.labels
  CEL rule, not just in the doc comment. The rule excluded the legacy
  domain only, so a label under the domain this controller now writes
  could pass CRD admission and collide with one NVKE owns. The REST API
  validator already rejected both domains; this aligns the two.

Signed-off-by: Terry Howe <thowe@nvidia.com>

* fix: address review feedback

Signed-off-by: Terry Howe <thowe@nvidia.com>

---------

Signed-off-by: Terry Howe <thowe@nvidia.com>
2026-10-16 15:51:06 -06:00

303 lines
11 KiB
Go

// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package nodeset
import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand/v2"
"github.com/google/uuid"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/dsx-ai-factory/nvke/controller/internal/clients"
"github.com/dsx-ai-factory/nvke/controller/internal/config"
"github.com/dsx-ai-factory/nvke/controller/internal/controllers/dbreconcile"
"github.com/dsx-ai-factory/nvke/controller/internal/controllers/dbreconcile/dbwrapper"
dbfilters "github.com/dsx-ai-factory/nvke/controller/internal/controllers/dbreconcile/filters"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
"github.com/dsx-ai-factory/nvke/controller/internal/naming"
"github.com/dsx-ai-factory/nvke/controller/internal/nodes"
)
// Controller is responsible for reconciling node sets.
type Controller struct {
cfg config.Config
db *dbwrapper.DB
logger *slog.Logger
}
func NewController(
cfg config.Config,
logger *slog.Logger,
dbInstance *dbwrapper.DB,
) *Controller {
return &Controller{
cfg: cfg,
db: dbInstance,
logger: logger,
}
}
func (c *Controller) SetupWithManager(mgr manager.Manager) error {
return dbreconcile.SetupController(
mgr,
"node-set-controller",
c,
dbwrapper.NewNodeSetSource(c.db, dbfilters.NodeSet{}),
dbwrapper.NewNodeSource(c.db, dbfilters.Node{}, nodeSetKeysForNode),
)
}
func nodeSetKeysForNode(_ context.Context, node db.Node) ([]dbreconcile.Key, error) {
if node.NodeSetID == uuid.Nil {
return nil, nil
}
return []dbreconcile.Key{dbreconcile.NodeSetKey(node.NodeSetID)}, nil
}
// Reconcile NodeSets, for each NodeSet:
// - Examine the NodeSet.DesiredCount
// - Create pending records for any missing nodes.
// - The node pool node scheduler will try to provision Pending Nodes when resources are available.
// - Delete pending nodes when the count is above the desired count.
// - !!! NOTE: Only pending nodes will be deleted. We do not currently delete or mark for deletion active nodes.
// - For non-current NodeSets the NodePoolController will have set the DesiredCount to 0.
// - So we will effectively delete all pending nodes from any non-current NodeSets.
//
// - (Future) Auto-deprovision down to desired count by applying the nvke.nvidia.com/maintenance-required label.
// - (Future) Perform in-place upgrades of existing node sets.
// - Only non-current node sets may be upgraded.
func (c *Controller) Reconcile(ctx context.Context, key dbreconcile.Key) (reconcile.Result, error) {
err := c.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
nodeSet, err := tx.GetNodeSet(ctx, key.ID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
c.logger.Debug("Node set not found, skipping node set reconciliation", "nodeSetID", key.ID)
return nil
}
return fmt.Errorf("failed to get node set %s: %w", key.ID, err)
}
return c.reconcileNodeSet(ctx, tx, nodeSet)
})
return reconcile.Result{}, err
}
func (c *Controller) reconcileNodeSet(ctx context.Context, tx db.Tx, nodeSet db.NodeSet) error {
nodePool, err := tx.GetNodePool(ctx, nodeSet.NodePoolID)
if err != nil {
return fmt.Errorf("failed to get node pool: %w", err)
}
nsLogger := c.logger.With(
"nodeSetID", nodeSet.ID,
"nodePoolID", nodePool.ID,
)
// The control-plane controller owns the control-plane node lifecycle, so
// control-plane node sets are never reconciled here.
if nodePool.ControlPlane {
nsLogger.Debug("Control-plane node set fully managed by control-plane controller; skipping")
return nil
}
if nodePool.AutoProvisionDisabled {
nsLogger.Debug("Node pool has auto-provision disabled, skipping node set reconciliation")
return nil
}
// If the node pool is deleting, skip reconciliation.
if nodePool.Conditions.Deleting.Status == db.ConditionStatusTrue {
nsLogger.Debug("Node pool is deleting, skipping node set reconciliation")
return nil
}
// Calculate how many nodes to provision
nsLogger, deficit, err := c.calculateNumberToProvision(ctx, tx, nodeSet, nsLogger)
if err != nil {
return fmt.Errorf("failed to calculate number to provision: %w", err)
}
switch {
case deficit == 0:
nsLogger.Debug("Node set is at desired count")
case deficit > 0:
nsLogger.Debug("Node set is below desired count")
cluster, err := tx.GetCluster(ctx, nodePool.ClusterID)
if err != nil {
return fmt.Errorf("failed to get cluster: %w", err)
}
// Create a pending node record for each node we need to provision, to come up to the desired count.
// The node pool node scheduler will then try to provision the pending node records when resources are available.
for range deficit {
createdNode, err := c.createPendingNode(ctx, tx, cluster, nodePool, nodeSet)
if err != nil {
return fmt.Errorf("failed to create node: %w", err)
}
nsLogger.Info("Created pending node", "nodeID", createdNode.ID, "nodeName", createdNode.Name)
}
case deficit < 0:
nsLogger.Debug("Node set is above desired count, delete pending nodes, skip auto-teardown")
// We could implement auto-teardown to get back down to the desired count.
// This is potentially risky, because a misconfiguration or a bug could quickly cause an SLO breach or outage.
// Additionally if we implement the constant maintenance via label it will take care of itself.
// - Whenever a node is terminated for maintenance if the node pool count is >= desired count, no new node will be auto-provisioned back in.
// - so it would eventually get back to the desired count.
// - We still have the delete node capability from the API.
//
// For these reasons, we only delete pending node records if there is a surplus.
// So that the node pool node scheduler does not provision nodes into a node pool, and thus consume forge resources, that would be above the desired count.
pendingNodes, err := tx.ListNodes(ctx, db.NodeFilters{
NodeSetID: &nodeSet.ID,
Pending: ptr.To(true),
ProvisioningClaimed: ptr.To(false),
})
if err != nil {
return fmt.Errorf("failed to list nodes: %w", err)
}
// Try to delete nodes, until we have deleted the surplus, or we have deleted all pending nodes.
// Skipping any that are locked (being provisioned), we will either get another pending node to delete,
// or the next Reconcile() will try again.
// To prevent race conditions where this controller attempts to delete a pending
// node that has a provision workflow running, but hasn't marked the node as provisioning yet.
surplus := max(deficit*-1, 0)
deletedCount := 0
for _, pendingNode := range pendingNodes {
if deletedCount >= surplus {
break
}
deleted, err := c.deletePendingNode(ctx, tx, pendingNode, nsLogger)
if err != nil {
return fmt.Errorf("failed to delete pending node: %w", err)
}
if !deleted {
continue
}
deletedCount++
nsLogger.Info("Deleted pending node", "nodeID", pendingNode.ID, "nodeName", pendingNode.Name, "deletedCount", deletedCount, "surplus", surplus)
}
}
return nil
}
func (c *Controller) calculateNumberToProvision(ctx context.Context, tx db.Tx, nodeSet db.NodeSet, nsLogger *slog.Logger) (*slog.Logger, int, error) {
nodeSetNodes, err := tx.ListNodes(ctx, db.NodeFilters{NodeSetID: &nodeSet.ID})
if err != nil {
return nsLogger, 0, fmt.Errorf("failed to list nodes: %w", err)
}
// Note: The actual count includes nodes that are provisioning / deleting down.
actualCount := len(nodeSetNodes)
// Calculate how many nodes we need to reach desired state
// example: desiredCount = 10, actual = 4, deficit = 6
// example: desiredCount = 10, actual = 14, deficit = -4
deficit := nodeSet.DesiredCount - actualCount
nsLogger = nsLogger.With(
"desiredCount", nodeSet.DesiredCount,
"actualCount", actualCount,
"deficit", deficit,
)
return nsLogger, deficit, nil
}
func (c *Controller) createPendingNode(ctx context.Context, tx db.Tx, cluster db.Cluster, nodePool db.NodePool, nodeSet db.NodeSet) (db.Node, error) {
if !nodePool.IsCurrentNodeSet(nodeSet.ID) {
return db.Node{}, fmt.Errorf("node set is non-current")
}
existingNodeNames, err := tx.ListClusterNodeNames(ctx, cluster.ID)
if err != nil {
return db.Node{}, fmt.Errorf("failed to list cluster node names: %w", err)
}
dbNode := db.Node{
ClusterID: cluster.ID,
NodePoolID: nodePool.ID,
NodeSetID: nodeSet.ID,
ControlPlane: nodePool.ControlPlane,
Name: naming.GenerateNodeName(existingNodeNames, cluster.Name, nodePool.NodeNamePrefix, rand.IntN),
Conditions: db.NodeConditions{
Pending: db.NewCondition(true, "Pending node provisioning"),
ProvisioningClaimed: db.NewCondition(false, "Provisioning workflow has not claimed node"),
Provisioning: db.NewCondition(false, "Not yet provisioning"),
ReadyToJoin: db.NewCondition(false, "Not yet ready to join"),
Joined: db.NewCondition(false, "Not yet joined"),
Provisioned: db.NewCondition(false, "Not yet provisioned"),
Deleting: db.NewCondition(false, "Node is not being deleted"),
KubernetesReady: db.NewCondition(false, "Status unknown"),
KubernetesUnschedulable: db.NewCondition(false, "Status unknown"),
NodeAgentReady: db.NewCondition(false, "Status unknown"),
},
}
nodes.PinAgentProfile(&dbNode, c.cfg)
nodeProvider, err := clients.GetNewNodeProvider(cluster)
if err != nil {
return db.Node{}, err
}
if err := nodeProvider.ApplyNodePoolNodePayload(nodePool, &dbNode); err != nil {
return db.Node{}, err
}
createdNode, err := tx.CreateNode(ctx, &dbNode)
if err != nil {
return db.Node{}, fmt.Errorf("failed to create node: %w", err)
}
return createdNode, nil
}
func (c *Controller) deletePendingNode(ctx context.Context, tx db.Tx, pendingNode db.Node, nsLogger *slog.Logger) (bool, error) {
// Try to acquire lock - fail/continue fast if already held
acquired, err := tx.TryAcquireNodeProvisioningLock(ctx, pendingNode.ID)
if err != nil {
return false, fmt.Errorf("failed to try to acquire lock for pending node %s: %w", pendingNode.ID, err)
}
if !acquired {
nsLogger.Debug("Pending Node is being provisioned, skipping deletion", "nodeID", pendingNode.ID)
return false, nil
}
nodeForUpdate, err := tx.GetNodeForUpdate(ctx, pendingNode.ID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
nsLogger.Debug("Pending node disappeared before deletion", "nodeID", pendingNode.ID)
return false, nil
}
return false, fmt.Errorf("failed to get node for update: %w", err)
}
if nodeForUpdate.Conditions.Pending.Status != db.ConditionStatusTrue ||
nodeForUpdate.Conditions.ProvisioningClaimed.Status == db.ConditionStatusTrue {
nsLogger.Debug("Pending node is no longer eligible for deletion",
"nodeID", pendingNode.ID,
"pending", nodeForUpdate.Conditions.Pending.Status,
"provisioningClaimed", nodeForUpdate.Conditions.ProvisioningClaimed.Status,
)
return false, nil
}
err = tx.DeleteNode(ctx, pendingNode.ID)
if err != nil {
return false, fmt.Errorf("failed to delete node: %w", err)
}
return true, nil
}