apply.go 27 KB

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