run.go 4.8 KB

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