apply.go 38 KB

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