apply.go 26 KB

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