-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathdump.go
More file actions
1496 lines (1276 loc) · 44.6 KB
/
dump.go
File metadata and controls
1496 lines (1276 loc) · 44.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dump
import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"slices"
"strings"
"time"
"github.com/go-logr/logr"
"github.com/rancher/fleet/internal/config"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/yaml"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
errutil "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
"k8s.io/streaming/pkg/httpstream"
fleet "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"
"github.com/rancher/fleet/pkg/sharding"
)
type Options struct {
FetchLimit int64
Namespace string
AllNamespaces bool
GitRepo string
Bundle string
HelmOp string
WithSecrets bool
WithSecretsMetadata bool
WithContent bool
WithContentMetadata bool
}
func Create(ctx context.Context, cfg *rest.Config, path string, opt Options) error {
c, err := createClient(cfg)
if err != nil {
return fmt.Errorf("failed to create Kubernetes client: %w", err)
}
d, err := createDynamicClient(cfg)
if err != nil {
return fmt.Errorf("failed to create dynamic Kubernetes client: %w", err)
}
return CreateWithClients(ctx, cfg, d, c, path, opt)
}
func addObjectsToArchive(
ctx context.Context,
dynamic dynamic.Interface,
logger logr.Logger,
resource string,
w *tar.Writer,
opt Options,
) error {
rID := schema.GroupVersionResource{
Group: "fleet.cattle.io",
Version: "v1alpha1",
Resource: resource,
}
logger.V(1).Info("Fetching ...", "resource", rID.String())
lo := metav1.ListOptions{Limit: opt.FetchLimit}
for {
var list *unstructured.UnstructuredList
var err error
// Apply namespace filtering when opt.Namespace is set and not in all-namespaces mode
if opt.Namespace != "" && !opt.AllNamespaces {
list, err = dynamic.Resource(rID).Namespace(opt.Namespace).List(ctx, lo)
} else {
list, err = dynamic.Resource(rID).List(ctx, lo)
}
if err != nil {
return fmt.Errorf("failed to list %s: %w", resource, err)
}
for _, i := range list.Items {
g, err := yaml.Marshal(&i)
if err != nil {
return fmt.Errorf("failed to marshal %s: %w", resource, err)
}
fileName := fmt.Sprintf("%s_%s_%s", resource, i.GetNamespace(), i.GetName())
if err := addFileToArchive(g, fileName, w); err != nil {
return err
}
}
c := list.GetContinue()
if c == "" {
break
}
lo.Continue = c
}
return nil
}
func addFileToArchive(data []byte, name string, w *tar.Writer) error {
if err := w.WriteHeader(&tar.Header{
Name: name,
Mode: 0644,
Typeflag: tar.TypeReg,
ModTime: time.Unix(0, 0),
Size: int64(len(data)),
}); err != nil {
return err
}
_, err := w.Write(data)
return err
}
func addContentsToArchive(
ctx context.Context,
dynamic dynamic.Interface,
logger logr.Logger,
w *tar.Writer,
metadataOnly bool,
filterCfg *filterConfig,
opt Options,
) error {
if filterCfg.useFiltering && filterCfg.contentIDs == nil {
// Filtering is active but no bundles were found, so there are no relevant contents to add.
// contentIDs is nil (not collected) precisely when bundleNames was empty.
return nil
}
// Convert to map for faster lookups
var contentIDMap map[string]bool
if filterCfg.contentIDs != nil {
contentIDMap = make(map[string]bool, len(filterCfg.contentIDs))
for _, id := range filterCfg.contentIDs {
contentIDMap[id] = true
}
logger.Info("Filtering content resources", "contentIDs", len(filterCfg.contentIDs))
}
rID := schema.GroupVersionResource{
Group: "fleet.cattle.io",
Version: "v1alpha1",
Resource: "contents",
}
logger.V(1).Info("Fetching ...", "resource", rID.String())
lo := metav1.ListOptions{Limit: opt.FetchLimit}
for {
list, err := dynamic.Resource(rID).List(ctx, lo)
if err != nil {
return fmt.Errorf("failed to list contents: %w", err)
}
for _, i := range list.Items {
// Skip if filtering and this content ID is not in our filter set
if contentIDMap != nil && !contentIDMap[i.GetName()] {
continue
}
if metadataOnly {
// Only strip the actual content (manifests), keep sha256sum and status as metadata
i.Object["content"] = nil
}
g, err := yaml.Marshal(&i)
if err != nil {
return fmt.Errorf("failed to marshal content: %w", err)
}
fileName := "contents_" + i.GetName()
if err := addFileToArchive(g, fileName, w); err != nil {
return err
}
}
c := list.GetContinue()
if c == "" {
break
}
lo.Continue = c
}
return nil
}
func addSecretsToArchive(
ctx context.Context,
dynamic dynamic.Interface,
c client.Client,
logger logr.Logger,
w *tar.Writer,
metadataOnly bool,
filterCfg *filterConfig,
opt Options,
) error {
if filterCfg.useFiltering && len(filterCfg.secretNames) == 0 {
// No secret names to filter, skip adding any secrets
return nil
}
nss, err := getNamespaces(ctx, dynamic, logger, opt)
if err != nil {
return fmt.Errorf("failed to get relevant namespaces for secrets: %w", err)
}
// Convert secretNames to map for efficient lookup
var secretNameMap map[string]bool
if filterCfg.secretNames != nil {
secretNameMap = make(map[string]bool, len(filterCfg.secretNames))
for _, name := range filterCfg.secretNames {
secretNameMap[name] = true
}
}
// System namespaces that should never be filtered
systemNamespaces := map[string]bool{
"kube-system": true,
"default": true,
config.DefaultNamespace: true,
"cattle-fleet-local-system": true,
}
var merr []error
nss:
for _, ns := range nss {
// Determine if we should filter secrets in this namespace
shouldFilter := secretNameMap != nil && ns == opt.Namespace && !systemNamespaces[ns]
var secrets corev1.SecretList
for {
if err := c.List(ctx, &secrets, client.InNamespace(ns), client.Limit(opt.FetchLimit), client.Continue(secrets.Continue)); err != nil {
merr = append(merr, fmt.Errorf("failed to list secrets for namespace %q: %w", ns, err))
continue nss
}
for _, secret := range secrets.Items {
// Skip if filtering and this secret is not in our filter set
if shouldFilter && !secretNameMap[secret.Name] {
continue
}
if metadataOnly {
secret.Data = nil
}
data, err := yaml.Marshal(&secret)
if err != nil {
merr = append(merr, fmt.Errorf("failed to marshal secret: %w", err))
continue
}
fileName := fmt.Sprintf("secrets_%s_%s", secret.Namespace, secret.Name)
if err := addFileToArchive(data, fileName, w); err != nil {
merr = append(merr, fmt.Errorf("failed to add secret to archive: %w", err))
}
}
if secrets.Continue == "" {
break
}
}
}
return errutil.NewAggregate(merr)
}
// getNamespaces returns a list of namespaces relevant to the current context, containing:
// - kube-system
// - default
// - cattle-fleet-system
// - cattle-fleet-local-system
// - each cluster's namespace (only when not filtering by namespace)
// When namespace filtering is active (opt.Namespace is set and not AllNamespaces),
// returns only the filtered namespace plus system namespaces.
//
// TODO getNamespaces is called twice (for events and for secrets); consider caching the result.
func getNamespaces(ctx context.Context, dynamic dynamic.Interface, logger logr.Logger, opt Options) ([]string, error) {
// Use a map to deduplicate namespaces
nsMap := map[string]struct{}{
"default": {},
"kube-system": {},
config.DefaultNamespace: {},
"cattle-fleet-local-system": {},
}
// When filtering by namespace, just return the filtered namespace plus system namespaces
if opt.Namespace != "" && !opt.AllNamespaces {
nsMap[opt.Namespace] = struct{}{}
// Convert map to slice and return early
res := make([]string, 0, len(nsMap))
for ns := range nsMap {
res = append(res, ns)
}
return res, nil
}
// When not filtering, discover all cluster namespaces
clusRscID := schema.GroupVersionResource{
Group: "fleet.cattle.io",
Version: "v1alpha1",
Resource: "clusters",
}
lo := metav1.ListOptions{Limit: opt.FetchLimit}
for {
clusters, err := dynamic.Resource(clusRscID).List(ctx, lo)
if err != nil {
return nil, fmt.Errorf("failed to list clusters: %w", err)
}
for _, i := range clusters.Items {
var c fleet.Cluster
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(i.Object, &c); err != nil {
logger.Error(
fmt.Errorf("resource %v", i),
"Skipping resource listed as cluster but with incompatible format; this should not happen",
)
continue
}
nsMap[c.Namespace] = struct{}{}
}
c := clusters.GetContinue()
if c == "" {
break
}
lo.Continue = c
}
// Convert map to slice
res := make([]string, 0, len(nsMap))
for ns := range nsMap {
res = append(res, ns)
}
slices.Sort(res)
return res, nil
}
// addEventsToArchive determines which namespaces to fetch events from, and for each of those namespaces where events
// are found, writes a file named `events_<namespace>` into w.
func addEventsToArchive(
ctx context.Context,
d dynamic.Interface,
c client.Client,
logger logr.Logger,
w *tar.Writer,
opt Options,
) error {
nss, err := getNamespaces(ctx, d, logger, opt)
if err != nil {
return fmt.Errorf("failed to get relevant namespaces for events: %w", err)
}
var merr []error
for _, ns := range nss {
err := func() error {
// Create a temporary file to accumulate events. We need to do this because we need to know
// the total size of the events for the tar header, but we want to fetch and write events
// page by page to avoid keeping them all in memory.
tmpFile, err := os.CreateTemp("", fmt.Sprintf("events_%s_*.json", ns))
if err != nil {
return fmt.Errorf("failed to create temp file for events in namespace %q: %w", ns, err)
}
defer os.Remove(tmpFile.Name()) // Clean up temp file
defer tmpFile.Close() // Close file handle
var NSevts corev1.EventList
foundEvents := false
// Write events page by page to temp file
writeErr := false
for {
if err := c.List(ctx, &NSevts, client.InNamespace(ns), client.Limit(opt.FetchLimit), client.Continue(NSevts.Continue)); err != nil {
merr = append(merr, fmt.Errorf("failed to list events for namespace %q: %w", ns, err))
writeErr = true
break
}
for _, e := range NSevts.Items {
je, err := json.Marshal(e)
if err != nil {
merr = append(merr, fmt.Errorf("failed to encode event into JSON: %w", err))
continue
}
if foundEvents {
if _, err := tmpFile.WriteString("\n"); err != nil {
merr = append(merr, fmt.Errorf("failed to write newline to temp file: %w", err))
writeErr = true
break
}
}
if _, err := tmpFile.Write(je); err != nil {
merr = append(merr, fmt.Errorf("failed to write event to temp file: %w", err))
writeErr = true
break
}
foundEvents = true
}
if writeErr || NSevts.Continue == "" {
break
}
}
if writeErr {
return nil
}
if !foundEvents {
return nil
}
// Get file size
fileInfo, err := tmpFile.Stat()
if err != nil {
return fmt.Errorf("failed to stat temp file for namespace %q: %w", ns, err)
}
// Seek back to beginning to read
if _, err := tmpFile.Seek(0, 0); err != nil {
return fmt.Errorf("failed to seek temp file for namespace %q: %w", ns, err)
}
// Write tar header
if err := w.WriteHeader(&tar.Header{
Name: "events_" + ns,
Mode: 0644,
Typeflag: tar.TypeReg,
ModTime: time.Unix(0, 0),
Size: fileInfo.Size(),
}); err != nil {
return fmt.Errorf("failed to write tar header for events in namespace %q: %w", ns, err)
}
// Copy temp file to tar
if _, err := io.Copy(w, tmpFile); err != nil {
return fmt.Errorf("failed to copy events to archive for namespace %q: %w", ns, err)
}
return nil
}()
if err != nil {
merr = append(merr, err)
}
}
return errutil.NewAggregate(merr)
}
func addMetricsToArchive(ctx context.Context, c client.Client, logger logr.Logger, cfg *rest.Config, w *tar.Writer, opt Options) error {
var monitoringSvcs []corev1.Service
var svcs corev1.ServiceList
for {
opts := []client.ListOption{client.Limit(opt.FetchLimit), client.Continue(svcs.Continue)}
if err := c.List(ctx, &svcs, opts...); err != nil {
return fmt.Errorf("failed to list services for extracting metrics: %w", err)
}
for _, svc := range svcs.Items {
if !strings.HasPrefix(svc.Name, "monitoring-") {
continue
}
monitoringSvcs = append(monitoringSvcs, svc)
}
if svcs.Continue == "" {
break
}
}
if len(monitoringSvcs) == 0 {
logger.Info("No monitoring services found; Fleet has probably been installed with metrics disabled.")
return nil
}
// XXX: how about HelmOps? report missing svc?
for _, svc := range monitoringSvcs {
closeFn, port, httpCli, err := forwardPorts(ctx, cfg, logger, c, &svc, opt)
if err != nil {
return fmt.Errorf("failed to forward ports: %w", err)
}
defer closeFn()
req, err := http.NewRequestWithContext(
ctx,
http.MethodGet,
fmt.Sprintf("http://localhost:%d/metrics", port),
nil,
)
if err != nil {
return fmt.Errorf("failed to create request to metrics service: %w", err)
}
resp, err := httpCli.Do(req)
if err != nil {
return fmt.Errorf("failed to get response from metrics service: %w", err)
}
defer func() {
if resp.Body != nil {
resp.Body.Close()
}
}()
if resp.Body == nil {
return fmt.Errorf("received empty response body from service %s/%s", svc.Namespace, svc.Name)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body from metrics service: %w", err)
}
logger.Info("Extracted metrics", "service", svc.Name)
fileName := fmt.Sprintf("metrics_%s_%s", svc.Namespace, svc.Name)
if err := addFileToArchive(body, fileName, w); err != nil {
return fmt.Errorf("failed to write metrics to archive from service %s: %w", svc.Name, err)
}
}
return nil
}
func createClient(cfg *rest.Config) (client.Client, error) {
c, err := client.New(cfg, client.Options{Scheme: clientgoscheme.Scheme})
if err != nil {
return nil, err
}
return c, nil
}
func createDynamicClient(cfg *rest.Config) (dynamic.Interface, error) {
di, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, err
}
return di, nil
}
// createDialer creates a dialer needed to build a port forwarder from the service svc.
// It involves identifying the pod exposed by svc, since building a port forwarder using the service's K8s API URL
// directly does not work.
func createDialer(ctx context.Context, cfg *rest.Config, c client.Client, svc *corev1.Service, opt Options) (httpstream.Dialer, *http.Client, error) {
var (
appLabel string
shardKey string
shardValue string
)
for k, v := range svc.Spec.Selector {
switch k {
case "app":
appLabel = v
continue
case sharding.ShardingIDLabel, sharding.ShardingDefaultLabel:
shardKey = k
shardValue = v
continue
}
}
if appLabel == "" {
return nil, nil, fmt.Errorf("no app label found on service %s/%s", svc.Namespace, svc.Name)
}
var selectedPod *corev1.Pod
matchingLabels := client.MatchingLabels{
"app": appLabel,
}
if shardKey != "" {
matchingLabels[shardKey] = shardValue
}
var pods corev1.PodList
for {
opts := []client.ListOption{
client.InNamespace(svc.Namespace),
matchingLabels,
client.Limit(opt.FetchLimit),
client.Continue(pods.Continue),
}
if err := c.List(ctx, &pods, opts...); err != nil {
return nil, nil, fmt.Errorf("failed to get pod behind service %s/%s: %w", svc.Namespace, svc.Name, err)
}
for _, p := range pods.Items {
if selectedPod == nil {
podCopy := p
selectedPod = &podCopy
} else {
return nil, nil, fmt.Errorf("found more than one pod behind service %s/%s", svc.Namespace, svc.Name)
}
}
if pods.Continue == "" {
break
}
}
if selectedPod == nil {
return nil, nil, fmt.Errorf("no pod found behind service %s/%s", svc.Namespace, svc.Name)
}
pod := *selectedPod
rt, up, err := spdy.RoundTripperFor(cfg)
if err != nil {
return nil, nil, fmt.Errorf("failed to create upgrader for fetching metrics: %w", err)
}
u, err := url.Parse(cfg.Host)
if err != nil {
return nil, nil, fmt.Errorf("failed to create dialer for fetching metrics because the API server URL could not be parsed: %w", err)
}
u.Path = path.Join(u.Path, fmt.Sprintf("/api/v1/namespaces/%s/pods/%s/portforward", pod.Namespace, pod.Name))
u.Host = strings.TrimRight(u.Host, "/")
httpCli := http.Client{Transport: rt}
return spdy.NewDialerForStreaming(up, &httpCli, http.MethodPost, u), &httpCli, nil
}
// filterConfig holds the filtering configuration determined from options
type filterConfig struct {
bundleNames []string
contentIDs []string
secretNames []string
// useFiltering indicates whether any filtering is active; It does so by checking if
// opt.Namespace is set (and not in all-namespaces mode). Filtering by GitRepo, Bundle or HelmOp
// also implies namespace filtering, so we don't need to check those separately here.
//
// If false, all bundles, contents, and secrets will be included. If true, it means at least a
// namespace, but not necessarily a GitRepo, Bundle or HelmOp has been specified.
useFiltering bool
}
// determineFilterConfig analyzes options and returns the appropriate filtering configuration
func determineFilterConfig(ctx context.Context, d dynamic.Interface, logger logr.Logger, opt Options) (*filterConfig, error) {
cfg := &filterConfig{
useFiltering: !opt.AllNamespaces && opt.Namespace != "",
}
if !cfg.useFiltering {
return cfg, nil
}
var err error
switch {
case opt.Bundle != "":
cfg.bundleNames, err = validateAndGetBundle(ctx, d, opt.Namespace, opt.Bundle)
if err != nil {
return nil, err
}
logger.Info("Filtering by Bundle", "namespace", opt.Namespace, "bundle", opt.Bundle)
case opt.GitRepo != "":
cfg.bundleNames, err = collectBundleNamesByGitRepo(ctx, d, opt.Namespace, opt.GitRepo, opt.FetchLimit)
if err != nil {
return nil, fmt.Errorf("failed to collect bundle names for gitrepo %q: %w", opt.GitRepo, err)
}
logger.Info("Filtering by GitRepo", "namespace", opt.Namespace, "gitrepo", opt.GitRepo, "bundles", len(cfg.bundleNames))
case opt.HelmOp != "":
cfg.bundleNames, err = collectBundleNamesByHelmOp(ctx, d, opt.Namespace, opt.HelmOp, opt.FetchLimit)
if err != nil {
return nil, fmt.Errorf("failed to collect bundle names for helmop %q: %w", opt.HelmOp, err)
}
logger.Info("Filtering by HelmOp", "namespace", opt.Namespace, "helmop", opt.HelmOp, "bundles", len(cfg.bundleNames))
default:
cfg.bundleNames, err = collectBundleNames(ctx, d, opt.Namespace, opt.FetchLimit)
if err != nil {
return nil, fmt.Errorf("failed to collect bundle names: %w", err)
}
logger.Info("Filtering by namespace", "namespace", opt.Namespace, "bundles", len(cfg.bundleNames))
}
// Collect content IDs if content options are enabled
if (opt.WithContent || opt.WithContentMetadata) && len(cfg.bundleNames) > 0 {
cfg.contentIDs, err = collectContentIDs(ctx, d, opt.Namespace, cfg.bundleNames, opt.FetchLimit)
if err != nil {
return nil, fmt.Errorf("failed to collect content IDs: %w", err)
}
logger.Info("Collected content IDs from bundles", "count", len(cfg.contentIDs))
}
// Collect secret names if secret options are enabled
if (opt.WithSecrets || opt.WithSecretsMetadata) && len(cfg.bundleNames) > 0 {
cfg.secretNames, err = collectSecretNames(ctx, d, logger, opt.Namespace, cfg.bundleNames, opt.GitRepo, opt.Bundle, opt.HelmOp, opt.FetchLimit)
if err != nil {
return nil, fmt.Errorf("failed to collect secret names: %w", err)
}
logger.Info("Collected secret names from GitRepos/Bundles/HelmOps", "count", len(cfg.secretNames))
}
return cfg, nil
}
// validateAndGetBundle validates a bundle exists and returns it as a single-element slice
func validateAndGetBundle(ctx context.Context, d dynamic.Interface, namespace, bundleName string) ([]string, error) {
exists, err := bundleExists(ctx, d, namespace, bundleName)
if err != nil {
return nil, fmt.Errorf("failed to check if bundle %q exists: %w", bundleName, err)
}
if !exists {
return nil, fmt.Errorf("bundle %q does not exist in namespace %q", bundleName, namespace)
}
return []string{bundleName}, nil
}
// addFilteredGitReposAndBundles adds GitRepos and Bundles with appropriate filtering
func addFilteredGitReposAndBundles(ctx context.Context, d dynamic.Interface, logger logr.Logger, w *tar.Writer, cfg *filterConfig, opt Options) error {
switch {
case opt.GitRepo != "":
// Add only the specific GitRepo
if err := addObjectsWithNameFilter(ctx, d, logger, "gitrepos", w, []string{opt.GitRepo}, opt); err != nil {
return fmt.Errorf("failed to add gitrepos to archive: %w", err)
}
// Add only bundles matching the collected bundle names
if err := addObjectsWithNameFilter(ctx, d, logger, "bundles", w, cfg.bundleNames, opt); err != nil {
return fmt.Errorf("failed to add bundles to archive: %w", err)
}
case opt.HelmOp != "":
// HelmOp filter: skip GitRepos, add only bundles
if err := addObjectsWithNameFilter(ctx, d, logger, "bundles", w, cfg.bundleNames, opt); err != nil {
return fmt.Errorf("failed to add bundles to archive: %w", err)
}
case opt.Bundle != "":
// Bundle filter: skip GitRepos, add only the specific Bundle
if err := addObjectsWithNameFilter(ctx, d, logger, "bundles", w, cfg.bundleNames, opt); err != nil {
return fmt.Errorf("failed to add bundles to archive: %w", err)
}
default:
// No filter, add all gitrepos and bundles from namespace
if err := addObjectsToArchive(ctx, d, logger, "gitrepos", w, opt); err != nil {
return fmt.Errorf("failed to add gitrepos to archive: %w", err)
}
if err := addObjectsToArchive(ctx, d, logger, "bundles", w, opt); err != nil {
return fmt.Errorf("failed to add bundles to archive: %w", err)
}
}
return nil
}
// addOtherNamespaceResources adds resources that are not filtered by GitRepo/Bundle
func addOtherNamespaceResources(ctx context.Context, d dynamic.Interface, logger logr.Logger, w *tar.Writer, opt Options) error {
otherNamespaceTypes := []string{
"clusters",
"clustergroups",
"bundlenamespacemappings",
"gitreporestrictions",
}
for _, t := range otherNamespaceTypes {
if err := addObjectsToArchive(ctx, d, logger, t, w, opt); err != nil {
return fmt.Errorf("failed to add %s to archive: %w", t, err)
}
}
return nil
}
// addFilteredHelmOps adds HelmOps with appropriate filtering.
// HelmOps are namespace-scoped resources like GitRepos. They are:
// - excluded entirely when filtering by GitRepo or Bundle,
// - name-filtered when a specific HelmOp is requested, and
// - otherwise included using namespace filtering only.
func addFilteredHelmOps(ctx context.Context, d dynamic.Interface, logger logr.Logger, w *tar.Writer, opt Options) error {
switch {
case opt.GitRepo != "" || opt.Bundle != "":
// When filtering by GitRepo or Bundle, HelmOps are unrelated resources and must not be included.
return nil
case opt.HelmOp != "":
// Add only the specific HelmOp
if err := addObjectsWithNameFilter(ctx, d, logger, "helmops", w, []string{opt.HelmOp}, opt); err != nil {
return fmt.Errorf("failed to add helmops to archive: %w", err)
}
default:
// In unfiltered mode, HelmOps are namespace-scoped like GitRepos and use namespace filtering only.
if err := addObjectsToArchive(ctx, d, logger, "helmops", w, opt); err != nil {
return fmt.Errorf("failed to add helmops to archive: %w", err)
}
}
return nil
}
// forwardPorts creates a port forwarder for svc.
// In case of success, it returns a non-zero port number on which the service is available, an HTTP client which can
// later be used to query the service on the forwarded port, and a closing function.
// It is the caller's responsibility to call that closing function to close the port forwarder once it is no longer
// needed.
func forwardPorts(
ctx context.Context,
cfg *rest.Config,
logger logr.Logger,
c client.Client,
svc *corev1.Service,
opt Options,
) (func(), int, *http.Client, error) {
fail := func(fmtStr string, args ...any) (func(), int, *http.Client, error) {
return func() {}, 0, nil, fmt.Errorf(fmtStr, args...)
}
if len(svc.Spec.Ports) == 0 {
return fail("service %s/%s does not have any exposed ports", svc.Namespace, svc.Name)
}
svcPort := svc.Spec.Ports[0].Port
dl, httpCli, err := createDialer(ctx, cfg, c, svc, opt)
if err != nil {
return fail("failed to create dialer for port forwarding for service %s/%s: %w", svc.Namespace, svc.Name, err)
}
basePort := 8000
var closeFn func()
var port int
// Keep trying to set up a port forwarder if failures happen, for instance because the chosen port is already in use
maxAttempts := 5
i := 0
for i < maxAttempts {
prefix := fmt.Sprintf("attempt %d: ", i+1)
// Note on the `nolint: gosec` comment below: We are looking for an available port number; this can afford to be
// fairly predictable.
r := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint: gosec
port = basePort + r.Intn(57535) // Highest possible port: 65534
ports := []string{fmt.Sprintf("%d:%d", port, svcPort)}
stopChan := make(chan struct{})
readyChan := make(chan struct{})
fwder, err := portforward.NewForStreaming(dl, ports, stopChan, readyChan, os.Stdout, os.Stderr)
if err != nil {
msg := "failed to create ports forwarder for fetching metrics"
logger.Error(err, "%s%s", prefix, msg)
if i < maxAttempts-1 {
continue
}
return fail("%s%s: %w", prefix, msg, err)
}
errChan := make(chan error)
go func() {
if err := fwder.ForwardPorts(); err != nil {
errChan <- err
}
}()
closeFn = func() {
fwder.Close()
logger.Info("Closed port forwarding", "service", svc.Name, "port", port)
}
select {
case <-readyChan:
logger.Info("Port forwarding ready")
i = maxAttempts // No need to keep trying
case err = <-errChan:
msg := "failed to forward ports for fetching metrics"
logger.Error(err, "%s%s", prefix, msg)
if i < maxAttempts-1 {
i++
continue
}
return fail("%s%s : %w", prefix, msg, err)
}
}
return closeFn, port, httpCli, nil
}
// CreateWithClients creates a dump with namespace filtering support.
// When opt.Namespace is set and opt.AllNamespaces is false, it filters resources
// intelligently based on their relationships:
// - GitRepos, Bundles, ClusterGroups, etc. are filtered by namespace
// - BundleDeployments are filtered by bundle-namespace label
// - Clusters may be in the bundle namespace or other namespaces
func CreateWithClients(ctx context.Context, cfg *rest.Config, d dynamic.Interface, c client.Client, path string, opt Options) error {
logger := log.FromContext(ctx).WithName("fleet-dump")
tgz, err := os.Create(path)
if err != nil {
return fmt.Errorf("failed to create %s: %w", path, err)
}
defer tgz.Close()
gz := gzip.NewWriter(tgz)
w := tar.NewWriter(gz)
// Determine filtering configuration
filterCfg, err := determineFilterConfig(ctx, d, logger, opt)
if err != nil {
return err
}
// Add GitRepos and Bundles with appropriate filtering
if err := addFilteredGitReposAndBundles(ctx, d, logger, w, filterCfg, opt); err != nil {
return err
}
// Add other namespace resources
if err := addOtherNamespaceResources(ctx, d, logger, w, opt); err != nil {
return err
}
// BundleDeployments: filter by bundle-namespace label when filtering
if err := addBundleDeployments(ctx, d, logger, w, filterCfg, opt); err != nil {
return fmt.Errorf("failed to add bundledeployments to archive: %w", err)
}
// HelmOps: add with appropriate filtering
if err := addFilteredHelmOps(ctx, d, logger, w, opt); err != nil {
return err
}
// Add contents if requested
if opt.WithContent || opt.WithContentMetadata {
contentMetadataOnly := opt.WithContentMetadata && !opt.WithContent
if err := addContentsToArchive(ctx, d, logger, w, contentMetadataOnly, filterCfg, opt); err != nil {
return fmt.Errorf("failed to add contents to archive: %w", err)
}
}
// Add secrets if requested
if opt.WithSecrets || opt.WithSecretsMetadata {
secretsMetadataOnly := opt.WithSecretsMetadata && !opt.WithSecrets
if err := addSecretsToArchive(ctx, d, c, logger, w, secretsMetadataOnly, filterCfg, opt); err != nil {
return fmt.Errorf("failed to add secrets to archive: %w", err)
}
}
// Add events
if err := addEventsToArchive(ctx, d, c, logger, w, opt); err != nil {
return fmt.Errorf("failed to add events to archive: %w", err)
}
// Add metrics
if err := addMetricsToArchive(ctx, c, logger, cfg, w, opt); err != nil {
return fmt.Errorf("failed to add metrics to archive: %w", err)
}
// Close archive
if err := w.Close(); err != nil {
return fmt.Errorf("failed to close tar writer: %w", err)
}
if err := gz.Close(); err != nil {
return fmt.Errorf("failed to close gzip writer: %w", err)
}
return nil
}
// bundleExists checks if a bundle with the given name exists in the namespace
func bundleExists(ctx context.Context, d dynamic.Interface, namespace string, bundleName string) (bool, error) {