|
| 1 | +package helpers |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "context" |
| 7 | + "embed" |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "strings" |
| 12 | + "text/template" |
| 13 | + "time" |
| 14 | + |
| 15 | + extensionsapiserver "k8s.io/apiextensions-apiserver/pkg/apiserver" |
| 16 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 17 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 18 | + "k8s.io/apimachinery/pkg/types" |
| 19 | + apimachineryerrors "k8s.io/apimachinery/pkg/util/errors" |
| 20 | + "k8s.io/apimachinery/pkg/util/sets" |
| 21 | + "k8s.io/apimachinery/pkg/util/wait" |
| 22 | + kubeyaml "k8s.io/apimachinery/pkg/util/yaml" |
| 23 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 24 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 25 | +) |
| 26 | + |
| 27 | +// Bootstrap creates resources in a package's fs by |
| 28 | +// continuously retrying the list. This is blocking, i.e. it only returns (with error) |
| 29 | +// when the context is closed or with nil when the bootstrapping is successfully completed. |
| 30 | +func Bootstrap(ctx context.Context, client client.Client, fs embed.FS, batteriesIncluded sets.Set[string]) error { |
| 31 | + // bootstrap non-crd resources |
| 32 | + return wait.PollUntilContextCancel(ctx, time.Second, true, func(ctx context.Context) (bool, error) { |
| 33 | + if err := CreateResourcesFromFS(ctx, client, fs, batteriesIncluded); err != nil { |
| 34 | + log.FromContext(ctx).WithValues("err", err).Info("failed to bootstrap resources, retrying") |
| 35 | + return false, nil |
| 36 | + } |
| 37 | + return true, nil |
| 38 | + }) |
| 39 | +} |
| 40 | + |
| 41 | +// CreateResourcesFromFS creates all resources from a filesystem. |
| 42 | +func CreateResourcesFromFS(ctx context.Context, client client.Client, fs embed.FS, batteriesIncluded sets.Set[string]) error { |
| 43 | + files, err := fs.ReadDir(".") |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + |
| 48 | + var errs []error |
| 49 | + for _, f := range files { |
| 50 | + if f.IsDir() { |
| 51 | + continue |
| 52 | + } |
| 53 | + if err := CreateResourceFromFS(ctx, client, f.Name(), fs, batteriesIncluded); err != nil { |
| 54 | + errs = append(errs, err) |
| 55 | + } |
| 56 | + } |
| 57 | + return apimachineryerrors.NewAggregate(errs) |
| 58 | +} |
| 59 | + |
| 60 | +// CreateResourceFromFS creates given resource file. |
| 61 | +func CreateResourceFromFS(ctx context.Context, client client.Client, filename string, fs embed.FS, batteriesIncluded sets.Set[string]) error { |
| 62 | + raw, err := fs.ReadFile(filename) |
| 63 | + if err != nil { |
| 64 | + return fmt.Errorf("could not read %s: %w", filename, err) |
| 65 | + } |
| 66 | + |
| 67 | + if len(raw) == 0 { |
| 68 | + return nil // ignore empty files |
| 69 | + } |
| 70 | + |
| 71 | + d := kubeyaml.NewYAMLReader(bufio.NewReader(bytes.NewReader(raw))) |
| 72 | + var errs []error |
| 73 | + for i := 1; ; i++ { |
| 74 | + doc, err := d.Read() |
| 75 | + if errors.Is(err, io.EOF) { |
| 76 | + break |
| 77 | + } else if err != nil { |
| 78 | + return err |
| 79 | + } |
| 80 | + if len(bytes.TrimSpace(doc)) == 0 { |
| 81 | + continue |
| 82 | + } |
| 83 | + |
| 84 | + if err := createResourceFromFS(ctx, client, doc, batteriesIncluded); err != nil { |
| 85 | + errs = append(errs, fmt.Errorf("failed to create resource %s doc %d: %w", filename, i, err)) |
| 86 | + } |
| 87 | + } |
| 88 | + return apimachineryerrors.NewAggregate(errs) |
| 89 | +} |
| 90 | + |
| 91 | +const annotationCreateOnlyKey = "bootstrap.kcp.io/create-only" |
| 92 | +const annotationBattery = "bootstrap.kcp.io/battery" |
| 93 | + |
| 94 | +func createResourceFromFS(ctx context.Context, client client.Client, raw []byte, batteriesIncluded sets.Set[string]) error { |
| 95 | + log := log.FromContext(ctx) |
| 96 | + |
| 97 | + type Input struct { |
| 98 | + Batteries map[string]bool |
| 99 | + } |
| 100 | + input := Input{ |
| 101 | + Batteries: map[string]bool{}, |
| 102 | + } |
| 103 | + for _, b := range sets.List[string](batteriesIncluded) { |
| 104 | + input.Batteries[b] = true |
| 105 | + } |
| 106 | + tmpl, err := template.New("manifest").Parse(string(raw)) |
| 107 | + if err != nil { |
| 108 | + return fmt.Errorf("failed to parse manifest: %w", err) |
| 109 | + } |
| 110 | + var buf bytes.Buffer |
| 111 | + if err := tmpl.Execute(&buf, input); err != nil { |
| 112 | + return fmt.Errorf("failed to execute manifest: %w", err) |
| 113 | + } |
| 114 | + |
| 115 | + obj, gvk, err := extensionsapiserver.Codecs.UniversalDeserializer().Decode(buf.Bytes(), nil, &unstructured.Unstructured{}) |
| 116 | + if err != nil { |
| 117 | + return fmt.Errorf("could not decode raw: %w", err) |
| 118 | + } |
| 119 | + u, ok := obj.(*unstructured.Unstructured) |
| 120 | + if !ok { |
| 121 | + return fmt.Errorf("decoded into incorrect type, got %T, wanted %T", obj, &unstructured.Unstructured{}) |
| 122 | + } |
| 123 | + |
| 124 | + if v, found := u.GetAnnotations()[annotationBattery]; found { |
| 125 | + partOf := strings.Split(v, ",") |
| 126 | + included := false |
| 127 | + for _, p := range partOf { |
| 128 | + if batteriesIncluded.Has(strings.TrimSpace(p)) { |
| 129 | + included = true |
| 130 | + break |
| 131 | + } |
| 132 | + } |
| 133 | + if !included { |
| 134 | + log.V(4).WithValues("resource", u.GetName(), "batteriesRequired", v, "batteriesIncluded", batteriesIncluded).Info("skipping resource because required batteries are not among included batteries") |
| 135 | + return nil |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + key := types.NamespacedName{ |
| 140 | + Namespace: u.GetNamespace(), |
| 141 | + Name: u.GetName(), |
| 142 | + } |
| 143 | + err = client.Create(ctx, u) |
| 144 | + if err != nil { |
| 145 | + if apierrors.IsAlreadyExists(err) { |
| 146 | + err = client.Get(ctx, key, u) |
| 147 | + if err != nil { |
| 148 | + return err |
| 149 | + } |
| 150 | + |
| 151 | + if _, exists := u.GetAnnotations()[annotationCreateOnlyKey]; exists { |
| 152 | + log.Info("skipping update of object because it has the create-only annotation") |
| 153 | + |
| 154 | + return nil |
| 155 | + } |
| 156 | + |
| 157 | + u.SetResourceVersion(u.GetResourceVersion()) |
| 158 | + err = client.Update(ctx, u) |
| 159 | + if err != nil { |
| 160 | + return fmt.Errorf("could not update %s %s: %w", gvk.Kind, key.String(), err) |
| 161 | + } else { |
| 162 | + log.WithValues("resource", u.GetName(), "kind", gvk.Kind).Info("updated object") |
| 163 | + return nil |
| 164 | + } |
| 165 | + } |
| 166 | + return err |
| 167 | + } |
| 168 | + |
| 169 | + log.WithValues("resource", u.GetName(), "kind", gvk.Kind).Info("created object") |
| 170 | + |
| 171 | + return nil |
| 172 | +} |
0 commit comments