app.go 34 KB

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