run.go 21 KB

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