apply.go 42 KB

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