app.go 40 KB

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