apply.go 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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/deploy"
  18. "github.com/porter-dev/porter/internal/templater/utils"
  19. "github.com/porter-dev/switchboard/pkg/drivers"
  20. "github.com/porter-dev/switchboard/pkg/models"
  21. "github.com/porter-dev/switchboard/pkg/parser"
  22. switchboardTypes "github.com/porter-dev/switchboard/pkg/types"
  23. "github.com/porter-dev/switchboard/pkg/worker"
  24. "github.com/rs/zerolog"
  25. "github.com/spf13/cobra"
  26. )
  27. // applyCmd represents the "porter apply" base command when called
  28. // with a porter.yaml file as an argument
  29. var applyCmd = &cobra.Command{
  30. Use: "apply",
  31. Short: "Applies a configuration to an application",
  32. Long: fmt.Sprintf(`
  33. %s
  34. Applies a configuration to an application by either creating a new one or updating an existing
  35. one. For example:
  36. %s
  37. This command will apply the configuration contained in porter.yaml to the requested project and
  38. cluster either provided inside the porter.yaml file or through environment variables. Note that
  39. environment variables will always take precendence over values specified in the porter.yaml file.
  40. By default, this command expects to be run from a local git repository.
  41. The following are the environment variables that can be used to set certain values while
  42. applying a configuration:
  43. PORTER_CLUSTER Cluster ID that contains the project
  44. PORTER_PROJECT Project ID that contains the application
  45. PORTER_NAMESPACE The Kubernetes namespace that the application belongs to
  46. PORTER_SOURCE_NAME Name of the source Helm chart
  47. PORTER_SOURCE_REPO The URL of the Helm charts registry
  48. PORTER_SOURCE_VERSION The version of the Helm chart to use
  49. PORTER_TAG The Docker image tag to use (like the git commit hash)
  50. `,
  51. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter apply\":"),
  52. color.New(color.FgGreen, color.Bold).Sprintf("porter apply -f porter.yaml"),
  53. ),
  54. Run: func(cmd *cobra.Command, args []string) {
  55. err := checkLoginAndRun(args, apply)
  56. if err != nil {
  57. os.Exit(1)
  58. }
  59. },
  60. }
  61. var porterYAML string
  62. func init() {
  63. rootCmd.AddCommand(applyCmd)
  64. applyCmd.Flags().StringVarP(&porterYAML, "file", "f", "", "path to porter.yaml")
  65. applyCmd.MarkFlagRequired("file")
  66. }
  67. func apply(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  68. fileBytes, err := ioutil.ReadFile(porterYAML)
  69. if err != nil {
  70. return err
  71. }
  72. resGroup, err := parser.ParseRawBytes(fileBytes)
  73. if err != nil {
  74. return err
  75. }
  76. basePath, err := os.Getwd()
  77. if err != nil {
  78. return err
  79. }
  80. worker := worker.NewWorker()
  81. worker.RegisterDriver("porter.deploy", NewPorterDriver)
  82. worker.SetDefaultDriver("porter.deploy")
  83. if hasDeploymentHookEnvVars() {
  84. deplNamespace := os.Getenv("PORTER_NAMESPACE")
  85. if deplNamespace == "" {
  86. return fmt.Errorf("namespace must be set by PORTER_NAMESPACE")
  87. }
  88. deploymentHook, err := NewDeploymentHook(client, resGroup, deplNamespace)
  89. if err != nil {
  90. return err
  91. }
  92. worker.RegisterHook("deployment", deploymentHook)
  93. }
  94. cloneEnvGroupHook := NewCloneEnvGroupHook(client, resGroup)
  95. worker.RegisterHook("cloneenvgroup", cloneEnvGroupHook)
  96. return worker.Apply(resGroup, &switchboardTypes.ApplyOpts{
  97. BasePath: basePath,
  98. })
  99. }
  100. func hasDeploymentHookEnvVars() bool {
  101. if ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID"); ghIDStr == "" {
  102. return false
  103. }
  104. if prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID"); prIDStr == "" {
  105. return false
  106. }
  107. if branchName := os.Getenv("PORTER_BRANCH_NAME"); branchName == "" {
  108. return false
  109. }
  110. if actionIDStr := os.Getenv("PORTER_ACTION_ID"); actionIDStr == "" {
  111. return false
  112. }
  113. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName == "" {
  114. return false
  115. }
  116. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner == "" {
  117. return false
  118. }
  119. if prName := os.Getenv("PORTER_PR_NAME"); prName == "" {
  120. return false
  121. }
  122. return true
  123. }
  124. type Source struct {
  125. Name string
  126. Repo string
  127. Version string
  128. IsApplication bool
  129. SourceValues map[string]interface{}
  130. }
  131. type Target struct {
  132. Project uint
  133. Cluster uint
  134. Namespace string
  135. }
  136. type ApplicationConfig struct {
  137. WaitForJob bool
  138. // If set to true, this does not run an update, it only creates the initial application and job,
  139. // skipping subsequent updates
  140. OnlyCreate bool
  141. Build struct {
  142. ForceBuild bool
  143. ForcePush bool
  144. UseCache bool
  145. Method string
  146. Context string
  147. Dockerfile string
  148. Image string
  149. Builder string
  150. Buildpacks []string
  151. }
  152. EnvGroups []types.EnvGroupMeta
  153. Values map[string]interface{}
  154. }
  155. type Driver struct {
  156. source *Source
  157. target *Target
  158. output map[string]interface{}
  159. lookupTable *map[string]drivers.Driver
  160. logger *zerolog.Logger
  161. }
  162. func NewPorterDriver(resource *models.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  163. driver := &Driver{
  164. lookupTable: opts.DriverLookupTable,
  165. logger: opts.Logger,
  166. output: make(map[string]interface{}),
  167. }
  168. source := &Source{}
  169. err := getSource(resource.Source, source)
  170. if err != nil {
  171. return nil, err
  172. }
  173. driver.source = source
  174. target := &Target{}
  175. err = getTarget(resource.Target, target)
  176. if err != nil {
  177. return nil, err
  178. }
  179. driver.target = target
  180. return driver, nil
  181. }
  182. func (d *Driver) ShouldApply(resource *models.Resource) bool {
  183. return true
  184. }
  185. func (d *Driver) Apply(resource *models.Resource) (*models.Resource, error) {
  186. client := GetAPIClient(config)
  187. name := resource.Name
  188. if name == "" {
  189. return nil, fmt.Errorf("empty app name")
  190. }
  191. _, err := client.GetRelease(
  192. context.Background(),
  193. d.target.Project,
  194. d.target.Cluster,
  195. d.target.Namespace,
  196. resource.Name,
  197. )
  198. shouldCreate := err != nil
  199. if err != nil {
  200. color.New(color.FgYellow).Printf("Could not read release %s/%s (%s): attempting creation\n", d.target.Namespace, resource.Name, err.Error())
  201. }
  202. if d.source.IsApplication {
  203. return d.applyApplication(resource, client, shouldCreate)
  204. }
  205. return d.applyAddon(resource, client, shouldCreate)
  206. }
  207. // Simple apply for addons
  208. func (d *Driver) applyAddon(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  209. var err error
  210. if shouldCreate {
  211. err = client.DeployAddon(
  212. context.Background(),
  213. d.target.Project,
  214. d.target.Cluster,
  215. d.target.Namespace,
  216. &types.CreateAddonRequest{
  217. CreateReleaseBaseRequest: &types.CreateReleaseBaseRequest{
  218. RepoURL: d.source.Repo,
  219. TemplateName: d.source.Name,
  220. TemplateVersion: d.source.Version,
  221. Values: resource.Config,
  222. Name: resource.Name,
  223. },
  224. },
  225. )
  226. } else {
  227. bytes, err := json.Marshal(resource.Config)
  228. if err != nil {
  229. return nil, err
  230. }
  231. err = client.UpgradeRelease(
  232. context.Background(),
  233. d.target.Project,
  234. d.target.Cluster,
  235. d.target.Namespace,
  236. resource.Name,
  237. &types.UpgradeReleaseRequest{
  238. Values: string(bytes),
  239. },
  240. )
  241. }
  242. if err != nil {
  243. return nil, err
  244. }
  245. if err = d.assignOutput(resource, client); err != nil {
  246. return nil, err
  247. }
  248. return resource, err
  249. }
  250. func (d *Driver) applyApplication(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  251. appConfig, err := d.getApplicationConfig(resource)
  252. if err != nil {
  253. return nil, err
  254. }
  255. method := appConfig.Build.Method
  256. if method != "pack" && method != "docker" && method != "registry" {
  257. return nil, fmt.Errorf("method should either be \"docker\", \"pack\" or \"registry\"")
  258. }
  259. fullPath, err := filepath.Abs(appConfig.Build.Context)
  260. if err != nil {
  261. return nil, err
  262. }
  263. tag := os.Getenv("PORTER_TAG")
  264. if tag == "" {
  265. commit, err := git.LastCommit()
  266. if err != nil {
  267. return nil, err
  268. }
  269. tag = commit.Sha[:7]
  270. }
  271. // if the method is registry and a tag is defined, we use the provided tag
  272. if appConfig.Build.Method == "registry" {
  273. imageSpl := strings.Split(appConfig.Build.Image, ":")
  274. if len(imageSpl) == 2 {
  275. tag = imageSpl[1]
  276. }
  277. if tag == "" {
  278. tag = "latest"
  279. }
  280. }
  281. sharedOpts := &deploy.SharedOpts{
  282. ProjectID: d.target.Project,
  283. ClusterID: d.target.Cluster,
  284. Namespace: d.target.Namespace,
  285. LocalPath: fullPath,
  286. LocalDockerfile: appConfig.Build.Dockerfile,
  287. OverrideTag: tag,
  288. Method: deploy.DeployBuildType(method),
  289. EnvGroups: appConfig.EnvGroups,
  290. UseCache: appConfig.Build.UseCache,
  291. }
  292. if appConfig.Build.UseCache {
  293. err := setDockerConfig(client)
  294. if err != nil {
  295. return nil, err
  296. }
  297. }
  298. if shouldCreate {
  299. resource, err = d.createApplication(resource, client, sharedOpts, appConfig)
  300. if err != nil {
  301. return nil, err
  302. }
  303. } else if !appConfig.OnlyCreate {
  304. resource, err = d.updateApplication(resource, client, sharedOpts, appConfig)
  305. if err != nil {
  306. return nil, err
  307. }
  308. } else {
  309. color.New(color.FgYellow).Printf("Skipping creation for %s as onlyCreate is set to true\n", resource.Name)
  310. }
  311. if err = d.assignOutput(resource, client); err != nil {
  312. return nil, err
  313. }
  314. if d.source.Name == "job" && appConfig.WaitForJob && (shouldCreate || !appConfig.OnlyCreate) {
  315. color.New(color.FgYellow).Printf("Waiting for job '%s' to finish\n", resource.Name)
  316. prevProject := config.Project
  317. prevCluster := config.Cluster
  318. name = resource.Name
  319. namespace = d.target.Namespace
  320. config.Project = d.target.Project
  321. config.Cluster = d.target.Cluster
  322. err = waitForJob(nil, client, []string{})
  323. if err != nil {
  324. return nil, err
  325. }
  326. config.Project = prevProject
  327. config.Cluster = prevCluster
  328. }
  329. return resource, err
  330. }
  331. func (d *Driver) createApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  332. // create new release
  333. color.New(color.FgGreen).Printf("Creating %s release: %s\n", d.source.Name, resource.Name)
  334. regList, err := client.ListRegistries(context.Background(), d.target.Project)
  335. if err != nil {
  336. return nil, err
  337. }
  338. var registryURL string
  339. if len(*regList) == 0 {
  340. return nil, fmt.Errorf("no registry found")
  341. } else {
  342. registryURL = (*regList)[0].URL
  343. }
  344. // attempt to get repo suffix from environment variables
  345. var repoSuffix string
  346. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
  347. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
  348. repoSuffix = strings.ReplaceAll(fmt.Sprintf("%s-%s", repoOwner, repoName), "_", "-")
  349. }
  350. }
  351. createAgent := &deploy.CreateAgent{
  352. Client: client,
  353. CreateOpts: &deploy.CreateOpts{
  354. SharedOpts: sharedOpts,
  355. Kind: d.source.Name,
  356. ReleaseName: resource.Name,
  357. RegistryURL: registryURL,
  358. RepoSuffix: repoSuffix,
  359. },
  360. }
  361. var buildConfig *types.BuildConfig
  362. if appConf.Build.Builder != "" {
  363. buildConfig = &types.BuildConfig{
  364. Builder: appConf.Build.Builder,
  365. Buildpacks: appConf.Build.Buildpacks,
  366. }
  367. }
  368. var subdomain string
  369. if appConf.Build.Method == "registry" {
  370. subdomain, err = createAgent.CreateFromRegistry(appConf.Build.Image, appConf.Values)
  371. } else {
  372. subdomain, err = createAgent.CreateFromDocker(appConf.Values, sharedOpts.OverrideTag, buildConfig, appConf.Build.ForceBuild)
  373. }
  374. if err != nil {
  375. return nil, err
  376. }
  377. return resource, handleSubdomainCreate(subdomain, err)
  378. }
  379. func (d *Driver) updateApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  380. color.New(color.FgGreen).Println("Updating existing release:", resource.Name)
  381. updateAgent, err := deploy.NewDeployAgent(client, resource.Name, &deploy.DeployOpts{
  382. SharedOpts: sharedOpts,
  383. Local: appConf.Build.Method != "registry",
  384. })
  385. if err != nil {
  386. return nil, err
  387. }
  388. // if the build method is registry, we do not trigger a build
  389. if appConf.Build.Method != "registry" {
  390. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  391. UseNewConfig: true,
  392. NewConfig: appConf.Values,
  393. })
  394. if err != nil {
  395. return nil, err
  396. }
  397. err = updateAgent.SetBuildEnv(buildEnv)
  398. if err != nil {
  399. return nil, err
  400. }
  401. var buildConfig *types.BuildConfig
  402. if appConf.Build.Builder != "" {
  403. buildConfig = &types.BuildConfig{
  404. Builder: appConf.Build.Builder,
  405. Buildpacks: appConf.Build.Buildpacks,
  406. }
  407. }
  408. err = updateAgent.Build(buildConfig, appConf.Build.ForceBuild)
  409. if err != nil {
  410. return nil, err
  411. }
  412. if !appConf.Build.UseCache {
  413. err = updateAgent.Push(appConf.Build.ForcePush)
  414. if err != nil {
  415. return nil, err
  416. }
  417. }
  418. }
  419. err = updateAgent.UpdateImageAndValues(appConf.Values)
  420. if err != nil {
  421. return nil, err
  422. }
  423. return resource, nil
  424. }
  425. func (d *Driver) assignOutput(resource *models.Resource, client *api.Client) error {
  426. release, err := client.GetRelease(
  427. context.Background(),
  428. d.target.Project,
  429. d.target.Cluster,
  430. d.target.Namespace,
  431. resource.Name,
  432. )
  433. if err != nil {
  434. return err
  435. }
  436. d.output = utils.CoalesceValues(d.source.SourceValues, release.Config)
  437. return nil
  438. }
  439. func (d *Driver) Output() (map[string]interface{}, error) {
  440. return d.output, nil
  441. }
  442. func getSource(input map[string]interface{}, output *Source) error {
  443. // first read from env vars
  444. output.Name = os.Getenv("PORTER_SOURCE_NAME")
  445. output.Repo = os.Getenv("PORTER_SOURCE_REPO")
  446. output.Version = os.Getenv("PORTER_SOURCE_VERSION")
  447. // next, check for values in the YAML file
  448. if output.Name == "" {
  449. if name, ok := input["name"]; ok {
  450. nameVal, ok := name.(string)
  451. if !ok {
  452. return fmt.Errorf("invalid name provided")
  453. }
  454. output.Name = nameVal
  455. }
  456. }
  457. if output.Name == "" {
  458. return fmt.Errorf("source name required")
  459. }
  460. if output.Repo == "" {
  461. if repo, ok := input["repo"]; ok {
  462. repoVal, ok := repo.(string)
  463. if !ok {
  464. return fmt.Errorf("invalid repo provided")
  465. }
  466. output.Repo = repoVal
  467. }
  468. }
  469. if output.Version == "" {
  470. if version, ok := input["version"]; ok {
  471. versionVal, ok := version.(string)
  472. if !ok {
  473. return fmt.Errorf("invalid version provided")
  474. }
  475. output.Version = versionVal
  476. }
  477. }
  478. // lastly, just put in the defaults
  479. if output.Version == "" {
  480. output.Version = "latest"
  481. }
  482. output.IsApplication = output.Repo == "https://charts.getporter.dev"
  483. if output.Repo == "" {
  484. output.Repo = "https://charts.getporter.dev"
  485. values, err := existsInRepo(output.Name, output.Version, output.Repo)
  486. if err == nil {
  487. // found in "https://charts.getporter.dev"
  488. output.SourceValues = values
  489. output.IsApplication = true
  490. return nil
  491. }
  492. output.Repo = "https://chart-addons.getporter.dev"
  493. values, err = existsInRepo(output.Name, output.Version, output.Repo)
  494. if err == nil {
  495. // found in https://chart-addons.getporter.dev
  496. output.SourceValues = values
  497. return nil
  498. }
  499. return fmt.Errorf("source does not exist in any repo")
  500. }
  501. return fmt.Errorf("source '%s' does not exist in repo '%s'", output.Name, output.Repo)
  502. }
  503. func getTarget(input map[string]interface{}, output *Target) error {
  504. // first read from env vars
  505. if projectEnv := os.Getenv("PORTER_PROJECT"); projectEnv != "" {
  506. project, err := strconv.Atoi(projectEnv)
  507. if err != nil {
  508. return err
  509. }
  510. output.Project = uint(project)
  511. }
  512. if clusterEnv := os.Getenv("PORTER_CLUSTER"); clusterEnv != "" {
  513. cluster, err := strconv.Atoi(clusterEnv)
  514. if err != nil {
  515. return err
  516. }
  517. output.Cluster = uint(cluster)
  518. }
  519. output.Namespace = os.Getenv("PORTER_NAMESPACE")
  520. // next, check for values in the YAML file
  521. if output.Project == 0 {
  522. if project, ok := input["project"]; ok {
  523. projectVal, ok := project.(uint)
  524. if !ok {
  525. return fmt.Errorf("project value must be an integer")
  526. }
  527. output.Project = projectVal
  528. }
  529. }
  530. if output.Cluster == 0 {
  531. if cluster, ok := input["cluster"]; ok {
  532. clusterVal, ok := cluster.(uint)
  533. if !ok {
  534. return fmt.Errorf("cluster value must be an integer")
  535. }
  536. output.Cluster = clusterVal
  537. }
  538. }
  539. if output.Namespace == "" {
  540. if namespace, ok := input["namespace"]; ok {
  541. namespaceVal, ok := namespace.(string)
  542. if !ok {
  543. return fmt.Errorf("invalid namespace provided")
  544. }
  545. output.Namespace = namespaceVal
  546. }
  547. }
  548. // lastly, just put in the defaults
  549. if output.Project == 0 {
  550. output.Project = config.Project
  551. }
  552. if output.Cluster == 0 {
  553. output.Cluster = config.Cluster
  554. }
  555. if output.Namespace == "" {
  556. output.Namespace = "default"
  557. }
  558. return nil
  559. }
  560. func (d *Driver) getApplicationConfig(resource *models.Resource) (*ApplicationConfig, error) {
  561. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  562. RawConf: resource.Config,
  563. LookupTable: *d.lookupTable,
  564. Dependencies: resource.Dependencies,
  565. })
  566. if err != nil {
  567. return nil, err
  568. }
  569. config := &ApplicationConfig{}
  570. err = mapstructure.Decode(populatedConf, config)
  571. if err != nil {
  572. return nil, err
  573. }
  574. if _, ok := resource.Config["waitForJob"]; !ok && d.source.Name == "job" {
  575. // default to true and wait for the job to finish
  576. config.WaitForJob = true
  577. }
  578. return config, nil
  579. }
  580. func existsInRepo(name, version, url string) (map[string]interface{}, error) {
  581. chart, err := GetAPIClient(config).GetTemplate(
  582. context.Background(),
  583. name, version,
  584. &types.GetTemplateRequest{
  585. TemplateGetBaseRequest: types.TemplateGetBaseRequest{
  586. RepoURL: url,
  587. },
  588. },
  589. )
  590. if err != nil {
  591. return nil, err
  592. }
  593. return chart.Values, nil
  594. }
  595. type DeploymentHook struct {
  596. client *api.Client
  597. resourceGroup *switchboardTypes.ResourceGroup
  598. gitInstallationID, projectID, clusterID, prID, actionID uint
  599. branch, namespace, repoName, repoOwner, prName, commitSHA string
  600. }
  601. func NewDeploymentHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup, namespace string) (*DeploymentHook, error) {
  602. res := &DeploymentHook{
  603. client: client,
  604. resourceGroup: resourceGroup,
  605. namespace: namespace,
  606. }
  607. ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID")
  608. ghID, err := strconv.Atoi(ghIDStr)
  609. if err != nil {
  610. return nil, err
  611. }
  612. res.gitInstallationID = uint(ghID)
  613. prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID")
  614. prID, err := strconv.Atoi(prIDStr)
  615. if err != nil {
  616. return nil, err
  617. }
  618. res.prID = uint(prID)
  619. res.projectID = config.Project
  620. if res.projectID == 0 {
  621. return nil, fmt.Errorf("project id must be set")
  622. }
  623. res.clusterID = config.Cluster
  624. if res.clusterID == 0 {
  625. return nil, fmt.Errorf("cluster id must be set")
  626. }
  627. branchName := os.Getenv("PORTER_BRANCH_NAME")
  628. res.branch = branchName
  629. actionIDStr := os.Getenv("PORTER_ACTION_ID")
  630. actionID, err := strconv.Atoi(actionIDStr)
  631. if err != nil {
  632. return nil, err
  633. }
  634. res.actionID = uint(actionID)
  635. repoName := os.Getenv("PORTER_REPO_NAME")
  636. res.repoName = repoName
  637. repoOwner := os.Getenv("PORTER_REPO_OWNER")
  638. res.repoOwner = repoOwner
  639. prName := os.Getenv("PORTER_PR_NAME")
  640. res.prName = prName
  641. commit, err := git.LastCommit()
  642. if err != nil {
  643. return nil, fmt.Errorf(err.Error())
  644. }
  645. res.commitSHA = commit.Sha[:7]
  646. return res, nil
  647. }
  648. func (t *DeploymentHook) PreApply() error {
  649. // attempt to read the deployment -- if it doesn't exist, create it
  650. _, err := t.client.GetDeployment(
  651. context.Background(),
  652. t.projectID, t.gitInstallationID, t.clusterID,
  653. t.repoOwner, t.repoName,
  654. &types.GetDeploymentRequest{
  655. Namespace: t.namespace,
  656. },
  657. )
  658. // TODO: case this on the response status code rather than text
  659. if err != nil && strings.Contains(err.Error(), "deployment not found") {
  660. // in this case, create the deployment
  661. _, err = t.client.CreateDeployment(
  662. context.Background(),
  663. t.projectID, t.gitInstallationID, t.clusterID,
  664. t.repoOwner, t.repoName,
  665. &types.CreateDeploymentRequest{
  666. Namespace: t.namespace,
  667. PullRequestID: t.prID,
  668. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  669. Branch: t.branch,
  670. ActionID: t.actionID,
  671. },
  672. GitHubMetadata: &types.GitHubMetadata{
  673. PRName: t.prName,
  674. RepoName: t.repoName,
  675. RepoOwner: t.repoOwner,
  676. CommitSHA: t.commitSHA,
  677. },
  678. },
  679. )
  680. } else if err == nil {
  681. _, err = t.client.UpdateDeployment(
  682. context.Background(),
  683. t.projectID, t.gitInstallationID, t.clusterID,
  684. t.repoOwner, t.repoName,
  685. &types.UpdateDeploymentRequest{
  686. Namespace: t.namespace,
  687. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  688. Branch: t.branch,
  689. ActionID: t.actionID,
  690. },
  691. CommitSHA: t.commitSHA,
  692. },
  693. )
  694. }
  695. return err
  696. }
  697. func (t *DeploymentHook) DataQueries() map[string]interface{} {
  698. res := make(map[string]interface{})
  699. // use the resource group to find all web applications that can have an exposed subdomain
  700. // that we can query for
  701. for _, resource := range t.resourceGroup.Resources {
  702. isWeb := false
  703. if sourceNameInter, exists := resource.Source["name"]; exists {
  704. if sourceName, ok := sourceNameInter.(string); ok {
  705. if sourceName == "web" {
  706. isWeb = true
  707. }
  708. }
  709. }
  710. if isWeb {
  711. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.porter_hosts[0] }", resource.Name)
  712. }
  713. }
  714. return res
  715. }
  716. func (t *DeploymentHook) PostApply(populatedData map[string]interface{}) error {
  717. subdomains := make([]string, 0)
  718. for _, data := range populatedData {
  719. domain, ok := data.(string)
  720. if !ok {
  721. continue
  722. }
  723. if _, err := url.Parse("https://" + domain); err == nil {
  724. subdomains = append(subdomains, "https://"+domain)
  725. }
  726. }
  727. // finalize the deployment
  728. _, err := t.client.FinalizeDeployment(
  729. context.Background(),
  730. t.projectID, t.gitInstallationID, t.clusterID,
  731. t.repoOwner, t.repoName,
  732. &types.FinalizeDeploymentRequest{
  733. Namespace: t.namespace,
  734. Subdomain: strings.Join(subdomains, ","),
  735. },
  736. )
  737. return err
  738. }
  739. func (t *DeploymentHook) OnError(err error) {
  740. // if the deployment exists, throw an error for that deployment
  741. _, getDeplErr := t.client.GetDeployment(
  742. context.Background(),
  743. t.projectID, t.gitInstallationID, t.clusterID,
  744. t.repoOwner, t.repoName,
  745. &types.GetDeploymentRequest{
  746. Namespace: t.namespace,
  747. },
  748. )
  749. if getDeplErr == nil {
  750. _, err = t.client.UpdateDeploymentStatus(
  751. context.Background(),
  752. t.projectID, t.gitInstallationID, t.clusterID,
  753. t.repoOwner, t.repoName,
  754. &types.UpdateDeploymentStatusRequest{
  755. Namespace: t.namespace,
  756. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  757. Branch: t.branch,
  758. ActionID: t.actionID,
  759. },
  760. Status: string(types.DeploymentStatusFailed),
  761. },
  762. )
  763. }
  764. }
  765. type CloneEnvGroupHook struct {
  766. client *api.Client
  767. resGroup *switchboardTypes.ResourceGroup
  768. }
  769. func NewCloneEnvGroupHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup) *CloneEnvGroupHook {
  770. return &CloneEnvGroupHook{
  771. client: client,
  772. resGroup: resourceGroup,
  773. }
  774. }
  775. func (t *CloneEnvGroupHook) PreApply() error {
  776. for _, res := range t.resGroup.Resources {
  777. config := &ApplicationConfig{}
  778. err := mapstructure.Decode(res.Config, &config)
  779. if err != nil {
  780. continue
  781. }
  782. if config != nil && len(config.EnvGroups) > 0 {
  783. target := &Target{}
  784. err = getTarget(res.Target, target)
  785. if err != nil {
  786. return err
  787. }
  788. for _, group := range config.EnvGroups {
  789. if group.Name == "" {
  790. return fmt.Errorf("env group name cannot be empty")
  791. }
  792. _, err := t.client.GetEnvGroup(
  793. context.Background(),
  794. target.Project,
  795. target.Cluster,
  796. target.Namespace,
  797. &types.GetEnvGroupRequest{
  798. Name: group.Name,
  799. Version: group.Version,
  800. },
  801. )
  802. if err != nil && err.Error() == "env group not found" {
  803. if group.Namespace == "" {
  804. return fmt.Errorf("env group namespace cannot be empty")
  805. }
  806. color.New(color.FgBlue, color.Bold).
  807. Printf("Env group '%s' does not exist in the target namespace '%s'\n", group.Name, target.Namespace)
  808. color.New(color.FgBlue, color.Bold).
  809. Printf("Cloning env group '%s' from namespace '%s' to target namespace '%s'\n",
  810. group.Name, group.Namespace, target.Namespace)
  811. _, err = t.client.CloneEnvGroup(
  812. context.Background(), target.Project, target.Cluster, group.Namespace,
  813. &types.CloneEnvGroupRequest{
  814. Name: group.Name,
  815. Namespace: target.Namespace,
  816. },
  817. )
  818. if err != nil {
  819. return err
  820. }
  821. } else if err != nil {
  822. return err
  823. }
  824. }
  825. }
  826. }
  827. return nil
  828. }
  829. func (t *CloneEnvGroupHook) DataQueries() map[string]interface{} {
  830. return nil
  831. }
  832. func (t *CloneEnvGroupHook) PostApply(populatedData map[string]interface{}) error {
  833. return nil
  834. }
  835. func (t *CloneEnvGroupHook) OnError(err error) {}