Skip to content

Commit 3b4db69

Browse files
authored
feat(backups): record the RDB snapshot location and size for Redis backups (#5046)
## What this PR does Builds on the shared S3 probe from #5223 (MariaDB and CNPG), which is on `main`. Refs #4316. Backups made by the Redis strategy carry no `Backup.status.artifact` at all: no URI and no size. This covers both the Redis and Valkey apps, which share the driver. The snapshot is a single object per backup, `<namespace>/<app>/<backup>.rdb` (`redisObjectKey`). The driver already records that key in `driverMetadata`. The default strategy uploads the object using the S3 coordinates from the backup credentials Secret, which the controller projects into the application namespace (`endpoint`, `bucketName`, `region` and the access keys). When a backup completes, the driver now: 1. reads that projected Secret (`CredentialsConfig.TargetSecretName`) in the application namespace. The projector stores its `endpoint` without a scheme, and the strategy script reaches it over https; an endpoint with a path prefix is refused by minio-go, which leaves the artifact unset; 2. reads the TLS trust from the pod spec of the completed backup Job, in the order the script applies it: `ca.crt`, then `tls.crt`, from the Secret mounted as the `s3-ca` volume (`backupStorage.endpointCASecretName`). Only when there is no `s3-ca` volume does it honour `S3_INSECURE_SKIP_VERIFY=true`, and only when every container of the pod sets it, since the probe cannot tell which container uploaded. The Secret is read at probe time; the default strategy mounts `s3-ca` only when an endpoint CA is configured, so when the volume yields no CA now (the Secret is gone or lacks both keys, or the volume is not a Secret), the probe leaves the artifact unset rather than trust the system roots or skip verification where the Job may have verified. The CA is trusted on its own, as `curl --cacert` does, not on top of the system roots; 3. runs `StatObject` on the recorded key; a response without `Content-Length`, which minio-go reports as size -1, counts as unmeasured; 4. records `status.artifact.uri = s3://<bucket>/<key>` and `status.artifact.sizeBytes` = the object's size. An empty object is recorded too, but `sizeBytes` is `omitempty`, so on the Backup it reads like an unmeasured size; since a valid RDB snapshot always carries a header, a Warning `EmptySnapshot` Event on the BackupJob flags it as a broken backup. The artifact is set **only when the object is found**. A custom strategy that writes elsewhere would otherwise get a URI pointing at an object that does not exist. On any failure (Secret missing or incomplete, endpoint invalid, CA unreadable, object not found, TLS error) the artifact stays absent and the backup still succeeds. The full error is logged at info, and once the Backup is created a Normal `ArtifactNotMeasured` Event on the BackupJob gives a fixed reason, also when a failed existence check skipped the probe; the Event lives in the application namespace, so it never carries the raw error, which may name the platform's endpoint and bucket. The probe shares the 10s timeout of the MariaDB and CNPG probes. The retry check is shared with those drivers too: a `Backup` that already exists is returned without probing, a failed existence check creates the Backup without probing, a `Create` collision is resolved by reading past the cache, and an existing Backup that cannot be read back is retried with `Ready=False` instead of failing the BackupJob. The size is useful because an RDB snapshot is the compressed dataset. It shows growth, and a snapshot that is suddenly tiny is a broken backup. Kafka is deliberately left out. Its backup is a topic-metadata export of a few kilobytes, so the size would say nothing about the data and might suggest the data itself was backed up. Tests: - the stat uses the projected credentials; - every path that leaves the artifact unset: object missing, Secret missing, bucket, endpoint, access key or secret key missing, no target Secret configured, a size the endpoint did not report; - trust resolution: `ca.crt` wins over `tls.crt` and skip-verify; `items` remapping of the volume, and a key the `items` do not project is never trusted; the Redis CA volume mounted next to `s3-ca` is not taken as the S3 CA; an `s3-ca` volume that yields no CA (Secret gone, Secret without the keys, a ConfigMap source) is refused with and without skip-verify; skip-verify applies only on an exact `true` of that variable in every container, the last entry of a repeated variable winning; - the real minio client against a TLS stub: its certificate is trusted only through the `s3-ca` volume or skip-verify, a CA that did not sign it is refused even with skip-verify set on the Job, and the shared client enforces a configured CA with and without the system roots; the client sends a signed `HEAD` and parses `Content-Length`; - the Events: an unmeasured artifact or a failed existence check raises `ArtifactNotMeasured` without the raw error; an empty snapshot is recorded and raises a Warning `EmptySnapshot`; a measured artifact, a rejected `Create` and a `Create` collision raise none; - a reconcile test pinning that the completed Job's pod spec reaches the probe; a Backup that already exists is returned without a probe or a `Create`; the `Create` collision is read back from the API server past the cache. The suite fails if any guard of the trust lookup (volume name, Secret source, variable name, every-container rule, refusal of an unreadable CA), the CA enforcement in the transport, the negative-size check, the Events, the reason-only message, their place after `Create`, the empty-snapshot warning, the existing-Backup check, the wiring, any term of the Secret check, or the API-server read-back is removed. ### Screenshots N/A — no UI changes. ### Downstream repositories I walked the trigger map against the diff. The change is Go-only in `internal/backupcontroller`, with no API, CRD, chart, value or schema change. Existing `Backup` fields are now filled for one more driver. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note ```release-note feat(backups): Redis and Valkey backups now record `status.artifact` with the `s3://` location and the size of the RDB snapshot. If the snapshot cannot be found with the platform backup credentials, the artifact stays unset and a Normal `ArtifactNotMeasured` Event on the BackupJob says why. An empty snapshot raises a Warning `EmptySnapshot` Event. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Redis backups now include artifact location and size when they can be measured. * Backups are still created when artifact measurement fails, with status reporting that the artifact was not measured. * **Bug Fixes** * Improved handling of existing backups and temporary read-back failures to support reliable reconciliation. * Improved compatibility with S3 endpoints using custom certificate authorities or configured TLS verification settings. * Zero-size snapshots are now reported with a warning. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
2 parents 66acdb8 + 1093f39 commit 3b4db69

5 files changed

Lines changed: 941 additions & 19 deletions

File tree

‎internal/backupcontroller/artifact_size.go‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ type s3ObjectInfo struct {
3636

3737
type s3ObjectLister interface {
3838
ListObjects(ctx context.Context, bucket, prefix string, recursive bool) ([]s3ObjectInfo, error)
39+
StatObject(ctx context.Context, bucket, key string) (int64, error)
3940
}
4041

4142
// s3Connection is what a driver resolves from its rendered strategy to
@@ -53,6 +54,9 @@ type s3Connection struct {
5354
// what the writer of the backup trusted, no more.
5455
CAPEM []byte
5556
CAOnly bool
57+
// InsecureSkipVerify mirrors an explicit admin opt-in a strategy
58+
// already applies to its own uploads; it is never a fallback.
59+
InsecureSkipVerify bool
5660
}
5761

5862
// objectStore reads back what a backup wrote: the Secrets it was written
@@ -104,14 +108,18 @@ func newMinioObjectLister(conn s3Connection) (s3ObjectLister, error) {
104108
Region: conn.Region,
105109
Secure: conn.Secure,
106110
}
107-
if conn.Secure && len(conn.CAPEM) > 0 {
111+
if conn.Secure && (len(conn.CAPEM) > 0 || conn.InsecureSkipVerify) {
108112
// Start from minio's transport to keep its proxy and timeout settings.
109113
tr, err := minio.DefaultTransport(true)
110114
if err != nil {
111115
return nil, err
112116
}
113-
if tr.TLSClientConfig.RootCAs, err = endpointTrustPool(conn, tr.TLSClientConfig.RootCAs); err != nil {
114-
return nil, err
117+
if len(conn.CAPEM) > 0 {
118+
if tr.TLSClientConfig.RootCAs, err = endpointTrustPool(conn, tr.TLSClientConfig.RootCAs); err != nil {
119+
return nil, err
120+
}
121+
} else {
122+
tr.TLSClientConfig.InsecureSkipVerify = true
115123
}
116124
opts.Transport = tr
117125
}
@@ -148,6 +156,18 @@ func (l *minioObjectLister) ListObjects(ctx context.Context, bucket, prefix stri
148156
return collectObjects(ctx, l.client.ListObjects(ctx, bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: recursive}))
149157
}
150158

159+
func (l *minioObjectLister) StatObject(ctx context.Context, bucket, key string) (int64, error) {
160+
info, err := l.client.StatObject(ctx, bucket, key, minio.StatObjectOptions{})
161+
if err != nil {
162+
return 0, err
163+
}
164+
// minio-go reports -1 when the response carries no Content-Length.
165+
if info.Size < 0 {
166+
return 0, fmt.Errorf("object %s/%s: the endpoint reported no size", bucket, key)
167+
}
168+
return info.Size, nil
169+
}
170+
151171
// collectObjects drains a minio listing. minio-go ends a listing whose
152172
// context is cancelled between pages by closing the channel without an
153173
// error item, so a cancelled context is checked once the channel closes:

‎internal/backupcontroller/artifact_size_test.go‎

Lines changed: 87 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"math/big"
1515
"net/http"
1616
"net/http/httptest"
17+
"strings"
1718
"testing"
1819
"time"
1920

@@ -37,6 +38,16 @@ type fakeS3Lister struct {
3738
bucket, prefix string
3839
recursive bool
3940
calls int
41+
42+
statSize int64
43+
statErr error
44+
statKey string
45+
}
46+
47+
func (f *fakeS3Lister) StatObject(_ context.Context, bucket, key string) (int64, error) {
48+
f.calls++
49+
f.bucket, f.statKey = bucket, key
50+
return f.statSize, f.statErr
4051
}
4152

4253
func (f *fakeS3Lister) ListObjects(_ context.Context, bucket, prefix string, recursive bool) ([]s3ObjectInfo, error) {
@@ -167,6 +178,11 @@ func (blockingLister) ListObjects(ctx context.Context, _, _ string, _ bool) ([]s
167178
return nil, ctx.Err()
168179
}
169180

181+
func (blockingLister) StatObject(ctx context.Context, _, _ string) (int64, error) {
182+
<-ctx.Done()
183+
return 0, ctx.Err()
184+
}
185+
170186
// withShortProbeTimeout shortens the probe timeout and fails the test if fn
171187
// is not back well before the default timeout would have expired.
172188
func withShortProbeTimeout(t *testing.T, fn func()) {
@@ -233,6 +249,76 @@ func TestFailBackupArtifact(t *testing.T) {
233249
})
234250
}
235251

252+
// unrelatedCAPEM mints a CA that signed nothing an httptest server serves:
253+
// every httptest server shares one certificate.
254+
func unrelatedCAPEM(t *testing.T) []byte {
255+
t.Helper()
256+
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
257+
if err != nil {
258+
t.Fatal(err)
259+
}
260+
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "unrelated CA"}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true}
261+
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
262+
if err != nil {
263+
t.Fatal(err)
264+
}
265+
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
266+
}
267+
268+
// TestMinioObjectLister_EnforcesTheCA pins that a configured CA is the
269+
// trust the client verifies with, whether alone or on top of the system
270+
// roots: an endpoint whose certificate it did not sign is refused.
271+
func TestMinioObjectLister_EnforcesTheCA(t *testing.T) {
272+
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
273+
w.Header().Set("Content-Length", "1")
274+
w.Header().Set("ETag", `"abc"`)
275+
w.Header().Set("Last-Modified", "Wed, 21 Oct 2026 10:00:00 GMT")
276+
}))
277+
defer srv.Close()
278+
// minio-go retries a TLS failure with backoff; a refusal needs no more
279+
// than the first attempt.
280+
stat := func(ca []byte, caOnly bool) error {
281+
l, err := newMinioObjectLister(s3Connection{
282+
Endpoint: strings.TrimPrefix(srv.URL, "https://"), Secure: true,
283+
AccessKey: "AKID", SecretKey: "secret", Region: "us-east-1",
284+
CAPEM: ca, CAOnly: caOnly,
285+
})
286+
if err != nil {
287+
t.Fatalf("newMinioObjectLister: %v", err)
288+
}
289+
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
290+
defer cancel()
291+
_, err = l.StatObject(ctx, "cozy-backups", "k")
292+
return err
293+
}
294+
signer := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw})
295+
for _, caOnly := range []bool{true, false} {
296+
if err := stat(signer, caOnly); err != nil {
297+
t.Errorf("CAOnly=%v: the CA that signed the endpoint: %v", caOnly, err)
298+
}
299+
if err := stat(unrelatedCAPEM(t), caOnly); err == nil {
300+
t.Errorf("CAOnly=%v: StatObject succeeded against a certificate the CA did not sign, want a TLS error", caOnly)
301+
}
302+
}
303+
}
304+
305+
// TestMinioObjectLister_StatWithoutSize pins that a HEAD answer without
306+
// Content-Length, which minio-go turns into size -1, is not a size.
307+
func TestMinioObjectLister_StatWithoutSize(t *testing.T) {
308+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
309+
w.Header().Set("ETag", `"abc"`)
310+
w.Header().Set("Last-Modified", "Wed, 21 Oct 2026 10:00:00 GMT")
311+
}))
312+
defer srv.Close()
313+
l, err := newMinioObjectLister(s3Connection{Endpoint: strings.TrimPrefix(srv.URL, "http://"), AccessKey: "AKID", SecretKey: "secret", Region: "us-east-1"})
314+
if err != nil {
315+
t.Fatalf("newMinioObjectLister: %v", err)
316+
}
317+
if size, err := l.StatObject(context.Background(), "cozy-backups", "k"); err == nil {
318+
t.Errorf("StatObject = %d, nil; want an error for a response without Content-Length", size)
319+
}
320+
}
321+
236322
// TestEndpointTrustPool_CAOnly tells apart "the CA on top of the system
237323
// roots" and "the CA alone". The system pool holds the endpoint's
238324
// certificate, and the configured CA is an unrelated one, so the endpoint
@@ -243,18 +329,7 @@ func TestEndpointTrustPool_CAOnly(t *testing.T) {
243329
system := x509.NewCertPool()
244330
system.AddCert(endpoint.Certificate())
245331

246-
// Every httptest server shares one certificate, so the unrelated CA is
247-
// minted here.
248-
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
249-
if err != nil {
250-
t.Fatal(err)
251-
}
252-
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "unrelated CA"}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true}
253-
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
254-
if err != nil {
255-
t.Fatal(err)
256-
}
257-
unrelatedCA := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
332+
unrelatedCA := unrelatedCAPEM(t)
258333

259334
verifies := func(caOnly bool) bool {
260335
pool, err := endpointTrustPool(s3Connection{CAPEM: unrelatedCA, CAOnly: caOnly}, system.Clone())
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
package backupcontroller
3+
4+
import (
5+
"context"
6+
"errors"
7+
"fmt"
8+
9+
corev1 "k8s.io/api/core/v1"
10+
apierrors "k8s.io/apimachinery/pkg/api/errors"
11+
"k8s.io/apimachinery/pkg/types"
12+
13+
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
14+
)
15+
16+
// redisArtifact locates the RDB snapshot the backup Job uploaded and returns
17+
// an Artifact carrying its s3:// URI and size. The default Redis strategy
18+
// takes its S3 coordinates from the projected backup credentials Secret, so
19+
// the object is looked up there, with the TLS trust the Job's pod applied
20+
// (see redisS3Trust). It returns an artifactProbeError, and no Artifact,
21+
// when the Secret cannot be read or the object is not found: a custom
22+
// strategy that writes elsewhere must not get a URI pointing at an object
23+
// that does not exist.
24+
func (r *BackupJobReconciler) redisArtifact(ctx context.Context, namespace, objectKey string, podSpec *corev1.PodSpec) (*backupsv1alpha1.BackupArtifact, error) {
25+
ctx, cancel := context.WithTimeout(ctx, artifactSizeProbeTimeout)
26+
defer cancel()
27+
28+
bucket, conn, err := r.projectedS3Connection(ctx, namespace)
29+
if err != nil {
30+
return nil, &artifactProbeError{reason: "the backup credentials Secret is unusable", err: err}
31+
}
32+
if conn.CAPEM, conn.InsecureSkipVerify, err = r.redisS3Trust(ctx, namespace, podSpec); err != nil {
33+
return nil, &artifactProbeError{reason: "the S3 endpoint CA the Job mounted cannot be read", err: err}
34+
}
35+
// The script passes the CA as curl --cacert, which replaces the default
36+
// trust store rather than adding to it.
37+
conn.CAOnly = true
38+
lister, err := r.s3Lister(conn)
39+
if err != nil {
40+
return nil, &artifactProbeError{reason: "the S3 endpoint is not usable", err: err}
41+
}
42+
size, err := lister.StatObject(ctx, bucket, objectKey)
43+
if err != nil {
44+
return nil, &artifactProbeError{reason: "the snapshot could not be found or read in the bucket", err: err}
45+
}
46+
return &backupsv1alpha1.BackupArtifact{
47+
URI: fmt.Sprintf("s3://%s/%s", bucket, objectKey),
48+
SizeBytes: size,
49+
}, nil
50+
}
51+
52+
// artifactProbeError carries a fixed reason fit for an Event in the
53+
// application namespace; err may name the platform's endpoint and bucket,
54+
// so it goes to the controller log only.
55+
type artifactProbeError struct {
56+
reason string
57+
err error
58+
}
59+
60+
func (e *artifactProbeError) Error() string { return e.reason + ": " + e.err.Error() }
61+
func (e *artifactProbeError) Unwrap() error { return e.err }
62+
63+
// projectedS3Connection reads the backup credentials Secret the controller
64+
// projects into the application namespace. The projector stores the endpoint
65+
// without a scheme, and the strategy scripts reach it over https. It can
66+
// still carry a path, which minio-go refuses.
67+
func (r *BackupJobReconciler) projectedS3Connection(ctx context.Context, namespace string) (string, s3Connection, error) {
68+
var conn s3Connection
69+
name := r.CredentialsConfig.TargetSecretName
70+
if name == "" {
71+
return "", conn, errors.New("no projected credentials Secret is configured")
72+
}
73+
secret := &corev1.Secret{}
74+
if err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, secret); err != nil {
75+
return "", conn, err
76+
}
77+
value := func(key string) string { return string(secret.Data[key]) }
78+
79+
bucket := value("bucketName")
80+
conn.AccessKey, conn.SecretKey = value("AWS_ACCESS_KEY_ID"), value("AWS_SECRET_ACCESS_KEY")
81+
if bucket == "" || value("endpoint") == "" || conn.AccessKey == "" || conn.SecretKey == "" {
82+
return "", conn, fmt.Errorf("secret %s/%s lacks bucketName, endpoint or access keys", namespace, name)
83+
}
84+
conn.Endpoint, conn.Secure = value("endpoint"), true
85+
conn.Region = value("region")
86+
return bucket, conn, nil
87+
}
88+
89+
const (
90+
redisS3CAVolume = "s3-ca"
91+
redisS3InsecureSkipEnv = "S3_INSECURE_SKIP_VERIFY"
92+
)
93+
94+
// redisS3Trust mirrors how the default strategy script verifies the S3
95+
// endpoint: it trusts ca.crt, then tls.crt, from the s3-ca volume, and only
96+
// when neither exists does it honour S3_INSECURE_SKIP_VERIFY=true. Both are
97+
// read from the pod spec the backup Job ran with, but the Secret is read
98+
// now, so an s3-ca volume that yields no CA now - a Secret that is gone or
99+
// lacks the keys, or a source other than a Secret - is refused: the Job may
100+
// have verified against a CA that is gone, and neither the system roots nor
101+
// skip-verify would trust as narrowly. The default strategy mounts s3-ca
102+
// only when the admin configured an endpoint CA.
103+
func (r *BackupJobReconciler) redisS3Trust(ctx context.Context, namespace string, podSpec *corev1.PodSpec) ([]byte, bool, error) {
104+
if podSpec == nil {
105+
return nil, false, nil
106+
}
107+
caUnknown := false
108+
for _, v := range podSpec.Volumes {
109+
if v.Name != redisS3CAVolume {
110+
continue
111+
}
112+
if v.Secret == nil {
113+
caUnknown = true
114+
break
115+
}
116+
secret := &corev1.Secret{}
117+
err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: v.Secret.SecretName}, secret)
118+
if apierrors.IsNotFound(err) {
119+
caUnknown = true
120+
break
121+
}
122+
if err != nil {
123+
return nil, false, err
124+
}
125+
for _, file := range []string{"ca.crt", "tls.crt"} {
126+
if pem := secret.Data[secretKeyForFile(v.Secret.Items, file)]; len(pem) > 0 {
127+
return pem, false, nil
128+
}
129+
}
130+
caUnknown = true
131+
}
132+
if caUnknown {
133+
return nil, false, fmt.Errorf("the %s volume yields no CA now", redisS3CAVolume)
134+
}
135+
return nil, redisSkipsVerify(podSpec.Containers), nil
136+
}
137+
138+
// redisSkipsVerify reports whether every container sets
139+
// S3_INSECURE_SKIP_VERIFY=true: the probe cannot tell which container
140+
// uploaded, so one that verified is enough to keep verification on. When a
141+
// container lists the variable twice, the last entry wins, as in the
142+
// kubelet.
143+
func redisSkipsVerify(containers []corev1.Container) bool {
144+
for _, c := range containers {
145+
value := ""
146+
for _, e := range c.Env {
147+
if e.Name == redisS3InsecureSkipEnv {
148+
value = e.Value
149+
}
150+
}
151+
if value != "true" {
152+
return false
153+
}
154+
}
155+
return len(containers) > 0
156+
}
157+
158+
// secretKeyForFile returns the Secret key a secret volume projects to file:
159+
// the key itself when the volume lists no items.
160+
func secretKeyForFile(items []corev1.KeyToPath, file string) string {
161+
if len(items) == 0 {
162+
return file
163+
}
164+
for _, it := range items {
165+
if it.Path == file {
166+
return it.Key
167+
}
168+
}
169+
return ""
170+
}

0 commit comments

Comments
 (0)