apply.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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.SetDefaultDriver("deploy")
  91. if hasDeploymentHookEnvVars() {
  92. deplNamespace := os.Getenv("PORTER_NAMESPACE")
  93. if deplNamespace == "" {
  94. return fmt.Errorf("namespace must be set by PORTER_NAMESPACE")
  95. }
  96. deploymentHook, err := NewDeploymentHook(client, resGroup, deplNamespace)
  97. if err != nil {
  98. return err
  99. }
  100. worker.RegisterHook("deployment", deploymentHook)
  101. }
  102. cloneEnvGroupHook := NewCloneEnvGroupHook(client, resGroup)
  103. worker.RegisterHook("cloneenvgroup", cloneEnvGroupHook)
  104. return worker.Apply(resGroup, &switchboardTypes.ApplyOpts{
  105. BasePath: basePath,
  106. })
  107. }
  108. func hasDeploymentHookEnvVars() bool {
  109. if ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID"); ghIDStr == "" {
  110. return false
  111. }
  112. if prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID"); prIDStr == "" {
  113. return false
  114. }
  115. if branchName := os.Getenv("PORTER_BRANCH_NAME"); branchName == "" {
  116. return false
  117. }
  118. if actionIDStr := os.Getenv("PORTER_ACTION_ID"); actionIDStr == "" {
  119. return false
  120. }
  121. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName == "" {
  122. return false
  123. }
  124. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner == "" {
  125. return false
  126. }
  127. if prName := os.Getenv("PORTER_PR_NAME"); prName == "" {
  128. return false
  129. }
  130. return true
  131. }
  132. type ApplicationConfig struct {
  133. WaitForJob bool
  134. // If set to true, this does not run an update, it only creates the initial application and job,
  135. // skipping subsequent updates
  136. OnlyCreate bool
  137. Build struct {
  138. ForceBuild bool `mapstructure:"force_build"`
  139. ForcePush bool `mapstructure:"force_push"`
  140. UseCache bool `mapstructure:"use_cache"`
  141. Method string
  142. Context string
  143. Dockerfile string
  144. Image string
  145. Builder string
  146. Buildpacks []string
  147. }
  148. EnvGroups []types.EnvGroupMeta `mapstructure:"env_groups"`
  149. Values map[string]interface{}
  150. }
  151. type Driver struct {
  152. source *preview.Source
  153. target *preview.Target
  154. output map[string]interface{}
  155. lookupTable *map[string]drivers.Driver
  156. logger *zerolog.Logger
  157. }
  158. func NewPorterDriver(resource *models.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  159. driver := &Driver{
  160. lookupTable: opts.DriverLookupTable,
  161. logger: opts.Logger,
  162. output: make(map[string]interface{}),
  163. }
  164. source, err := preview.GetSource(resource.Source)
  165. if err != nil {
  166. return nil, err
  167. }
  168. driver.source = source
  169. target, err := preview.GetTarget(resource.Target)
  170. if err != nil {
  171. return nil, err
  172. }
  173. driver.target = target
  174. return driver, nil
  175. }
  176. func (d *Driver) ShouldApply(resource *models.Resource) bool {
  177. return true
  178. }
  179. func (d *Driver) Apply(resource *models.Resource) (*models.Resource, error) {
  180. client := config.GetAPIClient()
  181. name := resource.Name
  182. if name == "" {
  183. return nil, fmt.Errorf("empty app name")
  184. }
  185. _, err := client.GetRelease(
  186. context.Background(),
  187. d.target.Project,
  188. d.target.Cluster,
  189. d.target.Namespace,
  190. resource.Name,
  191. )
  192. shouldCreate := err != nil
  193. if err != nil {
  194. color.New(color.FgYellow).Printf("Could not read release %s/%s (%s): attempting creation\n", d.target.Namespace, resource.Name, err.Error())
  195. }
  196. if d.source.IsApplication {
  197. return d.applyApplication(resource, client, shouldCreate)
  198. }
  199. return d.applyAddon(resource, client, shouldCreate)
  200. }
  201. // Simple apply for addons
  202. func (d *Driver) applyAddon(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  203. addonConfig, err := d.getAddonConfig(resource)
  204. if err != nil {
  205. return nil, err
  206. }
  207. if shouldCreate {
  208. err = client.DeployAddon(
  209. context.Background(),
  210. d.target.Project,
  211. d.target.Cluster,
  212. d.target.Namespace,
  213. &types.CreateAddonRequest{
  214. CreateReleaseBaseRequest: &types.CreateReleaseBaseRequest{
  215. RepoURL: d.source.Repo,
  216. TemplateName: d.source.Name,
  217. TemplateVersion: d.source.Version,
  218. Values: addonConfig,
  219. Name: resource.Name,
  220. },
  221. },
  222. )
  223. } else {
  224. bytes, err := json.Marshal(addonConfig)
  225. if err != nil {
  226. return nil, err
  227. }
  228. err = client.UpgradeRelease(
  229. context.Background(),
  230. d.target.Project,
  231. d.target.Cluster,
  232. d.target.Namespace,
  233. resource.Name,
  234. &types.UpgradeReleaseRequest{
  235. Values: string(bytes),
  236. },
  237. )
  238. }
  239. if err != nil {
  240. return nil, err
  241. }
  242. if err = d.assignOutput(resource, client); err != nil {
  243. return nil, err
  244. }
  245. return resource, err
  246. }
  247. func (d *Driver) applyApplication(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  248. appConfig, err := d.getApplicationConfig(resource)
  249. if err != nil {
  250. return nil, err
  251. }
  252. method := appConfig.Build.Method
  253. if method != "pack" && method != "docker" && method != "registry" {
  254. return nil, fmt.Errorf("method should either be \"docker\", \"pack\" or \"registry\"")
  255. }
  256. fullPath, err := filepath.Abs(appConfig.Build.Context)
  257. if err != nil {
  258. return nil, err
  259. }
  260. tag := os.Getenv("PORTER_TAG")
  261. if tag == "" {
  262. commit, err := git.LastCommit()
  263. if err != nil {
  264. return nil, err
  265. }
  266. tag = commit.Sha[:7]
  267. }
  268. // if the method is registry and a tag is defined, we use the provided tag
  269. if appConfig.Build.Method == "registry" {
  270. imageSpl := strings.Split(appConfig.Build.Image, ":")
  271. if len(imageSpl) == 2 {
  272. tag = imageSpl[1]
  273. }
  274. if tag == "" {
  275. tag = "latest"
  276. }
  277. }
  278. sharedOpts := &deploy.SharedOpts{
  279. ProjectID: d.target.Project,
  280. ClusterID: d.target.Cluster,
  281. Namespace: d.target.Namespace,
  282. LocalPath: fullPath,
  283. LocalDockerfile: appConfig.Build.Dockerfile,
  284. OverrideTag: tag,
  285. Method: deploy.DeployBuildType(method),
  286. EnvGroups: appConfig.EnvGroups,
  287. UseCache: appConfig.Build.UseCache,
  288. }
  289. if appConfig.Build.UseCache {
  290. // set the docker config so that pack caching can use the repo credentials
  291. err := config.SetDockerConfig(client)
  292. if err != nil {
  293. return nil, err
  294. }
  295. }
  296. if shouldCreate {
  297. resource, err = d.createApplication(resource, client, sharedOpts, appConfig)
  298. if err != nil {
  299. return nil, err
  300. }
  301. } else if !appConfig.OnlyCreate {
  302. resource, err = d.updateApplication(resource, client, sharedOpts, appConfig)
  303. if err != nil {
  304. return nil, err
  305. }
  306. } else {
  307. color.New(color.FgYellow).Printf("Skipping creation for %s as onlyCreate is set to true\n", resource.Name)
  308. }
  309. if err = d.assignOutput(resource, client); err != nil {
  310. return nil, err
  311. }
  312. if d.source.Name == "job" && appConfig.WaitForJob && (shouldCreate || !appConfig.OnlyCreate) {
  313. color.New(color.FgYellow).Printf("Waiting for job '%s' to finish\n", resource.Name)
  314. prevProject := cliConf.Project
  315. prevCluster := cliConf.Cluster
  316. name = resource.Name
  317. namespace = d.target.Namespace
  318. cliConf.Project = d.target.Project
  319. cliConf.Cluster = d.target.Cluster
  320. err = wait.WaitForJob(client, &wait.WaitOpts{
  321. ProjectID: cliConf.Project,
  322. ClusterID: cliConf.Cluster,
  323. Namespace: namespace,
  324. Name: name,
  325. })
  326. if err != nil {
  327. return nil, err
  328. }
  329. cliConf.Project = prevProject
  330. cliConf.Cluster = prevCluster
  331. }
  332. return resource, err
  333. }
  334. func (d *Driver) createApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  335. // create new release
  336. color.New(color.FgGreen).Printf("Creating %s release: %s\n", d.source.Name, resource.Name)
  337. regList, err := client.ListRegistries(context.Background(), d.target.Project)
  338. if err != nil {
  339. return nil, err
  340. }
  341. var registryURL string
  342. if len(*regList) == 0 {
  343. return nil, fmt.Errorf("no registry found")
  344. } else {
  345. registryURL = (*regList)[0].URL
  346. }
  347. // attempt to get repo suffix from environment variables
  348. var repoSuffix string
  349. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
  350. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
  351. repoSuffix = strings.ReplaceAll(fmt.Sprintf("%s-%s", repoOwner, repoName), "_", "-")
  352. }
  353. }
  354. createAgent := &deploy.CreateAgent{
  355. Client: client,
  356. CreateOpts: &deploy.CreateOpts{
  357. SharedOpts: sharedOpts,
  358. Kind: d.source.Name,
  359. ReleaseName: resource.Name,
  360. RegistryURL: registryURL,
  361. RepoSuffix: repoSuffix,
  362. },
  363. }
  364. var buildConfig *types.BuildConfig
  365. if appConf.Build.Builder != "" {
  366. buildConfig = &types.BuildConfig{
  367. Builder: appConf.Build.Builder,
  368. Buildpacks: appConf.Build.Buildpacks,
  369. }
  370. }
  371. var subdomain string
  372. if appConf.Build.Method == "registry" {
  373. subdomain, err = createAgent.CreateFromRegistry(appConf.Build.Image, appConf.Values)
  374. } else {
  375. // if useCache is set, create the image repository first
  376. if appConf.Build.UseCache {
  377. regID, imageURL, err := createAgent.GetImageRepoURL(resource.Name, sharedOpts.Namespace)
  378. if err != nil {
  379. return nil, err
  380. }
  381. err = client.CreateRepository(
  382. context.Background(),
  383. sharedOpts.ProjectID,
  384. regID,
  385. &types.CreateRegistryRepositoryRequest{
  386. ImageRepoURI: imageURL,
  387. },
  388. )
  389. if err != nil {
  390. return nil, err
  391. }
  392. }
  393. subdomain, err = createAgent.CreateFromDocker(appConf.Values, sharedOpts.OverrideTag, buildConfig, appConf.Build.ForceBuild)
  394. }
  395. if err != nil {
  396. return nil, err
  397. }
  398. return resource, handleSubdomainCreate(subdomain, err)
  399. }
  400. func (d *Driver) updateApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  401. color.New(color.FgGreen).Println("Updating existing release:", resource.Name)
  402. updateAgent, err := deploy.NewDeployAgent(client, resource.Name, &deploy.DeployOpts{
  403. SharedOpts: sharedOpts,
  404. Local: appConf.Build.Method != "registry",
  405. })
  406. if err != nil {
  407. return nil, err
  408. }
  409. // if the build method is registry, we do not trigger a build
  410. if appConf.Build.Method != "registry" {
  411. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  412. UseNewConfig: true,
  413. NewConfig: appConf.Values,
  414. })
  415. if err != nil {
  416. return nil, err
  417. }
  418. err = updateAgent.SetBuildEnv(buildEnv)
  419. if err != nil {
  420. return nil, err
  421. }
  422. var buildConfig *types.BuildConfig
  423. if appConf.Build.Builder != "" {
  424. buildConfig = &types.BuildConfig{
  425. Builder: appConf.Build.Builder,
  426. Buildpacks: appConf.Build.Buildpacks,
  427. }
  428. }
  429. err = updateAgent.Build(buildConfig, appConf.Build.ForceBuild)
  430. if err != nil {
  431. return nil, err
  432. }
  433. if !appConf.Build.UseCache {
  434. err = updateAgent.Push(appConf.Build.ForcePush)
  435. if err != nil {
  436. return nil, err
  437. }
  438. }
  439. }
  440. err = updateAgent.UpdateImageAndValues(appConf.Values)
  441. if err != nil {
  442. return nil, err
  443. }
  444. return resource, nil
  445. }
  446. func (d *Driver) assignOutput(resource *models.Resource, client *api.Client) error {
  447. release, err := client.GetRelease(
  448. context.Background(),
  449. d.target.Project,
  450. d.target.Cluster,
  451. d.target.Namespace,
  452. resource.Name,
  453. )
  454. if err != nil {
  455. return err
  456. }
  457. d.output = utils.CoalesceValues(d.source.SourceValues, release.Config)
  458. return nil
  459. }
  460. func (d *Driver) Output() (map[string]interface{}, error) {
  461. return d.output, nil
  462. }
  463. func (d *Driver) getApplicationConfig(resource *models.Resource) (*ApplicationConfig, error) {
  464. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  465. RawConf: resource.Config,
  466. LookupTable: *d.lookupTable,
  467. Dependencies: resource.Dependencies,
  468. })
  469. if err != nil {
  470. return nil, err
  471. }
  472. config := &ApplicationConfig{}
  473. err = mapstructure.Decode(populatedConf, config)
  474. if err != nil {
  475. return nil, err
  476. }
  477. if _, ok := resource.Config["waitForJob"]; !ok && d.source.Name == "job" {
  478. // default to true and wait for the job to finish
  479. config.WaitForJob = true
  480. }
  481. return config, nil
  482. }
  483. func (d *Driver) getAddonConfig(resource *models.Resource) (map[string]interface{}, error) {
  484. return drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  485. RawConf: resource.Config,
  486. LookupTable: *d.lookupTable,
  487. Dependencies: resource.Dependencies,
  488. })
  489. }
  490. type DeploymentHook struct {
  491. client *api.Client
  492. resourceGroup *switchboardTypes.ResourceGroup
  493. gitInstallationID, projectID, clusterID, prID, actionID uint
  494. branch, namespace, repoName, repoOwner, prName, commitSHA string
  495. }
  496. func NewDeploymentHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup, namespace string) (*DeploymentHook, error) {
  497. res := &DeploymentHook{
  498. client: client,
  499. resourceGroup: resourceGroup,
  500. namespace: namespace,
  501. }
  502. ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID")
  503. ghID, err := strconv.Atoi(ghIDStr)
  504. if err != nil {
  505. return nil, err
  506. }
  507. res.gitInstallationID = uint(ghID)
  508. prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID")
  509. prID, err := strconv.Atoi(prIDStr)
  510. if err != nil {
  511. return nil, err
  512. }
  513. res.prID = uint(prID)
  514. res.projectID = cliConf.Project
  515. if res.projectID == 0 {
  516. return nil, fmt.Errorf("project id must be set")
  517. }
  518. res.clusterID = cliConf.Cluster
  519. if res.clusterID == 0 {
  520. return nil, fmt.Errorf("cluster id must be set")
  521. }
  522. branchName := os.Getenv("PORTER_BRANCH_NAME")
  523. res.branch = branchName
  524. actionIDStr := os.Getenv("PORTER_ACTION_ID")
  525. actionID, err := strconv.Atoi(actionIDStr)
  526. if err != nil {
  527. return nil, err
  528. }
  529. res.actionID = uint(actionID)
  530. repoName := os.Getenv("PORTER_REPO_NAME")
  531. res.repoName = repoName
  532. repoOwner := os.Getenv("PORTER_REPO_OWNER")
  533. res.repoOwner = repoOwner
  534. prName := os.Getenv("PORTER_PR_NAME")
  535. res.prName = prName
  536. commit, err := git.LastCommit()
  537. if err != nil {
  538. return nil, fmt.Errorf(err.Error())
  539. }
  540. res.commitSHA = commit.Sha[:7]
  541. return res, nil
  542. }
  543. func (t *DeploymentHook) PreApply() error {
  544. // attempt to read the deployment -- if it doesn't exist, create it
  545. _, err := t.client.GetDeployment(
  546. context.Background(),
  547. t.projectID, t.gitInstallationID, t.clusterID,
  548. t.repoOwner, t.repoName,
  549. &types.GetDeploymentRequest{
  550. Namespace: t.namespace,
  551. },
  552. )
  553. // TODO: case this on the response status code rather than text
  554. if err != nil && strings.Contains(err.Error(), "deployment not found") {
  555. // in this case, create the deployment
  556. _, err = t.client.CreateDeployment(
  557. context.Background(),
  558. t.projectID, t.gitInstallationID, t.clusterID,
  559. t.repoOwner, t.repoName,
  560. &types.CreateDeploymentRequest{
  561. Namespace: t.namespace,
  562. PullRequestID: t.prID,
  563. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  564. Branch: t.branch,
  565. ActionID: t.actionID,
  566. },
  567. GitHubMetadata: &types.GitHubMetadata{
  568. PRName: t.prName,
  569. RepoName: t.repoName,
  570. RepoOwner: t.repoOwner,
  571. CommitSHA: t.commitSHA,
  572. },
  573. },
  574. )
  575. } else if err == nil {
  576. _, err = t.client.UpdateDeployment(
  577. context.Background(),
  578. t.projectID, t.gitInstallationID, t.clusterID,
  579. t.repoOwner, t.repoName,
  580. &types.UpdateDeploymentRequest{
  581. Namespace: t.namespace,
  582. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  583. Branch: t.branch,
  584. ActionID: t.actionID,
  585. },
  586. CommitSHA: t.commitSHA,
  587. },
  588. )
  589. }
  590. return err
  591. }
  592. func (t *DeploymentHook) DataQueries() map[string]interface{} {
  593. res := make(map[string]interface{})
  594. // use the resource group to find all web applications that can have an exposed subdomain
  595. // that we can query for
  596. for _, resource := range t.resourceGroup.Resources {
  597. isWeb := false
  598. if sourceNameInter, exists := resource.Source["name"]; exists {
  599. if sourceName, ok := sourceNameInter.(string); ok {
  600. if sourceName == "web" {
  601. isWeb = true
  602. }
  603. }
  604. }
  605. if isWeb {
  606. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.porter_hosts[0] }", resource.Name)
  607. }
  608. }
  609. return res
  610. }
  611. func (t *DeploymentHook) PostApply(populatedData map[string]interface{}) error {
  612. subdomains := make([]string, 0)
  613. for _, data := range populatedData {
  614. domain, ok := data.(string)
  615. if !ok {
  616. continue
  617. }
  618. if _, err := url.Parse("https://" + domain); err == nil {
  619. subdomains = append(subdomains, "https://"+domain)
  620. }
  621. }
  622. // finalize the deployment
  623. _, err := t.client.FinalizeDeployment(
  624. context.Background(),
  625. t.projectID, t.gitInstallationID, t.clusterID,
  626. t.repoOwner, t.repoName,
  627. &types.FinalizeDeploymentRequest{
  628. Namespace: t.namespace,
  629. Subdomain: strings.Join(subdomains, ","),
  630. },
  631. )
  632. return err
  633. }
  634. func (t *DeploymentHook) OnError(err error) {
  635. // if the deployment exists, throw an error for that deployment
  636. _, getDeplErr := t.client.GetDeployment(
  637. context.Background(),
  638. t.projectID, t.gitInstallationID, t.clusterID,
  639. t.repoOwner, t.repoName,
  640. &types.GetDeploymentRequest{
  641. Namespace: t.namespace,
  642. },
  643. )
  644. if getDeplErr == nil {
  645. _, err = t.client.UpdateDeploymentStatus(
  646. context.Background(),
  647. t.projectID, t.gitInstallationID, t.clusterID,
  648. t.repoOwner, t.repoName,
  649. &types.UpdateDeploymentStatusRequest{
  650. Namespace: t.namespace,
  651. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  652. Branch: t.branch,
  653. ActionID: t.actionID,
  654. },
  655. Status: string(types.DeploymentStatusFailed),
  656. },
  657. )
  658. }
  659. }
  660. type CloneEnvGroupHook struct {
  661. client *api.Client
  662. resGroup *switchboardTypes.ResourceGroup
  663. }
  664. func NewCloneEnvGroupHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup) *CloneEnvGroupHook {
  665. return &CloneEnvGroupHook{
  666. client: client,
  667. resGroup: resourceGroup,
  668. }
  669. }
  670. func (t *CloneEnvGroupHook) PreApply() error {
  671. for _, res := range t.resGroup.Resources {
  672. if res.Driver == "env-group" {
  673. continue
  674. }
  675. config := &ApplicationConfig{}
  676. err := mapstructure.Decode(res.Config, &config)
  677. if err != nil {
  678. continue
  679. }
  680. if config != nil && len(config.EnvGroups) > 0 {
  681. target, err := preview.GetTarget(res.Target)
  682. if err != nil {
  683. return err
  684. }
  685. for _, group := range config.EnvGroups {
  686. if group.Name == "" {
  687. return fmt.Errorf("env group name cannot be empty")
  688. }
  689. _, err := t.client.GetEnvGroup(
  690. context.Background(),
  691. target.Project,
  692. target.Cluster,
  693. target.Namespace,
  694. &types.GetEnvGroupRequest{
  695. Name: group.Name,
  696. Version: group.Version,
  697. },
  698. )
  699. if err != nil && err.Error() == "env group not found" {
  700. if group.Namespace == "" {
  701. return fmt.Errorf("env group namespace cannot be empty")
  702. }
  703. color.New(color.FgBlue, color.Bold).
  704. Printf("Env group '%s' does not exist in the target namespace '%s'\n", group.Name, target.Namespace)
  705. color.New(color.FgBlue, color.Bold).
  706. Printf("Cloning env group '%s' from namespace '%s' to target namespace '%s'\n",
  707. group.Name, group.Namespace, target.Namespace)
  708. _, err = t.client.CloneEnvGroup(
  709. context.Background(), target.Project, target.Cluster, group.Namespace,
  710. &types.CloneEnvGroupRequest{
  711. Name: group.Name,
  712. Namespace: target.Namespace,
  713. },
  714. )
  715. if err != nil {
  716. return err
  717. }
  718. } else if err != nil {
  719. return err
  720. }
  721. }
  722. }
  723. }
  724. return nil
  725. }
  726. func (t *CloneEnvGroupHook) DataQueries() map[string]interface{} {
  727. return nil
  728. }
  729. func (t *CloneEnvGroupHook) PostApply(populatedData map[string]interface{}) error {
  730. return nil
  731. }
  732. func (t *CloneEnvGroupHook) OnError(err error) {}