apply.go 31 KB

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