2
0

run.go 22 KB

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