apply.go 28 KB

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