run.go 21 KB

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