mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-09 22:13:18 +09:00
The S3 endpoint the platform backups use is copied twice and neither copy is refreshed. The COSI sidecar writes BucketInfo once per BucketAccess, so the credentials Secret rendered from it keeps its endpoint, and the Velero BSL and the default Strategy CRs keep whatever endpoint the last render of backupstrategy-controller saw. The default objects gate only acted on objects that were missing, so after a publishing.host change every backup kept going to the old host with nothing reporting it. The gate now also forces a render when a copy is stale: the bucket's <bucket>-system release when the credentials Secret's endpoint differs from the COSI Secret it is rendered from, and backupstrategy-controller when the endpoint an object was rendered with differs from the credentials Secret's. That endpoint sits at a different path in every kind, in some only as a bare host, so the chart stamps the rendered value on each object as backups.cozystack.io/endpoint and the gate compares that. Objects rendered before the annotation existed count as stale until one forced render has gone through, which stamps it. The COSI Secret itself still holds the endpoint the BucketAccess was granted with; it follows a host change only once the BucketAccess is re-granted. Assisted-by: LLM Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
301 lines
12 KiB
Go
301 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/kafkatypes"
|
|
"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))
|
|
utilruntime.Must(kafkatypes.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)
|
|
}
|
|
}
|
|
|
|
if err := mgr.Add(&backupcontroller.LegacyPasswordScrubber{Client: mgr.GetClient()}); err != nil {
|
|
setupLog.Error(err, "unable to add LegacyPasswordScrubber 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"),
|
|
},
|
|
CredentialsCOSISecretName: os.Getenv("BACKUP_CREDENTIALS_COSI_SECRET_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)
|
|
}
|
|
}
|