apply.go 22 KB

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