mirror of
https://github.com/dsx-ai-factory/nvke.git
synced 2026-12-07 04:35:58 +08:00
* refactor(controller): ask one cluster method at each control-plane endpoint gate Each gate that scales, upgrades or replaces control-plane nodes tested the control-plane VIP for an empty string by itself. The gates now call db.Cluster.HasStableControlPlaneEndpoint, which is true when the cluster has a VIP. The gates are the count check at create and scale, the upgrade and rollout checks of the cluster API, the node delete guard, the control-plane controller (recycling, remediation, rebalance, stuck pending nodes) and the node pool controller (surge, NodeSet replacement). No behavior changes. A later change adds a second kind of stable endpoint to the method. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * feat(controller): add controlPlaneEndpoint to the cluster API schema A cluster can name an API server endpoint that NVKE does not manage, for example a load balancer in front of the API servers. The create request gets the optional object controlPlaneEndpoint. Its type says who manages the endpoint, and the block named after the type carries what that type needs. This change has one type, External, with a host and an optional port in the external block. The port defaults to 6443. The cluster response returns the type and the resolved host and port. The update request has no such property, so the value is fixed at creation. The shape is the one of the proposal for a load balancer as the control plane endpoint, and this change is its first part. The enum of the type has only External. The other types of the proposal come later. A new enum value passes the API compatibility check, and a removed one does not, so the enum lists only what the code does. The existing descriptions change only where the new field makes them wrong or incomplete: - The overview of the Clusters tag and the description of controlPlaneVIP say which address is the API server endpoint. - Seven sentences that say an operation requires controlPlaneVIP now name both fields. Each is one changed line. - The 400 list of the create operation gets the new reasons. - The desiredNodeCount descriptions of the two node pool requests lose their sentence about control-plane pools. The node pool handlers refuse each create and each update of a control-plane node pool, so no request reaches a rule on that count. This change is only api/openapi.yaml and the code that make generate writes from it (models.gen.go, server.gen.go). The handler does not read the field yet. The next changes store it, check it and use it. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * feat(controller): store controlPlaneEndpoint in the clusters table The clusters table gets three nullable columns for the API server endpoint that a cluster was created with: control_plane_endpoint_type, control_plane_endpoint_host and control_plane_endpoint_port. db.Cluster gets the fields ControlPlaneEndpointType, ControlPlaneEndpointHost and ControlPlaneEndpointPort. The type says who manages the endpoint. The one type is External, an endpoint that NVKE does not manage. The host and the port are the resolved endpoint. A cluster without the field stores NULL in the three columns, which is what each existing row has after the migration. An empty type marks such a row. control_plane_vip does not change. No handler writes the fields yet and no workflow reads them. The test proves that the values come back from a read and stay in the row through an update of the cluster. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * feat(controller): count controlPlaneEndpoint as a stable endpoint at each gate db.Cluster.HasStableControlPlaneEndpoint is now true for a cluster with an endpoint of the type External, as it is for one with a VIP. Each gate that scales, upgrades or replaces control-plane nodes asks this method, so the one line opens them all: scale-up, upgrade and rollout in the cluster API, node delete, recycling, remediation, rebalance, stuck pending nodes, surge and NodeSet replacement. The method reads the stored type and not the host. An empty type is a cluster without the field, and a type that this controller does not know is no stable endpoint. The tests run each gate with such a cluster. Recycling, remediation, rebalance and stuck pending nodes share one check, controlPlaneReplacementBlocked, which gets its own test. The 400 messages and the log warnings of the gates keep their text. Each of them is given only for a cluster with no VIP and no controlPlaneEndpoint. allowControlPlaneWithoutVIP keeps its meaning and its default. No cluster has the field yet, because the create request does not store it. A later change adds that, with the count check at create. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * feat(controller): check controlPlaneEndpoint on cluster create The create request is now rejected with 400 when it has both controlPlaneEndpoint and controlPlaneVIP, when the type is not External, when the type External has no external block, and when the host or the port is not valid. The host is a DNS name or an IPv4 address. A DNS name is lowercase, has at most 253 characters, no trailing dot and no wildcard. An IPv4 address must be unicast, not loopback and not link-local, and outside the pod and service CIDRs. The port is a number from 1 to 65535, and 6443 when the request has none. A host of only digits and dots must be a valid IPv4 address, so that a mistyped address does not pass as a DNS name and skip the address rules. A DNS name is not checked against the CIDRs, because NVKE cannot tell which addresses it resolves to. The host is not trimmed. NVKE does not resolve or dial the endpoint. The CIDR rule of controlPlaneVIP moves into a helper that both fields use. Its messages keep their text, and the checks of controlPlaneVIP do not change. The checks come before the change that stores the value, so that no commit stores a value without them. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * feat(controller): use controlPlaneEndpoint for kubeadm init kubeadm init now takes its controlPlaneEndpoint from one function, kubeadmControlPlaneEndpoint. For a cluster with an external endpoint the value is host:port. Without one it is the kube-vip VIP, then the IP of the initializing node, as before. The value goes into the ClusterConfiguration and into the request to the node agent, as before. NVKE also names the host of an external endpoint in apiServer.certSANs of the ClusterConfiguration. kubeadm adds the host of its controlPlaneEndpoint to the API server certificate by itself. The explicit entry keeps certificate renewal and control-plane joins correct if that default changes. A cluster without an external endpoint gets no certSANs entry, so its configuration does not change. The step fails for a cluster row with an endpoint type that this controller does not know, and for an external endpoint with no host or no port. The address goes into each certificate and each kubeconfig of the cluster, so the step does not guess. The kube-vip step needs no change and gets no check for the new field. It returns with no action for a cluster without a VIP, and a cluster with a controlPlaneEndpoint has no VIP: the create request refuses the two fields together, and no other request writes either of them to the cluster row. One test keeps this true: for such a cluster the step makes no kube-vip call and runs no script on the node. Each later step reads the endpoint back from what kubeadm wrote: the join string, admin.conf and the Cluster API endpoint. They need no change. No cluster has the field yet. The next change makes the create request store it. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * feat(controller): accept controlPlaneEndpoint on cluster create The create request now stores controlPlaneEndpoint in the cluster row: the type, the host and the resolved port, which is 6443 when the request names none. The cluster response returns the type and the resolved host and port. The response leaves the field out when the cluster has none. The count check at create asks HasStableControlPlaneEndpoint of the fields that the request would store. So a request with an external endpoint can ask for more than one control-plane node, as one with a VIP can. The tests go through the service and through the HTTP handler with the OpenAPI validator: at each level requests that are accepted and requests that are refused, then the bounds that only the schema checks, and a PATCH with the field, which the schema refuses. One test checks the JSON form of the field in the response. The full table of refused values is in the test of the check itself. This change comes after each part that reads the value, so that no cluster can have the field before kubeadm init uses it. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * docs: describe controlPlaneEndpoint for workload clusters The pages that state the VIP rule now name controlPlaneEndpoint as the second way to give a cluster a stable API address: the cluster spec table and the count rule in the create guide, the API address in the two access pages, the upgrade rule in the supported platforms, and the installation plan. The create guide shows the object with the type External, its host and its port, and says what the response returns. It says what the endpoint must do before the request, and that NVKE does not resolve or call the endpoint when it accepts the request. The access page says that NVKE does not take a node out of the endpoint before it restarts the API server or etcd there, so the health check of the endpoint must do it. The pages come after the change that stores the value, so that each sentence is true when it is added. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * fix(controller): reject a DNS label over 63 characters in controlPlaneEndpoint The host check of an external control plane endpoint used IsDNS1123Subdomain, which checks the whole length and the form of a DNS name and not the length of each label. So a name with a label of 64 characters passed the check, and DNS has no such name. The check now also rejects a label of more than 63 characters. The text of the field in the spec says so, and the generated code follows it. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> * docs: say that an endpoint health check acts after the failure The access page said that the endpoint must stop traffic to a node through its own health check. A health check sees a failure only after it happens, so a call can fail between the restart of the API server or of etcd and that check. The page says so now. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com> --------- Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>
285 lines
11 KiB
Go
285 lines
11 KiB
Go
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package nodepool
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"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"
|
|
)
|
|
|
|
// Controller is responsible for reconciling node pools.
|
|
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 (a *Controller) SetupWithManager(mgr manager.Manager) error {
|
|
return dbreconcile.SetupController(
|
|
mgr,
|
|
"node-pool-controller",
|
|
a,
|
|
dbwrapper.NewNodePoolSource(a.db, dbfilters.NodePool{}),
|
|
dbwrapper.NewNodeSource(a.db, dbfilters.Node{}, nodePoolKeysForNode),
|
|
)
|
|
}
|
|
|
|
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 a NodePool:
|
|
// - Create a new Current NodeSet If:
|
|
// - A current NodeSet doesn't exist.
|
|
// - The NodePool's Release or ConfigProfile has changed.
|
|
//
|
|
// - Distribute the desired count of the NodePool to the NodeSets.
|
|
// - Set the DesiredCount of the current NodeSet to be the DesiredCount of the NodePool
|
|
// less the actual node count of nodes assigned to non-current NodeSets.
|
|
// - Delete non-current NodeSets when their actual node count is 0.
|
|
// - Update the DesiredCount of non-current NodeSets to 0.
|
|
func (a *Controller) Reconcile(ctx context.Context, key dbreconcile.Key) (reconcile.Result, error) {
|
|
err := a.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
|
|
// Discover the parent before taking any row locks. Legacy CP pools share
|
|
// the same cluster-first admission mutex as the control-plane controller.
|
|
pool, err := tx.GetNodePool(ctx, key.ID)
|
|
if err != nil {
|
|
if errors.Is(err, db.ErrNotFound) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("reading node pool: %w", err)
|
|
}
|
|
if pool.ControlPlane {
|
|
cluster, err := tx.GetClusterForUpdate(ctx, pool.ClusterID)
|
|
if err != nil {
|
|
return fmt.Errorf("locking cluster for control-plane node pool: %w", err)
|
|
}
|
|
if db.ControlPlaneMutationBlocked(cluster) {
|
|
return db.ErrControlPlaneMutationBlocked
|
|
}
|
|
}
|
|
nodePool, err := tx.GetNodePoolForUpdate(ctx, key.ID)
|
|
if err != nil {
|
|
if errors.Is(err, db.ErrNotFound) {
|
|
a.logger.Debug("Node pool not found, skipping reconciliation", "nodePoolID", key.ID)
|
|
return nil
|
|
}
|
|
return fmt.Errorf("failed to get node pool: %w", err)
|
|
}
|
|
|
|
return a.reconcileNodePool(ctx, tx, nodePool)
|
|
})
|
|
if errors.Is(err, db.ErrControlPlaneMutationBlocked) {
|
|
return reconcile.Result{RequeueAfter: 30 * time.Second}, nil
|
|
}
|
|
return reconcile.Result{}, err
|
|
}
|
|
|
|
func (a *Controller) reconcileNodePool(ctx context.Context, tx db.Tx, nodePool db.NodePool) error {
|
|
logger := a.logger.With(
|
|
"nodePoolID", nodePool.ID,
|
|
"nodePoolDesiredCount", nodePool.DesiredCount,
|
|
"maxSurge", nodePool.MaxSurge,
|
|
)
|
|
|
|
var err error
|
|
|
|
if nodePool.AutoProvisionDisabled {
|
|
logger.Debug("Node pool has auto-provision disabled, skipping node pool reconciliation")
|
|
return nil
|
|
}
|
|
|
|
// If the node pool is deleting, skip reconciliation.
|
|
if nodePool.Conditions.Deleting.Status == db.ConditionStatusTrue {
|
|
logger.Debug("Node pool is deleting, skipping node pool reconciliation")
|
|
return nil
|
|
}
|
|
|
|
cluster, err := tx.GetCluster(ctx, nodePool.ClusterID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get cluster: %w", err)
|
|
}
|
|
|
|
var currentNodeSet db.NodeSet
|
|
if nodePool.CurrentNodeSetID != nil {
|
|
currentNodeSet, err = tx.GetNodeSet(ctx, *nodePool.CurrentNodeSetID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get current node set: %w", err)
|
|
}
|
|
}
|
|
|
|
nodePool, currentNodeSet, err = a.createNodeSetIfChanged(ctx, tx, cluster, nodePool, currentNodeSet, logger)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
nodeSets, err := tx.ListNodeSets(ctx, db.NodeSetFilters{NodePoolID: &nodePool.ID})
|
|
if err != nil {
|
|
return fmt.Errorf("failed to list node sets: %w", err)
|
|
}
|
|
|
|
// Set the desiredNodeCount of every non-current NodeSet to 0.
|
|
// And count the number of nodes in non-current node sets.
|
|
nodesInNonCurrentNodeSets := 0
|
|
for _, nodeSet := range nodeSets {
|
|
if nodeSet.ID == currentNodeSet.ID {
|
|
// This is the current node set, so we don't need to do anything other than reset the currentNodeSet.
|
|
currentNodeSet = nodeSet
|
|
continue
|
|
}
|
|
|
|
// If we wanted to be strict about NodePoolController only interacting with NodeSets we could
|
|
// Add an ActualCount field to NodeSet, and have NodeSet Controller update it (similar to status in k8s)
|
|
// - However that is essentially Len(nodes where NodeSetID = xx).
|
|
nodeSetNodes, err := tx.ListNodes(ctx, db.NodeFilters{NodeSetID: &nodeSet.ID})
|
|
if err != nil {
|
|
return fmt.Errorf("failed to list nodes: %w", err)
|
|
}
|
|
|
|
nodesInNonCurrentNodeSets += len(nodeSetNodes)
|
|
|
|
// If there are no nodes in the non-current node set, delete it.
|
|
// Else set the desired count to 0.
|
|
if len(nodeSetNodes) == 0 {
|
|
if err := tx.DeleteNodeSet(ctx, nodeSet.ID); err != nil {
|
|
return fmt.Errorf("failed to delete non-current node set: %w", err)
|
|
}
|
|
logger.Info("Deleted non-current node set", "nodeSetID", nodeSet.ID)
|
|
} else {
|
|
nodeSet.DesiredCount = 0
|
|
if _, err := tx.UpdateNodeSet(ctx, &nodeSet); err != nil {
|
|
return fmt.Errorf("failed to update non-current node set: %w", err)
|
|
}
|
|
logger.Debug("Updated non-current node set desired count", "nodeSetID", nodeSet.ID, "desiredCount", nodeSet.DesiredCount)
|
|
}
|
|
}
|
|
|
|
// Calculate surge nodes for migration
|
|
// Only surge when there are deprecated nodes to migrate, enabling faster rollout
|
|
// Cap surge to the number of deprecated nodes (no point surging more than what we're migrating)
|
|
surgeNodes := min(nodePool.MaxSurge, nodesInNonCurrentNodeSets)
|
|
if !a.cfg.AllowControlPlaneWithoutVIP && nodePool.ControlPlane && surgeNodes > 0 && !cluster.HasStableControlPlaneEndpoint() {
|
|
logger.Warn("Skipping control-plane surge because controlPlaneVIP is not configured")
|
|
surgeNodes = 0
|
|
}
|
|
|
|
// Set the desired count of the current nodeSet to be the desired count of the node pool
|
|
// less the actual node count of nodes assigned to non-current NodeSets,
|
|
// plus surge nodes for migration.
|
|
//
|
|
// Even though the desired count for a non-current node set is 0,
|
|
// we still need to account for the actual nodes that exist in the non-current node sets
|
|
// so that we don't over-provision the current node set.
|
|
// This will be re-calculated as nodes are de-provisioned or deleted from the non-current node sets.
|
|
currentNodeSetDesiredCount := max(0, nodePool.DesiredCount-nodesInNonCurrentNodeSets+surgeNodes)
|
|
|
|
// Cap the desired count to never exceed nodePool.DesiredCount
|
|
// This prevents creating extra surge nodes after all non-current nodes are deleted
|
|
// if there are any race conditions, the current node set desired count will be adjusted to the node pool desired count.
|
|
// Example: nodePool.DesiredCount=2, nodesInNonCurrentNodeSets=0 → cap 3 to 2
|
|
currentNodeSetDesiredCount = min(currentNodeSetDesiredCount, nodePool.DesiredCount)
|
|
|
|
if currentNodeSet.DesiredCount != currentNodeSetDesiredCount {
|
|
currentNodeSet.DesiredCount = currentNodeSetDesiredCount
|
|
if _, err := tx.UpdateNodeSet(ctx, ¤tNodeSet); err != nil {
|
|
return fmt.Errorf("failed to update current node set: %w", err)
|
|
}
|
|
|
|
logger.Info("Updated current node set desired count", "nodeSetID", currentNodeSet.ID, "desiredCount", currentNodeSet.DesiredCount, "nodesInNonCurrentNodeSets", nodesInNonCurrentNodeSets)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// createNodeSetIfChanged compares the pool's provider payload and common
|
|
// fields against the current NodeSet, and creates a new NodeSet when
|
|
// anything has changed. Provider-specific payload comparison and
|
|
// construction are delegated to clients.NodeSetProvider so this stays
|
|
// provider-agnostic.
|
|
func (a *Controller) createNodeSetIfChanged(
|
|
ctx context.Context, tx db.Tx,
|
|
cluster db.Cluster, nodePool db.NodePool, currentNodeSet db.NodeSet,
|
|
logger *slog.Logger,
|
|
) (db.NodePool, db.NodeSet, error) {
|
|
if !db.NodePoolNeedsNewNodeSet(nodePool, currentNodeSet) {
|
|
return nodePool, currentNodeSet, nil
|
|
}
|
|
|
|
provider, err := clients.GetProviderClient(cluster)
|
|
if err != nil {
|
|
return nodePool, currentNodeSet, err
|
|
}
|
|
newNodeSet := buildBaseNodeSet(nodePool)
|
|
if err := provider.NodeSetProvider().ApplyNodeSetProvider(nodePool, newNodeSet); err != nil {
|
|
return nodePool, currentNodeSet, err
|
|
}
|
|
return a.applyNewNodeSet(ctx, tx, cluster, nodePool, currentNodeSet, newNodeSet, logger)
|
|
}
|
|
|
|
// buildBaseNodeSet returns a new NodeSet pre-populated with the provider-independent
|
|
// fields from the node pool. The caller must call SetNico or SetCapi before persisting.
|
|
func buildBaseNodeSet(nodePool db.NodePool) *db.NodeSet {
|
|
return &db.NodeSet{
|
|
ID: uuid.New(),
|
|
NodePoolID: nodePool.ID,
|
|
KubernetesVersion: nodePool.KubernetesVersion,
|
|
SystemReservedMemory: nodePool.SystemReservedMemory,
|
|
KubeReservedMemory: nodePool.KubeReservedMemory,
|
|
TeleportEnabled: nodePool.TeleportEnabled,
|
|
}
|
|
}
|
|
|
|
// applyNewNodeSet persists the new NodeSet and updates the pool's current NodeSet pointer.
|
|
func (a *Controller) applyNewNodeSet(
|
|
ctx context.Context, tx db.Tx,
|
|
cluster db.Cluster, nodePool db.NodePool, prevNodeSet db.NodeSet, newNodeSet *db.NodeSet,
|
|
logger *slog.Logger,
|
|
) (db.NodePool, db.NodeSet, error) {
|
|
if !a.cfg.AllowControlPlaneWithoutVIP && nodePool.ControlPlane && nodePool.CurrentNodeSetID != nil && !cluster.HasStableControlPlaneEndpoint() {
|
|
logger.Warn("Skipping control-plane NodeSet replacement because controlPlaneVIP is not configured")
|
|
return nodePool, prevNodeSet, nil
|
|
}
|
|
|
|
currentNodeSet, err := tx.CreateNodeSet(ctx, newNodeSet)
|
|
if err != nil {
|
|
return nodePool, db.NodeSet{}, fmt.Errorf("failed to create node set: %w", err)
|
|
}
|
|
nodePool.CurrentNodeSetID = ¤tNodeSet.ID
|
|
nodePool, err = tx.UpdateNodePool(ctx, &nodePool)
|
|
if err != nil {
|
|
return nodePool, currentNodeSet, fmt.Errorf("failed to update node pool: %w", err)
|
|
}
|
|
logger.Info("Created new current node set", "nodeSetID", currentNodeSet.ID, "desiredCount", 0)
|
|
return nodePool, currentNodeSet, nil
|
|
}
|