run.go 21 KB

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