apply.go 41 KB

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