deploy.go 16 KB

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