apply.go 22 KB

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