Skip to content

Commit 1f0b5ff

Browse files
authored
[backups] Stub the Job backup strategy controller (#1720)
## What this PR does This PR introduces a bare-bones Job backup strategy API type and stubs out all the boilerplate for a new controller that will handle this strategy, as well as any others in the `strategy.backups.cozystack.io` API group. ### Release note ```release-note [backups] Create stubs and minimal implmentations for controllers for the strategy.backups.cozystack.io API group. ```
2 parents 1ec14d6 + ee2a34c commit 1f0b5ff

16 files changed

Lines changed: 8551 additions & 0 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// Package v1alpha1 defines strategy.backups.cozystack.io API types.
3+
//
4+
// Group: strategy.backups.cozystack.io
5+
// Version: v1alpha1
6+
package v1alpha1
7+
8+
import (
9+
corev1 "k8s.io/api/core/v1"
10+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
11+
"k8s.io/apimachinery/pkg/runtime"
12+
)
13+
14+
func init() {
15+
SchemeBuilder.Register(func(s *runtime.Scheme) error {
16+
s.AddKnownTypes(GroupVersion,
17+
&Job{},
18+
&JobList{},
19+
)
20+
return nil
21+
})
22+
}
23+
24+
const (
25+
JobStrategyKind = "Job"
26+
)
27+
28+
// +kubebuilder:object:root=true
29+
// +kubebuilder:subresource:status
30+
// +kubebuilder:resource:scope=Cluster
31+
32+
// Job defines a backup strategy using a one-shot Job
33+
type Job struct {
34+
metav1.TypeMeta `json:",inline"`
35+
metav1.ObjectMeta `json:"metadata,omitempty"`
36+
37+
Spec JobSpec `json:"spec,omitempty"`
38+
Status JobStatus `json:"status,omitempty"`
39+
}
40+
41+
// +kubebuilder:object:root=true
42+
43+
// JobList contains a list of backup Jobs.
44+
type JobList struct {
45+
metav1.TypeMeta `json:",inline"`
46+
metav1.ListMeta `json:"metadata,omitempty"`
47+
Items []Job `json:"items"`
48+
}
49+
50+
// JobSpec specifies the desired behavior of a backup job.
51+
type JobSpec struct {
52+
// Template holds a PodTemplateSpec with the right shape to
53+
// run a single pod to completion and create a tarball with
54+
// a given apps data. Helm-like Go templates are supported.
55+
// The values of the source application are available under
56+
// `.Values`. `.Release.Name` and `.Release.Namespace` are
57+
// also exported.
58+
Template corev1.PodTemplateSpec `json:"template"`
59+
}
60+
61+
type JobStatus struct {
62+
Conditions []metav1.Condition `json:"conditions,omitempty"`
63+
}

‎api/backups/strategy/v1alpha1/zz_generated.deepcopy.go‎

Lines changed: 123 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
/*
2+
Copyright 2025.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"crypto/tls"
21+
"flag"
22+
"os"
23+
24+
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
25+
// to ensure that exec-entrypoint and run can make use of them.
26+
_ "k8s.io/client-go/plugin/pkg/client/auth"
27+
28+
"k8s.io/apimachinery/pkg/runtime"
29+
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
30+
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
31+
ctrl "sigs.k8s.io/controller-runtime"
32+
"sigs.k8s.io/controller-runtime/pkg/healthz"
33+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
34+
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
35+
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
36+
"sigs.k8s.io/controller-runtime/pkg/webhook"
37+
38+
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
39+
"github.com/cozystack/cozystack/internal/backupcontroller"
40+
// +kubebuilder:scaffold:imports
41+
)
42+
43+
var (
44+
scheme = runtime.NewScheme()
45+
setupLog = ctrl.Log.WithName("setup")
46+
)
47+
48+
func init() {
49+
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
50+
51+
utilruntime.Must(backupsv1alpha1.AddToScheme(scheme))
52+
// +kubebuilder:scaffold:scheme
53+
}
54+
55+
func main() {
56+
var metricsAddr string
57+
var enableLeaderElection bool
58+
var probeAddr string
59+
var secureMetrics bool
60+
var enableHTTP2 bool
61+
var tlsOpts []func(*tls.Config)
62+
flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
63+
"Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.")
64+
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
65+
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
66+
"Enable leader election for controller manager. "+
67+
"Enabling this will ensure there is only one active controller manager.")
68+
flag.BoolVar(&secureMetrics, "metrics-secure", true,
69+
"If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.")
70+
flag.BoolVar(&enableHTTP2, "enable-http2", false,
71+
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
72+
opts := zap.Options{
73+
Development: false,
74+
}
75+
opts.BindFlags(flag.CommandLine)
76+
flag.Parse()
77+
78+
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
79+
80+
// if the enable-http2 flag is false (the default), http/2 should be disabled
81+
// due to its vulnerabilities. More specifically, disabling http/2 will
82+
// prevent from being vulnerable to the HTTP/2 Stream Cancellation and
83+
// Rapid Reset CVEs. For more information see:
84+
// - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
85+
// - https://github.com/advisories/GHSA-4374-p667-p6c8
86+
disableHTTP2 := func(c *tls.Config) {
87+
setupLog.Info("disabling http/2")
88+
c.NextProtos = []string{"http/1.1"}
89+
}
90+
91+
if !enableHTTP2 {
92+
tlsOpts = append(tlsOpts, disableHTTP2)
93+
}
94+
95+
webhookServer := webhook.NewServer(webhook.Options{
96+
TLSOpts: tlsOpts,
97+
})
98+
99+
// Metrics endpoint is enabled in 'config/default/kustomization.yaml'. The Metrics options configure the server.
100+
// More info:
101+
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/metrics/server
102+
// - https://book.kubebuilder.io/reference/metrics.html
103+
metricsServerOptions := metricsserver.Options{
104+
BindAddress: metricsAddr,
105+
SecureServing: secureMetrics,
106+
TLSOpts: tlsOpts,
107+
}
108+
109+
if secureMetrics {
110+
// FilterProvider is used to protect the metrics endpoint with authn/authz.
111+
// These configurations ensure that only authorized users and service accounts
112+
// can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info:
113+
// https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/metrics/filters#WithAuthenticationAndAuthorization
114+
metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
115+
116+
// TODO(user): If CertDir, CertName, and KeyName are not specified, controller-runtime will automatically
117+
// generate self-signed certificates for the metrics server. While convenient for development and testing,
118+
// this setup is not recommended for production.
119+
}
120+
121+
// Configure rate limiting for the Kubernetes client
122+
config := ctrl.GetConfigOrDie()
123+
config.QPS = 50.0 // Increased from default 5.0
124+
config.Burst = 100 // Increased from default 10
125+
126+
mgr, err := ctrl.NewManager(config, ctrl.Options{
127+
Scheme: scheme,
128+
Metrics: metricsServerOptions,
129+
WebhookServer: webhookServer,
130+
HealthProbeBindAddress: probeAddr,
131+
LeaderElection: enableLeaderElection,
132+
LeaderElectionID: "strategy.backups.cozystack.io",
133+
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
134+
// when the Manager ends. This requires the binary to immediately end when the
135+
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
136+
// speeds up voluntary leader transitions as the new leader don't have to wait
137+
// LeaseDuration time first.
138+
//
139+
// In the default scaffold provided, the program ends immediately after
140+
// the manager stops, so would be fine to enable this option. However,
141+
// if you are doing or is intended to do any operation such as perform cleanups
142+
// after the manager stops then its usage might be unsafe.
143+
// LeaderElectionReleaseOnCancel: true,
144+
})
145+
if err != nil {
146+
setupLog.Error(err, "unable to start manager")
147+
os.Exit(1)
148+
}
149+
150+
if err = (&backupcontroller.BackupJobStrategyReconciler{
151+
Client: mgr.GetClient(),
152+
Scheme: mgr.GetScheme(),
153+
}).SetupWithManager(mgr); err != nil {
154+
setupLog.Error(err, "unable to create controller", "controller", "Job")
155+
os.Exit(1)
156+
}
157+
158+
// +kubebuilder:scaffold:builder
159+
160+
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
161+
setupLog.Error(err, "unable to set up health check")
162+
os.Exit(1)
163+
}
164+
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
165+
setupLog.Error(err, "unable to set up ready check")
166+
os.Exit(1)
167+
}
168+
169+
setupLog.Info("starting manager")
170+
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
171+
setupLog.Error(err, "problem running manager")
172+
os.Exit(1)
173+
}
174+
}

‎hack/update-codegen.sh‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ TMPDIR=$(mktemp -d)
2727
COZY_CONTROLLER_CRDDIR=packages/system/cozystack-controller/crds
2828
COZY_RD_CRDDIR=packages/system/cozystack-resource-definition-crd/definition
2929
BACKUPS_CORE_CRDDIR=packages/system/backup-controller/definitions
30+
BACKUPSTRATEGY_CRDDIR=packages/system/backupstrategy-controller/definitions
31+
3032
trap 'rm -rf ${TMPDIR}' EXIT
3133

3234
source "${CODEGEN_PKG}/kube_codegen.sh"
@@ -64,5 +66,6 @@ mv ${TMPDIR}/cozystack.io_cozystackresourcedefinitions.yaml \
6466
${COZY_RD_CRDDIR}/cozystack.io_cozystackresourcedefinitions.yaml
6567

6668
mv ${TMPDIR}/backups.cozystack.io*.yaml ${BACKUPS_CORE_CRDDIR}/
69+
mv ${TMPDIR}/strategy.backups.cozystack.io*.yaml ${BACKUPSTRATEGY_CRDDIR}/
6770

6871
mv ${TMPDIR}/*.yaml ${COZY_CONTROLLER_CRDDIR}/

0 commit comments

Comments
 (0)