app.go 47 KB

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