|
| 1 | +// SPDX-License-Identifier: AGPL-3.0-only |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "os" |
| 10 | + "sort" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/spf13/cobra" |
| 14 | + "k8s.io/apimachinery/pkg/runtime" |
| 15 | + "k8s.io/apimachinery/pkg/runtime/serializer" |
| 16 | + utilyaml "k8s.io/apimachinery/pkg/util/yaml" |
| 17 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 18 | + |
| 19 | + inventoryv1alpha1 "go.miloapis.com/inventory/api/v1alpha1" |
| 20 | +) |
| 21 | + |
| 22 | +const fieldManager = "datumctl-inventory" |
| 23 | + |
| 24 | +// applyOrder lists the inventory kinds apply handles, in dependency order: |
| 25 | +// parents are applied before the children that reference them. |
| 26 | +var applyOrder = []string{"Provider", "Region", "Site", "Cluster", "Node"} |
| 27 | + |
| 28 | +func kindOrder(kind string) (int, bool) { |
| 29 | + for i, k := range applyOrder { |
| 30 | + if k == kind { |
| 31 | + return i, true |
| 32 | + } |
| 33 | + } |
| 34 | + return 0, false |
| 35 | +} |
| 36 | + |
| 37 | +func newApplyCmd() *cobra.Command { |
| 38 | + var files []string |
| 39 | + var dryRun string |
| 40 | + cmd := &cobra.Command{ |
| 41 | + Use: "apply -f FILE", |
| 42 | + Short: "Create or update inventory objects from a manifest", |
| 43 | + Long: `Create or update inventory objects (providers, regions, sites, clusters, |
| 44 | +nodes) from a YAML or JSON manifest. |
| 45 | +
|
| 46 | +apply is an idempotent, declarative upsert: re-applying the same manifest makes |
| 47 | +no changes. Objects are applied in dependency order (providers, then regions, |
| 48 | +then sites, then clusters, then nodes) so a single mixed manifest lands cleanly. |
| 49 | +It uses server-side apply with field manager "datumctl-inventory". |
| 50 | +
|
| 51 | +This is for populating the inventory from declared configuration — not fleet |
| 52 | +management. Inventory lives on the Datum Cloud platform root, so apply takes no |
| 53 | +organization or project scope.`, |
| 54 | + Example: ` # Apply a manifest file |
| 55 | + datumctl inventory apply -f fleet.yaml |
| 56 | +
|
| 57 | + # Apply from stdin (e.g. piped from a renderer) |
| 58 | + render-fleet | datumctl inventory apply -f - |
| 59 | +
|
| 60 | + # Validate against the server without persisting |
| 61 | + datumctl inventory apply -f fleet.yaml --dry-run=server`, |
| 62 | + Args: cobra.NoArgs, |
| 63 | + RunE: func(cmd *cobra.Command, _ []string) error { |
| 64 | + if len(files) == 0 { |
| 65 | + return fmt.Errorf("at least one -f/--filename is required") |
| 66 | + } |
| 67 | + var server bool |
| 68 | + switch dryRun { |
| 69 | + case "", "none": |
| 70 | + server = false |
| 71 | + case "server": |
| 72 | + server = true |
| 73 | + default: |
| 74 | + return fmt.Errorf("invalid value %q for --dry-run; allowed: none, server", dryRun) |
| 75 | + } |
| 76 | + |
| 77 | + objs, err := readManifests(cmd.InOrStdin(), files) |
| 78 | + if err != nil { |
| 79 | + return err |
| 80 | + } |
| 81 | + if len(objs) == 0 { |
| 82 | + return fmt.Errorf("no inventory objects found in input") |
| 83 | + } |
| 84 | + sort.SliceStable(objs, func(i, j int) bool { return objs[i].order < objs[j].order }) |
| 85 | + |
| 86 | + c, err := newClient() |
| 87 | + if err != nil { |
| 88 | + return err |
| 89 | + } |
| 90 | + return applyObjects(cmd.Context(), cmd.OutOrStdout(), c, objs, server) |
| 91 | + }, |
| 92 | + } |
| 93 | + cmd.Flags().StringArrayVarP(&files, "filename", "f", nil, "Manifest file (YAML or JSON), or - for stdin. Repeatable.") |
| 94 | + cmd.Flags().StringVar(&dryRun, "dry-run", "none", `Must be "none" or "server". "server" validates against the API without persisting.`) |
| 95 | + return cmd |
| 96 | +} |
| 97 | + |
| 98 | +type applyObj struct { |
| 99 | + obj client.Object |
| 100 | + kind string |
| 101 | + order int |
| 102 | +} |
| 103 | + |
| 104 | +// readManifests parses every document from the given files (and stdin for "-") |
| 105 | +// into typed inventory objects, giving client-side validation and rejecting |
| 106 | +// kinds apply does not handle. |
| 107 | +func readManifests(stdin io.Reader, files []string) ([]applyObj, error) { |
| 108 | + scheme := runtime.NewScheme() |
| 109 | + if err := inventoryv1alpha1.AddToScheme(scheme); err != nil { |
| 110 | + return nil, fmt.Errorf("build scheme: %w", err) |
| 111 | + } |
| 112 | + decoder := serializer.NewCodecFactory(scheme).UniversalDeserializer() |
| 113 | + |
| 114 | + var out []applyObj |
| 115 | + for _, f := range files { |
| 116 | + r, closeFn, err := openInput(stdin, f) |
| 117 | + if err != nil { |
| 118 | + return nil, err |
| 119 | + } |
| 120 | + docs := utilyaml.NewYAMLOrJSONDecoder(r, 4096) |
| 121 | + for { |
| 122 | + var raw runtime.RawExtension |
| 123 | + if derr := docs.Decode(&raw); derr != nil { |
| 124 | + if derr == io.EOF { |
| 125 | + break |
| 126 | + } |
| 127 | + closeFn() |
| 128 | + return nil, fmt.Errorf("parse %s: %w", f, derr) |
| 129 | + } |
| 130 | + if len(raw.Raw) == 0 { |
| 131 | + continue |
| 132 | + } |
| 133 | + obj, gvk, derr := decoder.Decode(raw.Raw, nil, nil) |
| 134 | + if derr != nil { |
| 135 | + closeFn() |
| 136 | + return nil, fmt.Errorf("decode %s: %w", f, derr) |
| 137 | + } |
| 138 | + order, ok := kindOrder(gvk.Kind) |
| 139 | + if !ok { |
| 140 | + closeFn() |
| 141 | + return nil, fmt.Errorf("unsupported kind %q in %s (apply handles: %s)", gvk.Kind, f, strings.Join(applyOrder, ", ")) |
| 142 | + } |
| 143 | + co, ok := obj.(client.Object) |
| 144 | + if !ok { |
| 145 | + closeFn() |
| 146 | + return nil, fmt.Errorf("%s in %s is not an applyable object", gvk.Kind, f) |
| 147 | + } |
| 148 | + co.GetObjectKind().SetGroupVersionKind(*gvk) |
| 149 | + out = append(out, applyObj{obj: co, kind: gvk.Kind, order: order}) |
| 150 | + } |
| 151 | + closeFn() |
| 152 | + } |
| 153 | + return out, nil |
| 154 | +} |
| 155 | + |
| 156 | +func openInput(stdin io.Reader, f string) (io.Reader, func(), error) { |
| 157 | + if f == "-" { |
| 158 | + return stdin, func() {}, nil |
| 159 | + } |
| 160 | + fh, err := os.Open(f) |
| 161 | + if err != nil { |
| 162 | + return nil, func() {}, fmt.Errorf("open %s: %w", f, err) |
| 163 | + } |
| 164 | + return fh, func() { _ = fh.Close() }, nil |
| 165 | +} |
| 166 | + |
| 167 | +func applyObjects(ctx context.Context, w io.Writer, c client.Client, objs []applyObj, server bool) error { |
| 168 | + opts := []client.PatchOption{client.FieldOwner(fieldManager), client.ForceOwnership} |
| 169 | + suffix := "" |
| 170 | + if server { |
| 171 | + opts = append(opts, client.DryRunAll) |
| 172 | + suffix = " (server dry-run)" |
| 173 | + } |
| 174 | + for _, o := range objs { |
| 175 | + if err := c.Patch(ctx, o.obj, client.Apply, opts...); err != nil { |
| 176 | + return fmt.Errorf("apply %s/%s: %w", strings.ToLower(o.kind), o.obj.GetName(), err) |
| 177 | + } |
| 178 | + fmt.Fprintf(w, "applied %s/%s%s\n", strings.ToLower(o.kind), o.obj.GetName(), suffix) |
| 179 | + } |
| 180 | + return nil |
| 181 | +} |
0 commit comments