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

246 lines
8.7 KiB
Go

// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package automode
import (
"context"
"errors"
"fmt"
"log/slog"
"github.com/google/uuid"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"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/config"
"github.com/dsx-ai-factory/nvke/controller/internal/constants"
"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/keys"
"github.com/dsx-ai-factory/nvke/controller/internal/otelx"
"github.com/dsx-ai-factory/nvke/controller/internal/temporal/workflows"
)
// Controller is responsible for auto-mode operations.
type Controller struct {
cfg config.Config
db *dbwrapper.DB
logger *slog.Logger
}
// NewController creates a new auto-mode controller.
func NewController(
cfg config.Config,
logger *slog.Logger,
dbInstance *dbwrapper.DB,
) *Controller {
return &Controller{
cfg: cfg,
db: dbInstance,
logger: logger,
}
}
// SetupWithManager wires the controller into controller-runtime with DB-backed sources.
func (c *Controller) SetupWithManager(mgr manager.Manager) error {
return dbreconcile.SetupController(
mgr,
"auto-mode-controller",
c,
dbwrapper.NewNodePoolSource(c.db, dbfilters.NodePool{ControlPlane: ptr.To(false)}),
dbwrapper.NewNodeSetSource(c.db, dbfilters.NodeSet{}, nodePoolKeysForNodeSet),
dbwrapper.NewNodeSource(c.db, dbfilters.Node{ControlPlane: ptr.To(false)}, nodePoolKeysForNode),
)
}
func nodePoolKeysForNodeSet(_ context.Context, nodeSet db.NodeSet) ([]dbreconcile.Key, error) {
if nodeSet.NodePoolID == uuid.Nil {
return nil, nil
}
return []dbreconcile.Key{dbreconcile.NodePoolKey(nodeSet.NodePoolID)}, nil
}
func nodePoolKeysForNode(_ context.Context, node db.Node) ([]dbreconcile.Key, error) {
if node.NodePoolID == uuid.Nil {
return nil, nil
}
return []dbreconcile.Key{dbreconcile.NodePoolKey(node.NodePoolID)}, nil
}
// Reconcile applies auto-mode for a single NodePool key.
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 {
nodePool, err := tx.GetNodePoolForUpdate(ctx, key.ID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
c.logger.Debug("Node pool not found, skipping auto-mode reconciliation", "nodePoolID", key.ID)
return nil
}
return fmt.Errorf("failed to get node pool: %w", err)
}
return c.reconcileAutoMode(ctx, tx, nodePool)
})
return reconcile.Result{}, err
}
// reconcileAutoMode:
//
// - Selects the oldest nodes from deprecated NodeSets that are eligible for recycling.
// - Applies the NeedsRecycle node condition, respecting the recycleBudget.
// - Only applied if (desiredCount - availableCount) < recycleBudget.
//
// NVSentinel (the downstream consumer of NeedsRecycle conditions) may:
// - Allow less recycle parallelism than recycleBudget at the NVKE layer.
// - Consider additional factors, such as cordon state of other nodes.
// - Enforce maintenance windows, leaving NeedsRecycle nodes in place until customer-specified windows.
func (c *Controller) reconcileAutoMode(ctx context.Context, tx db.Tx, nodePool db.NodePool) error {
logger := c.logger.With(
"nodePoolID", nodePool.ID,
"nodePoolName", nodePool.Name,
"nodePoolRecycleBudget", nodePool.RecycleBudget,
)
if nodePool.AutoModeDisabled {
logger.Debug("Node pool has auto-mode disabled, skipping auto-mode reconciliation")
return nil
}
if nodePool.RecycleBudget <= 0 {
logger.Debug("Node pool has no recycle budget, skipping auto-mode reconciliation")
return nil
}
if nodePool.ControlPlane {
logger.Debug("Node pool is a control plane, skipping auto-mode reconciliation")
return nil
}
if nodePool.Conditions.Deleting.Status == db.ConditionStatusTrue {
logger.Debug("Node pool is deleting, skipping auto-mode reconciliation")
return nil
}
if nodePool.CurrentNodeSetID == nil || *nodePool.CurrentNodeSetID == uuid.Nil {
logger.Debug("Node pool has no current node set, skipping auto-mode reconciliation")
return nil
}
nodes, err := c.selectNodesForRecycling(ctx, tx, nodePool)
if err != nil {
return fmt.Errorf("failed to select nodes for recycling: %w", err)
}
for _, node := range nodes {
logger.Info("Marking node for auto-mode recycling", "nodeID", node.ID, "nodeName", node.Name)
// Re-read under a row lock so MarkedForRecycling is applied on top of
// the latest persisted state.
lockedNode, err := tx.GetNodeForUpdate(ctx, node.ID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
// Node was deleted between selection and locking; skip it.
continue
}
return fmt.Errorf("failed to lock node: %w", err)
}
lockedNode.Conditions.MarkedForRecycling = db.NewCondition(true, "Marked for auto-mode recycling")
if _, err := tx.UpdateNode(ctx, &lockedNode); err != nil {
return fmt.Errorf("failed to update node conditions: %s: %w", lockedNode.ID, err)
}
workflowID := constants.ApplyK8sNodeConditionWorkflowPrefix + lockedNode.ID.String()
workflowCtx, span := otelx.StartWorkflowSpan(ctx, otelx.WorkflowEnqueue, otelx.WorkflowAttributes{
WorkflowType: workflows.ApplyK8sNodeConditionWorkflowType,
WorkflowID: workflowID,
ClusterID: lockedNode.ClusterID,
NodePoolID: lockedNode.NodePoolID,
NodePoolName: nodePool.Name,
NodeID: lockedNode.ID,
NodeName: lockedNode.Name,
})
_, err = tx.CreateWorkflowOutboxEntry(workflowCtx, workflows.ApplyK8sNodeConditionWorkflowType, workflowID, workflows.ApplyK8sNodeConditionInput{
NodeID: lockedNode.ID,
NodeCondition: corev1.NodeCondition{
Type: corev1.NodeConditionType(keys.NeedsRecycle.String()),
Status: corev1.ConditionTrue,
Reason: "Deprecated",
Message: "NVKE auto-mode recycling deprecated node",
LastTransitionTime: metav1.Now(),
},
})
otelx.EndWorkflowSpan(span, err)
if err != nil {
return fmt.Errorf("failed to create workflow outbox entry: %s: %w", lockedNode.ID, err)
}
}
return nil
}
func (c *Controller) selectNodesForRecycling(ctx context.Context, tx db.Tx, nodePool db.NodePool) ([]db.Node, error) {
// Available nodes are nodes that are:
// 1. K8s ready
// 2. Not Cordoned (unschedulable)
// 3. Not Deleting
// 4. Not Marked for Recycling
// 5. Not Marked for Repair
//
// This is a relatively conservative selection of nodes for recycling.
// The intention being to err on the side of recycling too few nodes rather than too many at any given time.
availableNodes, err := tx.ListNodes(ctx, db.NodeFilters{
NodePoolID: &nodePool.ID,
KubernetesReady: ptr.To(true),
KubernetesUnschedulable: ptr.To(false),
Deleting: ptr.To(false),
MarkedForRecycling: ptr.To(false),
MarkedForRepair: ptr.To(false),
})
if err != nil {
return nil, fmt.Errorf("failed to list available nodes: %w", err)
}
//
// Example 1:
// nodePool.DesiredCount = 250
// availableCount = 248
// nodePool.RecycleBudget = 10
// availableDeficit = 250 - 248 = 2
// iterationRecycleCount = 10 - 2 = 8 -> 8 nodes to recycle
//
// Example 2 (insufficient available capacity):
// nodePool.DesiredCount = 250
// availableCount = 230 (8 nodes not K8s ready, 2 nodes cordoned, 2 nodes deleting, 8 nodes marked for recycling)
// nodePool.RecycleBudget = 10
// availableDeficit = 250 - 230 = 20
// iterationRecycleCount = 10 - 20 = -10 -> 0 nodes to recycle
//
// Example 3 (surplus available capacity):
// nodePool.DesiredCount = 250
// availableCount = 260 (10 extra available nodes beyond desired)
// nodePool.RecycleBudget = 10
// availableDeficit = 250 - 260 = -10 -> 0
// iterationRecycleCount = 10 - 0 = 10 -> 10 nodes to recycle
//
// A negative availableDeficit means we have more available nodes than desired (node pool desired value reduced from a prior value).
// We can just set it to 0, which will allow the full recycle budget to be used, effectively treating the recycle budget as a hard cap.
availableDeficit := max(nodePool.DesiredCount-len(availableNodes), 0)
iterationRecycleCount := max(nodePool.RecycleBudget-availableDeficit, 0)
nodes, err := tx.ListNodesEligibleForRecycling(ctx, nodePool.ID, iterationRecycleCount)
if err != nil {
return nil, fmt.Errorf("failed to list nodes: %w", err)
}
return nodes, nil
}