run.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. package cmd
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/fatih/color"
  11. api "github.com/porter-dev/porter/api/client"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/cli/cmd/utils"
  14. "github.com/spf13/cobra"
  15. batchv1 "k8s.io/api/batch/v1"
  16. batchv1beta1 "k8s.io/api/batch/v1beta1"
  17. v1 "k8s.io/api/core/v1"
  18. rbacv1 "k8s.io/api/rbac/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/fields"
  21. "k8s.io/apimachinery/pkg/watch"
  22. "k8s.io/kubectl/pkg/util/term"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/runtime/schema"
  25. "k8s.io/client-go/kubernetes"
  26. "k8s.io/client-go/rest"
  27. "k8s.io/client-go/tools/clientcmd"
  28. "k8s.io/client-go/tools/remotecommand"
  29. )
  30. var namespace string
  31. var verbose bool
  32. var existingPod bool
  33. var nonInteractive bool
  34. var containerName string
  35. // runCmd represents the "porter run" base command when called
  36. // without any subcommands
  37. var runCmd = &cobra.Command{
  38. Use: "run [release] -- COMMAND [args...]",
  39. Args: cobra.MinimumNArgs(2),
  40. Short: "Runs a command inside a connected cluster container.",
  41. Run: func(cmd *cobra.Command, args []string) {
  42. err := checkLoginAndRun(args, run)
  43. if err != nil {
  44. os.Exit(1)
  45. }
  46. },
  47. }
  48. // cleanupCmd represents the "porter run cleanup" subcommand
  49. var cleanupCmd = &cobra.Command{
  50. Use: "cleanup",
  51. Args: cobra.NoArgs,
  52. Short: "Delete any lingering ephemeral pods that were created with \"porter run\".",
  53. Run: func(cmd *cobra.Command, args []string) {
  54. err := checkLoginAndRun(args, cleanup)
  55. if err != nil {
  56. os.Exit(1)
  57. }
  58. },
  59. }
  60. func init() {
  61. rootCmd.AddCommand(runCmd)
  62. runCmd.PersistentFlags().StringVar(
  63. &namespace,
  64. "namespace",
  65. "default",
  66. "namespace of release to connect to",
  67. )
  68. runCmd.PersistentFlags().BoolVarP(
  69. &existingPod,
  70. "existing_pod",
  71. "e",
  72. false,
  73. "whether to connect to an existing pod",
  74. )
  75. runCmd.PersistentFlags().BoolVarP(
  76. &verbose,
  77. "verbose",
  78. "v",
  79. false,
  80. "whether to print verbose output",
  81. )
  82. runCmd.PersistentFlags().BoolVar(
  83. &nonInteractive,
  84. "non-interactive",
  85. false,
  86. "whether to run in non-interactive mode",
  87. )
  88. runCmd.PersistentFlags().StringVarP(
  89. &containerName,
  90. "container",
  91. "c",
  92. "",
  93. "name of the container inside pod to run the command in",
  94. )
  95. runCmd.AddCommand(cleanupCmd)
  96. }
  97. func run(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  98. color.New(color.FgGreen).Println("Running", strings.Join(args[1:], " "), "for release", args[0])
  99. if nonInteractive {
  100. color.New(color.FgBlue).Println("Using non-interactive mode. The first available pod will be used to run the command.")
  101. }
  102. podsSimple, err := getPods(client, namespace, args[0])
  103. if err != nil {
  104. return fmt.Errorf("Could not retrieve list of pods: %s", err.Error())
  105. }
  106. // if length of pods is 0, throw error
  107. var selectedPod podSimple
  108. if len(podsSimple) == 0 {
  109. return fmt.Errorf("At least one pod must exist in this deployment.")
  110. } else if nonInteractive || len(podsSimple) == 1 || !existingPod {
  111. selectedPod = podsSimple[0]
  112. } else {
  113. podNames := make([]string, 0)
  114. for _, podSimple := range podsSimple {
  115. podNames = append(podNames, podSimple.Name)
  116. }
  117. selectedPodName, err := utils.PromptSelect("Select the pod:", podNames)
  118. if err != nil {
  119. return err
  120. }
  121. // find selected pod
  122. for _, podSimple := range podsSimple {
  123. if selectedPodName == podSimple.Name {
  124. selectedPod = podSimple
  125. }
  126. }
  127. }
  128. var selectedContainerName string
  129. if len(selectedPod.ContainerNames) == 0 {
  130. return fmt.Errorf("At least one container must exist in the selected pod.")
  131. } else if len(selectedPod.ContainerNames) == 1 {
  132. if containerName != "" && containerName != selectedPod.ContainerNames[0] {
  133. return fmt.Errorf("provided container %s does not exist in pod %s", containerName, selectedPod.Name)
  134. }
  135. selectedContainerName = selectedPod.ContainerNames[0]
  136. }
  137. if containerName != "" && selectedContainerName == "" {
  138. // check if provided container name exists in the pod
  139. for _, name := range selectedPod.ContainerNames {
  140. if name == containerName {
  141. selectedContainerName = name
  142. break
  143. }
  144. }
  145. if selectedContainerName == "" {
  146. return fmt.Errorf("provided container %s does not exist in pod %s", containerName, selectedPod.Name)
  147. }
  148. }
  149. if selectedContainerName == "" {
  150. if nonInteractive {
  151. return fmt.Errorf("container name must be specified using the --container flag when using non-interactive mode")
  152. }
  153. selectedContainer, err := utils.PromptSelect("Select the container:", selectedPod.ContainerNames)
  154. if err != nil {
  155. return err
  156. }
  157. selectedContainerName = selectedContainer
  158. }
  159. config := &PorterRunSharedConfig{
  160. Client: client,
  161. }
  162. err = config.setSharedConfig()
  163. if err != nil {
  164. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  165. }
  166. if existingPod {
  167. return executeRun(config, namespace, selectedPod.Name, selectedContainerName, args[1:])
  168. }
  169. return executeRunEphemeral(config, namespace, selectedPod.Name, selectedContainerName, args[1:])
  170. }
  171. func cleanup(_ *types.GetAuthenticatedUserResponse, client *api.Client, _ []string) error {
  172. config := &PorterRunSharedConfig{
  173. Client: client,
  174. }
  175. err := config.setSharedConfig()
  176. if err != nil {
  177. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  178. }
  179. proceed, err := utils.PromptSelect(
  180. fmt.Sprintf("You have chosen the '%s' namespace for cleanup. Do you want to proceed?", namespace),
  181. []string{"Yes", "No", "All namespaces"},
  182. )
  183. if err != nil {
  184. return err
  185. }
  186. if proceed == "No" {
  187. return nil
  188. }
  189. var podNames []string
  190. color.New(color.FgGreen).Println("Fetching ephemeral pods for cleanup")
  191. if proceed == "All namespaces" {
  192. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  193. if err != nil {
  194. return err
  195. }
  196. for _, namespace := range namespaces.Items {
  197. if pods, err := getEphemeralPods(namespace.Name, config.Clientset); err == nil {
  198. podNames = append(podNames, pods...)
  199. } else {
  200. return err
  201. }
  202. }
  203. } else {
  204. if pods, err := getEphemeralPods(namespace, config.Clientset); err == nil {
  205. podNames = append(podNames, pods...)
  206. } else {
  207. return err
  208. }
  209. }
  210. if len(podNames) == 0 {
  211. color.New(color.FgBlue).Println("No ephemeral pods to delete")
  212. return nil
  213. }
  214. selectedPods, err := utils.PromptMultiselect("Select ephemeral pods to delete", podNames)
  215. if err != nil {
  216. return err
  217. }
  218. for _, podName := range selectedPods {
  219. color.New(color.FgBlue).Printf("Deleting ephemeral pod: %s\n", podName)
  220. err = config.Clientset.CoreV1().Pods(namespace).Delete(
  221. context.Background(), podName, metav1.DeleteOptions{},
  222. )
  223. if err != nil {
  224. return err
  225. }
  226. }
  227. return nil
  228. }
  229. func getEphemeralPods(namespace string, clientset *kubernetes.Clientset) ([]string, error) {
  230. var podNames []string
  231. pods, err := clientset.CoreV1().Pods(namespace).List(
  232. context.Background(), metav1.ListOptions{LabelSelector: "porter/ephemeral-pod"},
  233. )
  234. if err != nil {
  235. return nil, err
  236. }
  237. for _, pod := range pods.Items {
  238. podNames = append(podNames, pod.Name)
  239. }
  240. return podNames, nil
  241. }
  242. type PorterRunSharedConfig struct {
  243. Client *api.Client
  244. RestConf *rest.Config
  245. Clientset *kubernetes.Clientset
  246. RestClient *rest.RESTClient
  247. }
  248. func (p *PorterRunSharedConfig) setSharedConfig() error {
  249. pID := cliConf.Project
  250. cID := cliConf.Cluster
  251. kubeResp, err := p.Client.GetKubeconfig(context.Background(), pID, cID, cliConf.Kubeconfig)
  252. if err != nil {
  253. return err
  254. }
  255. kubeBytes := kubeResp.Kubeconfig
  256. cmdConf, err := clientcmd.NewClientConfigFromBytes(kubeBytes)
  257. if err != nil {
  258. return err
  259. }
  260. restConf, err := cmdConf.ClientConfig()
  261. if err != nil {
  262. return err
  263. }
  264. restConf.GroupVersion = &schema.GroupVersion{
  265. Group: "api",
  266. Version: "v1",
  267. }
  268. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  269. p.RestConf = restConf
  270. clientset, err := kubernetes.NewForConfig(restConf)
  271. if err != nil {
  272. return err
  273. }
  274. p.Clientset = clientset
  275. restClient, err := rest.RESTClientFor(restConf)
  276. if err != nil {
  277. return err
  278. }
  279. p.RestClient = restClient
  280. return nil
  281. }
  282. type podSimple struct {
  283. Name string
  284. ContainerNames []string
  285. }
  286. func getPods(client *api.Client, namespace, releaseName string) ([]podSimple, error) {
  287. pID := cliConf.Project
  288. cID := cliConf.Cluster
  289. resp, err := client.GetK8sAllPods(context.TODO(), pID, cID, namespace, releaseName)
  290. if err != nil {
  291. return nil, err
  292. }
  293. pods := *resp
  294. res := make([]podSimple, 0)
  295. for _, pod := range pods {
  296. if pod.Status.Phase == v1.PodRunning {
  297. containerNames := make([]string, 0)
  298. for _, container := range pod.Spec.Containers {
  299. containerNames = append(containerNames, container.Name)
  300. }
  301. res = append(res, podSimple{
  302. Name: pod.ObjectMeta.Name,
  303. ContainerNames: containerNames,
  304. })
  305. }
  306. }
  307. return res, nil
  308. }
  309. func executeRun(config *PorterRunSharedConfig, namespace, name, container string, args []string) error {
  310. req := config.RestClient.Post().
  311. Resource("pods").
  312. Name(name).
  313. Namespace(namespace).
  314. SubResource("exec")
  315. for _, arg := range args {
  316. req.Param("command", arg)
  317. }
  318. req.Param("stdin", "true")
  319. req.Param("stdout", "true")
  320. req.Param("tty", "true")
  321. req.Param("container", container)
  322. t := term.TTY{
  323. In: os.Stdin,
  324. Out: os.Stdout,
  325. Raw: true,
  326. }
  327. size := t.GetSize()
  328. sizeQueue := t.MonitorSize(size)
  329. return t.Safe(func() error {
  330. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  331. if err != nil {
  332. return err
  333. }
  334. return exec.Stream(remotecommand.StreamOptions{
  335. Stdin: os.Stdin,
  336. Stdout: os.Stdout,
  337. Stderr: os.Stderr,
  338. Tty: true,
  339. TerminalSizeQueue: sizeQueue,
  340. })
  341. })
  342. }
  343. func executeRunEphemeral(config *PorterRunSharedConfig, namespace, name, container string, args []string) error {
  344. existing, err := getExistingPod(config, name, namespace)
  345. if err != nil {
  346. return err
  347. }
  348. newPod, err := createEphemeralPodFromExisting(config, existing, args)
  349. if err != nil {
  350. return err
  351. }
  352. podName := newPod.ObjectMeta.Name
  353. // delete the ephemeral pod no matter what
  354. defer deletePod(config, podName, namespace)
  355. color.New(color.FgYellow).Printf("Waiting for pod %s to be ready...", podName)
  356. if err = waitForPod(config, newPod); err != nil {
  357. color.New(color.FgRed).Println("failed")
  358. return handlePodAttachError(err, config, namespace, podName, container)
  359. }
  360. err = checkForPodDeletionCronJob(config)
  361. if err != nil {
  362. return err
  363. }
  364. // refresh pod info for latest status
  365. newPod, err = config.Clientset.CoreV1().
  366. Pods(newPod.Namespace).
  367. Get(context.Background(), newPod.Name, metav1.GetOptions{})
  368. // pod exited while we were waiting. maybe an error maybe not.
  369. // we dont know if the user wanted an interactive shell or not.
  370. // if it was an error the logs hopefully say so.
  371. if isPodExited(newPod) {
  372. color.New(color.FgGreen).Println("complete!")
  373. var writtenBytes int64
  374. writtenBytes, _ = pipePodLogsToStdout(config, namespace, podName, container, false)
  375. if verbose || writtenBytes == 0 {
  376. color.New(color.FgYellow).Println("Could not get logs. Pod events:")
  377. pipeEventsToStdout(config, namespace, podName, container, false)
  378. }
  379. return nil
  380. }
  381. color.New(color.FgGreen).Println("ready!")
  382. color.New(color.FgYellow).Println("Attempting connection to the container. If you don't see a command prompt, try pressing enter.")
  383. req := config.RestClient.Post().
  384. Resource("pods").
  385. Name(podName).
  386. Namespace(namespace).
  387. SubResource("attach")
  388. req.Param("stdin", "true")
  389. req.Param("stdout", "true")
  390. req.Param("tty", "true")
  391. req.Param("container", container)
  392. t := term.TTY{
  393. In: os.Stdin,
  394. Out: os.Stdout,
  395. Raw: true,
  396. }
  397. size := t.GetSize()
  398. sizeQueue := t.MonitorSize(size)
  399. if err = t.Safe(func() error {
  400. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  401. if err != nil {
  402. return err
  403. }
  404. return exec.Stream(remotecommand.StreamOptions{
  405. Stdin: os.Stdin,
  406. Stdout: os.Stdout,
  407. Stderr: os.Stderr,
  408. Tty: true,
  409. TerminalSizeQueue: sizeQueue,
  410. })
  411. }); err != nil {
  412. // ugly way to catch no TTY errors, such as when running command "echo \"hello\""
  413. return handlePodAttachError(err, config, namespace, podName, container)
  414. }
  415. if verbose {
  416. color.New(color.FgYellow).Println("Pod events:")
  417. pipeEventsToStdout(config, namespace, podName, container, false)
  418. }
  419. return err
  420. }
  421. func checkForPodDeletionCronJob(config *PorterRunSharedConfig) error {
  422. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  423. if err != nil {
  424. return err
  425. }
  426. for _, namespace := range namespaces.Items {
  427. cronJobs, err := config.Clientset.BatchV1beta1().CronJobs(namespace.Name).List(
  428. context.Background(), metav1.ListOptions{},
  429. )
  430. if err != nil {
  431. return err
  432. }
  433. if namespace.Name != "default" {
  434. for _, cronJob := range cronJobs.Items {
  435. if cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  436. err = config.Clientset.BatchV1beta1().CronJobs(namespace.Name).Delete(
  437. context.Background(), cronJob.Name, metav1.DeleteOptions{},
  438. )
  439. if err != nil {
  440. return err
  441. }
  442. }
  443. }
  444. }
  445. for _, cronJob := range cronJobs.Items {
  446. if namespace.Name == "default" && cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  447. return nil
  448. }
  449. }
  450. }
  451. // try and create the cron job and all of the other required resources as necessary,
  452. // starting with the service account, then role and then a role binding
  453. err = checkForServiceAccount(config)
  454. if err != nil {
  455. return err
  456. }
  457. err = checkForClusterRole(config)
  458. if err != nil {
  459. return err
  460. }
  461. err = checkForRoleBinding(config)
  462. if err != nil {
  463. return err
  464. }
  465. // create the cronjob
  466. cronJob := &batchv1beta1.CronJob{
  467. ObjectMeta: metav1.ObjectMeta{
  468. Name: "porter-ephemeral-pod-deletion-cronjob",
  469. },
  470. Spec: batchv1beta1.CronJobSpec{
  471. Schedule: "0 * * * *",
  472. JobTemplate: batchv1beta1.JobTemplateSpec{
  473. Spec: batchv1.JobSpec{
  474. Template: v1.PodTemplateSpec{
  475. Spec: v1.PodSpec{
  476. ServiceAccountName: "porter-ephemeral-pod-deletion-service-account",
  477. RestartPolicy: v1.RestartPolicyNever,
  478. Containers: []v1.Container{
  479. {
  480. Name: "ephemeral-pods-manager",
  481. Image: "public.ecr.aws/o1j4x7p4/porter-ephemeral-pods-manager:latest",
  482. ImagePullPolicy: v1.PullAlways,
  483. Args: []string{"delete"},
  484. },
  485. },
  486. },
  487. },
  488. },
  489. },
  490. },
  491. }
  492. _, err = config.Clientset.BatchV1beta1().CronJobs("default").Create(
  493. context.Background(), cronJob, metav1.CreateOptions{},
  494. )
  495. if err != nil {
  496. return err
  497. }
  498. return nil
  499. }
  500. func checkForServiceAccount(config *PorterRunSharedConfig) error {
  501. serviceAccounts, err := config.Clientset.CoreV1().ServiceAccounts(namespace).List(
  502. context.Background(), metav1.ListOptions{},
  503. )
  504. if err != nil {
  505. return err
  506. }
  507. for _, serviceAccount := range serviceAccounts.Items {
  508. if serviceAccount.Name == "porter-ephemeral-pod-deletion-service-account" {
  509. return nil
  510. }
  511. }
  512. serviceAccount := &v1.ServiceAccount{
  513. ObjectMeta: metav1.ObjectMeta{
  514. Name: "porter-ephemeral-pod-deletion-service-account",
  515. },
  516. }
  517. _, err = config.Clientset.CoreV1().ServiceAccounts(namespace).Create(
  518. context.Background(), serviceAccount, metav1.CreateOptions{},
  519. )
  520. if err != nil {
  521. return err
  522. }
  523. return nil
  524. }
  525. func checkForClusterRole(config *PorterRunSharedConfig) error {
  526. roles, err := config.Clientset.RbacV1().ClusterRoles().List(
  527. context.Background(), metav1.ListOptions{},
  528. )
  529. if err != nil {
  530. return err
  531. }
  532. for _, role := range roles.Items {
  533. if role.Name == "porter-ephemeral-pod-deletion-cluster-role" {
  534. return nil
  535. }
  536. }
  537. role := &rbacv1.ClusterRole{
  538. ObjectMeta: metav1.ObjectMeta{
  539. Name: "porter-ephemeral-pod-deletion-cluster-role",
  540. },
  541. Rules: []rbacv1.PolicyRule{
  542. {
  543. APIGroups: []string{""},
  544. Resources: []string{"pods"},
  545. Verbs: []string{"list", "delete"},
  546. },
  547. {
  548. APIGroups: []string{""},
  549. Resources: []string{"namespaces"},
  550. Verbs: []string{"list"},
  551. },
  552. },
  553. }
  554. _, err = config.Clientset.RbacV1().ClusterRoles().Create(
  555. context.Background(), role, metav1.CreateOptions{},
  556. )
  557. if err != nil {
  558. return err
  559. }
  560. return nil
  561. }
  562. func checkForRoleBinding(config *PorterRunSharedConfig) error {
  563. bindings, err := config.Clientset.RbacV1().ClusterRoleBindings().List(
  564. context.Background(), metav1.ListOptions{},
  565. )
  566. if err != nil {
  567. return err
  568. }
  569. for _, binding := range bindings.Items {
  570. if binding.Name == "porter-ephemeral-pod-deletion-cluster-rolebinding" {
  571. return nil
  572. }
  573. }
  574. binding := &rbacv1.ClusterRoleBinding{
  575. ObjectMeta: metav1.ObjectMeta{
  576. Name: "porter-ephemeral-pod-deletion-cluster-rolebinding",
  577. },
  578. RoleRef: rbacv1.RoleRef{
  579. APIGroup: "rbac.authorization.k8s.io",
  580. Kind: "ClusterRole",
  581. Name: "porter-ephemeral-pod-deletion-cluster-role",
  582. },
  583. Subjects: []rbacv1.Subject{
  584. {
  585. APIGroup: "",
  586. Kind: "ServiceAccount",
  587. Name: "porter-ephemeral-pod-deletion-service-account",
  588. Namespace: "default",
  589. },
  590. },
  591. }
  592. _, err = config.Clientset.RbacV1().ClusterRoleBindings().Create(
  593. context.Background(), binding, metav1.CreateOptions{},
  594. )
  595. if err != nil {
  596. return err
  597. }
  598. return nil
  599. }
  600. func waitForPod(config *PorterRunSharedConfig, pod *v1.Pod) error {
  601. var (
  602. w watch.Interface
  603. err error
  604. ok bool
  605. )
  606. // immediately after creating a pod, the API may return a 404. heuristically 1
  607. // second seems to be plenty.
  608. watchRetries := 3
  609. for i := 0; i < watchRetries; i++ {
  610. selector := fields.OneTermEqualSelector("metadata.name", pod.Name).String()
  611. w, err = config.Clientset.CoreV1().
  612. Pods(pod.Namespace).
  613. Watch(context.Background(), metav1.ListOptions{FieldSelector: selector})
  614. if err == nil {
  615. break
  616. }
  617. time.Sleep(time.Second)
  618. }
  619. if err != nil {
  620. return err
  621. }
  622. defer w.Stop()
  623. for {
  624. select {
  625. case <-time.Tick(time.Second):
  626. // poll every second in case we already missed the ready event while
  627. // creating the listener.
  628. pod, err = config.Clientset.CoreV1().
  629. Pods(pod.Namespace).
  630. Get(context.Background(), pod.Name, metav1.GetOptions{})
  631. if isPodReady(pod) || isPodExited(pod) {
  632. return nil
  633. }
  634. case evt := <-w.ResultChan():
  635. pod, ok = evt.Object.(*v1.Pod)
  636. if !ok {
  637. return fmt.Errorf("unexpected object type: %T", evt.Object)
  638. }
  639. if isPodReady(pod) || isPodExited(pod) {
  640. return nil
  641. }
  642. case <-time.After(time.Second * 10):
  643. return errors.New("timed out waiting for pod")
  644. }
  645. }
  646. }
  647. func isPodReady(pod *v1.Pod) bool {
  648. ready := false
  649. conditions := pod.Status.Conditions
  650. for i := range conditions {
  651. if conditions[i].Type == v1.PodReady {
  652. ready = pod.Status.Conditions[i].Status == v1.ConditionTrue
  653. }
  654. }
  655. return ready
  656. }
  657. func isPodExited(pod *v1.Pod) bool {
  658. return pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed
  659. }
  660. func handlePodAttachError(err error, config *PorterRunSharedConfig, namespace, podName, container string) error {
  661. if verbose {
  662. color.New(color.FgYellow).Printf("Error: %s\n", err)
  663. }
  664. color.New(color.FgYellow).Println("Could not open a shell to this container. Container logs:")
  665. var writtenBytes int64
  666. writtenBytes, _ = pipePodLogsToStdout(config, namespace, podName, container, false)
  667. if verbose || writtenBytes == 0 {
  668. color.New(color.FgYellow).Println("Could not get logs. Pod events:")
  669. pipeEventsToStdout(config, namespace, podName, container, false)
  670. }
  671. return err
  672. }
  673. func pipePodLogsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) (int64, error) {
  674. podLogOpts := v1.PodLogOptions{
  675. Container: container,
  676. Follow: follow,
  677. }
  678. req := config.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  679. podLogs, err := req.Stream(
  680. context.Background(),
  681. )
  682. if err != nil {
  683. return 0, err
  684. }
  685. defer podLogs.Close()
  686. return io.Copy(os.Stdout, podLogs)
  687. }
  688. func pipeEventsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) error {
  689. // update the config in case the operation has taken longer than token expiry time
  690. config.setSharedConfig()
  691. // creates the clientset
  692. resp, err := config.Clientset.CoreV1().Events(namespace).List(
  693. context.TODO(),
  694. metav1.ListOptions{
  695. FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.namespace=%s", name, namespace),
  696. },
  697. )
  698. if err != nil {
  699. return err
  700. }
  701. for _, event := range resp.Items {
  702. color.New(color.FgRed).Println(event.Message)
  703. }
  704. return nil
  705. }
  706. func getExistingPod(config *PorterRunSharedConfig, name, namespace string) (*v1.Pod, error) {
  707. return config.Clientset.CoreV1().Pods(namespace).Get(
  708. context.Background(),
  709. name,
  710. metav1.GetOptions{},
  711. )
  712. }
  713. func deletePod(config *PorterRunSharedConfig, name, namespace string) error {
  714. // update the config in case the operation has taken longer than token expiry time
  715. config.setSharedConfig()
  716. err := config.Clientset.CoreV1().Pods(namespace).Delete(
  717. context.Background(),
  718. name,
  719. metav1.DeleteOptions{},
  720. )
  721. if err != nil {
  722. color.New(color.FgRed).Printf("Could not delete ephemeral pod: %s\n", err.Error())
  723. return err
  724. }
  725. color.New(color.FgGreen).Println("Sucessfully deleted ephemeral pod")
  726. return nil
  727. }
  728. func createEphemeralPodFromExisting(config *PorterRunSharedConfig, existing *v1.Pod, args []string) (*v1.Pod, error) {
  729. newPod := existing.DeepCopy()
  730. // only copy the pod spec, overwrite metadata
  731. newPod.ObjectMeta = metav1.ObjectMeta{
  732. Name: strings.ToLower(fmt.Sprintf("%s-copy-%s", existing.ObjectMeta.Name, utils.String(4))),
  733. Namespace: existing.ObjectMeta.Namespace,
  734. }
  735. newPod.Status = v1.PodStatus{}
  736. // only use "primary" container
  737. newPod.Spec.Containers = newPod.Spec.Containers[0:1]
  738. // set restart policy to never
  739. newPod.Spec.RestartPolicy = v1.RestartPolicyNever
  740. // change the command in the pod to the passed in pod command
  741. cmdRoot := args[0]
  742. cmdArgs := make([]string, 0)
  743. // annotate with the ephemeral pod tag
  744. newPod.Labels = make(map[string]string)
  745. newPod.Labels["porter/ephemeral-pod"] = "true"
  746. if len(args) > 1 {
  747. cmdArgs = args[1:]
  748. }
  749. newPod.Spec.Containers[0].Command = []string{cmdRoot}
  750. newPod.Spec.Containers[0].Args = cmdArgs
  751. newPod.Spec.Containers[0].TTY = true
  752. newPod.Spec.Containers[0].Stdin = true
  753. newPod.Spec.Containers[0].StdinOnce = true
  754. newPod.Spec.NodeName = ""
  755. // remove health checks and probes
  756. newPod.Spec.Containers[0].LivenessProbe = nil
  757. newPod.Spec.Containers[0].ReadinessProbe = nil
  758. newPod.Spec.Containers[0].StartupProbe = nil
  759. // create the pod and return it
  760. return config.Clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
  761. context.Background(),
  762. newPod,
  763. metav1.CreateOptions{},
  764. )
  765. }