app.go 37 KB

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