2
0

apply.go 37 KB

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