apply.go 41 KB

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