deploy.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. package cmd
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "github.com/fatih/color"
  8. api "github.com/porter-dev/porter/api/client"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/cli/cmd/config"
  11. "github.com/porter-dev/porter/cli/cmd/deploy"
  12. "github.com/porter-dev/porter/cli/cmd/utils"
  13. "github.com/spf13/cobra"
  14. "k8s.io/client-go/util/homedir"
  15. )
  16. // updateCmd represents the "porter update" base command when called
  17. // without any subcommands
  18. var updateCmd = &cobra.Command{
  19. Use: "update",
  20. Short: "Builds and updates a specified application given by the --app flag.",
  21. Long: fmt.Sprintf(`
  22. %s
  23. Builds and updates a specified application given by the --app flag. For example:
  24. %s
  25. This command will automatically build from a local path. The path can be configured via the
  26. --path flag. You can also overwrite the tag using the --tag flag. For example, to build from the
  27. local directory ~/path-to-dir with the tag "testing":
  28. %s
  29. If the application has a remote Git repository source configured, you can specify that the remote
  30. Git repository should be used to build the new image by specifying "--source github". Porter will use
  31. the latest commit from the remote repo and branch to update an application, and will use the latest
  32. commit as the image tag.
  33. %s
  34. To add new configuration or update existing configuration, you can pass a values.yaml file in via the
  35. --values flag. For example;
  36. %s
  37. If your application is set up to use a Dockerfile by default, you can use a buildpack via the flag
  38. "--method pack". Conversely, if your application is set up to use a buildpack by default, you can
  39. use a Dockerfile by passing the flag "--method docker". You can specify the relative path to a Dockerfile
  40. in your remote Git repository. For example, if a Dockerfile is found at ./docker/prod.Dockerfile, you can
  41. specify it as follows:
  42. %s
  43. `,
  44. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update\":"),
  45. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app"),
  46. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --path ~/path-to-dir --tag testing"),
  47. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app remote-git-app --source github"),
  48. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --values my-values.yaml"),
  49. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --method docker --dockerfile ./docker/prod.Dockerfile"),
  50. ),
  51. Run: func(cmd *cobra.Command, args []string) {
  52. err := checkLoginAndRun(args, updateFull)
  53. if err != nil {
  54. os.Exit(1)
  55. }
  56. },
  57. }
  58. var updateGetEnvCmd = &cobra.Command{
  59. Use: "get-env",
  60. Short: "Gets environment variables for a deployment for a specified application given by the --app flag.",
  61. Long: fmt.Sprintf(`
  62. %s
  63. Gets environment variables for a deployment for a specified application given by the --app
  64. flag. By default, env variables are printed via stdout for use in downstream commands:
  65. %s
  66. Output can also be written to a file via the --file flag, which should specify the
  67. destination path for a .env file. For example:
  68. %s
  69. `,
  70. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update get-env\":"),
  71. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app | xargs"),
  72. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app --file .env"),
  73. ),
  74. Run: func(cmd *cobra.Command, args []string) {
  75. err := checkLoginAndRun(args, updateGetEnv)
  76. if err != nil {
  77. os.Exit(1)
  78. }
  79. },
  80. }
  81. var updateBuildCmd = &cobra.Command{
  82. Use: "build",
  83. Short: "Builds a new version of the application specified by the --app flag.",
  84. Long: fmt.Sprintf(`
  85. %s
  86. Builds a new version of the application specified by the --app flag. Depending on the
  87. configured settings, this command may work automatically or will require a specified
  88. --method flag.
  89. If you have configured the Dockerfile path and/or a build context for this application,
  90. this command will by default use those settings, so you just need to specify the --app
  91. flag:
  92. %s
  93. If you have not linked the build-time requirements for this application, the command will
  94. use a local build. By default, the cloud-native buildpacks builder will automatically be run
  95. from the current directory. If you would like to change the build method, you can do so by
  96. using the --method flag, for example:
  97. %s
  98. When using "--method docker", you can specify the path to the Dockerfile using the
  99. --dockerfile flag. This will also override the Dockerfile path that you may have linked
  100. for the application:
  101. %s
  102. `,
  103. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update build\":"),
  104. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app"),
  105. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker"),
  106. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker --dockerfile ./prod.Dockerfile"),
  107. ),
  108. Run: func(cmd *cobra.Command, args []string) {
  109. err := checkLoginAndRun(args, updateBuild)
  110. if err != nil {
  111. os.Exit(1)
  112. }
  113. },
  114. }
  115. var updatePushCmd = &cobra.Command{
  116. Use: "push",
  117. Short: "Pushes a new image for an application specified by the --app flag.",
  118. Long: fmt.Sprintf(`
  119. %s
  120. Pushes a new image for an application specified by the --app flag. This command uses
  121. the image repository saved in the application config by default. For example, if an
  122. application "nginx" was created from the image repo "gcr.io/snowflake-123456/nginx",
  123. the following command would push the image "gcr.io/snowflake-123456/nginx:new-tag":
  124. %s
  125. This command will not use your pre-saved authentication set up via "docker login," so if you
  126. are using an image registry that was created outside of Porter, make sure that you have
  127. linked it via "porter connect".
  128. `,
  129. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update push\":"),
  130. color.New(color.FgGreen, color.Bold).Sprintf("porter update push --app nginx --tag new-tag"),
  131. ),
  132. Run: func(cmd *cobra.Command, args []string) {
  133. err := checkLoginAndRun(args, updatePush)
  134. if err != nil {
  135. os.Exit(1)
  136. }
  137. },
  138. }
  139. var updateConfigCmd = &cobra.Command{
  140. Use: "config",
  141. Short: "Updates the configuration for an application specified by the --app flag.",
  142. Long: fmt.Sprintf(`
  143. %s
  144. Updates the configuration for an application specified by the --app flag, using the configuration
  145. given by the --values flag. This will trigger a new deployment for the application with
  146. new configuration set. Note that this will merge your existing configuration with configuration
  147. specified in the --values file. For example:
  148. %s
  149. You can update the configuration with only a new tag with the --tag flag, which will only update
  150. the image that the application uses if no --values file is specified:
  151. %s
  152. `,
  153. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update config\":"),
  154. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --values my-values.yaml"),
  155. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --tag custom-tag"),
  156. ),
  157. Run: func(cmd *cobra.Command, args []string) {
  158. err := checkLoginAndRun(args, updateUpgrade)
  159. if err != nil {
  160. os.Exit(1)
  161. }
  162. },
  163. }
  164. var app string
  165. var getEnvFileDest string
  166. var localPath string
  167. var tag string
  168. var dockerfile string
  169. var method string
  170. var stream bool
  171. var buildFlagsEnv []string
  172. var forcePush bool
  173. var useCache bool
  174. func init() {
  175. buildFlagsEnv = []string{}
  176. rootCmd.AddCommand(updateCmd)
  177. updateCmd.PersistentFlags().StringVar(
  178. &app,
  179. "app",
  180. "",
  181. "Application in the Porter dashboard",
  182. )
  183. updateCmd.MarkPersistentFlagRequired("app")
  184. updateCmd.PersistentFlags().BoolVar(
  185. &useCache,
  186. "use-cache",
  187. false,
  188. "Whether to use cache (currently in beta)",
  189. )
  190. updateCmd.PersistentFlags().StringVar(
  191. &namespace,
  192. "namespace",
  193. "default",
  194. "Namespace of the application",
  195. )
  196. updateCmd.PersistentFlags().StringVar(
  197. &source,
  198. "source",
  199. "local",
  200. "the type of source (\"local\" or \"github\")",
  201. )
  202. updateCmd.PersistentFlags().StringVarP(
  203. &localPath,
  204. "path",
  205. "p",
  206. "",
  207. "If local build, the path to the build directory. If remote build, the relative path from the repository root to the build directory.",
  208. )
  209. updateCmd.PersistentFlags().StringVarP(
  210. &tag,
  211. "tag",
  212. "t",
  213. "",
  214. "the specified tag to use, if not \"latest\"",
  215. )
  216. updateCmd.PersistentFlags().StringVarP(
  217. &values,
  218. "values",
  219. "v",
  220. "",
  221. "Filepath to a values.yaml file",
  222. )
  223. updateCmd.PersistentFlags().StringVar(
  224. &dockerfile,
  225. "dockerfile",
  226. "",
  227. "the path to the dockerfile",
  228. )
  229. updateCmd.PersistentFlags().StringArrayVarP(
  230. &buildFlagsEnv,
  231. "env",
  232. "e",
  233. []string{},
  234. "Build-time environment variable, in the form 'VAR=VALUE'. These are not available at image runtime.",
  235. )
  236. updateCmd.PersistentFlags().StringVar(
  237. &method,
  238. "method",
  239. "",
  240. "the build method to use (\"docker\" or \"pack\")",
  241. )
  242. updateCmd.PersistentFlags().BoolVar(
  243. &stream,
  244. "stream",
  245. false,
  246. "stream update logs to porter dashboard",
  247. )
  248. updateCmd.PersistentFlags().BoolVar(
  249. &forceBuild,
  250. "force-build",
  251. false,
  252. "set this to force build an image (images tagged with \"latest\" have this set by default)",
  253. )
  254. updateCmd.PersistentFlags().BoolVar(
  255. &forcePush,
  256. "force-push",
  257. false,
  258. "set this to force push an image (images tagged with \"latest\" have this set by default)",
  259. )
  260. updateCmd.AddCommand(updateGetEnvCmd)
  261. updateGetEnvCmd.PersistentFlags().StringVar(
  262. &getEnvFileDest,
  263. "file",
  264. "",
  265. "file destination for .env files",
  266. )
  267. updateCmd.AddCommand(updateBuildCmd)
  268. updateCmd.AddCommand(updatePushCmd)
  269. updateCmd.AddCommand(updateConfigCmd)
  270. }
  271. func updateFull(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  272. fullPath, err := filepath.Abs(localPath)
  273. if err != nil {
  274. return err
  275. }
  276. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  277. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  278. if err != nil {
  279. return err
  280. }
  281. if !proceed {
  282. return nil
  283. }
  284. }
  285. color.New(color.FgGreen).Println("Deploying app:", app)
  286. updateAgent, err := updateGetAgent(client)
  287. if err != nil {
  288. return err
  289. }
  290. err = updateBuildWithAgent(updateAgent)
  291. if err != nil {
  292. return err
  293. }
  294. err = updatePushWithAgent(updateAgent)
  295. if err != nil {
  296. return err
  297. }
  298. err = updateUpgradeWithAgent(updateAgent)
  299. if err != nil {
  300. return err
  301. }
  302. return nil
  303. }
  304. func updateGetEnv(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  305. updateAgent, err := updateGetAgent(client)
  306. if err != nil {
  307. return err
  308. }
  309. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  310. UseNewConfig: false,
  311. })
  312. if err != nil {
  313. return err
  314. }
  315. // set the environment variables in the process
  316. err = updateAgent.SetBuildEnv(buildEnv)
  317. if err != nil {
  318. return err
  319. }
  320. // write the environment variables to either a file or stdout (stdout by default)
  321. return updateAgent.WriteBuildEnv(getEnvFileDest)
  322. }
  323. func updateBuild(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  324. updateAgent, err := updateGetAgent(client)
  325. if err != nil {
  326. return err
  327. }
  328. return updateBuildWithAgent(updateAgent)
  329. }
  330. func updatePush(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  331. updateAgent, err := updateGetAgent(client)
  332. if err != nil {
  333. return err
  334. }
  335. return updatePushWithAgent(updateAgent)
  336. }
  337. func updateUpgrade(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  338. updateAgent, err := updateGetAgent(client)
  339. if err != nil {
  340. return err
  341. }
  342. return updateUpgradeWithAgent(updateAgent)
  343. }
  344. // HELPER METHODS
  345. func updateGetAgent(client *api.Client) (*deploy.DeployAgent, error) {
  346. var buildMethod deploy.DeployBuildType
  347. if method != "" {
  348. buildMethod = deploy.DeployBuildType(method)
  349. }
  350. // add additional env, if they exist
  351. additionalEnv := make(map[string]string)
  352. for _, buildEnv := range buildFlagsEnv {
  353. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  354. additionalEnv[strSplArr[0]] = strSplArr[1]
  355. }
  356. }
  357. // initialize the update agent
  358. return deploy.NewDeployAgent(client, app, &deploy.DeployOpts{
  359. SharedOpts: &deploy.SharedOpts{
  360. ProjectID: cliConf.Project,
  361. ClusterID: cliConf.Cluster,
  362. Namespace: namespace,
  363. LocalPath: localPath,
  364. LocalDockerfile: dockerfile,
  365. OverrideTag: tag,
  366. Method: buildMethod,
  367. AdditionalEnv: additionalEnv,
  368. UseCache: useCache,
  369. },
  370. Local: source != "github",
  371. })
  372. }
  373. func updateBuildWithAgent(updateAgent *deploy.DeployAgent) error {
  374. // build the deployment
  375. color.New(color.FgGreen).Println("Building docker image for", app)
  376. if stream {
  377. updateAgent.StreamEvent(types.SubEvent{
  378. EventID: "build",
  379. Name: "Build",
  380. Index: 100,
  381. Status: types.EventStatusInProgress,
  382. Info: "",
  383. })
  384. }
  385. if useCache {
  386. err := config.SetDockerConfig(updateAgent.Client)
  387. if err != nil {
  388. return err
  389. }
  390. }
  391. // read the values if necessary
  392. valuesObj, err := readValuesFile()
  393. if err != nil {
  394. return err
  395. }
  396. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  397. UseNewConfig: true,
  398. NewConfig: valuesObj,
  399. })
  400. if err != nil {
  401. if stream {
  402. // another concern: is it safe to ignore the error here?
  403. updateAgent.StreamEvent(types.SubEvent{
  404. EventID: "build",
  405. Name: "Build",
  406. Index: 110,
  407. Status: types.EventStatusFailed,
  408. Info: err.Error(),
  409. })
  410. }
  411. return err
  412. }
  413. // set the environment variables in the process
  414. err = updateAgent.SetBuildEnv(buildEnv)
  415. if err != nil {
  416. if stream {
  417. updateAgent.StreamEvent(types.SubEvent{
  418. EventID: "build",
  419. Name: "Build",
  420. Index: 120,
  421. Status: types.EventStatusFailed,
  422. Info: err.Error(),
  423. })
  424. }
  425. return err
  426. }
  427. if err := updateAgent.Build(nil, forceBuild); err != nil {
  428. if stream {
  429. updateAgent.StreamEvent(types.SubEvent{
  430. EventID: "build",
  431. Name: "Build",
  432. Index: 130,
  433. Status: types.EventStatusFailed,
  434. Info: err.Error(),
  435. })
  436. }
  437. return err
  438. }
  439. if stream {
  440. updateAgent.StreamEvent(types.SubEvent{
  441. EventID: "build",
  442. Name: "Build",
  443. Index: 140,
  444. Status: types.EventStatusSuccess,
  445. Info: "",
  446. })
  447. }
  448. return nil
  449. }
  450. func updatePushWithAgent(updateAgent *deploy.DeployAgent) error {
  451. if useCache {
  452. color.New(color.FgGreen).Println("Skipping image push for", app, "as use-cache is set")
  453. return nil
  454. }
  455. // push the deployment
  456. color.New(color.FgGreen).Println("Pushing new image for", app)
  457. if stream {
  458. updateAgent.StreamEvent(types.SubEvent{
  459. EventID: "push",
  460. Name: "Push",
  461. Index: 200,
  462. Status: types.EventStatusInProgress,
  463. Info: "",
  464. })
  465. }
  466. if err := updateAgent.Push(forcePush); err != nil {
  467. if stream {
  468. updateAgent.StreamEvent(types.SubEvent{
  469. EventID: "push",
  470. Name: "Push",
  471. Index: 210,
  472. Status: types.EventStatusFailed,
  473. Info: err.Error(),
  474. })
  475. }
  476. return err
  477. }
  478. if stream {
  479. updateAgent.StreamEvent(types.SubEvent{
  480. EventID: "push",
  481. Name: "Push",
  482. Index: 220,
  483. Status: types.EventStatusSuccess,
  484. Info: "",
  485. })
  486. }
  487. return nil
  488. }
  489. func updateUpgradeWithAgent(updateAgent *deploy.DeployAgent) error {
  490. // push the deployment
  491. color.New(color.FgGreen).Println("Upgrading configuration for", app)
  492. if stream {
  493. updateAgent.StreamEvent(types.SubEvent{
  494. EventID: "upgrade",
  495. Name: "Upgrade",
  496. Index: 300,
  497. Status: types.EventStatusInProgress,
  498. Info: "",
  499. })
  500. }
  501. var err error
  502. // read the values if necessary
  503. valuesObj, err := readValuesFile()
  504. if err != nil {
  505. return err
  506. }
  507. if err != nil {
  508. if stream {
  509. updateAgent.StreamEvent(types.SubEvent{
  510. EventID: "upgrade",
  511. Name: "Upgrade",
  512. Index: 310,
  513. Status: types.EventStatusFailed,
  514. Info: err.Error(),
  515. })
  516. }
  517. return err
  518. }
  519. err = updateAgent.UpdateImageAndValues(valuesObj)
  520. if err != nil {
  521. if stream {
  522. updateAgent.StreamEvent(types.SubEvent{
  523. EventID: "upgrade",
  524. Name: "Upgrade",
  525. Index: 320,
  526. Status: types.EventStatusFailed,
  527. Info: err.Error(),
  528. })
  529. }
  530. return err
  531. }
  532. if stream {
  533. updateAgent.StreamEvent(types.SubEvent{
  534. EventID: "upgrade",
  535. Name: "Upgrade",
  536. Index: 330,
  537. Status: types.EventStatusSuccess,
  538. Info: "",
  539. })
  540. }
  541. color.New(color.FgGreen).Println("Successfully updated", app)
  542. return nil
  543. }