github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/cmd/orbctl/exec.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/caos/orbos/mntr"
     8  
     9  	"github.com/caos/orbos/pkg/tree"
    10  
    11  	"github.com/AlecAivazis/survey/v2"
    12  	"github.com/caos/orbos/internal/operator/orbiter/kinds/clusters/core/infra"
    13  
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  func ExecCommand(getRv GetRootValues) *cobra.Command {
    18  	var (
    19  		command string
    20  		cmd     = &cobra.Command{
    21  			Use:   "exec",
    22  			Short: "Exec shell command on machine",
    23  			Long:  "Exec shell command on machine",
    24  			Args:  cobra.MaximumNArgs(1),
    25  		}
    26  	)
    27  
    28  	flags := cmd.Flags()
    29  	flags.StringVar(&command, "command", "", "Command to be executed")
    30  
    31  	cmd.RunE = func(cmd *cobra.Command, args []string) (err error) {
    32  
    33  		machineID := ""
    34  		if len(args) > 0 {
    35  			machineID = args[0]
    36  		}
    37  
    38  		rv := getRv("exec", "", map[string]interface{}{"machine": machineID, "command": command != ""})
    39  		defer rv.ErrFunc(err)
    40  
    41  		if !rv.Gitops {
    42  			return mntr.ToUserError(errors.New("exec command is only supported with the --gitops flag and a committed orbiter.yml"))
    43  		}
    44  
    45  		return machines(monitor, rv.GitClient, rv.OrbConfig, func(machineIDs []string, machines map[string]infra.Machine, _ *tree.Tree) error {
    46  
    47  			if machineID == "" {
    48  				if err := survey.AskOne(&survey.Select{
    49  					Message: "Select a machine:",
    50  					Options: machineIDs,
    51  				}, &machineID, survey.WithValidator(survey.Required)); err != nil {
    52  					return err
    53  				}
    54  			}
    55  
    56  			machine, found := machines[machineID]
    57  			if !found {
    58  				return mntr.ToUserError(errors.New(fmt.Sprintf("Machine with ID %s unknown", machineID)))
    59  			}
    60  
    61  			if command != "" {
    62  				output, err := machine.Execute(nil, command)
    63  				if err != nil {
    64  					return mntr.ToUserError(err)
    65  				}
    66  				fmt.Print(string(output))
    67  			} else {
    68  				if err := machine.Shell(); err != nil {
    69  					return err
    70  				}
    71  			}
    72  			return nil
    73  		})
    74  	}
    75  	return cmd
    76  }