2
0

apply.go 41 KB

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