app.go 44 KB

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