2
0

deploy.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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 app string
  211. var getEnvFileDest string
  212. var localPath string
  213. var tag string
  214. var dockerfile string
  215. var method string
  216. var stream bool
  217. var buildFlagsEnv []string
  218. var forcePush bool
  219. var useCache bool
  220. var version uint
  221. var varType string
  222. var normalEnvGroupVars []string
  223. var secretEnvGroupVars []string
  224. var waitForSuccessfulDeploy bool
  225. func init() {
  226. buildFlagsEnv = []string{}
  227. rootCmd.AddCommand(updateCmd)
  228. updateCmd.PersistentFlags().StringVar(
  229. &app,
  230. "app",
  231. "",
  232. "Application in the Porter dashboard",
  233. )
  234. updateCmd.PersistentFlags().BoolVar(
  235. &useCache,
  236. "use-cache",
  237. false,
  238. "Whether to use cache (currently in beta)",
  239. )
  240. updateCmd.PersistentFlags().StringVar(
  241. &namespace,
  242. "namespace",
  243. "default",
  244. "Namespace of the application",
  245. )
  246. updateCmd.PersistentFlags().StringVar(
  247. &source,
  248. "source",
  249. "local",
  250. "the type of source (\"local\" or \"github\")",
  251. )
  252. updateCmd.PersistentFlags().StringVarP(
  253. &localPath,
  254. "path",
  255. "p",
  256. "",
  257. "If local build, the path to the build directory. If remote build, the relative path from the repository root to the build directory.",
  258. )
  259. updateCmd.PersistentFlags().StringVarP(
  260. &tag,
  261. "tag",
  262. "t",
  263. "",
  264. "the specified tag to use, if not \"latest\"",
  265. )
  266. updateCmd.PersistentFlags().StringVarP(
  267. &values,
  268. "values",
  269. "v",
  270. "",
  271. "Filepath to a values.yaml file",
  272. )
  273. updateCmd.PersistentFlags().StringVar(
  274. &dockerfile,
  275. "dockerfile",
  276. "",
  277. "the path to the dockerfile",
  278. )
  279. updateCmd.PersistentFlags().StringArrayVarP(
  280. &buildFlagsEnv,
  281. "env",
  282. "e",
  283. []string{},
  284. "Build-time environment variable, in the form 'VAR=VALUE'. These are not available at image runtime.",
  285. )
  286. updateCmd.PersistentFlags().StringVar(
  287. &method,
  288. "method",
  289. "",
  290. "the build method to use (\"docker\" or \"pack\")",
  291. )
  292. updateCmd.PersistentFlags().BoolVar(
  293. &stream,
  294. "stream",
  295. false,
  296. "stream update logs to porter dashboard",
  297. )
  298. updateCmd.PersistentFlags().BoolVar(
  299. &forceBuild,
  300. "force-build",
  301. false,
  302. "set this to force build an image (images tagged with \"latest\" have this set by default)",
  303. )
  304. updateCmd.PersistentFlags().BoolVar(
  305. &forcePush,
  306. "force-push",
  307. false,
  308. "set this to force push an image (images tagged with \"latest\" have this set by default)",
  309. )
  310. updateCmd.PersistentFlags().MarkDeprecated("force-build", "--force-build is now deprecated")
  311. updateCmd.PersistentFlags().MarkDeprecated("force-push", "--force-push is now deprecated")
  312. updateCmd.PersistentFlags().BoolVar(
  313. &waitForSuccessfulDeploy,
  314. "wait",
  315. false,
  316. "set this to wait and be notified when a deployment is successful, otherwise time out",
  317. )
  318. updateCmd.AddCommand(updateGetEnvCmd)
  319. updateGetEnvCmd.PersistentFlags().StringVar(
  320. &getEnvFileDest,
  321. "file",
  322. "",
  323. "file destination for .env files",
  324. )
  325. updateGetEnvCmd.MarkPersistentFlagRequired("app")
  326. updateBuildCmd.MarkPersistentFlagRequired("app")
  327. updateConfigCmd.MarkPersistentFlagRequired("app")
  328. updateEnvGroupCmd.PersistentFlags().StringVar(
  329. &name,
  330. "name",
  331. "",
  332. "the name of the environment group",
  333. )
  334. updateEnvGroupCmd.PersistentFlags().UintVar(
  335. &version,
  336. "version",
  337. 0,
  338. "the version of the environment group",
  339. )
  340. updateEnvGroupCmd.MarkPersistentFlagRequired("name")
  341. updateSetEnvGroupCmd.PersistentFlags().StringVar(
  342. &varType,
  343. "type",
  344. "normal",
  345. "the type of environment variable (either \"normal\" or \"secret\")",
  346. )
  347. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  348. &normalEnvGroupVars,
  349. "normal",
  350. "n",
  351. []string{},
  352. "list of variables to set, in the form VAR=VALUE",
  353. )
  354. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  355. &secretEnvGroupVars,
  356. "secret",
  357. "s",
  358. []string{},
  359. "list of secret variables to set, in the form VAR=VALUE",
  360. )
  361. updateEnvGroupCmd.AddCommand(updateSetEnvGroupCmd)
  362. updateEnvGroupCmd.AddCommand(updateUnsetEnvGroupCmd)
  363. updateCmd.AddCommand(updateBuildCmd)
  364. updateCmd.AddCommand(updatePushCmd)
  365. updateCmd.AddCommand(updateConfigCmd)
  366. updateCmd.AddCommand(updateEnvGroupCmd)
  367. }
  368. func updateFull(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  369. fullPath, err := filepath.Abs(localPath)
  370. if err != nil {
  371. return err
  372. }
  373. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  374. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  375. if err != nil {
  376. return err
  377. }
  378. if !proceed {
  379. return nil
  380. }
  381. }
  382. color.New(color.FgGreen).Println("Deploying app:", app)
  383. updateAgent, err := updateGetAgent(client)
  384. if err != nil {
  385. return err
  386. }
  387. err = updateBuildWithAgent(updateAgent)
  388. if err != nil {
  389. return err
  390. }
  391. err = updatePushWithAgent(updateAgent)
  392. if err != nil {
  393. return err
  394. }
  395. err = updateUpgradeWithAgent(updateAgent)
  396. if err != nil {
  397. return err
  398. }
  399. if waitForSuccessfulDeploy {
  400. // solves timing issue where replicasets were not on the cluster, before our initial check
  401. time.Sleep(10 * time.Second)
  402. err := checkDeploymentStatus(client)
  403. if err != nil {
  404. return err
  405. }
  406. }
  407. return nil
  408. }
  409. func updateGetEnv(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  410. updateAgent, err := updateGetAgent(client)
  411. if err != nil {
  412. return err
  413. }
  414. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  415. UseNewConfig: false,
  416. })
  417. if err != nil {
  418. return err
  419. }
  420. // set the environment variables in the process
  421. err = updateAgent.SetBuildEnv(buildEnv)
  422. if err != nil {
  423. return err
  424. }
  425. // write the environment variables to either a file or stdout (stdout by default)
  426. return updateAgent.WriteBuildEnv(getEnvFileDest)
  427. }
  428. func updateBuild(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  429. updateAgent, err := updateGetAgent(client)
  430. if err != nil {
  431. return err
  432. }
  433. return updateBuildWithAgent(updateAgent)
  434. }
  435. func updatePush(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  436. if app == "" {
  437. if len(args) == 0 {
  438. return fmt.Errorf("please provide the docker image name")
  439. }
  440. image := args[0]
  441. registries, err := client.ListRegistries(context.Background(), cliConf.Project)
  442. if err != nil {
  443. return err
  444. }
  445. regs := *registries
  446. regID := uint(0)
  447. for _, reg := range regs {
  448. if strings.Contains(image, reg.URL) {
  449. regID = reg.ID
  450. break
  451. }
  452. }
  453. if regID == 0 {
  454. return fmt.Errorf("could not find registry for image: %s", image)
  455. }
  456. err = client.CreateRepository(context.Background(), cliConf.Project, regID,
  457. &types.CreateRegistryRepositoryRequest{
  458. ImageRepoURI: strings.Split(image, ":")[0],
  459. },
  460. )
  461. if err != nil {
  462. return err
  463. }
  464. agent, err := docker.NewAgentWithAuthGetter(client, cliConf.Project)
  465. if err != nil {
  466. return err
  467. }
  468. err = agent.PushImage(image)
  469. if err != nil {
  470. return err
  471. }
  472. return nil
  473. }
  474. updateAgent, err := updateGetAgent(client)
  475. if err != nil {
  476. return err
  477. }
  478. return updatePushWithAgent(updateAgent)
  479. }
  480. func updateUpgrade(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  481. updateAgent, err := updateGetAgent(client)
  482. if err != nil {
  483. return err
  484. }
  485. err = updateUpgradeWithAgent(updateAgent)
  486. if err != nil {
  487. return err
  488. }
  489. if waitForSuccessfulDeploy {
  490. // solves timing issue where replicasets were not on the cluster, before our initial check
  491. time.Sleep(10 * time.Second)
  492. err := checkDeploymentStatus(client)
  493. if err != nil {
  494. return err
  495. }
  496. }
  497. return nil
  498. }
  499. func updateSetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  500. if len(normalEnvGroupVars) == 0 && len(secretEnvGroupVars) == 0 && len(args) == 0 {
  501. return fmt.Errorf("please provide one or more variables to update")
  502. }
  503. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  504. s.Color("cyan")
  505. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  506. s.Start()
  507. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  508. &types.GetEnvGroupRequest{
  509. Name: name, Version: version,
  510. },
  511. )
  512. s.Stop()
  513. if err != nil {
  514. return err
  515. }
  516. newEnvGroup := &types.CreateEnvGroupRequest{
  517. Name: envGroupResp.Name,
  518. Variables: envGroupResp.Variables,
  519. }
  520. // first check for multiple variables being set using the -e or -s flags
  521. if len(normalEnvGroupVars) > 0 || len(secretEnvGroupVars) > 0 {
  522. for _, v := range normalEnvGroupVars {
  523. delete(newEnvGroup.Variables, v)
  524. key, value, err := validateVarValue(v)
  525. if err != nil {
  526. return err
  527. }
  528. newEnvGroup.Variables[key] = value
  529. }
  530. if len(secretEnvGroupVars) > 0 {
  531. newEnvGroup.SecretVariables = make(map[string]string)
  532. }
  533. for _, v := range secretEnvGroupVars {
  534. delete(newEnvGroup.Variables, v)
  535. key, value, err := validateVarValue(v)
  536. if err != nil {
  537. return err
  538. }
  539. newEnvGroup.SecretVariables[key] = value
  540. }
  541. s.Suffix = fmt.Sprintf(" Updating env group '%s' in namespace '%s'", name, namespace)
  542. } else { // legacy usage
  543. key, value, err := validateVarValue(args[0])
  544. if err != nil {
  545. return err
  546. }
  547. delete(newEnvGroup.Variables, key)
  548. if varType == "secret" {
  549. newEnvGroup.SecretVariables = make(map[string]string)
  550. newEnvGroup.SecretVariables[key] = value
  551. s.Suffix = fmt.Sprintf(" Adding new secret variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  552. } else {
  553. newEnvGroup.Variables[key] = value
  554. s.Suffix = fmt.Sprintf(" Adding new variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  555. }
  556. }
  557. s.Start()
  558. _, err = client.CreateEnvGroup(
  559. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  560. )
  561. s.Stop()
  562. if err != nil {
  563. return err
  564. }
  565. color.New(color.FgGreen).Println("env group successfully updated")
  566. return nil
  567. }
  568. func validateVarValue(in string) (string, string, error) {
  569. key, value, found := strings.Cut(in, "=")
  570. if !found {
  571. return "", "", fmt.Errorf("%s is not in the form of VAR=VALUE", in)
  572. }
  573. return key, value, nil
  574. }
  575. func updateUnsetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  576. if len(args) == 0 {
  577. return fmt.Errorf("required variable name")
  578. }
  579. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  580. s.Color("cyan")
  581. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  582. s.Start()
  583. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  584. &types.GetEnvGroupRequest{
  585. Name: name, Version: version,
  586. },
  587. )
  588. s.Stop()
  589. if err != nil {
  590. return err
  591. }
  592. newEnvGroup := &types.CreateEnvGroupRequest{
  593. Name: envGroupResp.Name,
  594. Variables: envGroupResp.Variables,
  595. }
  596. for _, v := range args {
  597. delete(newEnvGroup.Variables, v)
  598. }
  599. s.Suffix = fmt.Sprintf(" Removing variables from env group '%s' in namespace '%s'", name, namespace)
  600. s.Start()
  601. _, err = client.CreateEnvGroup(
  602. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  603. )
  604. s.Stop()
  605. if err != nil {
  606. return err
  607. }
  608. color.New(color.FgGreen).Println("env group successfully updated")
  609. return nil
  610. }
  611. // HELPER METHODS
  612. func updateGetAgent(client *api.Client) (*deploy.DeployAgent, error) {
  613. var buildMethod deploy.DeployBuildType
  614. if method != "" {
  615. buildMethod = deploy.DeployBuildType(method)
  616. }
  617. // add additional env, if they exist
  618. additionalEnv := make(map[string]string)
  619. for _, buildEnv := range buildFlagsEnv {
  620. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  621. additionalEnv[strSplArr[0]] = strSplArr[1]
  622. }
  623. }
  624. // initialize the update agent
  625. return deploy.NewDeployAgent(client, app, &deploy.DeployOpts{
  626. SharedOpts: &deploy.SharedOpts{
  627. ProjectID: cliConf.Project,
  628. ClusterID: cliConf.Cluster,
  629. Namespace: namespace,
  630. LocalPath: localPath,
  631. LocalDockerfile: dockerfile,
  632. OverrideTag: tag,
  633. Method: buildMethod,
  634. AdditionalEnv: additionalEnv,
  635. UseCache: useCache,
  636. },
  637. Local: source != "github",
  638. })
  639. }
  640. func updateBuildWithAgent(updateAgent *deploy.DeployAgent) error {
  641. // build the deployment
  642. color.New(color.FgGreen).Println("Building docker image for", app)
  643. if stream {
  644. updateAgent.StreamEvent(types.SubEvent{
  645. EventID: "build",
  646. Name: "Build",
  647. Index: 100,
  648. Status: types.EventStatusInProgress,
  649. Info: "",
  650. })
  651. }
  652. if useCache {
  653. err := config.SetDockerConfig(updateAgent.Client)
  654. if err != nil {
  655. return err
  656. }
  657. }
  658. // read the values if necessary
  659. valuesObj, err := readValuesFile()
  660. if err != nil {
  661. return err
  662. }
  663. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  664. UseNewConfig: true,
  665. NewConfig: valuesObj,
  666. })
  667. if err != nil {
  668. if stream {
  669. // another concern: is it safe to ignore the error here?
  670. updateAgent.StreamEvent(types.SubEvent{
  671. EventID: "build",
  672. Name: "Build",
  673. Index: 110,
  674. Status: types.EventStatusFailed,
  675. Info: err.Error(),
  676. })
  677. }
  678. return err
  679. }
  680. // set the environment variables in the process
  681. err = updateAgent.SetBuildEnv(buildEnv)
  682. if err != nil {
  683. if stream {
  684. updateAgent.StreamEvent(types.SubEvent{
  685. EventID: "build",
  686. Name: "Build",
  687. Index: 120,
  688. Status: types.EventStatusFailed,
  689. Info: err.Error(),
  690. })
  691. }
  692. return err
  693. }
  694. if err := updateAgent.Build(nil); err != nil {
  695. if stream {
  696. updateAgent.StreamEvent(types.SubEvent{
  697. EventID: "build",
  698. Name: "Build",
  699. Index: 130,
  700. Status: types.EventStatusFailed,
  701. Info: err.Error(),
  702. })
  703. }
  704. return err
  705. }
  706. if stream {
  707. updateAgent.StreamEvent(types.SubEvent{
  708. EventID: "build",
  709. Name: "Build",
  710. Index: 140,
  711. Status: types.EventStatusSuccess,
  712. Info: "",
  713. })
  714. }
  715. return nil
  716. }
  717. func updatePushWithAgent(updateAgent *deploy.DeployAgent) error {
  718. if useCache {
  719. color.New(color.FgGreen).Println("Skipping image push for", app, "as use-cache is set")
  720. return nil
  721. }
  722. // push the deployment
  723. color.New(color.FgGreen).Println("Pushing new image for", app)
  724. if stream {
  725. updateAgent.StreamEvent(types.SubEvent{
  726. EventID: "push",
  727. Name: "Push",
  728. Index: 200,
  729. Status: types.EventStatusInProgress,
  730. Info: "",
  731. })
  732. }
  733. if err := updateAgent.Push(); err != nil {
  734. if stream {
  735. updateAgent.StreamEvent(types.SubEvent{
  736. EventID: "push",
  737. Name: "Push",
  738. Index: 210,
  739. Status: types.EventStatusFailed,
  740. Info: err.Error(),
  741. })
  742. }
  743. return err
  744. }
  745. if stream {
  746. updateAgent.StreamEvent(types.SubEvent{
  747. EventID: "push",
  748. Name: "Push",
  749. Index: 220,
  750. Status: types.EventStatusSuccess,
  751. Info: "",
  752. })
  753. }
  754. return nil
  755. }
  756. func updateUpgradeWithAgent(updateAgent *deploy.DeployAgent) error {
  757. // push the deployment
  758. color.New(color.FgGreen).Println("Upgrading configuration for", app)
  759. if stream {
  760. updateAgent.StreamEvent(types.SubEvent{
  761. EventID: "upgrade",
  762. Name: "Upgrade",
  763. Index: 300,
  764. Status: types.EventStatusInProgress,
  765. Info: "",
  766. })
  767. }
  768. var err error
  769. // read the values if necessary
  770. valuesObj, err := readValuesFile()
  771. if err != nil {
  772. return err
  773. }
  774. if err != nil {
  775. if stream {
  776. updateAgent.StreamEvent(types.SubEvent{
  777. EventID: "upgrade",
  778. Name: "Upgrade",
  779. Index: 310,
  780. Status: types.EventStatusFailed,
  781. Info: err.Error(),
  782. })
  783. }
  784. return err
  785. }
  786. if len(updateAgent.Opts.AdditionalEnv) > 0 {
  787. syncedEnv, err := deploy.GetSyncedEnv(
  788. updateAgent.Client,
  789. updateAgent.Release.Config,
  790. updateAgent.Opts.ProjectID,
  791. updateAgent.Opts.ClusterID,
  792. updateAgent.Opts.Namespace,
  793. false,
  794. )
  795. if err != nil {
  796. return err
  797. }
  798. for k := range updateAgent.Opts.AdditionalEnv {
  799. if _, ok := syncedEnv[k]; ok {
  800. return fmt.Errorf("environment variable %s already exists as part of a synced environment group", k)
  801. }
  802. }
  803. normalEnv, err := deploy.GetNormalEnv(
  804. updateAgent.Client,
  805. updateAgent.Release.Config,
  806. updateAgent.Opts.ProjectID,
  807. updateAgent.Opts.ClusterID,
  808. updateAgent.Opts.Namespace,
  809. false,
  810. )
  811. if err != nil {
  812. return err
  813. }
  814. // add the additional environment variables to container.env.normal
  815. for k, v := range updateAgent.Opts.AdditionalEnv {
  816. normalEnv[k] = v
  817. }
  818. valuesObj = templaterUtils.CoalesceValues(valuesObj, map[string]interface{}{
  819. "container": map[string]interface{}{
  820. "env": map[string]interface{}{
  821. "normal": normalEnv,
  822. },
  823. },
  824. })
  825. }
  826. err = updateAgent.UpdateImageAndValues(valuesObj)
  827. if err != nil {
  828. if stream {
  829. updateAgent.StreamEvent(types.SubEvent{
  830. EventID: "upgrade",
  831. Name: "Upgrade",
  832. Index: 320,
  833. Status: types.EventStatusFailed,
  834. Info: err.Error(),
  835. })
  836. }
  837. return err
  838. }
  839. if stream {
  840. updateAgent.StreamEvent(types.SubEvent{
  841. EventID: "upgrade",
  842. Name: "Upgrade",
  843. Index: 330,
  844. Status: types.EventStatusSuccess,
  845. Info: "",
  846. })
  847. }
  848. color.New(color.FgGreen).Println("Successfully updated", app)
  849. return nil
  850. }
  851. func checkDeploymentStatus(client *api.Client) error {
  852. 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")
  853. sharedConf := &PorterRunSharedConfig{
  854. Client: client,
  855. }
  856. err := sharedConf.setSharedConfig()
  857. if err != nil {
  858. return fmt.Errorf("could not retrieve kubernetes credentials: %w", err)
  859. }
  860. prevRefresh := time.Now()
  861. timeWait := prevRefresh.Add(30 * time.Minute)
  862. success := false
  863. depls, err := sharedConf.Clientset.AppsV1().Deployments(namespace).List(
  864. context.Background(),
  865. metav1.ListOptions{
  866. LabelSelector: fmt.Sprintf("app.kubernetes.io/instance=%s", app),
  867. },
  868. )
  869. if err != nil {
  870. return fmt.Errorf("could not get deployments for app %s: %w", app, err)
  871. }
  872. if len(depls.Items) == 0 {
  873. return fmt.Errorf("could not find any deployments for app %s", app)
  874. }
  875. sort.Slice(depls.Items, func(i, j int) bool {
  876. return depls.Items[i].CreationTimestamp.After(depls.Items[j].CreationTimestamp.Time)
  877. })
  878. depl := depls.Items[0]
  879. // determine if the deployment has an appropriate number of ready replicas
  880. minAvailable := *(depl.Spec.Replicas) - getMaxUnavailable(depl)
  881. var revision string
  882. for k, v := range depl.Spec.Template.ObjectMeta.Annotations {
  883. if k == "helm.sh/revision" {
  884. revision = v
  885. break
  886. }
  887. }
  888. if revision == "" {
  889. return fmt.Errorf("could not find revision for deployment")
  890. }
  891. pods, err := sharedConf.Clientset.CoreV1().Pods(namespace).List(
  892. context.Background(), metav1.ListOptions{
  893. LabelSelector: fmt.Sprintf("app.kubernetes.io/instance=%s", app),
  894. },
  895. )
  896. if err != nil {
  897. return fmt.Errorf("error fetching pods for app %s: %w", app, err)
  898. }
  899. if len(pods.Items) == 0 {
  900. return fmt.Errorf("could not find any pods for app %s", app)
  901. }
  902. var rsName string
  903. for _, pod := range pods.Items {
  904. if pod.ObjectMeta.Annotations["helm.sh/revision"] == revision {
  905. for _, ref := range pod.OwnerReferences {
  906. if ref.Kind == "ReplicaSet" {
  907. rs, err := sharedConf.Clientset.AppsV1().ReplicaSets(namespace).Get(
  908. context.Background(),
  909. ref.Name,
  910. metav1.GetOptions{},
  911. )
  912. if err != nil {
  913. return fmt.Errorf("error fetching new replicaset: %w", err)
  914. }
  915. rsName = rs.Name
  916. break
  917. }
  918. }
  919. if rsName != "" {
  920. break
  921. }
  922. }
  923. }
  924. if rsName == "" {
  925. return fmt.Errorf("could not find replicaset for app %s", app)
  926. }
  927. for time.Now().Before(timeWait) {
  928. // refresh the client every 10 minutes
  929. if time.Now().After(prevRefresh.Add(10 * time.Minute)) {
  930. err = sharedConf.setSharedConfig()
  931. if err != nil {
  932. return fmt.Errorf("could not retrieve kube credentials: %s", err.Error())
  933. }
  934. prevRefresh = time.Now()
  935. }
  936. rs, err := sharedConf.Clientset.AppsV1().ReplicaSets(namespace).Get(
  937. context.Background(),
  938. rsName,
  939. metav1.GetOptions{},
  940. )
  941. if err != nil {
  942. return fmt.Errorf("error fetching new replicaset: %w", err)
  943. }
  944. if minAvailable <= rs.Status.ReadyReplicas {
  945. success = true
  946. }
  947. if success {
  948. break
  949. }
  950. time.Sleep(2 * time.Second)
  951. }
  952. if success {
  953. color.New(color.FgGreen).Printf("%s has been successfully deployed on the cluster\n", app)
  954. } else {
  955. return fmt.Errorf("timed out waiting for deployment to be ready, please check the Porter dashboard for more information")
  956. }
  957. return nil
  958. }