Files
nvke/controller/internal/server/node_pools_test.go
Anisha Gupta US c1ef896e22 feat(controller): expose observed node pool counts (#2400)
* feat(controller): expose observed node pool counts (poc)

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): keep node pool counts with pool queries

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): name compared node set current

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): use a generic json equality helper name

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): use inner join for node set counts

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): use node set names in count aggregation

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): consolidate node pool response mapping

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* docs: keep node pool field definitions in the api reference

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): restore single node pool response conversion

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* test(controller): colocate node pool count tests

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* test(controller): colocate node pool response count tests

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(api): name observed node pool count explicitly

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* fix(controller): compare template JSON numbers by exact value

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): limit JSON comparison to node pool counts

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): restore shared pool configuration comparison

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): move json equality to shared utils

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* test(controller): use unambiguous numeric precision fixtures

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* refactor(controller): simplify node pool count responses

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

* perf(controller): index nodes by node pool

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>

---------

Signed-off-by: Anisha Gupta <anisgupta@nvidia.com>
2026-11-23 14:39:40 -05:00

2043 lines
75 KiB
Go

// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package server_test
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/google/uuid"
openapi_types "github.com/oapi-codegen/runtime/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
"github.com/dsx-ai-factory/nvke/controller/api"
"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/server"
"github.com/dsx-ai-factory/nvke/controller/internal/testutil"
)
// testNicoNodePoolProvider is the nested Forge payload the read fixtures below
// store, as it comes back on read.
func testNicoNodePoolProvider() *api.NicoNodePoolProvider {
return &api.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
SSHKeyGroupIDs: &[]uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
}
}
func TestNodePoolService_ListNodePools(t *testing.T) {
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440001")
now := time.Now()
tests := []struct {
name string
filters db.NodePoolFilters
dbNodePools []db.NodePool
dbError error
wantError bool
wantNodePool []api.NodePool
}{
{
name: "success with cluster filter",
filters: db.NodePoolFilters{
ClusterID: &clusterID,
},
dbNodePools: []db.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
SystemReservedMemory: "16Gi",
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}},
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
SSHKeyGroupIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
},
},
},
wantNodePool: []api.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
Nico: testNicoNodePoolProvider(),
SystemReservedMemory: func() *string { s := "16Gi"; return &s }(),
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
Conditions: mockAPINodePoolConditions(now),
TeleportEnabled: testutil.PtrTo(false),
},
},
},
{
name: "success without filter",
filters: db.NodePoolFilters{},
dbNodePools: []db.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
SystemReservedMemory: "16Gi",
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}},
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
SSHKeyGroupIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
},
},
},
wantNodePool: []api.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
Nico: testNicoNodePoolProvider(),
SystemReservedMemory: func() *string { s := "16Gi"; return &s }(),
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
Conditions: mockAPINodePoolConditions(now),
TeleportEnabled: testutil.PtrTo(false),
},
},
},
{
name: "success with name filter",
filters: db.NodePoolFilters{
Name: func() *string { s := "test-pool"; return &s }(),
},
dbNodePools: []db.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
SystemReservedMemory: "16Gi",
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}},
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
SSHKeyGroupIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
},
},
},
wantNodePool: []api.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
Nico: testNicoNodePoolProvider(),
SystemReservedMemory: func() *string { s := "16Gi"; return &s }(),
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
Conditions: mockAPINodePoolConditions(now),
CurrentNodeSetID: nil,
TeleportEnabled: testutil.PtrTo(false),
},
},
},
{
name: "success with cluster name filter",
filters: db.NodePoolFilters{
ClusterName: func() *string { s := "test-cluster"; return &s }(),
},
dbNodePools: []db.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
SystemReservedMemory: "16Gi",
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}},
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
SSHKeyGroupIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
},
},
},
wantNodePool: []api.NodePool{
{
ID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440000"),
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool",
Nico: testNicoNodePoolProvider(),
SystemReservedMemory: func() *string { s := "16Gi"; return &s }(),
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
Conditions: mockAPINodePoolConditions(now),
CurrentNodeSetID: nil,
TeleportEnabled: testutil.PtrTo(false),
},
},
},
{
name: "db error",
filters: db.NodePoolFilters{},
dbError: errors.New("db error"),
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &mockDB{}
mockDB.On("ListNodePools", mock.Anything, tt.filters).Return(tt.dbNodePools, tt.dbError)
if tt.dbError == nil {
counts := make(map[uuid.UUID]db.NodePoolCounts, len(tt.dbNodePools))
for _, pool := range tt.dbNodePools {
counts[pool.ID] = db.NodePoolCounts{}
}
mockDB.On("ListNodePoolCounts", mock.Anything, tt.dbNodePools).Return(counts, nil).Once()
for i := range tt.wantNodePool {
tt.wantNodePool[i].ObservedNodeCount = testutil.PtrTo(0)
tt.wantNodePool[i].ReadyNodeCount = testutil.PtrTo(0)
tt.wantNodePool[i].UpdatedNodeCount = testutil.PtrTo(0)
}
}
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
resp, err := service.ListNodePools(context.Background(), api.ListNodePoolsRequestObject{
Params: api.ListNodePoolsParams{
ClusterID: tt.filters.ClusterID,
Name: tt.filters.Name,
ClusterName: tt.filters.ClusterName,
},
})
if tt.wantError {
assert.Error(t, err)
return
}
require.NoError(t, err)
response := resp.(api.ListNodePools200JSONResponse)
assert.Equal(t, tt.wantNodePool, response.NodePools)
mockDB.AssertExpectations(t)
})
}
}
func TestNodePoolService_CreateNodePool(t *testing.T) {
provider := sdktrace.NewTracerProvider()
t.Cleanup(func() { require.NoError(t, provider.Shutdown(context.Background())) })
requestCtx, requestSpan := provider.Tracer("test").Start(t.Context(), "create-node-pool")
defer requestSpan.End()
wantTraceID := requestSpan.SpanContext().TraceID()
requestTrace := mock.MatchedBy(func(ctx context.Context) bool {
spanContext := trace.SpanContextFromContext(ctx)
return spanContext.TraceID() == wantTraceID && spanContext.SpanID().IsValid()
})
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440001")
siteID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
orgID := testOrgID // Use the same test orgID from clusters_test.go
tests := []struct {
name string
request api.CreateNodePoolRequest
setupMockCalls func(*mockTx)
wantResponseError bool
responseStatus int
responseErrorContains string
wantError bool
errorContains string
}{
{
name: "success",
request: func() api.CreateNodePoolRequest {
nvLinkLogicalPartitionID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440006")
return api.CreateNodePoolRequest{
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool-prefix",
Nico: &api.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
NvLinkLogicalPartitionID: &nvLinkLogicalPartitionID,
SSHKeyGroupIDs: &[]uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
},
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
MachineAnnotations: map[string]string{"example.com/profiles": "gpu,network"},
MachineLabels: map[string]string{"example.com/pool": "gpu"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
DesiredNodeCount: 3,
}
}(),
setupMockCalls: func(tx *mockTx) {
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
PodCIDR: "192.168.0.0/16",
ServiceCIDR: "10.96.0.0/12",
Nico: &db.NicoClusterProvider{
OrgID: orgID,
SiteID: siteID,
},
}, nil)
tx.On("CreateNodePool", mock.Anything, mock.MatchedBy(func(n *db.NodePool) bool {
nico, err := n.NicoProvider()
return err == nil &&
n.Name == "test-pool" &&
n.NodeNamePrefix == "test-pool-prefix" &&
assert.ObjectsAreEqual(map[string]string{"label1": "value1", "label2": "value2"}, n.NodeLabels) &&
assert.ObjectsAreEqual(map[string]string{"example.com/profiles": "gpu,network"}, n.MachineAnnotations) &&
assert.ObjectsAreEqual(map[string]string{"example.com/pool": "gpu"}, n.MachineLabels) &&
assert.ObjectsAreEqual([]db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}}, n.NodeTaints) &&
nico.NvLinkLogicalPartitionID != nil &&
*nico.NvLinkLogicalPartitionID == uuid.MustParse("550e8400-e29b-41d4-a716-446655440006")
})).Return(db.NodePool{
ID: nodePoolID,
Name: "test-pool",
NodeNamePrefix: "test-pool-prefix",
}, nil)
tx.On("CreateWorkflowOutboxEntry", requestTrace, "ProvisionNodePool", mock.Anything, mock.MatchedBy(func(input interface{}) bool {
m, ok := input.(map[string]interface{})
return ok && m["nodePoolID"] == nodePoolID
})).Return(db.WorkflowOutbox{}, nil)
},
},
{
name: "pod CIDR lacks capacity for new node pool",
request: api.CreateNodePoolRequest{
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool-prefix",
Nico: testNicoNodePoolProvider(),
DesiredNodeCount: 2,
},
setupMockCalls: func(tx *mockTx) {
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
PodCIDR: "10.240.0.0/23",
ServiceCIDR: "10.120.0.0/24",
Nico: &db.NicoClusterProvider{
OrgID: orgID,
SiteID: siteID,
},
}, nil)
tx.On(
"ListNodePools",
mock.Anything,
db.NodePoolFilters{ClusterID: &clusterID},
).Return([]db.NodePool{}, nil)
},
wantResponseError: true,
responseStatus: http.StatusBadRequest,
responseErrorContains: "provides 2 /24 node blocks, but 3 are required",
},
{
name: "duplicate node pool name in the same cluster",
request: api.CreateNodePoolRequest{
ClusterID: clusterID,
Name: "test-pool",
NodeNamePrefix: "test-pool-prefix",
Nico: testNicoNodePoolProvider(),
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
DesiredNodeCount: 3,
},
setupMockCalls: func(tx *mockTx) {
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
PodCIDR: "192.168.0.0/16",
ServiceCIDR: "10.96.0.0/12",
Nico: &db.NicoClusterProvider{
OrgID: orgID,
SiteID: siteID,
},
}, nil)
tx.On("CreateNodePool", mock.Anything, mock.MatchedBy(func(n *db.NodePool) bool {
return n.Name == "test-pool" &&
n.NodeNamePrefix == "test-pool-prefix" &&
assert.ObjectsAreEqual(map[string]string{"label1": "value1", "label2": "value2"}, n.NodeLabels) &&
assert.ObjectsAreEqual([]db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}}, n.NodeTaints)
})).Return(db.NodePool{}, db.ErrNodePoolNameNotUniqueInCluster)
},
wantResponseError: true,
// response is json so the quotes are escaped
responseErrorContains: "A node pool already exists with the name \\\"test-pool\\\" in cluster ID \\\"" + clusterID.String() + "\\\"",
},
{
name: "node pool creation error",
request: api.CreateNodePoolRequest{
ClusterID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440001"),
Name: "test-pool",
NodeNamePrefix: "test-pool-prefix",
Nico: testNicoNodePoolProvider(),
DesiredNodeCount: 3,
},
setupMockCalls: func(tx *mockTx) {
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
PodCIDR: "192.168.0.0/16",
ServiceCIDR: "10.96.0.0/12",
Nico: &db.NicoClusterProvider{
OrgID: orgID,
SiteID: siteID,
},
}, nil)
tx.On("CreateNodePool", mock.Anything, mock.Anything).Return(db.NodePool{}, errors.New("create node pool error"))
},
wantError: true,
},
{
name: "success with VPC prefixes (native networking enabled)",
request: api.CreateNodePoolRequest{
ClusterID: clusterID,
Name: "test-pool-vpc",
NodeNamePrefix: "test-pool-vpc-prefix",
Nico: &api.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440005")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
SSHKeyGroupIDs: &[]uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
},
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
DesiredNodeCount: 3,
},
setupMockCalls: func(tx *mockTx) {
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
PodCIDR: "192.168.0.0/16",
ServiceCIDR: "10.96.0.0/12",
Nico: &db.NicoClusterProvider{
OrgID: orgID,
SiteID: siteID,
},
}, nil)
tx.On("CreateNodePool", mock.Anything, mock.MatchedBy(func(n *db.NodePool) bool {
nico, err := n.NicoProvider()
return err == nil &&
n.Name == "test-pool-vpc" &&
n.NodeNamePrefix == "test-pool-vpc-prefix" &&
len(nico.VpcPrefixIDs) > 0 &&
assert.ObjectsAreEqual(map[string]string{"label1": "value1", "label2": "value2"}, n.NodeLabels) &&
assert.ObjectsAreEqual([]db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}}, n.NodeTaints)
})).Return(db.NodePool{
ID: nodePoolID,
Name: "test-pool-vpc",
NodeNamePrefix: "test-pool-vpc-prefix",
}, nil)
tx.On("CreateWorkflowOutboxEntry", requestTrace, "ProvisionNodePool", mock.Anything, mock.MatchedBy(func(input interface{}) bool {
m, ok := input.(map[string]interface{})
return ok && m["nodePoolID"] == nodePoolID
})).Return(db.WorkflowOutbox{}, nil)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &mockDB{}
mockDB.MockTx = &mockTx{}
// Mock GetCluster on mockDB for validation (validation uses s.db, not the transaction)
mockDB.On("GetCluster", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
ProviderType: db.ProviderTypeNico,
PodCIDR: "192.168.0.0/16",
ServiceCIDR: "10.96.0.0/12",
Nico: &db.NicoClusterProvider{
OrgID: orgID,
SiteID: siteID,
},
}, nil)
if tt.setupMockCalls != nil {
tt.setupMockCalls(mockDB.MockTx)
}
mockDB.MockTx.On(
"ListNodePools",
mock.Anything,
db.NodePoolFilters{ClusterID: &clusterID},
).Return([]db.NodePool{}, nil).Maybe()
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil)
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
resp, err := service.CreateNodePool(requestCtx, api.CreateNodePoolRequestObject{
Body: &tt.request,
})
if tt.wantError {
assert.Error(t, err)
if tt.errorContains != "" {
assert.Contains(t, err.Error(), tt.errorContains)
}
return
}
require.NoError(t, err)
require.NotNil(t, resp)
mockDB.MockTx.AssertNotCalled(t, "ListNodePoolCounts", mock.Anything, mock.Anything)
responseWriter := httptest.NewRecorder()
require.NoError(t, resp.VisitCreateNodePoolResponse(responseWriter))
response := responseWriter.Result()
body, err := io.ReadAll(response.Body)
require.NoError(t, err)
if tt.responseStatus != 0 {
assert.Equal(t, tt.responseStatus, response.StatusCode)
}
if tt.wantResponseError {
assert.Contains(t, string(body), tt.responseErrorContains)
}
mockDB.AssertExpectations(t)
mockDB.MockTx.AssertExpectations(t)
})
}
}
func TestNodePoolService_GetNodePool(t *testing.T) {
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
now := time.Now()
tests := []struct {
name string
nodePoolID uuid.UUID
dbNodePool db.NodePool
dbError error
wantError bool
want404 bool
wantNodePool api.GetNodePool200JSONResponse
}{
{
name: "success",
nodePoolID: nodePoolID,
dbNodePool: db.NodePool{
ID: nodePoolID,
ClusterID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440001"),
Name: "test-pool",
NodeNamePrefix: "test-pool",
SystemReservedMemory: "16Gi",
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []db.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: "NoSchedule"}},
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")},
InstanceTypeID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440003"),
SSHKeyGroupIDs: []uuid.UUID{uuid.MustParse("550e8400-e29b-41d4-a716-446655440004")},
Release: "ubuntu",
ConfigProfile: "default",
},
},
wantNodePool: api.GetNodePool200JSONResponse{
ID: nodePoolID,
ClusterID: uuid.MustParse("550e8400-e29b-41d4-a716-446655440001"),
Name: "test-pool",
NodeNamePrefix: "test-pool",
Nico: testNicoNodePoolProvider(),
SystemReservedMemory: func() *string { s := "16Gi"; return &s }(),
ControlPlane: false,
NodeLabels: map[string]string{"label1": "value1", "label2": "value2"},
NodeTaints: []api.NodeTaint{{Key: "nvidia.com/dedicated", Value: "gpu", Effect: api.NodeTaintEffectNoSchedule}},
Conditions: mockAPINodePoolConditions(now),
TeleportEnabled: testutil.PtrTo(false),
},
},
{
name: "not found",
nodePoolID: nodePoolID,
dbError: db.ErrNotFound,
want404: true,
},
{
name: "db error",
nodePoolID: nodePoolID,
dbError: errors.New("db error"),
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &mockDB{}
mockDB.On("GetNodePool", mock.Anything, tt.nodePoolID).Return(tt.dbNodePool, tt.dbError)
if tt.dbError == nil {
mockDB.On("ListNodePoolCounts", mock.Anything, []db.NodePool{tt.dbNodePool}).Return(map[uuid.UUID]db.NodePoolCounts{tt.dbNodePool.ID: {}}, nil).Once()
tt.wantNodePool.ObservedNodeCount = testutil.PtrTo(0)
tt.wantNodePool.ReadyNodeCount = testutil.PtrTo(0)
tt.wantNodePool.UpdatedNodeCount = testutil.PtrTo(0)
}
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
resp, err := service.GetNodePool(context.Background(), api.GetNodePoolRequestObject{
NodePoolID: tt.nodePoolID,
})
if tt.wantError {
assert.Error(t, err)
return
}
if tt.want404 {
assert.IsType(t, api.GetNodePool404Response{}, resp)
return
}
require.NoError(t, err)
response := resp.(api.GetNodePool200JSONResponse)
assert.Equal(t, tt.wantNodePool, response)
mockDB.AssertExpectations(t)
})
}
}
func TestNodePoolService_UpdateNodePool(t *testing.T) {
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440001")
siteID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")
subnetID1 := uuid.MustParse("550e8400-e29b-41d4-a716-446655440010")
subnetID2 := uuid.MustParse("550e8400-e29b-41d4-a716-446655440011")
vpcPrefixID1 := uuid.MustParse("550e8400-e29b-41d4-a716-446655440020")
vpcPrefixID2 := uuid.MustParse("550e8400-e29b-41d4-a716-446655440021")
currentNodeSetID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440030")
now := time.Now()
tests := []struct {
name string
nodePoolID uuid.UUID
body api.UpdateNodePoolRequest
setupMockDB func(*mockDB, *mockTx)
expectError bool // if true, assert resp is nil and err != nil; else assert no error and validate response
wantResponseType interface{} // expected response type when no error (e.g. api.UpdateNodePool200JSONResponse{})
verifyUpdatePool func(t *testing.T, n *db.NodePool)
}{
{
name: "success with subnetIDs replace (differs) only updates pool; controller creates NodeSet on reconcile",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{SubnetIDs: []openapi_types.UUID{subnetID2}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
CurrentNodeSetID: &currentNodeSetID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
CurrentNodeSetID: &currentNodeSetID,
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID2},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, nodePoolID, n.ID)
assert.Equal(t, []uuid.UUID{subnetID2}, nico.SubnetIDs)
assert.Equal(t, currentNodeSetID, *n.CurrentNodeSetID)
},
},
{
name: "success with subnetIDs replace same set (no new NodeSet)",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{SubnetIDs: []openapi_types.UUID{subnetID1}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, nodePoolID, n.ID)
assert.Equal(t, []uuid.UUID{subnetID1}, nico.SubnetIDs)
},
},
{
name: "empty subnetIDs replaces subnets with empty",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{SubnetIDs: []openapi_types.UUID{}},
DesiredNodeCount: testutil.PtrTo(3),
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
DesiredCount: 3,
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Empty(t, nico.SubnetIDs)
assert.Equal(t, 3, n.DesiredCount)
},
},
{
name: "nil subnetIDs (field omitted) leaves subnets unchanged",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
DesiredNodeCount: testutil.PtrTo(4),
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1, subnetID2},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
DesiredCount: 4,
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1, subnetID2},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, []uuid.UUID{subnetID1, subnetID2}, nico.SubnetIDs)
assert.Equal(t, 4, n.DesiredCount)
},
},
{
name: "success without subnetIDs leaves subnets unchanged",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
DesiredNodeCount: testutil.PtrTo(5),
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
DesiredCount: 5,
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, nodePoolID, n.ID)
assert.Equal(t, []uuid.UUID{subnetID1}, nico.SubnetIDs)
assert.Equal(t, 5, n.DesiredCount)
},
},
{
name: "subnetIDs when node pool not found returns 404",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{SubnetIDs: []openapi_types.UUID{subnetID1}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{}, db.ErrNotFound)
},
wantResponseType: api.UpdateNodePool404Response{},
},
{
name: "subnetIDs when cluster not found returns 404",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{SubnetIDs: []openapi_types.UUID{subnetID1}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
// Cluster-first order: the cluster lock fails before the pool
// row is locked, so GetNodePoolForUpdate is never reached.
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{}, db.ErrNotFound)
},
wantResponseType: api.UpdateNodePool404Response{},
},
{
name: "success with vpcPrefixIDs replace (differs) only updates pool; controller creates NodeSet on reconcile",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{VpcPrefixIDs: []openapi_types.UUID{vpcPrefixID2}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
CurrentNodeSetID: &currentNodeSetID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
CurrentNodeSetID: &currentNodeSetID,
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID2},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, nodePoolID, n.ID)
assert.Equal(t, []uuid.UUID{vpcPrefixID2}, nico.VpcPrefixIDs)
assert.Equal(t, currentNodeSetID, *n.CurrentNodeSetID)
},
},
{
name: "success with vpcPrefixIDs replace same set (no new NodeSet)",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{VpcPrefixIDs: []openapi_types.UUID{vpcPrefixID1}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, []uuid.UUID{vpcPrefixID1}, nico.VpcPrefixIDs)
},
},
{
name: "empty vpcPrefixIDs replaces vpc prefixes with empty",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{VpcPrefixIDs: []openapi_types.UUID{}},
DesiredNodeCount: testutil.PtrTo(2),
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
DesiredCount: 2,
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Empty(t, nico.VpcPrefixIDs)
assert.Equal(t, 2, n.DesiredCount)
},
},
{
name: "nil vpcPrefixIDs (field omitted) leaves vpc prefixes unchanged",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
DesiredNodeCount: testutil.PtrTo(6),
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1, vpcPrefixID2},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
DesiredCount: 6,
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1, vpcPrefixID2},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, []uuid.UUID{vpcPrefixID1, vpcPrefixID2}, nico.VpcPrefixIDs)
assert.Equal(t, 6, n.DesiredCount)
},
},
{
name: "subnetIDs replace when no current NodeSet only updates pool",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{SubnetIDs: []openapi_types.UUID{subnetID2}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID2},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, []uuid.UUID{subnetID2}, nico.SubnetIDs)
assert.Nil(t, n.CurrentNodeSetID)
},
},
{
name: "subnetIDs dedupe and same set no new NodeSet",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{SubnetIDs: []openapi_types.UUID{subnetID1, subnetID1, subnetID2}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID2, subnetID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
Nico: &db.NicoNodePoolProvider{
SubnetIDs: []uuid.UUID{subnetID1, subnetID2},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
require.Len(t, nico.SubnetIDs, 2)
assert.Contains(t, nico.SubnetIDs, subnetID1)
assert.Contains(t, nico.SubnetIDs, subnetID2)
},
},
{
name: "success without vpcPrefixIDs leaves vpc prefixes unchanged",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
DesiredNodeCount: testutil.PtrTo(5),
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
DesiredCount: 5,
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
assert.Equal(t, nodePoolID, n.ID)
assert.Equal(t, []uuid.UUID{vpcPrefixID1}, nico.VpcPrefixIDs)
assert.Equal(t, 5, n.DesiredCount)
},
},
{
name: "both subnetIDs and vpcPrefixIDs returns 400",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{
SubnetIDs: []openapi_types.UUID{subnetID1},
VpcPrefixIDs: []openapi_types.UUID{vpcPrefixID1},
},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil)
},
wantResponseType: api.UpdateNodePool400JSONResponse{},
},
{
name: "vpcPrefixIDs when node pool not found returns 404",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{VpcPrefixIDs: []openapi_types.UUID{vpcPrefixID1}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{}, db.ErrNotFound)
},
wantResponseType: api.UpdateNodePool404Response{},
},
{
name: "vpcPrefixIDs when cluster not found returns 404",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{VpcPrefixIDs: []openapi_types.UUID{vpcPrefixID1}},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
// Cluster-first order: the cluster lock fails before the pool
// row is locked, so GetNodePoolForUpdate is never reached.
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{}, db.ErrNotFound)
},
wantResponseType: api.UpdateNodePool404Response{},
},
{
name: "node pool deleting returns error",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{},
setupMockDB: func(_ *mockDB, tx *mockTx) {
deletingConditions := mockDBNodePoolConditions(now)
deletingConditions.Deleting = db.Condition{Status: db.ConditionStatusTrue, Message: "Deleting"}
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
Conditions: deletingConditions,
}, nil)
},
expectError: true,
},
{
name: "tx validation failure returns 400 response",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
MaxSurge: testutil.PtrTo(2),
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
ControlPlane: true,
Conditions: mockDBNodePoolConditions(now),
}, nil)
},
wantResponseType: api.UpdateNodePool400JSONResponse{},
},
{
name: "node pool not found in tx returns 404",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{}, db.ErrNotFound)
},
wantResponseType: api.UpdateNodePool404Response{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &mockDB{}
mockDB.MockTx = &mockTx{}
mockDB.MockTx.On("ListNodePoolCounts", mock.Anything, mock.Anything).Return(func(_ context.Context, pools []db.NodePool) map[uuid.UUID]db.NodePoolCounts {
counts := make(map[uuid.UUID]db.NodePoolCounts, len(pools))
for _, pool := range pools {
counts[pool.ID] = db.NodePoolCounts{}
}
return counts
}, nil).Maybe()
if tt.setupMockDB != nil {
tt.setupMockDB(mockDB, mockDB.MockTx)
}
// Unlocked read used to learn the pool's cluster before taking the
// cluster-first lock order. UpdateNodePool always performs this
// pre-read first, so require it (Once) rather than Maybe so a
// regression that drops it fails the test.
mockDB.MockTx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil).Maybe()
mockDB.MockTx.On("GetClusterForUpdate", mock.Anything, clusterID).Maybe().Return(db.Cluster{
ID: clusterID,
ProviderType: db.ProviderTypeNico,
PodCIDR: "192.168.0.0/16",
ServiceCIDR: "10.96.0.0/12",
Nico: &db.NicoClusterProvider{
OrgID: testOrgID,
SiteID: siteID,
},
}, nil)
mockDB.MockTx.On(
"ListNodePools",
mock.Anything,
db.NodePoolFilters{ClusterID: &clusterID},
).Maybe().Return([]db.NodePool{{ID: nodePoolID}}, nil)
mockDB.On("RunInTx", mock.Anything, mock.Anything).Maybe().Return(nil)
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
resp, err := service.UpdateNodePool(context.Background(), api.UpdateNodePoolRequestObject{
NodePoolID: tt.nodePoolID,
Body: &tt.body,
})
if tt.expectError {
assert.Nil(t, resp)
assert.Error(t, err)
return
}
require.NoError(t, err)
require.NotNil(t, resp)
require.NotNil(t, tt.wantResponseType, "test must set wantResponseType when expectError is false")
assert.IsType(t, tt.wantResponseType, resp)
if tt.verifyUpdatePool != nil {
validated := false
for _, call := range mockDB.MockTx.Calls {
if call.Method == "UpdateNodePool" {
tt.verifyUpdatePool(t, call.Arguments[1].(*db.NodePool))
validated = true
break
}
}
assert.True(t, validated, "UpdateNodePool was not called")
}
mockDB.AssertExpectations(t)
mockDB.MockTx.AssertExpectations(t)
})
}
}
// A node pool's Kubernetes version must not be newer than the control plane's,
// and must not change while the control plane upgrades. An older version, to
// roll a pool back, is allowed.
func TestNodePoolService_UpdateNodePool_KubernetesVersion(t *testing.T) {
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440001")
siteID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440002")
now := time.Now()
tests := []struct {
name string
controlPlaneVersion string
controlPlaneUpgrading bool
poolVersion string
requestedVersion string
wantErrContains string // empty means the update is accepted
}{
{
name: "newer minor than the control plane is rejected",
controlPlaneVersion: "1.36.3",
poolVersion: "1.36.3",
requestedVersion: "1.37.2",
wantErrContains: "must not be newer than the control plane version (control plane: 1.36.3, requested: 1.37.2)",
},
{
name: "newer major than the control plane is rejected",
controlPlaneVersion: "1.36.3",
poolVersion: "1.36.3",
requestedVersion: "2.0.0",
wantErrContains: "version skew policy violation",
},
{
name: "newer patch of the control plane's minor is accepted",
controlPlaneVersion: "1.36.3",
poolVersion: "1.36.3",
requestedVersion: "1.36.4",
},
{
name: "the control plane's version is accepted",
controlPlaneVersion: "1.37.2",
poolVersion: "1.36.3",
requestedVersion: "1.37.2",
},
{
name: "an older version is accepted, to roll the pool back",
controlPlaneVersion: "1.37.2",
poolVersion: "1.37.2",
requestedVersion: "1.36.3",
},
{
name: "an older version more than three minor versions back is accepted",
controlPlaneVersion: "1.37.2",
poolVersion: "1.37.2",
requestedVersion: "1.33.0",
},
{
name: "a version change while the control plane upgrades is rejected",
controlPlaneVersion: "1.37.2",
controlPlaneUpgrading: true,
poolVersion: "1.36.3",
requestedVersion: "1.37.2",
wantErrContains: "cannot update Kubernetes version while an upgrade is already in progress: wait for the control plane upgrade to 1.37.2 to finish",
},
{
name: "a rollback while the control plane upgrades is rejected",
controlPlaneVersion: "1.37.2",
controlPlaneUpgrading: true,
poolVersion: "1.36.3",
requestedVersion: "1.35.3",
wantErrContains: "already in progress",
},
{
name: "the pool's current version while the control plane upgrades is accepted",
controlPlaneVersion: "1.37.2",
controlPlaneUpgrading: true,
poolVersion: "1.36.3",
requestedVersion: "1.36.3",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &mockDB{}
mockDB.MockTx = &mockTx{}
mockDB.MockTx.On("ListNodePoolCounts", mock.Anything, mock.Anything).Return(func(_ context.Context, pools []db.NodePool) map[uuid.UUID]db.NodePoolCounts {
counts := make(map[uuid.UUID]db.NodePoolCounts, len(pools))
for _, pool := range pools {
counts[pool.ID] = db.NodePoolCounts{}
}
return counts
}, nil).Maybe()
conditions := db.ClusterConditions{
ControlPlaneUpgrading: db.NewCondition(tt.controlPlaneUpgrading, "upgrading"),
}
mockDB.MockTx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil)
mockDB.MockTx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
ProviderType: db.ProviderTypeNico,
KubernetesVersion: tt.controlPlaneVersion,
Conditions: conditions,
Nico: &db.NicoClusterProvider{
OrgID: testOrgID,
SiteID: siteID,
},
}, nil)
mockDB.MockTx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
KubernetesVersion: tt.poolVersion,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{},
}, nil)
if tt.wantErrContains == "" {
mockDB.MockTx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
KubernetesVersion: tt.requestedVersion,
}, nil)
}
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil)
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
requested := tt.requestedVersion
resp, err := service.UpdateNodePool(context.Background(), api.UpdateNodePoolRequestObject{
NodePoolID: nodePoolID,
Body: &api.UpdateNodePoolRequest{KubernetesVersion: &requested},
})
require.NoError(t, err)
if tt.wantErrContains != "" {
badRequest, ok := resp.(api.UpdateNodePool400JSONResponse)
require.True(t, ok, "want 400, got %T", resp)
assert.Contains(t, badRequest.Message, tt.wantErrContains)
mockDB.MockTx.AssertNotCalled(t, "UpdateNodePool", mock.Anything, mock.Anything)
} else {
require.IsType(t, api.UpdateNodePool200JSONResponse{}, resp)
var stored *db.NodePool
for _, call := range mockDB.MockTx.Calls {
if call.Method == "UpdateNodePool" {
stored = call.Arguments[1].(*db.NodePool)
}
}
require.NotNil(t, stored, "UpdateNodePool was not called")
assert.Equal(t, tt.requestedVersion, stored.KubernetesVersion)
}
mockDB.AssertExpectations(t)
mockDB.MockTx.AssertExpectations(t)
})
}
}
// A node pool's NVLink logical partition can be set or replaced, but not cleared.
func TestNodePoolService_UpdateNodePool_NVLinkLogicalPartition(t *testing.T) {
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440001")
vpcPrefixID1 := uuid.MustParse("550e8400-e29b-41d4-a716-446655440020")
currentNodeSetID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440030")
nvLinkPartitionID1 := uuid.MustParse("550e8400-e29b-41d4-a716-446655440040")
nvLinkPartitionID2 := uuid.MustParse("550e8400-e29b-41d4-a716-446655440041")
now := time.Now()
tests := []struct {
name string
nodePoolID uuid.UUID
body api.UpdateNodePoolRequest
setupMockDB func(*mockDB, *mockTx)
wantResponseType any
verifyUpdatePool func(t *testing.T, n *db.NodePool)
}{
{
name: "nvLinkLogicalPartitionID sets the partition and keeps other nico fields",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{NvLinkLogicalPartitionID: &nvLinkPartitionID1},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
CurrentNodeSetID: &currentNodeSetID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
Release: "os-v1",
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
Release: "os-v1",
NvLinkLogicalPartitionID: &nvLinkPartitionID1,
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
require.NotNil(t, nico.NvLinkLogicalPartitionID)
assert.Equal(t, nvLinkPartitionID1, *nico.NvLinkLogicalPartitionID)
assert.Equal(t, []uuid.UUID{vpcPrefixID1}, nico.VpcPrefixIDs)
assert.Equal(t, "os-v1", nico.Release)
assert.Equal(t, currentNodeSetID, *n.CurrentNodeSetID)
},
},
{
name: "nvLinkLogicalPartitionID replaces an existing partition",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{NvLinkLogicalPartitionID: &nvLinkPartitionID2},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
NvLinkLogicalPartitionID: &nvLinkPartitionID1,
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.AnythingOfType("*db.NodePool")).Return(db.NodePool{
ID: nodePoolID,
Nico: &db.NicoNodePoolProvider{
VpcPrefixIDs: []uuid.UUID{vpcPrefixID1},
NvLinkLogicalPartitionID: &nvLinkPartitionID2,
},
}, nil)
},
wantResponseType: api.UpdateNodePool200JSONResponse{},
verifyUpdatePool: func(t *testing.T, n *db.NodePool) {
t.Helper()
nico, err := n.NicoProvider()
require.NoError(t, err)
require.NotNil(t, nico.NvLinkLogicalPartitionID)
assert.Equal(t, nvLinkPartitionID2, *nico.NvLinkLogicalPartitionID)
},
},
{
name: "nil-UUID nvLinkLogicalPartitionID cannot clear the partition and returns 400",
nodePoolID: nodePoolID,
body: api.UpdateNodePoolRequest{
Nico: &api.NicoNodePoolProviderUpdate{NvLinkLogicalPartitionID: testutil.PtrTo(uuid.Nil)},
},
setupMockDB: func(_ *mockDB, tx *mockTx) {
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
Conditions: mockDBNodePoolConditions(now),
Nico: &db.NicoNodePoolProvider{
NvLinkLogicalPartitionID: &nvLinkPartitionID1,
},
}, nil)
},
wantResponseType: api.UpdateNodePool400JSONResponse{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &mockDB{}
mockDB.MockTx = &mockTx{}
mockDB.MockTx.On("ListNodePoolCounts", mock.Anything, mock.Anything).Return(func(_ context.Context, pools []db.NodePool) map[uuid.UUID]db.NodePoolCounts {
counts := make(map[uuid.UUID]db.NodePoolCounts, len(pools))
for _, pool := range pools {
counts[pool.ID] = db.NodePoolCounts{}
}
return counts
}, nil).Maybe()
tt.setupMockDB(mockDB, mockDB.MockTx)
mockDB.MockTx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{ID: nodePoolID, ClusterID: clusterID}, nil).Maybe()
mockDB.MockTx.On("GetClusterForUpdate", mock.Anything, clusterID).Maybe().Return(db.Cluster{
ID: clusterID,
ProviderType: db.ProviderTypeNico,
Nico: &db.NicoClusterProvider{OrgID: testOrgID},
}, nil)
mockDB.On("RunInTx", mock.Anything, mock.Anything).Maybe().Return(nil)
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
resp, err := service.UpdateNodePool(context.Background(), api.UpdateNodePoolRequestObject{NodePoolID: tt.nodePoolID, Body: &tt.body})
require.NoError(t, err)
assert.IsType(t, tt.wantResponseType, resp)
var updated *db.NodePool
for _, call := range mockDB.MockTx.Calls {
if call.Method == "UpdateNodePool" {
updated = call.Arguments[1].(*db.NodePool)
}
}
if tt.verifyUpdatePool == nil {
assert.Nil(t, updated, "a rejected update must not write the node pool")
} else {
require.NotNil(t, updated, "UpdateNodePool was not called")
tt.verifyUpdatePool(t, updated)
}
mockDB.MockTx.AssertExpectations(t)
})
}
}
func TestNodePoolService_UpdateNodePool_RejectsPodCIDRCapacityExceeded(t *testing.T) {
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440001")
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
desiredNodeCount := 2
mockDB := &mockDB{MockTx: &mockTx{}}
mockDB.MockTx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil)
mockDB.MockTx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
DesiredCount: 1,
}, nil)
mockDB.MockTx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(forgeDBCluster(db.Cluster{
ID: clusterID,
PodCIDR: "10.240.0.0/23",
ServiceCIDR: "10.120.0.0/24",
Nico: &db.NicoClusterProvider{
SiteID: uuid.New(),
},
}), nil)
mockDB.MockTx.On(
"ListNodePools",
mock.Anything,
db.NodePoolFilters{ClusterID: &clusterID},
).Return([]db.NodePool{{
ID: nodePoolID,
ClusterID: clusterID,
DesiredCount: 1,
}}, nil)
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil)
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
resp, err := service.UpdateNodePool(context.Background(), api.UpdateNodePoolRequestObject{
NodePoolID: nodePoolID,
Body: &api.UpdateNodePoolRequest{
DesiredNodeCount: &desiredNodeCount,
},
})
require.NoError(t, err)
badRequest, ok := resp.(api.UpdateNodePool400JSONResponse)
require.True(t, ok, "expected UpdateNodePool400JSONResponse, got %T", resp)
assert.Contains(t, badRequest.Message, "provides 2 /24 node blocks, but 3 are required")
mockDB.MockTx.AssertNotCalled(t, "UpdateNodePool", mock.Anything, mock.Anything)
}
func TestNodePoolService_DeleteNodePool(t *testing.T) {
nodePoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
otherCPPoolID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440010")
clusterID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440001")
joinedCPNodeID := uuid.MustParse("550e8400-e29b-41d4-a716-446655440020")
tests := []struct {
name string
nodePoolID uuid.UUID
setupMockCalls func(*mockTx)
wantError bool
want400 bool
want404 bool
want400Contains string
verifyConditions func(t *testing.T, conditions db.NodePoolConditions)
}{
{
name: "success worker pool",
nodePoolID: nodePoolID,
setupMockCalls: func(tx *mockTx) {
tx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil)
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
ControlPlane: false,
}, nil)
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.MatchedBy(func(n *db.NodePool) bool {
return n.ID == nodePoolID && n.Conditions.Deleting.Status == db.ConditionStatusTrue
})).Return(db.NodePool{}, nil)
tx.On("CreateWorkflowOutboxEntry", mock.Anything, "TeardownNodePool", mock.Anything,
mock.MatchedBy(func(input interface{}) bool {
m, ok := input.(map[string]interface{})
return ok && m["nodePoolID"] == nodePoolID
})).Return(db.WorkflowOutbox{}, nil)
},
verifyConditions: func(t *testing.T, conditions db.NodePoolConditions) {
t.Helper()
assert.Equal(t, db.ConditionStatusTrue, conditions.Deleting.Status)
},
},
{
name: "success control-plane pool when another joined CP remains",
nodePoolID: nodePoolID,
setupMockCalls: func(tx *mockTx) {
tx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil)
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
ControlPlane: true,
}, nil)
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
}, nil)
controlPlane := true
tx.On("ListNodePools", mock.Anything, db.NodePoolFilters{
ClusterID: &clusterID,
ControlPlane: &controlPlane,
}).Return([]db.NodePool{
{ID: nodePoolID, ControlPlane: true},
{ID: otherCPPoolID, ControlPlane: true},
}, nil)
tx.On("ListNodes", mock.Anything, db.NodeFilters{
ClusterID: &clusterID,
ControlPlane: &controlPlane,
}).Return([]db.Node{
{
ID: joinedCPNodeID,
NodePoolID: otherCPPoolID,
ControlPlane: true,
Conditions: db.NodeConditions{
Joined: db.NewCondition(true, "joined"),
},
},
}, nil)
tx.On("UpdateNodePool", mock.Anything, mock.MatchedBy(func(n *db.NodePool) bool {
return n.ID == nodePoolID && n.Conditions.Deleting.Status == db.ConditionStatusTrue
})).Return(db.NodePool{}, nil)
tx.On("CreateWorkflowOutboxEntry", mock.Anything, "TeardownNodePool", mock.Anything,
mock.MatchedBy(func(input interface{}) bool {
m, ok := input.(map[string]interface{})
return ok && m["nodePoolID"] == nodePoolID
})).Return(db.WorkflowOutbox{}, nil)
},
},
{
name: "reject last joined control-plane pool",
nodePoolID: nodePoolID,
setupMockCalls: func(tx *mockTx) {
tx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil)
tx.On("GetNodePoolForUpdate", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
ControlPlane: true,
}, nil)
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
}, nil)
controlPlane := true
tx.On("ListNodePools", mock.Anything, db.NodePoolFilters{
ClusterID: &clusterID,
ControlPlane: &controlPlane,
}).Return([]db.NodePool{
{ID: nodePoolID, ControlPlane: true},
}, nil)
tx.On("ListNodes", mock.Anything, db.NodeFilters{
ClusterID: &clusterID,
ControlPlane: &controlPlane,
}).Return([]db.Node{
{
ID: joinedCPNodeID,
NodePoolID: nodePoolID,
ControlPlane: true,
Conditions: db.NodeConditions{
Joined: db.NewCondition(true, "joined"),
},
},
}, nil)
},
want400: true,
want400Contains: "last joined control-plane node pool",
},
{
name: "noop while cluster deleting",
nodePoolID: nodePoolID,
setupMockCalls: func(tx *mockTx) {
tx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{
ID: nodePoolID,
ClusterID: clusterID,
}, nil)
tx.On("GetClusterForUpdate", mock.Anything, clusterID).Return(db.Cluster{
ID: clusterID,
Conditions: db.ClusterConditions{
Deleting: db.NewCondition(true, "deleting"),
},
}, nil)
},
},
{
name: "not found",
nodePoolID: nodePoolID,
setupMockCalls: func(tx *mockTx) {
tx.On("GetNodePool", mock.Anything, nodePoolID).Return(db.NodePool{}, db.ErrNotFound)
},
want404: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockDB := &mockDB{}
mockDB.MockTx = &mockTx{}
mockDB.MockTx.On("ListNodePoolCounts", mock.Anything, mock.Anything).Return(func(_ context.Context, pools []db.NodePool) map[uuid.UUID]db.NodePoolCounts {
counts := make(map[uuid.UUID]db.NodePoolCounts, len(pools))
for _, pool := range pools {
counts[pool.ID] = db.NodePoolCounts{}
}
return counts
}, nil).Maybe()
if tt.setupMockCalls != nil {
tt.setupMockCalls(mockDB.MockTx)
}
mockDB.On("RunInTx", mock.Anything, mock.Anything).Return(nil)
service := server.NewNodePoolService(&slog.Logger{}, mockDB, config.TeleportConfig{}, nil)
resp, err := service.DeleteNodePool(context.Background(), api.DeleteNodePoolRequestObject{
NodePoolID: tt.nodePoolID,
})
if tt.wantError {
assert.Error(t, err)
return
}
if tt.want400 {
require.IsType(t, api.DeleteNodePool400JSONResponse{}, resp)
badRequest := resp.(api.DeleteNodePool400JSONResponse)
assert.Contains(t, badRequest.Message, tt.want400Contains)
return
}
if tt.want404 {
assert.IsType(t, api.DeleteNodePool404Response{}, resp)
return
}
require.NoError(t, err)
require.IsType(t, api.DeleteNodePool202Response{}, resp)
if tt.verifyConditions != nil {
var conditions db.NodePoolConditions
for _, call := range mockDB.MockTx.Calls {
if call.Method == "UpdateNodePool" {
nodePool := call.Arguments[1].(*db.NodePool)
conditions = nodePool.Conditions
break
}
}
tt.verifyConditions(t, conditions)
}
mockDB.AssertExpectations(t)
mockDB.MockTx.AssertExpectations(t)
})
}
}
func mockDBNodePoolConditions(now time.Time) db.NodePoolConditions {
return db.NodePoolConditions{
Provisioning: db.Condition{
Status: db.ConditionStatusFalse,
Message: "Finished provisioning",
LastTransitionTime: now,
},
Provisioned: db.Condition{
Status: db.ConditionStatusTrue,
Message: "Provisioned",
LastTransitionTime: now,
},
Deleting: db.Condition{
Status: db.ConditionStatusFalse,
Message: "Not deleting",
LastTransitionTime: now,
},
}
}
func mockAPINodePoolConditions(now time.Time) api.NodePoolConditions {
return api.NodePoolConditions{
Provisioning: api.Condition{
Status: api.ConditionStatusFalse,
Message: "Finished provisioning",
LastTransitionTime: now,
},
Provisioned: api.Condition{
Status: api.ConditionStatusTrue,
Message: "Provisioned",
LastTransitionTime: now,
},
Deleting: api.Condition{
Status: api.ConditionStatusFalse,
Message: "Not deleting",
LastTransitionTime: now,
},
}
}
func TestNodePoolReadCounts(t *testing.T) {
pool := db.NodePool{ID: uuid.New(), DesiredCount: 4}
for _, endpoint := range []string{"get", "list"} {
for _, fails := range []bool{false, true} {
name := endpoint + "/success"
if fails {
name = endpoint + "/counts-error"
}
t.Run(name, func(t *testing.T) {
store := &testutil.MockDB{}
if endpoint == "get" {
store.On("GetNodePool", mock.Anything, pool.ID).Return(pool, nil).Once()
} else {
store.On("ListNodePools", mock.Anything, db.NodePoolFilters{}).Return([]db.NodePool{pool}, nil).Once()
}
var queryErr error
if fails {
queryErr = errors.New("count query failed")
}
store.On("ListNodePoolCounts", mock.Anything, []db.NodePool{pool}).Return(map[uuid.UUID]db.NodePoolCounts{
pool.ID: {NodeCount: 5, ReadyNodeCount: 3, UpdatedNodeCount: 2},
}, queryErr).Once()
svc := server.NewNodePoolService(slog.Default(), store, config.TeleportConfig{}, nil)
var result api.NodePool
var err error
if endpoint == "get" {
var response api.GetNodePoolResponseObject
response, err = svc.GetNodePool(t.Context(), api.GetNodePoolRequestObject{NodePoolID: pool.ID})
if err == nil {
result = api.NodePool(response.(api.GetNodePool200JSONResponse))
}
} else {
var response api.ListNodePoolsResponseObject
response, err = svc.ListNodePools(t.Context(), api.ListNodePoolsRequestObject{})
if err == nil {
result = response.(api.ListNodePools200JSONResponse).NodePools[0]
}
}
if fails {
require.ErrorContains(t, err, "count query failed")
} else {
require.NoError(t, err)
require.Equal(t, 4, result.DesiredNodeCount)
require.Equal(t, 5, *result.ObservedNodeCount)
require.Equal(t, 3, *result.ReadyNodeCount)
require.Equal(t, 2, *result.UpdatedNodeCount)
encoded, err := json.Marshal(result)
require.NoError(t, err)
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal(encoded, &fields))
require.JSONEq(t, "5", string(fields["observedNodeCount"]))
require.NotContains(t, fields, "nodeCount")
}
store.AssertExpectations(t)
})
}
}
}
func TestNodePoolCountsRejectMissingObservation(t *testing.T) {
store := &testutil.MockDB{}
pool := db.NodePool{ID: uuid.New()}
store.On("GetNodePool", mock.Anything, pool.ID).Return(pool, nil).Once()
store.On("ListNodePoolCounts", mock.Anything, []db.NodePool{pool}).Return(map[uuid.UUID]db.NodePoolCounts{}, nil).Once()
service := server.NewNodePoolService(slog.Default(), store, config.TeleportConfig{}, nil)
response, err := service.GetNodePool(t.Context(), api.GetNodePoolRequestObject{NodePoolID: pool.ID})
require.Nil(t, response)
require.ErrorContains(t, err, "node pool counts missing")
store.AssertExpectations(t)
}
func TestNodePoolWriteCounts(t *testing.T) {
for _, tt := range []struct {
operation string
fails bool
}{
{operation: "create"},
{operation: "update"},
{operation: "update", fails: true},
} {
operation, fails := tt.operation, tt.fails
name := operation + "/success"
if fails {
name = operation + "/counts-error"
}
t.Run(name, func(t *testing.T) {
cluster := forgeDBCluster(db.Cluster{Nico: &db.NicoClusterProvider{OrgID: "test-org", SiteID: uuid.New()}})
cluster.ID, cluster.Name, cluster.PodCIDR = uuid.New(), "tenant", "10.240.0.0/16"
cluster.ServiceCIDR = "10.120.0.0/24"
pool := db.NodePool{ID: uuid.New(), ClusterID: cluster.ID, DesiredCount: 4}
tx := &testutil.MockTx{}
store := &testutil.MockDB{MockTx: tx}
store.On("RunInTx", mock.Anything, mock.Anything).Return(nil).Once()
tx.On("GetClusterForUpdate", mock.Anything, cluster.ID).Return(cluster, nil).Once()
var write *mock.Call
if operation == "create" {
store.On("GetCluster", mock.Anything, cluster.ID).Return(cluster, nil).Once()
tx.On("ListNodePools", mock.Anything, db.NodePoolFilters{ClusterID: &cluster.ID}).Return([]db.NodePool{}, nil).Once()
write = tx.On("CreateNodePool", mock.Anything, mock.Anything).Return(pool, nil).Once()
tx.On("CreateWorkflowOutboxEntry", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(db.WorkflowOutbox{}, nil).Once()
} else {
tx.On("GetNodePool", mock.Anything, pool.ID).Return(pool, nil).Once()
tx.On("GetNodePoolForUpdate", mock.Anything, pool.ID).Return(pool, nil).Once()
write = tx.On("UpdateNodePool", mock.Anything, mock.Anything).Return(pool, nil).Once()
}
var queryErr error
if fails {
queryErr = errors.New("count query failed")
}
if operation == "update" {
tx.On("ListNodePoolCounts", mock.Anything, []db.NodePool{pool}).Return(map[uuid.UUID]db.NodePoolCounts{
pool.ID: {NodeCount: 5, ReadyNodeCount: 3, UpdatedNodeCount: 2},
}, queryErr).Once().NotBefore(write)
}
svc := server.NewNodePoolService(slog.Default(), store, config.TeleportConfig{}, nil)
var result api.NodePool
var err error
if operation == "create" {
var response api.CreateNodePoolResponseObject
response, err = svc.CreateNodePool(t.Context(), api.CreateNodePoolRequestObject{Body: &api.CreateNodePoolRequest{
ClusterID: cluster.ID, Name: "workers", NodeNamePrefix: "w", DesiredNodeCount: 4,
Nico: &api.NicoNodePoolProvider{InstanceTypeID: uuid.New(), SubnetIDs: []uuid.UUID{uuid.New()}, Release: "worker-release"},
}})
if err == nil {
require.IsType(t, api.CreateNodePool201JSONResponse{}, response, "%#v", response)
result = api.NodePool(response.(api.CreateNodePool201JSONResponse))
}
} else {
var response api.UpdateNodePoolResponseObject
response, err = svc.UpdateNodePool(t.Context(), api.UpdateNodePoolRequestObject{NodePoolID: pool.ID, Body: &api.UpdateNodePoolRequest{}})
if err == nil {
result = api.NodePool(response.(api.UpdateNodePool200JSONResponse))
}
}
if fails {
require.ErrorContains(t, err, "count query failed")
} else {
require.NoError(t, err)
if operation == "create" {
require.Zero(t, *result.ObservedNodeCount)
require.Zero(t, *result.ReadyNodeCount)
require.Zero(t, *result.UpdatedNodeCount)
tx.AssertNotCalled(t, "ListNodePoolCounts", mock.Anything, mock.Anything)
} else {
require.Equal(t, 5, *result.ObservedNodeCount)
require.Equal(t, 3, *result.ReadyNodeCount)
require.Equal(t, 2, *result.UpdatedNodeCount)
}
}
store.AssertExpectations(t)
tx.AssertExpectations(t)
store.AssertNotCalled(t, "ListNodePoolCounts", mock.Anything, mock.Anything)
})
}
}
func TestListNodePoolsBatchCounts(t *testing.T) {
pools := []db.NodePool{
{ID: uuid.New(), Name: "first", SystemReservedMemory: "16Gi"},
{ID: uuid.New(), Name: "second", SystemReservedMemory: "32Gi"},
}
store := &testutil.MockDB{}
store.On("ListNodePools", mock.Anything, db.NodePoolFilters{}).Return(pools, nil).Once()
store.On("ListNodePoolCounts", mock.Anything, pools).Return(map[uuid.UUID]db.NodePoolCounts{
pools[0].ID: {NodeCount: 5, ReadyNodeCount: 3, UpdatedNodeCount: 2},
pools[1].ID: {NodeCount: 2, ReadyNodeCount: 1, UpdatedNodeCount: 0},
}, nil).Once()
service := server.NewNodePoolService(slog.Default(), store, config.TeleportConfig{}, nil)
response, err := service.ListNodePools(t.Context(), api.ListNodePoolsRequestObject{})
require.NoError(t, err)
responses := response.(api.ListNodePools200JSONResponse).NodePools
require.Len(t, responses, 2)
require.Equal(t, "first", responses[0].Name)
require.Equal(t, "second", responses[1].Name)
require.Equal(t, "16Gi", *responses[0].SystemReservedMemory)
require.Equal(t, "32Gi", *responses[1].SystemReservedMemory)
require.Equal(t, 5, *responses[0].ObservedNodeCount)
require.Equal(t, 3, *responses[0].ReadyNodeCount)
require.Equal(t, 2, *responses[0].UpdatedNodeCount)
require.Equal(t, 2, *responses[1].ObservedNodeCount)
require.Equal(t, 1, *responses[1].ReadyNodeCount)
require.Zero(t, *responses[1].UpdatedNodeCount)
store.AssertExpectations(t)
}
func TestListNodePoolsEmptyCounts(t *testing.T) {
store := &testutil.MockDB{}
store.On("ListNodePoolCounts", mock.Anything, []db.NodePool{}).Return(map[uuid.UUID]db.NodePoolCounts{}, nil).Once()
store.On("ListNodePools", mock.Anything, db.NodePoolFilters{}).Return([]db.NodePool{}, nil).Once()
service := server.NewNodePoolService(slog.Default(), store, config.TeleportConfig{}, nil)
response, err := service.ListNodePools(t.Context(), api.ListNodePoolsRequestObject{})
require.NoError(t, err)
pools := response.(api.ListNodePools200JSONResponse).NodePools
require.NotNil(t, pools)
require.Empty(t, pools)
store.AssertExpectations(t)
}