apply.go 42 KB

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