github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/command/exec/exec.go (about)

     1  package exec
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/henvic/wedeploycli/cmdflagsfromhost"
     8  	"github.com/henvic/wedeploycli/verbose"
     9  
    10  	"github.com/henvic/wedeploycli/command/internal/we"
    11  	"github.com/henvic/wedeploycli/isterm"
    12  	"github.com/henvic/wedeploycli/services"
    13  	"github.com/henvic/wedeploycli/shell"
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  var setupHost = cmdflagsfromhost.SetupHost{
    18  	Pattern: cmdflagsfromhost.FullHostPattern | cmdflagsfromhost.InstancePattern,
    19  
    20  	Requires: cmdflagsfromhost.Requires{
    21  		Project:  true,
    22  		Service:  true,
    23  		Instance: true,
    24  	},
    25  
    26  	AutoSelectSingleInstance: true,
    27  
    28  	PromptMissingService:  true,
    29  	PromptMissingInstance: true,
    30  }
    31  
    32  // ExecCmd executes a process (command) remotely
    33  var ExecCmd = &cobra.Command{
    34  	Use:   "exec",
    35  	Short: "Execute command remotely",
    36  	Example: `  lcp exec -p demo -s web -- ls
    37    lcp exec -p demo -s web --instance any -- uname -a (run command on any instance)
    38    lcp exec -p demo -s web --instance ab123 -- backup-db`,
    39  	PreRunE: execPreRun,
    40  	RunE:    execRun,
    41  	Args:    cobra.MinimumNArgs(1),
    42  	Hidden:  true,
    43  }
    44  
    45  func init() {
    46  	setupHost.Init(ExecCmd)
    47  }
    48  
    49  func execPreRun(cmd *cobra.Command, args []string) error {
    50  	if err := setupHost.Process(context.Background(), we.Context()); err != nil {
    51  		return err
    52  	}
    53  
    54  	servicesClient := services.New(we.Context())
    55  
    56  	_, err := servicesClient.Get(context.Background(), setupHost.Project(), setupHost.Service())
    57  	return err
    58  }
    59  
    60  func execRun(cmd *cobra.Command, args []string) error {
    61  	var childArgs []string
    62  
    63  	if len(args) > 1 {
    64  		childArgs = args[1:]
    65  	}
    66  
    67  	var wectx = we.Context()
    68  	var host = wectx.Infrastructure()
    69  
    70  	host = strings.Replace(host, "http://", "", 1)
    71  	host = strings.Replace(host, "https://", "", 1)
    72  
    73  	var params = shell.Params{
    74  		Host:  host,
    75  		Token: wectx.Token(),
    76  
    77  		ProjectID: setupHost.Project(),
    78  		ServiceID: setupHost.Service(),
    79  		Instance:  setupHost.Instance(),
    80  
    81  		AttachStdin: true,
    82  		TTY:         isterm.Stdin(),
    83  	}
    84  
    85  	switch params.TTY {
    86  	case true:
    87  		verbose.Debug("Attaching tty")
    88  	default:
    89  		verbose.Debug("Not attaching tty")
    90  	}
    91  
    92  	return shell.Run(context.Background(), params, args[0], childArgs...)
    93  }