app.go 46 KB

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