run.go 18 KB

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