app.go 29 KB

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