apply.go 38 KB

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