2
0

run.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. 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. color.New(color.FgYellow).Println("Attempting connection to the container, this may take up to 10 seconds. If you don't see a command prompt, try pressing enter.")
  231. for i := 0; i < 5; i++ {
  232. err = t.Safe(fn)
  233. if err == nil {
  234. break
  235. }
  236. time.Sleep(2 * time.Second)
  237. // ugly way to catch non-TTY errors, such as when running command "echo \"hello\""
  238. if i == 4 && err != nil && strings.Contains(err.Error(), "not found in pod") {
  239. fmt.Printf("Could not open a shell to this container. Container logs:\n")
  240. err = pipePodLogsToStdout(config, namespace, podName, container, false)
  241. }
  242. }
  243. // delete the ephemeral pod
  244. deletePod(config, podName, namespace)
  245. return err
  246. }
  247. func pipePodLogsToStdout(config *rest.Config, namespace, name, container string, follow bool) error {
  248. podLogOpts := v1.PodLogOptions{
  249. Container: container,
  250. Follow: follow,
  251. }
  252. // creates the clientset
  253. clientset, err := kubernetes.NewForConfig(config)
  254. if err != nil {
  255. return err
  256. }
  257. req := clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  258. podLogs, err := req.Stream(
  259. context.Background(),
  260. )
  261. if err != nil {
  262. return err
  263. }
  264. defer podLogs.Close()
  265. _, err = io.Copy(os.Stdout, podLogs)
  266. if err != nil {
  267. return err
  268. }
  269. return nil
  270. }
  271. func getExistingPod(config *rest.Config, name, namespace string) (*v1.Pod, error) {
  272. clientset, err := kubernetes.NewForConfig(config)
  273. if err != nil {
  274. return nil, err
  275. }
  276. return clientset.CoreV1().Pods(namespace).Get(
  277. context.Background(),
  278. name,
  279. metav1.GetOptions{},
  280. )
  281. }
  282. func deletePod(config *rest.Config, name, namespace string) error {
  283. clientset, err := kubernetes.NewForConfig(config)
  284. if err != nil {
  285. return err
  286. }
  287. return clientset.CoreV1().Pods(namespace).Delete(
  288. context.Background(),
  289. name,
  290. metav1.DeleteOptions{},
  291. )
  292. }
  293. func createPodFromExisting(config *rest.Config, existing *v1.Pod, args []string) (*v1.Pod, error) {
  294. clientset, err := kubernetes.NewForConfig(config)
  295. if err != nil {
  296. return nil, err
  297. }
  298. newPod := existing.DeepCopy()
  299. // only copy the pod spec, overwrite metadata
  300. newPod.ObjectMeta = metav1.ObjectMeta{
  301. Name: strings.ToLower(fmt.Sprintf("%s-copy-%s", existing.ObjectMeta.Name, utils.String(4))),
  302. Namespace: existing.ObjectMeta.Namespace,
  303. }
  304. newPod.Status = v1.PodStatus{}
  305. // set restart policy to never
  306. newPod.Spec.RestartPolicy = v1.RestartPolicyNever
  307. // change the command in the pod to the passed in pod command
  308. cmdRoot := args[0]
  309. cmdArgs := make([]string, 0)
  310. if len(args) > 1 {
  311. cmdArgs = args[1:]
  312. }
  313. newPod.Spec.Containers[0].Command = []string{cmdRoot}
  314. newPod.Spec.Containers[0].Args = cmdArgs
  315. newPod.Spec.Containers[0].TTY = true
  316. newPod.Spec.Containers[0].Stdin = true
  317. newPod.Spec.Containers[0].StdinOnce = true
  318. // create the pod and return it
  319. return clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
  320. context.Background(),
  321. newPod,
  322. metav1.CreateOptions{},
  323. )
  324. }