apply.go 43 KB

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