apply.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. package commands
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/porter-dev/porter/cli/cmd/commands/flags"
  15. v2 "github.com/porter-dev/porter/cli/cmd/v2"
  16. appV2 "github.com/porter-dev/porter/internal/porter_app/v2"
  17. "github.com/cli/cli/git"
  18. "github.com/fatih/color"
  19. "github.com/mitchellh/mapstructure"
  20. api "github.com/porter-dev/porter/api/client"
  21. "github.com/porter-dev/porter/api/types"
  22. "github.com/porter-dev/porter/cli/cmd/config"
  23. "github.com/porter-dev/porter/cli/cmd/deploy"
  24. "github.com/porter-dev/porter/cli/cmd/deploy/wait"
  25. porter_app "github.com/porter-dev/porter/cli/cmd/porter_app"
  26. "github.com/porter-dev/porter/cli/cmd/preview"
  27. previewV2Beta1 "github.com/porter-dev/porter/cli/cmd/preview/v2beta1"
  28. cliUtils "github.com/porter-dev/porter/cli/cmd/utils"
  29. previewInt "github.com/porter-dev/porter/internal/integrations/preview"
  30. "github.com/porter-dev/porter/internal/templater/utils"
  31. "github.com/porter-dev/switchboard/pkg/drivers"
  32. switchboardModels "github.com/porter-dev/switchboard/pkg/models"
  33. "github.com/porter-dev/switchboard/pkg/parser"
  34. switchboardTypes "github.com/porter-dev/switchboard/pkg/types"
  35. switchboardWorker "github.com/porter-dev/switchboard/pkg/worker"
  36. "github.com/rs/zerolog"
  37. "github.com/spf13/cobra"
  38. "gopkg.in/yaml.v2"
  39. )
  40. var (
  41. porterYAML string
  42. previewApply bool
  43. // pullImageBeforeBuild is a flag that determines whether to pull the docker image from a repo before building
  44. pullImageBeforeBuild bool
  45. predeploy bool
  46. exact bool
  47. )
  48. func registerCommand_Apply(cliConf config.CLIConfig) *cobra.Command {
  49. applyCmd := &cobra.Command{
  50. Use: "apply",
  51. Short: "Applies a configuration to an application",
  52. Long: fmt.Sprintf(`
  53. %s
  54. Applies a configuration to an application by either creating a new one or updating an existing
  55. one. For example:
  56. %s
  57. This command will apply the configuration contained in porter.yaml to the requested project and
  58. cluster either provided inside the porter.yaml file or through environment variables. Note that
  59. environment variables will always take precendence over values specified in the porter.yaml file.
  60. By default, this command expects to be run from a local git repository.
  61. The following are the environment variables that can be used to set certain values while
  62. applying a configuration:
  63. PORTER_CLUSTER Cluster ID that contains the project
  64. PORTER_PROJECT Project ID that contains the application
  65. PORTER_NAMESPACE The Kubernetes namespace that the application belongs to
  66. PORTER_SOURCE_NAME Name of the source Helm chart
  67. PORTER_SOURCE_REPO The URL of the Helm charts registry
  68. PORTER_SOURCE_VERSION The version of the Helm chart to use
  69. PORTER_TAG The Docker image tag to use (like the git commit hash)
  70. `,
  71. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter apply\":"),
  72. color.New(color.FgGreen, color.Bold).Sprintf("porter apply -f porter.yaml"),
  73. ),
  74. Run: func(cmd *cobra.Command, args []string) {
  75. err := checkLoginAndRunWithConfig(cmd, cliConf, args, apply)
  76. if err != nil {
  77. if strings.Contains(err.Error(), "Forbidden") {
  78. _, _ = color.New(color.FgRed).Fprintf(os.Stderr, "You may have to update your GitHub secret token")
  79. }
  80. os.Exit(1)
  81. }
  82. },
  83. }
  84. // applyValidateCmd represents the "porter apply validate" command when called
  85. // with a porter.yaml file as an argument
  86. applyValidateCmd := &cobra.Command{
  87. Use: "validate",
  88. Short: "Validates a porter.yaml",
  89. Run: func(*cobra.Command, []string) {
  90. err := applyValidate()
  91. if err != nil {
  92. _, _ = color.New(color.FgRed).Fprintf(os.Stderr, "Error: %s\n", err.Error())
  93. os.Exit(1)
  94. } else {
  95. _, _ = color.New(color.FgGreen).Printf("The porter.yaml file is valid!\n")
  96. }
  97. },
  98. }
  99. applyCmd.AddCommand(applyValidateCmd)
  100. applyCmd.PersistentFlags().StringVarP(&porterYAML, "file", "f", "", "path to porter.yaml")
  101. applyCmd.PersistentFlags().BoolVarP(&previewApply, "preview", "p", false, "apply as preview environment based on current git branch")
  102. applyCmd.PersistentFlags().BoolVar(&pullImageBeforeBuild, "pull-before-build", false, "attempt to pull image from registry before building")
  103. applyCmd.PersistentFlags().BoolVar(&predeploy, "predeploy", false, "run predeploy job before deploying the application")
  104. applyCmd.PersistentFlags().BoolVar(&exact, "exact", false, "apply the exact configuration as specified in the porter.yaml file (default is to merge with existing configuration)")
  105. applyCmd.PersistentFlags().BoolVarP(
  106. &appWait,
  107. "wait",
  108. "w",
  109. false,
  110. "set this to wait and be notified when an apply is successful, otherwise time out",
  111. )
  112. applyCmd.PersistentFlags().Bool(flags.App_NoBuild, false, "apply configuration without building a new image")
  113. applyCmd.PersistentFlags().Bool(flags.App_NoPull, false, "do not pull the previous image before building")
  114. applyCmd.PersistentFlags().MarkDeprecated("pull-before-build", "previous image is pulled by default, use --no-pull to disable") //nolint:errcheck,gosec
  115. flags.UseAppBuildFlags(applyCmd)
  116. flags.UseAppImageFlags(applyCmd)
  117. flags.UseAppConfigFlags(applyCmd)
  118. applyCmd.MarkFlagRequired("file")
  119. return applyCmd
  120. }
  121. func appNameFromEnvironmentVariable() string {
  122. if os.Getenv("PORTER_APP_NAME") != "" {
  123. return os.Getenv("PORTER_APP_NAME")
  124. }
  125. if os.Getenv("PORTER_STACK_NAME") != "" {
  126. return os.Getenv("PORTER_STACK_NAME")
  127. }
  128. return ""
  129. }
  130. func apply(ctx context.Context, _ *types.GetAuthenticatedUserResponse, client api.Client, cliConfig config.CLIConfig, _ config.FeatureFlags, cmd *cobra.Command, _ []string) (err error) {
  131. project, err := client.GetProject(ctx, cliConfig.Project)
  132. if err != nil {
  133. return fmt.Errorf("could not retrieve project from Porter API. Please contact support@porter.run")
  134. }
  135. appName := appNameFromEnvironmentVariable()
  136. imageValues, err := flags.AppImageValuesFromCmd(cmd)
  137. if err != nil {
  138. return fmt.Errorf("could not retrieve image values from command")
  139. }
  140. buildValues, err := flags.AppBuildValuesFromCmd(cmd)
  141. if err != nil {
  142. return fmt.Errorf("could not retrieve build values from command")
  143. }
  144. extraAppConfig, err := flags.AppConfigValuesFromCmd(cmd)
  145. if err != nil {
  146. return fmt.Errorf("could not retrieve app config values from command")
  147. }
  148. noBuild, err := cmd.Flags().GetBool(flags.App_NoBuild)
  149. if err != nil {
  150. return fmt.Errorf("could not retrieve no-build flag from command")
  151. }
  152. noPull, err := cmd.Flags().GetBool(flags.App_NoPull)
  153. if err != nil {
  154. return fmt.Errorf("could not retrieve no-pull flag from command")
  155. }
  156. pullBeforeBuild := !noPull
  157. if project.ValidateApplyV2 {
  158. if previewApply && !project.PreviewEnvsEnabled {
  159. return fmt.Errorf("preview environments are not enabled for this project. Please contact support@porter.run")
  160. }
  161. patchOperations := appV2.PatchOperationsFromFlagValues(appV2.PatchOperationsFromFlagValuesInput{
  162. EnvGroups: extraAppConfig.AttachEnvGroups,
  163. BuildMethod: buildValues.BuildMethod,
  164. Dockerfile: buildValues.Dockerfile,
  165. Builder: buildValues.Builder,
  166. Buildpacks: buildValues.Buildpacks,
  167. BuildContext: buildValues.BuildContext,
  168. ImageRepository: imageValues.Repository,
  169. ImageTag: imageValues.Tag,
  170. })
  171. inp := v2.ApplyInput{
  172. CLIConfig: cliConfig,
  173. Client: client,
  174. PorterYamlPath: porterYAML,
  175. AppName: appName,
  176. ImageTagOverride: imageValues.Tag,
  177. PreviewApply: previewApply,
  178. WaitForSuccessfulDeployment: appWait,
  179. PullImageBeforeBuild: pullBeforeBuild,
  180. WithPredeploy: predeploy,
  181. Exact: exact,
  182. PatchOperations: patchOperations,
  183. SkipBuild: noBuild,
  184. }
  185. err = v2.Apply(ctx, inp)
  186. if err != nil {
  187. return err
  188. }
  189. return nil
  190. }
  191. fileBytes, err := os.ReadFile(porterYAML) //nolint:errcheck,gosec // do not want to change logic of CLI. New linter error
  192. if err != nil && appName == "" {
  193. return fmt.Errorf("a valid porter.yaml file must be specified. Run porter apply --help for more information")
  194. }
  195. var previewVersion struct {
  196. Version string `json:"version"`
  197. }
  198. err = yaml.Unmarshal(fileBytes, &previewVersion)
  199. if err != nil {
  200. return fmt.Errorf("error unmarshaling porter.yaml: %w", err)
  201. }
  202. var resGroup *switchboardTypes.ResourceGroup
  203. worker := switchboardWorker.NewWorker()
  204. if previewVersion.Version == "v2beta1" {
  205. ns := os.Getenv("PORTER_NAMESPACE")
  206. applier, err := previewV2Beta1.NewApplier(client, cliConfig, fileBytes, ns)
  207. if err != nil {
  208. return err
  209. }
  210. resGroup, err = applier.DowngradeToV1()
  211. if err != nil {
  212. return err
  213. }
  214. } else if previewVersion.Version == "v1" {
  215. if _, ok := os.LookupEnv("PORTER_VALIDATE_YAML"); ok {
  216. err := applyValidate()
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. resGroup, err = parser.ParseRawBytes(fileBytes)
  222. if err != nil {
  223. return fmt.Errorf("error parsing porter.yaml: %w", err)
  224. }
  225. } else if previewVersion.Version == "v1stack" || previewVersion.Version == "" {
  226. parsed, err := porter_app.ValidateAndMarshal(fileBytes)
  227. if err != nil {
  228. return fmt.Errorf("error parsing porter.yaml: %w", err)
  229. }
  230. resGroup = &switchboardTypes.ResourceGroup{
  231. Version: "v1",
  232. Resources: []*switchboardTypes.Resource{
  233. {
  234. Name: "get-env",
  235. Driver: "os-env",
  236. },
  237. },
  238. }
  239. if parsed.Applications != nil {
  240. for name, app := range parsed.Applications {
  241. resources, err := porter_app.CreateApplicationDeploy(ctx, client, worker, app, name, cliConfig)
  242. if err != nil {
  243. return fmt.Errorf("error parsing porter.yaml for build resources: %w", err)
  244. }
  245. resGroup.Resources = append(resGroup.Resources, resources...)
  246. }
  247. } else {
  248. if appName == "" {
  249. return fmt.Errorf("environment variable PORTER_STACK_NAME must be set")
  250. }
  251. if parsed.Apps != nil && parsed.Services != nil {
  252. return fmt.Errorf("'apps' and 'services' are synonymous but both were defined")
  253. }
  254. var services map[string]*porter_app.Service
  255. if parsed.Apps != nil {
  256. services = parsed.Apps
  257. }
  258. if parsed.Services != nil {
  259. services = parsed.Services
  260. }
  261. app := &porter_app.Application{
  262. Env: parsed.Env,
  263. Services: services,
  264. Build: parsed.Build,
  265. Release: parsed.Release,
  266. }
  267. resources, err := porter_app.CreateApplicationDeploy(ctx, client, worker, app, appName, cliConfig)
  268. if err != nil {
  269. return fmt.Errorf("error parsing porter.yaml for build resources: %w", err)
  270. }
  271. resGroup.Resources = append(resGroup.Resources, resources...)
  272. }
  273. } else if previewVersion.Version == "v2" {
  274. return errors.New("porter.yaml v2 is not enabled for this project")
  275. } else {
  276. return fmt.Errorf("unknown porter.yaml version: %s", previewVersion.Version)
  277. }
  278. basePath, err := os.Getwd()
  279. if err != nil {
  280. err = fmt.Errorf("error getting working directory: %w", err)
  281. return
  282. }
  283. drivers := []struct {
  284. name string
  285. funcName func(resource *switchboardModels.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error)
  286. }{
  287. {"deploy", NewDeployDriver(ctx, client, cliConfig)},
  288. {"build-image", preview.NewBuildDriver(ctx, client, cliConfig)},
  289. {"push-image", preview.NewPushDriver(ctx, client, cliConfig)},
  290. {"update-config", preview.NewUpdateConfigDriver(ctx, client, cliConfig)},
  291. {"random-string", preview.NewRandomStringDriver},
  292. {"env-group", preview.NewEnvGroupDriver(ctx, client, cliConfig)},
  293. {"os-env", preview.NewOSEnvDriver},
  294. }
  295. for _, driver := range drivers {
  296. err = worker.RegisterDriver(driver.name, driver.funcName)
  297. if err != nil {
  298. err = fmt.Errorf("error registering driver %s: %w", driver.name, err)
  299. return
  300. }
  301. }
  302. worker.SetDefaultDriver("deploy")
  303. if hasDeploymentHookEnvVars() {
  304. deplNamespace := os.Getenv("PORTER_NAMESPACE")
  305. if deplNamespace == "" {
  306. err = fmt.Errorf("namespace must be set by PORTER_NAMESPACE")
  307. return
  308. }
  309. deploymentHook, err := NewDeploymentHook(cliConfig, client, resGroup, deplNamespace)
  310. if err != nil {
  311. err = fmt.Errorf("error creating deployment hook: %w", err)
  312. return err
  313. }
  314. err = worker.RegisterHook("deployment", deploymentHook)
  315. if err != nil {
  316. err = fmt.Errorf("error registering deployment hook: %w", err)
  317. return err
  318. }
  319. }
  320. errorEmitterHook := NewErrorEmitterHook(client, resGroup)
  321. err = worker.RegisterHook("erroremitter", errorEmitterHook)
  322. if err != nil {
  323. err = fmt.Errorf("error registering error emitter hook: %w", err)
  324. return err
  325. }
  326. cloneEnvGroupHook := NewCloneEnvGroupHook(client, cliConfig, resGroup)
  327. err = worker.RegisterHook("cloneenvgroup", cloneEnvGroupHook)
  328. if err != nil {
  329. err = fmt.Errorf("error registering clone env group hook: %w", err)
  330. return err
  331. }
  332. err = worker.Apply(resGroup, &switchboardTypes.ApplyOpts{
  333. BasePath: basePath,
  334. })
  335. return
  336. }
  337. func applyValidate() error {
  338. fileBytes, err := ioutil.ReadFile(porterYAML)
  339. if err != nil {
  340. return fmt.Errorf("error reading porter.yaml: %w", err)
  341. }
  342. validationErrors := previewInt.Validate(string(fileBytes))
  343. if len(validationErrors) > 0 {
  344. errString := "the following error(s) were found while validating the porter.yaml file:"
  345. for _, err := range validationErrors {
  346. errString += "\n- " + strings.ReplaceAll(err.Error(), "\n\n*", "\n *")
  347. }
  348. return fmt.Errorf(errString)
  349. }
  350. return nil
  351. }
  352. func hasDeploymentHookEnvVars() bool {
  353. if ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID"); ghIDStr == "" {
  354. return false
  355. }
  356. if prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID"); prIDStr == "" {
  357. return false
  358. }
  359. if branchFrom := os.Getenv("PORTER_BRANCH_FROM"); branchFrom == "" {
  360. return false
  361. }
  362. if branchInto := os.Getenv("PORTER_BRANCH_INTO"); branchInto == "" {
  363. return false
  364. }
  365. if actionIDStr := os.Getenv("PORTER_ACTION_ID"); actionIDStr == "" {
  366. return false
  367. }
  368. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName == "" {
  369. return false
  370. }
  371. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner == "" {
  372. return false
  373. }
  374. if prName := os.Getenv("PORTER_PR_NAME"); prName == "" {
  375. return false
  376. }
  377. return true
  378. }
  379. // DeployDriver contains all information needed for deploying with switchboard
  380. type DeployDriver struct {
  381. source *previewInt.Source
  382. target *previewInt.Target
  383. output map[string]interface{}
  384. lookupTable *map[string]drivers.Driver
  385. logger *zerolog.Logger
  386. cliConfig config.CLIConfig
  387. apiClient api.Client
  388. }
  389. // NewDeployDriver creates a deployment driver for use with switchboard
  390. func NewDeployDriver(ctx context.Context, apiClient api.Client, cliConfig config.CLIConfig) func(resource *switchboardModels.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  391. return func(resource *switchboardModels.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  392. driver := &DeployDriver{
  393. lookupTable: opts.DriverLookupTable,
  394. logger: opts.Logger,
  395. output: make(map[string]interface{}),
  396. cliConfig: cliConfig,
  397. apiClient: apiClient,
  398. }
  399. target, err := preview.GetTarget(ctx, resource.Name, resource.Target, apiClient, cliConfig)
  400. if err != nil {
  401. return nil, err
  402. }
  403. driver.target = target
  404. source, err := preview.GetSource(ctx, target.Project, resource.Name, resource.Source, apiClient)
  405. if err != nil {
  406. return nil, err
  407. }
  408. driver.source = source
  409. return driver, nil
  410. }
  411. }
  412. // ShouldApply extends switchboard
  413. func (d *DeployDriver) ShouldApply(_ *switchboardModels.Resource) bool {
  414. return true
  415. }
  416. // Apply extends switchboard
  417. func (d *DeployDriver) Apply(resource *switchboardModels.Resource) (*switchboardModels.Resource, error) {
  418. ctx := context.TODO() // blocked from switchboard for now
  419. _, err := d.apiClient.GetRelease(
  420. ctx,
  421. d.target.Project,
  422. d.target.Cluster,
  423. d.target.Namespace,
  424. resource.Name,
  425. )
  426. shouldCreate := err != nil
  427. if err != nil {
  428. color.New(color.FgYellow).Printf("Could not read release %s/%s (%s): attempting creation\n", d.target.Namespace, resource.Name, err.Error())
  429. }
  430. if d.source.IsApplication {
  431. return d.applyApplication(ctx, resource, d.apiClient, shouldCreate)
  432. }
  433. return d.applyAddon(ctx, resource, d.apiClient, shouldCreate)
  434. }
  435. // Simple apply for addons
  436. func (d *DeployDriver) applyAddon(ctx context.Context, resource *switchboardModels.Resource, client api.Client, shouldCreate bool) (*switchboardModels.Resource, error) {
  437. addonConfig, err := d.getAddonConfig(resource)
  438. if err != nil {
  439. return nil, fmt.Errorf("error getting addon config for resource %s: %w", resource.Name, err)
  440. }
  441. if shouldCreate {
  442. err := client.DeployAddon(
  443. ctx,
  444. d.target.Project,
  445. d.target.Cluster,
  446. d.target.Namespace,
  447. &types.CreateAddonRequest{
  448. CreateReleaseBaseRequest: &types.CreateReleaseBaseRequest{
  449. RepoURL: d.source.Repo,
  450. TemplateName: d.source.Name,
  451. TemplateVersion: d.source.Version,
  452. Values: addonConfig,
  453. Name: resource.Name,
  454. },
  455. },
  456. )
  457. if err != nil {
  458. return nil, fmt.Errorf("error creating addon from resource %s: %w", resource.Name, err)
  459. }
  460. } else {
  461. bytes, err := json.Marshal(addonConfig)
  462. if err != nil {
  463. return nil, fmt.Errorf("error marshalling addon config from resource %s: %w", resource.Name, err)
  464. }
  465. err = client.UpgradeRelease(
  466. ctx,
  467. d.target.Project,
  468. d.target.Cluster,
  469. d.target.Namespace,
  470. resource.Name,
  471. &types.UpgradeReleaseRequest{
  472. Values: string(bytes),
  473. },
  474. )
  475. if err != nil {
  476. return nil, fmt.Errorf("error updating addon from resource %s: %w", resource.Name, err)
  477. }
  478. }
  479. if err = d.assignOutput(ctx, resource, client); err != nil {
  480. return nil, err
  481. }
  482. return resource, nil
  483. }
  484. func (d *DeployDriver) applyApplication(ctx context.Context, resource *switchboardModels.Resource, client api.Client, shouldCreate bool) (*switchboardModels.Resource, error) {
  485. if resource == nil {
  486. return nil, fmt.Errorf("nil resource")
  487. }
  488. resourceName := resource.Name
  489. appConfig, err := d.getApplicationConfig(resource)
  490. if err != nil {
  491. return nil, err
  492. }
  493. fullPath, err := filepath.Abs(appConfig.Build.Context)
  494. if err != nil {
  495. return nil, fmt.Errorf("for resource %s, error getting absolute path for config.build.context: %w", resourceName,
  496. err)
  497. }
  498. tag := os.Getenv("PORTER_TAG")
  499. if tag == "" {
  500. color.New(color.FgYellow).Printf("for resource %s, since PORTER_TAG is not set, the Docker image tag will default to"+
  501. " the git repo SHA\n", resourceName)
  502. commit, err := git.LastCommit()
  503. if err != nil {
  504. return nil, fmt.Errorf("for resource %s, error getting last git commit: %w", resourceName, err)
  505. }
  506. tag = commit.Sha[:7]
  507. color.New(color.FgYellow).Printf("for resource %s, using tag %s\n", resourceName, tag)
  508. }
  509. // if the method is registry and a tag is defined, we use the provided tag
  510. if appConfig.Build.Method == "registry" {
  511. imageSpl := strings.Split(appConfig.Build.Image, ":")
  512. if len(imageSpl) == 2 {
  513. tag = imageSpl[1]
  514. }
  515. if tag == "" {
  516. tag = "latest"
  517. }
  518. }
  519. sharedOpts := &deploy.SharedOpts{
  520. ProjectID: d.target.Project,
  521. ClusterID: d.target.Cluster,
  522. Namespace: d.target.Namespace,
  523. LocalPath: fullPath,
  524. LocalDockerfile: appConfig.Build.Dockerfile,
  525. OverrideTag: tag,
  526. Method: deploy.DeployBuildType(appConfig.Build.Method),
  527. EnvGroups: appConfig.EnvGroups,
  528. UseCache: appConfig.Build.UseCache,
  529. }
  530. if appConfig.Build.UseCache {
  531. // set the docker config so that pack caching can use the repo credentials
  532. err := config.SetDockerConfig(ctx, client, d.target.Project)
  533. if err != nil {
  534. return nil, err
  535. }
  536. }
  537. if shouldCreate {
  538. resource, err = d.createApplication(ctx, resource, client, sharedOpts, appConfig)
  539. if err != nil {
  540. return nil, fmt.Errorf("error creating app from resource %s: %w", resourceName, err)
  541. }
  542. } else if !appConfig.OnlyCreate {
  543. resource, err = d.updateApplication(ctx, resource, client, sharedOpts, appConfig)
  544. if err != nil {
  545. return nil, fmt.Errorf("error updating application from resource %s: %w", resourceName, err)
  546. }
  547. } else {
  548. color.New(color.FgYellow).Printf("Skipping creation for resource %s as onlyCreate is set to true\n", resourceName)
  549. }
  550. if err = d.assignOutput(ctx, resource, client); err != nil {
  551. return nil, err
  552. }
  553. if d.source.Name == "job" && appConfig.WaitForJob && (shouldCreate || !appConfig.OnlyCreate) {
  554. color.New(color.FgYellow).Printf("Waiting for job '%s' to finish\n", resourceName)
  555. var predeployEventResponseID string
  556. stackNameWithoutRelease := strings.TrimSuffix(d.target.AppName, "-r")
  557. if strings.Contains(d.target.Namespace, "porter-stack-") {
  558. eventRequest := types.CreateOrUpdatePorterAppEventRequest{
  559. Status: "PROGRESSING",
  560. Type: types.PorterAppEventType_PreDeploy,
  561. Metadata: map[string]any{
  562. "start_time": time.Now().UTC(),
  563. },
  564. }
  565. eventResponse, err := client.CreateOrUpdatePorterAppEvent(ctx, d.target.Project, d.target.Cluster, stackNameWithoutRelease, &eventRequest)
  566. if err != nil {
  567. return nil, fmt.Errorf("error creating porter app event for pre-deploy job: %s", err.Error())
  568. }
  569. predeployEventResponseID = eventResponse.ID
  570. }
  571. err = wait.WaitForJob(ctx, client, &wait.WaitOpts{
  572. ProjectID: d.target.Project,
  573. ClusterID: d.target.Cluster,
  574. Namespace: d.target.Namespace,
  575. Name: resourceName,
  576. })
  577. if err != nil {
  578. if strings.Contains(d.target.Namespace, "porter-stack-") {
  579. if predeployEventResponseID == "" {
  580. return nil, errors.New("unable to find pre-deploy event response ID for failed pre-deploy event")
  581. }
  582. eventRequest := types.CreateOrUpdatePorterAppEventRequest{
  583. ID: predeployEventResponseID,
  584. Status: "FAILED",
  585. Type: types.PorterAppEventType_PreDeploy,
  586. Metadata: map[string]any{
  587. "end_time": time.Now().UTC(),
  588. },
  589. }
  590. _, err := client.CreateOrUpdatePorterAppEvent(ctx, d.target.Project, d.target.Cluster, stackNameWithoutRelease, &eventRequest)
  591. if err != nil {
  592. return nil, fmt.Errorf("error updating failed porter app event for pre-deploy job: %s", err.Error())
  593. }
  594. }
  595. if appConfig.OnlyCreate {
  596. deleteJobErr := client.DeleteRelease(
  597. ctx,
  598. d.target.Project,
  599. d.target.Cluster,
  600. d.target.Namespace,
  601. resourceName,
  602. )
  603. if deleteJobErr != nil {
  604. return nil, fmt.Errorf("error deleting job %s with waitForJob and onlyCreate set to true: %w",
  605. resourceName, deleteJobErr)
  606. }
  607. }
  608. return nil, fmt.Errorf("error waiting for job %s: %w", resourceName, err)
  609. }
  610. if strings.Contains(d.target.Namespace, "porter-stack-") {
  611. stackNameWithoutRelease := strings.TrimSuffix(d.target.AppName, "-r")
  612. if predeployEventResponseID == "" {
  613. return nil, errors.New("unable to find pre-deploy event response ID for successful pre-deploy event")
  614. }
  615. eventRequest := types.CreateOrUpdatePorterAppEventRequest{
  616. ID: predeployEventResponseID,
  617. Status: "SUCCESS",
  618. Type: types.PorterAppEventType_PreDeploy,
  619. Metadata: map[string]any{
  620. "end_time": time.Now().UTC(),
  621. },
  622. }
  623. _, err := client.CreateOrUpdatePorterAppEvent(ctx, d.target.Project, d.target.Cluster, stackNameWithoutRelease, &eventRequest)
  624. if err != nil {
  625. return nil, fmt.Errorf("error updating successful porter app event for pre-deploy job: %s", err.Error())
  626. }
  627. }
  628. }
  629. return resource, err
  630. }
  631. func (d *DeployDriver) createApplication(ctx context.Context, resource *switchboardModels.Resource, client api.Client, sharedOpts *deploy.SharedOpts, appConf *previewInt.ApplicationConfig) (*switchboardModels.Resource, error) {
  632. // create new release
  633. color.New(color.FgGreen).Printf("Creating %s release: %s\n", d.source.Name, resource.Name)
  634. color.New(color.FgBlue).Printf("for resource %s, using registry %s\n", resource.Name, d.target.RegistryURL)
  635. // attempt to get repo suffix from environment variables
  636. var repoSuffix string
  637. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
  638. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
  639. repoSuffix = cliUtils.SlugifyRepoSuffix(repoOwner, repoName)
  640. }
  641. }
  642. createAgent := &deploy.CreateAgent{
  643. Client: client,
  644. CreateOpts: &deploy.CreateOpts{
  645. SharedOpts: sharedOpts,
  646. Kind: d.source.Name,
  647. ReleaseName: resource.Name,
  648. RegistryURL: registryURL,
  649. RepoSuffix: repoSuffix,
  650. },
  651. }
  652. var buildConfig *types.BuildConfig
  653. if appConf.Build.Builder != "" {
  654. buildConfig = &types.BuildConfig{
  655. Builder: appConf.Build.Builder,
  656. Buildpacks: appConf.Build.Buildpacks,
  657. }
  658. }
  659. var subdomain string
  660. var err error
  661. if appConf.Build.Method == "registry" {
  662. subdomain, err = createAgent.CreateFromRegistry(ctx, appConf.Build.Image, appConf.Values)
  663. } else {
  664. // if useCache is set, create the image repository first
  665. if appConf.Build.UseCache {
  666. regID, imageURL, err := createAgent.GetImageRepoURL(ctx, resource.Name, sharedOpts.Namespace)
  667. if err != nil {
  668. return nil, err
  669. }
  670. err = client.CreateRepository(
  671. ctx,
  672. sharedOpts.ProjectID,
  673. regID,
  674. &types.CreateRegistryRepositoryRequest{
  675. ImageRepoURI: imageURL,
  676. },
  677. )
  678. if err != nil {
  679. return nil, err
  680. }
  681. }
  682. subdomain, err = createAgent.CreateFromDocker(ctx, appConf.Values, sharedOpts.OverrideTag, buildConfig)
  683. }
  684. if err != nil {
  685. return nil, err
  686. }
  687. return resource, handleSubdomainCreate(subdomain, err)
  688. }
  689. func (d *DeployDriver) updateApplication(ctx context.Context, resource *switchboardModels.Resource, client api.Client, sharedOpts *deploy.SharedOpts, appConf *previewInt.ApplicationConfig) (*switchboardModels.Resource, error) {
  690. color.New(color.FgGreen).Println("Updating existing release:", resource.Name)
  691. if len(appConf.Build.Env) > 0 {
  692. sharedOpts.AdditionalEnv = appConf.Build.Env
  693. }
  694. updateAgent, err := deploy.NewDeployAgent(ctx, client, resource.Name, &deploy.DeployOpts{
  695. SharedOpts: sharedOpts,
  696. Local: appConf.Build.Method != "registry",
  697. })
  698. if err != nil {
  699. return nil, err
  700. }
  701. // if the build method is registry, we do not trigger a build
  702. if appConf.Build.Method != "registry" {
  703. buildEnv, err := updateAgent.GetBuildEnv(ctx, &deploy.GetBuildEnvOpts{
  704. UseNewConfig: true,
  705. NewConfig: appConf.Values,
  706. })
  707. if err != nil {
  708. return nil, err
  709. }
  710. err = updateAgent.SetBuildEnv(buildEnv)
  711. if err != nil {
  712. return nil, err
  713. }
  714. var buildConfig *types.BuildConfig
  715. if appConf.Build.Builder != "" {
  716. buildConfig = &types.BuildConfig{
  717. Builder: appConf.Build.Builder,
  718. Buildpacks: appConf.Build.Buildpacks,
  719. }
  720. }
  721. err = updateAgent.Build(ctx, buildConfig)
  722. if err != nil {
  723. return nil, err
  724. }
  725. if !appConf.Build.UseCache {
  726. err = updateAgent.Push(ctx)
  727. if err != nil {
  728. return nil, err
  729. }
  730. }
  731. }
  732. if appConf.InjectBuild {
  733. // use the built image in the values if it is set
  734. // if it contains a $, then the query did not resolve
  735. if appConf.Build.Image != "" && !strings.Contains(appConf.Build.Image, "$") {
  736. imageSpl := strings.Split(appConf.Build.Image, ":")
  737. if len(imageSpl) == 2 {
  738. appConf.Values["image"] = map[string]interface{}{
  739. "repository": imageSpl[0],
  740. "tag": imageSpl[1],
  741. }
  742. } else {
  743. return nil, fmt.Errorf("could not parse image info %s", appConf.Build.Image)
  744. }
  745. }
  746. }
  747. err = updateAgent.UpdateImageAndValues(ctx, appConf.Values)
  748. if err != nil {
  749. return nil, err
  750. }
  751. return resource, nil
  752. }
  753. func (d *DeployDriver) assignOutput(ctx context.Context, resource *switchboardModels.Resource, client api.Client) error {
  754. release, err := client.GetRelease(
  755. ctx,
  756. d.target.Project,
  757. d.target.Cluster,
  758. d.target.Namespace,
  759. resource.Name,
  760. )
  761. if err != nil {
  762. return err
  763. }
  764. d.output = utils.CoalesceValues(d.source.SourceValues, release.Config)
  765. return nil
  766. }
  767. // Output extends switchboard
  768. func (d *DeployDriver) Output() (map[string]interface{}, error) {
  769. return d.output, nil
  770. }
  771. func (d *DeployDriver) getApplicationConfig(resource *switchboardModels.Resource) (*previewInt.ApplicationConfig, error) {
  772. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  773. RawConf: resource.Config,
  774. LookupTable: *d.lookupTable,
  775. Dependencies: resource.Dependencies,
  776. })
  777. if err != nil {
  778. return nil, err
  779. }
  780. appConf := &previewInt.ApplicationConfig{}
  781. err = mapstructure.Decode(populatedConf, appConf)
  782. if err != nil {
  783. return nil, err
  784. }
  785. if _, ok := resource.Config["waitForJob"]; !ok && d.source.Name == "job" {
  786. // default to true and wait for the job to finish
  787. appConf.WaitForJob = true
  788. }
  789. return appConf, nil
  790. }
  791. func (d *DeployDriver) getAddonConfig(resource *switchboardModels.Resource) (map[string]interface{}, error) {
  792. return drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  793. RawConf: resource.Config,
  794. LookupTable: *d.lookupTable,
  795. Dependencies: resource.Dependencies,
  796. })
  797. }
  798. // DeploymentHook contains all information needed for deploying with switchboard
  799. type DeploymentHook struct {
  800. client api.Client
  801. resourceGroup *switchboardTypes.ResourceGroup
  802. gitInstallationID, projectID, clusterID, prID, actionID, envID uint
  803. branchFrom, branchInto, namespace, repoName, repoOwner, prName, commitSHA string
  804. cliConfig config.CLIConfig
  805. }
  806. // NewDeploymentHook creates a new deployment using switchboard
  807. func NewDeploymentHook(cliConfig config.CLIConfig, client api.Client, resourceGroup *switchboardTypes.ResourceGroup, namespace string) (*DeploymentHook, error) {
  808. res := &DeploymentHook{
  809. client: client,
  810. resourceGroup: resourceGroup,
  811. namespace: namespace,
  812. cliConfig: cliConfig,
  813. }
  814. ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID")
  815. ghID, err := strconv.Atoi(ghIDStr)
  816. if err != nil {
  817. return nil, err
  818. }
  819. res.gitInstallationID = uint(ghID)
  820. prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID")
  821. prID, err := strconv.Atoi(prIDStr)
  822. if err != nil {
  823. return nil, err
  824. }
  825. res.prID = uint(prID)
  826. res.projectID = cliConfig.Project
  827. if res.projectID == 0 {
  828. return nil, fmt.Errorf("project id must be set")
  829. }
  830. res.clusterID = cliConfig.Cluster
  831. if res.clusterID == 0 {
  832. return nil, fmt.Errorf("cluster id must be set")
  833. }
  834. branchFrom := os.Getenv("PORTER_BRANCH_FROM")
  835. res.branchFrom = branchFrom
  836. branchInto := os.Getenv("PORTER_BRANCH_INTO")
  837. res.branchInto = branchInto
  838. actionIDStr := os.Getenv("PORTER_ACTION_ID")
  839. actionID, err := strconv.Atoi(actionIDStr)
  840. if err != nil {
  841. return nil, err
  842. }
  843. res.actionID = uint(actionID)
  844. repoName := os.Getenv("PORTER_REPO_NAME")
  845. res.repoName = repoName
  846. repoOwner := os.Getenv("PORTER_REPO_OWNER")
  847. res.repoOwner = repoOwner
  848. prName := os.Getenv("PORTER_PR_NAME")
  849. res.prName = prName
  850. commit, err := git.LastCommit()
  851. if err != nil {
  852. return nil, fmt.Errorf(err.Error())
  853. }
  854. res.commitSHA = commit.Sha[:7]
  855. return res, nil
  856. }
  857. func (t *DeploymentHook) isBranchDeploy() bool {
  858. return t.branchFrom != "" && t.branchInto != "" && t.branchFrom == t.branchInto
  859. }
  860. // PreApply extends switchboard
  861. func (t *DeploymentHook) PreApply() error {
  862. ctx := context.TODO() // switchboard blocks changing this for now
  863. if isSystemNamespace(t.namespace) {
  864. color.New(color.FgYellow).Printf("attempting to deploy to system namespace '%s'\n", t.namespace)
  865. }
  866. envList, err := t.client.ListEnvironments(
  867. ctx, t.projectID, t.clusterID,
  868. )
  869. if err != nil {
  870. return err
  871. }
  872. envs := *envList
  873. var deplEnv *types.Environment
  874. for _, env := range envs {
  875. if strings.EqualFold(env.GitRepoOwner, t.repoOwner) &&
  876. strings.EqualFold(env.GitRepoName, t.repoName) &&
  877. env.GitInstallationID == t.gitInstallationID {
  878. t.envID = env.ID
  879. deplEnv = env
  880. break
  881. }
  882. }
  883. if t.envID == 0 {
  884. return fmt.Errorf("could not find environment for deployment")
  885. }
  886. nsList, err := t.client.GetK8sNamespaces(
  887. ctx, t.projectID, t.clusterID,
  888. )
  889. if err != nil {
  890. return fmt.Errorf("error fetching namespaces: %w", err)
  891. }
  892. found := false
  893. for _, ns := range *nsList {
  894. if ns.Name == t.namespace {
  895. found = true
  896. break
  897. }
  898. }
  899. if !found {
  900. if isSystemNamespace(t.namespace) {
  901. return fmt.Errorf("attempting to deploy to system namespace '%s' which does not exist, please create it "+
  902. "to continue", t.namespace)
  903. }
  904. createNS := &types.CreateNamespaceRequest{
  905. Name: t.namespace,
  906. }
  907. if len(deplEnv.NamespaceLabels) > 0 {
  908. createNS.Labels = deplEnv.NamespaceLabels
  909. }
  910. // create the new namespace
  911. _, err := t.client.CreateNewK8sNamespace(ctx, t.projectID, t.clusterID, createNS)
  912. if err != nil && !strings.Contains(err.Error(), "namespace already exists") {
  913. // ignore the error if the namespace already exists
  914. //
  915. // this might happen if someone creates the namespace in between this operation
  916. return fmt.Errorf("error creating namespace: %w", err)
  917. }
  918. }
  919. var deplErr error
  920. if t.isBranchDeploy() {
  921. _, deplErr = t.client.GetDeployment(
  922. ctx,
  923. t.projectID, t.clusterID, t.envID,
  924. &types.GetDeploymentRequest{
  925. Branch: t.branchFrom,
  926. },
  927. )
  928. } else {
  929. _, deplErr = t.client.GetDeployment(
  930. ctx,
  931. t.projectID, t.clusterID, t.envID,
  932. &types.GetDeploymentRequest{
  933. PRNumber: t.prID,
  934. },
  935. )
  936. }
  937. if deplErr != nil && strings.Contains(deplErr.Error(), "not found") {
  938. // in this case, create the deployment
  939. createReq := &types.CreateDeploymentRequest{
  940. Namespace: t.namespace,
  941. PullRequestID: t.prID,
  942. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  943. ActionID: t.actionID,
  944. },
  945. GitHubMetadata: &types.GitHubMetadata{
  946. PRName: t.prName,
  947. RepoName: t.repoName,
  948. RepoOwner: t.repoOwner,
  949. CommitSHA: t.commitSHA,
  950. PRBranchFrom: t.branchFrom,
  951. PRBranchInto: t.branchInto,
  952. },
  953. }
  954. if t.isBranchDeploy() {
  955. createReq.PullRequestID = 0
  956. }
  957. _, err = t.client.CreateDeployment(
  958. ctx,
  959. t.projectID, t.clusterID, createReq,
  960. )
  961. } else if err == nil {
  962. updateReq := &types.UpdateDeploymentByClusterRequest{
  963. RepoOwner: t.repoOwner,
  964. RepoName: t.repoName,
  965. Namespace: t.namespace,
  966. PRNumber: t.prID,
  967. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  968. ActionID: t.actionID,
  969. },
  970. PRBranchFrom: t.branchFrom,
  971. CommitSHA: t.commitSHA,
  972. }
  973. if t.isBranchDeploy() {
  974. updateReq.PRNumber = 0
  975. }
  976. _, err = t.client.UpdateDeployment(ctx, t.projectID, t.clusterID, updateReq)
  977. }
  978. return err
  979. }
  980. // DataQueries extends switchboard
  981. func (t *DeploymentHook) DataQueries() map[string]interface{} {
  982. res := make(map[string]interface{})
  983. // use the resource group to find all web applications that can have an exposed subdomain
  984. // that we can query for
  985. for _, resource := range t.resourceGroup.Resources {
  986. isWeb := false
  987. if sourceNameInter, exists := resource.Source["name"]; exists {
  988. if sourceName, ok := sourceNameInter.(string); ok {
  989. if sourceName == "web" {
  990. isWeb = true
  991. }
  992. }
  993. }
  994. if isWeb {
  995. // determine if we should query for porter_hosts or just hosts
  996. isCustomDomain := false
  997. ingressMap, err := deploy.GetNestedMap(resource.Config, "values", "ingress")
  998. if err == nil {
  999. enabledVal, enabledExists := ingressMap["enabled"]
  1000. customDomVal, customDomExists := ingressMap["custom_domain"]
  1001. if enabledExists && customDomExists {
  1002. enabled, eOK := enabledVal.(bool)
  1003. customDomain, cOK := customDomVal.(bool)
  1004. if eOK && cOK && enabled {
  1005. if customDomain {
  1006. // return the first custom domain when one exists
  1007. hostsArr, hostsExists := ingressMap["hosts"]
  1008. if hostsExists {
  1009. hostsArrVal, hostsArrOk := hostsArr.([]interface{})
  1010. if hostsArrOk && len(hostsArrVal) > 0 {
  1011. if _, ok := hostsArrVal[0].(string); ok {
  1012. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.hosts[0] }", resource.Name)
  1013. isCustomDomain = true
  1014. }
  1015. }
  1016. }
  1017. }
  1018. }
  1019. }
  1020. }
  1021. if !isCustomDomain {
  1022. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.porter_hosts[0] }", resource.Name)
  1023. }
  1024. }
  1025. }
  1026. return res
  1027. }
  1028. // PostApply extends switchboard
  1029. func (t *DeploymentHook) PostApply(populatedData map[string]interface{}) error {
  1030. ctx := context.TODO() // switchboard blocks changing this for now
  1031. subdomains := make([]string, 0)
  1032. for _, data := range populatedData {
  1033. domain, ok := data.(string)
  1034. if !ok {
  1035. continue
  1036. }
  1037. if _, err := url.Parse("https://" + domain); err == nil {
  1038. subdomains = append(subdomains, "https://"+domain)
  1039. }
  1040. }
  1041. req := &types.FinalizeDeploymentByClusterRequest{
  1042. RepoOwner: t.repoOwner,
  1043. RepoName: t.repoName,
  1044. Subdomain: strings.Join(subdomains, ", "),
  1045. }
  1046. if t.isBranchDeploy() {
  1047. req.Namespace = t.namespace
  1048. } else {
  1049. req.PRNumber = t.prID
  1050. }
  1051. for _, res := range t.resourceGroup.Resources {
  1052. releaseType := getReleaseType(ctx, t.projectID, res, t.client)
  1053. releaseName := getReleaseName(ctx, res, t.client, t.cliConfig)
  1054. if releaseType != "" && releaseName != "" {
  1055. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  1056. ReleaseName: releaseName,
  1057. ReleaseType: releaseType,
  1058. })
  1059. }
  1060. }
  1061. // finalize the deployment
  1062. _, err := t.client.FinalizeDeployment(ctx, t.projectID, t.clusterID, req)
  1063. return err
  1064. }
  1065. // OnError extends switchboard
  1066. func (t *DeploymentHook) OnError(error) {
  1067. ctx := context.TODO() // switchboard blocks changing this for now
  1068. var deplErr error
  1069. if t.isBranchDeploy() {
  1070. _, deplErr = t.client.GetDeployment(
  1071. ctx,
  1072. t.projectID, t.clusterID, t.envID,
  1073. &types.GetDeploymentRequest{
  1074. Branch: t.branchFrom,
  1075. },
  1076. )
  1077. } else {
  1078. _, deplErr = t.client.GetDeployment(
  1079. ctx,
  1080. t.projectID, t.clusterID, t.envID,
  1081. &types.GetDeploymentRequest{
  1082. PRNumber: t.prID,
  1083. },
  1084. )
  1085. }
  1086. // if the deployment exists, throw an error for that deployment
  1087. if deplErr == nil {
  1088. req := &types.UpdateDeploymentStatusByClusterRequest{
  1089. RepoOwner: t.repoOwner,
  1090. RepoName: t.repoName,
  1091. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  1092. ActionID: t.actionID,
  1093. },
  1094. PRBranchFrom: t.branchFrom,
  1095. Status: string(types.DeploymentStatusFailed),
  1096. }
  1097. if t.isBranchDeploy() {
  1098. req.Namespace = t.namespace
  1099. } else {
  1100. req.PRNumber = t.prID
  1101. }
  1102. // FIXME: try to use the error with a custom logger
  1103. t.client.UpdateDeploymentStatus(ctx, t.projectID, t.clusterID, req) //nolint:errcheck,gosec // do not want to change logic of CLI. New linter error
  1104. }
  1105. }
  1106. // OnConsolidatedErrors extends switchboard
  1107. func (t *DeploymentHook) OnConsolidatedErrors(allErrors map[string]error) {
  1108. ctx := context.TODO() // switchboard blocks changing this for now
  1109. var deplErr error
  1110. if t.isBranchDeploy() {
  1111. _, deplErr = t.client.GetDeployment(
  1112. ctx,
  1113. t.projectID, t.clusterID, t.envID,
  1114. &types.GetDeploymentRequest{
  1115. Branch: t.branchFrom,
  1116. },
  1117. )
  1118. } else {
  1119. _, deplErr = t.client.GetDeployment(
  1120. ctx,
  1121. t.projectID, t.clusterID, t.envID,
  1122. &types.GetDeploymentRequest{
  1123. PRNumber: t.prID,
  1124. },
  1125. )
  1126. }
  1127. // if the deployment exists, throw an error for that deployment
  1128. if deplErr == nil {
  1129. req := &types.FinalizeDeploymentWithErrorsByClusterRequest{
  1130. RepoOwner: t.repoOwner,
  1131. RepoName: t.repoName,
  1132. Errors: make(map[string]string),
  1133. }
  1134. if t.isBranchDeploy() {
  1135. req.Namespace = t.namespace
  1136. } else {
  1137. req.PRNumber = t.prID
  1138. }
  1139. for _, res := range t.resourceGroup.Resources {
  1140. if _, ok := allErrors[res.Name]; !ok {
  1141. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  1142. ReleaseName: getReleaseName(ctx, res, t.client, t.cliConfig),
  1143. ReleaseType: getReleaseType(ctx, t.projectID, res, t.client),
  1144. })
  1145. }
  1146. }
  1147. for res, err := range allErrors {
  1148. req.Errors[res] = err.Error()
  1149. }
  1150. // FIXME: handle the error
  1151. t.client.FinalizeDeploymentWithErrors(ctx, t.projectID, t.clusterID, req) //nolint:errcheck,gosec // do not want to change logic of CLI. New linter error
  1152. }
  1153. }
  1154. // CloneEnvGroupHook contains all information needed to clone an env group
  1155. type CloneEnvGroupHook struct {
  1156. client api.Client
  1157. resGroup *switchboardTypes.ResourceGroup
  1158. cliConfig config.CLIConfig
  1159. }
  1160. // NewCloneEnvGroupHook wraps switchboard for cloning env groups
  1161. func NewCloneEnvGroupHook(client api.Client, cliConfig config.CLIConfig, resourceGroup *switchboardTypes.ResourceGroup) *CloneEnvGroupHook {
  1162. return &CloneEnvGroupHook{
  1163. client: client,
  1164. cliConfig: cliConfig,
  1165. resGroup: resourceGroup,
  1166. }
  1167. }
  1168. func (t *CloneEnvGroupHook) PreApply() error {
  1169. ctx := context.TODO() // switchboard blocks changing this for now
  1170. for _, res := range t.resGroup.Resources {
  1171. if res.Driver == "env-group" {
  1172. continue
  1173. }
  1174. appConf := &previewInt.ApplicationConfig{}
  1175. err := mapstructure.Decode(res.Config, &appConf)
  1176. if err != nil {
  1177. continue
  1178. }
  1179. if appConf != nil && len(appConf.EnvGroups) > 0 {
  1180. target, err := preview.GetTarget(ctx, res.Name, res.Target, t.client, t.cliConfig)
  1181. if err != nil {
  1182. return err
  1183. }
  1184. for _, group := range appConf.EnvGroups {
  1185. if group.Name == "" {
  1186. return fmt.Errorf("env group name cannot be empty")
  1187. }
  1188. _, err := t.client.GetEnvGroup(
  1189. ctx,
  1190. target.Project,
  1191. target.Cluster,
  1192. target.Namespace,
  1193. &types.GetEnvGroupRequest{
  1194. Name: group.Name,
  1195. Version: group.Version,
  1196. },
  1197. )
  1198. if err != nil && err.Error() == "env group not found" {
  1199. if group.Namespace == "" {
  1200. return fmt.Errorf("env group namespace cannot be empty")
  1201. }
  1202. color.New(color.FgBlue, color.Bold).
  1203. Printf("Env group '%s' does not exist in the target namespace '%s'\n", group.Name, target.Namespace)
  1204. color.New(color.FgBlue, color.Bold).
  1205. Printf("Cloning env group '%s' from namespace '%s' to target namespace '%s'\n",
  1206. group.Name, group.Namespace, target.Namespace)
  1207. _, err = t.client.CloneEnvGroup(
  1208. ctx, target.Project, target.Cluster, group.Namespace,
  1209. &types.CloneEnvGroupRequest{
  1210. SourceName: group.Name,
  1211. TargetNamespace: target.Namespace,
  1212. },
  1213. )
  1214. if err != nil {
  1215. return err
  1216. }
  1217. } else if err != nil {
  1218. return err
  1219. }
  1220. }
  1221. }
  1222. }
  1223. return nil
  1224. }
  1225. func (t *CloneEnvGroupHook) DataQueries() map[string]interface{} {
  1226. return nil
  1227. }
  1228. func (t *CloneEnvGroupHook) PostApply(map[string]interface{}) error {
  1229. return nil
  1230. }
  1231. func (t *CloneEnvGroupHook) OnError(error) {}
  1232. func (t *CloneEnvGroupHook) OnConsolidatedErrors(map[string]error) {}
  1233. func getReleaseName(ctx context.Context, res *switchboardTypes.Resource, apiClient api.Client, cliConfig config.CLIConfig) string {
  1234. // can ignore the error because this method is called once
  1235. // GetTarget has alrealy been called and validated previously
  1236. target, _ := preview.GetTarget(ctx, res.Name, res.Target, apiClient, cliConfig)
  1237. if target.AppName != "" {
  1238. return target.AppName
  1239. }
  1240. return res.Name
  1241. }
  1242. func getReleaseType(ctx context.Context, projectID uint, res *switchboardTypes.Resource, apiClient api.Client) string {
  1243. // can ignore the error because this method is called once
  1244. // GetSource has alrealy been called and validated previously
  1245. source, _ := preview.GetSource(ctx, projectID, res.Name, res.Source, apiClient)
  1246. if source != nil && source.Name != "" {
  1247. return source.Name
  1248. }
  1249. return ""
  1250. }
  1251. func isSystemNamespace(namespace string) bool {
  1252. systemNamespaces := map[string]bool{
  1253. "ack-system": true,
  1254. "cert-manager": true,
  1255. "default": true,
  1256. "ingress-nginx": true,
  1257. "ingress-nginx-private": true,
  1258. "kube-node-lease": true,
  1259. "kube-public": true,
  1260. "kube-system": true,
  1261. "monitoring": true,
  1262. "porter-agent-system": true,
  1263. }
  1264. return systemNamespaces[namespace]
  1265. }
  1266. type ErrorEmitterHook struct{}
  1267. // NewErrorEmitterHook handles switchboard errors
  1268. func NewErrorEmitterHook(api.Client, *switchboardTypes.ResourceGroup) *ErrorEmitterHook {
  1269. return &ErrorEmitterHook{}
  1270. }
  1271. func (t *ErrorEmitterHook) PreApply() error {
  1272. return nil
  1273. }
  1274. func (t *ErrorEmitterHook) DataQueries() map[string]interface{} {
  1275. return nil
  1276. }
  1277. func (t *ErrorEmitterHook) PostApply(map[string]interface{}) error {
  1278. return nil
  1279. }
  1280. func (t *ErrorEmitterHook) OnError(err error) {
  1281. color.New(color.FgRed).Fprintf(os.Stderr, "Errors while building: %s\n", err.Error())
  1282. }
  1283. func (t *ErrorEmitterHook) OnConsolidatedErrors(errMap map[string]error) {
  1284. color.New(color.FgRed).Fprintf(os.Stderr, "Errors while building:\n")
  1285. for resName, err := range errMap {
  1286. color.New(color.FgRed).Fprintf(os.Stderr, " - %s: %s\n", resName, err.Error())
  1287. }
  1288. }