run.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. // try and create the cron job and all of the other required resources as necessary,
  423. // starting with the service account, then role and then a role binding
  424. err := checkForServiceAccount(config)
  425. if err != nil {
  426. return err
  427. }
  428. err = checkForClusterRole(config)
  429. if err != nil {
  430. return err
  431. }
  432. err = checkForRoleBinding(config)
  433. if err != nil {
  434. return err
  435. }
  436. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  437. if err != nil {
  438. return err
  439. }
  440. for _, namespace := range namespaces.Items {
  441. cronJobs, err := config.Clientset.BatchV1beta1().CronJobs(namespace.Name).List(
  442. context.Background(), metav1.ListOptions{},
  443. )
  444. if err != nil {
  445. return err
  446. }
  447. if namespace.Name == "default" {
  448. for _, cronJob := range cronJobs.Items {
  449. if cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  450. return nil
  451. }
  452. }
  453. } else {
  454. for _, cronJob := range cronJobs.Items {
  455. if cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  456. err = config.Clientset.BatchV1beta1().CronJobs(namespace.Name).Delete(
  457. context.Background(), cronJob.Name, metav1.DeleteOptions{},
  458. )
  459. if err != nil {
  460. return err
  461. }
  462. }
  463. }
  464. }
  465. }
  466. // create the cronjob
  467. cronJob := &batchv1beta1.CronJob{
  468. ObjectMeta: metav1.ObjectMeta{
  469. Name: "porter-ephemeral-pod-deletion-cronjob",
  470. },
  471. Spec: batchv1beta1.CronJobSpec{
  472. Schedule: "0 * * * *",
  473. JobTemplate: batchv1beta1.JobTemplateSpec{
  474. Spec: batchv1.JobSpec{
  475. Template: v1.PodTemplateSpec{
  476. Spec: v1.PodSpec{
  477. ServiceAccountName: "porter-ephemeral-pod-deletion-service-account",
  478. RestartPolicy: v1.RestartPolicyNever,
  479. Containers: []v1.Container{
  480. {
  481. Name: "ephemeral-pods-manager",
  482. Image: "public.ecr.aws/o1j4x7p4/porter-ephemeral-pods-manager:latest",
  483. ImagePullPolicy: v1.PullAlways,
  484. Args: []string{"delete"},
  485. },
  486. },
  487. },
  488. },
  489. },
  490. },
  491. },
  492. }
  493. _, err = config.Clientset.BatchV1beta1().CronJobs("default").Create(
  494. context.Background(), cronJob, metav1.CreateOptions{},
  495. )
  496. if err != nil {
  497. return err
  498. }
  499. return nil
  500. }
  501. func checkForServiceAccount(config *PorterRunSharedConfig) error {
  502. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  503. if err != nil {
  504. return err
  505. }
  506. for _, namespace := range namespaces.Items {
  507. serviceAccounts, err := config.Clientset.CoreV1().ServiceAccounts(namespace.Name).List(
  508. context.Background(), metav1.ListOptions{},
  509. )
  510. if err != nil {
  511. return err
  512. }
  513. if namespace.Name == "default" {
  514. for _, svcAccount := range serviceAccounts.Items {
  515. if svcAccount.Name == "porter-ephemeral-pod-deletion-service-account" {
  516. return nil
  517. }
  518. }
  519. } else {
  520. for _, svcAccount := range serviceAccounts.Items {
  521. if svcAccount.Name == "porter-ephemeral-pod-deletion-service-account" {
  522. err = config.Clientset.CoreV1().ServiceAccounts(namespace.Name).Delete(
  523. context.Background(), svcAccount.Name, metav1.DeleteOptions{},
  524. )
  525. if err != nil {
  526. return err
  527. }
  528. }
  529. }
  530. }
  531. }
  532. serviceAccount := &v1.ServiceAccount{
  533. ObjectMeta: metav1.ObjectMeta{
  534. Name: "porter-ephemeral-pod-deletion-service-account",
  535. },
  536. }
  537. _, err = config.Clientset.CoreV1().ServiceAccounts("default").Create(
  538. context.Background(), serviceAccount, metav1.CreateOptions{},
  539. )
  540. if err != nil {
  541. return err
  542. }
  543. return nil
  544. }
  545. func checkForClusterRole(config *PorterRunSharedConfig) error {
  546. roles, err := config.Clientset.RbacV1().ClusterRoles().List(
  547. context.Background(), metav1.ListOptions{},
  548. )
  549. if err != nil {
  550. return err
  551. }
  552. for _, role := range roles.Items {
  553. if role.Name == "porter-ephemeral-pod-deletion-cluster-role" {
  554. return nil
  555. }
  556. }
  557. role := &rbacv1.ClusterRole{
  558. ObjectMeta: metav1.ObjectMeta{
  559. Name: "porter-ephemeral-pod-deletion-cluster-role",
  560. },
  561. Rules: []rbacv1.PolicyRule{
  562. {
  563. APIGroups: []string{""},
  564. Resources: []string{"pods"},
  565. Verbs: []string{"list", "delete"},
  566. },
  567. {
  568. APIGroups: []string{""},
  569. Resources: []string{"namespaces"},
  570. Verbs: []string{"list"},
  571. },
  572. },
  573. }
  574. _, err = config.Clientset.RbacV1().ClusterRoles().Create(
  575. context.Background(), role, metav1.CreateOptions{},
  576. )
  577. if err != nil {
  578. return err
  579. }
  580. return nil
  581. }
  582. func checkForRoleBinding(config *PorterRunSharedConfig) error {
  583. bindings, err := config.Clientset.RbacV1().ClusterRoleBindings().List(
  584. context.Background(), metav1.ListOptions{},
  585. )
  586. if err != nil {
  587. return err
  588. }
  589. for _, binding := range bindings.Items {
  590. if binding.Name == "porter-ephemeral-pod-deletion-cluster-rolebinding" {
  591. return nil
  592. }
  593. }
  594. binding := &rbacv1.ClusterRoleBinding{
  595. ObjectMeta: metav1.ObjectMeta{
  596. Name: "porter-ephemeral-pod-deletion-cluster-rolebinding",
  597. },
  598. RoleRef: rbacv1.RoleRef{
  599. APIGroup: "rbac.authorization.k8s.io",
  600. Kind: "ClusterRole",
  601. Name: "porter-ephemeral-pod-deletion-cluster-role",
  602. },
  603. Subjects: []rbacv1.Subject{
  604. {
  605. APIGroup: "",
  606. Kind: "ServiceAccount",
  607. Name: "porter-ephemeral-pod-deletion-service-account",
  608. Namespace: "default",
  609. },
  610. },
  611. }
  612. _, err = config.Clientset.RbacV1().ClusterRoleBindings().Create(
  613. context.Background(), binding, metav1.CreateOptions{},
  614. )
  615. if err != nil {
  616. return err
  617. }
  618. return nil
  619. }
  620. func waitForPod(config *PorterRunSharedConfig, pod *v1.Pod) error {
  621. var (
  622. w watch.Interface
  623. err error
  624. ok bool
  625. )
  626. // immediately after creating a pod, the API may return a 404. heuristically 1
  627. // second seems to be plenty.
  628. watchRetries := 3
  629. for i := 0; i < watchRetries; i++ {
  630. selector := fields.OneTermEqualSelector("metadata.name", pod.Name).String()
  631. w, err = config.Clientset.CoreV1().
  632. Pods(pod.Namespace).
  633. Watch(context.Background(), metav1.ListOptions{FieldSelector: selector})
  634. if err == nil {
  635. break
  636. }
  637. time.Sleep(time.Second)
  638. }
  639. if err != nil {
  640. return err
  641. }
  642. defer w.Stop()
  643. for {
  644. select {
  645. case <-time.Tick(time.Second):
  646. // poll every second in case we already missed the ready event while
  647. // creating the listener.
  648. pod, err = config.Clientset.CoreV1().
  649. Pods(pod.Namespace).
  650. Get(context.Background(), pod.Name, metav1.GetOptions{})
  651. if isPodReady(pod) || isPodExited(pod) {
  652. return nil
  653. }
  654. case evt := <-w.ResultChan():
  655. pod, ok = evt.Object.(*v1.Pod)
  656. if !ok {
  657. return fmt.Errorf("unexpected object type: %T", evt.Object)
  658. }
  659. if isPodReady(pod) || isPodExited(pod) {
  660. return nil
  661. }
  662. case <-time.After(time.Second * 10):
  663. return errors.New("timed out waiting for pod")
  664. }
  665. }
  666. }
  667. func isPodReady(pod *v1.Pod) bool {
  668. ready := false
  669. conditions := pod.Status.Conditions
  670. for i := range conditions {
  671. if conditions[i].Type == v1.PodReady {
  672. ready = pod.Status.Conditions[i].Status == v1.ConditionTrue
  673. }
  674. }
  675. return ready
  676. }
  677. func isPodExited(pod *v1.Pod) bool {
  678. return pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed
  679. }
  680. func handlePodAttachError(err error, config *PorterRunSharedConfig, namespace, podName, container string) error {
  681. if verbose {
  682. color.New(color.FgYellow).Printf("Error: %s\n", err)
  683. }
  684. color.New(color.FgYellow).Println("Could not open a shell to this container. Container logs:")
  685. var writtenBytes int64
  686. writtenBytes, _ = pipePodLogsToStdout(config, namespace, podName, container, false)
  687. if verbose || writtenBytes == 0 {
  688. color.New(color.FgYellow).Println("Could not get logs. Pod events:")
  689. pipeEventsToStdout(config, namespace, podName, container, false)
  690. }
  691. return err
  692. }
  693. func pipePodLogsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) (int64, error) {
  694. podLogOpts := v1.PodLogOptions{
  695. Container: container,
  696. Follow: follow,
  697. }
  698. req := config.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  699. podLogs, err := req.Stream(
  700. context.Background(),
  701. )
  702. if err != nil {
  703. return 0, err
  704. }
  705. defer podLogs.Close()
  706. return io.Copy(os.Stdout, podLogs)
  707. }
  708. func pipeEventsToStdout(config *PorterRunSharedConfig, namespace, name, container string, follow bool) error {
  709. // update the config in case the operation has taken longer than token expiry time
  710. config.setSharedConfig()
  711. // creates the clientset
  712. resp, err := config.Clientset.CoreV1().Events(namespace).List(
  713. context.TODO(),
  714. metav1.ListOptions{
  715. FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.namespace=%s", name, namespace),
  716. },
  717. )
  718. if err != nil {
  719. return err
  720. }
  721. for _, event := range resp.Items {
  722. color.New(color.FgRed).Println(event.Message)
  723. }
  724. return nil
  725. }
  726. func getExistingPod(config *PorterRunSharedConfig, name, namespace string) (*v1.Pod, error) {
  727. return config.Clientset.CoreV1().Pods(namespace).Get(
  728. context.Background(),
  729. name,
  730. metav1.GetOptions{},
  731. )
  732. }
  733. func deletePod(config *PorterRunSharedConfig, name, namespace string) error {
  734. // update the config in case the operation has taken longer than token expiry time
  735. config.setSharedConfig()
  736. err := config.Clientset.CoreV1().Pods(namespace).Delete(
  737. context.Background(),
  738. name,
  739. metav1.DeleteOptions{},
  740. )
  741. if err != nil {
  742. color.New(color.FgRed).Printf("Could not delete ephemeral pod: %s\n", err.Error())
  743. return err
  744. }
  745. color.New(color.FgGreen).Println("Sucessfully deleted ephemeral pod")
  746. return nil
  747. }
  748. func createEphemeralPodFromExisting(config *PorterRunSharedConfig, existing *v1.Pod, args []string) (*v1.Pod, error) {
  749. newPod := existing.DeepCopy()
  750. // only copy the pod spec, overwrite metadata
  751. newPod.ObjectMeta = metav1.ObjectMeta{
  752. Name: strings.ToLower(fmt.Sprintf("%s-copy-%s", existing.ObjectMeta.Name, utils.String(4))),
  753. Namespace: existing.ObjectMeta.Namespace,
  754. }
  755. newPod.Status = v1.PodStatus{}
  756. // only use "primary" container
  757. newPod.Spec.Containers = newPod.Spec.Containers[0:1]
  758. // set restart policy to never
  759. newPod.Spec.RestartPolicy = v1.RestartPolicyNever
  760. // change the command in the pod to the passed in pod command
  761. cmdRoot := args[0]
  762. cmdArgs := make([]string, 0)
  763. // annotate with the ephemeral pod tag
  764. newPod.Labels = make(map[string]string)
  765. newPod.Labels["porter/ephemeral-pod"] = "true"
  766. if len(args) > 1 {
  767. cmdArgs = args[1:]
  768. }
  769. newPod.Spec.Containers[0].Command = []string{cmdRoot}
  770. newPod.Spec.Containers[0].Args = cmdArgs
  771. newPod.Spec.Containers[0].TTY = true
  772. newPod.Spec.Containers[0].Stdin = true
  773. newPod.Spec.Containers[0].StdinOnce = true
  774. newPod.Spec.NodeName = ""
  775. // remove health checks and probes
  776. newPod.Spec.Containers[0].LivenessProbe = nil
  777. newPod.Spec.Containers[0].ReadinessProbe = nil
  778. newPod.Spec.Containers[0].StartupProbe = nil
  779. // create the pod and return it
  780. return config.Clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
  781. context.Background(),
  782. newPod,
  783. metav1.CreateOptions{},
  784. )
  785. }