deploy.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/briandowns/spinner"
  10. "github.com/fatih/color"
  11. api "github.com/porter-dev/porter/api/client"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/cli/cmd/config"
  14. "github.com/porter-dev/porter/cli/cmd/deploy"
  15. "github.com/porter-dev/porter/cli/cmd/docker"
  16. "github.com/porter-dev/porter/cli/cmd/utils"
  17. templaterUtils "github.com/porter-dev/porter/internal/templater/utils"
  18. "github.com/spf13/cobra"
  19. "k8s.io/client-go/util/homedir"
  20. )
  21. // updateCmd represents the "porter update" base command when called
  22. // without any subcommands
  23. var updateCmd = &cobra.Command{
  24. Use: "update",
  25. Short: "Builds and updates a specified application given by the --app flag.",
  26. Long: fmt.Sprintf(`
  27. %s
  28. Builds and updates a specified application given by the --app flag. For example:
  29. %s
  30. This command will automatically build from a local path. The path can be configured via the
  31. --path flag. You can also overwrite the tag using the --tag flag. For example, to build from the
  32. local directory ~/path-to-dir with the tag "testing":
  33. %s
  34. If the application has a remote Git repository source configured, you can specify that the remote
  35. Git repository should be used to build the new image by specifying "--source github". Porter will use
  36. the latest commit from the remote repo and branch to update an application, and will use the latest
  37. commit as the image tag.
  38. %s
  39. To add new configuration or update existing configuration, you can pass a values.yaml file in via the
  40. --values flag. For example;
  41. %s
  42. If your application is set up to use a Dockerfile by default, you can use a buildpack via the flag
  43. "--method pack". Conversely, if your application is set up to use a buildpack by default, you can
  44. use a Dockerfile by passing the flag "--method docker". You can specify the relative path to a Dockerfile
  45. in your remote Git repository. For example, if a Dockerfile is found at ./docker/prod.Dockerfile, you can
  46. specify it as follows:
  47. %s
  48. `,
  49. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update\":"),
  50. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app"),
  51. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --path ~/path-to-dir --tag testing"),
  52. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app remote-git-app --source github"),
  53. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --values my-values.yaml"),
  54. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --method docker --dockerfile ./docker/prod.Dockerfile"),
  55. ),
  56. Run: func(cmd *cobra.Command, args []string) {
  57. err := checkLoginAndRun(args, updateFull)
  58. if err != nil {
  59. os.Exit(1)
  60. }
  61. },
  62. }
  63. var updateGetEnvCmd = &cobra.Command{
  64. Use: "get-env",
  65. Short: "Gets environment variables for a deployment for a specified application given by the --app flag.",
  66. Long: fmt.Sprintf(`
  67. %s
  68. Gets environment variables for a deployment for a specified application given by the --app
  69. flag. By default, env variables are printed via stdout for use in downstream commands:
  70. %s
  71. Output can also be written to a file via the --file flag, which should specify the
  72. destination path for a .env file. For example:
  73. %s
  74. `,
  75. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update get-env\":"),
  76. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app | xargs"),
  77. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app --file .env"),
  78. ),
  79. Run: func(cmd *cobra.Command, args []string) {
  80. err := checkLoginAndRun(args, updateGetEnv)
  81. if err != nil {
  82. os.Exit(1)
  83. }
  84. },
  85. }
  86. var updateBuildCmd = &cobra.Command{
  87. Use: "build",
  88. Short: "Builds a new version of the application specified by the --app flag.",
  89. Long: fmt.Sprintf(`
  90. %s
  91. Builds a new version of the application specified by the --app flag. Depending on the
  92. configured settings, this command may work automatically or will require a specified
  93. --method flag.
  94. If you have configured the Dockerfile path and/or a build context for this application,
  95. this command will by default use those settings, so you just need to specify the --app
  96. flag:
  97. %s
  98. If you have not linked the build-time requirements for this application, the command will
  99. use a local build. By default, the cloud-native buildpacks builder will automatically be run
  100. from the current directory. If you would like to change the build method, you can do so by
  101. using the --method flag, for example:
  102. %s
  103. When using "--method docker", you can specify the path to the Dockerfile using the
  104. --dockerfile flag. This will also override the Dockerfile path that you may have linked
  105. for the application:
  106. %s
  107. `,
  108. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update build\":"),
  109. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app"),
  110. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker"),
  111. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker --dockerfile ./prod.Dockerfile"),
  112. ),
  113. Run: func(cmd *cobra.Command, args []string) {
  114. err := checkLoginAndRun(args, updateBuild)
  115. if err != nil {
  116. os.Exit(1)
  117. }
  118. },
  119. }
  120. var updatePushCmd = &cobra.Command{
  121. Use: "push",
  122. Short: "Pushes an image to a Docker registry linked to your Porter project.",
  123. Args: cobra.MaximumNArgs(1),
  124. Long: fmt.Sprintf(`
  125. %s
  126. Pushes a local Docker image to a registry linked to your Porter project. This command
  127. requires the project ID to be set either by using the %s command
  128. or the --project flag. For example, to push a local nginx image:
  129. %s
  130. %s
  131. Pushes a new image for an application specified by the --app flag. This command uses
  132. the image repository saved in the application config by default. For example, if an
  133. application "nginx" was created from the image repo "gcr.io/snowflake-123456/nginx",
  134. the following command would push the image "gcr.io/snowflake-123456/nginx:new-tag":
  135. %s
  136. This command will not use your pre-saved authentication set up via "docker login," so if you
  137. are using an image registry that was created outside of Porter, make sure that you have
  138. linked it via "porter connect".
  139. `,
  140. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update push\":"),
  141. color.New(color.FgBlue).Sprintf("porter config set-project"),
  142. color.New(color.FgGreen, color.Bold).Sprintf("porter update push gcr.io/snowflake-123456/nginx:1234567"),
  143. color.New(color.Bold).Sprintf("LEGACY USAGE:"),
  144. color.New(color.FgGreen, color.Bold).Sprintf("porter update push --app nginx --tag new-tag"),
  145. ),
  146. Run: func(cmd *cobra.Command, args []string) {
  147. err := checkLoginAndRun(args, updatePush)
  148. if err != nil {
  149. os.Exit(1)
  150. }
  151. },
  152. }
  153. var updateConfigCmd = &cobra.Command{
  154. Use: "config",
  155. Short: "Updates the configuration for an application specified by the --app flag.",
  156. Long: fmt.Sprintf(`
  157. %s
  158. Updates the configuration for an application specified by the --app flag, using the configuration
  159. given by the --values flag. This will trigger a new deployment for the application with
  160. new configuration set. Note that this will merge your existing configuration with configuration
  161. specified in the --values file. For example:
  162. %s
  163. You can update the configuration with only a new tag with the --tag flag, which will only update
  164. the image that the application uses if no --values file is specified:
  165. %s
  166. `,
  167. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update config\":"),
  168. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --values my-values.yaml"),
  169. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --tag custom-tag"),
  170. ),
  171. Run: func(cmd *cobra.Command, args []string) {
  172. err := checkLoginAndRun(args, updateUpgrade)
  173. if err != nil {
  174. os.Exit(1)
  175. }
  176. },
  177. }
  178. var updateEnvGroupCmd = &cobra.Command{
  179. Use: "env-group",
  180. Aliases: []string{"eg", "envgroup", "env-groups", "envgroups"},
  181. Short: "Updates an environment group's variables, specified by the --name flag.",
  182. Run: func(cmd *cobra.Command, args []string) {
  183. color.New(color.FgRed).Println("need to specify an operation to continue")
  184. },
  185. }
  186. var updateSetEnvGroupCmd = &cobra.Command{
  187. Use: "set",
  188. Short: "Sets the desired value of an environment variable in an env group in the form VAR=VALUE.",
  189. Run: func(cmd *cobra.Command, args []string) {
  190. err := checkLoginAndRun(args, updateSetEnvGroup)
  191. if err != nil {
  192. os.Exit(1)
  193. }
  194. },
  195. }
  196. var updateUnsetEnvGroupCmd = &cobra.Command{
  197. Use: "unset",
  198. Short: "Removes an environment variable from an env group.",
  199. Args: cobra.MinimumNArgs(1),
  200. Run: func(cmd *cobra.Command, args []string) {
  201. err := checkLoginAndRun(args, updateUnsetEnvGroup)
  202. if err != nil {
  203. os.Exit(1)
  204. }
  205. },
  206. }
  207. var app string
  208. var getEnvFileDest string
  209. var localPath string
  210. var tag string
  211. var dockerfile string
  212. var method string
  213. var stream bool
  214. var buildFlagsEnv []string
  215. var forcePush bool
  216. var useCache bool
  217. var version uint
  218. var varType string
  219. var normalEnvVars []string
  220. var secretEnvVars []string
  221. func init() {
  222. buildFlagsEnv = []string{}
  223. rootCmd.AddCommand(updateCmd)
  224. updateCmd.PersistentFlags().StringVar(
  225. &app,
  226. "app",
  227. "",
  228. "Application in the Porter dashboard",
  229. )
  230. updateCmd.PersistentFlags().BoolVar(
  231. &useCache,
  232. "use-cache",
  233. false,
  234. "Whether to use cache (currently in beta)",
  235. )
  236. updateCmd.PersistentFlags().StringVar(
  237. &namespace,
  238. "namespace",
  239. "default",
  240. "Namespace of the application",
  241. )
  242. updateCmd.PersistentFlags().StringVar(
  243. &source,
  244. "source",
  245. "local",
  246. "the type of source (\"local\" or \"github\")",
  247. )
  248. updateCmd.PersistentFlags().StringVarP(
  249. &localPath,
  250. "path",
  251. "p",
  252. "",
  253. "If local build, the path to the build directory. If remote build, the relative path from the repository root to the build directory.",
  254. )
  255. updateCmd.PersistentFlags().StringVarP(
  256. &tag,
  257. "tag",
  258. "t",
  259. "",
  260. "the specified tag to use, if not \"latest\"",
  261. )
  262. updateCmd.PersistentFlags().StringVarP(
  263. &values,
  264. "values",
  265. "v",
  266. "",
  267. "Filepath to a values.yaml file",
  268. )
  269. updateCmd.PersistentFlags().StringVar(
  270. &dockerfile,
  271. "dockerfile",
  272. "",
  273. "the path to the dockerfile",
  274. )
  275. updateCmd.PersistentFlags().StringArrayVarP(
  276. &buildFlagsEnv,
  277. "env",
  278. "e",
  279. []string{},
  280. "Build-time environment variable, in the form 'VAR=VALUE'. These are not available at image runtime.",
  281. )
  282. updateCmd.PersistentFlags().StringVar(
  283. &method,
  284. "method",
  285. "",
  286. "the build method to use (\"docker\" or \"pack\")",
  287. )
  288. updateCmd.PersistentFlags().BoolVar(
  289. &stream,
  290. "stream",
  291. false,
  292. "stream update logs to porter dashboard",
  293. )
  294. updateCmd.PersistentFlags().BoolVar(
  295. &forceBuild,
  296. "force-build",
  297. false,
  298. "set this to force build an image (images tagged with \"latest\" have this set by default)",
  299. )
  300. updateCmd.PersistentFlags().BoolVar(
  301. &forcePush,
  302. "force-push",
  303. false,
  304. "set this to force push an image (images tagged with \"latest\" have this set by default)",
  305. )
  306. updateCmd.PersistentFlags().MarkDeprecated("force-build", "--force-build is now deprecated")
  307. updateCmd.PersistentFlags().MarkDeprecated("force-push", "--force-push is now deprecated")
  308. updateCmd.AddCommand(updateGetEnvCmd)
  309. updateGetEnvCmd.PersistentFlags().StringVar(
  310. &getEnvFileDest,
  311. "file",
  312. "",
  313. "file destination for .env files",
  314. )
  315. updateGetEnvCmd.MarkPersistentFlagRequired("app")
  316. updateBuildCmd.MarkPersistentFlagRequired("app")
  317. updateConfigCmd.MarkPersistentFlagRequired("app")
  318. updateEnvGroupCmd.PersistentFlags().StringVar(
  319. &name,
  320. "name",
  321. "",
  322. "the name of the environment group",
  323. )
  324. updateEnvGroupCmd.PersistentFlags().UintVar(
  325. &version,
  326. "version",
  327. 0,
  328. "the version of the environment group",
  329. )
  330. updateEnvGroupCmd.MarkPersistentFlagRequired("name")
  331. updateSetEnvGroupCmd.PersistentFlags().StringVar(
  332. &varType,
  333. "type",
  334. "normal",
  335. "the type of environment variable (either \"normal\" or \"secret\")",
  336. )
  337. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  338. &normalEnvVars,
  339. "normal",
  340. "e",
  341. []string{},
  342. "list of variables to set, in the form VAR=VALUE",
  343. )
  344. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  345. &normalEnvVars,
  346. "normal",
  347. "e",
  348. []string{},
  349. "list of variables to set, in the form VAR=VALUE",
  350. )
  351. updateEnvGroupCmd.AddCommand(updateSetEnvGroupCmd)
  352. updateEnvGroupCmd.AddCommand(updateUnsetEnvGroupCmd)
  353. updateCmd.AddCommand(updateBuildCmd)
  354. updateCmd.AddCommand(updatePushCmd)
  355. updateCmd.AddCommand(updateConfigCmd)
  356. updateCmd.AddCommand(updateEnvGroupCmd)
  357. }
  358. func updateFull(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  359. fullPath, err := filepath.Abs(localPath)
  360. if err != nil {
  361. return err
  362. }
  363. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  364. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  365. if err != nil {
  366. return err
  367. }
  368. if !proceed {
  369. return nil
  370. }
  371. }
  372. color.New(color.FgGreen).Println("Deploying app:", app)
  373. updateAgent, err := updateGetAgent(client)
  374. if err != nil {
  375. return err
  376. }
  377. err = updateBuildWithAgent(updateAgent)
  378. if err != nil {
  379. return err
  380. }
  381. err = updatePushWithAgent(updateAgent)
  382. if err != nil {
  383. return err
  384. }
  385. err = updateUpgradeWithAgent(updateAgent)
  386. if err != nil {
  387. return err
  388. }
  389. return nil
  390. }
  391. func updateGetEnv(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  392. updateAgent, err := updateGetAgent(client)
  393. if err != nil {
  394. return err
  395. }
  396. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  397. UseNewConfig: false,
  398. })
  399. if err != nil {
  400. return err
  401. }
  402. // set the environment variables in the process
  403. err = updateAgent.SetBuildEnv(buildEnv)
  404. if err != nil {
  405. return err
  406. }
  407. // write the environment variables to either a file or stdout (stdout by default)
  408. return updateAgent.WriteBuildEnv(getEnvFileDest)
  409. }
  410. func updateBuild(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  411. updateAgent, err := updateGetAgent(client)
  412. if err != nil {
  413. return err
  414. }
  415. return updateBuildWithAgent(updateAgent)
  416. }
  417. func updatePush(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  418. if app == "" {
  419. if len(args) == 0 {
  420. return fmt.Errorf("please provide the docker image name")
  421. }
  422. image := args[0]
  423. registries, err := client.ListRegistries(context.Background(), cliConf.Project)
  424. if err != nil {
  425. return err
  426. }
  427. regs := *registries
  428. regID := uint(0)
  429. for _, reg := range regs {
  430. if strings.Contains(image, reg.URL) {
  431. regID = reg.ID
  432. break
  433. }
  434. }
  435. if regID == 0 {
  436. return fmt.Errorf("could not find registry for image: %s", image)
  437. }
  438. err = client.CreateRepository(context.Background(), cliConf.Project, regID,
  439. &types.CreateRegistryRepositoryRequest{
  440. ImageRepoURI: strings.Split(image, ":")[0],
  441. },
  442. )
  443. if err != nil {
  444. return err
  445. }
  446. agent, err := docker.NewAgentWithAuthGetter(client, cliConf.Project)
  447. if err != nil {
  448. return err
  449. }
  450. err = agent.PushImage(image)
  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 updatePushWithAgent(updateAgent)
  461. }
  462. func updateUpgrade(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  463. updateAgent, err := updateGetAgent(client)
  464. if err != nil {
  465. return err
  466. }
  467. return updateUpgradeWithAgent(updateAgent)
  468. }
  469. func updateSetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  470. if len(args) == 0 {
  471. return fmt.Errorf("required variable in the form of VAR=VALUE")
  472. }
  473. key, value, found := strings.Cut(args[0], "=")
  474. if !found {
  475. return fmt.Errorf("variable should be in the form of VAR=VALUE")
  476. }
  477. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  478. s.Color("cyan")
  479. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  480. s.Start()
  481. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  482. &types.GetEnvGroupRequest{
  483. Name: name, Version: version,
  484. },
  485. )
  486. s.Stop()
  487. if err != nil {
  488. return err
  489. }
  490. newEnvGroup := &types.CreateEnvGroupRequest{
  491. Name: envGroupResp.Name,
  492. Variables: envGroupResp.Variables,
  493. }
  494. delete(newEnvGroup.Variables, key)
  495. if varType == "secret" {
  496. newEnvGroup.SecretVariables = make(map[string]string)
  497. newEnvGroup.SecretVariables[key] = value
  498. s.Suffix = fmt.Sprintf(" Adding new secret variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  499. } else {
  500. newEnvGroup.Variables[key] = value
  501. s.Suffix = fmt.Sprintf(" Adding new variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  502. }
  503. s.Start()
  504. _, err = client.CreateEnvGroup(
  505. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  506. )
  507. s.Stop()
  508. if err != nil {
  509. return err
  510. }
  511. color.New(color.FgGreen).Println("env group successfully updated")
  512. return nil
  513. }
  514. func updateUnsetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  515. if len(args) == 0 {
  516. return fmt.Errorf("required variable name")
  517. }
  518. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  519. s.Color("cyan")
  520. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  521. s.Start()
  522. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  523. &types.GetEnvGroupRequest{
  524. Name: name, Version: version,
  525. },
  526. )
  527. s.Stop()
  528. if err != nil {
  529. return err
  530. }
  531. newEnvGroup := &types.CreateEnvGroupRequest{
  532. Name: envGroupResp.Name,
  533. Variables: envGroupResp.Variables,
  534. }
  535. for _, v := range args {
  536. delete(newEnvGroup.Variables, v)
  537. }
  538. s.Suffix = fmt.Sprintf(" Removing variables from env group '%s' in namespace '%s'", name, namespace)
  539. s.Start()
  540. _, err = client.CreateEnvGroup(
  541. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  542. )
  543. s.Stop()
  544. if err != nil {
  545. return err
  546. }
  547. color.New(color.FgGreen).Println("env group successfully updated")
  548. return nil
  549. }
  550. // HELPER METHODS
  551. func updateGetAgent(client *api.Client) (*deploy.DeployAgent, error) {
  552. var buildMethod deploy.DeployBuildType
  553. if method != "" {
  554. buildMethod = deploy.DeployBuildType(method)
  555. }
  556. // add additional env, if they exist
  557. additionalEnv := make(map[string]string)
  558. for _, buildEnv := range buildFlagsEnv {
  559. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  560. additionalEnv[strSplArr[0]] = strSplArr[1]
  561. }
  562. }
  563. // initialize the update agent
  564. return deploy.NewDeployAgent(client, app, &deploy.DeployOpts{
  565. SharedOpts: &deploy.SharedOpts{
  566. ProjectID: cliConf.Project,
  567. ClusterID: cliConf.Cluster,
  568. Namespace: namespace,
  569. LocalPath: localPath,
  570. LocalDockerfile: dockerfile,
  571. OverrideTag: tag,
  572. Method: buildMethod,
  573. AdditionalEnv: additionalEnv,
  574. UseCache: useCache,
  575. },
  576. Local: source != "github",
  577. })
  578. }
  579. func updateBuildWithAgent(updateAgent *deploy.DeployAgent) error {
  580. // build the deployment
  581. color.New(color.FgGreen).Println("Building docker image for", app)
  582. if stream {
  583. updateAgent.StreamEvent(types.SubEvent{
  584. EventID: "build",
  585. Name: "Build",
  586. Index: 100,
  587. Status: types.EventStatusInProgress,
  588. Info: "",
  589. })
  590. }
  591. if useCache {
  592. err := config.SetDockerConfig(updateAgent.Client)
  593. if err != nil {
  594. return err
  595. }
  596. }
  597. // read the values if necessary
  598. valuesObj, err := readValuesFile()
  599. if err != nil {
  600. return err
  601. }
  602. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  603. UseNewConfig: true,
  604. NewConfig: valuesObj,
  605. })
  606. if err != nil {
  607. if stream {
  608. // another concern: is it safe to ignore the error here?
  609. updateAgent.StreamEvent(types.SubEvent{
  610. EventID: "build",
  611. Name: "Build",
  612. Index: 110,
  613. Status: types.EventStatusFailed,
  614. Info: err.Error(),
  615. })
  616. }
  617. return err
  618. }
  619. // set the environment variables in the process
  620. err = updateAgent.SetBuildEnv(buildEnv)
  621. if err != nil {
  622. if stream {
  623. updateAgent.StreamEvent(types.SubEvent{
  624. EventID: "build",
  625. Name: "Build",
  626. Index: 120,
  627. Status: types.EventStatusFailed,
  628. Info: err.Error(),
  629. })
  630. }
  631. return err
  632. }
  633. if err := updateAgent.Build(nil); err != nil {
  634. if stream {
  635. updateAgent.StreamEvent(types.SubEvent{
  636. EventID: "build",
  637. Name: "Build",
  638. Index: 130,
  639. Status: types.EventStatusFailed,
  640. Info: err.Error(),
  641. })
  642. }
  643. return err
  644. }
  645. if stream {
  646. updateAgent.StreamEvent(types.SubEvent{
  647. EventID: "build",
  648. Name: "Build",
  649. Index: 140,
  650. Status: types.EventStatusSuccess,
  651. Info: "",
  652. })
  653. }
  654. return nil
  655. }
  656. func updatePushWithAgent(updateAgent *deploy.DeployAgent) error {
  657. if useCache {
  658. color.New(color.FgGreen).Println("Skipping image push for", app, "as use-cache is set")
  659. return nil
  660. }
  661. // push the deployment
  662. color.New(color.FgGreen).Println("Pushing new image for", app)
  663. if stream {
  664. updateAgent.StreamEvent(types.SubEvent{
  665. EventID: "push",
  666. Name: "Push",
  667. Index: 200,
  668. Status: types.EventStatusInProgress,
  669. Info: "",
  670. })
  671. }
  672. if err := updateAgent.Push(); err != nil {
  673. if stream {
  674. updateAgent.StreamEvent(types.SubEvent{
  675. EventID: "push",
  676. Name: "Push",
  677. Index: 210,
  678. Status: types.EventStatusFailed,
  679. Info: err.Error(),
  680. })
  681. }
  682. return err
  683. }
  684. if stream {
  685. updateAgent.StreamEvent(types.SubEvent{
  686. EventID: "push",
  687. Name: "Push",
  688. Index: 220,
  689. Status: types.EventStatusSuccess,
  690. Info: "",
  691. })
  692. }
  693. return nil
  694. }
  695. func updateUpgradeWithAgent(updateAgent *deploy.DeployAgent) error {
  696. // push the deployment
  697. color.New(color.FgGreen).Println("Upgrading configuration for", app)
  698. if stream {
  699. updateAgent.StreamEvent(types.SubEvent{
  700. EventID: "upgrade",
  701. Name: "Upgrade",
  702. Index: 300,
  703. Status: types.EventStatusInProgress,
  704. Info: "",
  705. })
  706. }
  707. var err error
  708. // read the values if necessary
  709. valuesObj, err := readValuesFile()
  710. if err != nil {
  711. return err
  712. }
  713. if err != nil {
  714. if stream {
  715. updateAgent.StreamEvent(types.SubEvent{
  716. EventID: "upgrade",
  717. Name: "Upgrade",
  718. Index: 310,
  719. Status: types.EventStatusFailed,
  720. Info: err.Error(),
  721. })
  722. }
  723. return err
  724. }
  725. if len(updateAgent.Opts.AdditionalEnv) > 0 {
  726. syncedEnv, err := deploy.GetSyncedEnv(
  727. updateAgent.Client,
  728. updateAgent.Release.Config,
  729. updateAgent.Opts.ProjectID,
  730. updateAgent.Opts.ClusterID,
  731. updateAgent.Opts.Namespace,
  732. false,
  733. )
  734. if err != nil {
  735. return err
  736. }
  737. for k := range updateAgent.Opts.AdditionalEnv {
  738. if _, ok := syncedEnv[k]; ok {
  739. return fmt.Errorf("environment variable %s already exists as part of a synced environment group", k)
  740. }
  741. }
  742. normalEnv, err := deploy.GetNormalEnv(
  743. updateAgent.Client,
  744. updateAgent.Release.Config,
  745. updateAgent.Opts.ProjectID,
  746. updateAgent.Opts.ClusterID,
  747. updateAgent.Opts.Namespace,
  748. false,
  749. )
  750. if err != nil {
  751. return err
  752. }
  753. // add the additional environment variables to container.env.normal
  754. for k, v := range updateAgent.Opts.AdditionalEnv {
  755. normalEnv[k] = v
  756. }
  757. valuesObj = templaterUtils.CoalesceValues(valuesObj, map[string]interface{}{
  758. "container": map[string]interface{}{
  759. "env": map[string]interface{}{
  760. "normal": normalEnv,
  761. },
  762. },
  763. })
  764. }
  765. err = updateAgent.UpdateImageAndValues(valuesObj)
  766. if err != nil {
  767. if stream {
  768. updateAgent.StreamEvent(types.SubEvent{
  769. EventID: "upgrade",
  770. Name: "Upgrade",
  771. Index: 320,
  772. Status: types.EventStatusFailed,
  773. Info: err.Error(),
  774. })
  775. }
  776. return err
  777. }
  778. if stream {
  779. updateAgent.StreamEvent(types.SubEvent{
  780. EventID: "upgrade",
  781. Name: "Upgrade",
  782. Index: 330,
  783. Status: types.EventStatusSuccess,
  784. Info: "",
  785. })
  786. }
  787. color.New(color.FgGreen).Println("Successfully updated", app)
  788. return nil
  789. }