run.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. kubeResp, err := p.Client.GetKubeconfig(context.Background(), pID, cID, cliConf.Kubeconfig)
  216. if err != nil {
  217. return err
  218. }
  219. kubeBytes := kubeResp.Kubeconfig
  220. cmdConf, err := clientcmd.NewClientConfigFromBytes(kubeBytes)
  221. if err != nil {
  222. return err
  223. }
  224. restConf, err := cmdConf.ClientConfig()
  225. if err != nil {
  226. return err
  227. }
  228. restConf.GroupVersion = &schema.GroupVersion{
  229. Group: "api",
  230. Version: "v1",
  231. }
  232. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  233. p.RestConf = restConf
  234. clientset, err := kubernetes.NewForConfig(restConf)
  235. if err != nil {
  236. return err
  237. }
  238. p.Clientset = clientset
  239. restClient, err := rest.RESTClientFor(restConf)
  240. if err != nil {
  241. return err
  242. }
  243. p.RestClient = restClient
  244. return nil
  245. }
  246. type podSimple struct {
  247. Name string
  248. ContainerNames []string
  249. }
  250. func getPods(client *api.Client, namespace, releaseName string) ([]podSimple, error) {
  251. pID := cliConf.Project
  252. cID := cliConf.Cluster
  253. resp, err := client.GetK8sAllPods(context.TODO(), pID, cID, namespace, releaseName)
  254. if err != nil {
  255. return nil, err
  256. }
  257. pods := *resp
  258. res := make([]podSimple, 0)
  259. for _, pod := range pods {
  260. if pod.Status.Phase == v1.PodRunning {
  261. containerNames := make([]string, 0)
  262. for _, container := range pod.Spec.Containers {
  263. containerNames = append(containerNames, container.Name)
  264. }
  265. res = append(res, podSimple{
  266. Name: pod.ObjectMeta.Name,
  267. ContainerNames: containerNames,
  268. })
  269. }
  270. }
  271. return res, nil
  272. }
  273. func executeRun(config *PorterRunSharedConfig, namespace, name, container string, args []string) error {
  274. req := config.RestClient.Post().
  275. Resource("pods").
  276. Name(name).
  277. Namespace(namespace).
  278. SubResource("exec")
  279. for _, arg := range args {
  280. req.Param("command", arg)
  281. }
  282. req.Param("stdin", "true")
  283. req.Param("stdout", "true")
  284. req.Param("tty", "true")
  285. req.Param("container", container)
  286. t := term.TTY{
  287. In: os.Stdin,
  288. Out: os.Stdout,
  289. Raw: true,
  290. }
  291. size := t.GetSize()
  292. sizeQueue := t.MonitorSize(size)
  293. return t.Safe(func() error {
  294. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  295. if err != nil {
  296. return err
  297. }
  298. return exec.Stream(remotecommand.StreamOptions{
  299. Stdin: os.Stdin,
  300. Stdout: os.Stdout,
  301. Stderr: os.Stderr,
  302. Tty: true,
  303. TerminalSizeQueue: sizeQueue,
  304. })
  305. })
  306. }
  307. func executeRunEphemeral(config *PorterRunSharedConfig, namespace, name, container string, args []string) error {
  308. existing, err := getExistingPod(config, name, namespace)
  309. if err != nil {
  310. return err
  311. }
  312. newPod, err := createEphemeralPodFromExisting(config, existing, args)
  313. if err != nil {
  314. return err
  315. }
  316. podName := newPod.ObjectMeta.Name
  317. // delete the ephemeral pod no matter what
  318. defer deletePod(config, podName, namespace)
  319. color.New(color.FgYellow).Printf("Waiting for pod %s to be ready...", podName)
  320. if err = waitForPod(config, newPod); err != nil {
  321. color.New(color.FgRed).Println("failed")
  322. return handlePodAttachError(err, config, namespace, podName, container)
  323. }
  324. err = checkForPodDeletionCronJob(config)
  325. if err != nil {
  326. return err
  327. }
  328. // refresh pod info for latest status
  329. newPod, err = config.Clientset.CoreV1().
  330. Pods(newPod.Namespace).
  331. Get(context.Background(), newPod.Name, metav1.GetOptions{})
  332. // pod exited while we were waiting. maybe an error maybe not.
  333. // we dont know if the user wanted an interactive shell or not.
  334. // if it was an error the logs hopefully say so.
  335. if isPodExited(newPod) {
  336. color.New(color.FgGreen).Println("complete!")
  337. var writtenBytes int64
  338. writtenBytes, _ = pipePodLogsToStdout(config, namespace, podName, container, false)
  339. if verbose || writtenBytes == 0 {
  340. color.New(color.FgYellow).Println("Could not get logs. Pod events:")
  341. pipeEventsToStdout(config, namespace, podName, container, false)
  342. }
  343. return nil
  344. }
  345. color.New(color.FgGreen).Println("ready!")
  346. color.New(color.FgYellow).Println("Attempting connection to the container. If you don't see a command prompt, try pressing enter.")
  347. req := config.RestClient.Post().
  348. Resource("pods").
  349. Name(podName).
  350. Namespace(namespace).
  351. SubResource("attach")
  352. req.Param("stdin", "true")
  353. req.Param("stdout", "true")
  354. req.Param("tty", "true")
  355. req.Param("container", container)
  356. t := term.TTY{
  357. In: os.Stdin,
  358. Out: os.Stdout,
  359. Raw: true,
  360. }
  361. size := t.GetSize()
  362. sizeQueue := t.MonitorSize(size)
  363. if err = t.Safe(func() error {
  364. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  365. if err != nil {
  366. return err
  367. }
  368. return exec.Stream(remotecommand.StreamOptions{
  369. Stdin: os.Stdin,
  370. Stdout: os.Stdout,
  371. Stderr: os.Stderr,
  372. Tty: true,
  373. TerminalSizeQueue: sizeQueue,
  374. })
  375. }); err != nil {
  376. // ugly way to catch no TTY errors, such as when running command "echo \"hello\""
  377. return handlePodAttachError(err, config, namespace, podName, container)
  378. }
  379. if verbose {
  380. color.New(color.FgYellow).Println("Pod events:")
  381. pipeEventsToStdout(config, namespace, podName, container, false)
  382. }
  383. return err
  384. }
  385. func checkForPodDeletionCronJob(config *PorterRunSharedConfig) error {
  386. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  387. if err != nil {
  388. return err
  389. }
  390. for _, namespace := range namespaces.Items {
  391. cronJobs, err := config.Clientset.BatchV1beta1().CronJobs(namespace.Name).List(
  392. context.Background(), metav1.ListOptions{},
  393. )
  394. if err != nil {
  395. return err
  396. }
  397. if namespace.Name != "default" {
  398. for _, cronJob := range cronJobs.Items {
  399. if cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  400. err = config.Clientset.BatchV1beta1().CronJobs(namespace.Name).Delete(
  401. context.Background(), cronJob.Name, metav1.DeleteOptions{},
  402. )
  403. if err != nil {
  404. return err
  405. }
  406. }
  407. }
  408. }
  409. for _, cronJob := range cronJobs.Items {
  410. if namespace.Name == "default" && cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  411. return nil
  412. }
  413. }
  414. }
  415. // try and create the cron job and all of the other required resources as necessary,
  416. // starting with the service account, then role and then a role binding
  417. err = checkForServiceAccount(config)
  418. if err != nil {
  419. return err
  420. }
  421. err = checkForClusterRole(config)
  422. if err != nil {
  423. return err
  424. }
  425. err = checkForRoleBinding(config)
  426. if err != nil {
  427. return err
  428. }
  429. // create the cronjob
  430. cronJob := &batchv1beta1.CronJob{
  431. ObjectMeta: metav1.ObjectMeta{
  432. Name: "porter-ephemeral-pod-deletion-cronjob",
  433. },
  434. Spec: batchv1beta1.CronJobSpec{
  435. Schedule: "0 * * * *",
  436. JobTemplate: batchv1beta1.JobTemplateSpec{
  437. Spec: batchv1.JobSpec{
  438. Template: v1.PodTemplateSpec{
  439. Spec: v1.PodSpec{
  440. ServiceAccountName: "porter-ephemeral-pod-deletion-service-account",
  441. RestartPolicy: v1.RestartPolicyNever,
  442. Containers: []v1.Container{
  443. {
  444. Name: "ephemeral-pods-manager",
  445. Image: "public.ecr.aws/o1j4x7p4/porter-ephemeral-pods-manager:latest",
  446. ImagePullPolicy: v1.PullAlways,
  447. Args: []string{"delete"},
  448. },
  449. },
  450. },
  451. },
  452. },
  453. },
  454. },
  455. }
  456. _, err = config.Clientset.BatchV1beta1().CronJobs("default").Create(
  457. context.Background(), cronJob, metav1.CreateOptions{},
  458. )
  459. if err != nil {
  460. return err
  461. }
  462. return nil
  463. }
  464. func checkForServiceAccount(config *PorterRunSharedConfig) error {
  465. serviceAccounts, err := config.Clientset.CoreV1().ServiceAccounts(namespace).List(
  466. context.Background(), metav1.ListOptions{},
  467. )
  468. if err != nil {
  469. return err
  470. }
  471. for _, serviceAccount := range serviceAccounts.Items {
  472. if serviceAccount.Name == "porter-ephemeral-pod-deletion-service-account" {
  473. return nil
  474. }
  475. }
  476. serviceAccount := &v1.ServiceAccount{
  477. ObjectMeta: metav1.ObjectMeta{
  478. Name: "porter-ephemeral-pod-deletion-service-account",
  479. },
  480. }
  481. _, err = config.Clientset.CoreV1().ServiceAccounts(namespace).Create(
  482. context.Background(), serviceAccount, metav1.CreateOptions{},
  483. )
  484. if err != nil {
  485. return err
  486. }
  487. return nil
  488. }
  489. func checkForClusterRole(config *PorterRunSharedConfig) error {
  490. roles, err := config.Clientset.RbacV1().ClusterRoles().List(
  491. context.Background(), metav1.ListOptions{},
  492. )
  493. if err != nil {
  494. return err
  495. }
  496. for _, role := range roles.Items {
  497. if role.Name == "porter-ephemeral-pod-deletion-cluster-role" {
  498. return nil
  499. }
  500. }
  501. role := &rbacv1.ClusterRole{
  502. ObjectMeta: metav1.ObjectMeta{
  503. Name: "porter-ephemeral-pod-deletion-cluster-role",
  504. },
  505. Rules: []rbacv1.PolicyRule{
  506. {
  507. APIGroups: []string{""},
  508. Resources: []string{"pods"},
  509. Verbs: []string{"list", "delete"},
  510. },
  511. {
  512. APIGroups: []string{""},
  513. Resources: []string{"namespaces"},
  514. Verbs: []string{"list"},
  515. },
  516. },
  517. }
  518. _, err = config.Clientset.RbacV1().ClusterRoles().Create(
  519. context.Background(), role, metav1.CreateOptions{},
  520. )
  521. if err != nil {
  522. return err
  523. }
  524. return nil
  525. }
  526. func checkForRoleBinding(config *PorterRunSharedConfig) error {
  527. bindings, err := config.Clientset.RbacV1().ClusterRoleBindings().List(
  528. context.Background(), metav1.ListOptions{},
  529. )
  530. if err != nil {
  531. return err
  532. }
  533. for _, binding := range bindings.Items {
  534. if binding.Name == "porter-ephemeral-pod-deletion-cluster-rolebinding" {
  535. return nil
  536. }
  537. }
  538. binding := &rbacv1.ClusterRoleBinding{
  539. ObjectMeta: metav1.ObjectMeta{
  540. Name: "porter-ephemeral-pod-deletion-cluster-rolebinding",
  541. },
  542. RoleRef: rbacv1.RoleRef{
  543. APIGroup: "rbac.authorization.k8s.io",
  544. Kind: "ClusterRole",
  545. Name: "porter-ephemeral-pod-deletion-cluster-role",
  546. },
  547. Subjects: []rbacv1.Subject{
  548. {
  549. APIGroup: "",
  550. Kind: "ServiceAccount",
  551. Name: "porter-ephemeral-pod-deletion-service-account",
  552. Namespace: "default",
  553. },
  554. },
  555. }
  556. _, err = config.Clientset.RbacV1().ClusterRoleBindings().Create(
  557. context.Background(), binding, metav1.CreateOptions{},
  558. )
  559. if err != nil {
  560. return err
  561. }
  562. return nil
  563. }
  564. func waitForPod(config *PorterRunSharedConfig, pod *v1.Pod) error {
  565. var (
  566. w watch.Interface
  567. err error
  568. ok bool
  569. )
  570. // immediately after creating a pod, the API may return a 404. heuristically 1
  571. // second seems to be plenty.
  572. watchRetries := 3
  573. for i := 0; i < watchRetries; i++ {
  574. selector := fields.OneTermEqualSelector("metadata.name", pod.Name).String()
  575. w, err = config.Clientset.CoreV1().
  576. Pods(pod.Namespace).
  577. Watch(context.Background(), metav1.ListOptions{FieldSelector: selector})
  578. if err == nil {
  579. break
  580. }
  581. time.Sleep(time.Second)
  582. }
  583. if err != nil {
  584. return err
  585. }
  586. defer w.Stop()
  587. for {
  588. select {
  589. case <-time.Tick(time.Second):
  590. // poll every second in case we already missed the ready event while
  591. // creating the listener.
  592. pod, err = config.Clientset.CoreV1().
  593. Pods(pod.Namespace).
  594. Get(context.Background(), pod.Name, metav1.GetOptions{})
  595. if isPodReady(pod) || isPodExited(pod) {
  596. return nil
  597. }
  598. case evt := <-w.ResultChan():
  599. pod, ok = evt.Object.(*v1.Pod)
  600. if !ok {
  601. return fmt.Errorf("unexpected object type: %T", evt.Object)
  602. }
  603. if isPodReady(pod) || isPodExited(pod) {
  604. return nil
  605. }
  606. case <-time.After(time.Second * 10):
  607. return errors.New("timed out waiting for pod")
  608. }
  609. }
  610. }
  611. func isPodReady(pod *v1.Pod) bool {
  612. ready := false
  613. conditions := pod.Status.Conditions
  614. for i := range conditions {
  615. if conditions[i].Type == v1.PodReady {
  616. ready = pod.Status.Conditions[i].Status == v1.ConditionTrue
  617. }
  618. }
  619. return ready
  620. }
  621. func isPodExited(pod *v1.Pod) bool {
  622. return pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed
  623. }
  624. func handlePodAttachError(err error, config *PorterRunSharedConfig, namespace, podName, container string) error {
  625. if verbose {
  626. color.New(color.FgYellow).Printf("Error: %s\n", err)
  627. }
  628. color.New(color.FgYellow).Println("Could not open a shell to this container. Container logs:")
  629. var writtenBytes int64
  630. writtenBytes, _ = pipePodLogsToStdout(config, namespace, podName, container, false)
  631. if verbose || writtenBytes == 0 {
  632. color.New(color.FgYellow).Println("Could not get logs. Pod events:")
  633. pipeEventsToStdout(config, namespace, podName, container, false)
  634. }
  635. return err
  636. }
  637. func pipePodLogsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) (int64, error) {
  638. podLogOpts := v1.PodLogOptions{
  639. Container: container,
  640. Follow: follow,
  641. }
  642. req := config.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  643. podLogs, err := req.Stream(
  644. context.Background(),
  645. )
  646. if err != nil {
  647. return 0, err
  648. }
  649. defer podLogs.Close()
  650. return io.Copy(os.Stdout, podLogs)
  651. }
  652. func pipeEventsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) error {
  653. // update the config in case the operation has taken longer than token expiry time
  654. config.setSharedConfig()
  655. // creates the clientset
  656. resp, err := config.Clientset.CoreV1().Events(namespace).List(
  657. context.TODO(),
  658. metav1.ListOptions{
  659. FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.namespace=%s", name, namespace),
  660. },
  661. )
  662. if err != nil {
  663. return err
  664. }
  665. for _, event := range resp.Items {
  666. color.New(color.FgRed).Println(event.Message)
  667. }
  668. return nil
  669. }
  670. func getExistingPod(config *PorterRunSharedConfig, name, namespace string) (*v1.Pod, error) {
  671. return config.Clientset.CoreV1().Pods(namespace).Get(
  672. context.Background(),
  673. name,
  674. metav1.GetOptions{},
  675. )
  676. }
  677. func deletePod(config *PorterRunSharedConfig, name, namespace string) error {
  678. // update the config in case the operation has taken longer than token expiry time
  679. config.setSharedConfig()
  680. err := config.Clientset.CoreV1().Pods(namespace).Delete(
  681. context.Background(),
  682. name,
  683. metav1.DeleteOptions{},
  684. )
  685. if err != nil {
  686. color.New(color.FgRed).Printf("Could not delete ephemeral pod: %s\n", err.Error())
  687. return err
  688. }
  689. color.New(color.FgGreen).Println("Sucessfully deleted ephemeral pod")
  690. return nil
  691. }
  692. func createEphemeralPodFromExisting(config *PorterRunSharedConfig, existing *v1.Pod, args []string) (*v1.Pod, error) {
  693. newPod := existing.DeepCopy()
  694. // only copy the pod spec, overwrite metadata
  695. newPod.ObjectMeta = metav1.ObjectMeta{
  696. Name: strings.ToLower(fmt.Sprintf("%s-copy-%s", existing.ObjectMeta.Name, utils.String(4))),
  697. Namespace: existing.ObjectMeta.Namespace,
  698. }
  699. newPod.Status = v1.PodStatus{}
  700. // only use "primary" container
  701. newPod.Spec.Containers = newPod.Spec.Containers[0:1]
  702. // set restart policy to never
  703. newPod.Spec.RestartPolicy = v1.RestartPolicyNever
  704. // change the command in the pod to the passed in pod command
  705. cmdRoot := args[0]
  706. cmdArgs := make([]string, 0)
  707. // annotate with the ephemeral pod tag
  708. newPod.Labels = make(map[string]string)
  709. newPod.Labels["porter/ephemeral-pod"] = "true"
  710. if len(args) > 1 {
  711. cmdArgs = args[1:]
  712. }
  713. newPod.Spec.Containers[0].Command = []string{cmdRoot}
  714. newPod.Spec.Containers[0].Args = cmdArgs
  715. newPod.Spec.Containers[0].TTY = true
  716. newPod.Spec.Containers[0].Stdin = true
  717. newPod.Spec.Containers[0].StdinOnce = true
  718. newPod.Spec.NodeName = ""
  719. // remove health checks and probes
  720. newPod.Spec.Containers[0].LivenessProbe = nil
  721. newPod.Spec.Containers[0].ReadinessProbe = nil
  722. newPod.Spec.Containers[0].StartupProbe = nil
  723. // create the pod and return it
  724. return config.Clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
  725. context.Background(),
  726. newPod,
  727. metav1.CreateOptions{},
  728. )
  729. }