deploy.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "sort"
  8. "strings"
  9. "time"
  10. v2 "github.com/porter-dev/porter/cli/cmd/v2"
  11. "github.com/briandowns/spinner"
  12. "github.com/fatih/color"
  13. api "github.com/porter-dev/porter/api/client"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/cli/cmd/config"
  16. "github.com/porter-dev/porter/cli/cmd/deploy"
  17. "github.com/porter-dev/porter/cli/cmd/docker"
  18. "github.com/porter-dev/porter/cli/cmd/utils"
  19. templaterUtils "github.com/porter-dev/porter/internal/templater/utils"
  20. "github.com/spf13/cobra"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/client-go/util/homedir"
  23. )
  24. // updateCmd represents the "porter update" base command when called
  25. // without any subcommands
  26. var updateCmd = &cobra.Command{
  27. Use: "update",
  28. Short: "Builds and updates a specified application given by the --app flag.",
  29. Long: fmt.Sprintf(`
  30. %s
  31. Builds and updates a specified application given by the --app flag. For example:
  32. %s
  33. This command will automatically build from a local path. The path can be configured via the
  34. --path flag. You can also overwrite the tag using the --tag flag. For example, to build from the
  35. local directory ~/path-to-dir with the tag "testing":
  36. %s
  37. If the application has a remote Git repository source configured, you can specify that the remote
  38. Git repository should be used to build the new image by specifying "--source github". Porter will use
  39. the latest commit from the remote repo and branch to update an application, and will use the latest
  40. commit as the image tag.
  41. %s
  42. To add new configuration or update existing configuration, you can pass a values.yaml file in via the
  43. --values flag. For example;
  44. %s
  45. If your application is set up to use a Dockerfile by default, you can use a buildpack via the flag
  46. "--method pack". Conversely, if your application is set up to use a buildpack by default, you can
  47. use a Dockerfile by passing the flag "--method docker". You can specify the relative path to a Dockerfile
  48. in your remote Git repository. For example, if a Dockerfile is found at ./docker/prod.Dockerfile, you can
  49. specify it as follows:
  50. %s
  51. `,
  52. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update\":"),
  53. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app"),
  54. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --path ~/path-to-dir --tag testing"),
  55. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app remote-git-app --source github"),
  56. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --values my-values.yaml"),
  57. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --method docker --dockerfile ./docker/prod.Dockerfile"),
  58. ),
  59. Run: func(cmd *cobra.Command, args []string) {
  60. err := checkLoginAndRun(args, updateFull)
  61. if err != nil {
  62. os.Exit(1)
  63. }
  64. },
  65. }
  66. var updateGetEnvCmd = &cobra.Command{
  67. Use: "get-env",
  68. Short: "Gets environment variables for a deployment for a specified application given by the --app flag.",
  69. Long: fmt.Sprintf(`
  70. %s
  71. Gets environment variables for a deployment for a specified application given by the --app
  72. flag. By default, env variables are printed via stdout for use in downstream commands:
  73. %s
  74. Output can also be written to a file via the --file flag, which should specify the
  75. destination path for a .env file. For example:
  76. %s
  77. `,
  78. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update get-env\":"),
  79. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app | xargs"),
  80. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app --file .env"),
  81. ),
  82. Run: func(cmd *cobra.Command, args []string) {
  83. err := checkLoginAndRun(args, updateGetEnv)
  84. if err != nil {
  85. os.Exit(1)
  86. }
  87. },
  88. }
  89. var updateBuildCmd = &cobra.Command{
  90. Use: "build",
  91. Short: "Builds a new version of the application specified by the --app flag.",
  92. Long: fmt.Sprintf(`
  93. %s
  94. Builds a new version of the application specified by the --app flag. Depending on the
  95. configured settings, this command may work automatically or will require a specified
  96. --method flag.
  97. If you have configured the Dockerfile path and/or a build context for this application,
  98. this command will by default use those settings, so you just need to specify the --app
  99. flag:
  100. %s
  101. If you have not linked the build-time requirements for this application, the command will
  102. use a local build. By default, the cloud-native buildpacks builder will automatically be run
  103. from the current directory. If you would like to change the build method, you can do so by
  104. using the --method flag, for example:
  105. %s
  106. When using "--method docker", you can specify the path to the Dockerfile using the
  107. --dockerfile flag. This will also override the Dockerfile path that you may have linked
  108. for the application:
  109. %s
  110. `,
  111. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update build\":"),
  112. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app"),
  113. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker"),
  114. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker --dockerfile ./prod.Dockerfile"),
  115. ),
  116. Run: func(cmd *cobra.Command, args []string) {
  117. err := checkLoginAndRun(args, updateBuild)
  118. if err != nil {
  119. os.Exit(1)
  120. }
  121. },
  122. }
  123. var updatePushCmd = &cobra.Command{
  124. Use: "push",
  125. Short: "Pushes an image to a Docker registry linked to your Porter project.",
  126. Args: cobra.MaximumNArgs(1),
  127. Long: fmt.Sprintf(`
  128. %s
  129. Pushes a local Docker image to a registry linked to your Porter project. This command
  130. requires the project ID to be set either by using the %s command
  131. or the --project flag. For example, to push a local nginx image:
  132. %s
  133. %s
  134. Pushes a new image for an application specified by the --app flag. This command uses
  135. the image repository saved in the application config by default. For example, if an
  136. application "nginx" was created from the image repo "gcr.io/snowflake-123456/nginx",
  137. the following command would push the image "gcr.io/snowflake-123456/nginx:new-tag":
  138. %s
  139. This command will not use your pre-saved authentication set up via "docker login," so if you
  140. are using an image registry that was created outside of Porter, make sure that you have
  141. linked it via "porter connect".
  142. `,
  143. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update push\":"),
  144. color.New(color.FgBlue).Sprintf("porter config set-project"),
  145. color.New(color.FgGreen, color.Bold).Sprintf("porter update push gcr.io/snowflake-123456/nginx:1234567"),
  146. color.New(color.Bold).Sprintf("LEGACY USAGE:"),
  147. color.New(color.FgGreen, color.Bold).Sprintf("porter update push --app nginx --tag new-tag"),
  148. ),
  149. Run: func(cmd *cobra.Command, args []string) {
  150. err := checkLoginAndRun(args, updatePush)
  151. if err != nil {
  152. os.Exit(1)
  153. }
  154. },
  155. }
  156. var updateConfigCmd = &cobra.Command{
  157. Use: "config",
  158. Short: "Updates the configuration for an application specified by the --app flag.",
  159. Long: fmt.Sprintf(`
  160. %s
  161. Updates the configuration for an application specified by the --app flag, using the configuration
  162. given by the --values flag. This will trigger a new deployment for the application with
  163. new configuration set. Note that this will merge your existing configuration with configuration
  164. specified in the --values file. For example:
  165. %s
  166. You can update the configuration with only a new tag with the --tag flag, which will only update
  167. the image that the application uses if no --values file is specified:
  168. %s
  169. `,
  170. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update config\":"),
  171. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --values my-values.yaml"),
  172. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --tag custom-tag"),
  173. ),
  174. Run: func(cmd *cobra.Command, args []string) {
  175. err := checkLoginAndRun(args, updateUpgrade)
  176. if err != nil {
  177. os.Exit(1)
  178. }
  179. },
  180. }
  181. var updateEnvGroupCmd = &cobra.Command{
  182. Use: "env-group",
  183. Aliases: []string{"eg", "envgroup", "env-groups", "envgroups"},
  184. Short: "Updates an environment group's variables, specified by the --name flag.",
  185. Run: func(cmd *cobra.Command, args []string) {
  186. color.New(color.FgRed).Fprintln(os.Stderr, "need to specify an operation to continue")
  187. },
  188. }
  189. var updateSetEnvGroupCmd = &cobra.Command{
  190. Use: "set",
  191. Short: "Sets the desired value of an environment variable in an env group in the form VAR=VALUE.",
  192. Args: cobra.MaximumNArgs(1),
  193. Run: func(cmd *cobra.Command, args []string) {
  194. err := checkLoginAndRun(args, updateSetEnvGroup)
  195. if err != nil {
  196. os.Exit(1)
  197. }
  198. },
  199. }
  200. var updateUnsetEnvGroupCmd = &cobra.Command{
  201. Use: "unset",
  202. Short: "Removes an environment variable from an env group.",
  203. Args: cobra.MinimumNArgs(1),
  204. Run: func(cmd *cobra.Command, args []string) {
  205. err := checkLoginAndRun(args, updateUnsetEnvGroup)
  206. if err != nil {
  207. os.Exit(1)
  208. }
  209. },
  210. }
  211. var (
  212. app string
  213. getEnvFileDest string
  214. localPath string
  215. tag string
  216. dockerfile string
  217. method string
  218. stream bool
  219. buildFlagsEnv []string
  220. forcePush bool
  221. useCache bool
  222. version uint
  223. varType string
  224. normalEnvGroupVars []string
  225. secretEnvGroupVars []string
  226. waitForSuccessfulDeploy bool
  227. )
  228. func init() {
  229. buildFlagsEnv = []string{}
  230. rootCmd.AddCommand(updateCmd)
  231. updateCmd.PersistentFlags().StringVar(
  232. &app,
  233. "app",
  234. "",
  235. "Application in the Porter dashboard",
  236. )
  237. updateCmd.PersistentFlags().BoolVar(
  238. &useCache,
  239. "use-cache",
  240. false,
  241. "Whether to use cache (currently in beta)",
  242. )
  243. updateCmd.PersistentFlags().StringVar(
  244. &namespace,
  245. "namespace",
  246. "default",
  247. "Namespace of the application",
  248. )
  249. updateCmd.PersistentFlags().StringVar(
  250. &source,
  251. "source",
  252. "local",
  253. "the type of source (\"local\" or \"github\")",
  254. )
  255. updateCmd.PersistentFlags().StringVarP(
  256. &localPath,
  257. "path",
  258. "p",
  259. "",
  260. "If local build, the path to the build directory. If remote build, the relative path from the repository root to the build directory.",
  261. )
  262. updateCmd.PersistentFlags().StringVarP(
  263. &tag,
  264. "tag",
  265. "t",
  266. "",
  267. "the specified tag to use, if not \"latest\"",
  268. )
  269. updateCmd.PersistentFlags().StringVarP(
  270. &values,
  271. "values",
  272. "v",
  273. "",
  274. "Filepath to a values.yaml file",
  275. )
  276. updateCmd.PersistentFlags().StringVar(
  277. &dockerfile,
  278. "dockerfile",
  279. "",
  280. "the path to the dockerfile",
  281. )
  282. updateCmd.PersistentFlags().StringArrayVarP(
  283. &buildFlagsEnv,
  284. "env",
  285. "e",
  286. []string{},
  287. "Build-time environment variable, in the form 'VAR=VALUE'. These are not available at image runtime.",
  288. )
  289. updateCmd.PersistentFlags().StringVar(
  290. &method,
  291. "method",
  292. "",
  293. "the build method to use (\"docker\" or \"pack\")",
  294. )
  295. updateCmd.PersistentFlags().BoolVar(
  296. &stream,
  297. "stream",
  298. false,
  299. "stream update logs to porter dashboard",
  300. )
  301. updateCmd.PersistentFlags().BoolVar(
  302. &forceBuild,
  303. "force-build",
  304. false,
  305. "set this to force build an image (images tagged with \"latest\" have this set by default)",
  306. )
  307. updateCmd.PersistentFlags().BoolVar(
  308. &forcePush,
  309. "force-push",
  310. false,
  311. "set this to force push an image (images tagged with \"latest\" have this set by default)",
  312. )
  313. updateCmd.PersistentFlags().MarkDeprecated("force-build", "--force-build is now deprecated")
  314. updateCmd.PersistentFlags().MarkDeprecated("force-push", "--force-push is now deprecated")
  315. updateCmd.PersistentFlags().BoolVar(
  316. &waitForSuccessfulDeploy,
  317. "wait",
  318. false,
  319. "set this to wait and be notified when a deployment is successful, otherwise time out",
  320. )
  321. updateCmd.AddCommand(updateGetEnvCmd)
  322. updateGetEnvCmd.PersistentFlags().StringVar(
  323. &getEnvFileDest,
  324. "file",
  325. "",
  326. "file destination for .env files",
  327. )
  328. updateGetEnvCmd.MarkPersistentFlagRequired("app")
  329. updateBuildCmd.MarkPersistentFlagRequired("app")
  330. updateConfigCmd.MarkPersistentFlagRequired("app")
  331. updateEnvGroupCmd.PersistentFlags().StringVar(
  332. &name,
  333. "name",
  334. "",
  335. "the name of the environment group",
  336. )
  337. updateEnvGroupCmd.PersistentFlags().UintVar(
  338. &version,
  339. "version",
  340. 0,
  341. "the version of the environment group",
  342. )
  343. updateEnvGroupCmd.MarkPersistentFlagRequired("name")
  344. updateSetEnvGroupCmd.PersistentFlags().StringVar(
  345. &varType,
  346. "type",
  347. "normal",
  348. "the type of environment variable (either \"normal\" or \"secret\")",
  349. )
  350. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  351. &normalEnvGroupVars,
  352. "normal",
  353. "n",
  354. []string{},
  355. "list of variables to set, in the form VAR=VALUE",
  356. )
  357. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  358. &secretEnvGroupVars,
  359. "secret",
  360. "s",
  361. []string{},
  362. "list of secret variables to set, in the form VAR=VALUE",
  363. )
  364. updateEnvGroupCmd.AddCommand(updateSetEnvGroupCmd)
  365. updateEnvGroupCmd.AddCommand(updateUnsetEnvGroupCmd)
  366. updateCmd.AddCommand(updateBuildCmd)
  367. updateCmd.AddCommand(updatePushCmd)
  368. updateCmd.AddCommand(updateConfigCmd)
  369. updateCmd.AddCommand(updateEnvGroupCmd)
  370. }
  371. func updateFull(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  372. ctx := context.Background()
  373. project, err := client.GetProject(ctx, cliConf.Project)
  374. if err != nil {
  375. return fmt.Errorf("could not retrieve project from Porter API. Please contact support@porter.run")
  376. }
  377. if project.ValidateApplyV2 {
  378. err = v2.UpdateFull(ctx)
  379. if err != nil {
  380. return err
  381. }
  382. return nil
  383. }
  384. fullPath, err := filepath.Abs(localPath)
  385. if err != nil {
  386. return err
  387. }
  388. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  389. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  390. if err != nil {
  391. return err
  392. }
  393. if !proceed {
  394. return nil
  395. }
  396. }
  397. color.New(color.FgGreen).Println("Deploying app:", app)
  398. updateAgent, err := updateGetAgent(client)
  399. if err != nil {
  400. return err
  401. }
  402. err = updateBuildWithAgent(updateAgent)
  403. if err != nil {
  404. return err
  405. }
  406. err = updatePushWithAgent(updateAgent)
  407. if err != nil {
  408. return err
  409. }
  410. err = updateUpgradeWithAgent(updateAgent)
  411. if err != nil {
  412. return err
  413. }
  414. if waitForSuccessfulDeploy {
  415. // solves timing issue where replicasets were not on the cluster, before our initial check
  416. time.Sleep(10 * time.Second)
  417. err := checkDeploymentStatus(client)
  418. if err != nil {
  419. return err
  420. }
  421. }
  422. return nil
  423. }
  424. func updateGetEnv(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  425. updateAgent, err := updateGetAgent(client)
  426. if err != nil {
  427. return err
  428. }
  429. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  430. UseNewConfig: false,
  431. })
  432. if err != nil {
  433. return err
  434. }
  435. // set the environment variables in the process
  436. err = updateAgent.SetBuildEnv(buildEnv)
  437. if err != nil {
  438. return err
  439. }
  440. // write the environment variables to either a file or stdout (stdout by default)
  441. return updateAgent.WriteBuildEnv(getEnvFileDest)
  442. }
  443. func updateBuild(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  444. ctx := context.Background()
  445. project, err := client.GetProject(ctx, cliConf.Project)
  446. if err != nil {
  447. return fmt.Errorf("could not retrieve project from Porter API. Please contact support@porter.run")
  448. }
  449. if project.ValidateApplyV2 {
  450. err = v2.UpdateBuild(ctx)
  451. if err != nil {
  452. return err
  453. }
  454. return nil
  455. }
  456. updateAgent, err := updateGetAgent(client)
  457. if err != nil {
  458. return err
  459. }
  460. return updateBuildWithAgent(updateAgent)
  461. }
  462. func updatePush(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  463. if app == "" {
  464. if len(args) == 0 {
  465. return fmt.Errorf("please provide the docker image name")
  466. }
  467. image := args[0]
  468. registries, err := client.ListRegistries(context.Background(), cliConf.Project)
  469. if err != nil {
  470. return err
  471. }
  472. regs := *registries
  473. regID := uint(0)
  474. for _, reg := range regs {
  475. if strings.Contains(image, reg.URL) {
  476. regID = reg.ID
  477. break
  478. }
  479. }
  480. if regID == 0 {
  481. return fmt.Errorf("could not find registry for image: %s", image)
  482. }
  483. err = client.CreateRepository(context.Background(), cliConf.Project, regID,
  484. &types.CreateRegistryRepositoryRequest{
  485. ImageRepoURI: strings.Split(image, ":")[0],
  486. },
  487. )
  488. if err != nil {
  489. return err
  490. }
  491. agent, err := docker.NewAgentWithAuthGetter(client, cliConf.Project)
  492. if err != nil {
  493. return err
  494. }
  495. err = agent.PushImage(image)
  496. if err != nil {
  497. return err
  498. }
  499. return nil
  500. }
  501. updateAgent, err := updateGetAgent(client)
  502. if err != nil {
  503. return err
  504. }
  505. return updatePushWithAgent(updateAgent)
  506. }
  507. func updateUpgrade(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  508. ctx := context.Background()
  509. project, err := client.GetProject(ctx, cliConf.Project)
  510. if err != nil {
  511. return fmt.Errorf("could not retrieve project from Porter API. Please contact support@porter.run")
  512. }
  513. if project.ValidateApplyV2 {
  514. err = v2.UpdateUpgrade(ctx)
  515. if err != nil {
  516. return err
  517. }
  518. return nil
  519. }
  520. updateAgent, err := updateGetAgent(client)
  521. if err != nil {
  522. return err
  523. }
  524. err = updateUpgradeWithAgent(updateAgent)
  525. if err != nil {
  526. return err
  527. }
  528. if waitForSuccessfulDeploy {
  529. // solves timing issue where replicasets were not on the cluster, before our initial check
  530. time.Sleep(10 * time.Second)
  531. err := checkDeploymentStatus(client)
  532. if err != nil {
  533. return err
  534. }
  535. }
  536. return nil
  537. }
  538. func updateSetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  539. if len(normalEnvGroupVars) == 0 && len(secretEnvGroupVars) == 0 && len(args) == 0 {
  540. return fmt.Errorf("please provide one or more variables to update")
  541. }
  542. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  543. s.Color("cyan")
  544. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  545. s.Start()
  546. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  547. &types.GetEnvGroupRequest{
  548. Name: name, Version: version,
  549. },
  550. )
  551. s.Stop()
  552. if err != nil {
  553. return err
  554. }
  555. newEnvGroup := &types.CreateEnvGroupRequest{
  556. Name: envGroupResp.Name,
  557. Variables: make(map[string]string),
  558. }
  559. for k, v := range envGroupResp.Variables {
  560. newEnvGroup.Variables[k] = v
  561. }
  562. // first check for multiple variables being set using the -e or -s flags
  563. if len(normalEnvGroupVars) > 0 || len(secretEnvGroupVars) > 0 {
  564. for _, v := range normalEnvGroupVars {
  565. delete(newEnvGroup.Variables, v)
  566. key, value, err := validateVarValue(v)
  567. if err != nil {
  568. return err
  569. }
  570. newEnvGroup.Variables[key] = value
  571. }
  572. if len(secretEnvGroupVars) > 0 {
  573. newEnvGroup.SecretVariables = make(map[string]string)
  574. }
  575. for _, v := range secretEnvGroupVars {
  576. delete(newEnvGroup.Variables, v)
  577. key, value, err := validateVarValue(v)
  578. if err != nil {
  579. return err
  580. }
  581. newEnvGroup.SecretVariables[key] = value
  582. }
  583. s.Suffix = fmt.Sprintf(" Updating env group '%s' in namespace '%s'", name, namespace)
  584. } else { // legacy usage
  585. key, value, err := validateVarValue(args[0])
  586. if err != nil {
  587. return err
  588. }
  589. delete(newEnvGroup.Variables, key)
  590. if varType == "secret" {
  591. newEnvGroup.SecretVariables = make(map[string]string)
  592. newEnvGroup.SecretVariables[key] = value
  593. s.Suffix = fmt.Sprintf(" Adding new secret variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  594. } else {
  595. newEnvGroup.Variables[key] = value
  596. s.Suffix = fmt.Sprintf(" Adding new variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  597. }
  598. }
  599. s.Start()
  600. _, err = client.CreateEnvGroup(
  601. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  602. )
  603. s.Stop()
  604. if err != nil {
  605. return err
  606. }
  607. color.New(color.FgGreen).Println("env group successfully updated")
  608. return nil
  609. }
  610. func validateVarValue(in string) (string, string, error) {
  611. key, value, found := strings.Cut(in, "=")
  612. if !found {
  613. return "", "", fmt.Errorf("%s is not in the form of VAR=VALUE", in)
  614. }
  615. return key, value, nil
  616. }
  617. func updateUnsetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  618. if len(args) == 0 {
  619. return fmt.Errorf("required variable name")
  620. }
  621. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  622. s.Color("cyan")
  623. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  624. s.Start()
  625. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  626. &types.GetEnvGroupRequest{
  627. Name: name, Version: version,
  628. },
  629. )
  630. s.Stop()
  631. if err != nil {
  632. return err
  633. }
  634. newEnvGroup := &types.CreateEnvGroupRequest{
  635. Name: envGroupResp.Name,
  636. Variables: envGroupResp.Variables,
  637. }
  638. for _, v := range args {
  639. delete(newEnvGroup.Variables, v)
  640. }
  641. s.Suffix = fmt.Sprintf(" Removing variables from env group '%s' in namespace '%s'", name, namespace)
  642. s.Start()
  643. _, err = client.CreateEnvGroup(
  644. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  645. )
  646. s.Stop()
  647. if err != nil {
  648. return err
  649. }
  650. color.New(color.FgGreen).Println("env group successfully updated")
  651. return nil
  652. }
  653. // HELPER METHODS
  654. func updateGetAgent(client *api.Client) (*deploy.DeployAgent, error) {
  655. var buildMethod deploy.DeployBuildType
  656. if method != "" {
  657. buildMethod = deploy.DeployBuildType(method)
  658. }
  659. // add additional env, if they exist
  660. additionalEnv := make(map[string]string)
  661. for _, buildEnv := range buildFlagsEnv {
  662. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  663. additionalEnv[strSplArr[0]] = strSplArr[1]
  664. }
  665. }
  666. // initialize the update agent
  667. return deploy.NewDeployAgent(client, app, &deploy.DeployOpts{
  668. SharedOpts: &deploy.SharedOpts{
  669. ProjectID: cliConf.Project,
  670. ClusterID: cliConf.Cluster,
  671. Namespace: namespace,
  672. LocalPath: localPath,
  673. LocalDockerfile: dockerfile,
  674. OverrideTag: tag,
  675. Method: buildMethod,
  676. AdditionalEnv: additionalEnv,
  677. UseCache: useCache,
  678. },
  679. Local: source != "github",
  680. })
  681. }
  682. func updateBuildWithAgent(updateAgent *deploy.DeployAgent) error {
  683. // build the deployment
  684. color.New(color.FgGreen).Println("Building docker image for", app)
  685. if stream {
  686. updateAgent.StreamEvent(types.SubEvent{
  687. EventID: "build",
  688. Name: "Build",
  689. Index: 100,
  690. Status: types.EventStatusInProgress,
  691. Info: "",
  692. })
  693. }
  694. if useCache {
  695. err := config.SetDockerConfig(updateAgent.Client)
  696. if err != nil {
  697. return err
  698. }
  699. }
  700. // read the values if necessary
  701. valuesObj, err := readValuesFile()
  702. if err != nil {
  703. return err
  704. }
  705. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  706. UseNewConfig: true,
  707. NewConfig: valuesObj,
  708. })
  709. if err != nil {
  710. if stream {
  711. // another concern: is it safe to ignore the error here?
  712. updateAgent.StreamEvent(types.SubEvent{
  713. EventID: "build",
  714. Name: "Build",
  715. Index: 110,
  716. Status: types.EventStatusFailed,
  717. Info: err.Error(),
  718. })
  719. }
  720. return err
  721. }
  722. // set the environment variables in the process
  723. err = updateAgent.SetBuildEnv(buildEnv)
  724. if err != nil {
  725. if stream {
  726. updateAgent.StreamEvent(types.SubEvent{
  727. EventID: "build",
  728. Name: "Build",
  729. Index: 120,
  730. Status: types.EventStatusFailed,
  731. Info: err.Error(),
  732. })
  733. }
  734. return err
  735. }
  736. if err := updateAgent.Build(nil); err != nil {
  737. if stream {
  738. updateAgent.StreamEvent(types.SubEvent{
  739. EventID: "build",
  740. Name: "Build",
  741. Index: 130,
  742. Status: types.EventStatusFailed,
  743. Info: err.Error(),
  744. })
  745. }
  746. return err
  747. }
  748. if stream {
  749. updateAgent.StreamEvent(types.SubEvent{
  750. EventID: "build",
  751. Name: "Build",
  752. Index: 140,
  753. Status: types.EventStatusSuccess,
  754. Info: "",
  755. })
  756. }
  757. return nil
  758. }
  759. func updatePushWithAgent(updateAgent *deploy.DeployAgent) error {
  760. if useCache {
  761. color.New(color.FgGreen).Println("Skipping image push for", app, "as use-cache is set")
  762. return nil
  763. }
  764. // push the deployment
  765. color.New(color.FgGreen).Println("Pushing new image for", app)
  766. if stream {
  767. updateAgent.StreamEvent(types.SubEvent{
  768. EventID: "push",
  769. Name: "Push",
  770. Index: 200,
  771. Status: types.EventStatusInProgress,
  772. Info: "",
  773. })
  774. }
  775. if err := updateAgent.Push(); err != nil {
  776. if stream {
  777. updateAgent.StreamEvent(types.SubEvent{
  778. EventID: "push",
  779. Name: "Push",
  780. Index: 210,
  781. Status: types.EventStatusFailed,
  782. Info: err.Error(),
  783. })
  784. }
  785. return err
  786. }
  787. if stream {
  788. updateAgent.StreamEvent(types.SubEvent{
  789. EventID: "push",
  790. Name: "Push",
  791. Index: 220,
  792. Status: types.EventStatusSuccess,
  793. Info: "",
  794. })
  795. }
  796. return nil
  797. }
  798. func updateUpgradeWithAgent(updateAgent *deploy.DeployAgent) error {
  799. // push the deployment
  800. color.New(color.FgGreen).Println("Upgrading configuration for", app)
  801. if stream {
  802. updateAgent.StreamEvent(types.SubEvent{
  803. EventID: "upgrade",
  804. Name: "Upgrade",
  805. Index: 300,
  806. Status: types.EventStatusInProgress,
  807. Info: "",
  808. })
  809. }
  810. var err error
  811. // read the values if necessary
  812. valuesObj, err := readValuesFile()
  813. if err != nil {
  814. return err
  815. }
  816. if err != nil {
  817. if stream {
  818. updateAgent.StreamEvent(types.SubEvent{
  819. EventID: "upgrade",
  820. Name: "Upgrade",
  821. Index: 310,
  822. Status: types.EventStatusFailed,
  823. Info: err.Error(),
  824. })
  825. }
  826. return err
  827. }
  828. if len(updateAgent.Opts.AdditionalEnv) > 0 {
  829. syncedEnv, err := deploy.GetSyncedEnv(
  830. updateAgent.Client,
  831. updateAgent.Release.Config,
  832. updateAgent.Opts.ProjectID,
  833. updateAgent.Opts.ClusterID,
  834. updateAgent.Opts.Namespace,
  835. false,
  836. )
  837. if err != nil {
  838. return err
  839. }
  840. for k := range updateAgent.Opts.AdditionalEnv {
  841. if _, ok := syncedEnv[k]; ok {
  842. return fmt.Errorf("environment variable %s already exists as part of a synced environment group", k)
  843. }
  844. }
  845. normalEnv, err := deploy.GetNormalEnv(
  846. updateAgent.Client,
  847. updateAgent.Release.Config,
  848. updateAgent.Opts.ProjectID,
  849. updateAgent.Opts.ClusterID,
  850. updateAgent.Opts.Namespace,
  851. false,
  852. )
  853. if err != nil {
  854. return err
  855. }
  856. // add the additional environment variables to container.env.normal
  857. for k, v := range updateAgent.Opts.AdditionalEnv {
  858. normalEnv[k] = v
  859. }
  860. valuesObj = templaterUtils.CoalesceValues(valuesObj, map[string]interface{}{
  861. "container": map[string]interface{}{
  862. "env": map[string]interface{}{
  863. "normal": normalEnv,
  864. },
  865. },
  866. })
  867. }
  868. err = updateAgent.UpdateImageAndValues(valuesObj)
  869. if err != nil {
  870. if stream {
  871. updateAgent.StreamEvent(types.SubEvent{
  872. EventID: "upgrade",
  873. Name: "Upgrade",
  874. Index: 320,
  875. Status: types.EventStatusFailed,
  876. Info: err.Error(),
  877. })
  878. }
  879. return err
  880. }
  881. if stream {
  882. updateAgent.StreamEvent(types.SubEvent{
  883. EventID: "upgrade",
  884. Name: "Upgrade",
  885. Index: 330,
  886. Status: types.EventStatusSuccess,
  887. Info: "",
  888. })
  889. }
  890. color.New(color.FgGreen).Println("Successfully updated", app)
  891. return nil
  892. }
  893. func checkDeploymentStatus(client *api.Client) error {
  894. color.New(color.FgBlue).Println("waiting for deployment to be ready, this may take a few minutes and will time out if it takes longer than 30 minutes")
  895. sharedConf := &PorterRunSharedConfig{
  896. Client: client,
  897. }
  898. err := sharedConf.setSharedConfig()
  899. if err != nil {
  900. return fmt.Errorf("could not retrieve kubernetes credentials: %w", err)
  901. }
  902. prevRefresh := time.Now()
  903. timeWait := prevRefresh.Add(30 * time.Minute)
  904. success := false
  905. depls, err := sharedConf.Clientset.AppsV1().Deployments(namespace).List(
  906. context.Background(),
  907. metav1.ListOptions{
  908. LabelSelector: fmt.Sprintf("app.kubernetes.io/instance=%s", app),
  909. },
  910. )
  911. if err != nil {
  912. return fmt.Errorf("could not get deployments for app %s: %w", app, err)
  913. }
  914. if len(depls.Items) == 0 {
  915. return fmt.Errorf("could not find any deployments for app %s", app)
  916. }
  917. sort.Slice(depls.Items, func(i, j int) bool {
  918. return depls.Items[i].CreationTimestamp.After(depls.Items[j].CreationTimestamp.Time)
  919. })
  920. depl := depls.Items[0]
  921. // determine if the deployment has an appropriate number of ready replicas
  922. minAvailable := *(depl.Spec.Replicas) - getMaxUnavailable(depl)
  923. var revision string
  924. for k, v := range depl.Spec.Template.ObjectMeta.Annotations {
  925. if k == "helm.sh/revision" {
  926. revision = v
  927. break
  928. }
  929. }
  930. if revision == "" {
  931. return fmt.Errorf("could not find revision for deployment")
  932. }
  933. pods, err := sharedConf.Clientset.CoreV1().Pods(namespace).List(
  934. context.Background(), metav1.ListOptions{
  935. LabelSelector: fmt.Sprintf("app.kubernetes.io/instance=%s", app),
  936. },
  937. )
  938. if err != nil {
  939. return fmt.Errorf("error fetching pods for app %s: %w", app, err)
  940. }
  941. if len(pods.Items) == 0 {
  942. return fmt.Errorf("could not find any pods for app %s", app)
  943. }
  944. var rsName string
  945. for _, pod := range pods.Items {
  946. if pod.ObjectMeta.Annotations["helm.sh/revision"] == revision {
  947. for _, ref := range pod.OwnerReferences {
  948. if ref.Kind == "ReplicaSet" {
  949. rs, err := sharedConf.Clientset.AppsV1().ReplicaSets(namespace).Get(
  950. context.Background(),
  951. ref.Name,
  952. metav1.GetOptions{},
  953. )
  954. if err != nil {
  955. return fmt.Errorf("error fetching new replicaset: %w", err)
  956. }
  957. rsName = rs.Name
  958. break
  959. }
  960. }
  961. if rsName != "" {
  962. break
  963. }
  964. }
  965. }
  966. if rsName == "" {
  967. return fmt.Errorf("could not find replicaset for app %s", app)
  968. }
  969. for time.Now().Before(timeWait) {
  970. // refresh the client every 10 minutes
  971. if time.Now().After(prevRefresh.Add(10 * time.Minute)) {
  972. err = sharedConf.setSharedConfig()
  973. if err != nil {
  974. return fmt.Errorf("could not retrieve kube credentials: %s", err.Error())
  975. }
  976. prevRefresh = time.Now()
  977. }
  978. rs, err := sharedConf.Clientset.AppsV1().ReplicaSets(namespace).Get(
  979. context.Background(),
  980. rsName,
  981. metav1.GetOptions{},
  982. )
  983. if err != nil {
  984. return fmt.Errorf("error fetching new replicaset: %w", err)
  985. }
  986. if minAvailable <= rs.Status.ReadyReplicas {
  987. success = true
  988. }
  989. if success {
  990. break
  991. }
  992. time.Sleep(2 * time.Second)
  993. }
  994. if success {
  995. color.New(color.FgGreen).Printf("%s has been successfully deployed on the cluster\n", app)
  996. } else {
  997. return fmt.Errorf("timed out waiting for deployment to be ready, please check the Porter dashboard for more information")
  998. }
  999. return nil
  1000. }