apply.go 23 KB

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