2
0

apply.go 43 KB

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