|
| 1 | +package pipe |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/MakeNowJust/heredoc/v2" |
| 12 | + "github.com/charmbracelet/log" |
| 13 | + "github.com/ctrlplanedev/cli/internal/api" |
| 14 | + "github.com/ctrlplanedev/cli/internal/cliutil" |
| 15 | + "github.com/ctrlplanedev/cli/pkg/resourceprovider" |
| 16 | + "github.com/spf13/cobra" |
| 17 | + "github.com/spf13/viper" |
| 18 | +) |
| 19 | + |
| 20 | +func NewSyncPipeCmd() *cobra.Command { |
| 21 | + var providerName string |
| 22 | + |
| 23 | + cmd := &cobra.Command{ |
| 24 | + Use: "pipe", |
| 25 | + Short: "Sync resources from stdin into Ctrlplane", |
| 26 | + Example: heredoc.Doc(` |
| 27 | + # One-shot sync from a script |
| 28 | + $ ./discover-databases.sh | ctrlc sync pipe --provider "custom-db" |
| 29 | +
|
| 30 | + # Inline JSON |
| 31 | + $ echo '[{"name":"web-1","identifier":"web-1-prod","version":"custom/v1","kind":"Server","config":{},"metadata":{}}]' \ |
| 32 | + | ctrlc sync pipe --provider "my-servers" |
| 33 | +
|
| 34 | + # Single resource (no array wrapper needed) |
| 35 | + $ echo '{"name":"web-1","identifier":"web-1-prod","version":"custom/v1","kind":"Server"}' \ |
| 36 | + | ctrlc sync pipe --provider "my-servers" |
| 37 | +
|
| 38 | + # From curl with jq transformation |
| 39 | + $ curl -s https://cmdb.internal/api/servers \ |
| 40 | + | jq '[.[] | {name, identifier: .id, version: "cmdb/v1", kind: "Server", config: ., metadata: {}}]' \ |
| 41 | + | ctrlc sync pipe --provider "cmdb" |
| 42 | + `), |
| 43 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 44 | + // Detect piped stdin |
| 45 | + stat, err := os.Stdin.Stat() |
| 46 | + if err != nil { |
| 47 | + return fmt.Errorf("failed to stat stdin: %w", err) |
| 48 | + } |
| 49 | + if (stat.Mode() & os.ModeCharDevice) != 0 { |
| 50 | + return fmt.Errorf("no piped input detected -- pipe JSON resources to this command") |
| 51 | + } |
| 52 | + |
| 53 | + // Read all stdin |
| 54 | + data, err := io.ReadAll(os.Stdin) |
| 55 | + if err != nil { |
| 56 | + return fmt.Errorf("failed to read stdin: %w", err) |
| 57 | + } |
| 58 | + if len(data) == 0 { |
| 59 | + return fmt.Errorf("stdin is empty -- expected JSON resource array") |
| 60 | + } |
| 61 | + |
| 62 | + // Parse JSON -- try array first, then single object |
| 63 | + resources, err := parseResources(data) |
| 64 | + if err != nil { |
| 65 | + return err |
| 66 | + } |
| 67 | + |
| 68 | + // Validate required fields |
| 69 | + if err := validateResources(resources); err != nil { |
| 70 | + return err |
| 71 | + } |
| 72 | + |
| 73 | + log.Info("Syncing resources from stdin", "count", len(resources), "provider", providerName) |
| 74 | + |
| 75 | + // Create API client |
| 76 | + apiURL := viper.GetString("url") |
| 77 | + apiKey := viper.GetString("api-key") |
| 78 | + workspace := viper.GetString("workspace") |
| 79 | + ctrlplaneClient, err := api.NewAPIKeyClientWithResponses(apiURL, apiKey) |
| 80 | + if err != nil { |
| 81 | + return fmt.Errorf("failed to create API client: %w", err) |
| 82 | + } |
| 83 | + |
| 84 | + // Upsert resource provider |
| 85 | + rp, err := resourceprovider.New(ctrlplaneClient, workspace, providerName) |
| 86 | + if err != nil { |
| 87 | + return fmt.Errorf("failed to create resource provider: %w", err) |
| 88 | + } |
| 89 | + |
| 90 | + // Upsert resources |
| 91 | + ctx := context.Background() |
| 92 | + upsertResp, err := rp.UpsertResource(ctx, resources) |
| 93 | + if err != nil { |
| 94 | + return fmt.Errorf("failed to upsert resources: %w", err) |
| 95 | + } |
| 96 | + |
| 97 | + log.Info("Response from upserting resources", "status", upsertResp.Status) |
| 98 | + |
| 99 | + return cliutil.HandleResponseOutput(cmd, upsertResp) |
| 100 | + }, |
| 101 | + } |
| 102 | + |
| 103 | + cmd.Flags().StringVarP(&providerName, "provider", "p", "", "Resource provider name") |
| 104 | + cmd.MarkFlagRequired("provider") |
| 105 | + |
| 106 | + return cmd |
| 107 | +} |
| 108 | + |
| 109 | +// parseResources attempts to parse the raw JSON data as either an array of |
| 110 | +// resources or a single resource object. A single object is normalized to a |
| 111 | +// one-element array. |
| 112 | +func parseResources(data []byte) ([]api.ResourceProviderResource, error) { |
| 113 | + // Try array first |
| 114 | + var resources []api.ResourceProviderResource |
| 115 | + if err := json.Unmarshal(data, &resources); err == nil { |
| 116 | + return resources, nil |
| 117 | + } |
| 118 | + |
| 119 | + // Try single object |
| 120 | + var single api.ResourceProviderResource |
| 121 | + if err := json.Unmarshal(data, &single); err == nil { |
| 122 | + return []api.ResourceProviderResource{single}, nil |
| 123 | + } |
| 124 | + |
| 125 | + // Show a snippet of the input for debugging |
| 126 | + snippet := string(data) |
| 127 | + if len(snippet) > 200 { |
| 128 | + snippet = snippet[:200] + "..." |
| 129 | + } |
| 130 | + return nil, fmt.Errorf("invalid JSON input: %s", snippet) |
| 131 | +} |
| 132 | + |
| 133 | +// validateResources checks that each resource has the required fields: |
| 134 | +// Name, Identifier, Version, Kind. |
| 135 | +func validateResources(resources []api.ResourceProviderResource) error { |
| 136 | + var errs []string |
| 137 | + for i, r := range resources { |
| 138 | + var missing []string |
| 139 | + if r.Name == "" { |
| 140 | + missing = append(missing, "name") |
| 141 | + } |
| 142 | + if r.Identifier == "" { |
| 143 | + missing = append(missing, "identifier") |
| 144 | + } |
| 145 | + if r.Version == "" { |
| 146 | + missing = append(missing, "version") |
| 147 | + } |
| 148 | + if r.Kind == "" { |
| 149 | + missing = append(missing, "kind") |
| 150 | + } |
| 151 | + if len(missing) > 0 { |
| 152 | + errs = append(errs, fmt.Sprintf("resource[%d]: missing required field(s) '%s'", i, strings.Join(missing, "', '"))) |
| 153 | + } |
| 154 | + } |
| 155 | + if len(errs) > 0 { |
| 156 | + return fmt.Errorf("validation failed:\n %s", strings.Join(errs, "\n ")) |
| 157 | + } |
| 158 | + return nil |
| 159 | +} |
0 commit comments