|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/spf13/cobra" |
| 11 | + "github.com/stackrox/roxie/internal/env" |
| 12 | + "github.com/stackrox/roxie/internal/logger" |
| 13 | + "github.com/stackrox/roxie/internal/manifest" |
| 14 | +) |
| 15 | + |
| 16 | +func newShellCmd() *cobra.Command { |
| 17 | + cmd := &cobra.Command{ |
| 18 | + Use: "shell [-- command [args...]]", |
| 19 | + Short: "Open a subshell for an existing ACS Central deployment", |
| 20 | + Long: `Open an interactive subshell with ACS environment variables |
| 21 | +set for an existing ACS Central deployment. |
| 22 | +
|
| 23 | +This command reads the roxie manifest secret from the cluster, |
| 24 | +re-fetches the CA certificate, and spawns an interactive subshell |
| 25 | +with the environment variables set. |
| 26 | +
|
| 27 | +If a command is given after "--", it is executed in the modified environment |
| 28 | +instead of spawning a subshell. |
| 29 | +
|
| 30 | +Examples: |
| 31 | + roxie shel |
| 32 | + roxie shell -- roxctl central whoami |
| 33 | + roxie shell -- bash -c 'echo $ROX_ENDPOINT'`, |
| 34 | + RunE: runShell, |
| 35 | + DisableFlagParsing: false, |
| 36 | + } |
| 37 | + |
| 38 | + cmd.Flags().StringVar(&shell, "shell", "", "Shell to spawn") |
| 39 | + |
| 40 | + return cmd |
| 41 | +} |
| 42 | + |
| 43 | +func runShell(cmd *cobra.Command, args []string) error { |
| 44 | + log := logger.New() |
| 45 | + if err := env.Initialize(log); err != nil { |
| 46 | + return err |
| 47 | + } |
| 48 | + |
| 49 | + if os.Getenv("ROXIE_SHELL") != "" { |
| 50 | + return errors.New("already in a roxie sub-shell (ROXIE_SHELL environment variable is set), please exit the shell and try again") |
| 51 | + } |
| 52 | + |
| 53 | + log.Info("Loading manifest from cluster...") |
| 54 | + |
| 55 | + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) |
| 56 | + defer cancel() |
| 57 | + |
| 58 | + m, err := manifest.LoadManifestSecret(ctx, log) |
| 59 | + if err != nil { |
| 60 | + return fmt.Errorf("failed to load roxie manifest: %w", err) |
| 61 | + } |
| 62 | + log.Dim("roxie manifest loaded") |
| 63 | + |
| 64 | + // We need this for the setup of the CA cert. |
| 65 | + tempDir, err := os.MkdirTemp("", "roxie-shell-*") |
| 66 | + if err != nil { |
| 67 | + return fmt.Errorf("failed to create temp dir: %w", err) |
| 68 | + } |
| 69 | + defer os.RemoveAll(tempDir) |
| 70 | + |
| 71 | + centralDeploymentInfo, err := manifest.ManifestToCentralDeploymentInfo(ctx, log, tempDir, m) |
| 72 | + if err != nil { |
| 73 | + return fmt.Errorf("extracting central deployment info from manifest: %w", err) |
| 74 | + } |
| 75 | + |
| 76 | + return runCommandOrSubshell(centralDeploymentInfo, log, args) |
| 77 | +} |
0 commit comments