app.go 38 KB

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