run.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. &host,
  36. "host",
  37. getHost(),
  38. "host url of Porter instance",
  39. )
  40. runCmd.PersistentFlags().StringVar(
  41. &namespace,
  42. "namespace",
  43. "default",
  44. "namespace of release to connect to",
  45. )
  46. }
  47. func run(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
  48. color.New(color.FgGreen).Println("Running", strings.Join(args[1:], " "), "for release", args[0])
  49. podsSimple, err := getPods(client, namespace, args[0])
  50. if err != nil {
  51. return fmt.Errorf("Could not retrieve list of pods: %s", err.Error())
  52. }
  53. // if length of pods is 0, throw error
  54. var selectedPod podSimple
  55. if len(podsSimple) == 0 {
  56. return fmt.Errorf("At least one pod must exist in this deployment.")
  57. } else if len(podsSimple) == 1 {
  58. selectedPod = podsSimple[0]
  59. } else {
  60. podNames := make([]string, 0)
  61. for _, podSimple := range podsSimple {
  62. podNames = append(podNames, podSimple.Name)
  63. }
  64. selectedPodName, err := utils.PromptSelect("Select the pod:", podNames)
  65. if err != nil {
  66. return err
  67. }
  68. // find selected pod
  69. for _, podSimple := range podsSimple {
  70. if selectedPodName == podSimple.Name {
  71. selectedPod = podSimple
  72. }
  73. }
  74. }
  75. var selectedContainerName string
  76. // if the selected pod has multiple container, spawn selector
  77. if len(selectedPod.ContainerNames) == 0 {
  78. return fmt.Errorf("At least one pod must exist in this deployment.")
  79. } else if len(selectedPod.ContainerNames) == 1 {
  80. selectedContainerName = selectedPod.ContainerNames[0]
  81. } else {
  82. selectedContainer, err := utils.PromptSelect("Select the container:", selectedPod.ContainerNames)
  83. if err != nil {
  84. return err
  85. }
  86. selectedContainerName = selectedContainer
  87. }
  88. restConf, err := getRESTConfig(client)
  89. if err != nil {
  90. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  91. }
  92. return executeRun(restConf, namespace, selectedPod.Name, selectedContainerName, args[1:])
  93. }
  94. func getRESTConfig(client *api.Client) (*rest.Config, error) {
  95. pID := getProjectID()
  96. cID := getClusterID()
  97. kubeResp, err := client.GetKubeconfig(context.TODO(), pID, cID)
  98. if err != nil {
  99. return nil, err
  100. }
  101. kubeBytes := kubeResp.Kubeconfig
  102. cmdConf, err := clientcmd.NewClientConfigFromBytes(kubeBytes)
  103. if err != nil {
  104. return nil, err
  105. }
  106. restConf, err := cmdConf.ClientConfig()
  107. if err != nil {
  108. return nil, err
  109. }
  110. restConf.GroupVersion = &schema.GroupVersion{
  111. Group: "api",
  112. Version: "v1",
  113. }
  114. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  115. return restConf, nil
  116. }
  117. type podSimple struct {
  118. Name string
  119. ContainerNames []string
  120. }
  121. func getPods(client *api.Client, namespace, releaseName string) ([]podSimple, error) {
  122. pID := getProjectID()
  123. cID := getClusterID()
  124. resp, err := client.GetK8sAllPods(context.TODO(), pID, cID, namespace, releaseName)
  125. if err != nil {
  126. return nil, err
  127. }
  128. res := make([]podSimple, 0)
  129. for _, pod := range resp {
  130. containerNames := make([]string, 0)
  131. for _, container := range pod.Spec.Containers {
  132. containerNames = append(containerNames, container.Name)
  133. }
  134. res = append(res, podSimple{
  135. Name: pod.ObjectMeta.Name,
  136. ContainerNames: containerNames,
  137. })
  138. }
  139. return res, nil
  140. }
  141. func executeRun(config *rest.Config, namespace, name, container string, args []string) error {
  142. restClient, err := rest.RESTClientFor(config)
  143. if err != nil {
  144. return err
  145. }
  146. req := restClient.Post().
  147. Resource("pods").
  148. Name(name).
  149. Namespace(namespace).
  150. SubResource("exec")
  151. // req.Param("container", "web")
  152. for _, arg := range args {
  153. req.Param("command", arg)
  154. }
  155. req.Param("stdin", "true")
  156. req.Param("stdout", "true")
  157. req.Param("tty", "true")
  158. req.Param("container", container)
  159. t := term.TTY{
  160. In: os.Stdin,
  161. Out: os.Stdout,
  162. Raw: true,
  163. }
  164. fn := func() error {
  165. exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
  166. if err != nil {
  167. return err
  168. }
  169. return exec.Stream(remotecommand.StreamOptions{
  170. Stdin: os.Stdin,
  171. Stdout: os.Stdout,
  172. Stderr: os.Stderr,
  173. Tty: true,
  174. })
  175. }
  176. if err := t.Safe(fn); err != nil {
  177. return err
  178. }
  179. return err
  180. }