apply.go 40 KB

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