apply.go 22 KB

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