apply.go 28 KB

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