app.go 47 KB

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