apply.go 24 KB

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