run.go 21 KB

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