2
0

apply.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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. if err != nil {
  227. return nil, err
  228. }
  229. } else {
  230. bytes, err := json.Marshal(addonConfig)
  231. if err != nil {
  232. return nil, err
  233. }
  234. err = client.UpgradeRelease(
  235. context.Background(),
  236. d.target.Project,
  237. d.target.Cluster,
  238. d.target.Namespace,
  239. resource.Name,
  240. &types.UpgradeReleaseRequest{
  241. Values: string(bytes),
  242. },
  243. )
  244. if err != nil {
  245. return nil, err
  246. }
  247. }
  248. if err = d.assignOutput(resource, client); err != nil {
  249. return nil, err
  250. }
  251. return resource, nil
  252. }
  253. func (d *Driver) applyApplication(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  254. appConfig, err := d.getApplicationConfig(resource)
  255. if err != nil {
  256. return nil, err
  257. }
  258. method := appConfig.Build.Method
  259. if method != "pack" && method != "docker" && method != "registry" {
  260. return nil, fmt.Errorf("method should either be \"docker\", \"pack\" or \"registry\"")
  261. }
  262. fullPath, err := filepath.Abs(appConfig.Build.Context)
  263. if err != nil {
  264. return nil, err
  265. }
  266. tag := os.Getenv("PORTER_TAG")
  267. if tag == "" {
  268. commit, err := git.LastCommit()
  269. if err != nil {
  270. return nil, err
  271. }
  272. tag = commit.Sha[:7]
  273. }
  274. // if the method is registry and a tag is defined, we use the provided tag
  275. if appConfig.Build.Method == "registry" {
  276. imageSpl := strings.Split(appConfig.Build.Image, ":")
  277. if len(imageSpl) == 2 {
  278. tag = imageSpl[1]
  279. }
  280. if tag == "" {
  281. tag = "latest"
  282. }
  283. }
  284. sharedOpts := &deploy.SharedOpts{
  285. ProjectID: d.target.Project,
  286. ClusterID: d.target.Cluster,
  287. Namespace: d.target.Namespace,
  288. LocalPath: fullPath,
  289. LocalDockerfile: appConfig.Build.Dockerfile,
  290. OverrideTag: tag,
  291. Method: deploy.DeployBuildType(method),
  292. EnvGroups: appConfig.EnvGroups,
  293. UseCache: appConfig.Build.UseCache,
  294. }
  295. if appConfig.Build.UseCache {
  296. // set the docker config so that pack caching can use the repo credentials
  297. err := config.SetDockerConfig(client)
  298. if err != nil {
  299. return nil, err
  300. }
  301. }
  302. if shouldCreate {
  303. resource, err = d.createApplication(resource, client, sharedOpts, appConfig)
  304. if err != nil {
  305. return nil, err
  306. }
  307. } else if !appConfig.OnlyCreate {
  308. resource, err = d.updateApplication(resource, client, sharedOpts, appConfig)
  309. if err != nil {
  310. return nil, err
  311. }
  312. } else {
  313. color.New(color.FgYellow).Printf("Skipping creation for %s as onlyCreate is set to true\n", resource.Name)
  314. }
  315. if err = d.assignOutput(resource, client); err != nil {
  316. return nil, err
  317. }
  318. if d.source.Name == "job" && appConfig.WaitForJob && (shouldCreate || !appConfig.OnlyCreate) {
  319. color.New(color.FgYellow).Printf("Waiting for job '%s' to finish\n", resource.Name)
  320. err = wait.WaitForJob(client, &wait.WaitOpts{
  321. ProjectID: d.target.Project,
  322. ClusterID: d.target.Cluster,
  323. Namespace: d.target.Namespace,
  324. Name: resource.Name,
  325. })
  326. if err != nil && appConfig.OnlyCreate {
  327. deleteJobErr := client.DeleteRelease(
  328. context.Background(),
  329. d.target.Project,
  330. d.target.Cluster,
  331. d.target.Namespace,
  332. resource.Name,
  333. )
  334. if deleteJobErr != nil {
  335. return nil, fmt.Errorf("error deleting job %s with waitForJob and onlyCreate set to true: %w",
  336. resource.Name, deleteJobErr)
  337. }
  338. } else if err != nil {
  339. return nil, fmt.Errorf("error waiting for job %s: %w", resource.Name, err)
  340. }
  341. }
  342. return resource, err
  343. }
  344. func (d *Driver) createApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  345. // create new release
  346. color.New(color.FgGreen).Printf("Creating %s release: %s\n", d.source.Name, resource.Name)
  347. regList, err := client.ListRegistries(context.Background(), d.target.Project)
  348. if err != nil {
  349. return nil, err
  350. }
  351. var registryURL string
  352. if len(*regList) == 0 {
  353. return nil, fmt.Errorf("no registry found")
  354. } else {
  355. registryURL = (*regList)[0].URL
  356. }
  357. // attempt to get repo suffix from environment variables
  358. var repoSuffix string
  359. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
  360. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
  361. repoSuffix = strings.ToLower(strings.ReplaceAll(fmt.Sprintf("%s-%s", repoOwner, repoName), "_", "-"))
  362. }
  363. }
  364. createAgent := &deploy.CreateAgent{
  365. Client: client,
  366. CreateOpts: &deploy.CreateOpts{
  367. SharedOpts: sharedOpts,
  368. Kind: d.source.Name,
  369. ReleaseName: resource.Name,
  370. RegistryURL: registryURL,
  371. RepoSuffix: repoSuffix,
  372. },
  373. }
  374. var buildConfig *types.BuildConfig
  375. if appConf.Build.Builder != "" {
  376. buildConfig = &types.BuildConfig{
  377. Builder: appConf.Build.Builder,
  378. Buildpacks: appConf.Build.Buildpacks,
  379. }
  380. }
  381. var subdomain string
  382. if appConf.Build.Method == "registry" {
  383. subdomain, err = createAgent.CreateFromRegistry(appConf.Build.Image, appConf.Values)
  384. } else {
  385. // if useCache is set, create the image repository first
  386. if appConf.Build.UseCache {
  387. regID, imageURL, err := createAgent.GetImageRepoURL(resource.Name, sharedOpts.Namespace)
  388. if err != nil {
  389. return nil, err
  390. }
  391. err = client.CreateRepository(
  392. context.Background(),
  393. sharedOpts.ProjectID,
  394. regID,
  395. &types.CreateRegistryRepositoryRequest{
  396. ImageRepoURI: imageURL,
  397. },
  398. )
  399. if err != nil {
  400. return nil, err
  401. }
  402. }
  403. subdomain, err = createAgent.CreateFromDocker(appConf.Values, sharedOpts.OverrideTag, buildConfig)
  404. }
  405. if err != nil {
  406. return nil, err
  407. }
  408. return resource, handleSubdomainCreate(subdomain, err)
  409. }
  410. func (d *Driver) updateApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  411. color.New(color.FgGreen).Println("Updating existing release:", resource.Name)
  412. if len(appConf.Build.Env) > 0 {
  413. sharedOpts.AdditionalEnv = appConf.Build.Env
  414. }
  415. updateAgent, err := deploy.NewDeployAgent(client, resource.Name, &deploy.DeployOpts{
  416. SharedOpts: sharedOpts,
  417. Local: appConf.Build.Method != "registry",
  418. })
  419. if err != nil {
  420. return nil, err
  421. }
  422. // if the build method is registry, we do not trigger a build
  423. if appConf.Build.Method != "registry" {
  424. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  425. UseNewConfig: true,
  426. NewConfig: appConf.Values,
  427. })
  428. if err != nil {
  429. return nil, err
  430. }
  431. err = updateAgent.SetBuildEnv(buildEnv)
  432. if err != nil {
  433. return nil, err
  434. }
  435. var buildConfig *types.BuildConfig
  436. if appConf.Build.Builder != "" {
  437. buildConfig = &types.BuildConfig{
  438. Builder: appConf.Build.Builder,
  439. Buildpacks: appConf.Build.Buildpacks,
  440. }
  441. }
  442. err = updateAgent.Build(buildConfig)
  443. if err != nil {
  444. return nil, err
  445. }
  446. if !appConf.Build.UseCache {
  447. err = updateAgent.Push()
  448. if err != nil {
  449. return nil, err
  450. }
  451. }
  452. }
  453. err = updateAgent.UpdateImageAndValues(appConf.Values)
  454. if err != nil {
  455. return nil, err
  456. }
  457. return resource, nil
  458. }
  459. func (d *Driver) assignOutput(resource *models.Resource, client *api.Client) error {
  460. release, err := client.GetRelease(
  461. context.Background(),
  462. d.target.Project,
  463. d.target.Cluster,
  464. d.target.Namespace,
  465. resource.Name,
  466. )
  467. if err != nil {
  468. return err
  469. }
  470. d.output = utils.CoalesceValues(d.source.SourceValues, release.Config)
  471. return nil
  472. }
  473. func (d *Driver) Output() (map[string]interface{}, error) {
  474. return d.output, nil
  475. }
  476. func (d *Driver) getApplicationConfig(resource *models.Resource) (*ApplicationConfig, error) {
  477. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  478. RawConf: resource.Config,
  479. LookupTable: *d.lookupTable,
  480. Dependencies: resource.Dependencies,
  481. })
  482. if err != nil {
  483. return nil, err
  484. }
  485. config := &ApplicationConfig{}
  486. err = mapstructure.Decode(populatedConf, config)
  487. if err != nil {
  488. return nil, err
  489. }
  490. if _, ok := resource.Config["waitForJob"]; !ok && d.source.Name == "job" {
  491. // default to true and wait for the job to finish
  492. config.WaitForJob = true
  493. }
  494. return config, nil
  495. }
  496. func (d *Driver) getAddonConfig(resource *models.Resource) (map[string]interface{}, error) {
  497. return drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  498. RawConf: resource.Config,
  499. LookupTable: *d.lookupTable,
  500. Dependencies: resource.Dependencies,
  501. })
  502. }
  503. type DeploymentHook struct {
  504. client *api.Client
  505. resourceGroup *switchboardTypes.ResourceGroup
  506. gitInstallationID, projectID, clusterID, prID, actionID, envID uint
  507. branchFrom, branchInto, namespace, repoName, repoOwner, prName, commitSHA string
  508. }
  509. func NewDeploymentHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup, namespace string) (*DeploymentHook, error) {
  510. res := &DeploymentHook{
  511. client: client,
  512. resourceGroup: resourceGroup,
  513. namespace: namespace,
  514. }
  515. ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID")
  516. ghID, err := strconv.Atoi(ghIDStr)
  517. if err != nil {
  518. return nil, err
  519. }
  520. res.gitInstallationID = uint(ghID)
  521. prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID")
  522. prID, err := strconv.Atoi(prIDStr)
  523. if err != nil {
  524. return nil, err
  525. }
  526. res.prID = uint(prID)
  527. res.projectID = cliConf.Project
  528. if res.projectID == 0 {
  529. return nil, fmt.Errorf("project id must be set")
  530. }
  531. res.clusterID = cliConf.Cluster
  532. if res.clusterID == 0 {
  533. return nil, fmt.Errorf("cluster id must be set")
  534. }
  535. branchFrom := os.Getenv("PORTER_BRANCH_FROM")
  536. res.branchFrom = branchFrom
  537. branchInto := os.Getenv("PORTER_BRANCH_INTO")
  538. res.branchInto = branchInto
  539. actionIDStr := os.Getenv("PORTER_ACTION_ID")
  540. actionID, err := strconv.Atoi(actionIDStr)
  541. if err != nil {
  542. return nil, err
  543. }
  544. res.actionID = uint(actionID)
  545. repoName := os.Getenv("PORTER_REPO_NAME")
  546. res.repoName = repoName
  547. repoOwner := os.Getenv("PORTER_REPO_OWNER")
  548. res.repoOwner = repoOwner
  549. prName := os.Getenv("PORTER_PR_NAME")
  550. res.prName = prName
  551. commit, err := git.LastCommit()
  552. if err != nil {
  553. return nil, fmt.Errorf(err.Error())
  554. }
  555. res.commitSHA = commit.Sha[:7]
  556. return res, nil
  557. }
  558. func (t *DeploymentHook) PreApply() error {
  559. envList, err := t.client.ListEnvironments(
  560. context.Background(), t.projectID, t.clusterID,
  561. )
  562. if err != nil {
  563. return err
  564. }
  565. envs := *envList
  566. for _, env := range envs {
  567. if env.GitRepoOwner == t.repoOwner && env.GitRepoName == t.repoName && env.GitInstallationID == t.gitInstallationID {
  568. t.envID = env.ID
  569. break
  570. }
  571. }
  572. if t.envID == 0 {
  573. return fmt.Errorf("could not find environment for deployment")
  574. }
  575. // attempt to read the deployment -- if it doesn't exist, create it
  576. _, err = t.client.GetDeployment(
  577. context.Background(),
  578. t.projectID, t.clusterID, t.envID,
  579. &types.GetDeploymentRequest{
  580. Namespace: t.namespace,
  581. },
  582. )
  583. if err != nil && strings.Contains(err.Error(), "not found") {
  584. // in this case, create the deployment
  585. _, err = t.client.CreateDeployment(
  586. context.Background(),
  587. t.projectID, t.gitInstallationID, t.clusterID,
  588. t.repoOwner, t.repoName,
  589. &types.CreateDeploymentRequest{
  590. Namespace: t.namespace,
  591. PullRequestID: t.prID,
  592. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  593. ActionID: t.actionID,
  594. },
  595. GitHubMetadata: &types.GitHubMetadata{
  596. PRName: t.prName,
  597. RepoName: t.repoName,
  598. RepoOwner: t.repoOwner,
  599. CommitSHA: t.commitSHA,
  600. PRBranchFrom: t.branchFrom,
  601. PRBranchInto: t.branchInto,
  602. },
  603. },
  604. )
  605. } else if err == nil {
  606. _, err = t.client.UpdateDeployment(
  607. context.Background(),
  608. t.projectID, t.gitInstallationID, t.clusterID,
  609. t.repoOwner, t.repoName,
  610. &types.UpdateDeploymentRequest{
  611. Namespace: t.namespace,
  612. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  613. ActionID: t.actionID,
  614. },
  615. PRBranchFrom: t.branchFrom,
  616. CommitSHA: t.commitSHA,
  617. },
  618. )
  619. }
  620. return err
  621. }
  622. func (t *DeploymentHook) DataQueries() map[string]interface{} {
  623. res := make(map[string]interface{})
  624. // use the resource group to find all web applications that can have an exposed subdomain
  625. // that we can query for
  626. for _, resource := range t.resourceGroup.Resources {
  627. isWeb := false
  628. if sourceNameInter, exists := resource.Source["name"]; exists {
  629. if sourceName, ok := sourceNameInter.(string); ok {
  630. if sourceName == "web" {
  631. isWeb = true
  632. }
  633. }
  634. }
  635. if isWeb {
  636. // determine if we should query for porter_hosts or just hosts
  637. isCustomDomain := false
  638. ingressMap, err := deploy.GetNestedMap(resource.Config, "values", "ingress")
  639. if err == nil {
  640. enabledVal, enabledExists := ingressMap["enabled"]
  641. customDomVal, customDomExists := ingressMap["custom_domain"]
  642. if enabledExists && customDomExists {
  643. enabled, eOK := enabledVal.(bool)
  644. customDomain, cOK := customDomVal.(bool)
  645. if eOK && cOK && enabled {
  646. if customDomain {
  647. // return the first custom domain when one exists
  648. hostsArr, hostsExists := ingressMap["hosts"]
  649. if hostsExists {
  650. hostsArrVal, hostsArrOk := hostsArr.([]interface{})
  651. if hostsArrOk && len(hostsArrVal) > 0 {
  652. if _, ok := hostsArrVal[0].(string); ok {
  653. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.hosts[0] }", resource.Name)
  654. isCustomDomain = true
  655. }
  656. }
  657. }
  658. }
  659. }
  660. }
  661. }
  662. if !isCustomDomain {
  663. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.porter_hosts[0] }", resource.Name)
  664. }
  665. }
  666. }
  667. return res
  668. }
  669. func (t *DeploymentHook) PostApply(populatedData map[string]interface{}) error {
  670. subdomains := make([]string, 0)
  671. for _, data := range populatedData {
  672. domain, ok := data.(string)
  673. if !ok {
  674. continue
  675. }
  676. if _, err := url.Parse("https://" + domain); err == nil {
  677. subdomains = append(subdomains, "https://"+domain)
  678. }
  679. }
  680. req := &types.FinalizeDeploymentRequest{
  681. Namespace: t.namespace,
  682. Subdomain: strings.Join(subdomains, ", "),
  683. }
  684. for _, res := range t.resourceGroup.Resources {
  685. releaseType := getReleaseType(res)
  686. releaseName := getReleaseName(res)
  687. if releaseType != "" && releaseName != "" {
  688. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  689. ReleaseName: releaseName,
  690. ReleaseType: releaseType,
  691. })
  692. }
  693. }
  694. // finalize the deployment
  695. _, err := t.client.FinalizeDeployment(
  696. context.Background(),
  697. t.projectID, t.gitInstallationID, t.clusterID,
  698. t.repoOwner, t.repoName, req,
  699. )
  700. return err
  701. }
  702. func (t *DeploymentHook) OnError(err error) {
  703. // if the deployment exists, throw an error for that deployment
  704. _, getDeplErr := t.client.GetDeployment(
  705. context.Background(),
  706. t.projectID, t.clusterID, t.envID,
  707. &types.GetDeploymentRequest{
  708. Namespace: t.namespace,
  709. },
  710. )
  711. if getDeplErr == nil {
  712. _, err = t.client.UpdateDeploymentStatus(
  713. context.Background(),
  714. t.projectID, t.gitInstallationID, t.clusterID,
  715. t.repoOwner, t.repoName,
  716. &types.UpdateDeploymentStatusRequest{
  717. Namespace: t.namespace,
  718. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  719. ActionID: t.actionID,
  720. },
  721. PRBranchFrom: t.branchFrom,
  722. Status: string(types.DeploymentStatusFailed),
  723. },
  724. )
  725. }
  726. }
  727. func (t *DeploymentHook) OnConsolidatedErrors(allErrors map[string]error) {
  728. // if the deployment exists, throw an error for that deployment
  729. _, getDeplErr := t.client.GetDeployment(
  730. context.Background(),
  731. t.projectID, t.clusterID, t.envID,
  732. &types.GetDeploymentRequest{
  733. Namespace: t.namespace,
  734. },
  735. )
  736. if getDeplErr == nil {
  737. req := &types.FinalizeDeploymentWithErrorsRequest{
  738. Namespace: t.namespace,
  739. Errors: make(map[string]string),
  740. }
  741. for _, res := range t.resourceGroup.Resources {
  742. if _, ok := allErrors[res.Name]; !ok {
  743. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  744. ReleaseName: getReleaseName(res),
  745. ReleaseType: getReleaseType(res),
  746. })
  747. }
  748. }
  749. for res, err := range allErrors {
  750. req.Errors[res] = err.Error()
  751. }
  752. // FIXME: handle the error
  753. t.client.FinalizeDeploymentWithErrors(
  754. context.Background(),
  755. t.projectID, t.gitInstallationID, t.clusterID,
  756. t.repoOwner, t.repoName,
  757. req,
  758. )
  759. }
  760. }
  761. type CloneEnvGroupHook struct {
  762. client *api.Client
  763. resGroup *switchboardTypes.ResourceGroup
  764. }
  765. func NewCloneEnvGroupHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup) *CloneEnvGroupHook {
  766. return &CloneEnvGroupHook{
  767. client: client,
  768. resGroup: resourceGroup,
  769. }
  770. }
  771. func (t *CloneEnvGroupHook) PreApply() error {
  772. for _, res := range t.resGroup.Resources {
  773. if res.Driver == "env-group" {
  774. continue
  775. }
  776. config := &ApplicationConfig{}
  777. err := mapstructure.Decode(res.Config, &config)
  778. if err != nil {
  779. continue
  780. }
  781. if config != nil && len(config.EnvGroups) > 0 {
  782. target, err := preview.GetTarget(res.Target)
  783. if err != nil {
  784. return err
  785. }
  786. for _, group := range config.EnvGroups {
  787. if group.Name == "" {
  788. return fmt.Errorf("env group name cannot be empty")
  789. }
  790. _, err := t.client.GetEnvGroup(
  791. context.Background(),
  792. target.Project,
  793. target.Cluster,
  794. target.Namespace,
  795. &types.GetEnvGroupRequest{
  796. Name: group.Name,
  797. Version: group.Version,
  798. },
  799. )
  800. if err != nil && err.Error() == "env group not found" {
  801. if group.Namespace == "" {
  802. return fmt.Errorf("env group namespace cannot be empty")
  803. }
  804. color.New(color.FgBlue, color.Bold).
  805. Printf("Env group '%s' does not exist in the target namespace '%s'\n", group.Name, target.Namespace)
  806. color.New(color.FgBlue, color.Bold).
  807. Printf("Cloning env group '%s' from namespace '%s' to target namespace '%s'\n",
  808. group.Name, group.Namespace, target.Namespace)
  809. _, err = t.client.CloneEnvGroup(
  810. context.Background(), target.Project, target.Cluster, group.Namespace,
  811. &types.CloneEnvGroupRequest{
  812. Name: group.Name,
  813. Namespace: target.Namespace,
  814. },
  815. )
  816. if err != nil {
  817. return err
  818. }
  819. } else if err != nil {
  820. return err
  821. }
  822. }
  823. }
  824. }
  825. return nil
  826. }
  827. func (t *CloneEnvGroupHook) DataQueries() map[string]interface{} {
  828. return nil
  829. }
  830. func (t *CloneEnvGroupHook) PostApply(map[string]interface{}) error {
  831. return nil
  832. }
  833. func (t *CloneEnvGroupHook) OnError(error) {}
  834. func (t *CloneEnvGroupHook) OnConsolidatedErrors(map[string]error) {}
  835. func getReleaseName(res *switchboardTypes.Resource) string {
  836. // can ignore the error because this method is called once
  837. // GetTarget has alrealy been called and validated previously
  838. target, _ := preview.GetTarget(res.Target)
  839. if target.AppName != "" {
  840. return target.AppName
  841. }
  842. return res.Name
  843. }
  844. func getReleaseType(res *switchboardTypes.Resource) string {
  845. // can ignore the error because this method is called once
  846. // GetSource has alrealy been called and validated previously
  847. source, _ := preview.GetSource(res.Source)
  848. if source != nil && source.Name != "" {
  849. return source.Name
  850. }
  851. return ""
  852. }