apply.go 20 KB

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