run.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "strings"
  7. "time"
  8. "github.com/fatih/color"
  9. "github.com/porter-dev/porter/cli/cmd/api"
  10. "github.com/porter-dev/porter/cli/cmd/utils"
  11. "github.com/spf13/cobra"
  12. v1 "k8s.io/api/core/v1"
  13. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  14. "k8s.io/kubectl/pkg/util/term"
  15. "k8s.io/apimachinery/pkg/runtime"
  16. "k8s.io/apimachinery/pkg/runtime/schema"
  17. "k8s.io/client-go/kubernetes"
  18. "k8s.io/client-go/rest"
  19. "k8s.io/client-go/tools/clientcmd"
  20. "k8s.io/client-go/tools/remotecommand"
  21. )
  22. var namespace string
  23. // runCmd represents the "porter run" base command when called
  24. // without any subcommands
  25. var runCmd = &cobra.Command{
  26. Use: "run [release] -- COMMAND [args...]",
  27. Args: cobra.MinimumNArgs(2),
  28. Short: "Runs a command inside a connected cluster container.",
  29. Run: func(cmd *cobra.Command, args []string) {
  30. err := checkLoginAndRun(args, run)
  31. if err != nil {
  32. os.Exit(1)
  33. }
  34. },
  35. }
  36. var existingPod bool
  37. func init() {
  38. rootCmd.AddCommand(runCmd)
  39. runCmd.PersistentFlags().StringVar(
  40. &namespace,
  41. "namespace",
  42. "default",
  43. "namespace of release to connect to",
  44. )
  45. runCmd.PersistentFlags().BoolVarP(
  46. &existingPod,
  47. "existing_pod",
  48. "e",
  49. false,
  50. "whether to connect to an existing pod",
  51. )
  52. }
  53. func run(_ *api.AuthCheckResponse, client *api.Client, args []string) error {
  54. color.New(color.FgGreen).Println("Running", strings.Join(args[1:], " "), "for release", args[0])
  55. color.New(color.FgGreen).Println("If you don't see a command prompt, try pressing enter.")
  56. podsSimple, err := getPods(client, namespace, args[0])
  57. if err != nil {
  58. return fmt.Errorf("Could not retrieve list of pods: %s", err.Error())
  59. }
  60. // if length of pods is 0, throw error
  61. var selectedPod podSimple
  62. if len(podsSimple) == 0 {
  63. return fmt.Errorf("At least one pod must exist in this deployment.")
  64. } else if len(podsSimple) == 1 {
  65. selectedPod = podsSimple[0]
  66. } else {
  67. podNames := make([]string, 0)
  68. for _, podSimple := range podsSimple {
  69. podNames = append(podNames, podSimple.Name)
  70. }
  71. selectedPodName, err := utils.PromptSelect("Select the pod:", podNames)
  72. if err != nil {
  73. return err
  74. }
  75. // find selected pod
  76. for _, podSimple := range podsSimple {
  77. if selectedPodName == podSimple.Name {
  78. selectedPod = podSimple
  79. }
  80. }
  81. }
  82. var selectedContainerName string
  83. // if the selected pod has multiple container, spawn selector
  84. if len(selectedPod.ContainerNames) == 0 {
  85. return fmt.Errorf("At least one pod must exist in this deployment.")
  86. } else if len(selectedPod.ContainerNames) == 1 {
  87. selectedContainerName = selectedPod.ContainerNames[0]
  88. } else {
  89. selectedContainer, err := utils.PromptSelect("Select the container:", selectedPod.ContainerNames)
  90. if err != nil {
  91. return err
  92. }
  93. selectedContainerName = selectedContainer
  94. }
  95. restConf, err := getRESTConfig(client)
  96. if err != nil {
  97. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  98. }
  99. if existingPod {
  100. return executeRun(restConf, namespace, selectedPod.Name, selectedContainerName, args[1:])
  101. }
  102. return executeRunEphemeral(restConf, namespace, selectedPod.Name, selectedContainerName, args[1:])
  103. }
  104. func getRESTConfig(client *api.Client) (*rest.Config, error) {
  105. pID := config.Project
  106. cID := config.Cluster
  107. kubeResp, err := client.GetKubeconfig(context.TODO(), pID, cID)
  108. if err != nil {
  109. return nil, err
  110. }
  111. kubeBytes := kubeResp.Kubeconfig
  112. cmdConf, err := clientcmd.NewClientConfigFromBytes(kubeBytes)
  113. if err != nil {
  114. return nil, err
  115. }
  116. restConf, err := cmdConf.ClientConfig()
  117. if err != nil {
  118. return nil, err
  119. }
  120. restConf.GroupVersion = &schema.GroupVersion{
  121. Group: "api",
  122. Version: "v1",
  123. }
  124. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  125. return restConf, nil
  126. }
  127. type podSimple struct {
  128. Name string
  129. ContainerNames []string
  130. }
  131. func getPods(client *api.Client, namespace, releaseName string) ([]podSimple, error) {
  132. pID := config.Project
  133. cID := config.Cluster
  134. resp, err := client.GetK8sAllPods(context.TODO(), pID, cID, namespace, releaseName)
  135. if err != nil {
  136. return nil, err
  137. }
  138. res := make([]podSimple, 0)
  139. for _, pod := range resp {
  140. containerNames := make([]string, 0)
  141. for _, container := range pod.Spec.Containers {
  142. containerNames = append(containerNames, container.Name)
  143. }
  144. res = append(res, podSimple{
  145. Name: pod.ObjectMeta.Name,
  146. ContainerNames: containerNames,
  147. })
  148. }
  149. return res, nil
  150. }
  151. func executeRun(config *rest.Config, namespace, name, container string, args []string) error {
  152. restClient, err := rest.RESTClientFor(config)
  153. if err != nil {
  154. return err
  155. }
  156. req := restClient.Post().
  157. Resource("pods").
  158. Name(name).
  159. Namespace(namespace).
  160. SubResource("exec")
  161. for _, arg := range args {
  162. req.Param("command", arg)
  163. }
  164. req.Param("stdin", "true")
  165. req.Param("stdout", "true")
  166. req.Param("tty", "true")
  167. req.Param("container", container)
  168. t := term.TTY{
  169. In: os.Stdin,
  170. Out: os.Stdout,
  171. Raw: true,
  172. }
  173. fn := func() error {
  174. exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
  175. if err != nil {
  176. return err
  177. }
  178. return exec.Stream(remotecommand.StreamOptions{
  179. Stdin: os.Stdin,
  180. Stdout: os.Stdout,
  181. Stderr: os.Stderr,
  182. Tty: true,
  183. })
  184. }
  185. if err := t.Safe(fn); err != nil {
  186. return err
  187. }
  188. return err
  189. }
  190. func executeRunEphemeral(config *rest.Config, namespace, name, container string, args []string) error {
  191. existing, err := getExistingPod(config, name, namespace)
  192. if err != nil {
  193. return err
  194. }
  195. newPod, err := createPodFromExisting(config, existing, args)
  196. if err != nil {
  197. return err
  198. }
  199. podName := newPod.ObjectMeta.Name
  200. t := term.TTY{
  201. In: os.Stdin,
  202. Out: os.Stdout,
  203. Raw: true,
  204. }
  205. fn := func() error {
  206. restClient, err := rest.RESTClientFor(config)
  207. if err != nil {
  208. return err
  209. }
  210. req := restClient.Post().
  211. Resource("pods").
  212. Name(podName).
  213. Namespace("default").
  214. SubResource("attach")
  215. req.Param("stdin", "true")
  216. req.Param("stdout", "true")
  217. req.Param("tty", "true")
  218. req.Param("container", container)
  219. exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
  220. if err != nil {
  221. return err
  222. }
  223. return exec.Stream(remotecommand.StreamOptions{
  224. Stdin: os.Stdin,
  225. Stdout: os.Stdout,
  226. Stderr: os.Stderr,
  227. Tty: true,
  228. })
  229. }
  230. for i := 0; i < 5; i++ {
  231. fmt.Printf("attempting connection %d/5\n", i)
  232. err = t.Safe(fn)
  233. if err == nil {
  234. break
  235. }
  236. time.Sleep(2 * time.Second)
  237. }
  238. // delete the ephemeral pod
  239. deletePod(config, podName, namespace)
  240. return err
  241. }
  242. func getExistingPod(config *rest.Config, name, namespace string) (*v1.Pod, error) {
  243. clientset, err := kubernetes.NewForConfig(config)
  244. if err != nil {
  245. return nil, err
  246. }
  247. return clientset.CoreV1().Pods(namespace).Get(
  248. context.Background(),
  249. name,
  250. metav1.GetOptions{},
  251. )
  252. }
  253. func deletePod(config *rest.Config, name, namespace string) error {
  254. clientset, err := kubernetes.NewForConfig(config)
  255. if err != nil {
  256. return err
  257. }
  258. return clientset.CoreV1().Pods(namespace).Delete(
  259. context.Background(),
  260. name,
  261. metav1.DeleteOptions{},
  262. )
  263. }
  264. func createPodFromExisting(config *rest.Config, existing *v1.Pod, args []string) (*v1.Pod, error) {
  265. clientset, err := kubernetes.NewForConfig(config)
  266. if err != nil {
  267. return nil, err
  268. }
  269. newPod := existing.DeepCopy()
  270. // only copy the pod spec, overwrite metadata
  271. newPod.ObjectMeta = metav1.ObjectMeta{
  272. Name: strings.ToLower(fmt.Sprintf("%s-copy-%s", existing.ObjectMeta.Name, utils.String(4))),
  273. Namespace: existing.ObjectMeta.Namespace,
  274. }
  275. newPod.Status = v1.PodStatus{}
  276. // set restart policy to never
  277. newPod.Spec.RestartPolicy = v1.RestartPolicyNever
  278. // change the command in the pod to the passed in pod command
  279. cmdRoot := args[0]
  280. cmdArgs := make([]string, 0)
  281. if len(args) > 1 {
  282. cmdArgs = args[1:]
  283. }
  284. newPod.Spec.Containers[0].Command = []string{cmdRoot}
  285. newPod.Spec.Containers[0].Args = cmdArgs
  286. newPod.Spec.Containers[0].TTY = true
  287. newPod.Spec.Containers[0].Stdin = true
  288. newPod.Spec.Containers[0].StdinOnce = true
  289. // create the pod and return it
  290. return clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
  291. context.Background(),
  292. newPod,
  293. metav1.CreateOptions{},
  294. )
  295. }