apply.go 38 KB

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