Skip to content

Commit da215c1

Browse files
committed
refactor: improve function signatures and error handling across multiple files
1 parent 3e94a4e commit da215c1

6 files changed

Lines changed: 116 additions & 85 deletions

File tree

controllers/user/deploy/charts/user/templates/cert.yaml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,31 @@ spec:
2323
kind: Issuer
2424
name: {{ include "user.fullname" . }}-selfsigned-issuer
2525
secretName: webhook-server-cert
26+
---
27+
{{- if .Values.metrics.enabled }}
28+
apiVersion: cert-manager.io/v1
29+
kind: Issuer
30+
metadata:
31+
labels:
32+
{{- include "user.labels" . | nindent 4 }}
33+
name: selfsigned-issuer
34+
spec:
35+
selfSigned: {}
36+
---
37+
apiVersion: cert-manager.io/v1
38+
kind: Certificate
39+
metadata:
40+
labels:
41+
{{- include "user.labels" . | nindent 4 }}
42+
name: metrics-certs
43+
spec:
44+
privateKey:
45+
rotationPolicy: Always
46+
dnsNames:
47+
- {{ include "user.fullname" . }}-metrics.{{.Release.Namespace}}.svc
48+
- {{ include "user.fullname" . }}-metrics.{{.Release.Namespace}}.svc.cluster.local
49+
issuerRef:
50+
kind: Issuer
51+
name: selfsigned-issuer
52+
secretName: {{.Values.metrics.secretName}}
53+
{{- end }}

controllers/user/deploy/charts/user/templates/configmap.yaml

Lines changed: 0 additions & 24 deletions
This file was deleted.

controllers/user/deploy/charts/user/templates/deployment.yaml

Lines changed: 32 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,21 @@ spec:
3939
- /manager
4040
args:
4141
- --health-probe-bind-address=:8081
42-
- --metrics-bind-address=127.0.0.1:8080
4342
- --leader-elect
44-
- --config-file-path=/config.yaml
43+
{{- if .Values.metrics.enabled }}
44+
- --metrics-secure=true
45+
- --metrics-bind-address=:8443
46+
{{- end }}
4547
env:
4648
- name: NAMESPACE_NAME
4749
valueFrom:
4850
fieldRef:
4951
apiVersion: v1
5052
fieldPath: metadata.namespace
53+
- name: SEALOS_CLOUD_APISERVER_HOST
54+
value: "{{.Values.cloudAPIServerDomain}}"
55+
- name: SEALOS_CLOUD_APISERVER_PORT
56+
value: "{{.Values.cloudAPIServerPort}}"
5157
ports:
5258
- containerPort: 9443
5359
name: webhook-server
@@ -63,28 +69,17 @@ spec:
6369
securityContext:
6470
{{- toYaml .Values.securityContext | nindent 12 }}
6571
volumeMounts:
72+
{{- with .Values.volumeMounts }}
73+
{{- toYaml . | nindent 12 }}
74+
{{- end }}
75+
{{- if .Values.metrics.enabled }}
76+
- name: metrics-certs
77+
mountPath: {{.Values.metrics.certPath}}
78+
readOnly: true
79+
{{- end }}
6680
- mountPath: /tmp/k8s-webhook-server/serving-certs
6781
name: cert
6882
readOnly: true
69-
- name: user-manager-volume
70-
mountPath: /config.yaml
71-
subPath: config.yaml
72-
- name: kube-rbac-proxy
73-
args:
74-
- --secure-listen-address=0.0.0.0:8443
75-
- --upstream=http://127.0.0.1:8080/
76-
- --logtostderr=true
77-
- --v=0
78-
image: "{{ .Values.proxy.image }}"
79-
imagePullPolicy: {{ .Values.image.pullPolicy }}
80-
ports:
81-
- containerPort: 8443
82-
name: https
83-
protocol: TCP
84-
resources:
85-
{{- toYaml .Values.proxy.resources | nindent 12 }}
86-
securityContext:
87-
{{- toYaml .Values.securityContext | nindent 12 }}
8883
terminationGracePeriodSeconds: 10
8984
affinity:
9085
{{- if .Values.affinity }}
@@ -111,10 +106,23 @@ spec:
111106
{{- toYaml . | nindent 8 }}
112107
{{- end }}
113108
volumes:
109+
{{- if .Values.metrics.enabled }}
110+
- name: metrics-certs
111+
secret:
112+
secretName: {{.Values.metrics.secretName}}
113+
optional: false
114+
items:
115+
- key: ca.crt
116+
path: ca.crt
117+
- key: tls.crt
118+
path: tls.crt
119+
- key: tls.key
120+
path: tls.key
121+
{{- end }}
122+
{{- with .Values.volumes }}
123+
{{- toYaml . | nindent 8 }}
124+
{{- end }}
114125
- name: cert
115126
secret:
116127
defaultMode: 420
117128
secretName: webhook-server-cert
118-
- name: user-manager-volume
119-
configMap:
120-
name: {{ include "user.fullname" . }}-manager-config

controllers/user/deploy/charts/user/values.yaml

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,6 @@ resources:
4444
cpu: 10m
4545
memory: 64Mi
4646

47-
proxy:
48-
image: gcr.io/kubebuilder/kube-rbac-proxy:v0.13.0
49-
resources:
50-
limits:
51-
cpu: 1000m
52-
memory: 1024Mi
53-
requests:
54-
cpu: 5m
55-
memory: 64Mi
56-
5747
cloudAPIServerDomain: 127.0.0.1.nip.io
5848
cloudAPIServerPort: "6443"
5949

@@ -73,7 +63,7 @@ readinessProbe:
7363

7464
metrics:
7565
# Enable metrics endpoint
76-
enabled: false
66+
enabled: true
7767
# Path to the metrics certificate
7868
certPath: /tmp/k8s-metrics-server/metrics-certs
7969
secretName: metrics-server-cert

controllers/user/deploy/entrypoint.sh

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,7 @@ set -euo pipefail
44
HELM_OPTS=${HELM_OPTS:-""}
55

66
kubectl delete -f ./drop/ --ignore-not-found
7-
helm upgrade -i user -n user-system --create-namespace ./charts/user ${HELM_OPTS}
7+
SEALOS_CLOUD_DOMAIN=$(kubectl get configmap sealos-config -n sealos-system -o jsonpath='{.data.cloudDomain}')
8+
9+
helm upgrade -i user -n user-system --create-namespace ./charts/user --set cloudAPIServerDomain=${SEALOS_CLOUD_DOMAIN} ${HELM_OPTS}
810
helm show crds ./charts/user | kubectl apply -f - --server-side --force-conflicts

controllers/user/main.go

Lines changed: 52 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@ package main
1818

1919
import (
2020
"context"
21+
"crypto/tls"
2122
"flag"
2223
"os"
2324
"time"
2425

2526
"k8s.io/apimachinery/pkg/runtime"
2627
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
2728
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
29+
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
30+
2831
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
2932
// to ensure that exec-entrypoint and run can make use of them.
3033
_ "k8s.io/client-go/plugin/pkg/client/auth"
@@ -38,7 +41,6 @@ import (
3841
licensev1 "github.com/labring/sealos/controllers/license/api/v1"
3942
userv1 "github.com/labring/sealos/controllers/user/api/v1"
4043
"github.com/labring/sealos/controllers/user/controllers"
41-
configpkg "github.com/labring/sealos/controllers/user/controllers/helper/config"
4244
ratelimiter "github.com/labring/sealos/controllers/user/controllers/helper/ratelimiter"
4345
//+kubebuilder:scaffold:imports
4446
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
@@ -70,6 +72,9 @@ func main() {
7072
operationReqExpirationTime time.Duration
7173
restartPredicateDuration time.Duration
7274
operationReqRetentionTime time.Duration
75+
secureMetrics bool
76+
enableHTTP2 bool
77+
tlsOpts []func(*tls.Config)
7378
)
7479
flag.StringVar(
7580
&metricsAddr,
@@ -128,6 +133,14 @@ func main() {
128133
"/config.yaml",
129134
"The path to the configuration file.",
130135
)
136+
flag.BoolVar(
137+
&secureMetrics,
138+
"metrics-secure",
139+
true,
140+
"If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.",
141+
)
142+
flag.BoolVar(&enableHTTP2, "enable-http2", false,
143+
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
131144
rateLimiterOptions.BindFlags(flag.CommandLine)
132145
opts := zap.Options{
133146
Development: true,
@@ -137,11 +150,45 @@ func main() {
137150

138151
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
139152

153+
// if the enable-http2 flag is false (the default), http/2 should be disabled
154+
// due to its vulnerabilities. More specifically, disabling http/2 will
155+
// prevent from being vulnerable to the HTTP/2 Stream Cancellation and
156+
// Rapid Reset CVEs. For more information see:
157+
// - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
158+
// - https://github.com/advisories/GHSA-4374-p667-p6c8
159+
disableHTTP2 := func(c *tls.Config) {
160+
setupLog.Info("disabling http/2")
161+
c.NextProtos = []string{"http/1.1"}
162+
}
163+
164+
if !enableHTTP2 {
165+
tlsOpts = append(tlsOpts, disableHTTP2)
166+
}
167+
// Metrics endpoint is enabled in 'config/default/kustomization.yaml'. The Metrics options configure the server.
168+
// More info:
169+
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.19.1/pkg/metrics/server
170+
// - https://book.kubebuilder.io/reference/metrics.html
171+
metricsServerOptions := metricsserver.Options{
172+
BindAddress: metricsAddr,
173+
SecureServing: secureMetrics,
174+
TLSOpts: tlsOpts,
175+
}
176+
177+
if secureMetrics {
178+
// FilterProvider is used to protect the metrics endpoint with authn/authz.
179+
// These configurations ensure that only authorized users and service accounts
180+
// can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info:
181+
// https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.19.1/pkg/metrics/filters#WithAuthenticationAndAuthorization
182+
metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
183+
184+
// TODO(user): If CertDir, CertName, and KeyName are not specified, controller-runtime will automatically
185+
// generate self-signed certificates for the metrics server. While convenient for development and testing,
186+
// this setup is not recommended for production.
187+
}
188+
140189
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
141-
Scheme: scheme,
142-
Metrics: metricsserver.Options{
143-
BindAddress: metricsAddr,
144-
},
190+
Scheme: scheme,
191+
Metrics: metricsServerOptions,
145192
// WebhookServer: webhook.NewServer(webhook.Options{
146193
// Port: 9443,
147194
// }),
@@ -171,19 +218,6 @@ func main() {
171218
os.Exit(1)
172219
}
173220

174-
// Load the configuration file
175-
config := &configpkg.Config{}
176-
if err := configpkg.LoadConfig(configFilePath, config); err != nil {
177-
setupLog.Error(err, "unable to load configuration file")
178-
os.Exit(1)
179-
}
180-
181-
// Set the configuration
182-
if err := setConfigToEnv(*config); err != nil {
183-
setupLog.Error(err, "unable to set configuration to environment variables")
184-
os.Exit(1)
185-
}
186-
187221
if err := controllers.SetupLicenseGate(mgr); err != nil {
188222
setupLog.Error(err, "unable to set up license gate")
189223
os.Exit(1)
@@ -243,10 +277,3 @@ func main() {
243277
os.Exit(1)
244278
}
245279
}
246-
247-
func setConfigToEnv(cfg configpkg.Config) error {
248-
if err := os.Setenv("SEALOS_CLOUD_APISERVER_HOST", cfg.CloudAPIServerDomain); err != nil {
249-
return err
250-
}
251-
return os.Setenv("SEALOS_CLOUD_APISERVER_PORT", cfg.CloudAPIServerPort)
252-
}

0 commit comments

Comments
 (0)