apply.go 40 KB

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