mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-03 18:47:04 +09:00
RabbitMQ's cluster operator ships no backup CRD and RabbitMQ has no
consistent online export of message payloads, so back up broker
DEFINITIONS (vhosts, users, permissions, queues, exchanges, bindings,
policies, parameters) over the management HTTP API and store them in the
system bucket. Message payloads and PITR are out of scope - a full-data
backup is a Velero volume snapshot, a separate strategy.
Add a first-class strategy.backups.cozystack.io/Rabbitmq driver, following
the Altinity pattern (a dedicated driver that renders a one-shot Job for an
HTTP-API engine):
- reconcileRabbitmq / reconcileRabbitmqRestore render the strategy's
PodTemplateSpec (curl GET/POST /api/definitions, push/pull to S3 with
--aws-sigv4) as a batch/v1.Job, for both in-place and to-copy restore.
- A Go-read precondition gates each run on the RabbitmqCluster reporting
AllReplicasReady (via the rabbitmqtypes partial type), surfacing a
precise Ready=False wait instead of a Job that starts and fails.
- The produced Backup records the object location on status.artifact.uri
(rendered from spec.artifactURITemplate; the Backup CRD has no status
subresource, so it persists on Create, as in the Etcd driver).
Wire dispatch in both controllers + supportedBackupStrategyKinds, register
rabbitmqtypes in the scheme, and grant read on rabbitmqclusters. Ship
cozy-default-rabbitmq (a $bucketName-gated Rabbitmq strategy) and route
apps.cozystack.io/RabbitMQ to it in the cozy-default BackupClass. The
application chart is untouched.
Add unit tests for the driver's pure helpers and the precondition gate, a
runnable example, and an honest-roundtrip Chainsaw e2e that seeds a
sentinel vhost, backs it up, drops it, and asserts it round-trips through
object storage on both restore flows.
The Job pod reuses the platform-migrations image (curl + ca-certificates)
under a new rabbitmqBackupClientImage key, stamped in lockstep with
chBackupClientImage so the repository stays pinned at one digest; a
dedicated slim image is a follow-up.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
293 lines
12 KiB
Go
293 lines
12 KiB
Go
/*
|
|
Copyright 2025.
|
|
|
|
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 main
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"flag"
|
|
"os"
|
|
|
|
// 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"
|
|
|
|
corev1 "k8s.io/api/core/v1"
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
"k8s.io/apimachinery/pkg/types"
|
|
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
|
|
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
|
|
ctrl "sigs.k8s.io/controller-runtime"
|
|
"sigs.k8s.io/controller-runtime/pkg/cache"
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
"sigs.k8s.io/controller-runtime/pkg/healthz"
|
|
"sigs.k8s.io/controller-runtime/pkg/log/zap"
|
|
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
|
|
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
|
|
"sigs.k8s.io/controller-runtime/pkg/webhook"
|
|
|
|
strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1"
|
|
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/cnpgtypes"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/etcdapp"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/etcdtypes"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/foundationdbapp"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/foundationdbtypes"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/mariadbapp"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/mariadbtypes"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/mongodbapp"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/postgresapp"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/psmdbtypes"
|
|
"github.com/cozystack/cozystack/internal/backupcontroller/rabbitmqtypes"
|
|
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
|
|
// +kubebuilder:scaffold:imports
|
|
)
|
|
|
|
var (
|
|
scheme = runtime.NewScheme()
|
|
setupLog = ctrl.Log.WithName("setup")
|
|
)
|
|
|
|
func init() {
|
|
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
|
|
|
|
utilruntime.Must(backupsv1alpha1.AddToScheme(scheme))
|
|
utilruntime.Must(strategyv1alpha1.AddToScheme(scheme))
|
|
utilruntime.Must(velerov1.AddToScheme(scheme))
|
|
utilruntime.Must(cnpgtypes.AddToScheme(scheme))
|
|
utilruntime.Must(postgresapp.AddToScheme(scheme))
|
|
utilruntime.Must(mariadbtypes.AddToScheme(scheme))
|
|
utilruntime.Must(mariadbapp.AddToScheme(scheme))
|
|
utilruntime.Must(psmdbtypes.AddToScheme(scheme))
|
|
utilruntime.Must(mongodbapp.AddToScheme(scheme))
|
|
utilruntime.Must(foundationdbtypes.AddToScheme(scheme))
|
|
utilruntime.Must(foundationdbapp.AddToScheme(scheme))
|
|
utilruntime.Must(etcdtypes.AddToScheme(scheme))
|
|
utilruntime.Must(etcdapp.AddToScheme(scheme))
|
|
utilruntime.Must(rabbitmqtypes.AddToScheme(scheme))
|
|
// +kubebuilder:scaffold:scheme
|
|
}
|
|
|
|
func main() {
|
|
var metricsAddr string
|
|
var enableLeaderElection bool
|
|
var probeAddr string
|
|
var secureMetrics bool
|
|
var enableHTTP2 bool
|
|
var tlsOpts []func(*tls.Config)
|
|
flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
|
|
"Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.")
|
|
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
|
|
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
|
|
"Enable leader election for controller manager. "+
|
|
"Enabling this will ensure there is only one active controller manager.")
|
|
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.BoolVar(&enableHTTP2, "enable-http2", false,
|
|
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
|
|
opts := zap.Options{
|
|
Development: false,
|
|
}
|
|
opts.BindFlags(flag.CommandLine)
|
|
flag.Parse()
|
|
|
|
ctrl.SetLogger(zap.New(zap.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
|
|
// Rapid Reset CVEs. For more information see:
|
|
// - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
|
|
// - https://github.com/advisories/GHSA-4374-p667-p6c8
|
|
disableHTTP2 := func(c *tls.Config) {
|
|
setupLog.Info("disabling http/2")
|
|
c.NextProtos = []string{"http/1.1"}
|
|
}
|
|
|
|
if !enableHTTP2 {
|
|
tlsOpts = append(tlsOpts, disableHTTP2)
|
|
}
|
|
|
|
webhookServer := webhook.NewServer(webhook.Options{
|
|
TLSOpts: tlsOpts,
|
|
})
|
|
|
|
// Metrics endpoint is enabled in 'config/default/kustomization.yaml'. The Metrics options configure the server.
|
|
// More info:
|
|
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.19.1/pkg/metrics/server
|
|
// - https://book.kubebuilder.io/reference/metrics.html
|
|
metricsServerOptions := metricsserver.Options{
|
|
BindAddress: metricsAddr,
|
|
SecureServing: secureMetrics,
|
|
TLSOpts: tlsOpts,
|
|
}
|
|
|
|
if secureMetrics {
|
|
// FilterProvider is used to protect the metrics endpoint with authn/authz.
|
|
// These configurations ensure that only authorized users and service accounts
|
|
// can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info:
|
|
// https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.19.1/pkg/metrics/filters#WithAuthenticationAndAuthorization
|
|
metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
|
|
|
|
// TODO(user): If CertDir, CertName, and KeyName are not specified, controller-runtime will automatically
|
|
// generate self-signed certificates for the metrics server. While convenient for development and testing,
|
|
// this setup is not recommended for production.
|
|
}
|
|
|
|
// Configure rate limiting for the Kubernetes client
|
|
config := ctrl.GetConfigOrDie()
|
|
config.QPS = 50.0 // Increased from default 5.0
|
|
config.Burst = 100 // Increased from default 10
|
|
|
|
mgr, err := ctrl.NewManager(config, ctrl.Options{
|
|
Scheme: scheme,
|
|
Metrics: metricsServerOptions,
|
|
WebhookServer: webhookServer,
|
|
HealthProbeBindAddress: probeAddr,
|
|
LeaderElection: enableLeaderElection,
|
|
LeaderElectionID: "strategy.backups.cozystack.io",
|
|
Cache: cache.Options{
|
|
ByObject: map[client.Object]cache.ByObject{
|
|
&backupsv1alpha1.BackupClass{}: {},
|
|
},
|
|
},
|
|
Client: client.Options{
|
|
// Disable the controller-runtime cache for Secrets entirely.
|
|
// The credentials projector does point Get + CreateOrUpdate
|
|
// against arbitrary tenant namespaces, and a cluster-wide
|
|
// Secret informer would (a) require list/watch RBAC the chart
|
|
// explicitly does NOT grant, (b) keep every tenant Secret in
|
|
// the controller's RAM. Direct apiserver calls keep the
|
|
// blast radius bounded to the namespaces actively reconciled.
|
|
Cache: &client.CacheOptions{
|
|
DisableFor: []client.Object{&corev1.Secret{}},
|
|
},
|
|
},
|
|
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
|
|
// when the Manager ends. This requires the binary to immediately end when the
|
|
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
|
|
// speeds up voluntary leader transitions as the new leader don't have to wait
|
|
// LeaseDuration time first.
|
|
//
|
|
// In the default scaffold provided, the program ends immediately after
|
|
// the manager stops, so would be fine to enable this option. However,
|
|
// 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 != nil {
|
|
setupLog.Error(err, "unable to start manager")
|
|
os.Exit(1)
|
|
}
|
|
|
|
credentialsConfig := backupcontroller.BackupCredentialsConfig{
|
|
SourceNamespace: os.Getenv("BACKUP_STORAGE_SECRET_NAMESPACE"),
|
|
SourceSecretName: os.Getenv("BACKUP_STORAGE_SECRET_NAME"),
|
|
TargetSecretName: os.Getenv("BACKUP_STORAGE_CREDS_SECRET_NAME"),
|
|
Endpoint: os.Getenv("BACKUP_STORAGE_ENDPOINT"),
|
|
Region: os.Getenv("BACKUP_STORAGE_REGION"),
|
|
ForcePathStyle: os.Getenv("BACKUP_STORAGE_FORCE_PATH_STYLE"),
|
|
}
|
|
|
|
if systemNamespaces := os.Getenv("BACKUP_STORAGE_SYSTEM_NAMESPACES"); systemNamespaces != "" {
|
|
if err := mgr.Add(backupcontroller.NewSystemCredentialsProjector(mgr.GetClient(), credentialsConfig, systemNamespaces, 0)); err != nil {
|
|
setupLog.Error(err, "unable to add SystemCredentialsProjector runnable")
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
// The default Strategy CRs and the Velero BSL are Helm-templated behind
|
|
// a lookup of the BucketClaim the same chart creates, so a fresh install
|
|
// renders them empty — permanently, because helm-controller does not
|
|
// re-render an unchanged, successful release. The gate detects that and
|
|
// forces the one real Helm upgrade that materialises them. Disabled when
|
|
// the HelmRelease coordinates are not plumbed (e.g. a chart-less local run).
|
|
if hrName := os.Getenv("BACKUP_DEFAULT_OBJECTS_HELMRELEASE_NAME"); hrName != "" {
|
|
gate := &backupcontroller.DefaultObjectsGate{
|
|
Client: mgr.GetClient(),
|
|
Config: credentialsConfig,
|
|
BackupClassName: os.Getenv("BACKUP_DEFAULT_OBJECTS_BACKUPCLASS"),
|
|
HelmRelease: types.NamespacedName{
|
|
Namespace: os.Getenv("BACKUP_DEFAULT_OBJECTS_HELMRELEASE_NAMESPACE"),
|
|
Name: hrName,
|
|
},
|
|
VeleroNamespace: os.Getenv("BACKUP_DEFAULT_OBJECTS_VELERO_NAMESPACE"),
|
|
// The platform bucket's <bucket>-system release renders the
|
|
// credentials Secret the projector reads, behind the same kind
|
|
// of install-time lookup — and while that Secret is missing
|
|
// nothing downstream can resolve. Empty when the bucket is not
|
|
// provisioned by Cozystack (external S3), where the Secret is
|
|
// admin-managed and no release renders it.
|
|
CredentialsHelmRelease: types.NamespacedName{
|
|
Namespace: os.Getenv("BACKUP_CREDENTIALS_HELMRELEASE_NAMESPACE"),
|
|
Name: os.Getenv("BACKUP_CREDENTIALS_HELMRELEASE_NAME"),
|
|
},
|
|
}
|
|
if err := gate.SetupWithManager(mgr); err != nil {
|
|
setupLog.Error(err, "unable to add DefaultObjectsGate runnable")
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
if err = (&backupcontroller.BackupJobReconciler{
|
|
Client: mgr.GetClient(),
|
|
Scheme: mgr.GetScheme(),
|
|
Recorder: mgr.GetEventRecorderFor("backup-controller"),
|
|
CredentialsConfig: credentialsConfig,
|
|
}).SetupWithManager(mgr); err != nil {
|
|
setupLog.Error(err, "unable to create controller", "controller", "BackupJob")
|
|
os.Exit(1)
|
|
}
|
|
|
|
if err = (&backupcontroller.RestoreJobReconciler{
|
|
Client: mgr.GetClient(),
|
|
Scheme: mgr.GetScheme(),
|
|
Recorder: mgr.GetEventRecorderFor("restore-controller"),
|
|
CredentialsConfig: credentialsConfig,
|
|
}).SetupWithManager(mgr); err != nil {
|
|
setupLog.Error(err, "unable to create controller", "controller", "RestoreJob")
|
|
os.Exit(1)
|
|
}
|
|
|
|
if err = (&backupcontroller.BackupReconciler{
|
|
Client: mgr.GetClient(),
|
|
Scheme: mgr.GetScheme(),
|
|
Recorder: mgr.GetEventRecorderFor("backup-controller"),
|
|
CredentialsConfig: credentialsConfig,
|
|
}).SetupWithManager(mgr); err != nil {
|
|
setupLog.Error(err, "unable to create controller", "controller", "Backup")
|
|
os.Exit(1)
|
|
}
|
|
|
|
// +kubebuilder:scaffold:builder
|
|
|
|
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
|
|
setupLog.Error(err, "unable to set up health check")
|
|
os.Exit(1)
|
|
}
|
|
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
|
|
setupLog.Error(err, "unable to set up ready check")
|
|
os.Exit(1)
|
|
}
|
|
|
|
setupLog.Info("starting manager")
|
|
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
|
|
setupLog.Error(err, "problem running manager")
|
|
os.Exit(1)
|
|
}
|
|
}
|