feat(controller)!: converge control-plane node-agent versions (#1353)

* refactor(agent)!: use version and method for agent updates

Signed-off-by: Chao Chen <chaoch@nvidia.com>

* feat(controller): converge control-plane node-agent versions

Signed-off-by: Chao Chen <chaoch@nvidia.com>

* test: cover agent convergence and deletion recovery

Signed-off-by: Chao Chen <chaoch@nvidia.com>

* docs: explain control-plane node-agent updates

Signed-off-by: Chao Chen <chaoch@nvidia.com>
This commit is contained in:
Chao
2026-10-14 11:26:08 -07:00
committed by GitHub
parent a12794be51
commit f520e100aa
79 changed files with 6041 additions and 2723 deletions
+5 -1
View File
@@ -90,10 +90,12 @@ checkout, and do not stub a dependency to make the build pass.
| `controller/deploy/charts/controller/files/crds.yaml` | `make chart-crds` output (kustomize over the `management-engine` CRDs) | **No — regenerate** |
| `agent/pkg/agent/proto/*.pb.go` | buf/protoc output | **No — regenerate** |
| `agent/THIRD_PARTY_NOTICES.md` | go-licenses output | **No — regenerate** |
| `controller/deploy/charts/` | Helm charts | Yes. Do not bump `Chart.yaml`: its `0.0.0` is a placeholder and the release workflows set the version from the `controller/vX.Y.Z` tag |
| `controller/deploy/charts/` | Helm charts | Yes. Preserve the version placeholders; see below. |
| `nktp/deploy/charts/` | NKTP telemetry Helm chart | Yes, but bump the chart version. Read `nktp/AGENTS.md` |
| `controller/deploy/dashboards/` | Grafana reference dashboards (JSON import) | Yes — read that directory's `AGENTS.md`. Do not bump the Helm chart for dashboard-only edits |
Keep the controller chart's `version`, `appVersion`, and README version badge at `0.0.0`.
## What agents may do
- Implement or fix logic under `agent/internal/`, `agent/pkg/`,
@@ -171,6 +173,8 @@ checkout, and do not stub a dependency to make the build pass.
every parameter on its own line.
- Exported types and functions carry doc comments starting with the identifier
name.
- Append new fields after existing fields in handwritten structs and struct
initializers. Keep `ID` and other existing fields in their current order.
### Preferred and deprecated patterns
+7 -7
View File
@@ -15,14 +15,14 @@ import (
"github.com/dsx-ai-factory/nvke/agent/pkg/agentupgrade"
)
const defaultOperationRoot = "/var/lib/nvke/agent-upgrades"
const defaultOperationRoot = agentupgrade.DefaultRoot
// version is set at build time via -ldflags "-X main.version=<version>".
var version = "dev"
func main() {
versionFlag := flag.Bool("version", false, "Print the version and exit")
operationID := flag.String("operation-id", "", "durable node-agent upgrade operation ID")
requestKey := flag.String("request", "", "target version and installation method, separated by an underscore")
operationRoot := flag.String("operation-root", defaultOperationRoot, "durable node-agent upgrade operation root")
flag.Parse()
if *versionFlag {
@@ -32,8 +32,8 @@ func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
if err := agentupgrade.ValidateOperationID(*operationID); err != nil {
slog.Error("invalid node-agent upgrade operation", "operationID", *operationID, "err", err)
if err := agentupgrade.ValidateRequestKey(*requestKey); err != nil {
slog.Error("invalid node-agent upgrade operation", "requestKey", *requestKey, "err", err)
os.Exit(2)
}
@@ -41,9 +41,9 @@ func main() {
defer stop()
store := agentupgrade.NewStore(*operationRoot)
updater := agentupgrade.NewUpdater(store)
if err := updater.Run(ctx, *operationID); err != nil {
slog.Error("node-agent updater operation failed", "operationID", *operationID, "err", err)
if err := updater.Run(ctx, *requestKey); err != nil {
slog.Error("node-agent updater operation failed", "requestKey", *requestKey, "err", err)
os.Exit(1)
}
slog.Info("node-agent updater operation completed", "operationID", *operationID)
slog.Info("node-agent updater operation completed", "requestKey", *requestKey)
}
@@ -106,7 +106,7 @@ version after creation. It uses the same `nodeAgentConfig` shape as
| Setting | Required | Values | Purpose |
|---|---|---|---|
| `NODE_AGENT_UPDATE_METHOD` | Yes | `apt` or `bundle` | How agents are installed |
| `nodeAgent.updateMethod` | Yes | `apt` or `bundle` | How agents are installed |
Control plane nodes always upgrade one at a time per cluster. This is not
configurable.
@@ -268,14 +268,12 @@ transaction to select and record work.
3. Defer conflicting joins, Kubernetes upgrades, rolling replacements, and
deletions while the agent upgrade runs. Unrelated observation and host
provisioning can continue. Deletion and remediation can cancel the upgrade
before proceeding.
before proceeding. Cluster deletion does not require an agent response.
4. Operations started outside this controller, such as certificate renewal,
must use the same scheduling checks. They must not overlap with an agent
upgrade on the same node.
The controller also publishes the desired version and observed upgrade state
on existing control-plane CAPI Machine objects. It continues to use controller
records for upgrade decisions. It does not consume Machine state yet.
The controller uses its database records for upgrade decisions.
### Example: a desired version changes during join
+1 -1
View File
@@ -401,7 +401,7 @@ func NewNodeAgentServer(doMlx5Rescan bool, bundleServerURL, indexFileURL, cniIma
Runner: runner,
FileWriter: &nvkeutils.OSFileWriter{},
Persister: &JSONFilePersister{Path: StateFile},
AgentUpgradeStore: agentupgrade.NewStore(filepath.Join(NVKEDir, "agent-upgrades")),
AgentUpgradeStore: agentupgrade.NewStore(agentupgrade.DefaultRoot),
AgentUpgradeLauncher: systemdAgentUpgradeLauncher{
runner: runner,
},
+67 -99
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
@@ -23,17 +24,23 @@ import (
var canonicalAgentVersionPattern = regexp.MustCompile(`^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
type agentUpgradeLauncher interface {
Start(operationID string) error
Start(requestKey string) error
}
type systemdAgentUpgradeLauncher struct {
runner nvkeutils.CommandRunner
}
func (l systemdAgentUpgradeLauncher) Start(operationID string) error {
func (l systemdAgentUpgradeLauncher) Start(requestKey string) error {
if _, err := os.Stat(filepath.Join(agentupgrade.DefaultRoot, requestKey, "updater.py")); err == nil {
// The bootstrap runbook owns this attempt until it writes final status.
// Starting the packaged updater for it would race the bootstrap process.
_, err := l.runner.Run("systemctl", []string{"start", "--no-block", "nvke-agent-upgrade-" + requestKey + ".service"}, nil)
return err
}
_, err := l.runner.Run(
"systemctl",
[]string{"start", "--no-block", "nvke-agent-updater@" + operationID + ".service"},
[]string{"start", "--no-block", "nvke-agent-updater@" + requestKey + ".service"},
nil,
)
if err != nil {
@@ -52,10 +59,6 @@ func (s *NodeAgentServer) StartNodeAgentUpgrade(
if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required")
}
operationID := strings.TrimSpace(req.GetOperationId())
if err := agentupgrade.ValidateOperationID(operationID); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
targetVersion, err := parseCanonicalAgentVersion(req.GetTargetVersion())
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
@@ -70,6 +73,24 @@ func (s *NodeAgentServer) StartNodeAgentUpgrade(
s.agentUpgradeMu.Lock()
defer s.agentUpgradeMu.Unlock()
unlock, lockErr := s.AgentUpgradeStore.Lock()
if lockErr != nil {
return nil, status.Errorf(codes.Internal, "locking upgrade admission: %v", lockErr)
}
defer unlock()
current, err := s.AgentUpgradeStore.Current()
if err != nil {
return nil, upgradeStoreError(err)
}
if current != nil && !current.Terminal() && (current.TargetVersion != req.GetTargetVersion() || current.Method != method) {
return nil, status.Error(codes.FailedPrecondition, "another agent upgrade is active")
}
if current == nil || current.Terminal() {
if err := s.AgentUpgradeStore.Prune(); err != nil {
return nil, upgradeStoreError(err)
}
}
requestKey := (agentupgrade.Request{TargetVersion: req.GetTargetVersion(), Method: method}).Key()
s.mu.Lock()
previousVersion := strings.TrimSpace(s.NodeStatus.AgentVersion)
@@ -78,9 +99,10 @@ func (s *NodeAgentServer) StartNodeAgentUpgrade(
if previousVersion == "" {
return nil, status.Error(codes.FailedPrecondition, "current node-agent version is unknown")
}
if previousVersion == req.GetTargetVersion() && (current == nil || current.Terminal()) {
return &pb.StartNodeAgentUpgradeResponse{Operation: &pb.NodeAgentUpgradeOperation{TargetVersion: previousVersion, Method: req.GetMethod(), Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_SUCCEEDED, Step: "already at requested version"}}, nil
}
request := agentupgrade.Operation{
ID: operationID,
Action: agentupgrade.ActionUpgrade,
TargetVersion: req.GetTargetVersion(),
PreviousVersion: previousVersion,
Method: method,
@@ -88,18 +110,9 @@ func (s *NodeAgentServer) StartNodeAgentUpgrade(
if existing, found, loadErr := s.AgentUpgradeStore.Existing(request); loadErr != nil {
return nil, upgradeStoreError(loadErr)
} else if found {
if existing.Phase == agentupgrade.PhasePending {
if launchErr := s.AgentUpgradeLauncher.Start(operationID); launchErr != nil {
existing, err = s.AgentUpgradeStore.SetStatus(
operationID,
agentupgrade.PhaseFailedRestored,
"updater launch failed",
launchErr.Error(),
)
if err != nil {
return nil, status.Errorf(codes.Internal, "restarting updater: %v; persisting failure: %v", launchErr, err)
}
}
existing, err = s.launchNodeAgentUpdater(existing)
if err != nil {
return nil, err
}
return &pb.StartNodeAgentUpgradeResponse{Operation: upgradeOperationToProto(existing)}, nil
}
@@ -135,23 +148,20 @@ func (s *NodeAgentServer) StartNodeAgentUpgrade(
return &pb.StartNodeAgentUpgradeResponse{Operation: upgradeOperationToProto(op)}, nil
}
if previousVersion == req.GetTargetVersion() {
op, err = s.AgentUpgradeStore.SetStatus(operationID, agentupgrade.PhaseSucceeded, "already at requested version", "")
op, err = s.AgentUpgradeStore.SetStatus(requestKey, agentupgrade.PhaseSucceeded, "already at requested version", "")
if err != nil {
return nil, status.Errorf(codes.Internal, "persisting converged upgrade operation: %v", err)
}
return &pb.StartNodeAgentUpgradeResponse{Operation: upgradeOperationToProto(op)}, nil
}
if err := s.AgentUpgradeLauncher.Start(operationID); err != nil {
op, persistErr := s.AgentUpgradeStore.SetStatus(operationID, agentupgrade.PhaseFailedRestored, "updater launch failed", err.Error())
if persistErr != nil {
return nil, status.Errorf(codes.Internal, "starting updater: %v; persisting failure: %v", err, persistErr)
}
return &pb.StartNodeAgentUpgradeResponse{Operation: upgradeOperationToProto(op)}, nil
op, err = s.launchNodeAgentUpdater(op)
if err != nil {
return nil, err
}
return &pb.StartNodeAgentUpgradeResponse{Operation: upgradeOperationToProto(op)}, nil
}
// GetNodeAgentUpgradeStatus returns the durable state of an upgrade or rollback.
// GetNodeAgentUpgradeStatus returns the durable state of a version change.
func (s *NodeAgentServer) GetNodeAgentUpgradeStatus(
ctx context.Context,
req *pb.GetNodeAgentUpgradeStatusRequest,
@@ -160,82 +170,43 @@ func (s *NodeAgentServer) GetNodeAgentUpgradeStatus(
if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required")
}
operationID := strings.TrimSpace(req.GetOperationId())
if err := agentupgrade.ValidateOperationID(operationID); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
if s.AgentUpgradeStore == nil {
return nil, status.Error(codes.FailedPrecondition, "node-agent updater is not configured")
}
op, err := s.AgentUpgradeStore.Load(operationID)
if errors.Is(err, os.ErrNotExist) {
return nil, status.Errorf(codes.NotFound, "node-agent upgrade operation %s not found", operationID)
}
if err != nil {
return nil, status.Errorf(codes.Internal, "loading node-agent upgrade operation: %v", err)
}
return &pb.GetNodeAgentUpgradeStatusResponse{Operation: upgradeOperationToProto(op)}, nil
}
// StartNodeAgentRollback restores the exact artifact retained by a prior
// successful node-agent upgrade.
func (s *NodeAgentServer) StartNodeAgentRollback(
ctx context.Context,
req *pb.StartNodeAgentRollbackRequest,
) (*pb.StartNodeAgentRollbackResponse, error) {
defer logRPCSpan(ctx, "StartNodeAgentRollback")()
if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required")
}
operationID := strings.TrimSpace(req.GetOperationId())
upgradeOperationID := strings.TrimSpace(req.GetUpgradeOperationId())
if err := agentupgrade.ValidateOperationID(operationID); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
if err := agentupgrade.ValidateOperationID(upgradeOperationID); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "upgrade_operation_id: %v", err)
}
if s.AgentUpgradeStore == nil || s.AgentUpgradeLauncher == nil {
return nil, status.Error(codes.FailedPrecondition, "node-agent updater is not configured")
}
s.agentUpgradeMu.Lock()
defer s.agentUpgradeMu.Unlock()
original, err := s.AgentUpgradeStore.Load(upgradeOperationID)
if errors.Is(err, os.ErrNotExist) {
return nil, status.Errorf(codes.NotFound, "upgrade operation %s not found", upgradeOperationID)
}
if err != nil {
return nil, status.Errorf(codes.Internal, "loading upgrade operation: %v", err)
}
if original.Action != agentupgrade.ActionUpgrade || original.Phase != agentupgrade.PhaseSucceeded {
return nil, status.Errorf(codes.FailedPrecondition, "operation %s is not a successful upgrade", upgradeOperationID)
}
s.mu.Lock()
currentVersion := strings.TrimSpace(s.NodeStatus.AgentVersion)
s.mu.Unlock()
op, created, err := s.AgentUpgradeStore.Create(agentupgrade.Operation{
ID: operationID,
Action: agentupgrade.ActionRollback,
TargetVersion: original.PreviousVersion,
PreviousVersion: currentVersion,
Method: original.Method,
RestoreFromOperationID: original.ID,
})
unlock, err := s.AgentUpgradeStore.Lock()
if err != nil {
return nil, upgradeStoreError(err)
}
if created || op.Phase == agentupgrade.PhasePending {
if launchErr := s.AgentUpgradeLauncher.Start(operationID); launchErr != nil {
op, persistErr := s.AgentUpgradeStore.SetStatus(operationID, agentupgrade.PhaseFailedNotRestored, "updater launch failed", launchErr.Error())
if persistErr != nil {
return nil, status.Errorf(codes.Internal, "starting rollback updater: %v; persisting failure: %v", launchErr, persistErr)
}
return &pb.StartNodeAgentRollbackResponse{Operation: upgradeOperationToProto(op)}, nil
}
defer unlock()
current, err := s.AgentUpgradeStore.Current()
if err != nil {
return nil, upgradeStoreError(err)
}
return &pb.StartNodeAgentRollbackResponse{Operation: upgradeOperationToProto(op)}, nil
if current == nil {
return &pb.GetNodeAgentUpgradeStatusResponse{}, nil
}
return &pb.GetNodeAgentUpgradeStatusResponse{Operation: upgradeOperationToProto(*current)}, nil
}
// launchNodeAgentUpdater reasserts the service start and persists launch failures.
func (s *NodeAgentServer) launchNodeAgentUpdater(op agentupgrade.Operation) (agentupgrade.Operation, error) {
if op.Phase != agentupgrade.PhasePending && op.Phase != agentupgrade.PhaseRunning {
return op, nil
}
if err := s.AgentUpgradeLauncher.Start(op.Key()); err != nil {
phase := agentupgrade.PhaseFailedNotRestored
if op.Phase == agentupgrade.PhasePending {
phase = agentupgrade.PhaseFailedRestored
}
updated, persistErr := s.AgentUpgradeStore.SetStatus(op.Key(), phase, "updater launch failed", err.Error())
if persistErr != nil {
return op, status.Errorf(codes.Internal, "starting updater: %v; persisting failure: %v", err, persistErr)
}
return updated, nil
}
return op, nil
}
func parseCanonicalAgentVersion(value string) (*semver.Version, error) {
@@ -264,7 +235,6 @@ func upgradeMethodFromProto(method pb.NodeAgentUpgradeMethod) (agentupgrade.Meth
func upgradeOperationToProto(op agentupgrade.Operation) *pb.NodeAgentUpgradeOperation {
return &pb.NodeAgentUpgradeOperation{
OperationId: op.ID,
TargetVersion: op.TargetVersion,
PreviousVersion: op.PreviousVersion,
Method: upgradeMethodToProto(op.Method),
@@ -304,8 +274,6 @@ func upgradePhaseToProto(phase agentupgrade.Phase) pb.NodeAgentUpgradePhase {
func upgradeStoreError(err error) error {
switch {
case errors.Is(err, agentupgrade.ErrOperationConflict):
return status.Error(codes.AlreadyExists, err.Error())
case errors.Is(err, agentupgrade.ErrOperationActive):
return status.Error(codes.FailedPrecondition, err.Error())
default:
@@ -0,0 +1,94 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package agent
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/dsx-ai-factory/nvke/agent/pkg/agent/proto"
"github.com/dsx-ai-factory/nvke/agent/pkg/agentupgrade"
)
func TestUpgradeResumesAndRetriesAcrossRestart(t *testing.T) {
root := t.TempDir()
launcher := &recordingAgentUpgradeLauncher{}
server := &NodeAgentServer{NodeStatus: &NodeStatus{AgentVersion: "v0.1.2"}, AgentUpgradeStore: agentupgrade.NewStore(root), AgentUpgradeLauncher: launcher}
request := &pb.StartNodeAgentUpgradeRequest{TargetVersion: "v0.1.1", Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT}
first, err := server.StartNodeAgentUpgrade(context.Background(), request)
require.NoError(t, err)
require.NotNil(t, first.GetOperation())
key := launcher.requests[0]
require.NotEmpty(t, key)
server.AgentUpgradeStore = agentupgrade.NewStore(root)
resumed, err := server.StartNodeAgentUpgrade(context.Background(), request)
require.NoError(t, err)
require.NotNil(t, resumed.GetOperation())
require.Equal(t, key, launcher.requests[1])
_, err = server.AgentUpgradeStore.SetStatus(key, agentupgrade.PhaseFailedRestored, "failure", "artifact missing")
require.NoError(t, err)
observed, err := server.GetNodeAgentUpgradeStatus(context.Background(), &pb.GetNodeAgentUpgradeStatusRequest{})
require.NoError(t, err)
require.Equal(t, "artifact missing", observed.GetOperation().GetErrorMessage())
retried, err := server.StartNodeAgentUpgrade(context.Background(), request)
require.NoError(t, err)
require.Equal(t, key, launcher.requests[len(launcher.requests)-1])
require.Equal(t, pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_PENDING, retried.GetOperation().GetPhase())
request.TargetVersion = "v0.1.3"
_, err = server.StartNodeAgentUpgrade(context.Background(), request)
require.Equal(t, codes.FailedPrecondition, status.Code(err))
}
func TestUpgradeRelaunchFailurePreservesRestorationUncertainty(t *testing.T) {
for _, phase := range []agentupgrade.Phase{agentupgrade.PhasePending, agentupgrade.PhaseRunning} {
t.Run(string(phase), func(t *testing.T) {
store := agentupgrade.NewStore(t.TempDir())
_, _, err := store.Create(agentupgrade.Operation{TargetVersion: "v0.1.2", PreviousVersion: "v0.1.1", Method: agentupgrade.MethodAPT})
require.NoError(t, err)
_, err = store.SetStatus("v0.1.2_apt", phase, "installing", "")
require.NoError(t, err)
launcher := &recordingAgentUpgradeLauncher{err: errors.New("systemd unit unavailable")}
server := &NodeAgentServer{NodeStatus: &NodeStatus{AgentVersion: "v0.1.1"}, AgentUpgradeStore: store, AgentUpgradeLauncher: launcher}
response, err := server.StartNodeAgentUpgrade(t.Context(), &pb.StartNodeAgentUpgradeRequest{TargetVersion: "v0.1.2", Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT})
require.NoError(t, err)
want := pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_NOT_RESTORED
if phase == agentupgrade.PhasePending {
want = pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_RESTORED
}
require.Equal(t, want, response.GetOperation().GetPhase())
require.Equal(t, "systemd unit unavailable", response.GetOperation().GetErrorMessage())
persisted, err := store.Load("v0.1.2_apt")
require.NoError(t, err)
require.Equal(t, response.GetOperation().GetErrorMessage(), persisted.ErrorMessage)
})
}
}
func TestUpgradeAndDowngradeUseSameRPCAndStatus(t *testing.T) {
server := &NodeAgentServer{NodeStatus: &NodeStatus{AgentVersion: "v0.1.1"}, AgentUpgradeStore: agentupgrade.NewStore(t.TempDir()), AgentUpgradeLauncher: &recordingAgentUpgradeLauncher{}}
for _, target := range []string{"v0.1.2", "v0.1.1"} {
t.Run(target, func(t *testing.T) {
previous := server.NodeStatus.AgentVersion
response, err := server.StartNodeAgentUpgrade(t.Context(), &pb.StartNodeAgentUpgradeRequest{TargetVersion: target, Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT})
require.NoError(t, err)
require.Equal(t, target, response.GetOperation().GetTargetVersion())
require.Equal(t, previous, response.GetOperation().GetPreviousVersion())
observed, err := server.GetNodeAgentUpgradeStatus(t.Context(), &pb.GetNodeAgentUpgradeStatusRequest{})
require.NoError(t, err)
require.Equal(t, pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_PENDING, observed.GetOperation().GetPhase())
_, err = server.AgentUpgradeStore.SetStatus(target+"_apt", agentupgrade.PhaseSucceeded, "verified", "")
require.NoError(t, err)
server.NodeStatus.AgentVersion = target
observed, err = server.GetNodeAgentUpgradeStatus(t.Context(), &pb.GetNodeAgentUpgradeStatusRequest{})
require.NoError(t, err)
require.Equal(t, target, observed.GetOperation().GetTargetVersion())
require.Equal(t, pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_SUCCEEDED, observed.GetOperation().GetPhase())
})
}
}
+13 -44
View File
@@ -17,12 +17,12 @@ import (
)
type recordingAgentUpgradeLauncher struct {
operationIDs []string
err error
requests []string
err error
}
func (l *recordingAgentUpgradeLauncher) Start(operationID string) error {
l.operationIDs = append(l.operationIDs, operationID)
func (l *recordingAgentUpgradeLauncher) Start(requestKey string) error {
l.requests = append(l.requests, requestKey)
return l.err
}
@@ -35,7 +35,6 @@ func TestStartNodeAgentUpgradePersistsBeforeLaunching(t *testing.T) {
AgentUpgradeLauncher: launcher,
}
req := &pb.StartNodeAgentUpgradeRequest{
OperationId: "cluster-node-1",
TargetVersion: "v0.1.2",
Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT,
}
@@ -44,8 +43,9 @@ func TestStartNodeAgentUpgradePersistsBeforeLaunching(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, resp.GetOperation())
assert.Equal(t, pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_PENDING, resp.GetOperation().GetPhase())
assert.Equal(t, []string{"cluster-node-1"}, launcher.operationIDs)
persisted, err := store.Load("cluster-node-1")
require.Len(t, launcher.requests, 1)
attempt := launcher.requests[0]
persisted, err := store.Load(attempt)
require.NoError(t, err)
assert.Equal(t, agentupgrade.PhasePending, persisted.Phase)
assert.Equal(t, "v0.1.1", persisted.PreviousVersion)
@@ -54,7 +54,7 @@ func TestStartNodeAgentUpgradePersistsBeforeLaunching(t *testing.T) {
resp, err = server.StartNodeAgentUpgrade(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_PENDING, resp.GetOperation().GetPhase())
assert.Equal(t, []string{"cluster-node-1", "cluster-node-1"}, launcher.operationIDs, "pending retry must reassert the idempotent systemd start")
assert.Equal(t, []string{attempt, attempt}, launcher.requests, "pending retry must reassert the idempotent systemd start")
}
func TestStartNodeAgentUpgradeRejectsNonCanonicalVersion(t *testing.T) {
@@ -65,7 +65,6 @@ func TestStartNodeAgentUpgradeRejectsNonCanonicalVersion(t *testing.T) {
}
_, err := server.StartNodeAgentUpgrade(context.Background(), &pb.StartNodeAgentUpgradeRequest{
OperationId: "cluster-node-1",
TargetVersion: "0.1.2",
Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT,
})
@@ -80,40 +79,10 @@ func TestInstallBundleRejectsNodeAgentReplacement(t *testing.T) {
assert.Equal(t, codes.FailedPrecondition, status.Code(err))
}
func TestStartNodeAgentRollbackReferencesSuccessfulUpgrade(t *testing.T) {
store := agentupgrade.NewStore(t.TempDir())
_, _, err := store.Create(agentupgrade.Operation{
ID: "upgrade-1",
Action: agentupgrade.ActionUpgrade,
TargetVersion: "v0.1.2",
PreviousVersion: "v0.1.1",
Method: agentupgrade.MethodAPT,
})
func TestGetNodeAgentUpgradeStatusReturnsEmptyResponseWithoutAnUpgrade(t *testing.T) {
server := &NodeAgentServer{AgentUpgradeStore: agentupgrade.NewStore(t.TempDir())}
response, err := server.GetNodeAgentUpgradeStatus(t.Context(), &pb.GetNodeAgentUpgradeStatusRequest{})
require.NoError(t, err)
_, err = store.SetStatus("upgrade-1", agentupgrade.PhaseSucceeded, "verified", "")
require.NoError(t, err)
launcher := &recordingAgentUpgradeLauncher{}
server := &NodeAgentServer{
NodeStatus: &NodeStatus{AgentVersion: "v0.1.2"},
AgentUpgradeStore: store,
AgentUpgradeLauncher: launcher,
}
resp, err := server.StartNodeAgentRollback(context.Background(), &pb.StartNodeAgentRollbackRequest{
OperationId: "rollback-1",
UpgradeOperationId: "upgrade-1",
})
require.NoError(t, err)
assert.Equal(t, "v0.1.1", resp.GetOperation().GetTargetVersion())
assert.Equal(t, []string{"rollback-1"}, launcher.operationIDs)
rollback, err := store.Load("rollback-1")
require.NoError(t, err)
assert.Equal(t, "upgrade-1", rollback.RestoreFromOperationID)
_, err = server.StartNodeAgentRollback(context.Background(), &pb.StartNodeAgentRollbackRequest{
OperationId: "rollback-1",
UpgradeOperationId: "upgrade-1",
})
require.NoError(t, err)
assert.Equal(t, []string{"rollback-1", "rollback-1"}, launcher.operationIDs, "pending rollback retry must reassert the idempotent systemd start")
require.NotNil(t, response)
require.Nil(t, response.GetOperation())
}
File diff suppressed because it is too large Load Diff
+11 -26
View File
@@ -208,10 +208,6 @@ service NodeAgent {
// nvke-agent restart.
rpc GetNodeAgentUpgradeStatus(GetNodeAgentUpgradeStatusRequest) returns (GetNodeAgentUpgradeStatusResponse) {}
// StartNodeAgentRollback restores the exact artifact retained by a prior
// successful StartNodeAgentUpgrade operation.
rpc StartNodeAgentRollback(StartNodeAgentRollbackRequest) returns (StartNodeAgentRollbackResponse) {}
rpc InstallPackages(InstallPackagesRequest) returns (InstallPackagesResponse) {}
rpc ListPackages(ListPackagesRequest) returns (ListPackagesResponse) {}
@@ -284,6 +280,7 @@ message KubeadmStatusResponse {
string kubeadm_current_message = 4;
repeated string kubeadm_completed_phases = 5;
string agent_version = 6;
reserved 7;
}
message File {
@@ -877,40 +874,28 @@ enum NodeAgentUpgradePhase {
}
message NodeAgentUpgradeOperation {
string operation_id = 1;
string target_version = 2;
string previous_version = 3;
NodeAgentUpgradeMethod method = 4;
NodeAgentUpgradePhase phase = 5;
string step = 6;
string error_message = 7;
string target_version = 1;
string previous_version = 2;
NodeAgentUpgradeMethod method = 3;
NodeAgentUpgradePhase phase = 4;
string step = 5;
string error_message = 6;
}
message StartNodeAgentUpgradeRequest {
string operation_id = 1;
// Canonical node-agent release version, for example v0.1.31.
string target_version = 2;
NodeAgentUpgradeMethod method = 3;
string target_version = 1;
NodeAgentUpgradeMethod method = 2;
}
message StartNodeAgentUpgradeResponse {
NodeAgentUpgradeOperation operation = 1;
}
message GetNodeAgentUpgradeStatusRequest {
string operation_id = 1;
}
message GetNodeAgentUpgradeStatusRequest {}
message GetNodeAgentUpgradeStatusResponse {
NodeAgentUpgradeOperation operation = 1;
}
message StartNodeAgentRollbackRequest {
string operation_id = 1;
string upgrade_operation_id = 2;
}
message StartNodeAgentRollbackResponse {
// Absent when no upgrade has been requested.
NodeAgentUpgradeOperation operation = 1;
}
@@ -63,7 +63,6 @@ const (
NodeAgent_InstallCollection_FullMethodName = "/proto.NodeAgent/InstallCollection"
NodeAgent_StartNodeAgentUpgrade_FullMethodName = "/proto.NodeAgent/StartNodeAgentUpgrade"
NodeAgent_GetNodeAgentUpgradeStatus_FullMethodName = "/proto.NodeAgent/GetNodeAgentUpgradeStatus"
NodeAgent_StartNodeAgentRollback_FullMethodName = "/proto.NodeAgent/StartNodeAgentRollback"
NodeAgent_InstallPackages_FullMethodName = "/proto.NodeAgent/InstallPackages"
NodeAgent_ListPackages_FullMethodName = "/proto.NodeAgent/ListPackages"
NodeAgent_RemovePackages_FullMethodName = "/proto.NodeAgent/RemovePackages"
@@ -238,9 +237,6 @@ type NodeAgentClient interface {
// GetNodeAgentUpgradeStatus returns durable updater state that survives an
// nvke-agent restart.
GetNodeAgentUpgradeStatus(ctx context.Context, in *GetNodeAgentUpgradeStatusRequest, opts ...grpc.CallOption) (*GetNodeAgentUpgradeStatusResponse, error)
// StartNodeAgentRollback restores the exact artifact retained by a prior
// successful StartNodeAgentUpgrade operation.
StartNodeAgentRollback(ctx context.Context, in *StartNodeAgentRollbackRequest, opts ...grpc.CallOption) (*StartNodeAgentRollbackResponse, error)
InstallPackages(ctx context.Context, in *InstallPackagesRequest, opts ...grpc.CallOption) (*InstallPackagesResponse, error)
ListPackages(ctx context.Context, in *ListPackagesRequest, opts ...grpc.CallOption) (*ListPackagesResponse, error)
RemovePackages(ctx context.Context, in *RemovePackagesRequest, opts ...grpc.CallOption) (*RemovePackagesResponse, error)
@@ -753,16 +749,6 @@ func (c *nodeAgentClient) GetNodeAgentUpgradeStatus(ctx context.Context, in *Get
return out, nil
}
func (c *nodeAgentClient) StartNodeAgentRollback(ctx context.Context, in *StartNodeAgentRollbackRequest, opts ...grpc.CallOption) (*StartNodeAgentRollbackResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(StartNodeAgentRollbackResponse)
err := c.cc.Invoke(ctx, NodeAgent_StartNodeAgentRollback_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *nodeAgentClient) InstallPackages(ctx context.Context, in *InstallPackagesRequest, opts ...grpc.CallOption) (*InstallPackagesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(InstallPackagesResponse)
@@ -1016,9 +1002,6 @@ type NodeAgentServer interface {
// GetNodeAgentUpgradeStatus returns durable updater state that survives an
// nvke-agent restart.
GetNodeAgentUpgradeStatus(context.Context, *GetNodeAgentUpgradeStatusRequest) (*GetNodeAgentUpgradeStatusResponse, error)
// StartNodeAgentRollback restores the exact artifact retained by a prior
// successful StartNodeAgentUpgrade operation.
StartNodeAgentRollback(context.Context, *StartNodeAgentRollbackRequest) (*StartNodeAgentRollbackResponse, error)
InstallPackages(context.Context, *InstallPackagesRequest) (*InstallPackagesResponse, error)
ListPackages(context.Context, *ListPackagesRequest) (*ListPackagesResponse, error)
RemovePackages(context.Context, *RemovePackagesRequest) (*RemovePackagesResponse, error)
@@ -1193,9 +1176,6 @@ func (UnimplementedNodeAgentServer) StartNodeAgentUpgrade(context.Context, *Star
func (UnimplementedNodeAgentServer) GetNodeAgentUpgradeStatus(context.Context, *GetNodeAgentUpgradeStatusRequest) (*GetNodeAgentUpgradeStatusResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetNodeAgentUpgradeStatus not implemented")
}
func (UnimplementedNodeAgentServer) StartNodeAgentRollback(context.Context, *StartNodeAgentRollbackRequest) (*StartNodeAgentRollbackResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method StartNodeAgentRollback not implemented")
}
func (UnimplementedNodeAgentServer) InstallPackages(context.Context, *InstallPackagesRequest) (*InstallPackagesResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method InstallPackages not implemented")
}
@@ -1985,24 +1965,6 @@ func _NodeAgent_GetNodeAgentUpgradeStatus_Handler(srv interface{}, ctx context.C
return interceptor(ctx, in, info, handler)
}
func _NodeAgent_StartNodeAgentRollback_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(StartNodeAgentRollbackRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(NodeAgentServer).StartNodeAgentRollback(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: NodeAgent_StartNodeAgentRollback_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(NodeAgentServer).StartNodeAgentRollback(ctx, req.(*StartNodeAgentRollbackRequest))
}
return interceptor(ctx, in, info, handler)
}
func _NodeAgent_InstallPackages_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(InstallPackagesRequest)
if err := dec(in); err != nil {
@@ -2328,10 +2290,6 @@ var NodeAgent_ServiceDesc = grpc.ServiceDesc{
MethodName: "GetNodeAgentUpgradeStatus",
Handler: _NodeAgent_GetNodeAgentUpgradeStatus_Handler,
},
{
MethodName: "StartNodeAgentRollback",
Handler: _NodeAgent_StartNodeAgentRollback_Handler,
},
{
MethodName: "InstallPackages",
Handler: _NodeAgent_InstallPackages_Handler,
+14 -11
View File
@@ -102,15 +102,15 @@ func TestBundleRenameUpgradeAndRestore(t *testing.T) {
bundleDir := filepath.Join(root, "bundle")
writeBundleLayout(t, bundleDir, bundleDir, target, "v0.3.0")
store := NewStore(filepath.Join(root, "operations"))
_, _, err := store.Create(Operation{ID: "rename", Action: ActionUpgrade, Method: MethodBundle, TargetVersion: "v0.3.0", PreviousVersion: "v0.2.0", ArtifactURL: "https://example.test/agent.tgz"})
_, _, err := store.Create(Operation{Method: MethodBundle, TargetVersion: "v0.3.0", PreviousVersion: "v0.2.0", ArtifactURL: "https://example.test/agent.tgz"})
require.NoError(t, err)
runner := &bundleRenameRunner{bundleDir: bundleDir, activeService: previous + ".service", failTarget: failTarget}
updater := NewUpdater(store)
updater.Runner, updater.AgentBinary, updater.UpdaterBinary, updater.SystemdUnitDir = runner, filepath.Join(binDir, agentPackageName), filepath.Join(binDir, agentPackageName+"-updater"), unitDir
updater.MigrationScript = filepath.Join(binDir, "migrate-agent-paths.sh")
updater.VerifyAttempts = 1
err = updater.Run(context.Background(), "rename")
op, loadErr := store.Load("rename")
err = updater.Run(context.Background(), "v0.3.0_bundle")
op, loadErr := store.Load("v0.3.0_bundle")
require.NoError(t, loadErr)
if failTarget {
require.Error(t, err)
@@ -120,10 +120,13 @@ func TestBundleRenameUpgradeAndRestore(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, PhaseSucceeded, op.Phase)
assert.Equal(t, target+".service", runner.activeService)
// Explicit rollback works with retained files named by either release.
_, _, err = store.Create(Operation{ID: "rollback", Action: ActionRollback, RestoreFromOperationID: "rename"})
// A downgrade installs the older artifact through the same request path.
downgradeDir := filepath.Join(root, "downgrade")
writeBundleLayout(t, downgradeDir, downgradeDir, previous, "v0.2.0")
runner.bundleDir = downgradeDir
_, _, err = store.Create(Operation{TargetVersion: "v0.2.0", PreviousVersion: "v0.3.0", Method: MethodBundle, ArtifactURL: "https://example.test/older-agent.tgz"})
require.NoError(t, err)
require.NoError(t, updater.Run(context.Background(), "rollback"))
require.NoError(t, updater.Run(context.Background(), "v0.2.0_bundle"))
assert.Equal(t, previous+".service", runner.activeService)
}
data, err := os.ReadFile(filepath.Join(binDir, previous))
@@ -144,7 +147,7 @@ func TestBundleRenameResumeRetainsOriginalLayout(t *testing.T) {
bundleDir := filepath.Join(root, "bundle")
writeBundleLayout(t, bundleDir, bundleDir, agentPackageName, "v0.3.0")
store := NewStore(filepath.Join(root, "operations"))
_, _, err := store.Create(Operation{ID: "interrupted", Action: ActionUpgrade, Method: MethodBundle, TargetVersion: "v0.3.0", PreviousVersion: "v0.2.0", ArtifactURL: "https://example.test/agent.tgz"})
_, _, err := store.Create(Operation{Method: MethodBundle, TargetVersion: "v0.3.0", PreviousVersion: "v0.2.0", ArtifactURL: "https://example.test/agent.tgz"})
require.NoError(t, err)
runner := &bundleRenameRunner{bundleDir: bundleDir, activeService: legacyAgentPackageName + ".service"}
newUpdater := func() *Updater {
@@ -154,17 +157,17 @@ func TestBundleRenameResumeRetainsOriginalLayout(t *testing.T) {
return updater
}
first := newUpdater()
require.NoError(t, first.snapshotInstalledFiles("interrupted"))
require.NoError(t, first.snapshotInstalledFiles("v0.3.0_bundle"))
if legacySnapshot {
assets, err := first.assetsDir("interrupted")
assets, err := first.assetsDir("v0.3.0_bundle")
require.NoError(t, err)
require.NoError(t, os.Remove(filepath.Join(assets, "previous", ".snapshot-complete")))
}
require.NoError(t, first.installBundleFiles(context.Background(), bundleDir))
// Simulate a process interruption after replacement and a failed retry.
runner.failTarget = true
require.Error(t, newUpdater().Run(context.Background(), "interrupted"))
op, err := store.Load("interrupted")
require.Error(t, newUpdater().Run(context.Background(), "v0.3.0_bundle"))
op, err := store.Load("v0.3.0_bundle")
require.NoError(t, err)
assert.Equal(t, PhaseFailedRestored, op.Phase)
assert.Equal(t, legacyAgentPackageName+".service", runner.activeService)
+142 -39
View File
@@ -10,21 +10,20 @@ import (
"os"
"path/filepath"
"regexp"
"syscall"
"time"
)
const operationFileName = "operation.json"
var (
operationIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$`)
requestKeyPattern = regexp.MustCompile(`^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)_(apt|bundle)$`)
// ErrOperationConflict means an operation ID was reused for a different request.
ErrOperationConflict = errors.New("node-agent upgrade operation conflicts with existing request")
// ErrOperationActive means another non-terminal node-agent operation owns the node.
ErrOperationActive = errors.New("another node-agent upgrade operation is active")
)
// Store persists updater operations in one directory per caller-provided ID.
// Store persists updater state in one directory per target version and method.
type Store struct {
Root string
}
@@ -34,29 +33,29 @@ func NewStore(root string) *Store {
return &Store{Root: root}
}
// ValidateOperationID rejects values that cannot safely be used as systemd
// ValidateRequestKey rejects values that cannot safely be used as systemd
// instance names and operation-directory names.
func ValidateOperationID(id string) error {
if !operationIDPattern.MatchString(id) {
return fmt.Errorf("operation_id must match %s", operationIDPattern.String())
func ValidateRequestKey(key string) error {
if !requestKeyPattern.MatchString(key) {
return fmt.Errorf("request pair must match %s", requestKeyPattern.String())
}
return nil
}
// OperationDir returns the validated directory for an operation.
func (s *Store) OperationDir(id string) (string, error) {
if err := ValidateOperationID(id); err != nil {
func (s *Store) OperationDir(key string) (string, error) {
if err := ValidateRequestKey(key); err != nil {
return "", err
}
if s == nil || s.Root == "" {
return "", errors.New("node-agent upgrade store root is empty")
}
return filepath.Join(s.Root, id), nil
return filepath.Join(s.Root, key), nil
}
// Create persists op, returning an identical existing request idempotently.
func (s *Store) Create(op Operation) (Operation, bool, error) {
dir, err := s.OperationDir(op.ID)
dir, err := s.OperationDir(op.Key())
if err != nil {
return Operation{}, false, err
}
@@ -71,9 +70,14 @@ func (s *Store) Create(op Operation) (Operation, bool, error) {
return Operation{}, false, err
}
if active != nil {
return Operation{}, false, fmt.Errorf("%w: %s is %s", ErrOperationActive, active.ID, active.Phase)
return Operation{}, false, fmt.Errorf("%w: %s is %s", ErrOperationActive, active.Key(), active.Phase)
}
// A completed request can be retried with a new artifact. Retain only files
// captured for this installation, so restoration cannot use an older retry.
if err := os.RemoveAll(dir); err != nil {
return Operation{}, false, fmt.Errorf("clearing completed request files: %w", err)
}
now := time.Now().UTC()
op.Phase = PhasePending
op.Step = "queued"
@@ -92,22 +96,22 @@ func (s *Store) Create(op Operation) (Operation, bool, error) {
// Existing returns an idempotently matching operation before the caller does
// artifact resolution or other external work.
func (s *Store) Existing(request Operation) (Operation, bool, error) {
existing, err := s.Load(request.ID)
existing, err := s.Load(request.Key())
if errors.Is(err, os.ErrNotExist) {
return Operation{}, false, nil
}
if err != nil {
return Operation{}, false, err
}
if !sameRequest(existing, request) {
return Operation{}, false, ErrOperationConflict
if existing.Terminal() {
return Operation{}, false, nil
}
return existing, true, nil
}
// Load reads a persisted operation.
func (s *Store) Load(id string) (Operation, error) {
dir, err := s.OperationDir(id)
func (s *Store) Load(key string) (Operation, error) {
dir, err := s.OperationDir(key)
if err != nil {
return Operation{}, err
}
@@ -117,10 +121,10 @@ func (s *Store) Load(id string) (Operation, error) {
}
var op Operation
if err := json.Unmarshal(data, &op); err != nil {
return Operation{}, fmt.Errorf("decoding operation %s: %w", id, err)
return Operation{}, fmt.Errorf("decoding operation %s: %w", key, err)
}
if op.ID != id {
return Operation{}, fmt.Errorf("operation file for %s contains id %q", id, op.ID)
if op.Key() != key {
return Operation{}, fmt.Errorf("operation file for %s contains request pair %q", key, op.Key())
}
return op, nil
}
@@ -135,7 +139,7 @@ func (s *Store) Active() (*Operation, error) {
return nil, fmt.Errorf("listing node-agent upgrade operations: %w", err)
}
for _, entry := range entries {
if !entry.IsDir() || ValidateOperationID(entry.Name()) != nil {
if !entry.IsDir() || ValidateRequestKey(entry.Name()) != nil {
continue
}
op, loadErr := s.Load(entry.Name())
@@ -153,8 +157,8 @@ func (s *Store) Active() (*Operation, error) {
}
// SetStatus atomically updates the operation phase, step, and error message.
func (s *Store) SetStatus(id string, phase Phase, step, errorMessage string) (Operation, error) {
op, err := s.Load(id)
func (s *Store) SetStatus(key string, phase Phase, step, errorMessage string) (Operation, error) {
op, err := s.Load(key)
if err != nil {
return Operation{}, err
}
@@ -168,9 +172,9 @@ func (s *Store) SetStatus(id string, phase Phase, step, errorMessage string) (Op
return op, nil
}
// SetPreviousPackage records the exact Debian package retained for rollback.
func (s *Store) SetPreviousPackage(id, name, version string) (Operation, error) {
op, err := s.Load(id)
// SetPreviousPackage records the exact Debian package retained for restoration.
func (s *Store) SetPreviousPackage(key, name, version string) (Operation, error) {
op, err := s.Load(key)
if err != nil {
return Operation{}, err
}
@@ -184,13 +188,13 @@ func (s *Store) SetPreviousPackage(id, name, version string) (Operation, error)
}
func (s *Store) write(op Operation) error {
dir, err := s.OperationDir(op.ID)
dir, err := s.OperationDir(op.Key())
if err != nil {
return err
}
data, err := json.MarshalIndent(op, "", " ")
if err != nil {
return fmt.Errorf("encoding operation %s: %w", op.ID, err)
return fmt.Errorf("encoding operation %s: %w", op.Key(), err)
}
tmp, err := os.CreateTemp(dir, ".operation-*.json")
if err != nil {
@@ -219,16 +223,115 @@ func (s *Store) write(op Operation) error {
return nil
}
func sameRequest(existing, requested Operation) bool {
if existing.ID != requested.ID || existing.Action != requested.Action {
return false
// Current returns the newest durable operation, including completed attempts.
func (s *Store) Current() (*Operation, error) {
active, err := s.Active()
if err != nil || active != nil {
return active, err
}
switch existing.Action {
case ActionUpgrade:
return existing.TargetVersion == requested.TargetVersion && existing.Method == requested.Method
case ActionRollback:
return existing.RestoreFromOperationID == requested.RestoreFromOperationID
default:
return false
entries, err := os.ReadDir(s.Root)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("listing upgrade status: %w", err)
}
var current *Operation
for _, entry := range entries {
if !entry.IsDir() || ValidateRequestKey(entry.Name()) != nil {
continue
}
op, err := s.Load(entry.Name())
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, err
}
if current == nil || op.CreatedAt.After(current.CreatedAt) {
current = &op
}
}
return current, nil
}
// Lock serializes admission with the bootstrap updater in another process.
func (s *Store) Lock() (func(), error) {
if err := os.MkdirAll(s.Root, 0o700); err != nil {
return nil, err
}
file, err := os.OpenFile(filepath.Join(s.Root, "upgrade.lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil {
_ = file.Close()
return nil, err
}
return func() { _ = syscall.Flock(int(file.Fd()), syscall.LOCK_UN); _ = file.Close() }, nil
}
// Prune bounds completed attempts and retains assets for active and recent requests.
// Callers must hold Lock while pruning and admitting a new attempt.
func (s *Store) Prune() error {
operations, err := s.operations()
if err != nil {
return err
}
keep := map[string]bool{}
latest := map[string]Operation{}
for _, op := range operations {
if !op.Terminal() {
keep[op.Key()] = true
continue
}
category := "failure"
if op.Phase == PhaseSucceeded {
category = "success"
}
if previous, ok := latest[category]; !ok || op.CreatedAt.After(previous.CreatedAt) {
latest[category] = op
}
}
for _, op := range latest {
keep[op.Key()] = true
}
for _, op := range operations {
if keep[op.Key()] {
continue
}
dir, err := s.OperationDir(op.Key())
if err != nil {
return err
}
if err := os.RemoveAll(dir); err != nil {
return fmt.Errorf("pruning completed upgrade: %w", err)
}
}
return nil
}
func (s *Store) operations() ([]Operation, error) {
entries, err := os.ReadDir(s.Root)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("listing upgrade attempts: %w", err)
}
var operations []Operation
for _, entry := range entries {
if !entry.IsDir() || ValidateRequestKey(entry.Name()) != nil {
continue
}
op, err := s.Load(entry.Name())
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, err
}
operations = append(operations, op)
}
return operations, nil
}
@@ -0,0 +1,54 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package agentupgrade
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestPruneRetainsActiveRequestAndRecentResults(t *testing.T) {
store := NewStore(t.TempDir())
for index := range 3 {
request := Operation{TargetVersion: fmt.Sprintf("v0.1.%d", index), Method: MethodAPT}
_, _, err := store.Create(request)
require.NoError(t, err)
_, err = store.SetStatus(request.Key(), PhaseSucceeded, "verified", "")
require.NoError(t, err)
dir, err := store.OperationDir(request.Key())
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(dir, "retained.deb"), []byte("restore"), 0o600))
}
for index := range 8 {
request := Operation{TargetVersion: fmt.Sprintf("v0.2.%d", index), Method: MethodAPT}
_, _, err := store.Create(request)
require.NoError(t, err)
_, err = store.SetStatus(request.Key(), PhaseFailedRestored, "restored", "artifact missing")
require.NoError(t, err)
}
_, _, err := store.Create(Operation{TargetVersion: "v0.3.0", Method: MethodBundle})
require.NoError(t, err)
unlock, err := store.Lock()
require.NoError(t, err)
defer unlock()
require.NoError(t, store.Prune())
operations, err := store.operations()
require.NoError(t, err)
require.Len(t, operations, 3)
for _, key := range []string{"v0.1.2_apt", "v0.2.7_apt", "v0.3.0_bundle"} {
_, err := store.Load(key)
require.NoError(t, err)
}
dir, err := store.OperationDir("v0.1.2_apt")
require.NoError(t, err)
data, err := os.ReadFile(filepath.Join(dir, "retained.deb"))
require.NoError(t, err)
require.Equal(t, "restore", string(data))
_, err = store.Load("v0.1.1_apt")
require.ErrorIs(t, err, os.ErrNotExist)
}
+25 -77
View File
@@ -4,99 +4,47 @@
package agentupgrade
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStoreCreateIsIdempotentAndSerial(t *testing.T) {
func TestStoreUsesVersionAndMethodForIdempotenceAndSerialAdmission(t *testing.T) {
store := NewStore(t.TempDir())
request := Operation{
ID: "cluster-node-1",
Action: ActionUpgrade,
TargetVersion: "v0.1.2",
PreviousVersion: "v0.1.1",
Method: MethodAPT,
}
request := Operation{TargetVersion: "v0.1.2", PreviousVersion: "v0.1.1", Method: MethodAPT}
created, wasCreated, err := store.Create(request)
require.NoError(t, err)
assert.True(t, wasCreated)
assert.Equal(t, PhasePending, created.Phase)
require.True(t, wasCreated)
retry := request
retry.PreviousVersion = "v0.1.2"
existing, wasCreated, err := store.Create(retry)
require.NoError(t, err)
assert.False(t, wasCreated)
assert.Equal(t, created, existing)
_, _, err = store.Create(Operation{
ID: "cluster-node-2",
Action: ActionUpgrade,
TargetVersion: "v0.1.2",
PreviousVersion: "v0.1.1",
Method: MethodAPT,
})
require.Error(t, err)
assert.ErrorIs(t, err, ErrOperationActive)
_, err = store.SetStatus(request.ID, PhaseSucceeded, "verified", "")
require.False(t, wasCreated)
require.Equal(t, created, existing)
competing := request
competing.Method = MethodBundle
_, _, err = store.Create(competing)
require.ErrorIs(t, err, ErrOperationActive)
_, err = store.SetStatus(request.Key(), PhaseFailedRestored, "restored", "bad artifact")
require.NoError(t, err)
_, wasCreated, err = store.Create(Operation{
ID: "cluster-node-2",
Action: ActionUpgrade,
TargetVersion: "v0.1.2",
PreviousVersion: "v0.1.1",
Method: MethodAPT,
})
retried, wasCreated, err := store.Create(request)
require.NoError(t, err)
assert.True(t, wasCreated)
require.True(t, wasCreated)
require.Equal(t, created.Key(), retried.Key())
require.Equal(t, PhasePending, retried.Phase)
require.Empty(t, retried.ErrorMessage)
_, err = store.SetStatus(request.Key(), PhaseSucceeded, "verified", "")
require.NoError(t, err)
_, wasCreated, err = store.Create(competing)
require.NoError(t, err)
require.True(t, wasCreated)
}
func TestStoreRejectsOperationIDReuseForDifferentRequest(t *testing.T) {
store := NewStore(t.TempDir())
_, _, err := store.Create(Operation{
ID: "same-id",
Action: ActionUpgrade,
TargetVersion: "v0.1.2",
PreviousVersion: "v0.1.1",
Method: MethodAPT,
})
require.NoError(t, err)
_, _, err = store.Create(Operation{
ID: "same-id",
Action: ActionUpgrade,
TargetVersion: "v0.1.3",
PreviousVersion: "v0.1.1",
Method: MethodAPT,
})
require.Error(t, err)
assert.True(t, errors.Is(err, ErrOperationConflict))
}
func TestValidateOperationID(t *testing.T) {
tests := []struct {
name string
id string
wantError bool
}{
{name: "valid", id: "cluster.node-1_upgrade", wantError: false},
{name: "empty", id: "", wantError: true},
{name: "path traversal", id: "../escape", wantError: true},
{name: "systemd escape", id: "node@upgrade", wantError: true},
func TestValidateRequestKey(t *testing.T) {
for _, key := range []string{"v0.1.2_apt", "v0.1.2_bundle"} {
require.NoError(t, ValidateRequestKey(key))
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := ValidateOperationID(test.id)
if test.wantError {
require.Error(t, err)
return
}
require.NoError(t, err)
})
for _, key := range []string{"", "../escape", "v0.1.2@apt", "v01.1.2_apt", "v0.1.2_other"} {
require.Error(t, ValidateRequestKey(key))
}
}
+20 -13
View File
@@ -7,6 +7,9 @@ package agentupgrade
import "time"
// DefaultRoot is the durable directory shared by the agent and its updater.
const DefaultRoot = "/var/lib/nvke/agent-upgrades"
// Method selects how the updater obtains and installs the target artifact.
type Method string
@@ -17,16 +20,6 @@ const (
MethodBundle Method = "bundle"
)
// Action distinguishes an upgrade from a restore of a prior operation.
type Action string
const (
// ActionUpgrade applies the requested target artifact.
ActionUpgrade Action = "upgrade"
// ActionRollback restores the artifact retained by a prior upgrade.
ActionRollback Action = "rollback"
)
// Phase is the durable lifecycle state of an updater operation.
type Phase string
@@ -46,15 +39,12 @@ const (
// Operation is persisted below /var/lib/nvke/agent-upgrades and is intentionally
// independent of the nvke-agent state file so it survives service replacement.
type Operation struct {
ID string `json:"id"`
Action Action `json:"action"`
TargetVersion string `json:"targetVersion"`
PreviousVersion string `json:"previousVersion"`
PreviousPackageName string `json:"previousPackageName,omitempty"`
PreviousPackageVersion string `json:"previousPackageVersion,omitempty"`
Method Method `json:"method"`
ArtifactURL string `json:"artifactUrl,omitempty"`
RestoreFromOperationID string `json:"restoreFromOperationId,omitempty"`
Phase Phase `json:"phase"`
Step string `json:"step"`
ErrorMessage string `json:"errorMessage,omitempty"`
@@ -73,3 +63,20 @@ func (o Operation) Terminal() bool {
return false
}
}
// Request identifies an installation by its exact target version and method.
type Request struct {
TargetVersion string `json:"targetVersion"`
Method Method `json:"method"`
}
// Key returns the filesystem and systemd name derived from the request pair.
func (r Request) Key() string { return r.TargetVersion + "_" + string(r.Method) }
// Request returns the installation pair for this operation.
func (o Operation) Request() Request {
return Request{TargetVersion: o.TargetVersion, Method: o.Method}
}
// Key returns the filesystem and systemd name derived from the request pair.
func (o Operation) Key() string { return o.Request().Key() }
+85 -73
View File
@@ -73,42 +73,38 @@ func NewUpdater(store *Store) *Updater {
}
}
// Run executes or resumes the operation with id.
func (u *Updater) Run(ctx context.Context, id string) error {
op, err := u.Store.Load(id)
// Run executes or resumes the version-change request.
func (u *Updater) Run(ctx context.Context, key string) error {
op, err := u.Store.Load(key)
if err != nil {
return fmt.Errorf("loading node-agent upgrade operation: %w", err)
}
if op.Terminal() {
return nil
}
if _, err := u.Store.SetStatus(id, PhaseRunning, "starting", ""); err != nil {
if _, err := u.Store.SetStatus(key, PhaseRunning, "starting", ""); err != nil {
return fmt.Errorf("marking node-agent upgrade running: %w", err)
}
if op.Action == ActionRollback {
return u.runRollback(ctx, op)
}
mutated, runErr := u.runUpgrade(ctx, op)
if runErr == nil {
_, err = u.Store.SetStatus(id, PhaseSucceeded, "verified", "")
_, err = u.Store.SetStatus(key, PhaseSucceeded, "verified", "")
return err
}
if !mutated {
_, statusErr := u.Store.SetStatus(id, PhaseFailedRestored, "failed before replacement", runErr.Error())
_, statusErr := u.Store.SetStatus(key, PhaseFailedRestored, "failed before replacement", runErr.Error())
return errors.Join(runErr, statusErr)
}
_, _ = u.Store.SetStatus(id, PhaseRunning, "restoring previous version", runErr.Error())
_, _ = u.Store.SetStatus(key, PhaseRunning, "restoring previous version", runErr.Error())
restoreErr := u.restoreUpgrade(ctx, op)
if restoreErr == nil {
_, statusErr := u.Store.SetStatus(id, PhaseFailedRestored, "previous version restored", runErr.Error())
_, statusErr := u.Store.SetStatus(key, PhaseFailedRestored, "previous version restored", runErr.Error())
return errors.Join(runErr, statusErr)
}
message := fmt.Sprintf("upgrade failed: %v; restore failed: %v", runErr, restoreErr)
_, statusErr := u.Store.SetStatus(id, PhaseFailedNotRestored, "restore failed", message)
_, statusErr := u.Store.SetStatus(key, PhaseFailedNotRestored, "restore failed", message)
return errors.Join(runErr, restoreErr, statusErr)
}
@@ -124,7 +120,7 @@ func (u *Updater) runUpgrade(ctx context.Context, op Operation) (bool, error) {
}
func (u *Updater) runAPTUpgrade(ctx context.Context, op Operation) (bool, error) {
if _, err := u.Store.SetStatus(op.ID, PhaseRunning, "refreshing apt metadata", ""); err != nil {
if _, err := u.Store.SetStatus(op.Key(), PhaseRunning, "refreshing apt metadata", ""); err != nil {
return false, err
}
if _, err := u.Runner.Run(ctx, "apt-get", []string{"update"}, ""); err != nil {
@@ -138,14 +134,14 @@ func (u *Updater) runAPTUpgrade(ctx context.Context, op Operation) (bool, error)
if err != nil {
return false, err
}
if _, err := u.Store.SetPreviousPackage(op.ID, previousPackageName, previousPackageVersion); err != nil {
if _, err := u.Store.SetPreviousPackage(op.Key(), previousPackageName, previousPackageVersion); err != nil {
return false, err
}
} else if previousPackageName == "" {
previousPackageName = legacyAgentPackageName
}
assetsDir, err := u.assetsDir(op.ID)
assetsDir, err := u.assetsDir(op.Key())
if err != nil {
return false, err
}
@@ -153,7 +149,7 @@ func (u *Updater) runAPTUpgrade(ctx context.Context, op Operation) (bool, error)
return false, fmt.Errorf("creating APT staging directory: %w", err)
}
targetPackageVersion := strings.TrimPrefix(op.TargetVersion, "v")
if _, err := u.Store.SetStatus(op.ID, PhaseRunning, "downloading exact apt packages", ""); err != nil {
if _, err := u.Store.SetStatus(op.Key(), PhaseRunning, "downloading exact apt packages", ""); err != nil {
return false, err
}
targetPackageName, err := u.availablePackage(ctx, targetPackageVersion)
@@ -162,12 +158,9 @@ func (u *Updater) runAPTUpgrade(ctx context.Context, op Operation) (bool, error)
}
packages := uniqueStrings(targetPackageName+"="+targetPackageVersion, previousPackageName+"="+previousPackageVersion)
for _, pkg := range packages {
args := []string{
aptAssumeYesFlag, "--download-only", aptReinstallFlag, aptAllowDowngradesFlag,
"-o", "Dir::Cache::archives=" + assetsDir,
installCommand, pkg,
}
if _, err := u.Runner.Run(ctx, "apt-get", args, ""); err != nil {
// download retains exact artifacts even when the repository uses a file URL.
args := []string{"download", pkg}
if _, err := u.Runner.Run(ctx, "apt-get", args, assetsDir); err != nil {
return false, fmt.Errorf("staging %s: %w", pkg, err)
}
}
@@ -177,10 +170,10 @@ func (u *Updater) runAPTUpgrade(ctx context.Context, op Operation) (bool, error)
return false, err
}
if _, err := u.findDebianPackage(ctx, assetsDir, previousPackageName, previousPackageVersion); err != nil {
return false, fmt.Errorf("retaining previous package for rollback: %w", err)
return false, fmt.Errorf("retaining previous package for restoration: %w", err)
}
if _, err := u.Store.SetStatus(op.ID, PhaseRunning, "installing exact apt package", ""); err != nil {
if _, err := u.Store.SetStatus(op.Key(), PhaseRunning, "installing exact apt package", ""); err != nil {
return false, err
}
installArgs := []string{aptAssumeYesFlag, aptReinstallFlag, aptAllowDowngradesFlag, installCommand, targetDeb}
@@ -194,20 +187,20 @@ func (u *Updater) runBundleUpgrade(ctx context.Context, op Operation) (bool, err
if op.ArtifactURL == "" {
return false, errors.New("bundle operation is missing artifact URL")
}
assetsDir, err := u.assetsDir(op.ID)
assetsDir, err := u.assetsDir(op.Key())
if err != nil {
return false, err
}
if err := os.MkdirAll(assetsDir, 0o700); err != nil {
return false, fmt.Errorf("creating bundle staging directory: %w", err)
}
if err := u.snapshotInstalledFiles(op.ID); err != nil {
if err := u.snapshotInstalledFiles(op.Key()); err != nil {
return false, err
}
archive := filepath.Join(assetsDir, "target.tgz")
extractDir := filepath.Join(assetsDir, "target")
if _, err := u.Store.SetStatus(op.ID, PhaseRunning, "downloading exact bundle", ""); err != nil {
if _, err := u.Store.SetStatus(op.Key(), PhaseRunning, "downloading exact bundle", ""); err != nil {
return false, err
}
if _, err := u.Runner.Run(ctx, "curl", []string{"--fail", "--location", "--output", archive, op.ArtifactURL}, ""); err != nil {
@@ -219,7 +212,7 @@ func (u *Updater) runBundleUpgrade(ctx context.Context, op Operation) (bool, err
if _, err := u.Runner.Run(ctx, "tar", []string{"-xzf", archive, "-C", extractDir}, ""); err != nil {
return false, err
}
if _, err := u.Store.SetStatus(op.ID, PhaseRunning, "installing exact bundle", ""); err != nil {
if _, err := u.Store.SetStatus(op.Key(), PhaseRunning, "installing exact bundle", ""); err != nil {
return false, err
}
if err := u.installBundleFiles(ctx, extractDir); err != nil {
@@ -228,32 +221,12 @@ func (u *Updater) runBundleUpgrade(ctx context.Context, op Operation) (bool, err
return true, u.verifyVersion(ctx, op.TargetVersion)
}
func (u *Updater) runRollback(ctx context.Context, op Operation) error {
original, err := u.Store.Load(op.RestoreFromOperationID)
if err != nil {
return u.failRollback(op.ID, fmt.Errorf("loading upgrade operation to restore: %w", err))
}
if original.Phase != PhaseSucceeded {
return u.failRollback(op.ID, fmt.Errorf("upgrade operation %s is %s, not Succeeded", original.ID, original.Phase))
}
if _, err := u.Store.SetStatus(op.ID, PhaseRunning, "restoring retained artifact", ""); err != nil {
return err
}
if err := u.restoreUpgrade(ctx, original); err != nil {
return u.failRollback(op.ID, err)
}
if _, err := u.Store.SetStatus(op.ID, PhaseSucceeded, "previous version restored", ""); err != nil {
return err
}
return nil
}
func (u *Updater) restoreUpgrade(ctx context.Context, op Operation) error {
switch op.Method {
case MethodAPT:
return u.restoreAPT(ctx, op)
case MethodBundle:
if err := u.restoreSnapshot(ctx, op.ID); err != nil {
if err := u.restoreSnapshot(ctx, op.Key()); err != nil {
return err
}
return u.verifyVersion(ctx, op.PreviousVersion)
@@ -263,14 +236,14 @@ func (u *Updater) restoreUpgrade(ctx context.Context, op Operation) error {
}
func (u *Updater) restoreAPT(ctx context.Context, op Operation) error {
stored, err := u.Store.Load(op.ID)
stored, err := u.Store.Load(op.Key())
if err != nil {
return err
}
if stored.PreviousPackageVersion == "" {
return errors.New("previous Debian package version was not retained")
}
assetsDir, err := u.assetsDir(op.ID)
assetsDir, err := u.assetsDir(op.Key())
if err != nil {
return err
}
@@ -348,19 +321,19 @@ func (u *Updater) findDebianPackage(ctx context.Context, dir, name, version stri
return "", fmt.Errorf("staged %s=%s package not found", name, version)
}
func (u *Updater) snapshotInstalledFiles(operationID string) error {
func (u *Updater) snapshotInstalledFiles(requestKey string) error {
_, binaryErr := os.Stat(u.AgentBinary)
_, unitErr := os.Stat(filepath.Join(u.SystemdUnitDir, u.AgentService))
if errors.Is(binaryErr, os.ErrNotExist) || errors.Is(unitErr, os.ErrNotExist) {
u.usePackageName(legacyAgentPackageName)
}
assetsDir, err := u.assetsDir(operationID)
assetsDir, err := u.assetsDir(requestKey)
if err != nil {
return err
}
backupDir := filepath.Join(assetsDir, "previous")
if err := os.MkdirAll(backupDir, 0o700); err != nil {
return fmt.Errorf("creating bundle rollback directory: %w", err)
return fmt.Errorf("creating bundle restoration directory: %w", err)
}
marker := filepath.Join(backupDir, ".snapshot-complete")
if _, err := os.Stat(marker); err == nil {
@@ -397,7 +370,13 @@ func (u *Updater) snapshotInstalledFiles(operationID string) error {
files = append(files, u.MigrationScript)
}
for _, source := range files {
if err := copyRegularFile(source, filepath.Join(backupDir, filepath.Base(source))); err != nil {
destination := filepath.Join(backupDir, filepath.Base(source))
if _, err := os.Stat(destination); err == nil {
continue
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
if err := copyRegularFileAtomically(source, destination); err != nil {
return fmt.Errorf("retaining %s: %w", source, err)
}
}
@@ -405,26 +384,26 @@ func (u *Updater) snapshotInstalledFiles(operationID string) error {
}
func (u *Updater) installBundleFiles(ctx context.Context, extractDir string) error {
agent, err := findFile(extractDir, agentPackageName, legacyAgentPackageName)
agent, err := findFile(extractDir, true, agentPackageName, legacyAgentPackageName)
if err != nil {
return err
}
packageName := filepath.Base(agent)
updater, err := findFile(extractDir, packageName+"-updater")
updater, err := findFile(extractDir, false, packageName+"-updater")
if err != nil {
return err
}
agentUnit, err := findFile(extractDir, packageName+".service")
agentUnit, err := findFile(extractDir, true, packageName+".service")
if err != nil {
return err
}
updaterUnit, err := findFile(extractDir, packageName+"-updater@.service")
updaterUnit, err := findFile(extractDir, false, packageName+"-updater@.service")
if err != nil {
return err
}
migrationScript := ""
if packageName == agentPackageName {
migrationScript, err = findFile(extractDir, "migrate-agent-paths.sh")
migrationScript, err = findFile(extractDir, true, "migrate-agent-paths.sh")
if err != nil {
return err
}
@@ -443,14 +422,22 @@ func (u *Updater) installBundleFiles(ctx context.Context, extractDir string) err
}
if u.AgentService != packageName+".service" {
// A regular legacy unit would prevent systemd from creating the new
// unit's Alias. The snapshot already retained these files for rollback.
for _, name := range []string{u.AgentService, filepath.Base(u.UpdaterBinary) + "@.service"} {
// unit's Alias. The snapshot already retained these files for restoration.
replacedUnits := []string{u.AgentService}
if updaterUnit != "" {
replacedUnits = append(replacedUnits, filepath.Base(u.UpdaterBinary)+"@.service")
}
for _, name := range replacedUnits {
if err := os.Remove(filepath.Join(u.SystemdUnitDir, name)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("removing replaced unit %s: %w", name, err)
}
}
}
previousUpdater := u.UpdaterBinary
u.usePackageName(packageName)
if updater == "" {
u.UpdaterBinary = previousUpdater
}
// Old retained bundles predate the migration; aliases survive their restore.
if migrationScript != "" {
if _, err := u.Runner.Run(ctx, "bash", []string{migrationScript}, ""); err != nil {
@@ -473,6 +460,9 @@ func (u *Updater) installBundleFiles(ctx context.Context, extractDir string) err
{source: updaterUnit, target: filepath.Join(u.SystemdUnitDir, filepath.Base(u.UpdaterBinary)+"@.service"), mode: "0644"},
{source: agentUnit, target: filepath.Join(u.SystemdUnitDir, u.AgentService), mode: "0644"},
} {
if file.source == "" {
continue
}
if _, err := u.Runner.Run(ctx, installCommand, []string{"-m", file.mode, file.source, file.target}, ""); err != nil {
return err
}
@@ -496,8 +486,8 @@ func (u *Updater) installBundleFiles(ctx context.Context, extractDir string) err
return err
}
func (u *Updater) restoreSnapshot(ctx context.Context, operationID string) error {
assetsDir, err := u.assetsDir(operationID)
func (u *Updater) restoreSnapshot(ctx context.Context, requestKey string) error {
assetsDir, err := u.assetsDir(requestKey)
if err != nil {
return err
}
@@ -529,19 +519,14 @@ func (u *Updater) verifyVersion(ctx context.Context, expected string) error {
return fmt.Errorf("nvke-agent did not become active at version %s", expected)
}
func (u *Updater) assetsDir(operationID string) (string, error) {
dir, err := u.Store.OperationDir(operationID)
func (u *Updater) assetsDir(requestKey string) (string, error) {
dir, err := u.Store.OperationDir(requestKey)
if err != nil {
return "", err
}
return filepath.Join(dir, "assets"), nil
}
func (u *Updater) failRollback(operationID string, operationErr error) error {
_, statusErr := u.Store.SetStatus(operationID, PhaseFailedNotRestored, "rollback failed", operationErr.Error())
return errors.Join(operationErr, statusErr)
}
func parseAgentVersion(output string) string {
output = strings.TrimSpace(output)
for _, prefix := range []string{"NVKE Agent Version:", legacyAgentVersionPrefix} {
@@ -565,7 +550,7 @@ func uniqueStrings(values ...string) []string {
return result
}
func findFile(root string, names ...string) (string, error) {
func findFile(root string, required bool, names ...string) (string, error) {
var matches []string
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
@@ -579,6 +564,9 @@ func findFile(root string, names ...string) (string, error) {
if err != nil {
return "", fmt.Errorf("searching bundle for %v: %w", names, err)
}
if len(matches) == 0 && !required {
return "", nil
}
if len(matches) != 1 {
return "", fmt.Errorf("bundle must contain exactly one of %v, found %d", names, len(matches))
}
@@ -612,3 +600,27 @@ func copyRegularFile(source, target string) error {
}
return output.Close()
}
func copyRegularFileAtomically(source, target string) error {
file, err := os.CreateTemp(filepath.Dir(target), ".backup-*")
if err != nil {
return err
}
temporary := file.Name()
defer os.Remove(temporary)
if err := file.Close(); err != nil {
return err
}
if err := copyRegularFile(source, temporary); err != nil {
return err
}
if err := os.Rename(temporary, target); err != nil {
return err
}
directory, err := os.Open(filepath.Dir(target))
if err != nil {
return err
}
defer directory.Close()
return directory.Sync()
}
@@ -0,0 +1,87 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package agentupgrade
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
type bundleInstallRunner struct{}
func (bundleInstallRunner) Run(_ context.Context, name string, args []string, _ string) ([]byte, error) {
if name == "install" {
return nil, copyRegularFile(args[len(args)-2], args[len(args)-1])
}
return nil, nil
}
func TestBundleDowngradePreservesUpdaterAndOriginalRestorationFiles(t *testing.T) {
root := t.TempDir()
updater := NewUpdater(NewStore(root))
updater.AgentBinary = filepath.Join(root, "nvke-agent")
updater.UpdaterBinary = filepath.Join(root, "nvke-agent-updater")
updater.SystemdUnitDir = root
updater.MigrationScript = filepath.Join(root, "migrate-agent-paths.sh")
updater.Runner = bundleInstallRunner{}
for _, name := range []string{"nvke-agent", "nvke-agent-updater", "nvke-agent.service", "nvke-agent-updater@.service", "migrate-agent-paths.sh"} {
require.NoError(t, os.WriteFile(filepath.Join(root, name), []byte("original"), 0o600))
}
_, _, err := updater.Store.Create(Operation{TargetVersion: "v0.1.1", PreviousVersion: "v0.1.2", Method: MethodBundle})
require.NoError(t, err)
require.NoError(t, updater.snapshotInstalledFiles("v0.1.1_bundle"))
extracted := t.TempDir()
for _, name := range []string{"nvke-agent", "nvke-agent.service", "migrate-agent-paths.sh"} {
require.NoError(t, os.WriteFile(filepath.Join(extracted, name), []byte("older release"), 0o600))
}
require.NoError(t, updater.installBundleFiles(context.Background(), extracted))
require.NoError(t, updater.snapshotInstalledFiles("v0.1.1_bundle"))
originalUpdater, err := os.ReadFile(updater.UpdaterBinary)
require.NoError(t, err)
require.Equal(t, "original", string(originalUpdater))
assets, err := updater.assetsDir("v0.1.1_bundle")
require.NoError(t, err)
retained, err := os.ReadFile(filepath.Join(assets, "previous", "nvke-agent"))
require.NoError(t, err)
require.Equal(t, "original", string(retained))
}
func TestBundleSnapshotPublishesOnlyCompleteBackups(t *testing.T) {
root := t.TempDir()
store := NewStore(filepath.Join(root, "operations"))
_, _, err := store.Create(Operation{TargetVersion: "v0.1.2", PreviousVersion: "v0.1.1", Method: MethodBundle})
require.NoError(t, err)
updater := NewUpdater(store)
updater.AgentBinary = filepath.Join(root, "nvke-agent")
updater.UpdaterBinary = filepath.Join(root, "nvke-agent-updater")
updater.SystemdUnitDir = filepath.Join(root, "units")
updater.MigrationScript = filepath.Join(root, "migrate-agent-paths.sh")
require.NoError(t, os.MkdirAll(updater.SystemdUnitDir, 0o700))
require.NoError(t, os.WriteFile(filepath.Join(updater.SystemdUnitDir, agentServiceName), []byte("original"), 0o600))
// A nonregular source must never publish a backup that a retry skips.
require.NoError(t, os.Mkdir(updater.AgentBinary, 0o700))
require.ErrorContains(t, updater.snapshotInstalledFiles("v0.1.2_bundle"), "not a regular file")
assets, err := updater.assetsDir("v0.1.2_bundle")
require.NoError(t, err)
backup := filepath.Join(assets, "previous")
entries, err := os.ReadDir(backup)
require.NoError(t, err)
require.Empty(t, entries)
require.NoError(t, os.Remove(updater.AgentBinary))
for _, source := range []string{updater.AgentBinary, updater.UpdaterBinary, filepath.Join(updater.SystemdUnitDir, agentServiceName), filepath.Join(updater.SystemdUnitDir, "nvke-agent-updater@.service"), updater.MigrationScript} {
require.NoError(t, os.WriteFile(source, []byte("original"), 0o700))
}
// An interrupted unpublished copy must not become the restoration source.
require.NoError(t, os.WriteFile(filepath.Join(backup, ".backup-interrupted"), []byte("partial"), 0o600))
require.NoError(t, updater.snapshotInstalledFiles("v0.1.2_bundle"))
require.NoError(t, os.WriteFile(updater.AgentBinary, []byte("replacement"), 0o700))
require.NoError(t, updater.snapshotInstalledFiles("v0.1.2_bundle"))
retained, err := os.ReadFile(filepath.Join(backup, "nvke-agent"))
require.NoError(t, err)
require.Equal(t, "original", string(retained))
}
+15 -17
View File
@@ -25,12 +25,12 @@ type aptUpdaterRunner struct {
installedVersions []string
}
func (r *aptUpdaterRunner) Run(_ context.Context, name string, args []string, _ string) ([]byte, error) {
func (r *aptUpdaterRunner) Run(_ context.Context, name string, args []string, dir string) ([]byte, error) {
switch name {
case "apt-get":
if containsArg(args, "--download-only") {
if len(args) > 0 && args[0] == "download" {
pkg, version, _ := strings.Cut(args[len(args)-1], "=")
assetsDir := strings.TrimPrefix(valueAfter(args, "-o"), "Dir::Cache::archives=")
assetsDir := dir
path := filepath.Join(assetsDir, fmt.Sprintf("%s_%s_native.deb", pkg, version))
if err := os.WriteFile(path, []byte("test package"), 0o600); err != nil {
return nil, err
@@ -136,8 +136,6 @@ func TestUpdaterAPTUpgradeAndAutomaticRestore(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
store := NewStore(t.TempDir())
_, _, err := store.Create(Operation{
ID: "upgrade-1",
Action: ActionUpgrade,
TargetVersion: "v0.1.2",
PreviousVersion: "v0.1.1",
Method: MethodAPT,
@@ -154,13 +152,13 @@ func TestUpdaterAPTUpgradeAndAutomaticRestore(t *testing.T) {
updater.Runner = runner
updater.VerifyAttempts = 1
err = updater.Run(context.Background(), "upgrade-1")
err = updater.Run(context.Background(), "v0.1.2_apt")
if test.wantError {
require.Error(t, err)
} else {
require.NoError(t, err)
}
operation, loadErr := store.Load("upgrade-1")
operation, loadErr := store.Load("v0.1.2_apt")
require.NoError(t, loadErr)
assert.Equal(t, test.wantPhase, operation.Phase)
assert.Equal(t, "0.1.1", operation.PreviousPackageVersion)
@@ -210,34 +208,34 @@ func TestParseAgentVersion(t *testing.T) {
assert.Empty(t, parseAgentVersion("NVKE Agent Updater Version: v0.3.0"))
}
func TestAPTRollbackPreservesPackageNameAtSameVersion(t *testing.T) {
func TestAPTRestorationPreservesPackageNameAtSameVersion(t *testing.T) {
store := NewStore(t.TempDir())
_, _, err := store.Create(Operation{ID: "rename", Action: ActionUpgrade, Method: MethodAPT, TargetVersion: "v0.1.1", PreviousVersion: "v0.1.1"})
_, _, err := store.Create(Operation{Method: MethodAPT, TargetVersion: "v0.1.1", PreviousVersion: "v0.1.1"})
require.NoError(t, err)
runner := &aptUpdaterRunner{currentPackage: legacyAgentPackageName, targetPackage: agentPackageName, currentVersion: "v0.1.1", currentDebVersion: "0.1.1"}
updater := NewUpdater(store)
updater.Runner, updater.VerifyAttempts = runner, 1
require.NoError(t, updater.Run(context.Background(), "rename"))
require.NoError(t, updater.Run(context.Background(), "v0.1.1_apt"))
assert.Equal(t, agentPackageName, runner.currentPackage)
_, _, err = store.Create(Operation{ID: "restore", Action: ActionRollback, RestoreFromOperationID: "rename"})
op, err := store.Load("v0.1.1_apt")
require.NoError(t, err)
require.NoError(t, updater.Run(context.Background(), "restore"))
require.NoError(t, updater.restoreUpgrade(context.Background(), op))
assert.Equal(t, legacyAgentPackageName, runner.currentPackage)
assert.Equal(t, "0.1.1", runner.currentDebVersion)
}
func TestAPTResumeKeepsOriginalRollbackPackage(t *testing.T) {
func TestAPTResumeKeepsOriginalRestorationPackage(t *testing.T) {
store := NewStore(t.TempDir())
_, _, err := store.Create(Operation{ID: "resume", Action: ActionUpgrade, Method: MethodAPT, TargetVersion: "v0.1.2", PreviousVersion: "v0.1.1"})
_, _, err := store.Create(Operation{Method: MethodAPT, TargetVersion: "v0.1.2", PreviousVersion: "v0.1.1"})
require.NoError(t, err)
_, err = store.SetPreviousPackage("resume", legacyAgentPackageName, "0.1.1")
_, err = store.SetPreviousPackage("v0.1.2_apt", legacyAgentPackageName, "0.1.1")
require.NoError(t, err)
// The renamed target is installed when a prior updater process is interrupted.
runner := &aptUpdaterRunner{currentPackage: agentPackageName, targetPackage: agentPackageName, currentVersion: "v0.1.2", currentDebVersion: "0.1.2", failTargetInstall: true}
updater := NewUpdater(store)
updater.Runner, updater.VerifyAttempts = runner, 1
require.Error(t, updater.Run(context.Background(), "resume"))
op, err := store.Load("resume")
require.Error(t, updater.Run(context.Background(), "v0.1.2_apt"))
op, err := store.Load("v0.1.2_apt")
require.NoError(t, err)
assert.Equal(t, PhaseFailedRestored, op.Phase)
assert.Equal(t, legacyAgentPackageName, op.PreviousPackageName)
+2 -2
View File
@@ -5,7 +5,7 @@ Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/nvke-agent-updater --operation-id %i
ExecStart=/usr/local/bin/nvke-agent-updater --request %i
TimeoutStartSec=30min
Restart=on-failure
RestartSec=5s
@@ -13,5 +13,5 @@ StandardOutput=journal
StandardError=journal
# This unit deliberately has no PartOf=, Requires=, or shared cgroup with
# nvke-agent.service. Debian prerm stops nvke-agent.service during replacement;
# the node-agent service. Debian prerm stops it during replacement;
# the package transaction must continue in this independent unit.
+49 -4
View File
@@ -41,6 +41,12 @@ const (
DiskSelectionStrategyCreateSmallest DiskSelectionStrategyCreate = "smallest"
)
// Defines values for NodeAgentUpgradeStatusPhase.
const (
NodeAgentUpgradeStatusPhasePending NodeAgentUpgradeStatusPhase = "Pending"
NodeAgentUpgradeStatusPhaseRunning NodeAgentUpgradeStatusPhase = "Running"
)
// Defines values for NodeTaintEffect.
const (
NodeTaintEffectNoExecute NodeTaintEffect = "NoExecute"
@@ -103,15 +109,15 @@ type Cluster struct {
// TeleportEnabled Whether Teleport SSH enrollment is enabled for nodes in this cluster.
TeleportEnabled *bool `json:"teleportEnabled,omitempty"`
// CreatedAt Creation time.
CreatedAt time.Time `json:"createdAt"`
// Conditions Lifecycle conditions.
Conditions ClusterConditions `json:"conditions"`
// ControlPlaneConfig Current control-plane configuration.
ControlPlaneConfig *ControlPlaneConfig `json:"controlPlaneConfig,omitempty"`
// CreatedAt Creation time.
CreatedAt time.Time `json:"createdAt"`
// Infra Infra provider fields.
Infra *InfraClusterProvider `json:"infra,omitempty"`
@@ -120,6 +126,9 @@ type Cluster struct {
// Nico NICo identifiers.
Nico *NicoClusterProvider `json:"nico,omitempty"`
// NodeAgentUpgrade The active agent upgrade and latest retry error.
NodeAgentUpgrade *NodeAgentUpgradeStatus `json:"nodeAgentUpgrade,omitempty"`
}
// ClusterConditions Lifecycle conditions of a cluster. Each is a Condition.
@@ -197,7 +206,7 @@ type ConfigProfile struct {
Name string `json:"name"`
}
// ControlPlaneConfig The control-plane configuration in effect.
// ControlPlaneConfig The control-plane configuration in effect, including the desired node-agent version.
type ControlPlaneConfig struct {
// ConfigurationID ID of the current configuration snapshot.
ConfigurationID openapi_types.UUID `json:"configurationId,omitempty"`
@@ -214,6 +223,9 @@ type ControlPlaneConfig struct {
// Nico NICo settings for control-plane nodes.
Nico *NicoControlPlaneProvider `json:"nico,omitempty"`
// NodeAgentConfig Desired control-plane node-agent configuration.
NodeAgentConfig *NodeAgentConfig `json:"nodeAgentConfig,omitempty"`
// NodeLabels Labels applied to control-plane nodes, as a map of keys to values. Set at creation.
NodeLabels map[string]string `json:"nodeLabels,omitempty"`
@@ -366,6 +378,9 @@ type CreateClusterControlPlaneConfig struct {
// configProfile is optional, and exactly one of subnetIDs and vpcPrefixIDs.
Nico *NicoControlPlaneProviderCreate `json:"nico,omitempty"`
// NodeAgentConfig Desired control-plane node-agent configuration.
NodeAgentConfig *NodeAgentConfig `json:"nodeAgentConfig,omitempty"`
// NodeLabels Labels applied to control-plane nodes, as a map of keys to values. Set at creation.
NodeLabels map[string]string `json:"nodeLabels,omitempty"`
@@ -829,6 +844,33 @@ type Node struct {
Nico *NicoNodeProvider `json:"nico,omitempty"`
}
// NodeAgentConfig Desired control-plane node-agent configuration.
type NodeAgentConfig struct {
// Version Exact agent release version. An empty value disables agent convergence.
Version *string `json:"version,omitempty"`
}
// NodeAgentUpgradeStatus The active agent upgrade and latest retry error.
type NodeAgentUpgradeStatus struct {
// ErrorMessage Latest failure message while retries continue.
ErrorMessage string `json:"errorMessage"`
// Method Installation method from the controller configuration.
Method string `json:"method"`
// NodeID ID of the selected control-plane node.
NodeID openapi_types.UUID `json:"nodeId"`
// Phase Pending before installation starts. Running includes retries.
Phase NodeAgentUpgradeStatusPhase `json:"phase"`
// TargetVersion Exact version accepted for this upgrade.
TargetVersion string `json:"targetVersion"`
}
// NodeAgentUpgradeStatusPhase Pending before installation starts. Running includes retries.
type NodeAgentUpgradeStatusPhase string
// NodeConditions Each is a Condition. A node normally moves through pending, provisioningClaimed,
// provisioning, readyToJoin, joined and provisioned; deletion moves through
// deleteRequested (control-plane nodes) and deleting.
@@ -1101,6 +1143,9 @@ type UpdateClusterControlPlaneConfig struct {
// it, and an empty value clears it. Clearing a required field is rejected.
Nico *NicoControlPlaneProviderUpdate `json:"nico,omitempty"`
// NodeAgentConfig Desired control-plane node-agent configuration.
NodeAgentConfig *NodeAgentConfig `json:"nodeAgentConfig,omitempty"`
// ProvisioningMonitorDisabled When true, nodes stuck in provisioning past the timeout are not replaced automatically.
ProvisioningMonitorDisabled *bool `json:"provisioningMonitorDisabled,omitempty"`
+39 -2
View File
@@ -1032,10 +1032,40 @@ components:
infra:
x-fern-ignore: true
$ref: "#/components/schemas/InfraClusterProvider"
NodeAgentConfig:
description: Desired control-plane node-agent configuration.
type: object
additionalProperties: false
properties:
version:
type: string
description: Exact agent release version. An empty value disables agent convergence.
NodeAgentUpgradeStatus:
description: The active agent upgrade and latest retry error.
type: object
required: [nodeId, targetVersion, method, phase, errorMessage]
properties:
nodeId:
description: ID of the selected control-plane node.
type: string
format: uuid
targetVersion:
description: Exact version accepted for this upgrade.
type: string
method:
description: Installation method from the controller configuration.
type: string
phase:
description: Pending before installation starts. Running includes retries.
type: string
enum: [Pending, Running]
errorMessage:
description: Latest failure message while retries continue.
type: string
ControlPlaneConfig:
type: object
additionalProperties: false
description: The control-plane configuration in effect.
description: The control-plane configuration in effect, including the desired node-agent version.
properties:
configurationId:
type: string
@@ -1078,7 +1108,8 @@ components:
allOf:
- $ref: "#/components/schemas/InfraControlPlaneProvider"
description: Infra provider control plane fields.
nodeAgentConfig:
$ref: "#/components/schemas/NodeAgentConfig"
ClusterControlPlane:
type: object
additionalProperties: false
@@ -1203,6 +1234,8 @@ components:
infra:
x-fern-ignore: true
$ref: "#/components/schemas/InfraControlPlaneProvider"
nodeAgentConfig:
$ref: "#/components/schemas/NodeAgentConfig"
UpdateClusterControlPlaneConfig:
type: object
additionalProperties: false
@@ -1240,6 +1273,8 @@ components:
infra:
x-fern-ignore: true
$ref: "#/components/schemas/InfraControlPlaneProviderUpdate"
nodeAgentConfig:
$ref: "#/components/schemas/NodeAgentConfig"
Cluster:
description: |
A Kubernetes cluster. Holds the Kubernetes version, network, CNI, etcd
@@ -1327,6 +1362,8 @@ components:
allOf:
- $ref: "#/components/schemas/InfraClusterProvider"
description: Infra provider fields.
nodeAgentUpgrade:
$ref: "#/components/schemas/NodeAgentUpgradeStatus"
UpdateClusterRequest:
description: Changes to a cluster. All fields are optional; unknown fields are rejected.
type: object
+274 -269
View File
@@ -2187,275 +2187,280 @@ func (sh *strictHandler) ListOSProfiles(w http.ResponseWriter, r *http.Request)
// Base64 encoded, gzipped, json marshaled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pSr+bq1sa6RrreABiochYc",
"e3ZNl/YbykUYtG9Zeo98++0F/w1bSLQsrR8WPhhZyyZsrmgqMxSkbUG+TYcXzC1SLGVeBt+UZfNhDa5D",
"NLKqn70pc31+oyY7YdQPIdU2UI547cYWtiCJUlWce2PZhZQAI5X2hrpUVJxEqvikKOnYD8t8+H7GAXgg",
"xZKhqaOlcxvXhKZpUUUTdy8zy0+BXBJvv+gT37ZwE2bg0jlRV45tNwniiBR8AXjSDw/dncLIH0qR7zyl",
"hhVHM2qtLIF6tu2mVwUMzGl5n0Gm7mFoV041WbiwqXFbx+NcGJ5hB0rist2lIjQx2q3RuQJQAm0eaOod",
"BbZKNKcZaCkgCtgnXruG0bkubG6OYu00jPi7pLiorSZ8K+0QZ8B/ERjEi+LdHOwOFXv3pGzzdUCc0T52",
"Vreu++ULYTeqsyhGUSq0JZ7Xpx27biU+wXezjHVyanTtYriMTsRWKmzhcJYWiqVPD9YubXDdvXZCS6hs",
"7wSt73fhvC+tNk6FO6+eM0GHwyE/t8zWRQLOWdFpqRy92m1J5+hj0U2tfihwzXERTZUtiZFTe6/L/rFB",
"KmKR6+MYnpIZuBdOWiV/q8M4nNREY1ILfD0vqiZzUVTBLaDhTGHwYyVZZuTCJlGED14HOhbMh8JGSHDd",
"LonrtK+DRu2uQIP3U5TsB7fIrv22q+w4RNIWnvzCakkweMigiJ5RW3xe1FStWgziULRJ7GedJb9Js+L3",
"pSve0ILRclKBFtdkDX4PBTe6E61LsJyFqYBNmChfGiMORF0/T21V39TnQzciilNDwYV3KPpovL5TMM5K",
"62mhElsG74rRS8GaS3bxSs0VO2esd6GEEI7tXxWk46IpKMW2HDvJ+AQZi70blihWzRHVRbUtyOE7Sazh",
"SPfLT7wt6ebDzf8ZAOCxHKDeSwEA",
}
// GetSwagger returns the content of the embedded swagger specification file
+1
View File
@@ -480,6 +480,7 @@ func main() {
temporalClient,
k8sControllerManager.GetClient(),
managementK8sClient,
nodeAgentClient,
)
if err := controlPlaneController.SetupWithManager(k8sControllerManager); err != nil {
logger.Error("Failed to set up control plane controller", "error", err)
@@ -98,6 +98,7 @@ move `create` and `annotations` from `nkeSystemNamespace` to
| nodeAgent.tlsJwt.subjectService | string | `""` | Service segment in the canonical local SPIFFE ID exchanged by DSX Identity. |
| nodeAgent.tlsJwt.subjectTenant | string | `""` | Tenant segment in the canonical local SPIFFE ID exchanged by DSX Identity. |
| nodeAgent.tlsJwt.subjectTrustDomain | string | `""` | Exact SPIFFE trust domain accepted in node-agent JWT subjects. |
| nodeAgent.updateMethod | string | `""` | Agent installation method: apt or bundle. Required when clusters set a desired agent version. |
| nodeSelector | object | `{}` | |
| nvkeOIDCAuth.caBundleSecret.key | string | `""` | Key in the Secret containing the OIDC CA bundle. |
| nvkeOIDCAuth.caBundleSecret.name | string | `""` | Name of the Secret containing the OIDC CA bundle. |
@@ -27,6 +27,7 @@ PROFILES_DIR: profilesDir
RUNBOOKS_DIR: runbooksDir
TENANT_ACCESS_ENABLED: tenantAccessEnabled
NODE_AGENT_UPDATE_METHOD: nodeAgent.updateMethod
NODE_AGENT_SPIRE_ATTESTATION_METHOD: nodeAgent.spireAttestationMethod
NODE_AGENT_DSX_IMDS_ENDPOINT: nodeAgent.dsxImds.endpoint
NODE_AGENT_DSX_IMDS_PLUGIN_CHECKSUM: nodeAgent.dsxImds.pluginChecksum
@@ -58,6 +58,7 @@ data:
runbooksDir: {{ include "controller.runbooksDir" . | quote }}
tenantAccessEnabled: {{ .Values.tenantAccess.enabled }}
nodeAgent:
updateMethod: {{ .Values.nodeAgent.updateMethod | quote }}
spireAttestationMethod: {{ .Values.nodeAgent.spireAttestationMethod | quote }}
dsxImds:
endpoint: {{ if $dsxImds }}{{ trim .Values.nodeAgent.dsxImds.endpoint | quote }}{{ else }}"http://169.254.169.254"{{ end }}
@@ -92,6 +92,8 @@ nodeAgent:
interval: "2m"
# -- Symmetric fractional scheduling variation. Set 0 to disable jitter.
jitter: 0.1
# -- Installation method for agent convergence: apt or bundle. Required when clusters opt in.
updateMethod: ""
# -- SPIRE node attestation method pinned to newly created nodes. Changing
# this deployment default does not reconfigure existing nodes; keep their
# attestation plugins available until those nodes are retired or migrated.
+58
View File
@@ -0,0 +1,58 @@
# In-place control-plane node-agent updates
NVKE can update the node agent without replacing a bare-metal node. This feature
covers control planes managed by the control-plane controller. Workers and
pool-managed control planes are outside its scope.
Set `nodeAgent.updateMethod` to `apt` or `bundle` in `nke-controller-config`.
In Helm, set `nodeAgent.updateMethod`. The installation method comes from the controller
configuration, not the cluster request.
Set `controlPlaneConfig.nodeAgentConfig.version` to an exact release version in
`CreateCluster` or `UpdateCluster`. For example, a cluster update can include:
```json
{
"controlPlaneConfig": {
"nodeAgentConfig": {
"version": "v0.1.33"
}
}
}
```
NVKE also accepts `0.1.33` and stores `v0.1.33`. It rejects partial versions,
prerelease versions, build suffixes, and `latest`. It permits downgrades.
If an update omits the version, NVKE keeps the stored target. An explicit empty
version disables future convergence. An accepted installation finishes before
NVKE uses a changed target or stops scheduling updates.
New nodes start with the agent baked into the OS image. NVKE installs the desired
version before preflight and kubeadm. Nodes that already run that version
continue without another installation.
If you opt in, keep the OS image's agent version equal to the cluster's desired
version during rolling node updates. Before a rolling update, update the image
or the desired version so that both match. A newer image does not change the
cluster's desired version automatically.
The control-plane controller updates joined nodes one at a time. It retries the
same node after failures. `GetCluster.nodeAgentUpgrade` reports the accepted
target, current phase, and latest error. Changing the desired version does not
interrupt an accepted installation.
Installation runs in an independent systemd unit. Agent restarts do not stop
that unit. Older agents use the controller's bootstrap runbook. That path needs
Python 3, systemd, and the artifact tools included in the reference node image.
Upgrade and downgrade use `StartNodeAgentUpgrade` with the requested version.
Use `GetNodeAgentUpgradeStatus` to read the installation status.
APT installs use the node's configured repositories. Bundle installs use its
configured agent bundle source.
Node deletion or remediation stops further upgrade attempts for that node.
An accepted installation does not block the existing deletion workflow.
Cluster deletion also continues if the agent cannot respond.
See the [selected design](../../agent/docs/in-place-update/controller-driven-desired-state-design.md)
for the lifecycle and compatibility contract.
+42 -5
View File
@@ -58,9 +58,9 @@ collect_diagnostics() {
docker system df >"${state_dir}/docker-system-df.txt" 2>&1
e2e_collect_node_diagnostics "${state_dir}/nodes" \
"${CAPD_NODE_IMAGE:-cwe-capd-kindest-node:local}"
docker logs bgp-containers >"${state_dir}/bgp-containers.log" 2>&1
docker exec bgp-containers vtysh -c 'show bgp summary' >"${state_dir}/bgp-containers-summary.txt" 2>&1
docker exec bgp-containers vtysh -c 'show bgp ipv4 unicast' >"${state_dir}/bgp-containers-routes.txt" 2>&1
docker logs "${BGP_CONTAINER_NAME:-bgp-containers}" >"${state_dir}/bgp-containers.log" 2>&1
docker exec "${BGP_CONTAINER_NAME:-bgp-containers}" vtysh -c 'show bgp summary' >"${state_dir}/bgp-containers-summary.txt" 2>&1
docker exec "${BGP_CONTAINER_NAME:-bgp-containers}" vtysh -c 'show bgp ipv4 unicast' >"${state_dir}/bgp-containers-routes.txt" 2>&1
if [[ "${management_ready}" == true ]]; then
kubectl get nodes -o wide >"${state_dir}/management-nodes.txt" 2>&1
kubectl get pods -A -o wide >"${state_dir}/management-pods.txt" 2>&1
@@ -157,7 +157,9 @@ if curl --fail --silent --show-error --connect-timeout 1 --max-time 1 \
fail "another Tilt session is running on port 10350; stop it before running this script"
fi
if [[ "${host_os}" == darwin ]]; then
if [[ "${LOCAL_NVKE_E2E_REUSE_DOCKER_HOST:-false}" == true ]]; then
docker info >/dev/null 2>&1 || fail "the existing Docker daemon is unavailable"
elif [[ "${host_os}" == darwin ]]; then
log "starting Colima with ${COLIMA_CPUS} CPUs, ${COLIMA_MEMORY_GIB} GiB memory, and ${COLIMA_DISK_GIB} GiB disk"
make -C "${repo_root}" host-up
else
@@ -211,6 +213,9 @@ log "building the CAPD bundle from public sources"
bundle_dir="${tmp_dir}/bundles"
rm -rf "${bundle_dir}"
CNI_PLUGIN=ovn-kubernetes BUNDLE_ARCH="${host_arch}" bash "${repo_root}/hack/ci/prepare-capd-bundles.sh" "${bundle_dir}"
if [[ "${LOCAL_NVKE_E2E_NODE_AGENT_UPGRADE:-false}" == true ]]; then
bash "${repo_root}/hack/prepare-node-agent-e2e.sh" "${bundle_dir}" "${host_arch}"
fi
export SPIRE_AGENT_BUNDLE_PATH="${bundle_dir}/spire-agent.tgz"
CAPD_CNI_CHARTS_DEB_PATH="${bundle_dir}/nvke-cni-ovn-charts-1.4.0_1.4.0_${host_arch}.deb"
@@ -272,6 +277,36 @@ else
make -C "${repo_root}" capd-up REGISTRY_MIRROR_IMAGE="$(dockerhub_image registry:2)"
fi
if [[ "${LOCAL_NVKE_E2E_NODE_AGENT_UPGRADE:-false}" == true ]]; then
qualification_image_dir="${tmp_dir}/agent-qualification-image"
mkdir -p "${qualification_image_dir}"
cat >"${qualification_image_dir}/Dockerfile" <<'DOCKERFILE'
ARG BASE_IMAGE
FROM ${BASE_IMAGE}
COPY kubeadm-record-version /usr/local/sbin/kubeadm-record-version
RUN if [ ! -e /usr/local/sbin/kubeadm-container-original ]; then \
mv /usr/local/sbin/kubeadm-systemverification-shim /usr/local/sbin/kubeadm-container-original; \
fi && \
chmod 0755 /usr/local/sbin/kubeadm-record-version && \
ln -sf /usr/local/sbin/kubeadm-record-version /usr/local/sbin/kubeadm-systemverification-shim
DOCKERFILE
cat >"${qualification_image_dir}/kubeadm-record-version" <<'WRAPPER'
#!/bin/sh
set -eu
case "$1" in
init|join)
mkdir -p /var/lib/nvke
printf '%s %s\n' "$1" "$(/usr/local/bin/nvke-agent --version)" >>/var/lib/nvke/e2e-kubeadm-agent-versions.log
;;
esac
exec /usr/local/sbin/kubeadm-container-original "$@"
WRAPPER
node_image="${CAPD_NODE_IMAGE:-cwe-capd-kindest-node:local}"
qualification_image="nvke-capd-agent-qualification:$(basename "${tmp_dir}")"
docker build --build-arg "BASE_IMAGE=${node_image}" -t "${qualification_image}" "${qualification_image_dir}"
export CAPD_NODE_IMAGE="${qualification_image}"
fi
# The committed fixture, not the provider checkout: this script installs the
# CRDs but never builds the provider, so requiring a checkout would gate the
# whole entrypoint on fetching one. (It was also private when this was written,
@@ -425,7 +460,9 @@ local_e2e_exec() {
-e "NKE_CONTROLLER_EXPECTED_VERSION=${cwe_expected_version}" \
-e "NKE_E2E_DSX_IDENTITY_EXCHANGE=${exchange_enabled}" \
-e "NKE_E2E_BUNDLE_SERVER_URL=${e2e_bundle_server_url}" \
-e E2E_BGP_CONTAINER_NAME=bgp-containers \
-e "NVKE_E2E_NODE_AGENT_BUNDLE_VOLUME=${bundle_mirror_volume}" \
-e "NVKE_E2E_NODE_AGENT_UPGRADE=${LOCAL_NVKE_E2E_NODE_AGENT_UPGRADE:-false}" \
-e "E2E_BGP_CONTAINER_NAME=${BGP_CONTAINER_NAME:-bgp-containers}" \
${oidc_env[@]+"${oidc_env[@]}"} \
"${runner_name}" "$@"
}
@@ -40,6 +40,7 @@ profilesDir: test/fixtures/profiles
runbooksDir: test/fixtures/runbooks
tenantAccessEnabled: false
nodeAgent:
updateMethod: ""
spireAttestationMethod: tpm
dsxImds:
endpoint: http://169.254.169.254
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Build real agent releases in a private fixture namespace. The failed target
# contains a real binary with the wrong version, so verification must restore it.
set -euo pipefail
repository_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
output_directory="$1"
architecture="$2"
case "${architecture}" in
amd64) bundle_architecture=x86_64 ;;
arm64) bundle_architecture=aarch64 ;;
*) printf 'unsupported architecture: %s\n' "${architecture}" >&2; exit 1 ;;
esac
mkdir -p "${output_directory}/agent-e2e"
for version in v0.1.991 v0.1.992 v0.1.993; do
CGO_ENABLED=0 make -C "${repository_root}/agent" "package-${architecture}" VERSION="${version}"
cp "${repository_root}/agent/release/agent_${version}_${architecture}.tgz" \
"${output_directory}/agent-e2e/agent_${version}.tgz"
done
cp "${output_directory}/agent-e2e/agent_v0.1.993.tgz" "${output_directory}/agent-e2e/repaired.tgz"
cp "${output_directory}/agent-e2e/agent_v0.1.992.tgz" "${output_directory}/agent-e2e/agent_v0.1.993.tgz"
jq --arg architecture "${bundle_architecture}" \
'.agent = {entries: ["0.1.991", "0.1.992", "0.1.993"] | map({version: ., arch: $architecture, path: ("agent-e2e/agent_v" + . + ".tgz")})}' \
"${output_directory}/index.json" >"${output_directory}/index.next.json"
mv "${output_directory}/index.next.json" "${output_directory}/index.json"
@@ -295,3 +295,9 @@ type InstallCNICall struct {
Node db.Node
Request *nvkeproto.InstallCNIRequest
}
// ConvergeNodeAgent implements the agent convergence test surface.
func (f *FakeClient) ConvergeNodeAgent(ctx context.Context, node db.Node, target, _ string) (string, bool, error) {
version, err := f.GetAgentVersion(ctx, node)
return version, version == target || target == "", err
}
+1
View File
@@ -51,6 +51,7 @@ type Client interface {
GetEncryptedObjectsRewriteStatus(ctx context.Context, node db.Node, operationID string) (*nvkeproto.EtcdEncryptionAtRestObjectsRewriteOperation, error)
RemovePlainTextSecondaryEncryptionEntry(ctx context.Context, node db.Node) error
StartKubeVIPRestore(ctx context.Context, node db.Node, operationID string) (*nvkeproto.NodeAgentOperationStatus, error)
ConvergeNodeAgent(ctx context.Context, node db.Node, target, method string) (string, bool, error)
}
type NodeAgentClient struct {
@@ -0,0 +1,125 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package agent
import (
"context"
"encoding/json"
"fmt"
pb "github.com/dsx-ai-factory/nvke/agent/pkg/agent/proto"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
"github.com/dsx-ai-factory/nvke/controller/internal/runbook"
)
// ConvergeNodeAgent executes one durable convergence step with a fresh connection.
func (c *NodeAgentClient) ConvergeNodeAgent(ctx context.Context, node db.Node, target, method string) (string, bool, error) {
observation, err := c.GetKubeadmStatus(ctx, node)
if err != nil {
return "", false, err
}
version := observation.GetAgentVersion()
if method != "apt" && method != "bundle" {
return version, false, fmt.Errorf("node-agent update method must be apt or bundle")
}
// Inspect active status even on a version match. Installation or restoration
// can still be running when a new agent first accepts connections.
conn, cleanup, err := c.getGRPCConnection(ctx, node)
if err != nil {
return version, false, err
}
defer cleanup()
rpc := pb.NewNodeAgentClient(conn)
current, err := rpc.GetNodeAgentUpgradeStatus(ctx, &pb.GetNodeAgentUpgradeStatusRequest{})
op := current.GetOperation()
upgradeActive := op.GetPhase() == pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_PENDING ||
op.GetPhase() == pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_RUNNING
// No installation is active, and no version change is needed.
if err == nil && !upgradeActive && (target == "" || version == target) {
return version, true, nil
}
// Start the desired installation, including a retry after failure.
if err == nil && !upgradeActive {
err := startNodeAgentUpgrade(ctx, rpc, &pb.StartNodeAgentUpgradeRequest{
TargetVersion: target,
Method: upgradeMethodFromName(method),
})
return version, false, err
}
// Keep the accepted installation running until it finishes.
if err == nil && upgradeActive {
if target != "" && op.GetTargetVersion() != target {
return version, false, fmt.Errorf("another node-agent target is still active")
}
err := startNodeAgentUpgrade(ctx, rpc, &pb.StartNodeAgentUpgradeRequest{
TargetVersion: op.GetTargetVersion(),
Method: op.GetMethod(),
})
return version, false, err
}
// Older agents use the bootstrap script.
if status.Code(err) == codes.Unimplemented {
return c.convergeNodeAgentFallback(ctx, node, target, method, version)
}
return version, false, fmt.Errorf("reading node-agent upgrade status: %w", err)
}
// startNodeAgentUpgrade separates request errors from installation failures.
func startNodeAgentUpgrade(ctx context.Context, rpc pb.NodeAgentClient, request *pb.StartNodeAgentUpgradeRequest) error {
response, err := rpc.StartNodeAgentUpgrade(ctx, request)
if err != nil {
return fmt.Errorf("sending node-agent upgrade request: %w", err)
}
op := response.GetOperation()
switch op.GetPhase() {
case pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_PENDING,
pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_RUNNING,
pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_SUCCEEDED:
return nil
case pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_RESTORED,
pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_NOT_RESTORED:
return fmt.Errorf("node-agent installation failed (%s): %s", op.GetPhase(), op.GetErrorMessage())
case pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_UNSPECIFIED:
}
return fmt.Errorf("unexpected node-agent upgrade phase: %s", op.GetPhase())
}
func (c *NodeAgentClient) convergeNodeAgentFallback(ctx context.Context, node db.Node, target, method, version string) (string, bool, error) {
script, err := runbook.Script("", "node-agent-upgrade")
if err != nil {
return version, false, err
}
response, err := c.ExecuteScript(ctx, node, "node-agent-upgrade", script, []string{target, method, version})
if err != nil {
return version, false, err
}
if response.GetExitCode() != 0 {
return version, false, fmt.Errorf("node-agent upgrade fallback failed: %s", response.GetErrorMessage())
}
var result struct {
Phase string `json:"phase"`
ErrorMessage string `json:"errorMessage"`
}
if err := json.Unmarshal([]byte(response.GetOutput()), &result); err != nil {
return version, false, fmt.Errorf("reading fallback upgrade status: %w", err)
}
if result.ErrorMessage != "" {
return version, false, fmt.Errorf("node-agent upgrade: %s", result.ErrorMessage)
}
return version, (target == "" || version == target) && result.Phase == "Succeeded", nil
}
func upgradeMethodFromName(method string) pb.NodeAgentUpgradeMethod {
if method == "bundle" {
return pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_BUNDLE
}
return pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT
}
@@ -0,0 +1,267 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package agent
import (
"context"
"fmt"
"net"
"sync"
"testing"
pb "github.com/dsx-ai-factory/nvke/agent/pkg/agent/proto"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/dsx-ai-factory/nvke/controller/internal/config"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
)
type upgradeRPCServer struct {
pb.UnimplementedNodeAgentServer
mu sync.Mutex
version string
typed bool
operation *pb.NodeAgentUpgradeOperation
starts int
script *pb.ExecuteScriptRequest
fallback string
statusError error
startError error
startOperation *pb.NodeAgentUpgradeOperation
}
func (s *upgradeRPCServer) GetKubeadmStatus(context.Context, *pb.KubeadmStatusRequest) (*pb.KubeadmStatusResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
return &pb.KubeadmStatusResponse{AgentVersion: s.version}, nil
}
func (s *upgradeRPCServer) GetNodeAgentUpgradeStatus(_ context.Context, _ *pb.GetNodeAgentUpgradeStatusRequest) (*pb.GetNodeAgentUpgradeStatusResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.statusError != nil {
return nil, s.statusError
}
if !s.typed {
return nil, status.Error(codes.Unimplemented, "upgrade RPC unavailable")
}
if s.operation == nil {
return &pb.GetNodeAgentUpgradeStatusResponse{}, nil
}
operation := proto.Clone(s.operation).(*pb.NodeAgentUpgradeOperation)
return &pb.GetNodeAgentUpgradeStatusResponse{Operation: operation}, nil
}
func (s *upgradeRPCServer) StartNodeAgentUpgrade(_ context.Context, request *pb.StartNodeAgentUpgradeRequest) (*pb.StartNodeAgentUpgradeResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.starts++
if s.startError != nil {
return nil, s.startError
}
if s.startOperation != nil {
s.operation = proto.Clone(s.startOperation).(*pb.NodeAgentUpgradeOperation)
return &pb.StartNodeAgentUpgradeResponse{Operation: s.operation}, nil
}
s.operation = &pb.NodeAgentUpgradeOperation{TargetVersion: request.GetTargetVersion(), Method: request.GetMethod(), Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_PENDING}
return &pb.StartNodeAgentUpgradeResponse{Operation: s.operation}, nil
}
func (s *upgradeRPCServer) ExecuteScript(_ context.Context, request *pb.ExecuteScriptRequest) (*pb.ExecuteScriptResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.script = request
return &pb.ExecuteScriptResponse{Output: s.fallback}, nil
}
func upgradeTestClient(t *testing.T, server *upgradeRPCServer) (*NodeAgentClient, db.Node) {
t.Helper()
listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
require.NoError(t, err)
rpc := grpc.NewServer()
pb.RegisterNodeAgentServer(rpc, server)
go func() { _ = rpc.Serve(listener) }()
t.Cleanup(rpc.Stop)
host, port, err := net.SplitHostPort(listener.Addr().String())
require.NoError(t, err)
transport := &Transport{cfg: config.Config{NodeAgent: config.NodeAgentConfig{Port: port}}}
return NewClientWithTransport(transport), db.Node{IP: host}
}
func TestConvergeAgentUsesTypedRequests(t *testing.T) {
server := &upgradeRPCServer{version: "v0.1.2", typed: true}
client, node := upgradeTestClient(t, server)
version, done, err := client.ConvergeNodeAgent(context.Background(), node, "v0.1.1", "apt")
require.NoError(t, err)
require.False(t, done)
require.Equal(t, "v0.1.2", version)
require.Equal(t, 1, server.starts)
server.mu.Lock()
server.operation.Phase = pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_RESTORED
server.operation.ErrorMessage = "previous installation failed"
server.mu.Unlock()
_, done, err = client.ConvergeNodeAgent(context.Background(), node, "v0.1.1", "apt")
require.NoError(t, err)
require.False(t, done)
require.Equal(t, 2, server.starts)
server.mu.Lock()
server.version = "v0.1.1"
server.operation.Phase = pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_RUNNING
server.mu.Unlock()
_, done, err = client.ConvergeNodeAgent(context.Background(), node, "v0.1.1", "apt")
require.NoError(t, err)
require.False(t, done, "matching version alone must not complete an active installer")
server.mu.Lock()
server.operation.Phase = pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_SUCCEEDED
server.mu.Unlock()
_, done, err = client.ConvergeNodeAgent(context.Background(), node, "v0.1.1", "apt")
require.NoError(t, err)
require.True(t, done)
}
func TestConvergeAgentFallbackUsesDurableStatusAndExactObservation(t *testing.T) {
server := &upgradeRPCServer{version: "v0.1.2", fallback: `{"phase":"Succeeded","errorMessage":""}`}
client, node := upgradeTestClient(t, server)
_, done, err := client.ConvergeNodeAgent(context.Background(), node, "v0.1.1", "bundle")
require.NoError(t, err)
require.False(t, done)
require.Zero(t, server.starts)
require.Contains(t, server.script.GetScriptContents(), "systemd-run")
require.False(t, server.script.GetAsync())
require.Equal(t, []string{"v0.1.1", "bundle", "v0.1.2"}, server.script.GetArgs())
server.mu.Lock()
server.version = "v0.1.1"
server.fallback = `{"phase":"Running","errorMessage":""}`
server.mu.Unlock()
_, done, err = client.ConvergeNodeAgent(context.Background(), node, "v0.1.1", "bundle")
require.NoError(t, err)
require.False(t, done)
server.mu.Lock()
server.fallback = `{"phase":"Succeeded","errorMessage":""}`
server.mu.Unlock()
_, done, err = client.ConvergeNodeAgent(context.Background(), node, "v0.1.1", "bundle")
require.NoError(t, err)
require.True(t, done)
}
func TestConvergeAgentDrainDoesNotStartNewTarget(t *testing.T) {
for _, typed := range []bool{true, false} {
t.Run(fmt.Sprint(typed), func(t *testing.T) {
server := &upgradeRPCServer{version: "v0.1.1", typed: typed, fallback: `{"phase":"Succeeded","errorMessage":""}`}
client, node := upgradeTestClient(t, server)
_, done, err := client.ConvergeNodeAgent(context.Background(), node, "", "apt")
require.NoError(t, err)
require.True(t, done)
require.Zero(t, server.starts)
})
}
}
func TestConvergeAgentDoesNotCarryFailureAcrossTargets(t *testing.T) {
server := &upgradeRPCServer{version: "v0.1.1", typed: true, operation: &pb.NodeAgentUpgradeOperation{TargetVersion: "v0.1.2", Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT, Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_RESTORED, ErrorMessage: "old artifact missing"}}
client, node := upgradeTestClient(t, server)
_, done, err := client.ConvergeNodeAgent(context.Background(), node, "v0.1.3", "apt")
require.NoError(t, err)
require.False(t, done)
require.Equal(t, 1, server.starts)
require.Equal(t, "v0.1.3", server.operation.GetTargetVersion())
}
func TestConvergeAgentDistinguishesProgressAndFailures(t *testing.T) {
for _, active := range []bool{false, true} {
for _, test := range []struct {
name string
startOperation *pb.NodeAgentUpgradeOperation
startError error
wantError string
wantCode codes.Code
}{
{
name: "accepted request is in progress",
},
{
name: "running response ignores an earlier error",
startOperation: &pb.NodeAgentUpgradeOperation{Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_RUNNING, ErrorMessage: "previous failure"},
},
{
name: "RPC failure preserves its status code",
startError: status.Error(codes.Unavailable, "agent unreachable"),
wantError: "sending node-agent upgrade request:",
wantCode: codes.Unavailable,
},
{
name: "failed installation with restoration",
startOperation: &pb.NodeAgentUpgradeOperation{Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_RESTORED, ErrorMessage: "artifact missing"},
wantError: "node-agent installation failed (NODE_AGENT_UPGRADE_PHASE_FAILED_RESTORED): artifact missing",
},
{
name: "failed installation without a message",
startOperation: &pb.NodeAgentUpgradeOperation{Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_FAILED_NOT_RESTORED},
wantError: "node-agent installation failed (NODE_AGENT_UPGRADE_PHASE_FAILED_NOT_RESTORED)",
},
{
name: "missing response phase cannot imply acceptance",
startOperation: &pb.NodeAgentUpgradeOperation{},
wantError: "unexpected node-agent upgrade phase:",
},
} {
t.Run(fmt.Sprintf("active_%t/%s", active, test.name), func(t *testing.T) {
server := &upgradeRPCServer{version: "v0.1.1", typed: true, startError: test.startError, startOperation: test.startOperation}
if active {
server.operation = &pb.NodeAgentUpgradeOperation{TargetVersion: "v0.1.2", Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT, Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_RUNNING}
}
client, node := upgradeTestClient(t, server)
version, done, err := client.ConvergeNodeAgent(t.Context(), node, "v0.1.2", "apt")
if test.wantError == "" {
require.NoError(t, err)
} else {
require.ErrorContains(t, err, test.wantError)
}
if test.wantCode != codes.OK {
require.Equal(t, test.wantCode, status.Code(err))
}
require.Equal(t, "v0.1.1", version)
require.False(t, done)
require.Equal(t, 1, server.starts)
})
}
}
}
func TestConvergeAgentMatchingVersionRequiresNoActiveInstallation(t *testing.T) {
for _, test := range []struct {
name string
operation *pb.NodeAgentUpgradeOperation
statusError error
wantDone bool
wantStarts int
wantCode codes.Code
}{
{name: "no upgrade record", wantDone: true},
{name: "installation finished", operation: &pb.NodeAgentUpgradeOperation{Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_SUCCEEDED}, wantDone: true},
{name: "installation still running", operation: &pb.NodeAgentUpgradeOperation{TargetVersion: "v0.1.2", Method: pb.NodeAgentUpgradeMethod_NODE_AGENT_UPGRADE_METHOD_APT, Phase: pb.NodeAgentUpgradePhase_NODE_AGENT_UPGRADE_PHASE_RUNNING}, wantStarts: 1},
{name: "status unavailable", statusError: status.Error(codes.Unavailable, "status unreachable"), wantCode: codes.Unavailable},
{name: "invalid request is not an unsupported RPC", statusError: status.Error(codes.InvalidArgument, "invalid request"), wantCode: codes.InvalidArgument},
} {
t.Run(test.name, func(t *testing.T) {
server := &upgradeRPCServer{version: "v0.1.2", typed: true, operation: test.operation, statusError: test.statusError}
client, node := upgradeTestClient(t, server)
_, done, err := client.ConvergeNodeAgent(t.Context(), node, "v0.1.2", "apt")
if test.statusError != nil {
require.ErrorContains(t, err, "reading node-agent upgrade status:")
require.Equal(t, test.wantCode, status.Code(err))
} else {
require.NoError(t, err)
}
require.Equal(t, test.wantDone, done)
require.Equal(t, test.wantStarts, server.starts)
})
}
}
+3
View File
@@ -98,6 +98,9 @@ type NodeAgentConfig struct {
// TLSJWT contains TLS/JWT transport settings.
TLSJWT TLSJWTConfig
// UpdateMethod selects apt or bundle installation for opted-in clusters.
UpdateMethod string `controllerconfig:"nodeAgent.updateMethod"`
}
// Config is the controller's configuration. A field with an env tag comes from
@@ -58,6 +58,7 @@ func (c *Config) ApplyTo(cfg *config.Config) {
cfg.RunbooksDir = c.RunbooksDir
cfg.TenantAccessEnabled = c.TenantAccessEnabled
cfg.NodeAgent.UpdateMethod = c.NodeAgent.UpdateMethod
cfg.NodeAgent.SpireAttestationMethod = config.SpireAttestationMethod(c.NodeAgent.SpireAttestationMethod)
cfg.NodeAgent.DSXImds.Endpoint = c.NodeAgent.DSXImds.Endpoint
cfg.NodeAgent.DSXImds.PluginChecksum = c.NodeAgent.DSXImds.PluginChecksum
@@ -87,6 +87,7 @@ type NodeAgentConfig struct {
DSXImds DSXImdsConfig `json:"dsxImds"`
TLSJWT TLSJWTConfig `json:"tlsJWT"`
ExternalMTLSEnabled bool `json:"externalMTLSEnabled"`
UpdateMethod string `json:"updateMethod"`
}
// DSXImdsConfig mirrors config.DSXImdsConfig.
@@ -353,6 +354,9 @@ func validateSupportedInfraProviders(providers []string) error {
// dsxImds, and TLS/JWT all read spire.spiffeEnabled, which lives outside this
// struct, so it is passed in.
func (n *NodeAgentConfig) validate(spiffeEnabled bool) error {
if n.UpdateMethod != "" && n.UpdateMethod != "apt" && n.UpdateMethod != "bundle" {
return fmt.Errorf("updateMethod must be apt or bundle")
}
switch n.SpireAttestationMethod {
case SpireAttestationMethodTPM:
case SpireAttestationMethodJoinToken:
@@ -0,0 +1,268 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package controlplane
// Agent upgrade controller:
// 1. Leave converged nodes unchanged. Select one eligible control-plane node.
// 2. Request installation through the agent RPC. The independent updater does
// the installation; this controller does not wait for it to finish.
// 3. Check progress on later reconciliations. Retry failures on the same node.
// 4. Leave accepted installation alone during deletion or replacement. Do not
// send another installation request, and do not block teardown.
// Certificate renewal keeps its Temporal workflow. Actual renewal and agent
// installation cannot overlap; a due or queued renewal does not block upgrades.
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
pb "github.com/dsx-ai-factory/nvke/agent/pkg/agent/proto"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
)
const (
agentUpgradeRetryDelay = 30 * time.Second
)
func (c *Controller) reconcileNodeAgentUpgrade(ctx context.Context, cluster db.Cluster) (reconcile.Result, error) {
if !c.cfg.UseControlPlaneControllerForControlPlane() || cluster.ID == uuid.Nil || cluster.Conditions.Deleting.Status == db.ConditionStatusTrue ||
(cluster.ControlPlaneConfig.NodeAgentConfig.Version == "" && cluster.NodeAgentUpgrade == nil && cluster.CertificateRenewal == nil) {
return reconcile.Result{}, nil
}
if cluster.CertificateRenewal != nil {
running, err := c.checkCertificateRenewal(ctx, cluster)
if running || err != nil {
return reconcile.Result{RequeueAfter: 10 * time.Second}, err
}
}
selected, err := c.selectAgentUpgrade(ctx, cluster)
if err != nil {
return reconcile.Result{}, err
}
if selected == nil {
return reconcile.Result{RequeueAfter: agentUpgradeRetryDelay}, nil
}
if time.Now().Before(selected.RetryAt) {
return reconcile.Result{RequeueAfter: time.Until(selected.RetryAt)}, nil
}
if err := c.runNodeAgentUpgrade(ctx, cluster.ID, *selected); err != nil {
return reconcile.Result{}, err
}
return reconcile.Result{RequeueAfter: 10 * time.Second}, nil
}
// selectAgentUpgrade keeps accepted work on its node. Only selection of new
// work needs a transaction; status polling does not reserve it again.
func (c *Controller) selectAgentUpgrade(ctx context.Context, cluster db.Cluster) (*db.NodeAgentUpgrade, error) {
if active := cluster.NodeAgentUpgrade; active != nil {
current := *active
return &current, nil
}
var selected *db.NodeAgentUpgrade
err := c.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
locked, err := tx.GetClusterForUpdate(ctx, cluster.ID)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil {
return err
}
if locked.Conditions.Deleting.Status == db.ConditionStatusTrue || locked.CertificateRenewal != nil {
return nil
}
if active := locked.NodeAgentUpgrade; active != nil {
current := *active
selected = &current
return nil
}
target := locked.ControlPlaneConfig.NodeAgentConfig.Version
if target == "" || locked.Conditions.UpdateInProgress != nil ||
locked.Conditions.ControlPlaneUpgrading.Status == db.ConditionStatusTrue || locked.Conditions.CPNodesRecycling.Status == db.ConditionStatusTrue {
return nil
}
controlPlane := true
nodes, err := tx.ListNodes(ctx, db.NodeFilters{ClusterID: &cluster.ID, ControlPlane: &controlPlane})
if err != nil {
return err
}
for _, node := range nodes {
if agentUpgradeRemovalRequested(node) || node.Conditions.ControlPlaneRolloutRequired.Status == db.ConditionStatusTrue ||
(node.Conditions.ReadyToJoin.Status == db.ConditionStatusTrue && node.Conditions.Joined.Status != db.ConditionStatusTrue) {
return nil
}
}
for _, node := range nodes {
if agentUpgradeEligible(node) && node.AgentVersion != target {
selected = &db.NodeAgentUpgrade{Source: "background", NodeID: node.ID, TargetVersion: target, Method: c.cfg.NodeAgent.UpdateMethod, Phase: "Pending"}
locked.NodeAgentUpgrade = selected
_, err = tx.UpdateCluster(ctx, &locked)
return err
}
}
return nil
})
return selected, err
}
func (c *Controller) runNodeAgentUpgrade(ctx context.Context, clusterID uuid.UUID, selected db.NodeAgentUpgrade) error {
cluster, err := c.db.GetCluster(ctx, clusterID)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil {
return err
}
if !sameAgentUpgrade(cluster.NodeAgentUpgrade, selected) || cluster.CertificateRenewal != nil || cluster.Conditions.Deleting.Status == db.ConditionStatusTrue {
return nil
}
node, err := c.db.GetNode(ctx, selected.NodeID)
if errors.Is(err, db.ErrNotFound) {
return c.saveAgentUpgradeProgress(ctx, clusterID, selected, "", true, nil)
}
if err != nil {
return err
}
if agentUpgradeRemovalRequested(node) || selected.Source == db.NodeAgentUpgradeSourceLifecycle {
return nil
}
if c.nodeAgentClient == nil {
return fmt.Errorf("node-agent client is required for agent convergence")
}
// The accepted target stays unchanged. After completion, the next reconcile
// reads the current desired version instead of changing an active request.
callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
version, done, callErr := c.nodeAgentClient.ConvergeNodeAgent(callCtx, node, selected.TargetVersion, selected.Method)
cancel()
if done && callErr == nil && version != selected.TargetVersion {
callErr = fmt.Errorf("node agent reports %q, expected %q", version, selected.TargetVersion)
}
return c.saveAgentUpgradeProgress(ctx, clusterID, selected, version, done, callErr)
}
func (c *Controller) saveAgentUpgradeProgress(ctx context.Context, clusterID uuid.UUID, selected db.NodeAgentUpgrade, version string, done bool, callErr error) error {
return c.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
cluster, err := tx.GetClusterForUpdate(ctx, clusterID)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil {
return err
}
if !sameAgentUpgrade(cluster.NodeAgentUpgrade, selected) {
return nil
}
// Re-read the node so a status response cannot overwrite deletion state.
node, err := tx.GetNodeForUpdate(ctx, selected.NodeID)
switch {
case errors.Is(err, db.ErrNotFound):
cluster.NodeAgentUpgrade = nil
case err != nil:
return err
default:
if version != "" {
node.AgentVersion = version
if _, err := tx.UpdateNode(ctx, &node); err != nil {
return err
}
}
active := cluster.NodeAgentUpgrade
active.Phase = "Running"
active.RetryAt = time.Time{}
if callErr != nil {
active.ErrorMessage = callErr.Error()
active.RetryAt = time.Now().Add(agentUpgradeRetryDelay)
}
if done && callErr == nil {
cluster.NodeAgentUpgrade = nil
}
}
_, err = tx.UpdateCluster(ctx, &cluster)
return err
})
}
func sameAgentUpgrade(active *db.NodeAgentUpgrade, selected db.NodeAgentUpgrade) bool {
return active != nil && active.NodeID == selected.NodeID && active.TargetVersion == selected.TargetVersion && active.Method == selected.Method && active.Source == selected.Source
}
func agentUpgradeEligible(node db.Node) bool {
return node.IsManagedByControlPlaneController() &&
node.Conditions.Joined.Status == db.ConditionStatusTrue &&
node.Conditions.Provisioned.Status == db.ConditionStatusTrue &&
node.Conditions.KubernetesReady.Status == db.ConditionStatusTrue &&
node.Conditions.NodeAgentReady.Status == db.ConditionStatusTrue &&
!agentUpgradeRemovalRequested(node) && node.Conditions.Rebooting.Status != db.ConditionStatusTrue
}
func agentUpgradeRemovalRequested(node db.Node) bool {
return node.Conditions.DeleteRequested.Status == db.ConditionStatusTrue || node.Conditions.Deleting.Status == db.ConditionStatusTrue ||
node.Conditions.MarkedForRepair.Status == db.ConditionStatusTrue || node.Conditions.MarkedForRecycling.Status == db.ConditionStatusTrue
}
func agentUpgradeBlocksNodeWork(cluster db.Cluster, nodes []db.Node) bool {
if cluster.NodeAgentUpgrade == nil {
return false
}
for _, node := range nodes {
if node.ID == cluster.NodeAgentUpgrade.NodeID {
return !agentUpgradeRemovalRequested(node)
}
}
return false
}
// checkCertificateRenewal reads actual agent work, not Temporal or queue state.
// This also recovers an accepted renewal if its activity stopped polling it.
func (c *Controller) checkCertificateRenewal(ctx context.Context, cluster db.Cluster) (bool, error) {
if c.nodeAgentClient == nil {
return true, fmt.Errorf("node-agent client is required for agent convergence")
}
active := *cluster.CertificateRenewal
node, err := c.db.GetNode(ctx, active.NodeID)
if !errors.Is(err, db.ErrNotFound) {
if err != nil {
return true, err
}
callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
response, callErr := c.nodeAgentClient.GetKubernetesCertificateRenewalStatus(callCtx, node, &pb.GetKubernetesCertificateRenewalStatusRequest{OperationId: active.OperationID})
cancel()
if status.Code(callErr) == codes.Unimplemented {
// The existing legacy activity releases its record when its script ends.
return true, nil
}
if callErr != nil {
return true, callErr
}
switch response.GetOperation().GetOperation().GetPhase() {
case pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_SUCCEEDED, pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_FAILED:
case pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_RUNNING:
return true, nil
case pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_UNSPECIFIED:
return true, fmt.Errorf("certificate renewal status is empty")
default:
return true, fmt.Errorf("certificate renewal status is unknown")
}
}
err = c.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
locked, err := tx.GetClusterForUpdate(ctx, cluster.ID)
if err != nil {
return err
}
if locked.CertificateRenewal != nil && *locked.CertificateRenewal == active {
locked.CertificateRenewal = nil
_, err = tx.UpdateCluster(ctx, &locked)
}
return err
})
return false, err
}
@@ -0,0 +1,363 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package controlplane
import (
"context"
"errors"
"log/slog"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/dsx-ai-factory/nvke/agent/pkg/agent/proto"
"github.com/dsx-ai-factory/nvke/controller/internal/agent/agenttest"
"github.com/dsx-ai-factory/nvke/controller/internal/config"
"github.com/dsx-ai-factory/nvke/controller/internal/controllers/dbreconcile/dbwrapper"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
)
type upgradeDatabase struct {
db.DB
mu sync.Mutex
cluster db.Cluster
nodes map[uuid.UUID]db.Node
}
func (d *upgradeDatabase) RunInTx(ctx context.Context, fn func(context.Context, db.Tx) error) error {
d.mu.Lock()
defer d.mu.Unlock()
return fn(ctx, upgradeTx{d})
}
// The transaction view reads under the lock already held by RunInTx.
// The wrapper reads previous values before writing, so it also uses this view.
type upgradeTx struct{ *upgradeDatabase }
func (tx upgradeTx) GetCluster(ctx context.Context, id uuid.UUID) (db.Cluster, error) {
return tx.GetClusterForUpdate(ctx, id)
}
func (tx upgradeTx) GetNode(ctx context.Context, id uuid.UUID) (db.Node, error) {
return tx.GetNodeForUpdate(ctx, id)
}
func (d *upgradeDatabase) GetCluster(ctx context.Context, id uuid.UUID) (db.Cluster, error) {
d.mu.Lock()
defer d.mu.Unlock()
return d.GetClusterForUpdate(ctx, id)
}
func (d *upgradeDatabase) GetClusterForUpdate(context.Context, uuid.UUID) (db.Cluster, error) {
cluster := d.cluster
if cluster.NodeAgentUpgrade != nil {
current := *cluster.NodeAgentUpgrade
cluster.NodeAgentUpgrade = &current
}
if cluster.CertificateRenewal != nil {
current := *cluster.CertificateRenewal
cluster.CertificateRenewal = &current
}
return cluster, nil
}
func (d *upgradeDatabase) UpdateCluster(_ context.Context, cluster *db.Cluster) (db.Cluster, error) {
d.cluster = *cluster
return *cluster, nil
}
func (d *upgradeDatabase) ListNodes(context.Context, db.NodeFilters) ([]db.Node, error) {
nodes := make([]db.Node, 0, len(d.nodes))
for _, node := range d.nodes {
nodes = append(nodes, node)
}
slices.SortFunc(nodes, func(a, b db.Node) int { return strings.Compare(a.ID.String(), b.ID.String()) })
return nodes, nil
}
func (d *upgradeDatabase) GetNode(ctx context.Context, id uuid.UUID) (db.Node, error) {
d.mu.Lock()
defer d.mu.Unlock()
return d.GetNodeForUpdate(ctx, id)
}
func (d *upgradeDatabase) GetNodeForUpdate(_ context.Context, id uuid.UUID) (db.Node, error) {
node, ok := d.nodes[id]
if !ok {
return db.Node{}, db.ErrNotFound
}
return node, nil
}
func (d *upgradeDatabase) UpdateNode(_ context.Context, node *db.Node) (db.Node, error) {
d.nodes[node.ID] = *node
return *node, nil
}
type convergenceClient struct {
*agenttest.FakeClient
fn func(db.Node, string) (string, bool, error)
}
func (c convergenceClient) ConvergeNodeAgent(_ context.Context, node db.Node, target, _ string) (string, bool, error) {
return c.fn(node, target)
}
func healthyAgentNode() db.Node {
return db.Node{ID: uuid.New(), ControlPlane: true, AgentVersion: "v0.1.1", Conditions: db.NodeConditions{
Joined: db.NewCondition(true, ""), Provisioned: db.NewCondition(true, ""), KubernetesReady: db.NewCondition(true, ""), NodeAgentReady: db.NewCondition(true, ""),
}}
}
func agentUpgradeTestController(nodes ...db.Node) (*Controller, *upgradeDatabase) {
cluster := db.Cluster{ID: uuid.New(), ControlPlaneConfig: db.ControlPlaneConfig{ControlPlaneConfigSpec: db.ControlPlaneConfigSpec{NodeAgentConfig: db.NodeAgentConfig{Version: "v0.1.2"}}}}
database := &upgradeDatabase{cluster: cluster, nodes: map[uuid.UUID]db.Node{}}
for _, node := range nodes {
database.nodes[node.ID] = node
}
return &Controller{cfg: config.Config{ProvisionControlPlaneWithControlPlaneController: true, NodeAgent: config.NodeAgentConfig{UpdateMethod: "apt"}}, db: dbwrapper.New(database, slog.Default())}, database
}
func TestAgentUpgradeRetriesOneNodeAndAppliesLaterDesiredVersion(t *testing.T) {
first, second := healthyAgentNode(), healthyAgentNode()
first.ID = uuid.MustParse("00000000-0000-0000-0000-000000000001")
second.ID = uuid.MustParse("00000000-0000-0000-0000-000000000002")
controller, database := agentUpgradeTestController(first, second)
controller.nodeAgentClient = convergenceClient{fn: func(node db.Node, target string) (string, bool, error) {
require.Equal(t, first.ID, node.ID)
require.Equal(t, "v0.1.2", target)
return "v0.1.1", false, errors.New("artifact missing")
}}
for range 3 {
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Equal(t, first.ID, database.cluster.NodeAgentUpgrade.NodeID)
require.Equal(t, "Running", database.cluster.NodeAgentUpgrade.Phase)
require.Equal(t, "artifact missing", database.cluster.NodeAgentUpgrade.ErrorMessage)
require.True(t, database.cluster.NodeAgentUpgrade.RetryAt.After(time.Now()))
database.cluster.NodeAgentUpgrade.RetryAt = time.Time{}
}
database.cluster.ControlPlaneConfig.NodeAgentConfig.Version = "v0.1.3"
controller.nodeAgentClient = convergenceClient{fn: func(node db.Node, target string) (string, bool, error) {
require.Equal(t, first.ID, node.ID)
require.Equal(t, "v0.1.2", target, "finish the accepted target without rewriting it")
return target, true, nil
}}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Nil(t, database.cluster.NodeAgentUpgrade)
require.Equal(t, "v0.1.2", database.nodes[first.ID].AgentVersion)
controller.nodeAgentClient = convergenceClient{fn: func(node db.Node, target string) (string, bool, error) {
require.Equal(t, first.ID, node.ID)
require.Equal(t, "v0.1.3", target)
return target, true, nil
}}
_, err = controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Nil(t, database.cluster.NodeAgentUpgrade)
require.Equal(t, "v0.1.3", database.nodes[first.ID].AgentVersion)
}
func TestAgentUpgradeNoChangeAndScope(t *testing.T) {
for _, test := range []struct {
name string
change func(*db.Node)
}{
{"already converged", func(n *db.Node) { n.AgentVersion = "v0.1.2" }},
{"worker", func(n *db.Node) { n.ControlPlane = false }},
{"pool managed", func(n *db.Node) { n.NodePoolID = uuid.New() }},
{"not joined", func(n *db.Node) { n.Conditions.Joined = db.NewCondition(false, "") }},
{"not provisioned", func(n *db.Node) { n.Conditions.Provisioned = db.NewCondition(false, "") }},
{"not ready", func(n *db.Node) { n.Conditions.KubernetesReady = db.NewCondition(false, "") }},
{"deleting", func(n *db.Node) { n.Conditions.Deleting = db.NewCondition(true, "") }},
} {
t.Run(test.name, func(t *testing.T) {
node := healthyAgentNode()
test.change(&node)
controller, database := agentUpgradeTestController(node)
controller.nodeAgentClient = convergenceClient{fn: func(db.Node, string) (string, bool, error) {
t.Fatal("installation must not start")
return "", false, nil
}}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Nil(t, database.cluster.NodeAgentUpgrade)
})
}
}
func TestDueOrQueuedRenewalDoesNotBlockAgentUpgrade(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
past := time.Now().Add(-time.Hour)
database.cluster.NextCertRenewalDue = &past
controller.cfg.CertRenewalControllerEnabled = true
calls := 0
controller.nodeAgentClient = convergenceClient{fn: func(_ db.Node, target string) (string, bool, error) { calls++; return target, true, nil }}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Equal(t, 1, calls)
}
func TestDeletionAndReplacementLeaveAcceptedUpdaterAlone(t *testing.T) {
for _, test := range []struct {
name string
request func(*db.Node)
}{
{"requested deletion", func(n *db.Node) { n.Conditions.DeleteRequested = db.NewCondition(true, "") }},
{"deletion", func(n *db.Node) { n.Conditions.Deleting = db.NewCondition(true, "") }},
{"repair", func(n *db.Node) { n.Conditions.MarkedForRepair = db.NewCondition(true, "") }},
{"replacement", func(n *db.Node) { n.Conditions.MarkedForRecycling = db.NewCondition(true, "") }},
} {
t.Run(test.name, func(t *testing.T) {
node := healthyAgentNode()
test.request(&node)
controller, database := agentUpgradeTestController(node)
selected := db.NodeAgentUpgrade{Source: "background", NodeID: node.ID, TargetVersion: "v0.1.2", Method: "apt", Phase: "Running"}
database.cluster.NodeAgentUpgrade = &selected
controller.nodeAgentClient = convergenceClient{fn: func(db.Node, string) (string, bool, error) {
t.Fatal("deletion must not restart or wait for installation")
return "", false, nil
}}
require.False(t, agentUpgradeBlocksNodeWork(database.cluster, []db.Node{node}))
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Equal(t, selected, *database.cluster.NodeAgentUpgrade, "leave the accepted request alone")
})
}
}
func TestAgentRPCDoesNotHoldDeletionTransaction(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
controller.nodeAgentClient = convergenceClient{fn: func(_ db.Node, target string) (string, bool, error) {
finished := make(chan error, 1)
go func() {
finished <- database.RunInTx(t.Context(), func(context.Context, db.Tx) error {
updated := database.nodes[node.ID]
updated.Conditions.Deleting = db.NewCondition(true, "operator requested deletion")
database.nodes[node.ID] = updated
return nil
})
}()
select {
case err := <-finished:
require.NoError(t, err)
case <-time.After(time.Second):
t.Fatal("the agent RPC holds the deletion transaction")
}
return target, false, nil
}}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Equal(t, db.ConditionStatusTrue, database.nodes[node.ID].Conditions.Deleting.Status, "status must not overwrite deletion state")
}
func TestAgentUpgradeCannotCompleteOnWrongVersion(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
controller.nodeAgentClient = convergenceClient{fn: func(db.Node, string) (string, bool, error) { return "v0.1.1", true, nil }}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.NotNil(t, database.cluster.NodeAgentUpgrade)
require.Contains(t, database.cluster.NodeAgentUpgrade.ErrorMessage, "expected")
}
func TestAgentUpgradeDiscardsStaleResponseAndRemovedNode(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
old := db.NodeAgentUpgrade{Source: "background", NodeID: node.ID, TargetVersion: "v0.1.2", Method: "apt", Phase: "Running"}
newer := old
newer.TargetVersion = "v0.1.3"
database.cluster.NodeAgentUpgrade = &newer
controller.nodeAgentClient = convergenceClient{fn: func(db.Node, string) (string, bool, error) {
t.Fatal("stale work must not issue an RPC")
return "", false, nil
}}
require.NoError(t, controller.runNodeAgentUpgrade(t.Context(), database.cluster.ID, old))
require.NoError(t, controller.saveAgentUpgradeProgress(t.Context(), database.cluster.ID, old, "v0.1.2", true, nil))
require.Equal(t, newer, *database.cluster.NodeAgentUpgrade)
delete(database.nodes, node.ID)
require.NoError(t, controller.runNodeAgentUpgrade(t.Context(), database.cluster.ID, newer))
require.Nil(t, database.cluster.NodeAgentUpgrade)
}
func TestRunningRenewalBlocksUpgradeAndRecoversAfterCompletion(t *testing.T) {
for _, phase := range []pb.NodeAgentOperationPhase{pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_RUNNING, pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_SUCCEEDED, pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_FAILED} {
t.Run(phase.String(), func(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
database.cluster.CertificateRenewal = &db.NodeAgentCertificateRenewal{NodeID: node.ID, OperationID: "accepted-renewal"}
calls := 0
fake := &agenttest.FakeClient{GetKubernetesCertificateRenewalHook: func(_ db.Node, req *pb.GetKubernetesCertificateRenewalStatusRequest) (*pb.GetKubernetesCertificateRenewalStatusResponse, error) {
require.Equal(t, "accepted-renewal", req.GetOperationId())
return &pb.GetKubernetesCertificateRenewalStatusResponse{Operation: &pb.KubernetesCertificateRenewalOperation{Operation: &pb.NodeAgentOperationStatus{Phase: phase}}}, nil
}}
controller.nodeAgentClient = convergenceClient{FakeClient: fake, fn: func(_ db.Node, target string) (string, bool, error) { calls++; return target, true, nil }}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
if phase == pb.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_RUNNING {
require.Zero(t, calls)
require.NotNil(t, database.cluster.CertificateRenewal)
} else {
require.Equal(t, 1, calls)
require.Nil(t, database.cluster.CertificateRenewal)
}
})
}
}
func TestRenewalConnectionFailureDoesNotPermitAgentRestart(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
database.cluster.CertificateRenewal = &db.NodeAgentCertificateRenewal{NodeID: node.ID, OperationID: "accepted-renewal"}
controller.nodeAgentClient = convergenceClient{FakeClient: &agenttest.FakeClient{GetKubernetesCertificateRenewalHook: func(db.Node, *pb.GetKubernetesCertificateRenewalStatusRequest) (*pb.GetKubernetesCertificateRenewalStatusResponse, error) {
return nil, status.Error(codes.Unavailable, "renewal still owns the node")
}}, fn: func(db.Node, string) (string, bool, error) {
t.Fatal("unknown renewal status must not permit installation")
return "", false, nil
}}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.Error(t, err)
require.NotNil(t, database.cluster.CertificateRenewal)
}
func TestAgentUpgradeAndDowngradeUseTheSameReconciliation(t *testing.T) {
for _, target := range []string{"v0.1.2", "v0.1.0"} {
t.Run(target, func(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
database.cluster.ControlPlaneConfig.NodeAgentConfig.Version = target
controller.nodeAgentClient = convergenceClient{fn: func(_ db.Node, requested string) (string, bool, error) {
require.Equal(t, target, requested)
return requested, true, nil
}}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Equal(t, target, database.nodes[node.ID].AgentVersion)
require.Nil(t, database.cluster.NodeAgentUpgrade)
})
}
}
func TestRemovedLifecycleNodeReleasesUpgradeSelection(t *testing.T) {
node := healthyAgentNode()
controller, database := agentUpgradeTestController(node)
database.cluster.NodeAgentUpgrade = &db.NodeAgentUpgrade{NodeID: uuid.New(), Source: db.NodeAgentUpgradeSourceLifecycle, TargetVersion: "v0.1.2", Method: "apt", Phase: "Running"}
controller.nodeAgentClient = convergenceClient{fn: func(db.Node, string) (string, bool, error) {
t.Fatal("the removed lifecycle node must receive no installation request")
return "", false, nil
}}
_, err := controller.reconcileNodeAgentUpgrade(t.Context(), database.cluster)
require.NoError(t, err)
require.Nil(t, database.cluster.NodeAgentUpgrade)
}
@@ -17,6 +17,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/dsx-ai-factory/nvke/controller/internal/agent"
"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"
@@ -33,6 +34,7 @@ type Controller struct {
controllerTemporalClient client.Client
k8sClient ctrlclient.Client
k8sReader ctrlclient.Reader
nodeAgentClient agent.Client
}
// NewController creates a new control plane Controller.
@@ -43,6 +45,7 @@ func NewController(
controllerTemporalClient client.Client,
k8sClient ctrlclient.Client,
k8sReader ctrlclient.Reader,
nodeAgentClient agent.Client,
) *Controller {
return &Controller{
cfg: cfg,
@@ -51,6 +54,7 @@ func NewController(
controllerTemporalClient: controllerTemporalClient,
k8sClient: k8sClient,
k8sReader: k8sReader,
nodeAgentClient: nodeAgentClient,
}
}
@@ -82,6 +86,7 @@ func nodeClusterKeys(_ context.Context, node db.Node) ([]dbreconcile.Key, error)
// Reconcile reconciles one cluster's control plane from a ClusterID root key.
func (c *Controller) Reconcile(ctx context.Context, key dbreconcile.Key) (reconcile.Result, error) {
var cluster db.Cluster
err := c.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
// Re-read under a row lock: the cluster may have been enqueued from a stale
// event, so the reconciler could otherwise act on a stale snapshot and race
@@ -99,8 +104,12 @@ func (c *Controller) Reconcile(ctx context.Context, key dbreconcile.Key) (reconc
return nil
}
cluster = lockedCluster
reconciler := newReconciler(c.cfg, c.logger, tx, c.controllerTemporalClient, c.k8sClient, c.k8sReader)
return reconciler.reconcile(ctx, lockedCluster)
})
return reconcile.Result{}, err
if err != nil {
return reconcile.Result{}, err
}
return c.reconcileNodeAgentUpgrade(ctx, cluster)
}
@@ -57,6 +57,7 @@ func TestUnit_ControllerReconcileSkipsMissingCluster(t *testing.T) {
nil,
nil,
nil,
nil,
)
result, err := controller.Reconcile(context.Background(), dbreconcile.ClusterKey(clusterID))
@@ -450,7 +451,7 @@ func (c *controller) Start(ctx context.Context) {
// newCPController creates a controller wrapper for a controlplane.Controller.
func newCPController(cfg config.Config, logger *slog.Logger, database db.DB, clusterID uuid.UUID) *controller {
cpController := controlplane.NewController(cfg, logger, dbwrapper.New(database, logger), nil, nil, nil)
cpController := controlplane.NewController(cfg, logger, dbwrapper.New(database, logger), nil, nil, nil, nil)
return newController(func(ctx context.Context) error {
_, err := cpController.Reconcile(ctx, dbreconcile.ClusterKey(clusterID))
return err
@@ -245,6 +245,7 @@ func TestControllerReturnsErrorWhileClusterInfrastructureIsNotReady(t *testing.T
nil,
k8sClient,
k8sClient,
nil,
)
result, err := controller.Reconcile(context.Background(), dbreconcile.ClusterKey(clusterID))
@@ -107,26 +107,30 @@ func (r *reconciler) reconcile(ctx context.Context, cluster db.Cluster) error {
return err
}
// ConfigMap changes only.
if err := r.reconcileK8sUpgrade(ctx, cluster, controlPlane, provider.NodePoolUpgradeConfig()); err != nil {
return fmt.Errorf("reconciling k8s upgrade: %w", err)
}
// Agent replacement can interrupt join and kubeadm RPCs. Deletion and repair
// still proceed, because they do not require the upgrade to finish.
if !agentUpgradeBlocksNodeWork(cluster, controlPlane.nodes) {
// ConfigMap changes only.
if err := r.reconcileK8sUpgrade(ctx, cluster, controlPlane, provider.NodePoolUpgradeConfig()); err != nil {
return fmt.Errorf("reconciling k8s upgrade: %w", err)
}
// FIXME: https://github.com/dsx-ai-factory/nvke/issues/784 - reconcileNodesNeedingRollout
// still tears a node down directly instead of recording intent and letting the
// promotion below start it, so rollout teardowns bypass the serialized path.
if err := r.reconcileNodesNeedingRollout(ctx, cluster, controlPlane, allocator, provider.NewNodeProvider()); err != nil {
return fmt.Errorf("reconciling control plane nodes needing rollout: %w", err)
}
// FIXME: https://github.com/dsx-ai-factory/nvke/issues/784 - reconcileNodesNeedingRollout
// still tears a node down directly instead of recording intent and letting the
// promotion below start it, so rollout teardowns bypass the serialized path.
if err := r.reconcileNodesNeedingRollout(ctx, cluster, controlPlane, allocator, provider.NewNodeProvider()); err != nil {
return fmt.Errorf("reconciling control plane nodes needing rollout: %w", err)
}
// Grow before shrink: join a ready host if one is waiting, and leave any
// queued delete alone until that join is done.
joinInFlight, err := r.reconcileControlPlaneJoins(ctx, cluster, controlPlane)
if err != nil {
return fmt.Errorf("reconciling control plane joins: %w", err)
}
if joinInFlight {
return nil
// Grow before shrink: join a ready host if one is waiting, and leave any
// queued delete alone until that join is done.
joinInFlight, err := r.reconcileControlPlaneJoins(ctx, cluster, controlPlane)
if err != nil {
return fmt.Errorf("reconciling control plane joins: %w", err)
}
if joinInFlight {
return nil
}
}
// Promote the oldest accepted delete into a teardown, one at a time.
+3
View File
@@ -77,6 +77,9 @@ type Cluster struct {
Conditions ClusterConditions `bun:"type:jsonb"` // JSONB field keys use camelCase across all sub-structs for consistency (see ClusterConditions below)
CreatedAt time.Time `bun:"type:timestamptz,notnull,default:current_timestamp"`
UpdatedAt time.Time `bun:"type:timestamptz,notnull,default:current_timestamp"`
NodeAgentUpgrade *NodeAgentUpgrade `bun:"node_agent_upgrade,type:jsonb"`
CertificateRenewal *NodeAgentCertificateRenewal `bun:"certificate_renewal,type:jsonb"`
}
func (c *Cluster) NicoProvider() (NicoClusterProvider, error) {
@@ -17,6 +17,11 @@ import (
"github.com/uptrace/bun"
)
// NodeAgentConfig stores the exact desired agent release.
type NodeAgentConfig struct {
Version string `json:"version,omitempty"`
}
// ControlPlaneConfigSpec is the snapshot payload stored in
// control_plane_configurations.config.
//
@@ -32,6 +37,7 @@ type ControlPlaneConfigSpec struct {
KubernetesVersion string `json:"kubernetes_version,omitempty" bun:"-"`
Nico *NicoControlPlaneProvider `json:"nico,omitempty" bun:"-"`
Capi *CAPIControlPlaneProvider `json:"capi,omitempty" bun:"-"`
NodeAgentConfig NodeAgentConfig `json:"node_agent_config,omitempty" bun:"-"`
}
type NicoControlPlaneProvider struct {
@@ -0,0 +1,33 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package migrations
import (
"context"
"fmt"
"github.com/uptrace/bun"
)
func init() { //nolint:gochecknoinits // Bun registers migrations at package initialization.
migrations.MustRegister(func(ctx context.Context, database *bun.DB) error {
return database.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
for _, statement := range []string{
// Keep one selected upgrade after a restart, even while its agent is unreachable.
// Track accepted renewal work so agent restarts cannot interrupt it.
"ALTER TABLE clusters ADD COLUMN node_agent_upgrade jsonb, ADD COLUMN certificate_renewal jsonb",
// Preserve the first provisioning version and method across retries and configuration changes.
"ALTER TABLE nodes ADD COLUMN node_agent_lifecycle jsonb",
} {
if _, err := tx.ExecContext(ctx, statement); err != nil {
return fmt.Errorf("adding node-agent convergence state: %w", err)
}
}
return nil
})
}, func(context.Context, *bun.DB) error {
// Dropping these columns would discard active upgrade and renewal coordination.
return fmt.Errorf("down migration not supported")
})
}
@@ -0,0 +1,48 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package db
import (
"time"
"github.com/google/uuid"
)
const (
// NodeAgentUpgradeSourceLifecycle identifies upgrades required before preflight.
NodeAgentUpgradeSourceLifecycle = "lifecycle"
)
// NodeAgentUpgrade records the selected node and accepted target for a cluster.
type NodeAgentUpgrade struct {
// Source selects the provisioning workflow or background controller that resumes this request.
Source string `json:"source"`
// NodeID keeps the same node selected after a controller restart.
NodeID uuid.UUID `json:"nodeId"`
// TargetVersion preserves the accepted version until the current installation finishes.
TargetVersion string `json:"targetVersion"`
// Method preserves the accepted installation method across controller configuration changes.
Method string `json:"method"`
// Phase is Pending before the first request and Running during installation or retries.
Phase string `json:"phase"`
// ErrorMessage exposes the last failure even when the agent is unreachable.
ErrorMessage string `json:"errorMessage"`
// RetryAt keeps the retry delay across controller restarts.
RetryAt time.Time `json:"retryAt"`
}
// NodeAgentLifecycle keeps the provisioning target and method through join.
type NodeAgentLifecycle struct {
// Version pins the provisioning target across activity and workflow retries.
Version string `json:"version"`
// Method pins the installation method if controller configuration changes during provisioning.
Method string `json:"method"`
}
// NodeAgentCertificateRenewal identifies actual renewal work, not a queued workflow.
// Its identity lets activity retries resume accepted work after a connection failure.
type NodeAgentCertificateRenewal struct {
NodeID uuid.UUID `json:"nodeId"`
OperationID string `json:"operationId"`
}
+5 -4
View File
@@ -44,10 +44,11 @@ type Node struct {
// accepted but not yet started. It is set only on the control-plane-controller
// delete path, where the API records intent and the control-plane controller
// starts the teardown one node at a time; nil everywhere else.
DeleteRequest json.RawMessage `bun:"delete_request,type:jsonb,nullzero"`
CreatedAt time.Time `bun:"type:timestamptz,notnull,default:current_timestamp"`
UpdatedAt time.Time `bun:"type:timestamptz,notnull,default:current_timestamp"`
Nico *NicoNodeProvider `bun:"nico,type:jsonb"`
DeleteRequest json.RawMessage `bun:"delete_request,type:jsonb,nullzero"`
CreatedAt time.Time `bun:"type:timestamptz,notnull,default:current_timestamp"`
UpdatedAt time.Time `bun:"type:timestamptz,notnull,default:current_timestamp"`
Nico *NicoNodeProvider `bun:"nico,type:jsonb"`
NodeAgentLifecycle *NodeAgentLifecycle `bun:"node_agent_lifecycle,type:jsonb"`
}
type NicoNodeProvider struct {
@@ -213,7 +213,7 @@ func StartRequestedTeardown(ctx context.Context, tx db.Tx, nodeID uuid.UUID) err
return StartTeardown(ctx, tx, node, TeardownNodeInput{
Reason: recorded.Reason,
ForceUnreachable: recorded.ForceUnreachable,
ForceUnreachable: recorded.ForceUnreachable || !isHealthyControlPlaneNode(node),
MachineHealthIssue: recorded.MachineHealthIssue,
}, "Node deletion in progress")
}
@@ -509,3 +509,19 @@ func TestStartRequestedTeardownWithoutRequest(t *testing.T) {
require.ErrorIs(t, nodes.StartRequestedTeardown(ctx, mockTx, target.ID), nodes.ErrNoDeleteRequested)
mockTx.AssertNotCalled(t, "UpdateNode", mock.Anything, mock.Anything)
}
func TestStartRequestedTeardownForcesDeleteWhenAgentBecomesUnavailable(t *testing.T) {
t.Parallel()
target := joinedCPNode(cpNodeIDs(1)[0])
target.Conditions.DeleteRequested = db.NewCondition(true, "Delete accepted")
target.Conditions.NodeAgentReady = db.NewCondition(false, "Agent drain failed")
target.DeleteRequest = []byte(`{"reason":"API"}`)
mockTx := &testutil.MockTx{}
mockTx.On("GetNodeForUpdate", mock.Anything, target.ID).Return(target, nil)
mockTx.On("UpdateNode", mock.Anything, mock.Anything).Return(target, nil)
mockTx.On("CreateWorkflowOutboxEntry", mock.Anything, constants.TeardownNodeWorkflowType, constants.TeardownNodeWorkflowPrefix+target.ID.String(), mock.MatchedBy(func(input nodes.TeardownNodeInput) bool {
return input.NodeID == target.ID && input.Reason == "API" && input.ForceUnreachable && input.AllowCPNode
})).Return(db.WorkflowOutbox{}, nil)
require.NoError(t, nodes.StartRequestedTeardown(context.Background(), mockTx, target.ID))
mockTx.AssertExpectations(t)
}
@@ -0,0 +1,142 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package runbook
import (
"fmt"
"os/exec"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestAgentUpgradePruningIgnoresCorruptAndMismatchedRecords(t *testing.T) {
script, err := Script("", "node-agent-upgrade")
require.NoError(t, err)
_, python, found := strings.Cut(script, "<<'PY'\n")
require.True(t, found)
definitions, _, found := strings.Cut(python, "if len(sys.argv) == 3")
require.True(t, found)
// Exercise the runbook's actual record reader and retention policy without
// requiring systemd or modifying the host's upgrade directory.
checks := `
import tempfile
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
def record(folder, version, phase, date):
directory = root / folder
directory.mkdir()
(directory / 'operation.json').write_text(json.dumps(dict(
targetVersion=version, method='bundle',
phase=phase, createdAt=date)))
record('v0.1.1_bundle', 'v0.1.1', 'Succeeded', '2026-01-01')
record('v0.1.2_bundle', 'v0.1.2', 'Succeeded', '2026-01-02')
record('v0.1.3_bundle', 'v0.1.3', 'FailedRestored', '2026-01-03')
record('v0.1.4_bundle', 'v0.1.4', 'Running', '2026-01-04')
record('mismatched', 'v0.1.2', 'Succeeded', '2026-01-05')
record('v0.1.5_bundle', 'v0.1.6', 'Succeeded', '2026-01-06')
corrupt = root / 'v0.1.7_bundle'
corrupt.mkdir()
(corrupt / 'operation.json').write_text('{truncated')
records = read_operations(root)
assert len(records) == 4, records
prune_operations(records)
assert not (root / 'v0.1.1_bundle').exists()
for name in ('v0.1.2_bundle', 'v0.1.3_bundle', 'v0.1.4_bundle',
'mismatched', 'v0.1.5_bundle', 'v0.1.7_bundle'):
assert (root / name).exists(), name
`
command := exec.CommandContext(t.Context(), "python3", "-c", definitions+checks)
output, err := command.CombinedOutput()
require.NoError(t, err, "%s", output)
}
func TestAgentUpgradeBootstrapAcrossPackageRename(t *testing.T) {
script, err := Script("", "node-agent-upgrade")
require.NoError(t, err)
_, python, found := strings.Cut(script, "<<'PY'\n")
require.True(t, found)
definitions, _, found := strings.Cut(python, "if len(sys.argv) == 3")
require.True(t, found)
checks := `
import tempfile
from unittest.mock import patch
from pathlib import Path as RealPath
for previous_name, target_name in [('nke-agent', 'nvke-agent'), ('nvke-agent', 'nke-agent')]:
for fail_target in (False, True):
with tempfile.TemporaryDirectory() as temporary:
root = RealPath(temporary)
def mapped_path(value):
value = str(value)
if value.startswith('/') and not value.startswith(temporary + '/'):
return root / value.lstrip('/')
return RealPath(value)
namespace = {}
source = DEFINITIONS.replace('from pathlib import Path', 'Path = mapped_path')
namespace['mapped_path'] = mapped_path
state_dir = mapped_path('/var/lib/' + ('nke' if previous_name == 'nke-agent' else 'nvke'))
state_dir.mkdir(parents=True)
(state_dir / 'state.json').write_text('original state')
previous_binary = mapped_path('/usr/local/bin/' + previous_name)
previous_binary.parent.mkdir(parents=True)
previous_binary.write_text('NVKE Agent Version: v0.1.1')
previous_unit = mapped_path('/etc/systemd/system/' + previous_name + '.service')
previous_unit.parent.mkdir(parents=True)
previous_unit.write_text('original unit')
exec(source, namespace)
store = namespace['ROOT']
store.mkdir(parents=True)
op_dir = store / 'v0.1.2_bundle'
op_dir.mkdir()
op_path = op_dir / 'operation.json'
op = dict(method='bundle', targetVersion='v0.1.2',
previousVersion='v0.1.1', phase='Pending', bundleSource=[], createdAt=namespace['now']())
namespace['save'](op_path, op)
fixture_dir = root / 'fixture'
fixture_dir.mkdir()
version = 'v9.9.9' if fail_target else 'v0.1.2'
(fixture_dir / target_name).write_text('NVKE Agent Version: ' + version)
(fixture_dir / (target_name + '.service')).write_text('target unit')
if target_name == 'nvke-agent':
(fixture_dir / 'migrate-agent-paths.sh').write_text('migration fixture')
archive = root / 'fixture.tgz'
with namespace['tarfile'].open(archive, 'w:gz') as bundle:
for file in fixture_dir.iterdir():
bundle.add(file, arcname=file.name)
commands = []
def fake_run(*args, cwd=None):
commands.append(args)
if args[0] == 'systemctl':
return ''
if args[0] == 'install':
namespace['shutil'].copyfile(args[-2], mapped_path(args[-1]))
return ''
if args[0] == 'bash':
legacy = mapped_path('/var/lib/nke')
renamed = mapped_path('/var/lib/nvke')
if legacy.is_dir() and not legacy.is_symlink():
assert not renamed.exists(), 'bootstrap created a conflicting state tree'
legacy.rename(renamed)
legacy.symlink_to(renamed)
return ''
if args[-1] == '--version':
return mapped_path(args[0]).read_text()
raise AssertionError(args)
namespace['run'] = fake_run
namespace['bundle_url'] = lambda version, source: archive.as_uri()
with patch.object(namespace['time'], 'sleep', lambda seconds: None):
namespace['execute'](op_path)
result = namespace['json'].loads(op_path.read_text())
assert result['phase'] == ('FailedRestored' if fail_target else 'Succeeded'), result
expected_name = previous_name if fail_target else target_name
expected_version = 'v0.1.1' if fail_target else 'v0.1.2'
assert mapped_path('/usr/local/bin/' + expected_name).read_text().endswith(expected_version)
assert ('systemctl', 'restart', expected_name + '.service') in commands
assert (state_dir / 'state.json').read_text() == 'original state'
`
command := exec.CommandContext(t.Context(), "python3", "-c", "DEFINITIONS = "+fmt.Sprintf("%q", definitions)+"\n"+checks)
output, err := command.CombinedOutput()
require.NoError(t, err, "%s", output)
}
@@ -0,0 +1,401 @@
#!/bin/bash
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
set -euo pipefail
# Ubuntu's cloud-init image supplies Python. No script from the controller is
# executed in the agent cgroup after installation starts.
helper=$(mktemp /var/tmp/nvke-agent-upgrade.XXXXXX.py)
trap 'rm -f "$helper"' EXIT
cat > "$helper" <<'PY'
import datetime
import fcntl
import json
import os
from pathlib import Path
import platform
import re
import shlex
import shutil
import subprocess
import sys
import tarfile
import time
import urllib.parse
import urllib.request
ROOT = Path('/var/lib/nvke/agent-upgrades')
LEGACY_PACKAGE = 'nke-agent'
PACKAGE = 'nvke-agent'
# Keep the legacy state tree intact until the package migration moves it.
legacy_state = Path('/var/lib/nke')
if legacy_state.is_dir() and not legacy_state.is_symlink() and not ROOT.parent.exists():
ROOT = legacy_state / 'agent-upgrades'
def select_layout(name=None):
global SERVICE, BINARY, UNIT, BUNDLE_FILES
if name is None:
name = PACKAGE if Path('/usr/local/bin/' + PACKAGE).exists() else LEGACY_PACKAGE
SERVICE = name + '.service'
BINARY = Path('/usr/local/bin/' + name)
UNIT = Path('/etc/systemd/system/' + SERVICE)
BUNDLE_FILES = (BINARY, UNIT, Path('/usr/local/bin/' + name + '-updater'),
Path('/etc/systemd/system/' + name + '-updater@.service'))
if name == PACKAGE:
BUNDLE_FILES += (Path('/usr/local/lib/nvke-agent/migrate-agent-paths.sh'),)
select_layout()
def installed_package():
for name in (PACKAGE, LEGACY_PACKAGE):
try:
fields = run('dpkg-query', '--show', '--showformat=${db:Status-Status} ${Version}', name).split()
if len(fields) == 2 and fields[0] == 'installed':
return name, fields[1]
except subprocess.SubprocessError:
pass
raise RuntimeError('an installed node-agent package is required')
def available_package(version):
for name in (PACKAGE, LEGACY_PACKAGE):
try:
if ('Package: ' + name) in run('apt-cache', 'show', name + '=' + version).splitlines():
return name
except subprocess.SubprocessError:
pass
raise RuntimeError('exact agent package is not available')
def run(*args, cwd=None):
result = subprocess.run(args, cwd=cwd, check=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, timeout=1200)
return result.stdout.strip()
def request_key(request):
return request['targetVersion'] + '_' + request['method']
def now():
return datetime.datetime.now(datetime.timezone.utc).isoformat().replace('+00:00', 'Z')
def save(path, op):
op['updatedAt'] = now()
temp = path.with_suffix('.tmp')
with temp.open('w') as handle:
json.dump(op, handle)
handle.flush()
os.fsync(handle.fileno())
os.chmod(temp, 0o600)
os.replace(temp, path)
def verify(version):
for _ in range(60):
try:
actual = run(str(BINARY), '--version').rsplit(':', 1)[-1].strip()
run('systemctl', 'is-active', '--quiet', SERVICE)
if actual == version:
return
except subprocess.SubprocessError:
pass
time.sleep(2)
raise RuntimeError('agent did not become active at the exact target version')
def download(url, destination):
if urllib.parse.urlparse(url).scheme not in ('https', 'http', 'file'):
raise RuntimeError('bundle source must use HTTP, HTTPS, or file')
with urllib.request.urlopen(url, timeout=120) as source, destination.open('wb') as output:
shutil.copyfileobj(source, output)
def bundle_source(settings):
server = settings.get('NKE_BUNDLE_SERVER_URL', '')
index = settings.get('NKE_BUNDLE_INDEX_URL', '')
arguments = shlex.split(settings.get('AGENT_ARGS', ''))
for i, argument in enumerate(arguments):
for flag, key in (('--bundle-server-url', 'server'), ('--index-file-url', 'index')):
value = None
if argument.startswith(flag + '='):
value = argument.split('=', 1)[1]
elif argument == flag and i + 1 < len(arguments):
value = arguments[i + 1]
if value is not None:
if key == 'server':
server = value
else:
index = value
if not index:
release = Path('/etc/os-release').read_text()
ubuntu = '24' if '24.04' in release else '22' if '22.04' in release else ''
if not ubuntu or not server:
raise RuntimeError('agent bundle source is not configured for this OS')
index = server.rstrip('/') + '/nke_bundles/ubuntu_' + ubuntu + '_index.json'
return server, index
def bundle_url(version, source):
server, index = source
arch = platform.machine()
with urllib.request.urlopen(index, timeout=120) as source:
entries = json.load(source)['agent']['entries']
aliases = ('x86_64', 'amd64') if arch == 'x86_64' else ('aarch64', 'arm64')
for entry in entries:
if entry['version'].lstrip('v') == version.lstrip('v') and entry['arch'] in aliases:
return urllib.parse.urljoin(server.rstrip('/') + '/', entry['path'])
raise RuntimeError('exact agent bundle is not available')
def install_bundle(directory):
agents = [file for name in (PACKAGE, LEGACY_PACKAGE) for file in directory.rglob(name)]
if len(agents) != 1:
raise RuntimeError('bundle must contain one agent')
name = agents[0].name
units = list(directory.rglob(name + '.service'))
if len(units) != 1:
raise RuntimeError('bundle must contain one agent service unit')
run('systemctl', 'stop', SERVICE)
if SERVICE != name + '.service':
run('systemctl', 'disable', SERVICE)
UNIT.unlink(missing_ok=True)
if name == PACKAGE:
migrations = list(directory.rglob('migrate-agent-paths.sh'))
if len(migrations) != 1:
raise RuntimeError('renamed agent bundle must contain one migration script')
run('bash', str(migrations[0]))
destination = Path('/usr/local/lib/nvke-agent/migrate-agent-paths.sh')
destination.parent.mkdir(parents=True, exist_ok=True)
run('install', '-m', '0755', str(migrations[0]), str(destination))
select_layout(name)
BINARY.unlink(missing_ok=True)
UNIT.unlink(missing_ok=True)
run('install', '-m', '0755', str(agents[0]), str(BINARY))
run('install', '-m', '0644', str(units[0]), str(UNIT))
# Preserve the current independent updater when the target predates it.
for suffix, destination, mode in (
('-updater', '/usr/local/bin/' + name + '-updater', '0755'),
('-updater@.service', '/etc/systemd/system/' + name + '-updater@.service', '0644')):
matches = list(directory.rglob(name + suffix))
if len(matches) > 1:
raise RuntimeError('bundle contains duplicate updater files')
if len(matches) == 1:
Path(destination).unlink(missing_ok=True)
run('install', '-m', mode, str(matches[0]), destination)
if name == PACKAGE:
alias = BINARY.with_name(LEGACY_PACKAGE)
alias.unlink(missing_ok=True)
alias.symlink_to(BINARY)
run('systemctl', 'daemon-reload')
run('systemctl', 'enable', '--force', SERVICE)
run('systemctl', 'restart', SERVICE)
def execute(path):
op = json.loads(path.read_text())
assets = path.parent / 'assets'
assets.mkdir(mode=0o700, exist_ok=True)
op['phase'] = 'Running'
op['step'] = 'staging'
save(path, op)
mutated = False
previous_package = ''
previous_name = ''
previous_layout = BINARY.name
previous_files = BUNDLE_FILES
try:
if op['method'] == 'apt':
run('apt-get', 'update')
previous_name, previous_package = installed_package()
target_name = available_package(op['targetVersion'][1:])
op['previousPackageName'] = previous_name
op['previousPackageVersion'] = previous_package
save(path, op)
for package in set((previous_name + '=' + previous_package,
target_name + '=' + op['targetVersion'][1:])):
run('apt-get', 'download', package, cwd=assets)
mutated = True
run('apt-get', '-y', '--allow-downgrades', '--reinstall', 'install',
target_name + '=' + op['targetVersion'][1:])
select_layout(target_name)
if installed_package() != (target_name, op['targetVersion'][1:]):
raise RuntimeError('installed agent package does not match the target')
run('systemctl', 'restart', SERVICE)
else:
for file in BUNDLE_FILES:
if file.exists():
shutil.copy2(file, assets / file.name)
else:
(assets / (file.name + '.absent')).touch()
archive = assets / 'target.tgz'
op['artifactUrl'] = bundle_url(op['targetVersion'], op['bundleSource'])
save(path, op)
download(op['artifactUrl'], archive)
extracted = assets / 'target'
extracted.mkdir(exist_ok=True)
with tarfile.open(archive) as bundle:
# Reject escaping names, links and devices before extraction.
for member in bundle.getmembers():
if member.name.startswith('/') or '..' in Path(member.name).parts or not (member.isfile() or member.isdir()):
raise RuntimeError('unsafe agent bundle member')
bundle.extractall(extracted)
mutated = True
install_bundle(extracted)
verify(op['targetVersion'])
op.update(phase='Succeeded', step='verified', errorMessage='')
except Exception as error:
op.update(errorMessage=str(error), step='failed')
try:
if mutated:
if op['method'] == 'apt':
packages = [p for p in assets.glob('*.deb')
if run('dpkg-deb', '--field', str(p), 'Version') == previous_package
and run('dpkg-deb', '--field', str(p), 'Package') == previous_name]
if len(packages) != 1:
raise RuntimeError('retained previous agent package is missing')
run('apt-get', '-y', '--allow-downgrades', 'install', str(packages[0]))
select_layout(previous_name)
run('systemctl', 'restart', SERVICE)
else:
run('systemctl', 'stop', SERVICE)
if BINARY.name != previous_layout:
run('systemctl', 'disable', SERVICE)
UNIT.unlink(missing_ok=True)
for file in previous_files:
if (assets / (file.name + '.absent')).exists():
file.unlink(missing_ok=True)
else:
file.unlink(missing_ok=True)
mode = '0644' if file.name.endswith('.service') else '0755'
run('install', '-m', mode, str(assets / file.name), str(file))
select_layout(previous_layout)
run('systemctl', 'daemon-reload')
run('systemctl', 'enable', '--force', SERVICE)
run('systemctl', 'restart', SERVICE)
verify(op['previousVersion'])
op['phase'] = 'FailedRestored'
except Exception as restoration:
op['phase'] = 'FailedNotRestored'
op['errorMessage'] += '; restoration: ' + str(restoration)
save(path, op)
def read_operations(root):
records = []
for path in root.glob('*/operation.json'):
try:
op = json.loads(path.read_text())
key = request_key(op)
if path.parent.name != key or not re.fullmatch(r'v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)_(apt|bundle)', key):
continue
if not all(isinstance(op[field], str) for field in ('phase', 'createdAt')):
continue
except (OSError, ValueError, KeyError, TypeError):
continue
records.append((path.parent, op))
return records
def prune_operations(records):
operations = [op for _, op in records]
# Retain active requests and recent success and failure.
keep = {request_key(op) for op in operations if op['phase'] in ('Pending', 'Running')}
for candidates in ([op for op in operations if op['phase'] == 'Succeeded'],
[op for op in operations if op['phase'] in ('FailedRestored', 'FailedNotRestored')]):
if candidates:
keep.add(request_key(max(candidates, key=lambda op: op['createdAt'])))
for folder, previous in records:
name = request_key(previous)
if name not in keep:
if folder.name != name or not re.fullmatch(r'v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)_(apt|bundle)', name):
continue
shutil.rmtree(folder)
if len(sys.argv) == 3 and sys.argv[1] == '--execute':
execute(Path(sys.argv[2]))
sys.exit(0)
target, method, observed = sys.argv[1:]
if target and not re.fullmatch(r'v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', target) or method not in ('apt', 'bundle'):
raise RuntimeError('invalid exact agent target or installation method')
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
with (ROOT / 'upgrade.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
records = read_operations(ROOT)
operations = [op for _, op in records]
active = [op for op in operations if op['phase'] in ('Pending', 'Running')]
current = active[0] if active else max(operations, key=lambda op: op['createdAt'], default=None)
if active:
unit = ('nvke-agent-upgrade-' + request_key(current)) if (ROOT / request_key(current) / 'updater.py').exists() else ('nvke-agent-updater@' + request_key(current) + '.service')
state = subprocess.run(['systemctl', 'show', '--property=ActiveState', '--value', unit],
capture_output=True, text=True, timeout=15).stdout.strip()
if state in ('active', 'activating', 'deactivating'):
print(json.dumps(current))
sys.exit(0)
if not (ROOT / request_key(current) / 'updater.py').exists():
run('systemctl', 'start', '--no-block', unit)
print(json.dumps(current))
sys.exit(0)
# A reboot or killed updater can leave durable state ahead of systemd.
current.update(phase='FailedNotRestored', errorMessage='independent updater stopped before completion')
save(ROOT / request_key(current) / 'operation.json', current)
print(json.dumps(current))
sys.exit(0)
if not target or observed == target:
print(json.dumps({'phase': 'Succeeded', 'errorMessage': ''}))
sys.exit(0)
settings = {}
# Read settings without evaluating shell or exposing service credentials.
env_file = Path('/etc/default/' + BINARY.name)
if env_file.exists():
for line in env_file.read_text().splitlines():
if '=' in line and not line.lstrip().startswith('#'):
key, value = line.split('=', 1)
values = shlex.split(value)
settings[key.strip()] = values[0] if len(values) == 1 else value
pid = run('systemctl', 'show', '--property=MainPID', '--value', SERVICE)
if pid.isdigit() and pid != '0':
environment = Path('/proc/' + pid + '/environ').read_bytes().split(b'\0')
for item in environment:
if b'=' in item:
key, value = item.decode().split('=', 1)
if key in ('NKE_BUNDLE_SERVER_URL', 'NKE_BUNDLE_INDEX_URL'):
settings[key] = value
arguments = Path('/proc/' + pid + '/cmdline').read_bytes().split(b'\0')
settings['AGENT_ARGS'] = shlex.join([item.decode() for item in arguments[1:] if item])
prune_operations(records)
op = dict(targetVersion=target,
previousVersion=observed, method=method, phase='Pending', step='queued',
errorMessage='', createdAt=now(), updatedAt=now())
if method == 'bundle':
op['bundleSource'] = bundle_source(settings)
directory = ROOT / request_key(op)
if directory.exists():
shutil.rmtree(directory)
directory.mkdir(mode=0o700)
path = directory / 'operation.json'
save(path, op)
# The Python body is available through stdin to this bootstrap process.
# Copy it from the enclosing script, then launch an independent unit.
helper = directory / 'updater.py'
# The shell records the exact body before executing this bootstrap.
helper.write_text(Path(os.environ['NVKE_UPGRADE_HELPER']).read_text())
os.chmod(helper, 0o700)
try:
run('systemd-run', '--quiet', '--no-block', '--collect', '--unit=nvke-agent-upgrade-' + request_key(op),
'--property=Type=oneshot', '--property=TimeoutStartSec=30min',
'/usr/bin/python3', str(helper), '--execute', str(path))
except Exception as error:
op.update(phase='FailedRestored', errorMessage=str(error))
save(path, op)
result = dict(op)
if current and current.get('targetVersion') == target and current.get('method') == method and current.get('errorMessage') and current['phase'] in ('FailedRestored', 'FailedNotRestored'):
result['errorMessage'] = current['errorMessage']
print(json.dumps(result))
PY
NVKE_UPGRADE_HELPER="$helper" python3 "$helper" "$@"
@@ -299,6 +299,9 @@ func controlPlaneConfigSpecFromCreateAPI(
KubernetesVersion: kubernetesVersion,
}
if c.NodeAgentConfig != nil && c.NodeAgentConfig.Version != nil {
spec.NodeAgentConfig.Version = *c.NodeAgentConfig.Version
}
switch providerType {
case db.ProviderTypeNico:
nicoControlPlaneProvider := db.NicoControlPlaneProvider{
+67 -5
View File
@@ -94,6 +94,7 @@ type clusterService struct {
// false, the control plane is provisioned from a control-plane node pool and
// supplying controlPlaneConfig.desiredCount/spec is rejected.
useControlPlaneController bool
nodeAgentUpdateMethod string
}
func NewClusterService(
@@ -105,6 +106,7 @@ func NewClusterService(
supportedInfraProviders []string,
allowLegacyCalicoClusterCreation bool,
useControlPlaneController bool,
updateMethod string,
) *clusterService {
return &clusterService{
logger: logger,
@@ -115,6 +117,7 @@ func NewClusterService(
providers: newProviderSupport(supportedInfraProviders),
allowLegacyCalicoClusterCreation: allowLegacyCalicoClusterCreation,
useControlPlaneController: useControlPlaneController,
nodeAgentUpdateMethod: updateMethod,
}
}
@@ -365,6 +368,16 @@ func (s *clusterService) ValidateCreateClusterRequestFields(req *api.CreateClust
return fmt.Errorf("exactly one provider must be set")
}
if req.ControlPlaneConfig != nil && req.ControlPlaneConfig.NodeAgentConfig != nil && req.ControlPlaneConfig.NodeAgentConfig.Version != nil {
version, err := canonicalNodeAgentVersion(*req.ControlPlaneConfig.NodeAgentConfig.Version)
if err != nil {
return err
}
if version != "" && s.nodeAgentUpdateMethod == "" {
return fmt.Errorf("nodeAgent.updateMethod is required for agent convergence")
}
req.ControlPlaneConfig.NodeAgentConfig.Version = &version
}
if s.useControlPlaneController {
// Cluster-level control plane config is authoritative: control-plane node
// pools are rejected and the control plane is described by controlPlaneConfig.
@@ -564,6 +577,9 @@ func (s *clusterService) UpdateCluster(ctx context.Context, req api.UpdateCluste
message: uip.Message,
}
}
if agentUpgradeBlocksMaintenance(dbCluster, req.Body) {
return errAgentUpgradeInProgress
}
// Reject a controlPlaneConfig provider block that doesn't match the cluster before
// any field is touched.
if cpConfig := req.Body.ControlPlaneConfig; cpConfig != nil {
@@ -660,9 +676,8 @@ func (s *clusterService) UpdateCluster(ctx context.Context, req api.UpdateCluste
return api.UpdateCluster404Response{}, nil
}
// Return 409 when another mutually-exclusive operation is already running.
var uipErr *updateInProgressError
if errors.As(err, &uipErr) {
return api.UpdateCluster409JSONResponse{Message: uipErr.Error()}, nil
if response := updateClusterConflictResponse(err); response != nil {
return response, nil
}
var badRequestErr *badRequestError
if errors.As(err, &badRequestErr) {
@@ -880,7 +895,8 @@ func (s *clusterService) applyClusterControlPlaneConfigUpdate(ctx context.Contex
//
// Provider fields are read directly from the nested payloads.
func hasClusterLevelControlPlaneUpdate(req *api.UpdateClusterControlPlaneConfig) bool {
if req.DesiredCount != nil ||
if req.NodeAgentConfig != nil ||
req.DesiredCount != nil ||
req.SystemReservedMemory != nil ||
req.TeleportEnabled != nil ||
req.Infra != nil {
@@ -929,6 +945,16 @@ func (s *clusterService) applyClusterLevelControlPlaneSpecUpdate(
cluster.ControlPlaneConfig.DesiredCount = *req.DesiredCount
}
if req.NodeAgentConfig != nil && req.NodeAgentConfig.Version != nil {
version, err := canonicalNodeAgentVersion(*req.NodeAgentConfig.Version)
if err != nil {
return newBadRequestErrorf("%s", err)
}
if version != "" && s.nodeAgentUpdateMethod == "" {
return newBadRequestErrorf("nodeAgent.updateMethod is required for agent convergence")
}
spec.NodeAgentConfig.Version = version
}
if req.SystemReservedMemory != nil {
spec.SystemReservedMemory = *req.SystemReservedMemory
}
@@ -1037,6 +1063,7 @@ func apiControlPlaneConfigFromDB(cfg db.ControlPlaneConfig) *api.ControlPlaneCon
TeleportEnabled: &teleportEnabled,
Nico: apiNicoControlPlaneProviderFromDB(cfg.Nico),
Infra: apiInfraControlPlaneProviderFromDB(cfg.Capi),
NodeAgentConfig: apiNodeAgentConfigFromDB(cfg.NodeAgentConfig),
}
}
@@ -1135,6 +1162,7 @@ func (s *clusterService) DeleteCluster(ctx context.Context, req api.DeleteCluste
return fmt.Errorf("failed to get cluster: %w", err)
}
// Cluster deletion stops controller-side agent upgrades.
dbCluster.Conditions.Deleting = db.NewCondition(true, "Cluster deletion is pending")
if _, err := tx.UpdateCluster(ctx, &dbCluster); err != nil {
@@ -1217,7 +1245,8 @@ func APIClusterFromDB(dbCluster *db.Cluster) api.Cluster {
Nico: apiNicoClusterProviderFromDB(dbCluster.Nico),
Infra: apiInfraClusterProviderFromDB(dbCluster.Capi),
Conditions: conditions,
Conditions: conditions,
NodeAgentUpgrade: apiNodeAgentUpgradeFromDB(dbCluster.NodeAgentUpgrade),
}
}
@@ -1387,3 +1416,36 @@ func parseKubernetesVersion(version string) (int, int, int, error) {
}
return major, minor, patch, nil
}
func apiNodeAgentUpgradeFromDB(upgrade *db.NodeAgentUpgrade) *api.NodeAgentUpgradeStatus {
if upgrade == nil {
return nil
}
phase := api.NodeAgentUpgradeStatusPhase("Running")
if upgrade.Phase == "Pending" {
phase = "Pending"
}
return &api.NodeAgentUpgradeStatus{NodeID: upgrade.NodeID, TargetVersion: upgrade.TargetVersion, Method: upgrade.Method, Phase: phase, ErrorMessage: upgrade.ErrorMessage}
}
func apiNodeAgentConfigFromDB(config db.NodeAgentConfig) *api.NodeAgentConfig {
if config.Version == "" {
return nil
}
return &api.NodeAgentConfig{Version: &config.Version}
}
func agentUpgradeBlocksMaintenance(cluster db.Cluster, request *api.UpdateClusterJSONRequestBody) bool {
return cluster.NodeAgentUpgrade != nil && (request.EnableEtcdEncryption != nil && *request.EnableEtcdEncryption || request.EnableOidc != nil && *request.EnableOidc)
}
func updateClusterConflictResponse(err error) api.UpdateClusterResponseObject {
if errors.Is(err, errAgentUpgradeInProgress) {
return api.UpdateCluster409JSONResponse{Message: err.Error()}
}
var uipErr *updateInProgressError
if errors.As(err, &uipErr) {
return api.UpdateCluster409JSONResponse{Message: uipErr.Error()}
}
return nil
}
+8 -6
View File
@@ -49,7 +49,7 @@ func newTestClusterService(logger *slog.Logger, mockDB *mockDB) clusterService {
// useControlPlaneController.
func newTestClusterServiceWithControlPlaneController(logger *slog.Logger, mockDB *mockDB, useControlPlaneController bool) clusterService {
nodePoolService := server.NewNodePoolService(logger, mockDB, config.TeleportConfig{}, nil, useControlPlaneController)
return server.NewClusterService(logger, mockDB, nodePoolService, config.TeleportConfig{}, false, nil, true, useControlPlaneController)
return server.NewClusterService(logger, mockDB, nodePoolService, config.TeleportConfig{}, false, nil, true, useControlPlaneController, "")
}
func discardLogger() *slog.Logger {
@@ -718,6 +718,7 @@ func TestClusterService_CreateClusterRejectsUnsupportedInfraProvider(t *testing.
[]string{config.InfraProviderNico},
false,
false,
"",
)
resp, err := service.CreateCluster(context.Background(), api.CreateClusterRequestObject{
@@ -2118,6 +2119,7 @@ func TestClusterService_UpdateCluster_ControlPlaneConfig_RejectsUnsupportedProvi
[]string{config.InfraProviderInfra},
false,
false,
"",
)
resp, err := svc.UpdateCluster(context.Background(), api.UpdateClusterRequestObject{
@@ -2210,7 +2212,7 @@ func TestValidateCreateClusterRequestFields_LegacyCalicoCreationGate(t *testing.
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, tt.allowCalico, false)
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, tt.allowCalico, false, "")
req := baseNicoClusterCreateRequest()
req.CniPlugin = tt.cni
@@ -2227,7 +2229,7 @@ func TestValidateCreateClusterRequestFields_LegacyCalicoCreationGate(t *testing.
func TestClusterService_CreateClusterRejectsCalicoBeforeTransaction(t *testing.T) {
mockDB := &mockDB{}
svc := server.NewClusterService(discardLogger(), mockDB, nil, config.TeleportConfig{}, false, nil, false, false)
svc := server.NewClusterService(discardLogger(), mockDB, nil, config.TeleportConfig{}, false, nil, false, false, "")
resp, err := svc.CreateCluster(context.Background(), api.CreateClusterRequestObject{Body: baseNicoClusterCreateRequest()})
@@ -2239,7 +2241,7 @@ func TestClusterService_CreateClusterRejectsCalicoBeforeTransaction(t *testing.T
}
func TestValidateCreateClusterRequestFields_RejectsTaintsOnControlPlanePool(t *testing.T) {
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, true, false)
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, true, false, "")
req := baseNicoClusterCreateRequest()
(*req.NodePools)[0].NodeTaints = []api.NodeTaint{{
Key: "dedicated",
@@ -2252,7 +2254,7 @@ func TestValidateCreateClusterRequestFields_RejectsTaintsOnControlPlanePool(t *t
}
func TestValidateCreateClusterRequestFields_RequiresExactlyOneProvider(t *testing.T) {
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, false, false)
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, false, false, "")
t.Run("neither provider", func(t *testing.T) {
req := baseNicoClusterCreateRequest()
@@ -2275,7 +2277,7 @@ func TestValidateCreateClusterRequestFields_RequiresExactlyOneProvider(t *testin
// The Forge identity fields are required, and they are only reachable through
// the nested nico payload.
func TestValidateCreateClusterRequestFields_NicoIdentityFieldsRequired(t *testing.T) {
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, false, false)
svc := server.NewClusterService(discardLogger(), nil, nil, config.TeleportConfig{}, false, nil, false, false, "")
cases := []struct {
name string
@@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package server
import (
"errors"
"fmt"
"regexp"
"strings"
"github.com/blang/semver/v4"
)
var (
errAgentUpgradeInProgress = errors.New("control-plane agent upgrade is in progress; retry this maintenance update after it completes")
agentReleasePattern = regexp.MustCompile(`^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$`)
)
func canonicalNodeAgentVersion(value string) (string, error) {
if value == "" {
return "", nil
}
if !agentReleasePattern.MatchString(value) {
return "", fmt.Errorf("controlPlaneConfig.nodeAgentConfig.version must be an exact release SemVer")
}
version, err := semver.Parse(strings.TrimPrefix(value, "v"))
if err != nil {
return "", fmt.Errorf("invalid node-agent version: %w", err)
}
return "v" + version.String(), nil
}
@@ -0,0 +1,134 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package server
import (
"context"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/dsx-ai-factory/nvke/controller/api"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
"github.com/dsx-ai-factory/nvke/controller/internal/testutil"
)
func TestCanonicalNodeAgentVersion(t *testing.T) {
for _, test := range []struct {
input, want string
valid bool
}{
{"", "", true},
{"1.2.3", "v1.2.3", true},
{"v1.2.3", "v1.2.3", true},
{"latest", "", false},
{"1.2", "", false},
{"v01.2.3", "", false},
{"v1.2.3-rc.1", "", false},
{"v1.2.3+build", "", false},
{" v1.2.3", "", false},
} {
t.Run(test.input, func(t *testing.T) {
got, err := canonicalNodeAgentVersion(test.input)
if test.valid {
require.NoError(t, err)
require.Equal(t, test.want, got)
} else {
require.Error(t, err)
}
})
}
}
func TestAgentVersionChangeDoesNotReplaceNodes(t *testing.T) {
pinned := db.ControlPlaneConfigSpec{KubernetesVersion: "1.34.2", NodeAgentConfig: db.NodeAgentConfig{Version: "v1.2.3"}}
desired := pinned
desired.NodeAgentConfig.Version = "v1.2.2"
require.False(t, db.IsControlPlaneRolloutRequired(pinned, desired))
desired.NodeAgentConfig.Version = ""
require.False(t, db.IsControlPlaneRolloutRequired(pinned, desired))
desired.KubernetesVersion = "1.34.3"
require.True(t, db.IsControlPlaneRolloutRequired(pinned, desired))
}
func TestNodeAgentVersionPatchPreservesOmittedAndClearsEmpty(t *testing.T) {
service := clusterService{useControlPlaneController: true, nodeAgentUpdateMethod: "apt"}
ctx := context.Background()
spec := db.ControlPlaneConfigSpec{NodeAgentConfig: db.NodeAgentConfig{Version: "v1.2.3"}}
cluster := db.Cluster{}
require.NoError(t, service.applyClusterLevelControlPlaneSpecUpdate(ctx, &cluster, &api.UpdateClusterControlPlaneConfig{}, &spec))
require.Equal(t, "v1.2.3", spec.NodeAgentConfig.Version)
require.NoError(t, service.applyClusterLevelControlPlaneSpecUpdate(ctx, &cluster, &api.UpdateClusterControlPlaneConfig{NodeAgentConfig: &api.NodeAgentConfig{}}, &spec))
require.Equal(t, "v1.2.3", spec.NodeAgentConfig.Version)
downgrade := "1.2.2"
require.NoError(t, service.applyClusterLevelControlPlaneSpecUpdate(ctx, &cluster, &api.UpdateClusterControlPlaneConfig{NodeAgentConfig: &api.NodeAgentConfig{Version: &downgrade}}, &spec))
require.Equal(t, "v1.2.2", spec.NodeAgentConfig.Version)
empty := ""
require.NoError(t, service.applyClusterLevelControlPlaneSpecUpdate(ctx, &cluster, &api.UpdateClusterControlPlaneConfig{NodeAgentConfig: &api.NodeAgentConfig{Version: &empty}}, &spec))
require.Empty(t, spec.NodeAgentConfig.Version)
legacy := clusterService{}
tx := &testutil.MockTx{}
tx.On("GetCluster", mock.Anything, mock.Anything).Maybe().Return(cluster, nil)
require.ErrorIs(t, legacy.applyClusterControlPlaneConfigUpdate(ctx, tx, &cluster, &api.UpdateClusterControlPlaneConfig{NodeAgentConfig: &api.NodeAgentConfig{Version: &downgrade}}), errControlPlaneConfigNotEnabled)
}
func TestClusterDeletionLeavesAcceptedAgentUpgradeAlone(t *testing.T) {
cluster := db.Cluster{ID: uuid.New(), NodeAgentUpgrade: &db.NodeAgentUpgrade{NodeID: uuid.New(), Phase: "Running"}}
database := &testutil.MockDB{MockTx: &testutil.MockTx{}}
database.On("RunInTx", mock.Anything, mock.Anything).Return(nil)
database.MockTx.On("GetClusterForUpdate", mock.Anything, cluster.ID).Return(cluster, nil)
database.MockTx.On("UpdateCluster", mock.Anything, mock.MatchedBy(func(updated *db.Cluster) bool {
return updated.NodeAgentUpgrade == cluster.NodeAgentUpgrade && updated.Conditions.Deleting.Status == db.ConditionStatusTrue
})).Return(cluster, nil).Once()
database.MockTx.On("CreateWorkflowOutboxEntry", mock.Anything, "TeardownCluster", mock.Anything, map[string]interface{}{clusterIDConst: cluster.ID}).Return(db.WorkflowOutbox{}, nil).Once()
service := clusterService{db: database}
response, err := service.DeleteCluster(context.Background(), api.DeleteClusterRequestObject{ClusterID: cluster.ID})
require.NoError(t, err)
require.IsType(t, api.DeleteCluster202Response{}, response)
database.MockTx.AssertExpectations(t)
}
func TestAgentUpgradeMaintenanceReturnsConflict(t *testing.T) {
for _, maintenance := range []string{"OIDC", "etcd encryption"} {
t.Run(maintenance, func(t *testing.T) {
cluster := db.Cluster{ID: uuid.New(), NodeAgentUpgrade: &db.NodeAgentUpgrade{NodeID: uuid.New(), Phase: "Running"}}
database := &testutil.MockDB{MockTx: &testutil.MockTx{}}
database.On("RunInTx", mock.Anything, mock.Anything).Return(nil)
database.MockTx.On("GetClusterForUpdate", mock.Anything, cluster.ID).Return(cluster, nil)
body := &api.UpdateClusterRequest{}
enabled := true
if maintenance == "OIDC" {
body.EnableOidc = &enabled
} else {
body.EnableEtcdEncryption = &enabled
}
service := clusterService{db: database}
response, err := service.UpdateCluster(t.Context(), api.UpdateClusterRequestObject{ClusterID: cluster.ID, Body: body})
require.NoError(t, err)
conflict, ok := response.(api.UpdateCluster409JSONResponse)
require.True(t, ok)
require.Equal(t, errAgentUpgradeInProgress.Error(), conflict.Message)
database.MockTx.AssertNotCalled(t, "UpdateCluster", mock.Anything, mock.Anything)
})
}
}
func TestAgentUpgradeResponseHasOnlyPendingOrRunningPhase(t *testing.T) {
for _, test := range []struct {
phase string
want api.NodeAgentUpgradeStatusPhase
}{
{phase: "Pending", want: "Pending"},
{phase: "Running", want: "Running"},
} {
t.Run(test.phase, func(t *testing.T) {
response := apiNodeAgentUpgradeFromDB(&db.NodeAgentUpgrade{Phase: test.phase, ErrorMessage: "last attempt failed"})
require.Equal(t, test.want, response.Phase)
require.Equal(t, "last attempt failed", response.ErrorMessage)
})
}
require.Nil(t, apiNodeAgentUpgradeFromDB(nil))
}
+1
View File
@@ -250,6 +250,7 @@ func NewServerImpl(
cfg.SupportedInfraProviders,
o.allowLegacyCalicoClusterCreation,
cfg.UseControlPlaneControllerForControlPlane(),
cfg.NodeAgent.UpdateMethod,
)
clusterService.fleetOIDC = o.fleetOIDC
@@ -11,9 +11,12 @@ import (
"time"
"github.com/google/uuid"
"go.temporal.io/sdk/temporal"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
nvkeproto "github.com/dsx-ai-factory/nvke/agent/pkg/agent/proto"
)
@@ -56,6 +59,9 @@ func (a *Activities) RenewKubernetesCertificates(
if input.ThresholdDays <= 0 || input.ThresholdDays > math.MaxInt32 {
return KubernetesCertificateRenewalResult{}, fmt.Errorf("threshold days must be between 1 and %d", math.MaxInt32)
}
if err := a.reserveCertificateRenewal(ctx, node, &input); err != nil {
return KubernetesCertificateRenewalResult{}, err
}
response, err := a.nodeAgentClient.StartKubernetesCertificateRenewal(ctx, node, &nvkeproto.StartKubernetesCertificateRenewalRequest{
OperationId: input.OperationID,
ThresholdDays: int32(input.ThresholdDays),
@@ -74,6 +80,9 @@ func (a *Activities) RenewKubernetesCertificates(
if legacyErr != nil {
return KubernetesCertificateRenewalResult{}, fmt.Errorf("failed to execute legacy certificate renewal on node %s: %w", node.Name, legacyErr)
}
if err := a.releaseCertificateRenewal(ctx, node, input.OperationID); err != nil {
return KubernetesCertificateRenewalResult{}, err
}
return KubernetesCertificateRenewalResult(legacy), nil
}
if response == nil || response.GetOperation() == nil {
@@ -85,6 +94,12 @@ func (a *Activities) RenewKubernetesCertificates(
for {
result, done, err := certificateRenewalTerminalResult(operation)
if err != nil || done {
phase := operation.GetOperation().GetPhase()
if phase == nvkeproto.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_SUCCEEDED || phase == nvkeproto.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_FAILED {
if releaseErr := a.releaseCertificateRenewal(ctx, node, input.OperationID); releaseErr != nil {
return result, releaseErr
}
}
return result, err
}
if waitBeforePoll {
@@ -172,3 +187,59 @@ func certificateRenewalTerminalResult(
)
}
}
// reserveCertificateRenewal admits actual agent work. Merely scheduling the
// Temporal workflow does not block upgrades. Both callers use the cluster row
// so an agent restart cannot begin between this check and the renewal RPC.
func (a *Activities) reserveCertificateRenewal(ctx context.Context, node db.Node, input *KubernetesCertificateRenewalInput) error {
if !a.cfg.UseControlPlaneControllerForControlPlane() || !node.IsManagedByControlPlaneController() {
return nil
}
return a.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
cluster, err := tx.GetClusterForUpdate(ctx, node.ClusterID)
if err != nil {
return err
}
locked, err := tx.GetNodeForUpdate(ctx, node.ID)
if err != nil {
return err
}
if cluster.Conditions.Deleting.Status == db.ConditionStatusTrue || nodeAgentRemovalRequested(locked) {
return temporal.NewCanceledError("node or cluster is deleting")
}
if cluster.NodeAgentUpgrade != nil {
return fmt.Errorf("node-agent installation is in progress")
}
if active := cluster.CertificateRenewal; active != nil {
if active.NodeID != node.ID {
return fmt.Errorf("certificate renewal is in progress on another node")
}
// A later activity attempt reattaches even if its workflow run changed.
input.OperationID = active.OperationID
return nil
}
cluster.CertificateRenewal = &db.NodeAgentCertificateRenewal{NodeID: node.ID, OperationID: input.OperationID}
_, err = tx.UpdateCluster(ctx, &cluster)
return err
})
}
func (a *Activities) releaseCertificateRenewal(ctx context.Context, node db.Node, operationID string) error {
if !a.cfg.UseControlPlaneControllerForControlPlane() || !node.IsManagedByControlPlaneController() {
return nil
}
return a.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
cluster, err := tx.GetClusterForUpdate(ctx, node.ClusterID)
if errors.Is(err, db.ErrNotFound) {
return nil
}
if err != nil {
return err
}
if active := cluster.CertificateRenewal; active != nil && active.NodeID == node.ID && active.OperationID == operationID {
cluster.CertificateRenewal = nil
_, err = tx.UpdateCluster(ctx, &cluster)
}
return err
})
}
@@ -194,3 +194,55 @@ func certificateRenewalTestNode() db.Node {
ID: uuid.New(), ClusterID: uuid.New(), Name: "cp-0", ControlPlane: true,
}
}
func TestRenewalAdmissionAndRecovery(t *testing.T) {
for _, test := range []struct {
name string
upgrade bool
accepted bool
statusError bool
phase nvkeproto.NodeAgentOperationPhase
wantRetained bool
wantError string
}{
{name: "upgrade blocks renewal before its first RPC", upgrade: true, wantError: "installation is in progress"},
{name: "completed renewal releases admission", phase: nvkeproto.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_SUCCEEDED},
{name: "lost response retains accepted work", statusError: true, phase: nvkeproto.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_RUNNING, wantRetained: true, wantError: "connection lost"},
{name: "later workflow reattaches to accepted work", accepted: true, phase: nvkeproto.NodeAgentOperationPhase_NODE_AGENT_OPERATION_PHASE_SUCCEEDED},
} {
t.Run(test.name, func(t *testing.T) {
node := certificateRenewalTestNode()
database := &agentAdmissionDatabase{cluster: db.Cluster{ID: node.ClusterID}, node: node}
if test.upgrade {
database.cluster.NodeAgentUpgrade = &db.NodeAgentUpgrade{NodeID: node.ID, TargetVersion: "v0.1.2", Method: "apt", Phase: "Running"}
}
if test.accepted {
database.cluster.CertificateRenewal = &db.NodeAgentCertificateRenewal{NodeID: node.ID, OperationID: "accepted-operation"}
}
fake := &agenttest.FakeClient{
StartKubernetesCertificateRenewalHook: func(_ db.Node, req *nvkeproto.StartKubernetesCertificateRenewalRequest) (*nvkeproto.StartKubernetesCertificateRenewalResponse, error) {
require.False(t, test.upgrade, "renewal must not call the agent during an upgrade")
require.True(t, database.mu.TryLock(), "renewal RPC must not hold the database transaction")
require.NotNil(t, database.cluster.CertificateRenewal, "record admission before the RPC")
require.Equal(t, req.GetOperationId(), database.cluster.CertificateRenewal.OperationID)
if test.accepted {
require.Equal(t, "accepted-operation", req.GetOperationId())
}
database.mu.Unlock()
return certificateRenewalStartResponse(req.GetOperationId(), test.phase, nvkeproto.KubernetesCertificateRenewalOperation_OUTCOME_RENEWED, ""), nil
},
GetKubernetesCertificateRenewalHook: func(db.Node, *nvkeproto.GetKubernetesCertificateRenewalStatusRequest) (*nvkeproto.GetKubernetesCertificateRenewalStatusResponse, error) {
return nil, status.Error(codes.Unavailable, "connection lost")
},
}
a := &Activities{cfg: config.Config{ProvisionControlPlaneWithControlPlaneController: true}, db: database, nodeAgentClient: fake}
_, err := executeCertificateRenewalActivity(t, a, KubernetesCertificateRenewalInput{NodeID: node.ID, OperationID: "new-operation", ThresholdDays: 14})
if test.wantError == "" {
require.NoError(t, err)
} else {
require.ErrorContains(t, err, test.wantError)
}
require.Equal(t, test.wantRetained, database.cluster.CertificateRenewal != nil)
})
}
}
@@ -0,0 +1,129 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package activities
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"go.temporal.io/sdk/temporal"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
)
// EnsureNodeAgentVersionInput carries the immutable lifecycle target.
type EnsureNodeAgentVersionInput struct {
NodeID uuid.UUID
Version string
Method string
}
// EnsureNodeAgentVersion performs one step and retries until the target runs.
func (a *Activities) EnsureNodeAgentVersion(ctx context.Context, input EnsureNodeAgentVersionInput) error {
if input.Version == "" {
return nil
}
node, err := a.db.GetNode(ctx, input.NodeID)
if err != nil {
return err
}
if !node.IsManagedByControlPlaneController() {
return nil
}
if nodeAgentRemovalRequested(node) {
return temporal.NewCanceledError("node-agent convergence canceled by node removal")
}
if err := a.reserveLifecycleAgentUpgrade(ctx, node, input); err != nil {
return err
}
// Save admission before the RPC, but do not hold a database lock while the
// agent replaces itself. Deletion must remain free to proceed.
callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
version, done, callErr := a.nodeAgentClient.ConvergeNodeAgent(callCtx, node, input.Version, input.Method)
cancel()
if done && callErr == nil && version != input.Version {
callErr = fmt.Errorf("node agent reports %q, expected %q", version, input.Version)
}
err = a.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
cluster, err := tx.GetClusterForUpdate(ctx, node.ClusterID)
if err != nil {
return err
}
active := cluster.NodeAgentUpgrade
if active == nil || active.NodeID != node.ID || active.Source != db.NodeAgentUpgradeSourceLifecycle {
return temporal.NewCanceledError("node-agent lifecycle target is no longer active")
}
locked, err := tx.GetNodeForUpdate(ctx, node.ID)
if err != nil {
return err
}
if version != "" {
locked.AgentVersion = version
if _, err := tx.UpdateNode(ctx, &locked); err != nil {
return fmt.Errorf("persisting agent observation: %w", err)
}
}
active.Phase = "Running"
if callErr != nil {
active.ErrorMessage = callErr.Error()
}
if done && callErr == nil {
cluster.NodeAgentUpgrade = nil
}
_, err = tx.UpdateCluster(ctx, &cluster)
return err
})
if err != nil {
return err
}
if callErr != nil {
return callErr
}
if !done {
return fmt.Errorf("node-agent convergence is in progress")
}
return nil
}
// reserveLifecycleAgentUpgrade saves the selected node before an upgrade RPC can start its updater.
func (a *Activities) reserveLifecycleAgentUpgrade(ctx context.Context, node db.Node, input EnsureNodeAgentVersionInput) error {
return a.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
cluster, err := tx.GetClusterForUpdate(ctx, node.ClusterID)
if err != nil {
return err
}
locked, err := tx.GetNodeForUpdate(ctx, node.ID)
if err != nil {
return err
}
if cluster.Conditions.Deleting.Status == db.ConditionStatusTrue || nodeAgentRemovalRequested(locked) {
return temporal.NewCanceledError("node or cluster is deleting")
}
if active := cluster.NodeAgentUpgrade; active != nil {
if active.NodeID != node.ID || active.Source != db.NodeAgentUpgradeSourceLifecycle || active.TargetVersion != input.Version || active.Method != input.Method {
return fmt.Errorf("another control-plane operation is active")
}
return nil
}
if cluster.CertificateRenewal != nil || cluster.Conditions.UpdateInProgress != nil {
return fmt.Errorf("control-plane maintenance is active")
}
cluster.NodeAgentUpgrade = &db.NodeAgentUpgrade{
Source: db.NodeAgentUpgradeSourceLifecycle,
NodeID: node.ID,
TargetVersion: input.Version,
Method: input.Method,
Phase: "Pending",
}
_, err = tx.UpdateCluster(ctx, &cluster)
return err
})
}
func nodeAgentRemovalRequested(node db.Node) bool {
return node.Conditions.DeleteRequested.Status == db.ConditionStatusTrue || node.Conditions.Deleting.Status == db.ConditionStatusTrue || node.Conditions.MarkedForRepair.Status == db.ConditionStatusTrue || node.Conditions.MarkedForRecycling.Status == db.ConditionStatusTrue
}
@@ -0,0 +1,134 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package activities
import (
"context"
"sync"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"go.temporal.io/sdk/temporal"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/dsx-ai-factory/nvke/controller/internal/agent/agenttest"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
)
type agentAdmissionDatabase struct {
db.DB
mu sync.Mutex
cluster db.Cluster
node db.Node
}
func (d *agentAdmissionDatabase) RunInTx(ctx context.Context, fn func(context.Context, db.Tx) error) error {
d.mu.Lock()
defer d.mu.Unlock()
return fn(ctx, d)
}
func (d *agentAdmissionDatabase) GetClusterForUpdate(context.Context, uuid.UUID) (db.Cluster, error) {
return d.cluster, nil
}
func (d *agentAdmissionDatabase) GetNode(context.Context, uuid.UUID) (db.Node, error) {
return d.node, nil
}
func (d *agentAdmissionDatabase) GetNodeForUpdate(ctx context.Context, id uuid.UUID) (db.Node, error) {
return d.GetNode(ctx, id)
}
func (d *agentAdmissionDatabase) UpdateCluster(_ context.Context, cluster *db.Cluster) (db.Cluster, error) {
d.cluster = *cluster
return *cluster, nil
}
func (d *agentAdmissionDatabase) UpdateNode(_ context.Context, node *db.Node) (db.Node, error) {
d.node = *node
return *node, nil
}
type admissionAgentClient struct {
*agenttest.FakeClient
converge func(context.Context, db.Node, string, string) (string, bool, error)
}
func (c admissionAgentClient) ConvergeNodeAgent(ctx context.Context, node db.Node, target, method string) (string, bool, error) {
return c.converge(ctx, node, target, method)
}
func TestClusterDeletionStopsLifecycleAgentUpgradeRetries(t *testing.T) {
clusterID, nodeID := uuid.New(), uuid.New()
database := &agentAdmissionDatabase{
cluster: db.Cluster{ID: clusterID, Conditions: db.ClusterConditions{Deleting: db.NewCondition(true, "Cluster deletion is pending")}},
node: db.Node{ID: nodeID, ClusterID: clusterID, ControlPlane: true},
}
operations := &Activities{db: database, nodeAgentClient: admissionAgentClient{converge: func(context.Context, db.Node, string, string) (string, bool, error) {
t.Fatal("cluster deletion must not start or resume an agent installation")
return "", false, nil
}}}
err := operations.EnsureNodeAgentVersion(t.Context(), EnsureNodeAgentVersionInput{NodeID: nodeID, Version: "v0.1.2", Method: "apt"})
require.True(t, temporal.IsCanceledError(err))
require.Nil(t, database.cluster.NodeAgentUpgrade)
}
func TestEnsureNodeAgentVersionSavesProgressBeforeRetry(t *testing.T) {
for _, test := range []struct {
name string
done bool
callErr error
wantPhase string
wantError string
}{
{name: "desired version is ready", done: true},
{name: "accepted retry is running", wantPhase: "Running", wantError: "in progress"},
{name: "failed call remains selected", callErr: status.Error(codes.Unavailable, "agent restarting"), wantPhase: "Running", wantError: "agent restarting"},
} {
t.Run(test.name, func(t *testing.T) {
clusterID, nodeID := uuid.New(), uuid.New()
active := &db.NodeAgentUpgrade{Source: db.NodeAgentUpgradeSourceLifecycle, NodeID: nodeID, TargetVersion: "v0.1.2", Method: "apt", Phase: "Running", ErrorMessage: "previous failure"}
database := &agentAdmissionDatabase{cluster: db.Cluster{ID: clusterID, NodeAgentUpgrade: active}, node: db.Node{ID: nodeID, ClusterID: clusterID, ControlPlane: true}}
operations := &Activities{db: database, nodeAgentClient: admissionAgentClient{converge: func(context.Context, db.Node, string, string) (string, bool, error) {
return "v0.1.2", test.done, test.callErr
}}}
err := operations.EnsureNodeAgentVersion(t.Context(), EnsureNodeAgentVersionInput{NodeID: nodeID, Version: "v0.1.2", Method: "apt"})
if test.wantError == "" {
require.NoError(t, err)
} else {
require.ErrorContains(t, err, test.wantError)
}
require.Equal(t, "v0.1.2", database.node.AgentVersion)
if test.wantPhase == "" {
require.Nil(t, database.cluster.NodeAgentUpgrade)
return
}
require.NotNil(t, database.cluster.NodeAgentUpgrade)
require.Equal(t, nodeID, database.cluster.NodeAgentUpgrade.NodeID)
require.Equal(t, test.wantPhase, database.cluster.NodeAgentUpgrade.Phase)
if test.callErr != nil {
require.Equal(t, test.callErr.Error(), database.cluster.NodeAgentUpgrade.ErrorMessage)
} else {
require.Equal(t, "previous failure", database.cluster.NodeAgentUpgrade.ErrorMessage)
}
})
}
}
func TestLifecycleAgentRPCDoesNotHoldDeletionTransaction(t *testing.T) {
clusterID, nodeID := uuid.New(), uuid.New()
database := &agentAdmissionDatabase{cluster: db.Cluster{ID: clusterID}, node: db.Node{ID: nodeID, ClusterID: clusterID, ControlPlane: true}}
operations := &Activities{db: database, nodeAgentClient: admissionAgentClient{converge: func(context.Context, db.Node, string, string) (string, bool, error) {
require.True(t, database.mu.TryLock(), "agent RPC must not hold the database transaction")
database.node.Conditions.Deleting = db.NewCondition(true, "operator requested deletion")
database.mu.Unlock()
return "v0.1.2", false, nil
}}}
err := operations.EnsureNodeAgentVersion(t.Context(), EnsureNodeAgentVersionInput{NodeID: nodeID, Version: "v0.1.2", Method: "apt"})
require.ErrorContains(t, err, "in progress")
require.Equal(t, db.ConditionStatusTrue, database.node.Conditions.Deleting.Status)
}
@@ -16,9 +16,11 @@ import (
)
type NodeProvisioningContext struct {
NodeID uuid.UUID
ConfigProfile string
ManagedByNodePool bool // True when the node is managed by a node pool (has a non-nil node pool ID).
NodeID uuid.UUID
ConfigProfile string
ManagedByNodePool bool // True when the node is managed by a node pool (has a non-nil node pool ID).
NodeAgentVersion string
NodeAgentUpdateMethod string
}
func (a *Activities) GetNodeProvisioningContext(ctx context.Context, nodeID uuid.UUID) (NodeProvisioningContext, error) {
@@ -26,6 +28,10 @@ func (a *Activities) GetNodeProvisioningContext(ctx context.Context, nodeID uuid
if err != nil {
return NodeProvisioningContext{}, wrapProvisioningContextLookupError("node", err)
}
snapshot, err := a.nodeAgentLifecycleSnapshot(ctx, node)
if err != nil {
return NodeProvisioningContext{}, err
}
nodeSet, _, err := nodes.GetNodeContext(ctx, a.db, node)
if err != nil {
@@ -46,9 +52,11 @@ func (a *Activities) GetNodeProvisioningContext(ctx context.Context, nodeID uuid
}
return NodeProvisioningContext{
NodeID: node.ID,
ConfigProfile: configProfile,
ManagedByNodePool: node.IsManagedByNodePool(),
NodeID: node.ID,
ConfigProfile: configProfile,
ManagedByNodePool: node.IsManagedByNodePool(),
NodeAgentVersion: snapshot.Version,
NodeAgentUpdateMethod: snapshot.Method,
}, nil
}
@@ -59,3 +67,38 @@ func wrapProvisioningContextLookupError(resource string, err error) error {
return fmt.Errorf("failed to get %s: %w", resource, err)
}
func (a *Activities) nodeAgentLifecycleSnapshot(ctx context.Context, node db.Node) (db.NodeAgentLifecycle, error) {
if !node.IsManagedByControlPlaneController() {
return db.NodeAgentLifecycle{}, nil
}
var snapshot db.NodeAgentLifecycle
err := a.db.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
locked, err := tx.GetNodeForUpdate(ctx, node.ID)
if err != nil {
return err
}
if locked.NodeAgentLifecycle != nil {
snapshot = *locked.NodeAgentLifecycle
return nil
}
version, err := lifecycleAgentTarget(ctx, tx, locked)
if err != nil {
return err
}
snapshot = db.NodeAgentLifecycle{Version: version, Method: a.cfg.NodeAgent.UpdateMethod}
locked.NodeAgentLifecycle = &snapshot
_, err = tx.UpdateNode(ctx, &locked)
return err
})
return snapshot, err
}
func lifecycleAgentTarget(ctx context.Context, tx db.Tx, node db.Node) (string, error) {
if node.ControlPlaneConfigurationID == uuid.Nil {
cluster, err := tx.GetCluster(ctx, node.ClusterID)
return cluster.ControlPlaneConfig.NodeAgentConfig.Version, err
}
configuration, err := tx.GetControlPlaneConfiguration(ctx, node.ControlPlaneConfigurationID)
return configuration.Config.NodeAgentConfig.Version, err
}
@@ -0,0 +1,43 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package activities
import (
"context"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/dsx-ai-factory/nvke/controller/internal/config"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
"github.com/dsx-ai-factory/nvke/controller/internal/testutil"
)
func TestProvisioningContextKeepsAgentSnapshotThroughJoin(t *testing.T) {
node := db.Node{ID: uuid.New(), ClusterID: uuid.New(), ControlPlane: true, ControlPlaneConfigurationID: uuid.New()}
configuration := db.ControlPlaneConfiguration{Config: db.ControlPlaneConfigSpec{NodeAgentConfig: db.NodeAgentConfig{Version: "v0.1.2"}}}
cluster := db.Cluster{ID: node.ClusterID, ProviderType: db.ProviderTypeCAPI}
database := &testutil.MockDB{MockTx: &testutil.MockTx{}}
database.On("GetNode", mock.Anything, node.ID).Return(node, nil)
database.On("GetCluster", mock.Anything, node.ClusterID).Return(cluster, nil)
database.On("GetControlPlaneConfiguration", mock.Anything, node.ControlPlaneConfigurationID).Return(configuration, nil)
database.On("RunInTx", mock.Anything, mock.Anything).Return(nil)
database.MockTx.On("GetNodeForUpdate", mock.Anything, node.ID).Return(node, nil).Once()
database.MockTx.On("GetControlPlaneConfiguration", mock.Anything, node.ControlPlaneConfigurationID).Return(configuration, nil).Once()
database.MockTx.On("UpdateNode", mock.Anything, mock.Anything).Return(db.Node{}, nil).Run(func(args mock.Arguments) { node = *args.Get(1).(*db.Node) }).Once()
a := &Activities{db: database, cfg: config.Config{NodeAgent: config.NodeAgentConfig{UpdateMethod: "apt"}}}
first, err := a.GetNodeProvisioningContext(context.Background(), node.ID)
require.NoError(t, err)
require.Equal(t, "v0.1.2", first.NodeAgentVersion)
require.Equal(t, "apt", first.NodeAgentUpdateMethod)
// A later desired target and site setting do not replace this node's snapshot.
database.MockTx.On("GetNodeForUpdate", mock.Anything, node.ID).Return(node, nil).Once()
a.cfg.NodeAgent.UpdateMethod = "bundle"
second, err := a.GetNodeProvisioningContext(context.Background(), node.ID)
require.NoError(t, err)
require.Equal(t, first, second)
database.MockTx.AssertExpectations(t)
}
@@ -81,7 +81,7 @@ func ProvisionNode(ctx workflow.Context, input ProvisionNodeInput) error {
}
recordPhase("capi_create", infraProvisionStart, workflow.Now(ctx))
if err := provisionNode(ctx, input, labels); err != nil {
if err := provisionNode(ctx, input, labels, nodeCtx); err != nil {
// Best effort to update the node conditions to indicate the provisioning workflow failed
if err := updateNodeProvisioningMessage(ctx, input.NodeID, fmt.Sprintf("Workflow failed: %s", err)); err != nil {
logger.Error("failed to update node conditions", "error", err)
@@ -188,7 +188,34 @@ func getNodeProvisioningContext(ctx workflow.Context, nodeID uuid.UUID) (activit
return nodeCtx, nil
}
func provisionNode(ctx workflow.Context, input ProvisionNodeInput, labels nodeMetricLabels) error {
func ensureNodeAgentVersion(ctx workflow.Context, nodeCtx activities.NodeProvisioningContext) error {
// GetVersion checks workflow history, not the node-agent version.
// Existing workflows must replay without this new activity.
historyVersion := workflow.GetVersion(ctx, "node-agent-before-preflight", workflow.DefaultVersion, 1)
if historyVersion == workflow.DefaultVersion {
return nil
}
if nodeCtx.NodeAgentVersion == "" {
return nil
}
var a *activities.Activities
input := activities.EnsureNodeAgentVersionInput{
NodeID: nodeCtx.NodeID,
Version: nodeCtx.NodeAgentVersion,
Method: nodeCtx.NodeAgentUpdateMethod,
}
options := workflow.ActivityOptions{
StartToCloseTimeout: time.Minute,
RetryPolicy: &temporal.RetryPolicy{
InitialInterval: 10 * time.Second,
MaximumInterval: time.Minute,
MaximumAttempts: 0, // Retry until the desired agent version runs.
},
}
return workflow.ExecuteActivity(workflow.WithActivityOptions(ctx, options), a.EnsureNodeAgentVersion, input).Get(ctx, nil)
}
func provisionNode(ctx workflow.Context, input ProvisionNodeInput, labels nodeMetricLabels, nodeCtx activities.NodeProvisioningContext) error {
recordPhase := func(phase string, start, end time.Time) {
if !workflow.IsReplaying(ctx) {
metrics.RecordProvisionPhase(labels.ClusterName, labels.NodeType, phase, end.Sub(start))
@@ -205,6 +232,9 @@ func provisionNode(ctx workflow.Context, input ProvisionNodeInput, labels nodeMe
hostPrepStart := workflow.Now(ctx)
endHostPrep := func() { recordPhase("host_preparation", hostPrepStart, workflow.Now(ctx)) }
if err := ensureNodeAgentVersion(ctx, nodeCtx); err != nil {
return fmt.Errorf("converging node agent before preflight: %w", err)
}
if err := waitForNodePreflight(ctx, input.NodeID); err != nil {
endHostPrep()
return fmt.Errorf("failed to wait for node preflight to succeed: %w", err)
@@ -10,6 +10,7 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/testsuite"
"go.temporal.io/sdk/worker"
"go.temporal.io/sdk/workflow"
@@ -237,3 +238,38 @@ func TestProvisionCAPINodeClaimsNodeBeforeCreatingInfraMachine(t *testing.T) {
require.NoError(t, env.GetWorkflowError())
env.AssertExpectations(t)
}
func agentBeforePreflightTestWorkflow(ctx workflow.Context, nodeID uuid.UUID) error {
return provisionNode(ctx, ProvisionNodeInput{NodeID: nodeID}, nodeMetricLabels{}, activities.NodeProvisioningContext{NodeID: nodeID, NodeAgentVersion: "v0.1.2", NodeAgentUpdateMethod: "apt"})
}
func TestProvisioningConvergesAgentBeforePreflight(t *testing.T) {
for _, test := range []struct {
name string
historyVersion workflow.Version
wantUpgrade bool
}{
{name: "new workflow upgrades before preflight", historyVersion: 1, wantUpgrade: true},
{name: "existing workflow keeps its recorded steps", historyVersion: workflow.DefaultVersion},
} {
t.Run(test.name, func(t *testing.T) {
suite := &testsuite.WorkflowTestSuite{}
env := suite.NewTestWorkflowEnvironment()
env.RegisterWorkflow(agentBeforePreflightTestWorkflow)
env.OnGetVersion("node-agent-before-preflight", workflow.DefaultVersion, 1).Return(test.historyVersion)
var a *activities.Activities
nodeID := uuid.New()
completed := false
env.OnActivity(a.WaitForCAPIMachineReady, mock.Anything, mock.Anything).Return("", nil).Once()
if test.wantUpgrade {
env.OnActivity(a.EnsureNodeAgentVersion, mock.Anything, activities.EnsureNodeAgentVersionInput{NodeID: nodeID, Version: "v0.1.2", Method: "apt"}).Return(nil).Run(func(mock.Arguments) { completed = true }).Once()
}
env.OnActivity(a.NodePreflight, mock.Anything, mock.Anything).Return(nil).Run(func(mock.Arguments) { require.Equal(t, test.wantUpgrade, completed) }).Once()
// Stop after preflight so this test does not replace the join workflow tests.
env.OnActivity(a.GetNodeConfigProfile, mock.Anything, mock.Anything).Return(activities.ConfigProfile{}, temporal.NewNonRetryableApplicationError("stop after preflight", "test", nil)).Once()
env.ExecuteWorkflow(agentBeforePreflightTestWorkflow, nodeID)
require.ErrorContains(t, env.GetWorkflowError(), "stop after preflight")
env.AssertExpectations(t)
})
}
}
@@ -907,7 +907,7 @@ func setupWorkflowEnv(t *testing.T, database db.DB, profilesDir string, opts wor
env.OnActivity(a.LabelNode, mock.Anything, mock.Anything).Return(activities.LabelNodeResult{}, nil).Maybe()
drainErr := error(nil)
if opts.failDrainActivity {
drainErr = errors.New("node unreachable")
drainErr = errors.New("eviction blocked by PodDisruptionBudget")
}
env.OnActivity(a.DrainKubeNode, mock.Anything, mock.Anything).Return(drainErr).Maybe()
env.OnActivity(a.DeleteKubeNode, mock.Anything, mock.Anything).Return(opts.deleteKubeNodeErr).Maybe()
@@ -971,3 +971,42 @@ func writeConfigProfile(t *testing.T, profilesDir, name, content string) {
require.NoError(t, os.MkdirAll(dir, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, name+".yaml"), []byte(content), 0o644))
}
func TestClusterTeardownDeletesInfrastructureWhenAgentResetFails(t *testing.T) {
database, res := setupTestDB(t, seedOpts{clusterProvisioned: true, cpNodeJoined: true, omitConfigProfile: true})
env, a := setupWorkflowEnv(t, database, res.profilesDir, workflowEnvOpts{omitClusterRunbookMock: true, omitKubeadmResetMock: true, omitDeleteCAPIMachineMock: true})
env.OnActivity(a.KubeadmReset, mock.Anything, mock.Anything).Return(activities.KubeadmResetResult{}, errors.New("agent connection refused")).Times(3)
env.OnActivity(a.DeleteCAPIMachineForNode, mock.Anything, mock.Anything).Return(nil).Once()
env.ExecuteWorkflow(TeardownNode, TeardownNodeInput{NodeID: res.nodeID, AllowCPNode: true, SkipRemoveFromCluster: true})
require.True(t, env.IsWorkflowCompleted())
require.NoError(t, env.GetWorkflowError())
env.AssertExpectations(t)
_, err := database.GetNode(context.Background(), res.nodeID)
require.ErrorIs(t, err, db.ErrNotFound, "agent failure must not prevent infrastructure and node deletion")
}
func TestNodeDeletionStopsOnCleanupFailureWithoutForceUnreachable(t *testing.T) {
for _, test := range []struct {
name string
opts workflowEnvOpts
wantError string
}{
{name: "PDB blocks drain", opts: workflowEnvOpts{failDrainActivity: true}, wantError: "PodDisruptionBudget"},
{name: "agent cannot shut down gracefully", opts: workflowEnvOpts{failGracefulShutdownStart: true}, wantError: "apiserver stuck"},
} {
t.Run(test.name, func(t *testing.T) {
database, res := setupTestDB(t, seedOpts{clusterProvisioned: true, cpNodeJoined: true, omitConfigProfile: true})
env, _ := setupWorkflowEnv(t, database, res.profilesDir, test.opts)
var activityNames []string
env.SetOnActivityStartedListener(func(info *activity.Info, _ context.Context, _ converter.EncodedValues) {
activityNames = append(activityNames, info.ActivityType.Name)
})
env.ExecuteWorkflow(TeardownNode, TeardownNodeInput{NodeID: res.nodeID, AllowCPNode: true, ForceUnreachable: false})
require.True(t, env.IsWorkflowCompleted())
require.ErrorContains(t, env.GetWorkflowError(), test.wantError)
require.NotContains(t, activityNames, "DeleteCAPIMachineForNode")
_, err := database.GetNode(t.Context(), res.nodeID)
require.NoError(t, err, "failed graceful cleanup must retain the node")
})
}
}
+32
View File
@@ -554,6 +554,38 @@ no network path from the ARC fleet to the site's jump host on port 22 at all —
only the Teleport proxy reaches it — so `qualify-e2e.yml` always
goes through `tsh`.
The `node-agent-upgrade` label selects the controller-driven agent tests. These
tests use real agent bundles and an isolated bundle mirror. They cover upgrades,
downgrades, restoration after a failed installation, automatic retries, target
changes, process restarts, deferred joins, and deletion drains. The tests also
check the agent version before kubeadm and reject TLS clients without an identity.
Workers keep the version baked into the image.
To include the fixtures in a local run, set
`LOCAL_NVKE_E2E_NODE_AGENT_UPGRADE=true`. Use a separate checkout at
`92a3039bae7a12d10244263bff80776d83c2fe72` for the image's old agent. Set
`NODE_AGENT_REPO_PATH` to that checkout's `agent/` directory and
`NODE_AGENT_VERSION=v0.1.990`. The fixtures for the desired versions use the
current checkout. Choose unique names for the management cluster, node image,
and BGP container:
```bash
KIND_CLUSTER_NAME=nvke-agent-upgrade-e2e \
CAPD_NODE_IMAGE=nvke-agent-upgrade-node:local \
CAPD_KINDEST_NODE_IMAGE=nvke-agent-upgrade-node:local \
BGP_CONTAINER_NAME=nvke-agent-upgrade-bgp \
NODE_AGENT_REPO_PATH=/path/to/baseline/agent \
NODE_AGENT_VERSION=v0.1.990 \
LOCAL_NVKE_E2E_NODE_AGENT_UPGRADE=true \
LOCAL_NKE_E2E_LABEL_FILTER=node-agent-upgrade \
PROVISION_CONTROL_PLANE_WITH_CONTROL_PLANE_CONTROLLER=true \
flox activate -- bash controller/hack/local-backend-e2e.sh
```
If the Docker host already runs, set `LOCAL_NVKE_E2E_REUSE_DOCKER_HOST=true`
to reuse it without changing the host configuration. The test repairs only its
private fixture artifact. It does not change a released bundle.
## OIDC acceptance
From `controller/`, run `make test-oidc-reference` to check NVKE's rendered
@@ -161,3 +161,15 @@ func (c *Client) UpdateOIDC(ctx context.Context, id openapi_types.UUID, enable b
}
return resp, nil
}
// UpdateNodeAgentVersion changes the desired control-plane agent version.
func (c *Client) UpdateNodeAgentVersion(ctx context.Context, id openapi_types.UUID, version string) (*api.Cluster, error) {
response, err := c.api.UpdateClusterWithResponse(ctx, id, api.UpdateClusterRequest{ControlPlaneConfig: &api.UpdateClusterControlPlaneConfig{NodeAgentConfig: &api.NodeAgentConfig{Version: &version}}})
if err != nil {
return nil, fmt.Errorf("updating desired agent version: %w", err)
}
if response.StatusCode() != 200 || response.JSON200 == nil {
return nil, fmt.Errorf("updating desired agent version: %s: %s", response.Status(), response.Body)
}
return response.JSON200, nil
}
+12
View File
@@ -213,3 +213,15 @@ func waitForDeploymentRollout(ctx context.Context, c client.Client, namespace, n
deploy.Status.AvailableReplicas == desired, nil
})
}
// SetNodeAgentUpdateMethod configures the isolated test controller installation method.
func SetNodeAgentUpdateMethod(ctx context.Context, c client.Client, method string) (string, bool, error) {
previous, written, err := setControllerSetting(ctx, c, "nodeAgent.updateMethod", method)
value, _ := previous.(string)
return value, written, err
}
// RestartNodeAgentTestController restarts the isolated controller without changing desired state.
func RestartNodeAgentTestController(ctx context.Context, c client.Client) error {
return restartController(ctx, c)
}
@@ -160,3 +160,27 @@ func TestSetControllerSettingReportsTheWrite(t *testing.T) {
})
}
}
func TestNodeAgentMethodReportsWriteWhenRestartFails(t *testing.T) {
t.Parallel()
scheme := runtime.NewScheme()
require.NoError(t, appsv1.AddToScheme(scheme))
require.NoError(t, corev1.AddToScheme(scheme))
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{Namespace: controller.Namespace(), Name: ControllerConfigMap},
Data: map[string]string{controllerConfigKey: "nodeAgent:\n updateMethod: apt\npermissiveMode: false\n"},
}
c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cm).Build()
previous, written, err := SetNodeAgentUpdateMethod(t.Context(), c, "bundle")
require.ErrorContains(t, err, "getting NVKE deployment")
require.True(t, written, "cleanup must restore the old method after a failed restart")
require.Equal(t, "apt", previous)
var stored corev1.ConfigMap
require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(cm), &stored))
method, err := ControllerSetting(stored.Data, "nodeAgent.updateMethod")
require.NoError(t, err)
require.Equal(t, "bundle", method)
mode, err := ControllerSetting(stored.Data, permissiveModeKey)
require.NoError(t, err)
require.Equal(t, false, mode)
}
+6 -2
View File
@@ -77,8 +77,9 @@ type ControlPlane struct {
// CAPD supplies the CAPI machine template from an embedded skeleton. NICo VMs
// fill the Forge fields below instead.
type ControlPlaneConfigSpec struct {
DesiredCount int
MaxSurge *int
NodeAgentVersion string
DesiredCount int
MaxSurge *int
InstanceTypeID string
OSProfile string
@@ -506,6 +507,9 @@ func buildCAPDControlPlaneConfig(spec ClusterSpec) (*api.CreateClusterControlPla
if err := json.Unmarshal(capdControlPlaneConfigJSON, &cfg); err != nil {
return nil, fmt.Errorf("unmarshaling control plane config skeleton: %w", err)
}
if spec.ControlPlane.Config.NodeAgentVersion != "" {
cfg.NodeAgentConfig = &api.NodeAgentConfig{Version: &spec.ControlPlane.Config.NodeAgentVersion}
}
cfg.DesiredCount = spec.ControlPlane.Config.DesiredCount
cfg.MaxSurge = spec.ControlPlane.Config.MaxSurge
if spec.ControlPlane.Config.SystemReservedMemory != "" {
@@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package e2e
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"github.com/dsx-ai-factory/nvke/controller/api"
)
func TestUnit_AgentUpgradeCleanupContinuesAfterContainerStops(t *testing.T) {
root := t.TempDir()
calls := filepath.Join(root, "calls")
fakeDocker := `#!/bin/sh
case "$1" in
ps)
case "$5" in
*stopping*) printf '%s\n' stopping ;;
*surviving*) printf '%s\n' surviving ;;
esac
;;
exec)
printf '%s\n' "$2" >> "$AGENT_CLEANUP_TEST_CALLS"
case "$2" in stopping) exit 1 ;; esac
;;
esac
`
require.NoError(t, os.WriteFile(filepath.Join(root, "docker"), []byte(fakeDocker), 0o700))
t.Setenv("PATH", root+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("AGENT_CLEANUP_TEST_CALLS", calls)
cleanupAgentInstallations(t.Context(), []api.Node{{Name: "stopping"}, {Name: "surviving"}})
released, err := os.ReadFile(calls)
require.NoError(t, err)
require.Equal(t, "stopping\nsurviving\n", string(released))
}
@@ -0,0 +1,423 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package e2e
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/dsx-ai-factory/nvke/controller/api"
"github.com/dsx-ai-factory/nvke/controller/test/e2e/internal/nvke"
)
const agentFixtureInitial = "v0.1.991"
// agentInstallationState is the durable state written by either installation path.
type agentInstallationState struct {
TargetVersion string `json:"targetVersion"`
PreviousVersion string `json:"previousVersion"`
Method string `json:"method"`
Phase string `json:"phase"`
ErrorMessage string `json:"errorMessage"`
CreatedAt time.Time `json:"createdAt"`
}
func validateNodeAgentUpgrade(test *tenantTest) {
It("installs the desired agent before kubeadm and authenticates fresh observations", func(ctx context.Context) {
nodes := expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true))
Expect(nodes).To(HaveLen(3))
for _, node := range nodes {
container := expectSucceed(nodeContainerName(ctx, node.Name))
recorded := expectSucceed(agentDockerOutput(ctx, "exec", container, "cat", "/var/lib/nvke/e2e-kubeadm-agent-versions.log"))
Expect(strings.Fields(recorded)).NotTo(BeEmpty())
for _, line := range strings.Split(strings.TrimSpace(recorded), "\n") {
Expect(line).To(ContainSubstring(agentFixtureInitial), "kubeadm must run with the lifecycle target")
}
state := expectSucceed(readAgentInstallation(ctx, node, agentFixtureInitial))
Expect(state.Phase).To(Equal("Succeeded"))
Expect(state.PreviousVersion).To(Equal("v0.1.990"))
// The image fixture must exercise bootstrap before later native installations.
Expect(runDockerCommand(ctx, "exec", container, "test", "-f", "/var/lib/nvke/agent-upgrades/"+agentFixtureInitial+"_bundle/updater.py")).To(Succeed())
// A connection with no client identity must not obtain an agent response.
probe := `import socket,ssl
s=socket.create_connection(('127.0.0.1',15005),timeout=5)
c=ssl._create_unverified_context()
try:
t=c.wrap_socket(s,server_hostname='agent');t.sendall(b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n');reply=t.recv(1024)
if reply: raise RuntimeError('unauthenticated TLS received application data')
except (ssl.SSLError,ConnectionResetError): pass
`
Expect(runDockerCommand(ctx, "exec", container, "python3", "-c", probe)).To(Succeed())
}
waitForAgentConvergence(ctx, test, agentFixtureInitial, 3)
assertWorkerAgentVersions(ctx, test)
}, NodeTimeout(10*time.Minute))
It("upgrades one joined control-plane agent at a time", func(ctx context.Context) {
nodes := expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true))
holdAgentInstallations(ctx, nodes)
DeferCleanup(cleanupAgentInstallations, nodes)
expectSucceed(test.nvke.UpdateNodeAgentVersion(ctx, test.cluster.ID, "v0.1.992"))
seen := map[string]bool{}
for range nodes {
active := waitForAgentReservation(ctx, test, "v0.1.992")
Expect(seen[active.NodeID.String()]).To(BeFalse(), "the completed node must not be selected again")
selected := agentNodeByID(nodes, active.NodeID.String())
Eventually(func(ctx context.Context) error {
return assertOnlyAgentInstallationActive(ctx, nodes, selected, "v0.1.992")
}).WithContext(ctx).WithTimeout(2 * time.Minute).WithPolling(time.Second).Should(Succeed())
Consistently(func(ctx context.Context) error {
return assertOnlyAgentInstallationActive(ctx, nodes, selected, "v0.1.992")
}).WithContext(ctx).WithTimeout(10 * time.Second).WithPolling(time.Second).Should(Succeed())
releaseAgentInstallations(ctx, []api.Node{selected})
Eventually(func(ctx context.Context) error {
return assertAgentBinaryVersion(ctx, selected, "v0.1.992")
}).WithContext(ctx).WithTimeout(3 * time.Minute).WithPolling(time.Second).Should(Succeed())
seen[selected.ID.String()] = true
Eventually(func(ctx context.Context) bool {
current, err := test.nvke.GetCluster(ctx, test.cluster.ID)
return err == nil && (current.NodeAgentUpgrade == nil || current.NodeAgentUpgrade.NodeID != selected.ID)
}).WithContext(ctx).WithTimeout(2 * time.Minute).WithPolling(time.Second).Should(BeTrue())
}
waitForAgentConvergence(ctx, test, "v0.1.992", 3)
assertWorkerAgentVersions(ctx, test)
}, NodeTimeout(15*time.Minute))
It("downgrades through the same controller path", func(ctx context.Context) {
expectSucceed(test.nvke.UpdateNodeAgentVersion(ctx, test.cluster.ID, agentFixtureInitial))
waitForAgentConvergence(ctx, test, agentFixtureInitial, 3)
assertWorkerAgentVersions(ctx, test)
}, NodeTimeout(10*time.Minute))
It("restores a failed installation and retries the same node until the desired version converges", func(ctx context.Context) {
nodes := expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true))
expectSucceed(test.nvke.UpdateNodeAgentVersion(ctx, test.cluster.ID, "v0.1.993"))
active := waitForAgentReservation(ctx, test, "v0.1.993")
selected := agentNodeByID(nodes, active.NodeID.String())
Eventually(func(ctx context.Context) error {
state, err := readAgentInstallation(ctx, selected, "v0.1.993")
if err != nil {
return err
}
if state.Phase != "FailedRestored" {
return fmt.Errorf("installation phase is %s", state.Phase)
}
if state.ErrorMessage == "" {
return fmt.Errorf("failure was not recorded")
}
return assertAgentBinaryVersion(ctx, selected, agentFixtureInitial)
}).WithContext(ctx).WithTimeout(3 * time.Minute).WithPolling(200 * time.Millisecond).Should(Succeed())
Eventually(func(ctx context.Context) bool {
cluster, err := test.nvke.GetCluster(ctx, test.cluster.ID)
return err == nil && cluster.NodeAgentUpgrade != nil && cluster.NodeAgentUpgrade.NodeID == selected.ID && cluster.NodeAgentUpgrade.Phase == "Running" && cluster.NodeAgentUpgrade.ErrorMessage != ""
}).WithContext(ctx).WithTimeout(2 * time.Minute).WithPolling(time.Second).Should(BeTrue())
Consistently(func(ctx context.Context) error {
cluster, err := test.nvke.GetCluster(ctx, test.cluster.ID)
if err != nil {
return err
}
if cluster.NodeAgentUpgrade == nil || cluster.NodeAgentUpgrade.NodeID != selected.ID {
return fmt.Errorf("failed installation lost its selected node")
}
for _, node := range nodes {
if node.ID != selected.ID {
if err := assertAgentBinaryVersion(ctx, node, agentFixtureInitial); err != nil {
return err
}
}
}
return nil
}).WithContext(ctx).WithTimeout(40 * time.Second).WithPolling(2 * time.Second).Should(Succeed())
// Repair only this run's artifact. No cluster update or operator retry follows.
volume := os.Getenv("NVKE_E2E_NODE_AGENT_BUNDLE_VOLUME")
Expect(volume).NotTo(BeEmpty())
Expect(runDockerCommand(ctx, "run", "--rm", "-v", volume+":/bundle", "alpine:3.22", "sh", "-ec", "cp /bundle/agent-e2e/repaired.tgz /bundle/agent-e2e/repaired.next; mv /bundle/agent-e2e/repaired.next /bundle/agent-e2e/agent_v0.1.993.tgz")).To(Succeed())
waitForAgentConvergence(ctx, test, "v0.1.993", 3)
assertWorkerAgentVersions(ctx, test)
}, NodeTimeout(15*time.Minute))
It("drains an accepted target across restarts and defers a new join until installation ends", func(ctx context.Context) {
nodes := expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true))
holdAgentInstallations(ctx, nodes)
DeferCleanup(cleanupAgentInstallations, nodes)
expectSucceed(test.nvke.UpdateNodeAgentVersion(ctx, test.cluster.ID, "v0.1.992"))
active := waitForAgentReservation(ctx, test, "v0.1.992")
selected := agentNodeByID(nodes, active.NodeID.String())
Eventually(func(ctx context.Context) error {
return assertOnlyAgentInstallationActive(ctx, nodes, selected, "v0.1.992")
}).WithContext(ctx).WithTimeout(2 * time.Minute).WithPolling(time.Second).Should(Succeed())
original := expectSucceed(readAgentInstallation(ctx, selected, "v0.1.992"))
container := expectSucceed(nodeContainerName(ctx, selected.Name))
Expect(runDockerCommand(ctx, "exec", container, "systemctl", "restart", "nvke-agent.service")).To(Succeed())
Expect(nvke.RestartNodeAgentTestController(ctx, test.k8sClient)).To(Succeed())
expectSucceed(test.nvke.UpdateNodeAgentVersion(ctx, test.cluster.ID, agentFixtureInitial))
expectSucceed(test.nvke.UpdateControlPlaneDesiredCount(ctx, test.cluster.ID, 4))
test.spec.ControlPlane.Config.DesiredCount = 4
Consistently(func(ctx context.Context) error {
current, err := test.nvke.GetCluster(ctx, test.cluster.ID)
if err != nil {
return err
}
if current.NodeAgentUpgrade == nil || current.NodeAgentUpgrade.NodeID != selected.ID || current.NodeAgentUpgrade.TargetVersion != "v0.1.992" {
return fmt.Errorf("accepted target changed before installation completed")
}
state, err := readAgentInstallation(ctx, selected, "v0.1.992")
if err != nil {
return err
}
if state.CreatedAt != original.CreatedAt {
return fmt.Errorf("restart replaced the accepted installation")
}
actual, err := test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true)
if err != nil {
return err
}
joined := 0
for _, node := range actual {
if node.Conditions.Joined.Status == api.ConditionStatusTrue {
joined++
}
}
if joined != 3 {
return fmt.Errorf("a node joined while installation was active")
}
return assertOnlyAgentInstallationActive(ctx, nodes, selected, "v0.1.992")
}).WithContext(ctx).WithTimeout(20 * time.Second).WithPolling(time.Second).Should(Succeed())
releaseAgentInstallations(ctx, nodes)
waitForAgentConvergence(ctx, test, agentFixtureInitial, 4)
for _, node := range expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true)) {
container := expectSucceed(nodeContainerName(ctx, node.Name))
recorded := expectSucceed(agentDockerOutput(ctx, "exec", container, "cat", "/var/lib/nvke/e2e-kubeadm-agent-versions.log"))
Expect(recorded).To(ContainSubstring(agentFixtureInitial))
}
assertWorkerAgentVersions(ctx, test)
}, NodeTimeout(20*time.Minute))
It("drains an accepted installation before replacing a deleted control-plane node", func(ctx context.Context) {
nodes := expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true))
holdAgentInstallations(ctx, nodes)
DeferCleanup(cleanupAgentInstallations, nodes)
expectSucceed(test.nvke.UpdateNodeAgentVersion(ctx, test.cluster.ID, "v0.1.992"))
active := waitForAgentReservation(ctx, test, "v0.1.992")
selected := agentNodeByID(nodes, active.NodeID.String())
Eventually(func(ctx context.Context) error {
return assertOnlyAgentInstallationActive(ctx, nodes, selected, "v0.1.992")
}).WithContext(ctx).WithTimeout(2 * time.Minute).WithPolling(time.Second).Should(Succeed())
Expect(test.nvke.DeleteNode(ctx, selected.ID)).To(Succeed())
Consistently(func(ctx context.Context) error {
actual, err := test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true)
if err != nil {
return err
}
found := false
for _, node := range actual {
if node.ID == selected.ID {
found = true
if node.Conditions.Deleting.Status == "True" {
return fmt.Errorf("node teardown started before the accepted installation drained")
}
}
}
if !found {
return fmt.Errorf("selected node was removed before installation ended")
}
return assertOnlyAgentInstallationActive(ctx, nodes, selected, "v0.1.992")
}).WithContext(ctx).WithTimeout(20 * time.Second).WithPolling(time.Second).Should(Succeed())
releaseAgentInstallations(ctx, nodes)
Eventually(func(ctx context.Context) bool {
actual, err := test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true)
if err != nil {
return false
}
for _, node := range actual {
if node.ID == selected.ID {
return false
}
}
return len(actual) == 4
}).WithContext(ctx).WithTimeout(10 * time.Minute).WithPolling(2 * time.Second).Should(BeTrue())
waitForAgentConvergence(ctx, test, "v0.1.992", 4)
assertWorkerAgentVersions(ctx, test)
}, NodeTimeout(20*time.Minute))
}
func agentDockerOutput(ctx context.Context, args ...string) (string, error) {
command := exec.CommandContext(ctx, "docker", args...)
output, err := command.CombinedOutput()
if err != nil {
return "", commandError(command, err, output)
}
return strings.TrimSpace(string(output)), nil
}
func assertAgentBinaryVersion(ctx context.Context, node api.Node, version string) error {
container, err := nodeContainerName(ctx, node.Name)
if err != nil {
return err
}
output, err := agentDockerOutput(ctx, "exec", container, "/usr/local/bin/nvke-agent", "--version")
if err != nil {
return err
}
fields := strings.Fields(output)
if len(fields) == 0 || fields[len(fields)-1] != version {
return fmt.Errorf("node %s agent version: %s; want %s", node.Name, output, version)
}
return nil
}
func readAgentInstallation(ctx context.Context, node api.Node, target string) (agentInstallationState, error) {
container, err := nodeContainerName(ctx, node.Name)
if err != nil {
return agentInstallationState{}, err
}
output, err := agentDockerOutput(ctx, "exec", container, "cat", "/var/lib/nvke/agent-upgrades/"+target+"_bundle/operation.json")
if err != nil {
return agentInstallationState{}, err
}
var state agentInstallationState
err = json.Unmarshal([]byte(output), &state)
return state, err
}
func agentNodeByID(nodes []api.Node, id string) api.Node {
for _, node := range nodes {
if node.ID.String() == id {
return node
}
}
Fail("selected node is absent: " + id)
return api.Node{}
}
func waitForAgentReservation(ctx context.Context, test *tenantTest, target string) api.NodeAgentUpgradeStatus {
var state api.NodeAgentUpgradeStatus
Eventually(func(ctx context.Context) bool {
cluster, err := test.nvke.GetCluster(ctx, test.cluster.ID)
if err != nil || cluster.NodeAgentUpgrade == nil || cluster.NodeAgentUpgrade.TargetVersion != target {
return false
}
state = *cluster.NodeAgentUpgrade
return true
}).WithContext(ctx).WithTimeout(2 * time.Minute).WithPolling(time.Second).Should(BeTrue())
return state
}
func waitForAgentConvergence(ctx context.Context, test *tenantTest, target string, count int) {
Eventually(func(ctx context.Context) error {
cluster, err := test.nvke.GetCluster(ctx, test.cluster.ID)
if err != nil {
return err
}
if cluster.NodeAgentUpgrade != nil {
return fmt.Errorf("agent convergence is active: %+v", cluster.NodeAgentUpgrade)
}
nodes, err := test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true)
if err != nil {
return err
}
if len(nodes) != count {
return fmt.Errorf("control-plane count is %d, want %d", len(nodes), count)
}
for _, node := range nodes {
if err := assertAgentBinaryVersion(ctx, node, target); err != nil {
return err
}
}
return test.assertDesiredNodesReady(ctx)
}).WithContext(ctx).WithTimeout(10 * time.Minute).WithPolling(2 * time.Second).Should(Succeed())
}
func assertWorkerAgentVersions(ctx context.Context, test *tenantTest) {
for _, node := range expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, false)) {
Expect(assertAgentBinaryVersion(ctx, node, "v0.1.990")).To(Succeed())
}
}
func holdAgentInstallations(ctx context.Context, nodes []api.Node) {
for _, node := range nodes {
container := expectSucceed(nodeContainerName(ctx, node.Name))
Expect(runDockerCommand(ctx, "exec", container, "sh", "-ec", `mkdir -p /etc/systemd/system/nvke-agent-updater@.service.d; touch /var/lib/nvke/e2e-agent-hold; printf '%s\n' '[Service]' "ExecStartPre=/bin/sh -c 'while [ -f /var/lib/nvke/e2e-agent-hold ]; do sleep 1; done'" >/etc/systemd/system/nvke-agent-updater@.service.d/qualification.conf; systemctl daemon-reload`)).To(Succeed())
}
}
func releaseAgentInstallations(ctx context.Context, nodes []api.Node) {
for _, node := range nodes {
container, err := nodeContainerName(ctx, node.Name)
if err != nil {
continue
}
Expect(runDockerCommand(ctx, "exec", container, "rm", "-f", "/var/lib/nvke/e2e-agent-hold")).To(Succeed())
}
}
func cleanupAgentInstallations(ctx context.Context, nodes []api.Node) {
for _, node := range nodes {
container, err := nodeContainerName(ctx, node.Name)
if err != nil {
continue
}
if err := runDockerCommand(ctx, "exec", container, "rm", "-f", "/var/lib/nvke/e2e-agent-hold"); err != nil {
GinkgoLogr.Info("releasing agent hold during cleanup failed", "node", node.Name, "error", err)
}
}
}
func assertOnlyAgentInstallationActive(ctx context.Context, nodes []api.Node, selected api.Node, target string) error {
active := 0
for _, node := range nodes {
container, err := nodeContainerName(ctx, node.Name)
if err != nil {
return err
}
output, err := agentDockerOutput(ctx, "exec", container, "systemctl", "show", "--property=ActiveState", "--value", "nvke-agent-updater@"+target+"_bundle.service")
if err != nil {
return err
}
if output == "activating" || output == "active" || output == "deactivating" {
active++
if node.ID != selected.ID {
return fmt.Errorf("another node started an installation: %s", node.Name)
}
}
}
if active != 1 {
return fmt.Errorf("active installations: %d, want exactly one", active)
}
return nil
}
func deleteClusterWithAgentDrain(ctx context.Context, test *tenantTest, accepted *bool) {
nodes := expectSucceed(test.nvke.ListClusterNodesByControlPlane(ctx, test.cluster.ID, true))
holdAgentInstallations(ctx, nodes)
DeferCleanup(cleanupAgentInstallations, nodes)
expectSucceed(test.nvke.UpdateNodeAgentVersion(ctx, test.cluster.ID, agentFixtureInitial))
active := waitForAgentReservation(ctx, test, agentFixtureInitial)
selected := agentNodeByID(nodes, active.NodeID.String())
Eventually(func(ctx context.Context) error {
return assertOnlyAgentInstallationActive(ctx, nodes, selected, agentFixtureInitial)
}).WithContext(ctx).WithTimeout(2 * time.Minute).WithPolling(time.Second).Should(Succeed())
Expect(test.lifecycle.DeleteCluster(ctx, test.cluster.ID)).To(Succeed())
*accepted = true
Consistently(func(ctx context.Context) error {
for _, node := range nodes {
if _, err := nodeContainerName(ctx, node.Name); err != nil {
return fmt.Errorf("cluster deletion removed a node before draining installation: %w", err)
}
}
return assertOnlyAgentInstallationActive(ctx, nodes, selected, agentFixtureInitial)
}).WithContext(ctx).WithTimeout(20 * time.Second).WithPolling(time.Second).Should(Succeed())
// Lose the host while its installer is held. Cluster deletion must finish
// without an agent response or completion of the accepted installation.
container := expectSucceed(nodeContainerName(ctx, selected.Name))
Expect(runDockerCommand(ctx, "stop", "--time", "0", container)).To(Succeed())
Expect(test.lifecycle.WaitForClusterDeleted(ctx, test.cluster.ID)).To(Succeed())
}
+30 -2
View File
@@ -82,6 +82,12 @@ var _ = DescribeTableSubtree("NVKE with backend", withNicoVMSOSProfileEntries(
// nodes for its scale, rotation, and certificate checks; the core lane only
// proves that the deployed controller's control-plane path can create a usable
// cluster and delete it again.
Entry("CAPD node-agent convergence", Ordered, ContinueOnFailure, Label("node-agent-upgrade"), testSpec{
buildSpec: capdSpec,
shape: clusterShape{controlPlaneConfig: &nvke.ControlPlaneConfigSpec{DesiredCount: 3, NodeAgentVersion: "v0.1.991", SystemReservedMemory: "1Gi"}, workerPools: []nvke.NodePoolSpec{{DesiredNodeCount: 1}}},
options: nvke.Options{Provision: 15 * time.Minute, Delete: 5 * time.Minute, Poll: 2 * time.Second},
validate: validations{provisioningOnly: true, nodeAgentUpgrade: true},
}),
Entry("CAPD core", Ordered, ContinueOnFailure, Label("core", "core-docker"), testSpec{
buildSpec: capdSpec,
shape: clusterShape{
@@ -489,7 +495,9 @@ func tenantSubtree(resolve managementResolver) func(spec testSpec) {
// AfterAll below spent a second full budget on the same cluster.
// It stays false when the delete request itself failed, so the
// AfterAll still retries a delete the controller never took.
deleteAccepted bool
deleteAccepted bool
previousAgentMethod string
agentMethodChanged bool
)
// Record any spec failure so the cluster delete can honor preserveOnFailure.
@@ -513,6 +521,12 @@ func tenantSubtree(resolve managementResolver) func(spec testSpec) {
By("Creating the brownfield cluster with the controller OIDC create-default turned off")
Expect(nvke.SetOIDCEnabled(ctx, test.k8sClient, false)).To(Succeed())
}
if spec.validate.nodeAgentUpgrade {
Expect(os.Getenv("NVKE_E2E_NODE_AGENT_UPGRADE")).To(Equal("true"), "requires isolated node-agent fixtures")
var methodErr error
previousAgentMethod, agentMethodChanged, methodErr = nvke.SetNodeAgentUpdateMethod(ctx, test.k8sClient, "bundle")
Expect(methodErr).NotTo(HaveOccurred())
}
test.initCluster(ctx, spec)
}, Label("lifecycle"), NodeTimeout(2*time.Hour))
@@ -530,6 +544,9 @@ func tenantSubtree(resolve managementResolver) func(spec testSpec) {
if spec.validate.tpmAttestation {
validateTPMAttestationPostCreate(&test)
}
if spec.validate.nodeAgentUpgrade {
validateNodeAgentUpgrade(&test)
}
if spec.validate.openVSwitch {
validateOpenVSwitchPostCreate(&test)
}
@@ -622,7 +639,11 @@ func tenantSubtree(resolve managementResolver) func(spec testSpec) {
Skip("Preserving the cluster after a failure")
}
test.deleteClusterAndWait(ctx, &deleteAccepted)
if spec.validate.nodeAgentUpgrade {
deleteClusterWithAgentDrain(ctx, &test, &deleteAccepted)
} else {
test.deleteClusterAndWait(ctx, &deleteAccepted)
}
deleted = true
}, Label("lifecycle"), NodeTimeout(1*time.Hour))
@@ -646,6 +667,12 @@ func tenantSubtree(resolve managementResolver) func(spec testSpec) {
})
AfterAll(func(ctx context.Context) {
defer func() {
if agentMethodChanged && test.k8sClient != nil {
_, _, err := nvke.SetNodeAgentUpdateMethod(ctx, test.k8sClient, previousAgentMethod)
Expect(err).NotTo(HaveOccurred())
}
}()
// Named once so the delete below and the nvkectl sweep cannot disagree
// about when the cluster should outlive the run.
keepCluster := test.cfg.Lifecycle.ReuseCluster != "" ||
@@ -766,6 +793,7 @@ type validations struct {
// provisioningOnly limits the lifecycle to create, node readiness, delete,
// and the shared tenant-access cleanup check.
provisioningOnly bool
nodeAgentUpgrade bool
// postReadyChecks verifies intended cluster state after the initial CAPD
// cluster and all desired nodes are Ready.
postReadyChecks bool
+17 -11
View File
@@ -85,23 +85,29 @@ systemctl is-active --quiet nke-agent.service
[ "$(cat /var/lib/nke/enc-rotation.state)" = rotation-checkpoint ]
[ "$(cat /var/lib/nke/agent-upgrades/retained/operation.json)" = retained-operation ]
# Qualify the actual independent updater with both bundle layouts too.
# Requests use an exact release version, so stamp this private fixture explicitly.
target_version=v0.3.0
make -C "$repo_root/agent" "build-${arch}" VERSION="$target_version"
bundle_archive="$work/agent.tgz"
tar -czf "$bundle_archive" \
-C "$repo_root/agent/bin/linux_${arch}" nvke-agent nvke-agent-updater \
-C "$repo_root/agent/scripts" nvke-agent.service nvke-agent-updater@.service migrate-agent-paths.sh
op_root="$work/operations"
mkdir -p "$op_root/bundle-rename" "$op_root/bundle-restore"
target_version="$("$repo_root/agent/bin/linux_${arch}/nvke-agent" --version | sed 's/^NVKE Agent Version: //')"
printf '{"id":"bundle-rename","action":"upgrade","targetVersion":"%s","previousVersion":"v0.2.0","method":"bundle","artifactUrl":"file://%s","phase":"Pending"}\n' \
"$target_version" "$bundle_archive" >"$op_root/bundle-rename/operation.json"
"$repo_root/agent/bin/linux_${arch}/nvke-agent-updater" --operation-root "$op_root" --operation-id bundle-rename
grep -q '"phase": "Succeeded"' "$op_root/bundle-rename/operation.json"
upgrade_request="${target_version}_bundle"
downgrade_request=v0.2.0_bundle
mkdir -p "$op_root/$upgrade_request" "$op_root/$downgrade_request"
printf '{"targetVersion":"%s","previousVersion":"v0.2.0","method":"bundle","artifactUrl":"file://%s","phase":"Pending"}\n' \
"$target_version" "$bundle_archive" >"$op_root/$upgrade_request/operation.json"
"$repo_root/agent/bin/linux_${arch}/nvke-agent-updater" --operation-root "$op_root" --request "$upgrade_request"
grep -q '"phase": "Succeeded"' "$op_root/$upgrade_request/operation.json"
systemctl is-active --quiet nvke-agent.service
printf '{"id":"bundle-restore","action":"rollback","restoreFromOperationId":"bundle-rename","phase":"Pending"}\n' \
>"$op_root/bundle-restore/operation.json"
"$repo_root/agent/bin/linux_${arch}/nvke-agent-updater" --operation-root "$op_root" --operation-id bundle-restore
grep -q '"phase": "Succeeded"' "$op_root/bundle-restore/operation.json"
older_archive="$work/older-agent.tgz"
tar -czf "$older_archive" -C "$work/old/usr/local/bin" nke-agent -C "$work/old/etc/systemd/system" nke-agent.service
printf '{"targetVersion":"v0.2.0","previousVersion":"%s","method":"bundle","artifactUrl":"file://%s","phase":"Pending"}\n' \
"$target_version" "$older_archive" >"$op_root/$downgrade_request/operation.json"
"$repo_root/agent/bin/linux_${arch}/nvke-agent-updater" --operation-root "$op_root" --request "$downgrade_request"
grep -q '"phase": "Succeeded"' "$op_root/$downgrade_request/operation.json"
systemctl is-active --quiet nke-agent.service
/usr/local/bin/nke-agent --version | grep -Fx 'NKE Agent Version: v0.2.0'
[ "$(cat /var/lib/nvke/enc-rotation.state)" = rotation-checkpoint ]
echo 'PASS: apt replacement, systemd alias, state preservation, native daemon startup, bundle upgrade and exact legacy rollback'
echo 'PASS: apt replacement, systemd alias, state preservation, native daemon startup, bundle upgrade and legacy bundle downgrade'
+3 -3
View File
@@ -81,7 +81,7 @@ ARCH ?= amd64
# directly: its SHA256SUMS has no arm64 entry at all, which is why
# prepare-installer-iso.sh fails with an empty EXPECTED_SHA256 for an
# ARCH=arm64 build pointed at it. arm64 (and every other non-amd64 arch)
# is published under cdimage.ubuntu.com/releases/<version>/release/
# is published under cdimage.ubuntu.com/ubuntu/releases/<version>/release/
# instead, with its own separate SHA256SUMS there.
#
# Use 26.04.1 to avoid the GA installer's intermittent overlayfs crash
@@ -99,8 +99,8 @@ ARCH ?= amd64
UBUNTU_RELEASE ?= 26.04.1
override UBUNTU_SERIES := $(word 1,$(subst ., ,$(UBUNTU_RELEASE))).$(word 2,$(subst ., ,$(UBUNTU_RELEASE)))
ifeq ($(ARCH),arm64)
ISO_URL ?= https://cdimage.ubuntu.com/releases/$(UBUNTU_SERIES)/release/ubuntu-$(UBUNTU_RELEASE)-live-server-arm64.iso
ISO_CHECKSUM ?= file:https://cdimage.ubuntu.com/releases/$(UBUNTU_SERIES)/release/SHA256SUMS
ISO_URL ?= https://cdimage.ubuntu.com/ubuntu/releases/$(UBUNTU_SERIES)/release/ubuntu-$(UBUNTU_RELEASE)-live-server-arm64.iso
ISO_CHECKSUM ?= file:https://cdimage.ubuntu.com/ubuntu/releases/$(UBUNTU_SERIES)/release/SHA256SUMS
else
ISO_URL ?= https://releases.ubuntu.com/$(UBUNTU_SERIES)/ubuntu-$(UBUNTU_RELEASE)-live-server-$(ARCH).iso
ISO_CHECKSUM ?= file:https://releases.ubuntu.com/$(UBUNTU_SERIES)/SHA256SUMS
@@ -1546,14 +1546,14 @@ exec "${REAL_MV:?}" "$@"
"https://releases.ubuntu.com/26.04/ubuntu-26.04.1-live-server-amd64.iso",
"file:https://releases.ubuntu.com/26.04/SHA256SUMS"),
("26.04.1", "arm64",
"https://cdimage.ubuntu.com/releases/26.04/release/ubuntu-26.04.1-live-server-arm64.iso",
"file:https://cdimage.ubuntu.com/releases/26.04/release/SHA256SUMS"),
"https://cdimage.ubuntu.com/ubuntu/releases/26.04/release/ubuntu-26.04.1-live-server-arm64.iso",
"file:https://cdimage.ubuntu.com/ubuntu/releases/26.04/release/SHA256SUMS"),
("24.04.5", "amd64",
"https://releases.ubuntu.com/24.04/ubuntu-24.04.5-live-server-amd64.iso",
"file:https://releases.ubuntu.com/24.04/SHA256SUMS"),
("24.04.5", "arm64",
"https://cdimage.ubuntu.com/releases/24.04/release/ubuntu-24.04.5-live-server-arm64.iso",
"file:https://cdimage.ubuntu.com/releases/24.04/release/SHA256SUMS"),
"https://cdimage.ubuntu.com/ubuntu/releases/24.04/release/ubuntu-24.04.5-live-server-arm64.iso",
"file:https://cdimage.ubuntu.com/ubuntu/releases/24.04/release/SHA256SUMS"),
)
for release, arch, iso_url, iso_checksum in cases:
with self.subTest(release=release, arch=arch):