app.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. "k8s.io/apimachinery/pkg/api/resource"
  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 (
  31. appNamespace string
  32. appVerbose bool
  33. appExistingPod bool
  34. appInteractive bool
  35. appContainerName string
  36. appTag string
  37. appCpuMilli int
  38. appMemoryMi int
  39. )
  40. // appCmd represents the "porter app" base command when called
  41. // without any subcommands
  42. var appCmd = &cobra.Command{
  43. Use: "app",
  44. Short: "Runs a command for your application.",
  45. }
  46. // appRunCmd represents the "porter app run" subcommand
  47. var appRunCmd = &cobra.Command{
  48. Use: "run [application] -- COMMAND [args...]",
  49. Args: cobra.MinimumNArgs(2),
  50. Short: "Runs a command inside a connected cluster container.",
  51. Run: func(cmd *cobra.Command, args []string) {
  52. err := checkLoginAndRun(args, appRun)
  53. if err != nil {
  54. os.Exit(1)
  55. }
  56. },
  57. }
  58. // appRunCleanupCmd represents the "porter app run cleanup" subcommand
  59. var appRunCleanupCmd = &cobra.Command{
  60. Use: "cleanup",
  61. Args: cobra.NoArgs,
  62. Short: "Delete any lingering ephemeral pods that were created with \"porter app run\".",
  63. Run: func(cmd *cobra.Command, args []string) {
  64. err := checkLoginAndRun(args, appCleanup)
  65. if err != nil {
  66. os.Exit(1)
  67. }
  68. },
  69. }
  70. // appUpdateTagCmd represents the "porter app update-tag" subcommand
  71. var appUpdateTagCmd = &cobra.Command{
  72. Use: "update-tag [application]",
  73. Args: cobra.MinimumNArgs(1),
  74. Short: "Updates the image tag for an application.",
  75. Run: func(cmd *cobra.Command, args []string) {
  76. err := checkLoginAndRun(args, appUpdateTag)
  77. if err != nil {
  78. os.Exit(1)
  79. }
  80. },
  81. }
  82. func init() {
  83. rootCmd.AddCommand(appCmd)
  84. appRunCmd.PersistentFlags().BoolVarP(
  85. &appExistingPod,
  86. "existing_pod",
  87. "e",
  88. false,
  89. "whether to connect to an existing pod (default false)",
  90. )
  91. appRunCmd.PersistentFlags().BoolVarP(
  92. &appVerbose,
  93. "verbose",
  94. "v",
  95. false,
  96. "whether to print verbose output",
  97. )
  98. appRunCmd.PersistentFlags().BoolVar(
  99. &appInteractive,
  100. "interactive",
  101. false,
  102. "whether to run in interactive mode (default false)",
  103. )
  104. appRunCmd.PersistentFlags().IntVarP(
  105. &appCpuMilli,
  106. "cpu",
  107. "",
  108. 0,
  109. "cpu allocation in millicores (1000 millicores = 1 vCPU)",
  110. )
  111. appRunCmd.PersistentFlags().IntVarP(
  112. &appMemoryMi,
  113. "ram",
  114. "",
  115. 0,
  116. "ram allocation in Mi (1024 Mi = 1 GB)",
  117. )
  118. appRunCmd.PersistentFlags().StringVarP(
  119. &appContainerName,
  120. "container",
  121. "c",
  122. "",
  123. "name of the container inside pod to run the command in",
  124. )
  125. appRunCmd.AddCommand(appRunCleanupCmd)
  126. appUpdateTagCmd.PersistentFlags().StringVarP(
  127. &appTag,
  128. "tag",
  129. "t",
  130. "",
  131. "the specified tag to use, default is \"latest\"",
  132. )
  133. appCmd.AddCommand(appRunCmd)
  134. appCmd.AddCommand(appUpdateTagCmd)
  135. }
  136. func appRun(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  137. execArgs := args[1:]
  138. color.New(color.FgGreen).Println("Attempting to run", strings.Join(execArgs, " "), "for application", args[0])
  139. appNamespace = fmt.Sprintf("porter-stack-%s", args[0])
  140. if len(execArgs) > 0 {
  141. res, err := client.GetPorterApp(context.Background(), cliConf.Project, cliConf.Cluster, args[0])
  142. if err != nil {
  143. return fmt.Errorf("Unable to run command: %w", err)
  144. }
  145. if res.Name == "" {
  146. return fmt.Errorf("An application named \"%s\" was not found in your project (ID: %d). Please check your spelling and try again.", args[0], cliConf.Project)
  147. }
  148. if res.Builder != "" &&
  149. (strings.Contains(res.Builder, "heroku") ||
  150. strings.Contains(res.Builder, "paketo")) &&
  151. execArgs[0] != "/cnb/lifecycle/launcher" &&
  152. execArgs[0] != "launcher" {
  153. // this is a buildpacks release using a heroku builder, prepend the launcher
  154. execArgs = append([]string{"/cnb/lifecycle/launcher"}, execArgs...)
  155. }
  156. }
  157. podsSimple, err := appGetPods(client, appNamespace, args[0])
  158. if err != nil {
  159. return fmt.Errorf("Could not retrieve list of pods: %s", err.Error())
  160. }
  161. // if length of pods is 0, throw error
  162. var selectedPod appPodSimple
  163. if len(podsSimple) == 0 {
  164. return fmt.Errorf("At least one pod must exist in this deployment.")
  165. } else if !appInteractive || len(podsSimple) == 1 {
  166. selectedPod = podsSimple[0]
  167. } else {
  168. podNames := make([]string, 0)
  169. for _, podSimple := range podsSimple {
  170. podNames = append(podNames, podSimple.Name)
  171. }
  172. selectedPodName, err := utils.PromptSelect("Select the pod:", podNames)
  173. if err != nil {
  174. return err
  175. }
  176. // find selected pod
  177. for _, podSimple := range podsSimple {
  178. if selectedPodName == podSimple.Name {
  179. selectedPod = podSimple
  180. }
  181. }
  182. }
  183. var selectedContainerName string
  184. if len(selectedPod.ContainerNames) == 0 {
  185. return fmt.Errorf("At least one container must exist in the selected pod.")
  186. } else if len(selectedPod.ContainerNames) == 1 {
  187. if appContainerName != "" && appContainerName != selectedPod.ContainerNames[0] {
  188. return fmt.Errorf("provided container %s does not exist in pod %s", appContainerName, selectedPod.Name)
  189. }
  190. selectedContainerName = selectedPod.ContainerNames[0]
  191. }
  192. if appContainerName != "" && selectedContainerName == "" {
  193. // check if provided container name exists in the pod
  194. for _, name := range selectedPod.ContainerNames {
  195. if name == appContainerName {
  196. selectedContainerName = name
  197. break
  198. }
  199. }
  200. if selectedContainerName == "" {
  201. return fmt.Errorf("provided container %s does not exist in pod %s", appContainerName, selectedPod.Name)
  202. }
  203. }
  204. if selectedContainerName == "" {
  205. if !appInteractive {
  206. return fmt.Errorf("container name must be specified using the --container flag when not using interactive mode")
  207. }
  208. selectedContainer, err := utils.PromptSelect("Select the container:", selectedPod.ContainerNames)
  209. if err != nil {
  210. return err
  211. }
  212. selectedContainerName = selectedContainer
  213. }
  214. config := &AppPorterRunSharedConfig{
  215. Client: client,
  216. }
  217. err = config.setSharedConfig()
  218. if err != nil {
  219. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  220. }
  221. if appExistingPod {
  222. return appExecuteRun(config, appNamespace, selectedPod.Name, selectedContainerName, execArgs)
  223. }
  224. return appExecuteRunEphemeral(config, appNamespace, selectedPod.Name, selectedContainerName, execArgs)
  225. }
  226. func appCleanup(_ *types.GetAuthenticatedUserResponse, client *api.Client, _ []string) error {
  227. config := &AppPorterRunSharedConfig{
  228. Client: client,
  229. }
  230. err := config.setSharedConfig()
  231. if err != nil {
  232. return fmt.Errorf("Could not retrieve kube credentials: %s", err.Error())
  233. }
  234. proceed, err := utils.PromptSelect(
  235. fmt.Sprintf("You have chosen the '%s' namespace for cleanup. Do you want to proceed?", appNamespace),
  236. []string{"Yes", "No", "All namespaces"},
  237. )
  238. if err != nil {
  239. return err
  240. }
  241. if proceed == "No" {
  242. return nil
  243. }
  244. var podNames []string
  245. color.New(color.FgGreen).Println("Fetching ephemeral pods for cleanup")
  246. if proceed == "All namespaces" {
  247. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  248. if err != nil {
  249. return err
  250. }
  251. for _, namespace := range namespaces.Items {
  252. if pods, err := appGetEphemeralPods(namespace.Name, config.Clientset); err == nil {
  253. podNames = append(podNames, pods...)
  254. } else {
  255. return err
  256. }
  257. }
  258. } else {
  259. if pods, err := appGetEphemeralPods(appNamespace, config.Clientset); err == nil {
  260. podNames = append(podNames, pods...)
  261. } else {
  262. return err
  263. }
  264. }
  265. if len(podNames) == 0 {
  266. color.New(color.FgBlue).Println("No ephemeral pods to delete")
  267. return nil
  268. }
  269. selectedPods, err := utils.PromptMultiselect("Select ephemeral pods to delete", podNames)
  270. if err != nil {
  271. return err
  272. }
  273. for _, podName := range selectedPods {
  274. color.New(color.FgBlue).Printf("Deleting ephemeral pod: %s\n", podName)
  275. err = config.Clientset.CoreV1().Pods(appNamespace).Delete(
  276. context.Background(), podName, metav1.DeleteOptions{},
  277. )
  278. if err != nil {
  279. return err
  280. }
  281. }
  282. return nil
  283. }
  284. func appGetEphemeralPods(namespace string, clientset *kubernetes.Clientset) ([]string, error) {
  285. var podNames []string
  286. pods, err := clientset.CoreV1().Pods(namespace).List(
  287. context.Background(), metav1.ListOptions{LabelSelector: "porter/ephemeral-pod"},
  288. )
  289. if err != nil {
  290. return nil, err
  291. }
  292. for _, pod := range pods.Items {
  293. podNames = append(podNames, pod.Name)
  294. }
  295. return podNames, nil
  296. }
  297. type AppPorterRunSharedConfig struct {
  298. Client *api.Client
  299. RestConf *rest.Config
  300. Clientset *kubernetes.Clientset
  301. RestClient *rest.RESTClient
  302. }
  303. func (p *AppPorterRunSharedConfig) setSharedConfig() error {
  304. pID := cliConf.Project
  305. cID := cliConf.Cluster
  306. kubeResp, err := p.Client.GetKubeconfig(context.Background(), pID, cID, cliConf.Kubeconfig)
  307. if err != nil {
  308. return err
  309. }
  310. kubeBytes := kubeResp.Kubeconfig
  311. cmdConf, err := clientcmd.NewClientConfigFromBytes(kubeBytes)
  312. if err != nil {
  313. return err
  314. }
  315. restConf, err := cmdConf.ClientConfig()
  316. if err != nil {
  317. return err
  318. }
  319. restConf.GroupVersion = &schema.GroupVersion{
  320. Group: "api",
  321. Version: "v1",
  322. }
  323. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  324. p.RestConf = restConf
  325. clientset, err := kubernetes.NewForConfig(restConf)
  326. if err != nil {
  327. return err
  328. }
  329. p.Clientset = clientset
  330. restClient, err := rest.RESTClientFor(restConf)
  331. if err != nil {
  332. return err
  333. }
  334. p.RestClient = restClient
  335. return nil
  336. }
  337. type appPodSimple struct {
  338. Name string
  339. ContainerNames []string
  340. }
  341. func appGetPods(client *api.Client, namespace, releaseName string) ([]appPodSimple, error) {
  342. pID := cliConf.Project
  343. cID := cliConf.Cluster
  344. resp, err := client.GetK8sAllPods(context.TODO(), pID, cID, namespace, releaseName)
  345. if err != nil {
  346. return nil, err
  347. }
  348. pods := *resp
  349. res := make([]appPodSimple, 0)
  350. for _, pod := range pods {
  351. if pod.Status.Phase == v1.PodRunning {
  352. containerNames := make([]string, 0)
  353. for _, container := range pod.Spec.Containers {
  354. containerNames = append(containerNames, container.Name)
  355. }
  356. res = append(res, appPodSimple{
  357. Name: pod.ObjectMeta.Name,
  358. ContainerNames: containerNames,
  359. })
  360. }
  361. }
  362. return res, nil
  363. }
  364. func appExecuteRun(config *AppPorterRunSharedConfig, namespace, name, container string, args []string) error {
  365. req := config.RestClient.Post().
  366. Resource("pods").
  367. Name(name).
  368. Namespace(namespace).
  369. SubResource("exec")
  370. for _, arg := range args {
  371. req.Param("command", arg)
  372. }
  373. req.Param("stdin", "true")
  374. req.Param("stdout", "true")
  375. req.Param("tty", "true")
  376. req.Param("container", container)
  377. t := term.TTY{
  378. In: os.Stdin,
  379. Out: os.Stdout,
  380. Raw: true,
  381. }
  382. size := t.GetSize()
  383. sizeQueue := t.MonitorSize(size)
  384. return t.Safe(func() error {
  385. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  386. if err != nil {
  387. return err
  388. }
  389. return exec.Stream(remotecommand.StreamOptions{
  390. Stdin: os.Stdin,
  391. Stdout: os.Stdout,
  392. Stderr: os.Stderr,
  393. Tty: true,
  394. TerminalSizeQueue: sizeQueue,
  395. })
  396. })
  397. }
  398. func appExecuteRunEphemeral(config *AppPorterRunSharedConfig, namespace, name, container string, args []string) error {
  399. existing, err := appGetExistingPod(config, name, namespace)
  400. if err != nil {
  401. return err
  402. }
  403. newPod, err := appCreateEphemeralPodFromExisting(config, existing, container, args)
  404. if err != nil {
  405. return err
  406. }
  407. podName := newPod.ObjectMeta.Name
  408. // delete the ephemeral pod no matter what
  409. defer appDeletePod(config, podName, namespace)
  410. color.New(color.FgYellow).Printf("Waiting for pod %s to be ready...", podName)
  411. if err = appWaitForPod(config, newPod); err != nil {
  412. color.New(color.FgRed).Println("failed")
  413. return appHandlePodAttachError(err, config, namespace, podName, container)
  414. }
  415. err = appCheckForPodDeletionCronJob(config)
  416. if err != nil {
  417. return err
  418. }
  419. // refresh pod info for latest status
  420. newPod, err = config.Clientset.CoreV1().
  421. Pods(newPod.Namespace).
  422. Get(context.Background(), newPod.Name, metav1.GetOptions{})
  423. // pod exited while we were waiting. maybe an error maybe not.
  424. // we dont know if the user wanted an interactive shell or not.
  425. // if it was an error the logs hopefully say so.
  426. if appIsPodExited(newPod) {
  427. color.New(color.FgGreen).Println("complete!")
  428. var writtenBytes int64
  429. writtenBytes, _ = appPipePodLogsToStdout(config, namespace, podName, container, false)
  430. if appVerbose || writtenBytes == 0 {
  431. color.New(color.FgYellow).Println("Could not get logs. Pod events:")
  432. appPipeEventsToStdout(config, namespace, podName, container, false)
  433. }
  434. return nil
  435. }
  436. color.New(color.FgGreen).Println("ready!")
  437. color.New(color.FgYellow).Println("Attempting connection to the container. If you don't see a command prompt, try pressing enter.")
  438. req := config.RestClient.Post().
  439. Resource("pods").
  440. Name(podName).
  441. Namespace(namespace).
  442. SubResource("attach")
  443. req.Param("stdin", "true")
  444. req.Param("stdout", "true")
  445. req.Param("tty", "true")
  446. req.Param("container", container)
  447. t := term.TTY{
  448. In: os.Stdin,
  449. Out: os.Stdout,
  450. Raw: true,
  451. }
  452. size := t.GetSize()
  453. sizeQueue := t.MonitorSize(size)
  454. if err = t.Safe(func() error {
  455. exec, err := remotecommand.NewSPDYExecutor(config.RestConf, "POST", req.URL())
  456. if err != nil {
  457. return err
  458. }
  459. return exec.Stream(remotecommand.StreamOptions{
  460. Stdin: os.Stdin,
  461. Stdout: os.Stdout,
  462. Stderr: os.Stderr,
  463. Tty: true,
  464. TerminalSizeQueue: sizeQueue,
  465. })
  466. }); err != nil {
  467. // ugly way to catch no TTY errors, such as when running command "echo \"hello\""
  468. return appHandlePodAttachError(err, config, namespace, podName, container)
  469. }
  470. if appVerbose {
  471. color.New(color.FgYellow).Println("Pod events:")
  472. appPipeEventsToStdout(config, namespace, podName, container, false)
  473. }
  474. return err
  475. }
  476. func appCheckForPodDeletionCronJob(config *AppPorterRunSharedConfig) error {
  477. // try and create the cron job and all of the other required resources as necessary,
  478. // starting with the service account, then role and then a role binding
  479. err := appCheckForServiceAccount(config)
  480. if err != nil {
  481. return err
  482. }
  483. err = appCheckForClusterRole(config)
  484. if err != nil {
  485. return err
  486. }
  487. err = appCheckForRoleBinding(config)
  488. if err != nil {
  489. return err
  490. }
  491. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  492. if err != nil {
  493. return err
  494. }
  495. for _, namespace := range namespaces.Items {
  496. cronJobs, err := config.Clientset.BatchV1().CronJobs(namespace.Name).List(
  497. context.Background(), metav1.ListOptions{},
  498. )
  499. if err != nil {
  500. return err
  501. }
  502. if namespace.Name == "default" {
  503. for _, cronJob := range cronJobs.Items {
  504. if cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  505. return nil
  506. }
  507. }
  508. } else {
  509. for _, cronJob := range cronJobs.Items {
  510. if cronJob.Name == "porter-ephemeral-pod-deletion-cronjob" {
  511. err = config.Clientset.BatchV1().CronJobs(namespace.Name).Delete(
  512. context.Background(), cronJob.Name, metav1.DeleteOptions{},
  513. )
  514. if err != nil {
  515. return err
  516. }
  517. }
  518. }
  519. }
  520. }
  521. // create the cronjob
  522. cronJob := &batchv1.CronJob{
  523. ObjectMeta: metav1.ObjectMeta{
  524. Name: "porter-ephemeral-pod-deletion-cronjob",
  525. },
  526. Spec: batchv1.CronJobSpec{
  527. Schedule: "0 * * * *",
  528. JobTemplate: batchv1.JobTemplateSpec{
  529. Spec: batchv1.JobSpec{
  530. Template: v1.PodTemplateSpec{
  531. Spec: v1.PodSpec{
  532. ServiceAccountName: "porter-ephemeral-pod-deletion-service-account",
  533. RestartPolicy: v1.RestartPolicyNever,
  534. Containers: []v1.Container{
  535. {
  536. Name: "ephemeral-pods-manager",
  537. Image: "public.ecr.aws/o1j4x7p4/porter-ephemeral-pods-manager:latest",
  538. ImagePullPolicy: v1.PullAlways,
  539. Args: []string{"delete"},
  540. },
  541. },
  542. },
  543. },
  544. },
  545. },
  546. },
  547. }
  548. _, err = config.Clientset.BatchV1().CronJobs("default").Create(
  549. context.Background(), cronJob, metav1.CreateOptions{},
  550. )
  551. if err != nil {
  552. return err
  553. }
  554. return nil
  555. }
  556. func appCheckForServiceAccount(config *AppPorterRunSharedConfig) error {
  557. namespaces, err := config.Clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
  558. if err != nil {
  559. return err
  560. }
  561. for _, namespace := range namespaces.Items {
  562. serviceAccounts, err := config.Clientset.CoreV1().ServiceAccounts(namespace.Name).List(
  563. context.Background(), metav1.ListOptions{},
  564. )
  565. if err != nil {
  566. return err
  567. }
  568. if namespace.Name == "default" {
  569. for _, svcAccount := range serviceAccounts.Items {
  570. if svcAccount.Name == "porter-ephemeral-pod-deletion-service-account" {
  571. return nil
  572. }
  573. }
  574. } else {
  575. for _, svcAccount := range serviceAccounts.Items {
  576. if svcAccount.Name == "porter-ephemeral-pod-deletion-service-account" {
  577. err = config.Clientset.CoreV1().ServiceAccounts(namespace.Name).Delete(
  578. context.Background(), svcAccount.Name, metav1.DeleteOptions{},
  579. )
  580. if err != nil {
  581. return err
  582. }
  583. }
  584. }
  585. }
  586. }
  587. serviceAccount := &v1.ServiceAccount{
  588. ObjectMeta: metav1.ObjectMeta{
  589. Name: "porter-ephemeral-pod-deletion-service-account",
  590. },
  591. }
  592. _, err = config.Clientset.CoreV1().ServiceAccounts("default").Create(
  593. context.Background(), serviceAccount, metav1.CreateOptions{},
  594. )
  595. if err != nil {
  596. return err
  597. }
  598. return nil
  599. }
  600. func appCheckForClusterRole(config *AppPorterRunSharedConfig) error {
  601. roles, err := config.Clientset.RbacV1().ClusterRoles().List(
  602. context.Background(), metav1.ListOptions{},
  603. )
  604. if err != nil {
  605. return err
  606. }
  607. for _, role := range roles.Items {
  608. if role.Name == "porter-ephemeral-pod-deletion-cluster-role" {
  609. return nil
  610. }
  611. }
  612. role := &rbacv1.ClusterRole{
  613. ObjectMeta: metav1.ObjectMeta{
  614. Name: "porter-ephemeral-pod-deletion-cluster-role",
  615. },
  616. Rules: []rbacv1.PolicyRule{
  617. {
  618. APIGroups: []string{""},
  619. Resources: []string{"pods"},
  620. Verbs: []string{"list", "delete"},
  621. },
  622. {
  623. APIGroups: []string{""},
  624. Resources: []string{"namespaces"},
  625. Verbs: []string{"list"},
  626. },
  627. },
  628. }
  629. _, err = config.Clientset.RbacV1().ClusterRoles().Create(
  630. context.Background(), role, metav1.CreateOptions{},
  631. )
  632. if err != nil {
  633. return err
  634. }
  635. return nil
  636. }
  637. func appCheckForRoleBinding(config *AppPorterRunSharedConfig) error {
  638. bindings, err := config.Clientset.RbacV1().ClusterRoleBindings().List(
  639. context.Background(), metav1.ListOptions{},
  640. )
  641. if err != nil {
  642. return err
  643. }
  644. for _, binding := range bindings.Items {
  645. if binding.Name == "porter-ephemeral-pod-deletion-cluster-rolebinding" {
  646. return nil
  647. }
  648. }
  649. binding := &rbacv1.ClusterRoleBinding{
  650. ObjectMeta: metav1.ObjectMeta{
  651. Name: "porter-ephemeral-pod-deletion-cluster-rolebinding",
  652. },
  653. RoleRef: rbacv1.RoleRef{
  654. APIGroup: "rbac.authorization.k8s.io",
  655. Kind: "ClusterRole",
  656. Name: "porter-ephemeral-pod-deletion-cluster-role",
  657. },
  658. Subjects: []rbacv1.Subject{
  659. {
  660. APIGroup: "",
  661. Kind: "ServiceAccount",
  662. Name: "porter-ephemeral-pod-deletion-service-account",
  663. Namespace: "default",
  664. },
  665. },
  666. }
  667. _, err = config.Clientset.RbacV1().ClusterRoleBindings().Create(
  668. context.Background(), binding, metav1.CreateOptions{},
  669. )
  670. if err != nil {
  671. return err
  672. }
  673. return nil
  674. }
  675. func appWaitForPod(config *AppPorterRunSharedConfig, pod *v1.Pod) error {
  676. var (
  677. w watch.Interface
  678. err error
  679. ok bool
  680. )
  681. // immediately after creating a pod, the API may return a 404. heuristically 1
  682. // second seems to be plenty.
  683. watchRetries := 3
  684. for i := 0; i < watchRetries; i++ {
  685. selector := fields.OneTermEqualSelector("metadata.name", pod.Name).String()
  686. w, err = config.Clientset.CoreV1().
  687. Pods(pod.Namespace).
  688. Watch(context.Background(), metav1.ListOptions{FieldSelector: selector})
  689. if err == nil {
  690. break
  691. }
  692. time.Sleep(time.Second)
  693. }
  694. if err != nil {
  695. return err
  696. }
  697. defer w.Stop()
  698. for {
  699. select {
  700. case <-time.Tick(time.Second):
  701. // poll every second in case we already missed the ready event while
  702. // creating the listener.
  703. pod, err = config.Clientset.CoreV1().
  704. Pods(pod.Namespace).
  705. Get(context.Background(), pod.Name, metav1.GetOptions{})
  706. if appIsPodReady(pod) || appIsPodExited(pod) {
  707. return nil
  708. }
  709. case evt := <-w.ResultChan():
  710. pod, ok = evt.Object.(*v1.Pod)
  711. if !ok {
  712. return fmt.Errorf("unexpected object type: %T", evt.Object)
  713. }
  714. if appIsPodReady(pod) || appIsPodExited(pod) {
  715. return nil
  716. }
  717. case <-time.After(time.Second * 10):
  718. return errors.New("timed out waiting for pod")
  719. }
  720. }
  721. }
  722. func appIsPodReady(pod *v1.Pod) bool {
  723. ready := false
  724. conditions := pod.Status.Conditions
  725. for i := range conditions {
  726. if conditions[i].Type == v1.PodReady {
  727. ready = pod.Status.Conditions[i].Status == v1.ConditionTrue
  728. }
  729. }
  730. return ready
  731. }
  732. func appIsPodExited(pod *v1.Pod) bool {
  733. return pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed
  734. }
  735. func appHandlePodAttachError(err error, config *AppPorterRunSharedConfig, namespace, podName, container string) error {
  736. if appVerbose {
  737. color.New(color.FgYellow).Fprintf(os.Stderr, "Error: %s\n", err)
  738. }
  739. color.New(color.FgYellow).Fprintln(os.Stderr, "Could not open a shell to this container. Container logs:")
  740. var writtenBytes int64
  741. writtenBytes, _ = appPipePodLogsToStdout(config, namespace, podName, container, false)
  742. if appVerbose || writtenBytes == 0 {
  743. color.New(color.FgYellow).Fprintln(os.Stderr, "Could not get logs. Pod events:")
  744. appPipeEventsToStdout(config, namespace, podName, container, false)
  745. }
  746. return err
  747. }
  748. func appPipePodLogsToStdout(config *AppPorterRunSharedConfig, namespace, name, container string, follow bool) (int64, error) {
  749. podLogOpts := v1.PodLogOptions{
  750. Container: container,
  751. Follow: follow,
  752. }
  753. req := config.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  754. podLogs, err := req.Stream(
  755. context.Background(),
  756. )
  757. if err != nil {
  758. return 0, err
  759. }
  760. defer podLogs.Close()
  761. return io.Copy(os.Stdout, podLogs)
  762. }
  763. func appPipeEventsToStdout(config *AppPorterRunSharedConfig, namespace, name, container string, follow bool) error {
  764. // update the config in case the operation has taken longer than token expiry time
  765. config.setSharedConfig()
  766. // creates the clientset
  767. resp, err := config.Clientset.CoreV1().Events(namespace).List(
  768. context.TODO(),
  769. metav1.ListOptions{
  770. FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.namespace=%s", name, namespace),
  771. },
  772. )
  773. if err != nil {
  774. return err
  775. }
  776. for _, event := range resp.Items {
  777. color.New(color.FgRed).Println(event.Message)
  778. }
  779. return nil
  780. }
  781. func appGetExistingPod(config *AppPorterRunSharedConfig, name, namespace string) (*v1.Pod, error) {
  782. return config.Clientset.CoreV1().Pods(namespace).Get(
  783. context.Background(),
  784. name,
  785. metav1.GetOptions{},
  786. )
  787. }
  788. func appDeletePod(config *AppPorterRunSharedConfig, name, namespace string) error {
  789. // update the config in case the operation has taken longer than token expiry time
  790. config.setSharedConfig()
  791. err := config.Clientset.CoreV1().Pods(namespace).Delete(
  792. context.Background(),
  793. name,
  794. metav1.DeleteOptions{},
  795. )
  796. if err != nil {
  797. color.New(color.FgRed).Fprintf(os.Stderr, "Could not delete ephemeral pod: %s\n", err.Error())
  798. return err
  799. }
  800. color.New(color.FgGreen).Println("Sucessfully deleted ephemeral pod")
  801. return nil
  802. }
  803. func appCreateEphemeralPodFromExisting(
  804. config *AppPorterRunSharedConfig,
  805. existing *v1.Pod,
  806. container string,
  807. args []string,
  808. ) (*v1.Pod, error) {
  809. newPod := existing.DeepCopy()
  810. // only copy the pod spec, overwrite metadata
  811. newPod.ObjectMeta = metav1.ObjectMeta{
  812. Name: strings.ToLower(fmt.Sprintf("%s-copy-%s", existing.ObjectMeta.Name, utils.String(4))),
  813. Namespace: existing.ObjectMeta.Namespace,
  814. }
  815. newPod.Status = v1.PodStatus{}
  816. // set restart policy to never
  817. newPod.Spec.RestartPolicy = v1.RestartPolicyNever
  818. // change the command in the pod to the passed in pod command
  819. cmdRoot := args[0]
  820. cmdArgs := make([]string, 0)
  821. // annotate with the ephemeral pod tag
  822. newPod.Labels = make(map[string]string)
  823. newPod.Labels["porter/ephemeral-pod"] = "true"
  824. if len(args) > 1 {
  825. cmdArgs = args[1:]
  826. }
  827. for i := 0; i < len(newPod.Spec.Containers); i++ {
  828. if newPod.Spec.Containers[i].Name == container {
  829. newPod.Spec.Containers[i].Command = []string{cmdRoot}
  830. newPod.Spec.Containers[i].Args = cmdArgs
  831. newPod.Spec.Containers[i].TTY = true
  832. newPod.Spec.Containers[i].Stdin = true
  833. newPod.Spec.Containers[i].StdinOnce = true
  834. var newCpu int
  835. if appCpuMilli != 0 {
  836. newCpu = appCpuMilli
  837. } else if newPod.Spec.Containers[i].Resources.Requests.Cpu() != nil && newPod.Spec.Containers[i].Resources.Requests.Cpu().MilliValue() > 500 {
  838. newCpu = 500
  839. }
  840. if newCpu != 0 {
  841. newPod.Spec.Containers[i].Resources.Limits[v1.ResourceCPU] = resource.MustParse(fmt.Sprintf("%dm", newCpu))
  842. newPod.Spec.Containers[i].Resources.Requests[v1.ResourceCPU] = resource.MustParse(fmt.Sprintf("%dm", newCpu))
  843. for j := 0; j < len(newPod.Spec.Containers[i].Env); j++ {
  844. if newPod.Spec.Containers[i].Env[j].Name == "PORTER_RESOURCES_CPU" {
  845. newPod.Spec.Containers[i].Env[j].Value = fmt.Sprintf("%dm", newCpu)
  846. break
  847. }
  848. }
  849. }
  850. var newMemory int
  851. if appMemoryMi != 0 {
  852. newMemory = appMemoryMi
  853. } else if newPod.Spec.Containers[i].Resources.Requests.Memory() != nil && newPod.Spec.Containers[i].Resources.Requests.Memory().Value() > 1000*1024*1024 {
  854. newMemory = 1000
  855. }
  856. if newMemory != 0 {
  857. newPod.Spec.Containers[i].Resources.Limits[v1.ResourceMemory] = resource.MustParse(fmt.Sprintf("%dMi", newMemory))
  858. newPod.Spec.Containers[i].Resources.Requests[v1.ResourceMemory] = resource.MustParse(fmt.Sprintf("%dMi", newMemory))
  859. for j := 0; j < len(newPod.Spec.Containers[i].Env); j++ {
  860. if newPod.Spec.Containers[i].Env[j].Name == "PORTER_RESOURCES_RAM" {
  861. newPod.Spec.Containers[i].Env[j].Value = fmt.Sprintf("%dMi", newMemory)
  862. break
  863. }
  864. }
  865. }
  866. }
  867. // remove health checks and probes
  868. newPod.Spec.Containers[i].LivenessProbe = nil
  869. newPod.Spec.Containers[i].ReadinessProbe = nil
  870. newPod.Spec.Containers[i].StartupProbe = nil
  871. }
  872. newPod.Spec.NodeName = ""
  873. // create the pod and return it
  874. return config.Clientset.CoreV1().Pods(existing.ObjectMeta.Namespace).Create(
  875. context.Background(),
  876. newPod,
  877. metav1.CreateOptions{},
  878. )
  879. }
  880. func appUpdateTag(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  881. namespace := fmt.Sprintf("porter-stack-%s", args[0])
  882. if appTag == "" {
  883. appTag = "latest"
  884. }
  885. release, err := client.GetRelease(context.TODO(), cliConf.Project, cliConf.Cluster, namespace, args[0])
  886. if err != nil {
  887. return fmt.Errorf("Unable to find application %s", args[0])
  888. }
  889. repository, ok := release.Config["global"].(map[string]interface{})["image"].(map[string]interface{})["repository"].(string)
  890. if !ok || repository == "" {
  891. return fmt.Errorf("Application %s does not have an associated image repository. Unable to update tag", args[0])
  892. }
  893. imageInfo := types.ImageInfo{
  894. Repository: repository,
  895. Tag: appTag,
  896. }
  897. createUpdatePorterAppRequest := &types.CreatePorterAppRequest{
  898. ClusterID: cliConf.Cluster,
  899. ProjectID: cliConf.Project,
  900. ImageInfo: imageInfo,
  901. OverrideRelease: false,
  902. }
  903. color.New(color.FgGreen).Printf("Updating application %s to build using tag \"%s\"\n", args[0], appTag)
  904. _, err = client.CreatePorterApp(
  905. context.Background(),
  906. cliConf.Project,
  907. cliConf.Cluster,
  908. args[0],
  909. createUpdatePorterAppRequest,
  910. )
  911. if err != nil {
  912. return fmt.Errorf("Unable to update application %s: %w", args[0], err)
  913. }
  914. color.New(color.FgGreen).Printf("Successfully updated application %s to use tag \"%s\"\n", args[0], appTag)
  915. return nil
  916. }