app.go 38 KB

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