apply.go 38 KB

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