app.go 29 KB

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