run.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "strings"
  7. "github.com/fatih/color"
  8. "github.com/porter-dev/porter/cli/cmd/api"
  9. "github.com/porter-dev/porter/cli/cmd/utils"
  10. "github.com/spf13/cobra"
  11. "k8s.io/apimachinery/pkg/runtime"
  12. "k8s.io/apimachinery/pkg/runtime/schema"
  13. "k8s.io/client-go/rest"
  14. "k8s.io/client-go/tools/clientcmd"
  15. "k8s.io/client-go/tools/remotecommand"
  16. "k8s.io/kubectl/pkg/util/term"
  17. )
  18. var namespace string
  19. // runCmd represents the "porter run" base command when called
  20. // without any subcommands
  21. var runCmd = &cobra.Command{
  22. Use: "run [release] -- COMMAND [args...]",
  23. Args: cobra.MinimumNArgs(2),
  24. Short: "Runs a command inside a connected cluster container.",
  25. Run: func(cmd *cobra.Command, args []string) {
  26. err := checkLoginAndRun(args, run)
  27. if err != nil {
  28. os.Exit(1)
  29. }
  30. },
  31. }
  32. func init() {
  33. rootCmd.AddCommand(runCmd)
  34. runCmd.PersistentFlags().StringVar(
  35. &namespace,
  36. "namespace",
  37. "default",
  38. "namespace of release to connect to",
  39. )
  40. }
  41. func run(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
  42. color.New(color.FgGreen).Println("Running", strings.Join(args[1:], " "), "for release", args[0])
  43. podNames, err := getPods(client, namespace, args[0])
  44. if err != nil {
  45. return fmt.Errorf("Could not retrieve list of pods: %s", err.Error())
  46. }
  47. // if length of pods is 0, throw error
  48. pod := ""
  49. if len(podNames) == 0 {
  50. return fmt.Errorf("At least one pod must exist in this deployment.")
  51. } else if len(podNames) == 1 {
  52. pod = podNames[0]
  53. } else {
  54. pod, err = utils.PromptSelect("Select the pod:", podNames)
  55. if err != nil {
  56. return err
  57. }
  58. }
  59. restConf, err := getRESTConfig(client)
  60. if err != nil {
  61. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  62. }
  63. return executeRun(restConf, namespace, pod, args[1:])
  64. }
  65. func getRESTConfig(client *api.Client) (*rest.Config, error) {
  66. pID := config.Project
  67. cID := config.Cluster
  68. kubeResp, err := client.GetKubeconfig(context.TODO(), pID, cID)
  69. if err != nil {
  70. return nil, err
  71. }
  72. kubeBytes := kubeResp.Kubeconfig
  73. cmdConf, err := clientcmd.NewClientConfigFromBytes(kubeBytes)
  74. if err != nil {
  75. return nil, err
  76. }
  77. restConf, err := cmdConf.ClientConfig()
  78. if err != nil {
  79. return nil, err
  80. }
  81. restConf.GroupVersion = &schema.GroupVersion{
  82. Group: "api",
  83. Version: "v1",
  84. }
  85. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  86. return restConf, nil
  87. }
  88. func getPods(client *api.Client, namespace, releaseName string) ([]string, error) {
  89. pID := config.Project
  90. cID := config.Cluster
  91. resp, err := client.GetK8sAllPods(context.TODO(), pID, cID, namespace, releaseName)
  92. if err != nil {
  93. return nil, err
  94. }
  95. res := make([]string, 0)
  96. for _, pod := range resp {
  97. res = append(res, pod.ObjectMeta.Name)
  98. }
  99. return res, nil
  100. }
  101. func executeRun(config *rest.Config, namespace, name string, args []string) error {
  102. restClient, err := rest.RESTClientFor(config)
  103. if err != nil {
  104. return err
  105. }
  106. req := restClient.Post().
  107. Resource("pods").
  108. Name(name).
  109. Namespace(namespace).
  110. SubResource("exec")
  111. // req.Param("container", "web")
  112. for _, arg := range args {
  113. req.Param("command", arg)
  114. }
  115. req.Param("stdin", "true")
  116. req.Param("stdout", "true")
  117. req.Param("tty", "true")
  118. t := term.TTY{
  119. In: os.Stdin,
  120. Out: os.Stdout,
  121. Raw: true,
  122. }
  123. fn := func() error {
  124. exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
  125. if err != nil {
  126. return err
  127. }
  128. return exec.Stream(remotecommand.StreamOptions{
  129. Stdin: os.Stdin,
  130. Stdout: os.Stdout,
  131. Stderr: os.Stderr,
  132. Tty: true,
  133. })
  134. }
  135. if err := t.Safe(fn); err != nil {
  136. return err
  137. }
  138. return err
  139. }