Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 85 additions & 77 deletions cloud/services/server/reconcile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ package server_test

import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"net/http"
Expand Down Expand Up @@ -168,88 +169,95 @@ func lookup(m map[string]any, key string) any {

func TestServiceReconcile(t *testing.T) {
t.Run("creates server with bootVolume and expected payload when not found", func(t *testing.T) {
var (
createPayload map[string]any
recordedServer *server.Server
wasCreated bool
)
spec := server.ServerSpec{
Name: "node-0",
MachineType: "c2i.2",
ImageID: testImageID,
AvailabilityZone: "eu01-1",
SSHKeyName: "default",
NetworkID: testNetworkID,
SecurityGroups: []string{testSecurityGroupID},
UserData: []byte("#cloud-config\n"),
RootVolume: server.RootVolume{
SizeGiB: 50,
PerformanceClass: "storage_premium_perf6",
DeleteOnTermination: true,
},
Tags: map[string]string{"cluster": "test"},
SetServer: func(srv *server.Server, created bool) {
recordedServer = srv
wasCreated = created
},
}
for name, userData := range map[string][]byte{
"cloud-init": []byte("#cloud-config\n"),
"ignition": []byte("{\n \"ignition\": {\"version\": \"3.2.0\"}\n}\n"),
} {
t.Run(name, func(t *testing.T) {
var (
createPayload map[string]any
recordedServer *server.Server
wasCreated bool
)
spec := server.ServerSpec{
Name: "node-0",
MachineType: "c2i.2",
ImageID: testImageID,
AvailabilityZone: "eu01-1",
SSHKeyName: "default",
NetworkID: testNetworkID,
SecurityGroups: []string{testSecurityGroupID},
UserData: userData,
RootVolume: server.RootVolume{
SizeGiB: 50,
PerformanceClass: "storage_premium_perf6",
DeleteOnTermination: true,
},
Tags: map[string]string{"cluster": "test"},
SetServer: func(srv *server.Server, created bool) {
recordedServer = srv
wasCreated = created
},
}

svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers"):
if got := r.URL.Query().Get("label_selector"); got != "cluster=test" {
t.Fatalf("label_selector = %q, want cluster=test", got)
svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers"):
if got := r.URL.Query().Get("label_selector"); got != "cluster=test" {
t.Fatalf("label_selector = %q, want cluster=test", got)
}
if got := r.URL.Query().Get("details"); got != testBoolTrue {
t.Fatalf("details = %q, want true", got)
}
writeJSON(t, w, map[string]any{"items": []any{}})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/servers"):
createPayload = readJSON(t, r)
writeJSON(t, w, map[string]any{
"id": testServerID,
"machineType": "c2i.2",
"name": "node-0",
"status": "ACTIVE",
"availabilityZone": "eu01-1",
})
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers/"+testServerID+"/nics"):
writeJSON(t, w, map[string]any{
"items": []any{
map[string]any{"ipv4": "10.0.0.10", "ipv6": "fd00::10"},
},
})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
}
}))

if err := svc.Reconcile(context.Background()); err != nil {
t.Fatalf("Reconcile() error = %v", err)
}
if got := r.URL.Query().Get("details"); got != testBoolTrue {
t.Fatalf("details = %q, want true", got)
if !wasCreated {
t.Fatal("SetServer created = false, want true")
}
if recordedServer == nil || recordedServer.ID != testServerID || recordedServer.Name != "node-0" || recordedServer.State != "ACTIVE" {
t.Fatalf("recordedServer = %#v", recordedServer)
}
if len(recordedServer.Addresses) != 2 {
t.Fatalf("recordedServer.Addresses = %#v, want 2 addresses", recordedServer.Addresses)
}
writeJSON(t, w, map[string]any{"items": []any{}})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/servers"):
createPayload = readJSON(t, r)
writeJSON(t, w, map[string]any{
"id": testServerID,
"machineType": "c2i.2",
"name": "node-0",
"status": "ACTIVE",
"availabilityZone": "eu01-1",
})
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers/"+testServerID+"/nics"):
writeJSON(t, w, map[string]any{
"items": []any{
map[string]any{"ipv4": "10.0.0.10", "ipv6": "fd00::10"},
},
})
default:
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
}
}))

if err := svc.Reconcile(context.Background()); err != nil {
t.Fatalf("Reconcile() error = %v", err)
}
if !wasCreated {
t.Fatal("SetServer created = false, want true")
}
if recordedServer == nil || recordedServer.ID != testServerID || recordedServer.Name != "node-0" || recordedServer.State != "ACTIVE" {
t.Fatalf("recordedServer = %#v", recordedServer)
assertStringField(t, createPayload, "name", "node-0")
assertStringField(t, createPayload, "machineType", "c2i.2")
assertFieldAbsent(t, createPayload, "imageId")
assertStringField(t, createPayload, "availabilityZone", "eu01-1")
assertStringField(t, createPayload, "keypairName", "default")
assertStringField(t, createPayload, "userData", base64.StdEncoding.EncodeToString(userData))
assertBoolField(t, createPayload, "configDrive", true)
assertNestedStringField(t, createPayload, []string{"labels", "cluster"}, "test")
assertNestedStringField(t, createPayload, []string{"networking", "networkId"}, testNetworkID)
assertNestedStringField(t, createPayload, []string{"bootVolume", "performanceClass"}, "storage_premium_perf6")
assertNestedStringField(t, createPayload, []string{"bootVolume", "source", "id"}, testImageID)
assertNestedStringField(t, createPayload, []string{"bootVolume", "source", "type"}, "image")
assertNestedNumberField(t, createPayload, []string{"bootVolume", "size"}, 50)
})
}
if len(recordedServer.Addresses) != 2 {
t.Fatalf("recordedServer.Addresses = %#v, want 2 addresses", recordedServer.Addresses)
}

assertStringField(t, createPayload, "name", "node-0")
assertStringField(t, createPayload, "machineType", "c2i.2")
assertFieldAbsent(t, createPayload, "imageId")
assertStringField(t, createPayload, "availabilityZone", "eu01-1")
assertStringField(t, createPayload, "keypairName", "default")
assertStringField(t, createPayload, "userData", "I2Nsb3VkLWNvbmZpZwo=")
assertBoolField(t, createPayload, "configDrive", true)
assertNestedStringField(t, createPayload, []string{"labels", "cluster"}, "test")
assertNestedStringField(t, createPayload, []string{"networking", "networkId"}, testNetworkID)
assertNestedStringField(t, createPayload, []string{"bootVolume", "performanceClass"}, "storage_premium_perf6")
assertNestedStringField(t, createPayload, []string{"bootVolume", "source", "id"}, testImageID)
assertNestedStringField(t, createPayload, []string{"bootVolume", "source", "type"}, "image")
assertNestedNumberField(t, createPayload, []string{"bootVolume", "size"}, 50)
})

t.Run("creates server with imageId when rootVolume size and performanceClass are unset", func(t *testing.T) {
Expand Down
41 changes: 39 additions & 2 deletions cmd/manager/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,22 @@ package main
import (
"crypto/tls"
"flag"
"fmt"
"os"
"strings"

// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
_ "k8s.io/client-go/plugin/pkg/client/auth"

"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/validation"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2"
"sigs.k8s.io/cluster-api/util/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
Expand Down Expand Up @@ -63,6 +67,7 @@ func main() {
var metricsCertPath, metricsCertName, metricsCertKey string
var webhookCertPath, webhookCertName, webhookCertKey string
var enableLeaderElection bool
var namespace, leaderElectionNamespace string
var probeAddr string
var secureMetrics bool
var enableHTTP2 bool
Expand All @@ -73,6 +78,9 @@ func main() {
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.StringVar(&namespace, "namespace", "", "Namespace to watch. Leave empty to watch all namespaces.")
flag.StringVar(&leaderElectionNamespace, "leader-election-namespace", "",
"Namespace for leader election leases. Defaults to --namespace when set, otherwise the pod namespace.")
flag.BoolVar(&secureMetrics, "metrics-secure", true,
"If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.")
flag.StringVar(&webhookCertPath, "webhook-cert-path", "", "The directory that contains the webhook certificate.")
Expand Down Expand Up @@ -159,7 +167,7 @@ func main() {
metricsServerOptions.KeyName = metricsCertKey
}

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
managerOptions := ctrl.Options{
Scheme: scheme,
Metrics: metricsServerOptions,
WebhookServer: webhookServer,
Expand All @@ -177,7 +185,12 @@ func main() {
// if you are doing or is intended to do any operation such as perform cleanups
// after the manager stops then its usage might be unsafe.
// LeaderElectionReleaseOnCancel: true,
})
}
if err := configureNamespaces(&managerOptions, namespace, leaderElectionNamespace); err != nil {
setupLog.Error(err, "Invalid namespace configuration")
os.Exit(1)
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), managerOptions)
if err != nil {
setupLog.Error(err, "Failed to start manager")
os.Exit(1)
Expand Down Expand Up @@ -237,3 +250,27 @@ func main() {
os.Exit(1)
}
}

// configureNamespaces keeps the cached reads and watches in the requested
// namespace. The default lease namespace follows the watch namespace so that
// multiple namespaced managers can each elect a leader using namespaced RBAC.
func configureNamespaces(options *ctrl.Options, namespace, leaderElectionNamespace string) error {
for name, value := range map[string]string{
"namespace": namespace, "leader-election-namespace": leaderElectionNamespace,
} {
if value == "" {
continue
}
if problems := validation.IsDNS1123Label(value); len(problems) > 0 {
return fmt.Errorf("--%s must be a valid namespace: %s", name, strings.Join(problems, "; "))
}
}
if namespace != "" {
options.Cache.DefaultNamespaces = map[string]cache.Config{namespace: {}}
if leaderElectionNamespace == "" {
leaderElectionNamespace = namespace
}
}
options.LeaderElectionNamespace = leaderElectionNamespace
return nil
}
Loading