Skip to content

Commit 55d4bea

Browse files
committed
fix(imagerepository): sync only explicitly configured folders
1 parent ddf2435 commit 55d4bea

4 files changed

Lines changed: 154 additions & 77 deletions

File tree

‎api/v1alpha1/imagerepository_types.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ type ImageRepositorySpec struct {
2929
// +optional
3030
Ref string `json:"ref,omitempty"`
3131
// Paths are directories in the repo to scan for Image CR YAML files (relative to repo root).
32-
// If empty, defaults to ["images/"].
32+
// Only files directly in each directory are scanned; subdirectories must be listed separately.
33+
// A trailing slash is optional. If empty, defaults to ["images"].
3334
// +optional
3435
Paths []string `json:"paths,omitempty"`
3536
// Auth config for private repos.

‎config/crd/bases/kubeworkspaces.io_imagerepositories.yaml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ spec:
8585
paths:
8686
description: |-
8787
Paths are directories in the repo to scan for Image CR YAML files (relative to repo root).
88-
If empty, defaults to ["images/"].
88+
Only files directly in each directory are scanned; subdirectories must be listed separately.
89+
A trailing slash is optional. If empty, defaults to ["images"].
8990
items:
9091
type: string
9192
type: array

‎internal/controller/imagerepository_controller.go‎

Lines changed: 97 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,6 @@ package controller
1818

1919
import (
2020
"context"
21-
"crypto/sha256"
22-
"encoding/hex"
23-
"encoding/json"
2421
"fmt"
2522
"os"
2623
"path/filepath"
@@ -41,7 +38,6 @@ import (
4138
"k8s.io/apimachinery/pkg/types"
4239
ctrl "sigs.k8s.io/controller-runtime"
4340
"sigs.k8s.io/controller-runtime/pkg/client"
44-
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
4541
"sigs.k8s.io/controller-runtime/pkg/log"
4642
"sigs.k8s.io/yaml"
4743

@@ -168,7 +164,11 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
168164
if err != nil {
169165
return nil, err
170166
}
171-
defer os.RemoveAll(tmpDir)
167+
defer func() {
168+
if err := os.RemoveAll(tmpDir); err != nil {
169+
log.FromContext(ctx).Error(err, "failed to remove temporary image repository")
170+
}
171+
}()
172172

173173
cloneOpts := &git.CloneOptions{
174174
URL: repo.Spec.URL,
@@ -222,77 +222,25 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
222222

223223
paths := repo.Spec.Paths
224224
if len(paths) == 0 {
225-
paths = []string{"images/"}
225+
paths = []string{"images"}
226+
}
227+
files, err := imageRepositoryFiles(tmpDir, paths)
228+
if err != nil {
229+
return nil, err
226230
}
227231

228232
var imported []string
229233
desired := map[string]struct{}{}
230234

231-
for _, scanPath := range paths {
232-
fullPath := filepath.Join(tmpDir, scanPath)
233-
_ = filepath.Walk(fullPath, func(p string, info os.FileInfo, err error) error {
234-
if err != nil || info == nil || info.IsDir() {
235-
return nil
236-
}
237-
if !strings.HasSuffix(p, ".yaml") && !strings.HasSuffix(p, ".yml") {
238-
return nil
239-
}
240-
data, err := os.ReadFile(p)
241-
if err != nil {
242-
return nil
243-
}
244-
// try to parse as unstructured
245-
var u map[string]interface{}
246-
if err := yaml.Unmarshal(data, &u); err != nil {
247-
return nil
248-
}
249-
kind, _ := u["kind"].(string)
250-
apiVersion, _ := u["apiVersion"].(string)
251-
if kind != "Image" || !strings.Contains(apiVersion, "kubeworkspaces.io") {
252-
return nil
253-
}
254-
metaObj, _ := u["metadata"].(map[string]interface{})
255-
name, _ := metaObj["name"].(string)
256-
if name == "" {
257-
return nil
258-
}
259-
260-
// build object
261-
obj := &unstructured.Unstructured{Object: u}
262-
labels := obj.GetLabels()
263-
if labels == nil {
264-
labels = map[string]string{}
265-
}
266-
labels[imageRepositoryLabelKey] = repo.Name
267-
labels[imageRepositoryManagedBy] = imageRepositoryManagedVal
268-
obj.SetLabels(labels)
269-
ann := obj.GetAnnotations()
270-
if ann == nil {
271-
ann = map[string]string{}
272-
}
273-
ann[imageRepositorySourceURL] = repo.Spec.URL
274-
ann[imageRepositorySourceRef] = repo.Spec.Ref
275-
ann[imageRepositorySourceSHA] = commit
276-
ann[imageRepositorySourcePath] = strings.TrimPrefix(p, tmpDir+"/")
277-
obj.SetAnnotations(ann)
278-
279-
existing := &unstructured.Unstructured{}
280-
existing.SetGroupVersionKind(schema.GroupVersionKind{Group: "kubeworkspaces.io", Version: "v1alpha1", Kind: "Image"})
281-
err = r.Get(ctx, types.NamespacedName{Name: name}, existing)
282-
if apierrors.IsNotFound(err) {
283-
if err := r.Create(ctx, obj); err != nil {
284-
return nil
285-
}
286-
} else if err == nil {
287-
obj.SetResourceVersion(existing.GetResourceVersion())
288-
if err := r.Update(ctx, obj); err != nil {
289-
return nil
290-
}
291-
}
235+
for _, p := range files {
236+
name, err := r.syncImageFile(ctx, repo, commit, tmpDir, p)
237+
if err != nil {
238+
return nil, fmt.Errorf("sync %s: %w", strings.TrimPrefix(p, tmpDir+"/"), err)
239+
}
240+
if name != "" {
292241
imported = append(imported, name)
293242
desired[name] = struct{}{}
294-
return nil
295-
})
243+
}
296244
}
297245

298246
// GC
@@ -317,12 +265,86 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
317265
}
318266
}
319267

320-
res := &syncResult{commit: commit, imported: uniq}
321-
_, _ = json.Marshal(res)
322-
_ = sha256.Sum256([]byte(commit))
323-
_ = hex.EncodeToString([]byte{})
324-
_ = controllerutil.AddFinalizer
325-
return res, nil
268+
return &syncResult{commit: commit, imported: uniq}, nil
269+
}
270+
271+
// syncImageFile imports one manifest and returns its name, or an empty name for
272+
// documents that are not named Images.
273+
func (r *ImageRepositoryReconciler) syncImageFile(ctx context.Context, repo *kubeworkspacesiov1alpha1.ImageRepository, commit, root, path string) (string, error) {
274+
data, err := os.ReadFile(path)
275+
if err != nil {
276+
return "", err
277+
}
278+
var u map[string]interface{}
279+
if err := yaml.Unmarshal(data, &u); err != nil {
280+
return "", fmt.Errorf("parse %s: %w", path, err)
281+
}
282+
kind, _ := u["kind"].(string)
283+
apiVersion, _ := u["apiVersion"].(string)
284+
if kind != "Image" || !strings.Contains(apiVersion, "kubeworkspaces.io") {
285+
return "", nil
286+
}
287+
obj := &unstructured.Unstructured{Object: u}
288+
name := obj.GetName()
289+
if name == "" {
290+
return "", nil
291+
}
292+
labels := obj.GetLabels()
293+
if labels == nil {
294+
labels = map[string]string{}
295+
}
296+
labels[imageRepositoryLabelKey] = repo.Name
297+
labels[imageRepositoryManagedBy] = imageRepositoryManagedVal
298+
obj.SetLabels(labels)
299+
ann := obj.GetAnnotations()
300+
if ann == nil {
301+
ann = map[string]string{}
302+
}
303+
ann[imageRepositorySourceURL] = repo.Spec.URL
304+
ann[imageRepositorySourceRef] = repo.Spec.Ref
305+
ann[imageRepositorySourceSHA] = commit
306+
ann[imageRepositorySourcePath] = strings.TrimPrefix(path, root+"/")
307+
obj.SetAnnotations(ann)
308+
309+
existing := &unstructured.Unstructured{}
310+
existing.SetGroupVersionKind(schema.GroupVersionKind{Group: "kubeworkspaces.io", Version: "v1alpha1", Kind: "Image"})
311+
err = r.Get(ctx, types.NamespacedName{Name: name}, existing)
312+
if apierrors.IsNotFound(err) {
313+
err = r.Create(ctx, obj)
314+
} else if err == nil {
315+
obj.SetResourceVersion(existing.GetResourceVersion())
316+
err = r.Update(ctx, obj)
317+
}
318+
if err != nil {
319+
return "", err
320+
}
321+
return name, nil
322+
}
323+
324+
// imageRepositoryFiles lists only direct YAML children of each configured
325+
// directory. ReadDir accepts paths with or without a trailing slash. Resolve all
326+
// directories before importing so a missing path fails the sync without pruning.
327+
func imageRepositoryFiles(root string, paths []string) ([]string, error) {
328+
var files []string
329+
seen := map[string]bool{}
330+
for _, scanPath := range paths {
331+
fullPath := filepath.Join(root, strings.TrimSpace(scanPath))
332+
entries, err := os.ReadDir(fullPath)
333+
if err != nil {
334+
return nil, fmt.Errorf("read image directory %q: %w", scanPath, err)
335+
}
336+
for _, entry := range entries {
337+
if entry.IsDir() || (!strings.HasSuffix(entry.Name(), ".yaml") && !strings.HasSuffix(entry.Name(), ".yml")) {
338+
continue
339+
}
340+
path := filepath.Join(fullPath, entry.Name())
341+
if !seen[path] {
342+
files = append(files, path)
343+
seen[path] = true
344+
}
345+
}
346+
}
347+
return files, nil
326348
}
327349

328350
// SetupWithManager sets up the controller with the Manager.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package controller
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"reflect"
7+
"testing"
8+
)
9+
10+
func TestImageRepositoryFiles(t *testing.T) {
11+
root := t.TempDir()
12+
for _, name := range []string{"images/base.yaml", "images/other.yml", "images/README.md", "images/kasm/core/core.yaml", "images/kasm/desktop/app.yaml", "images/kasm/desktop/nested/ignored.yaml"} {
13+
path := filepath.Join(root, name)
14+
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
15+
t.Fatal(err)
16+
}
17+
if err := os.WriteFile(path, []byte("kind: Image\n"), 0o600); err != nil {
18+
t.Fatal(err)
19+
}
20+
}
21+
for _, test := range []struct {
22+
name string
23+
paths []string
24+
want []string
25+
}{
26+
{"direct files only", []string{"images"}, []string{"images/base.yaml", "images/other.yml"}},
27+
{"optional trailing slash", []string{"images/"}, []string{"images/base.yaml", "images/other.yml"}},
28+
{"explicit subfolders", []string{"images", "images/kasm/core/", "images/kasm/desktop"}, []string{"images/base.yaml", "images/other.yml", "images/kasm/core/core.yaml", "images/kasm/desktop/app.yaml"}},
29+
{"duplicate paths", []string{"images", "images/"}, []string{"images/base.yaml", "images/other.yml"}},
30+
} {
31+
t.Run(test.name, func(t *testing.T) {
32+
got, err := imageRepositoryFiles(root, test.paths)
33+
if err != nil {
34+
t.Fatal(err)
35+
}
36+
for i := range got {
37+
got[i], err = filepath.Rel(root, got[i])
38+
if err != nil {
39+
t.Fatal(err)
40+
}
41+
}
42+
if !reflect.DeepEqual(got, test.want) {
43+
t.Fatalf("got %v, want %v", got, test.want)
44+
}
45+
})
46+
}
47+
t.Run("missing folder fails rather than returning a partial inventory", func(t *testing.T) {
48+
files, err := imageRepositoryFiles(root, []string{"images", "does-not-exist"})
49+
if err == nil || files != nil {
50+
t.Fatalf("got files=%v err=%v; expected an error without partial inventory", files, err)
51+
}
52+
})
53+
}

0 commit comments

Comments
 (0)