apply.go 41 KB

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