run.go 9.0 KB

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