apply.go 40 KB

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