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
8 changes: 0 additions & 8 deletions charts/openstack-hypervisor-operator/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,6 @@ controllerManager:
- --metrics-bind-address=:8443
- --leader-elect
- --health-probe-bind-address=:8081
- --certificate-namespace=$(CERTIFICATE_NAMESPACE)
- --certificate-issuer-name=$(CERTIFICATE_ISSUER_NAME)
- --certificate-interface-include-regex=$(CERTIFICATE_INTERFACE_INCLUDE_REGEX)
- --certificate-interface-exclude-regex=$(CERTIFICATE_INTERFACE_EXCLUDE_REGEX)
- --label-selector=$(LABEL_SELECTOR)
- --agent-namespaces=$(AGENT_NAMESPACES)
- --eviction-concurrency=$(EVICTION_CONCURRENCY)
- --eviction-trait-concurrency=$(EVICTION_TRAIT_CONCURRENCY)
containerSecurityContext:
allowPrivilegeEscalation: false
capabilities:
Expand Down
118 changes: 30 additions & 88 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 @@ -55,7 +54,6 @@ import (
"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 +75,12 @@ func init() {
utilruntime.Must(cmapi.AddToScheme(scheme))
}

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

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

flag.BoolVar(&version, "version", false,
"Print the version and exit.")
Expand All @@ -102,31 +102,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.")
flag.StringVar(&certificateInterfaceIncludeRegex, "certificate-interface-include-regex", `^vlan_[0-9]+$`,
"Regular expression matching node interface names from the projectcalico.org/Interfaces annotation "+
"whose IP addresses are added to the hypervisor certificate. "+
"An empty expression includes all interfaces.")
flag.StringVar(&certificateInterfaceExcludeRegex, "certificate-interface-exclude-regex", "",
"Regular expression matching node interface names whose IP addresses are excluded "+
"from the hypervisor certificate. Applied after the include expression; "+
"an empty expression excludes no interfaces.")

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 @@ -147,62 +129,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 @@ -270,9 +213,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 @@ -283,7 +226,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 @@ -325,7 +268,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 @@ -341,7 +284,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 @@ -365,16 +308,15 @@ func main() {
if err = (&controller.NodeCertificateController{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr, certificateNamespace, certificateIssuerName,
certificateInterfaceIncludeRegex, certificateInterfaceExcludeRegex); 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 @@ -61,6 +62,7 @@ require (
github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // 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 @@ -105,8 +105,12 @@ github.com/gophercloud/utils/v2 v2.0.0-20260922174841-b4759ea0529b h1:G2KBa3ku8m
github.com/gophercloud/utils/v2 v2.0.0-20260922174841-b4759ea0529b/go.mod h1:lRwTjtOLb5RKkrSVZDvHoxYbzcIs5fO89Ll2CDCuwic=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
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
49 changes: 47 additions & 2 deletions internal/controller/eviction/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"

"github.com/gophercloud/gophercloud/v2"
Expand All @@ -42,11 +43,53 @@ import (
"github.com/cobaltcore-dev/openstack-hypervisor-operator/internal/utils"
)

// Options configures the eviction controller.
type Options struct {
Concurrency int `default:"1" usage:"Default maximum number of VM migrations to run concurrently while draining a hypervisor. Defaults to 1 (serial)."`
TraitConcurrency map[string]string `usage:"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."`
}

// ResolveConcurrency returns the maximum number of concurrent migrations
// for a host given its traits: the default, lowered by the lowest matching
// trait limit, and never below 1.
func (o Options) ResolveConcurrency(traits []string) int {
limit := o.Concurrency
for _, trait := range traits {
if value, ok := o.TraitConcurrency[trait]; ok {
if traitLimit, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && traitLimit < limit {
limit = traitLimit
}
}
}
return max(limit, 1)
}

// Validate checks that the concurrency and every trait limit are >= 1 and
// that trait names are not empty and have no surrounding whitespace.
func (o Options) Validate() error {
if o.Concurrency < 1 {
return fmt.Errorf("--eviction-concurrency (EVICTION_CONCURRENCY) must be >= 1, got %d", o.Concurrency)
}

for trait, value := range o.TraitConcurrency {
limit, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || limit < 1 {
return fmt.Errorf("--eviction-trait-concurrency (EVICTION_TRAIT_CONCURRENCY): trait %q must have an integer limit >= 1, got %q", trait, value)
}
if trait == "" || trait != strings.TrimSpace(trait) {
return fmt.Errorf("--eviction-trait-concurrency (EVICTION_TRAIT_CONCURRENCY): trait name %q must not be empty or have leading/trailing whitespace", trait)
}
}

return nil
}

// EvictionReconciler reconciles a Eviction object
type EvictionReconciler struct {
client.Client
Scheme *runtime.Scheme
computeClient *gophercloud.ServiceClient
Options Options
}

const (
Expand Down Expand Up @@ -173,7 +216,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 +576,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