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
6 changes: 0 additions & 6 deletions charts/openstack-hypervisor-operator/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@ controllerManager:
- --metrics-bind-address=:8443
- --leader-elect
- --health-probe-bind-address=:8081
- --certificate-namespace=$(CERTIFICATE_NAMESPACE)
- --certificate-issuer-name=$(CERTIFICATE_ISSUER_NAME)
- --label-selector=$(LABEL_SELECTOR)
- --agent-namespaces=$(AGENT_NAMESPACES)
- --eviction-concurrency=$(EVICTION_CONCURRENCY)
- --eviction-trait-concurrency=$(EVICTION_TRAIT_CONCURRENCY)
containerSecurityContext:
allowPrivilegeEscalation: false
capabilities:
Expand Down
106 changes: 30 additions & 76 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,14 @@ package main
import (
"crypto/sha256"
"crypto/tls"
"errors"
"flag"
"fmt"
"os"
gruntime "runtime"
"strconv"
"strings"

"github.com/itzg/go-flagsfiller"
"github.com/sapcc/go-api-declarations/bininfo"

// 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"
Expand All @@ -52,10 +51,10 @@ import (
"sigs.k8s.io/controller-runtime/pkg/webhook"

kvmv1 "github.com/cobaltcore-dev/openstack-hypervisor-operator/api/v1"
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/config"
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/controller"
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/controller/eviction"
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/controller/ready"
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/global"
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/logger"

// +kubebuilder:scaffold:imports
Expand All @@ -77,6 +76,12 @@ func init() {
utilruntime.Must(cmapi.AddToScheme(scheme))
}

type options struct {
Shared config.Shared `flatten:"true"`
Certificate controller.CertificateOptions
Eviction eviction.Options
}

func main() {
var version bool
var metricsAddr string
Expand All @@ -85,8 +90,6 @@ func main() {
var secureMetrics bool
var enableHTTP2 bool
var tlsOpts []func(*tls.Config)
var certificateNamespace string
var certificateIssuerName string

flag.BoolVar(&version, "version", false,
"Print the version and exit.")
Expand All @@ -100,23 +103,13 @@ func main() {
"If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.")
flag.BoolVar(&enableHTTP2, "enable-http2", false,
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
flag.StringVar(&global.LabelSelector, "label-selector", "", "Label selector to filter watched resources (namely nodes).")

var agentNamespacesFlag string
flag.StringVar(&agentNamespacesFlag, "agent-namespaces", "",
"Comma-separated list of namespaces to search for agent pods (nova-compute, neutron) during offboarding.")

flag.IntVar(&global.EvictionConcurrency, "eviction-concurrency", 1,
"Default maximum number of VM migrations to run concurrently while draining a hypervisor. Defaults to 1 (serial).")

var evictionTraitConcurrencyFlag string
flag.StringVar(&evictionTraitConcurrencyFlag, "eviction-trait-concurrency", "",
"Comma-separated TRAIT=N overrides for per-host migration concurrency, e.g. "+
"CUSTOM_HANA_EXCLUSIVE_HOST=1,CUSTOM_FOO=2. The lowest matching trait limit wins.")

flag.StringVar(&certificateNamespace, "certificate-namespace", "monsoon3", "The namespace for the certificates. ")
flag.StringVar(&certificateIssuerName, "certificate-issuer-name", "nova-hypervisor-agents-ca-issuer",
"Name of the certificate issuer.")
var cfg options
filler := flagsfiller.New(flagsfiller.WithEnv(""))
if err := filler.Fill(flag.CommandLine, &cfg); err != nil {
fmt.Fprintf(os.Stderr, "invalid configuration: %v\n", err)
os.Exit(1)
}

opts := ctrlzap.Options{
Development: true,
Expand All @@ -137,62 +130,23 @@ func main() {
os.Exit(0)
}

if agentNamespacesFlag != "" {
// Deduplicate. Without this, repeated entries (e.g. from templated
// values) would cause redundant pod-list calls and inflate the
// AgentPodsEvicted condition message with duplicate pod names.
seen := map[string]struct{}{}
for ns := range strings.SplitSeq(agentNamespacesFlag, ",") {
ns = strings.TrimSpace(ns)
if ns == "" {
continue
}
if _, ok := seen[ns]; ok {
continue
}
seen[ns] = struct{}{}
global.AgentNamespaces = append(global.AgentNamespaces, ns)
}
}

if len(global.AgentNamespaces) == 0 {
setupLog.Error(errors.New("--agent-namespaces is required"), "invalid configuration")
os.Exit(1)
}
ctrl.SetLogger(ctrlzap.New(ctrlzap.UseFlagOptions(&opts)))

if global.EvictionConcurrency < 1 {
setupLog.Error(errors.New("--eviction-concurrency must be >= 1"), "invalid configuration")
if err := cfg.Shared.Validate(); err != nil {
setupLog.Error(err, "invalid configuration")
os.Exit(1)
}

for entry := range strings.SplitSeq(evictionTraitConcurrencyFlag, ",") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
trait, value, ok := strings.Cut(entry, "=")
trait = strings.TrimSpace(trait)
n, err := strconv.Atoi(strings.TrimSpace(value))
if !ok || trait == "" || err != nil || n < 1 {
setupLog.Error(errors.New("invalid --eviction-trait-concurrency entry: "+entry),
"invalid configuration", "expected", "TRAIT=N with N >= 1")
os.Exit(1)
}
global.EvictionTraitConcurrency[trait] = n
}

if certificateIssuerName == "" {
setupLog.Error(errors.New("certificate-issuer-name cannot be empty"), "invalid certificate issuer name")
if err := cfg.Eviction.Validate(); err != nil {
setupLog.Error(err, "invalid configuration")
os.Exit(1)
}

if certificateNamespace == "" {
setupLog.Error(errors.New("certificate-namespace cannot be empty"), "invalid certificate namespace")
if err := cfg.Certificate.Validate(); err != nil {
setupLog.Error(err, "invalid configuration")
os.Exit(1)
}

ctrl.SetLogger(ctrlzap.New(ctrlzap.UseFlagOptions(&opts)))

// if the enable-http2 flag is false (the default), http/2 should be disabled
// due to its vulnerabilities. More specifically, disabling http/2 will
// prevent from being vulnerable to the HTTP/2 Stream Cancellation and
Expand Down Expand Up @@ -260,9 +214,9 @@ func main() {
&policyv1.PodDisruptionBudget{}: maintenanceCacheConfig,
},
}
if global.LabelSelector != "" {
setupLog.Info("setting up cache with label selector", "selector", global.LabelSelector)
selector, err := labels.Parse(global.LabelSelector)
if cfg.Shared.LabelSelector != "" {
setupLog.Info("setting up cache with label selector", "selector", cfg.Shared.LabelSelector)
selector, err := labels.Parse(cfg.Shared.LabelSelector)
if err != nil {
setupLog.Error(err, "unable to parse label selector")
os.Exit(1)
Expand All @@ -273,7 +227,7 @@ func main() {

h := sha256.New()
h.Write([]byte(leaderElectionID)) // Seed it with something "unique" to the project
h.Write([]byte(global.LabelSelector))
h.Write([]byte(cfg.Shared.LabelSelector))
leaderElectionID = fmt.Sprintf("%x.cloud.sap", h.Sum(nil))
}

Expand Down Expand Up @@ -315,7 +269,7 @@ func main() {
if err = (&controller.HypervisorController{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
}).SetupWithManager(mgr, cfg.Shared); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Hypervisor")
os.Exit(1)
}
Expand All @@ -331,7 +285,7 @@ func main() {
if err = (&eviction.EvictionReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
}).SetupWithManager(mgr, cfg.Eviction); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Eviction")
os.Exit(1)
}
Expand All @@ -355,15 +309,15 @@ func main() {
if err = (&controller.NodeCertificateController{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr, certificateNamespace, certificateIssuerName); err != nil {
}).SetupWithManager(mgr, cfg.Certificate); err != nil {
setupLog.Error(err, "unable to create controller", "certificate", "NodeCertificate")
os.Exit(1)
}

if err = (&controller.GardenerNodeLifecycleController{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr, certificateNamespace); err != nil {
}).SetupWithManager(mgr, cfg.Certificate.Namespace); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Maintenance")
os.Exit(1)
}
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ require (
github.com/go-logr/logr v1.4.4
github.com/gophercloud/gophercloud/v2 v2.15.0
github.com/gophercloud/utils/v2 v2.0.0-20260922174841-b4759ea0529b
github.com/itzg/go-flagsfiller v1.19.0
github.com/onsi/ginkgo/v2 v2.33.1
github.com/onsi/gomega v1.44.0
github.com/sapcc/go-api-declarations v1.25.1
Expand Down Expand Up @@ -62,6 +63,7 @@ require (
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,12 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF2
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/itzg/go-flagsfiller v1.19.0 h1:CiT97rDZJrRvWoiVzbx/mRM+/fn+GQ6cRMMa/x3psBs=
github.com/itzg/go-flagsfiller v1.19.0/go.mod h1:Zq4PnNALfrY73hVPlg7GExLxm3lVRu90895WVe8NQVg=
github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE=
github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
Expand Down
50 changes: 50 additions & 0 deletions internal/config/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
SPDX-FileCopyrightText: Copyright 2025 SAP SE or an SAP affiliate company and cobaltcore-dev contributors
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package config

import (
"errors"
"slices"
"strings"
)

// Shared contains configuration options used by more than one controller.
type Shared struct {
LabelSelector string `usage:"Label selector to filter watched resources (namely nodes)."`
AgentNamespaces []string `usage:"Comma-separated list of namespaces to search for agent pods (nova-compute, neutron) during offboarding." override-value:"true"`
}

// Validate normalizes the agent namespace list and requires at least one
// namespace to remain.
func (s *Shared) Validate() error {
namespaces := make([]string, 0, len(s.AgentNamespaces))
for _, namespace := range s.AgentNamespaces {
namespace = strings.TrimSpace(namespace)
if namespace == "" || slices.Contains(namespaces, namespace) {
continue
}
namespaces = append(namespaces, namespace)
}
s.AgentNamespaces = namespaces

if len(namespaces) == 0 {
return errors.New("--agent-namespaces (AGENT_NAMESPACES) must contain at least one namespace")
}

return nil
}
7 changes: 5 additions & 2 deletions internal/controller/eviction/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type EvictionReconciler struct {
client.Client
Scheme *runtime.Scheme
computeClient *gophercloud.ServiceClient
Options Options
}

const (
Expand Down Expand Up @@ -173,7 +174,7 @@ func (r *EvictionReconciler) handleRunning(ctx context.Context, eviction *kvmv1.

// That should leave us with "Running" and the hypervisor should be deactivated
if len(eviction.Status.OutstandingInstances) > 0 {
limit := global.ResolveConcurrency(hypervisor.Status.Traits)
limit := r.Options.ResolveConcurrency(hypervisor.Status.Traits)
return r.evictNext(ctx, eviction, limit)
}

Expand Down Expand Up @@ -533,7 +534,9 @@ func (r *EvictionReconciler) registerWithManager(mgr ctrl.Manager) error {
}

// SetupWithManager sets up the controller with the Manager.
func (r *EvictionReconciler) SetupWithManager(mgr ctrl.Manager) error {
func (r *EvictionReconciler) SetupWithManager(mgr ctrl.Manager, options Options) error {
r.Options = options

ctx := context.Background()

var err error
Expand Down
25 changes: 12 additions & 13 deletions internal/controller/eviction/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import (
ctrl "sigs.k8s.io/controller-runtime"

kvmv1 "github.com/cobaltcore-dev/openstack-hypervisor-operator/api/v1"
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/global"
)

var _ = Describe("Instance slice helpers", func() {
Expand Down Expand Up @@ -663,9 +662,9 @@ var _ = Describe("Eviction Controller", func() {
}

It("starts at most `limit` migrations per pass and never exceeds it in flight", func(ctx SpecContext) {
orig := global.EvictionConcurrency
global.EvictionConcurrency = 3
DeferCleanup(func() { global.EvictionConcurrency = orig })
orig := evictionReconciler.Options.Concurrency
evictionReconciler.Options.Concurrency = 3
DeferCleanup(func() { evictionReconciler.Options.Concurrency = orig })

seedVMs(ctx, 5)
resource := &kvmv1.Eviction{}
Expand Down Expand Up @@ -704,9 +703,9 @@ var _ = Describe("Eviction Controller", func() {
// with task_state "migrating" for a while before Status becomes
// MIGRATING. If those aren't counted as in-flight, the loop keeps
// triggering and exceeds the concurrency limit.
orig := global.EvictionConcurrency
global.EvictionConcurrency = 2
DeferCleanup(func() { global.EvictionConcurrency = orig })
orig := evictionReconciler.Options.Concurrency
evictionReconciler.Options.Concurrency = 2
DeferCleanup(func() { evictionReconciler.Options.Concurrency = orig })

const tmpl = `{
"server": {
Expand Down Expand Up @@ -798,13 +797,13 @@ var _ = Describe("Eviction Controller", func() {
})

It("forces serial migration for hosts carrying the exclusive trait", func(ctx SpecContext) {
orig := global.EvictionConcurrency
origMap := global.EvictionTraitConcurrency
global.EvictionConcurrency = 4
global.EvictionTraitConcurrency = map[string]int{"CUSTOM_HANA_EXCLUSIVE_HOST": 1}
orig := evictionReconciler.Options.Concurrency
origMap := evictionReconciler.Options.TraitConcurrency
evictionReconciler.Options.Concurrency = 4
evictionReconciler.Options.TraitConcurrency = map[string]string{"CUSTOM_HANA_EXCLUSIVE_HOST": "1"}
DeferCleanup(func() {
global.EvictionConcurrency = orig
global.EvictionTraitConcurrency = origMap
evictionReconciler.Options.Concurrency = orig
evictionReconciler.Options.TraitConcurrency = origMap
})

By("Marking the hypervisor with the exclusive trait")
Expand Down
Loading
Loading