apply.go 42 KB

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