deploy.go 29 KB

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