apply.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. previewInt "github.com/porter-dev/porter/internal/integrations/preview"
  22. "github.com/porter-dev/porter/internal/templater/utils"
  23. "github.com/porter-dev/switchboard/pkg/drivers"
  24. "github.com/porter-dev/switchboard/pkg/models"
  25. "github.com/porter-dev/switchboard/pkg/parser"
  26. switchboardTypes "github.com/porter-dev/switchboard/pkg/types"
  27. switchboardWorker "github.com/porter-dev/switchboard/pkg/worker"
  28. "github.com/rs/zerolog"
  29. "github.com/spf13/cobra"
  30. )
  31. // applyCmd represents the "porter apply" base command when called
  32. // with a porter.yaml file as an argument
  33. var applyCmd = &cobra.Command{
  34. Use: "apply",
  35. Short: "Applies a configuration to an application",
  36. Long: fmt.Sprintf(`
  37. %s
  38. Applies a configuration to an application by either creating a new one or updating an existing
  39. one. For example:
  40. %s
  41. This command will apply the configuration contained in porter.yaml to the requested project and
  42. cluster either provided inside the porter.yaml file or through environment variables. Note that
  43. environment variables will always take precendence over values specified in the porter.yaml file.
  44. By default, this command expects to be run from a local git repository.
  45. The following are the environment variables that can be used to set certain values while
  46. applying a configuration:
  47. PORTER_CLUSTER Cluster ID that contains the project
  48. PORTER_PROJECT Project ID that contains the application
  49. PORTER_NAMESPACE The Kubernetes namespace that the application belongs to
  50. PORTER_SOURCE_NAME Name of the source Helm chart
  51. PORTER_SOURCE_REPO The URL of the Helm charts registry
  52. PORTER_SOURCE_VERSION The version of the Helm chart to use
  53. PORTER_TAG The Docker image tag to use (like the git commit hash)
  54. `,
  55. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter apply\":"),
  56. color.New(color.FgGreen, color.Bold).Sprintf("porter apply -f porter.yaml"),
  57. ),
  58. Run: func(cmd *cobra.Command, args []string) {
  59. err := checkLoginAndRun(args, apply)
  60. if err != nil {
  61. os.Exit(1)
  62. }
  63. },
  64. }
  65. // applyValidateCmd represents the "porter apply validate" command when called
  66. // with a porter.yaml file as an argument
  67. var applyValidateCmd = &cobra.Command{
  68. Use: "validate",
  69. Short: "Validates a porter.yaml",
  70. Run: func(*cobra.Command, []string) {
  71. err := applyValidate()
  72. if err != nil {
  73. color.New(color.FgRed).Fprintf(os.Stderr, "Error: %s\n", err.Error())
  74. os.Exit(1)
  75. } else {
  76. color.New(color.FgGreen).Printf("The porter.yaml file is valid!\n")
  77. }
  78. },
  79. }
  80. var porterYAML string
  81. func init() {
  82. rootCmd.AddCommand(applyCmd)
  83. applyCmd.AddCommand(applyValidateCmd)
  84. applyCmd.PersistentFlags().StringVarP(&porterYAML, "file", "f", "", "path to porter.yaml")
  85. applyCmd.MarkFlagRequired("file")
  86. }
  87. func apply(_ *types.GetAuthenticatedUserResponse, client *api.Client, _ []string) error {
  88. if _, ok := os.LookupEnv("PORTER_VALIDATE_YAML"); ok {
  89. err := applyValidate()
  90. if err != nil {
  91. return err
  92. }
  93. }
  94. fileBytes, err := ioutil.ReadFile(porterYAML)
  95. if err != nil {
  96. return fmt.Errorf("error reading porter.yaml: %w", err)
  97. }
  98. resGroup, err := parser.ParseRawBytes(fileBytes)
  99. if err != nil {
  100. return fmt.Errorf("error parsing porter.yaml: %w", err)
  101. }
  102. basePath, err := os.Getwd()
  103. if err != nil {
  104. return fmt.Errorf("error getting working directory: %w", err)
  105. }
  106. worker := switchboardWorker.NewWorker()
  107. worker.RegisterDriver("deploy", NewDeployDriver)
  108. worker.RegisterDriver("build-image", preview.NewBuildDriver)
  109. worker.RegisterDriver("push-image", preview.NewPushDriver)
  110. worker.RegisterDriver("update-config", preview.NewUpdateConfigDriver)
  111. worker.RegisterDriver("random-string", preview.NewRandomStringDriver)
  112. worker.RegisterDriver("env-group", preview.NewEnvGroupDriver)
  113. worker.RegisterDriver("os-env", preview.NewOSEnvDriver)
  114. worker.SetDefaultDriver("deploy")
  115. if hasDeploymentHookEnvVars() {
  116. deplNamespace := os.Getenv("PORTER_NAMESPACE")
  117. if deplNamespace == "" {
  118. return fmt.Errorf("namespace must be set by PORTER_NAMESPACE")
  119. }
  120. deploymentHook, err := NewDeploymentHook(client, resGroup, deplNamespace)
  121. if err != nil {
  122. return fmt.Errorf("error creating deployment hook: %w", err)
  123. }
  124. worker.RegisterHook("deployment", deploymentHook)
  125. }
  126. cloneEnvGroupHook := NewCloneEnvGroupHook(client, resGroup)
  127. worker.RegisterHook("cloneenvgroup", cloneEnvGroupHook)
  128. return worker.Apply(resGroup, &switchboardTypes.ApplyOpts{
  129. BasePath: basePath,
  130. })
  131. }
  132. func applyValidate() error {
  133. fileBytes, err := ioutil.ReadFile(porterYAML)
  134. if err != nil {
  135. return fmt.Errorf("error reading porter.yaml: %w", err)
  136. }
  137. validationErrors := previewInt.Validate(string(fileBytes))
  138. if len(validationErrors) > 0 {
  139. errString := "the following error(s) were found while validating the porter.yaml file:"
  140. for _, err := range validationErrors {
  141. errString += "\n- " + strings.ReplaceAll(err.Error(), "\n\n*", "\n *")
  142. }
  143. return fmt.Errorf(errString)
  144. }
  145. return nil
  146. }
  147. func hasDeploymentHookEnvVars() bool {
  148. if ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID"); ghIDStr == "" {
  149. return false
  150. }
  151. if prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID"); prIDStr == "" {
  152. return false
  153. }
  154. if branchFrom := os.Getenv("PORTER_BRANCH_FROM"); branchFrom == "" {
  155. return false
  156. }
  157. if branchInto := os.Getenv("PORTER_BRANCH_INTO"); branchInto == "" {
  158. return false
  159. }
  160. if actionIDStr := os.Getenv("PORTER_ACTION_ID"); actionIDStr == "" {
  161. return false
  162. }
  163. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName == "" {
  164. return false
  165. }
  166. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner == "" {
  167. return false
  168. }
  169. if prName := os.Getenv("PORTER_PR_NAME"); prName == "" {
  170. return false
  171. }
  172. return true
  173. }
  174. type DeployDriver struct {
  175. source *previewInt.Source
  176. target *previewInt.Target
  177. output map[string]interface{}
  178. lookupTable *map[string]drivers.Driver
  179. logger *zerolog.Logger
  180. }
  181. func NewDeployDriver(resource *models.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  182. driver := &DeployDriver{
  183. lookupTable: opts.DriverLookupTable,
  184. logger: opts.Logger,
  185. output: make(map[string]interface{}),
  186. }
  187. source, err := preview.GetSource(resource.Name, resource.Source)
  188. if err != nil {
  189. return nil, err
  190. }
  191. driver.source = source
  192. target, err := preview.GetTarget(resource.Name, resource.Target)
  193. if err != nil {
  194. return nil, err
  195. }
  196. driver.target = target
  197. return driver, nil
  198. }
  199. func (d *DeployDriver) ShouldApply(_ *models.Resource) bool {
  200. return true
  201. }
  202. func (d *DeployDriver) Apply(resource *models.Resource) (*models.Resource, error) {
  203. client := config.GetAPIClient()
  204. _, err := client.GetRelease(
  205. context.Background(),
  206. d.target.Project,
  207. d.target.Cluster,
  208. d.target.Namespace,
  209. resource.Name,
  210. )
  211. shouldCreate := err != nil
  212. if err != nil {
  213. color.New(color.FgYellow).Printf("Could not read release %s/%s (%s): attempting creation\n", d.target.Namespace, resource.Name, err.Error())
  214. }
  215. if d.source.IsApplication {
  216. return d.applyApplication(resource, client, shouldCreate)
  217. }
  218. return d.applyAddon(resource, client, shouldCreate)
  219. }
  220. // Simple apply for addons
  221. func (d *DeployDriver) applyAddon(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  222. addonConfig, err := d.getAddonConfig(resource)
  223. if err != nil {
  224. return nil, fmt.Errorf("error getting addon config for resource %s: %w", resource.Name, err)
  225. }
  226. if shouldCreate {
  227. err := client.DeployAddon(
  228. context.Background(),
  229. d.target.Project,
  230. d.target.Cluster,
  231. d.target.Namespace,
  232. &types.CreateAddonRequest{
  233. CreateReleaseBaseRequest: &types.CreateReleaseBaseRequest{
  234. RepoURL: d.source.Repo,
  235. TemplateName: d.source.Name,
  236. TemplateVersion: d.source.Version,
  237. Values: addonConfig,
  238. Name: resource.Name,
  239. },
  240. },
  241. )
  242. if err != nil {
  243. return nil, fmt.Errorf("error creating addon from resource %s: %w", resource.Name, err)
  244. }
  245. } else {
  246. bytes, err := json.Marshal(addonConfig)
  247. if err != nil {
  248. return nil, fmt.Errorf("error marshalling addon config from resource %s: %w", resource.Name, err)
  249. }
  250. err = client.UpgradeRelease(
  251. context.Background(),
  252. d.target.Project,
  253. d.target.Cluster,
  254. d.target.Namespace,
  255. resource.Name,
  256. &types.UpgradeReleaseRequest{
  257. Values: string(bytes),
  258. },
  259. )
  260. if err != nil {
  261. return nil, fmt.Errorf("error updating addon from resource %s: %w", resource.Name, err)
  262. }
  263. }
  264. if err = d.assignOutput(resource, client); err != nil {
  265. return nil, err
  266. }
  267. return resource, nil
  268. }
  269. func (d *DeployDriver) applyApplication(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  270. if resource == nil {
  271. return nil, fmt.Errorf("nil resource")
  272. }
  273. resourceName := resource.Name
  274. appConfig, err := d.getApplicationConfig(resource)
  275. if err != nil {
  276. return nil, err
  277. }
  278. fullPath, err := filepath.Abs(appConfig.Build.Context)
  279. if err != nil {
  280. return nil, fmt.Errorf("for resource %s, error getting absolute path for config.build.context: %w", resourceName,
  281. err)
  282. }
  283. tag := os.Getenv("PORTER_TAG")
  284. if tag == "" {
  285. color.New(color.FgYellow).Printf("for resource %s, since PORTER_TAG is not set, the Docker image tag will default to"+
  286. " the git repo SHA", resourceName)
  287. commit, err := git.LastCommit()
  288. if err != nil {
  289. return nil, fmt.Errorf("for resource %s, error getting last git commit: %w", resourceName, err)
  290. }
  291. tag = commit.Sha[:7]
  292. color.New(color.FgYellow).Printf("for resource %s, using tag %s\n", resourceName, tag)
  293. }
  294. // if the method is registry and a tag is defined, we use the provided tag
  295. if appConfig.Build.Method == "registry" {
  296. imageSpl := strings.Split(appConfig.Build.Image, ":")
  297. if len(imageSpl) == 2 {
  298. tag = imageSpl[1]
  299. }
  300. if tag == "" {
  301. tag = "latest"
  302. }
  303. }
  304. sharedOpts := &deploy.SharedOpts{
  305. ProjectID: d.target.Project,
  306. ClusterID: d.target.Cluster,
  307. Namespace: d.target.Namespace,
  308. LocalPath: fullPath,
  309. LocalDockerfile: appConfig.Build.Dockerfile,
  310. OverrideTag: tag,
  311. Method: deploy.DeployBuildType(appConfig.Build.Method),
  312. EnvGroups: appConfig.EnvGroups,
  313. UseCache: appConfig.Build.UseCache,
  314. }
  315. if appConfig.Build.UseCache {
  316. // set the docker config so that pack caching can use the repo credentials
  317. err := config.SetDockerConfig(client)
  318. if err != nil {
  319. return nil, err
  320. }
  321. }
  322. if shouldCreate {
  323. resource, err = d.createApplication(resource, client, sharedOpts, appConfig)
  324. if err != nil {
  325. return nil, fmt.Errorf("error creating app from resource %s: %w", resourceName, err)
  326. }
  327. } else if !appConfig.OnlyCreate {
  328. resource, err = d.updateApplication(resource, client, sharedOpts, appConfig)
  329. if err != nil {
  330. return nil, fmt.Errorf("error updating application from resource %s: %w", resourceName, err)
  331. }
  332. } else {
  333. color.New(color.FgYellow).Printf("Skipping creation for resource %s as onlyCreate is set to true\n", resourceName)
  334. }
  335. if err = d.assignOutput(resource, client); err != nil {
  336. return nil, err
  337. }
  338. if d.source.Name == "job" && appConfig.WaitForJob && (shouldCreate || !appConfig.OnlyCreate) {
  339. color.New(color.FgYellow).Printf("Waiting for job '%s' to finish\n", resourceName)
  340. err = wait.WaitForJob(client, &wait.WaitOpts{
  341. ProjectID: d.target.Project,
  342. ClusterID: d.target.Cluster,
  343. Namespace: d.target.Namespace,
  344. Name: resourceName,
  345. })
  346. if err != nil && appConfig.OnlyCreate {
  347. deleteJobErr := client.DeleteRelease(
  348. context.Background(),
  349. d.target.Project,
  350. d.target.Cluster,
  351. d.target.Namespace,
  352. resourceName,
  353. )
  354. if deleteJobErr != nil {
  355. return nil, fmt.Errorf("error deleting job %s with waitForJob and onlyCreate set to true: %w",
  356. resourceName, deleteJobErr)
  357. }
  358. } else if err != nil {
  359. return nil, fmt.Errorf("error waiting for job %s: %w", resourceName, err)
  360. }
  361. }
  362. return resource, err
  363. }
  364. func (d *DeployDriver) createApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *previewInt.ApplicationConfig) (*models.Resource, error) {
  365. // create new release
  366. color.New(color.FgGreen).Printf("Creating %s release: %s\n", d.source.Name, resource.Name)
  367. regList, err := client.ListRegistries(context.Background(), d.target.Project)
  368. if err != nil {
  369. return nil, fmt.Errorf("for resource %s, error listing registries: %w", resource.Name, err)
  370. }
  371. var registryURL string
  372. if len(*regList) == 0 {
  373. return nil, fmt.Errorf("no registry found")
  374. } else {
  375. registryURL = (*regList)[0].URL
  376. }
  377. color.New(color.FgBlue).Printf("for resource %s, using registry %s\n", resource.Name, registryURL)
  378. // attempt to get repo suffix from environment variables
  379. var repoSuffix string
  380. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
  381. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
  382. repoSuffix = strings.ToLower(strings.ReplaceAll(fmt.Sprintf("%s-%s", repoOwner, repoName), "_", "-"))
  383. }
  384. }
  385. createAgent := &deploy.CreateAgent{
  386. Client: client,
  387. CreateOpts: &deploy.CreateOpts{
  388. SharedOpts: sharedOpts,
  389. Kind: d.source.Name,
  390. ReleaseName: resource.Name,
  391. RegistryURL: registryURL,
  392. RepoSuffix: repoSuffix,
  393. },
  394. }
  395. var buildConfig *types.BuildConfig
  396. if appConf.Build.Builder != "" {
  397. buildConfig = &types.BuildConfig{
  398. Builder: appConf.Build.Builder,
  399. Buildpacks: appConf.Build.Buildpacks,
  400. }
  401. }
  402. var subdomain string
  403. if appConf.Build.Method == "registry" {
  404. subdomain, err = createAgent.CreateFromRegistry(appConf.Build.Image, appConf.Values)
  405. } else {
  406. // if useCache is set, create the image repository first
  407. if appConf.Build.UseCache {
  408. regID, imageURL, err := createAgent.GetImageRepoURL(resource.Name, sharedOpts.Namespace)
  409. if err != nil {
  410. return nil, err
  411. }
  412. err = client.CreateRepository(
  413. context.Background(),
  414. sharedOpts.ProjectID,
  415. regID,
  416. &types.CreateRegistryRepositoryRequest{
  417. ImageRepoURI: imageURL,
  418. },
  419. )
  420. if err != nil {
  421. return nil, err
  422. }
  423. }
  424. subdomain, err = createAgent.CreateFromDocker(appConf.Values, sharedOpts.OverrideTag, buildConfig)
  425. }
  426. if err != nil {
  427. return nil, err
  428. }
  429. return resource, handleSubdomainCreate(subdomain, err)
  430. }
  431. func (d *DeployDriver) updateApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *previewInt.ApplicationConfig) (*models.Resource, error) {
  432. color.New(color.FgGreen).Println("Updating existing release:", resource.Name)
  433. if len(appConf.Build.Env) > 0 {
  434. sharedOpts.AdditionalEnv = appConf.Build.Env
  435. }
  436. updateAgent, err := deploy.NewDeployAgent(client, resource.Name, &deploy.DeployOpts{
  437. SharedOpts: sharedOpts,
  438. Local: appConf.Build.Method != "registry",
  439. })
  440. if err != nil {
  441. return nil, err
  442. }
  443. // if the build method is registry, we do not trigger a build
  444. if appConf.Build.Method != "registry" {
  445. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  446. UseNewConfig: true,
  447. NewConfig: appConf.Values,
  448. })
  449. if err != nil {
  450. return nil, err
  451. }
  452. err = updateAgent.SetBuildEnv(buildEnv)
  453. if err != nil {
  454. return nil, err
  455. }
  456. var buildConfig *types.BuildConfig
  457. if appConf.Build.Builder != "" {
  458. buildConfig = &types.BuildConfig{
  459. Builder: appConf.Build.Builder,
  460. Buildpacks: appConf.Build.Buildpacks,
  461. }
  462. }
  463. err = updateAgent.Build(buildConfig)
  464. if err != nil {
  465. return nil, err
  466. }
  467. if !appConf.Build.UseCache {
  468. err = updateAgent.Push()
  469. if err != nil {
  470. return nil, err
  471. }
  472. }
  473. }
  474. err = updateAgent.UpdateImageAndValues(appConf.Values)
  475. if err != nil {
  476. return nil, err
  477. }
  478. return resource, nil
  479. }
  480. func (d *DeployDriver) assignOutput(resource *models.Resource, client *api.Client) error {
  481. release, err := client.GetRelease(
  482. context.Background(),
  483. d.target.Project,
  484. d.target.Cluster,
  485. d.target.Namespace,
  486. resource.Name,
  487. )
  488. if err != nil {
  489. return err
  490. }
  491. d.output = utils.CoalesceValues(d.source.SourceValues, release.Config)
  492. return nil
  493. }
  494. func (d *DeployDriver) Output() (map[string]interface{}, error) {
  495. return d.output, nil
  496. }
  497. func (d *DeployDriver) getApplicationConfig(resource *models.Resource) (*previewInt.ApplicationConfig, error) {
  498. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  499. RawConf: resource.Config,
  500. LookupTable: *d.lookupTable,
  501. Dependencies: resource.Dependencies,
  502. })
  503. if err != nil {
  504. return nil, err
  505. }
  506. appConf := &previewInt.ApplicationConfig{}
  507. err = mapstructure.Decode(populatedConf, appConf)
  508. if err != nil {
  509. return nil, err
  510. }
  511. if _, ok := resource.Config["waitForJob"]; !ok && d.source.Name == "job" {
  512. // default to true and wait for the job to finish
  513. appConf.WaitForJob = true
  514. }
  515. return appConf, nil
  516. }
  517. func (d *DeployDriver) getAddonConfig(resource *models.Resource) (map[string]interface{}, error) {
  518. return drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  519. RawConf: resource.Config,
  520. LookupTable: *d.lookupTable,
  521. Dependencies: resource.Dependencies,
  522. })
  523. }
  524. type DeploymentHook struct {
  525. client *api.Client
  526. resourceGroup *switchboardTypes.ResourceGroup
  527. gitInstallationID, projectID, clusterID, prID, actionID, envID uint
  528. branchFrom, branchInto, namespace, repoName, repoOwner, prName, commitSHA string
  529. }
  530. func NewDeploymentHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup, namespace string) (*DeploymentHook, error) {
  531. res := &DeploymentHook{
  532. client: client,
  533. resourceGroup: resourceGroup,
  534. namespace: namespace,
  535. }
  536. ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID")
  537. ghID, err := strconv.Atoi(ghIDStr)
  538. if err != nil {
  539. return nil, err
  540. }
  541. res.gitInstallationID = uint(ghID)
  542. prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID")
  543. prID, err := strconv.Atoi(prIDStr)
  544. if err != nil {
  545. return nil, err
  546. }
  547. res.prID = uint(prID)
  548. res.projectID = cliConf.Project
  549. if res.projectID == 0 {
  550. return nil, fmt.Errorf("project id must be set")
  551. }
  552. res.clusterID = cliConf.Cluster
  553. if res.clusterID == 0 {
  554. return nil, fmt.Errorf("cluster id must be set")
  555. }
  556. branchFrom := os.Getenv("PORTER_BRANCH_FROM")
  557. res.branchFrom = branchFrom
  558. branchInto := os.Getenv("PORTER_BRANCH_INTO")
  559. res.branchInto = branchInto
  560. actionIDStr := os.Getenv("PORTER_ACTION_ID")
  561. actionID, err := strconv.Atoi(actionIDStr)
  562. if err != nil {
  563. return nil, err
  564. }
  565. res.actionID = uint(actionID)
  566. repoName := os.Getenv("PORTER_REPO_NAME")
  567. res.repoName = repoName
  568. repoOwner := os.Getenv("PORTER_REPO_OWNER")
  569. res.repoOwner = repoOwner
  570. prName := os.Getenv("PORTER_PR_NAME")
  571. res.prName = prName
  572. commit, err := git.LastCommit()
  573. if err != nil {
  574. return nil, fmt.Errorf(err.Error())
  575. }
  576. res.commitSHA = commit.Sha[:7]
  577. return res, nil
  578. }
  579. func (t *DeploymentHook) PreApply() error {
  580. envList, err := t.client.ListEnvironments(
  581. context.Background(), t.projectID, t.clusterID,
  582. )
  583. if err != nil {
  584. return err
  585. }
  586. envs := *envList
  587. for _, env := range envs {
  588. if env.GitRepoOwner == t.repoOwner && env.GitRepoName == t.repoName && env.GitInstallationID == t.gitInstallationID {
  589. t.envID = env.ID
  590. break
  591. }
  592. }
  593. if t.envID == 0 {
  594. return fmt.Errorf("could not find environment for deployment")
  595. }
  596. // attempt to read the deployment -- if it doesn't exist, create it
  597. _, err = t.client.GetDeployment(
  598. context.Background(),
  599. t.projectID, t.clusterID, t.envID,
  600. &types.GetDeploymentRequest{
  601. Namespace: t.namespace,
  602. },
  603. )
  604. if err != nil && strings.Contains(err.Error(), "not found") {
  605. // in this case, create the deployment
  606. _, err = t.client.CreateDeployment(
  607. context.Background(),
  608. t.projectID, t.gitInstallationID, t.clusterID,
  609. t.repoOwner, t.repoName,
  610. &types.CreateDeploymentRequest{
  611. Namespace: t.namespace,
  612. PullRequestID: t.prID,
  613. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  614. ActionID: t.actionID,
  615. },
  616. GitHubMetadata: &types.GitHubMetadata{
  617. PRName: t.prName,
  618. RepoName: t.repoName,
  619. RepoOwner: t.repoOwner,
  620. CommitSHA: t.commitSHA,
  621. PRBranchFrom: t.branchFrom,
  622. PRBranchInto: t.branchInto,
  623. },
  624. },
  625. )
  626. } else if err == nil {
  627. _, err = t.client.UpdateDeployment(
  628. context.Background(),
  629. t.projectID, t.gitInstallationID, t.clusterID,
  630. t.repoOwner, t.repoName,
  631. &types.UpdateDeploymentRequest{
  632. Namespace: t.namespace,
  633. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  634. ActionID: t.actionID,
  635. },
  636. PRBranchFrom: t.branchFrom,
  637. CommitSHA: t.commitSHA,
  638. },
  639. )
  640. }
  641. return err
  642. }
  643. func (t *DeploymentHook) DataQueries() map[string]interface{} {
  644. res := make(map[string]interface{})
  645. // use the resource group to find all web applications that can have an exposed subdomain
  646. // that we can query for
  647. for _, resource := range t.resourceGroup.Resources {
  648. isWeb := false
  649. if sourceNameInter, exists := resource.Source["name"]; exists {
  650. if sourceName, ok := sourceNameInter.(string); ok {
  651. if sourceName == "web" {
  652. isWeb = true
  653. }
  654. }
  655. }
  656. if isWeb {
  657. // determine if we should query for porter_hosts or just hosts
  658. isCustomDomain := false
  659. ingressMap, err := deploy.GetNestedMap(resource.Config, "values", "ingress")
  660. if err == nil {
  661. enabledVal, enabledExists := ingressMap["enabled"]
  662. customDomVal, customDomExists := ingressMap["custom_domain"]
  663. if enabledExists && customDomExists {
  664. enabled, eOK := enabledVal.(bool)
  665. customDomain, cOK := customDomVal.(bool)
  666. if eOK && cOK && enabled {
  667. if customDomain {
  668. // return the first custom domain when one exists
  669. hostsArr, hostsExists := ingressMap["hosts"]
  670. if hostsExists {
  671. hostsArrVal, hostsArrOk := hostsArr.([]interface{})
  672. if hostsArrOk && len(hostsArrVal) > 0 {
  673. if _, ok := hostsArrVal[0].(string); ok {
  674. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.hosts[0] }", resource.Name)
  675. isCustomDomain = true
  676. }
  677. }
  678. }
  679. }
  680. }
  681. }
  682. }
  683. if !isCustomDomain {
  684. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.porter_hosts[0] }", resource.Name)
  685. }
  686. }
  687. }
  688. return res
  689. }
  690. func (t *DeploymentHook) PostApply(populatedData map[string]interface{}) error {
  691. subdomains := make([]string, 0)
  692. for _, data := range populatedData {
  693. domain, ok := data.(string)
  694. if !ok {
  695. continue
  696. }
  697. if _, err := url.Parse("https://" + domain); err == nil {
  698. subdomains = append(subdomains, "https://"+domain)
  699. }
  700. }
  701. req := &types.FinalizeDeploymentRequest{
  702. Namespace: t.namespace,
  703. Subdomain: strings.Join(subdomains, ", "),
  704. }
  705. for _, res := range t.resourceGroup.Resources {
  706. releaseType := getReleaseType(res)
  707. releaseName := getReleaseName(res)
  708. if releaseType != "" && releaseName != "" {
  709. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  710. ReleaseName: releaseName,
  711. ReleaseType: releaseType,
  712. })
  713. }
  714. }
  715. // finalize the deployment
  716. _, err := t.client.FinalizeDeployment(
  717. context.Background(),
  718. t.projectID, t.gitInstallationID, t.clusterID,
  719. t.repoOwner, t.repoName, req,
  720. )
  721. return err
  722. }
  723. func (t *DeploymentHook) OnError(err error) {
  724. // if the deployment exists, throw an error for that deployment
  725. _, getDeplErr := t.client.GetDeployment(
  726. context.Background(),
  727. t.projectID, t.clusterID, t.envID,
  728. &types.GetDeploymentRequest{
  729. Namespace: t.namespace,
  730. },
  731. )
  732. if getDeplErr == nil {
  733. _, err = t.client.UpdateDeploymentStatus(
  734. context.Background(),
  735. t.projectID, t.gitInstallationID, t.clusterID,
  736. t.repoOwner, t.repoName,
  737. &types.UpdateDeploymentStatusRequest{
  738. Namespace: t.namespace,
  739. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  740. ActionID: t.actionID,
  741. },
  742. PRBranchFrom: t.branchFrom,
  743. Status: string(types.DeploymentStatusFailed),
  744. },
  745. )
  746. }
  747. }
  748. func (t *DeploymentHook) OnConsolidatedErrors(allErrors map[string]error) {
  749. // if the deployment exists, throw an error for that deployment
  750. _, getDeplErr := t.client.GetDeployment(
  751. context.Background(),
  752. t.projectID, t.clusterID, t.envID,
  753. &types.GetDeploymentRequest{
  754. Namespace: t.namespace,
  755. },
  756. )
  757. if getDeplErr == nil {
  758. req := &types.FinalizeDeploymentWithErrorsRequest{
  759. Namespace: t.namespace,
  760. Errors: make(map[string]string),
  761. }
  762. for _, res := range t.resourceGroup.Resources {
  763. if _, ok := allErrors[res.Name]; !ok {
  764. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  765. ReleaseName: getReleaseName(res),
  766. ReleaseType: getReleaseType(res),
  767. })
  768. }
  769. }
  770. for res, err := range allErrors {
  771. req.Errors[res] = err.Error()
  772. }
  773. // FIXME: handle the error
  774. t.client.FinalizeDeploymentWithErrors(
  775. context.Background(),
  776. t.projectID, t.gitInstallationID, t.clusterID,
  777. t.repoOwner, t.repoName,
  778. req,
  779. )
  780. }
  781. }
  782. type CloneEnvGroupHook struct {
  783. client *api.Client
  784. resGroup *switchboardTypes.ResourceGroup
  785. }
  786. func NewCloneEnvGroupHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup) *CloneEnvGroupHook {
  787. return &CloneEnvGroupHook{
  788. client: client,
  789. resGroup: resourceGroup,
  790. }
  791. }
  792. func (t *CloneEnvGroupHook) PreApply() error {
  793. for _, res := range t.resGroup.Resources {
  794. if res.Driver == "env-group" {
  795. continue
  796. }
  797. appConf := &previewInt.ApplicationConfig{}
  798. err := mapstructure.Decode(res.Config, &appConf)
  799. if err != nil {
  800. continue
  801. }
  802. if appConf != nil && len(appConf.EnvGroups) > 0 {
  803. target, err := preview.GetTarget(res.Name, res.Target)
  804. if err != nil {
  805. return err
  806. }
  807. for _, group := range appConf.EnvGroups {
  808. if group.Name == "" {
  809. return fmt.Errorf("env group name cannot be empty")
  810. }
  811. _, err := t.client.GetEnvGroup(
  812. context.Background(),
  813. target.Project,
  814. target.Cluster,
  815. target.Namespace,
  816. &types.GetEnvGroupRequest{
  817. Name: group.Name,
  818. Version: group.Version,
  819. },
  820. )
  821. if err != nil && err.Error() == "env group not found" {
  822. if group.Namespace == "" {
  823. return fmt.Errorf("env group namespace cannot be empty")
  824. }
  825. color.New(color.FgBlue, color.Bold).
  826. Printf("Env group '%s' does not exist in the target namespace '%s'\n", group.Name, target.Namespace)
  827. color.New(color.FgBlue, color.Bold).
  828. Printf("Cloning env group '%s' from namespace '%s' to target namespace '%s'\n",
  829. group.Name, group.Namespace, target.Namespace)
  830. _, err = t.client.CloneEnvGroup(
  831. context.Background(), target.Project, target.Cluster, group.Namespace,
  832. &types.CloneEnvGroupRequest{
  833. Name: group.Name,
  834. Namespace: target.Namespace,
  835. },
  836. )
  837. if err != nil {
  838. return err
  839. }
  840. } else if err != nil {
  841. return err
  842. }
  843. }
  844. }
  845. }
  846. return nil
  847. }
  848. func (t *CloneEnvGroupHook) DataQueries() map[string]interface{} {
  849. return nil
  850. }
  851. func (t *CloneEnvGroupHook) PostApply(map[string]interface{}) error {
  852. return nil
  853. }
  854. func (t *CloneEnvGroupHook) OnError(error) {}
  855. func (t *CloneEnvGroupHook) OnConsolidatedErrors(map[string]error) {}
  856. func getReleaseName(res *switchboardTypes.Resource) string {
  857. // can ignore the error because this method is called once
  858. // GetTarget has alrealy been called and validated previously
  859. target, _ := preview.GetTarget(res.Name, res.Target)
  860. if target.AppName != "" {
  861. return target.AppName
  862. }
  863. return res.Name
  864. }
  865. func getReleaseType(res *switchboardTypes.Resource) string {
  866. // can ignore the error because this method is called once
  867. // GetSource has alrealy been called and validated previously
  868. source, _ := preview.GetSource(res.Name, res.Source)
  869. if source != nil && source.Name != "" {
  870. return source.Name
  871. }
  872. return ""
  873. }