apply.go 41 KB

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