apply.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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. switchboardWorker "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, _ []string) error {
  71. fileBytes, err := ioutil.ReadFile(porterYAML)
  72. if err != nil {
  73. return fmt.Errorf("error reading porter.yaml: %w", err)
  74. }
  75. resGroup, err := parser.ParseRawBytes(fileBytes)
  76. if err != nil {
  77. return fmt.Errorf("error parsing porter.yaml: %w", err)
  78. }
  79. basePath, err := os.Getwd()
  80. if err != nil {
  81. return fmt.Errorf("error getting working directory: %w", err)
  82. }
  83. worker := switchboardWorker.NewWorker()
  84. worker.RegisterDriver("deploy", NewDeployDriver)
  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 fmt.Errorf("error creating deployment hook: %w", 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 DeployDriver 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 NewDeployDriver(resource *models.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  162. driver := &DeployDriver{
  163. lookupTable: opts.DriverLookupTable,
  164. logger: opts.Logger,
  165. output: make(map[string]interface{}),
  166. }
  167. source, err := preview.GetSource(resource.Name, resource.Source)
  168. if err != nil {
  169. return nil, err
  170. }
  171. driver.source = source
  172. target, err := preview.GetTarget(resource.Name, resource.Target)
  173. if err != nil {
  174. return nil, err
  175. }
  176. driver.target = target
  177. return driver, nil
  178. }
  179. func (d *DeployDriver) ShouldApply(_ *models.Resource) bool {
  180. return true
  181. }
  182. func (d *DeployDriver) Apply(resource *models.Resource) (*models.Resource, error) {
  183. client := config.GetAPIClient()
  184. name := resource.Name
  185. if name == "" {
  186. return nil, fmt.Errorf("empty resource 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 *DeployDriver) 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, fmt.Errorf("error getting addon config for resource %s: %w", resource.Name, 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. if err != nil {
  227. return nil, fmt.Errorf("error creating addon from resource %s: %w", resource.Name, err)
  228. }
  229. } else {
  230. bytes, err := json.Marshal(addonConfig)
  231. if err != nil {
  232. return nil, fmt.Errorf("error marshalling addon config from resource %s: %w", resource.Name, err)
  233. }
  234. err = client.UpgradeRelease(
  235. context.Background(),
  236. d.target.Project,
  237. d.target.Cluster,
  238. d.target.Namespace,
  239. resource.Name,
  240. &types.UpgradeReleaseRequest{
  241. Values: string(bytes),
  242. },
  243. )
  244. if err != nil {
  245. return nil, fmt.Errorf("error updating addon from resource %s: %w", resource.Name, err)
  246. }
  247. }
  248. if err = d.assignOutput(resource, client); err != nil {
  249. return nil, err
  250. }
  251. return resource, nil
  252. }
  253. func (d *DeployDriver) applyApplication(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  254. if resource == nil {
  255. return nil, fmt.Errorf("nil resource")
  256. }
  257. resourceName := resource.Name
  258. appConfig, err := d.getApplicationConfig(resource)
  259. if err != nil {
  260. return nil, err
  261. }
  262. method := appConfig.Build.Method
  263. if method != "pack" && method != "docker" && method != "registry" {
  264. return nil, fmt.Errorf("for resource %s, config.build.method should either be \"docker\", \"pack\" or \"registry\"",
  265. resourceName)
  266. }
  267. fullPath, err := filepath.Abs(appConfig.Build.Context)
  268. if err != nil {
  269. return nil, fmt.Errorf("for resource %s, error getting absolute path for config.build.context: %w", resourceName,
  270. err)
  271. }
  272. tag := os.Getenv("PORTER_TAG")
  273. if tag == "" {
  274. color.New(color.FgYellow).Printf("for resource %s, since PORTER_TAG is not set, the Docker image tag will default to"+
  275. " the git repo SHA", resourceName)
  276. commit, err := git.LastCommit()
  277. if err != nil {
  278. return nil, fmt.Errorf("for resource %s, error getting last git commit: %w", resourceName, err)
  279. }
  280. tag = commit.Sha[:7]
  281. color.New(color.FgYellow).Printf("for resource %s, using tag %s\n", resourceName, tag)
  282. }
  283. // if the method is registry and a tag is defined, we use the provided tag
  284. if appConfig.Build.Method == "registry" {
  285. imageSpl := strings.Split(appConfig.Build.Image, ":")
  286. if len(imageSpl) == 2 {
  287. tag = imageSpl[1]
  288. }
  289. if tag == "" {
  290. tag = "latest"
  291. }
  292. }
  293. sharedOpts := &deploy.SharedOpts{
  294. ProjectID: d.target.Project,
  295. ClusterID: d.target.Cluster,
  296. Namespace: d.target.Namespace,
  297. LocalPath: fullPath,
  298. LocalDockerfile: appConfig.Build.Dockerfile,
  299. OverrideTag: tag,
  300. Method: deploy.DeployBuildType(method),
  301. EnvGroups: appConfig.EnvGroups,
  302. UseCache: appConfig.Build.UseCache,
  303. }
  304. if appConfig.Build.UseCache {
  305. // set the docker config so that pack caching can use the repo credentials
  306. err := config.SetDockerConfig(client)
  307. if err != nil {
  308. return nil, err
  309. }
  310. }
  311. if shouldCreate {
  312. resource, err = d.createApplication(resource, client, sharedOpts, appConfig)
  313. if err != nil {
  314. return nil, fmt.Errorf("error creating app from resource %s: %w", resourceName, err)
  315. }
  316. } else if !appConfig.OnlyCreate {
  317. resource, err = d.updateApplication(resource, client, sharedOpts, appConfig)
  318. if err != nil {
  319. return nil, fmt.Errorf("error updating application from resource %s: %w", resourceName, err)
  320. }
  321. } else {
  322. color.New(color.FgYellow).Printf("Skipping creation for resource %s as onlyCreate is set to true\n", resourceName)
  323. }
  324. if err = d.assignOutput(resource, client); err != nil {
  325. return nil, err
  326. }
  327. if d.source.Name == "job" && appConfig.WaitForJob && (shouldCreate || !appConfig.OnlyCreate) {
  328. color.New(color.FgYellow).Printf("Waiting for job '%s' to finish\n", resourceName)
  329. err = wait.WaitForJob(client, &wait.WaitOpts{
  330. ProjectID: d.target.Project,
  331. ClusterID: d.target.Cluster,
  332. Namespace: d.target.Namespace,
  333. Name: resourceName,
  334. })
  335. if err != nil && appConfig.OnlyCreate {
  336. deleteJobErr := client.DeleteRelease(
  337. context.Background(),
  338. d.target.Project,
  339. d.target.Cluster,
  340. d.target.Namespace,
  341. resourceName,
  342. )
  343. if deleteJobErr != nil {
  344. return nil, fmt.Errorf("error deleting job %s with waitForJob and onlyCreate set to true: %w",
  345. resourceName, deleteJobErr)
  346. }
  347. } else if err != nil {
  348. return nil, fmt.Errorf("error waiting for job %s: %w", resourceName, err)
  349. }
  350. }
  351. return resource, err
  352. }
  353. func (d *DeployDriver) createApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  354. // create new release
  355. color.New(color.FgGreen).Printf("Creating %s release: %s\n", d.source.Name, resource.Name)
  356. regList, err := client.ListRegistries(context.Background(), d.target.Project)
  357. if err != nil {
  358. return nil, fmt.Errorf("for resource %s, error listing registries: %w", resource.Name, err)
  359. }
  360. var registryURL string
  361. if len(*regList) == 0 {
  362. return nil, fmt.Errorf("no registry found")
  363. } else {
  364. registryURL = (*regList)[0].URL
  365. }
  366. color.New(color.FgBlue).Printf("for resource %s, using registry %s\n", resource.Name, registryURL)
  367. // attempt to get repo suffix from environment variables
  368. var repoSuffix string
  369. if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
  370. if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
  371. repoSuffix = strings.ToLower(strings.ReplaceAll(fmt.Sprintf("%s-%s", repoOwner, repoName), "_", "-"))
  372. }
  373. }
  374. createAgent := &deploy.CreateAgent{
  375. Client: client,
  376. CreateOpts: &deploy.CreateOpts{
  377. SharedOpts: sharedOpts,
  378. Kind: d.source.Name,
  379. ReleaseName: resource.Name,
  380. RegistryURL: registryURL,
  381. RepoSuffix: repoSuffix,
  382. },
  383. }
  384. var buildConfig *types.BuildConfig
  385. if appConf.Build.Builder != "" {
  386. buildConfig = &types.BuildConfig{
  387. Builder: appConf.Build.Builder,
  388. Buildpacks: appConf.Build.Buildpacks,
  389. }
  390. }
  391. var subdomain string
  392. if appConf.Build.Method == "registry" {
  393. subdomain, err = createAgent.CreateFromRegistry(appConf.Build.Image, appConf.Values)
  394. } else {
  395. // if useCache is set, create the image repository first
  396. if appConf.Build.UseCache {
  397. regID, imageURL, err := createAgent.GetImageRepoURL(resource.Name, sharedOpts.Namespace)
  398. if err != nil {
  399. return nil, err
  400. }
  401. err = client.CreateRepository(
  402. context.Background(),
  403. sharedOpts.ProjectID,
  404. regID,
  405. &types.CreateRegistryRepositoryRequest{
  406. ImageRepoURI: imageURL,
  407. },
  408. )
  409. if err != nil {
  410. return nil, err
  411. }
  412. }
  413. subdomain, err = createAgent.CreateFromDocker(appConf.Values, sharedOpts.OverrideTag, buildConfig)
  414. }
  415. if err != nil {
  416. return nil, err
  417. }
  418. return resource, handleSubdomainCreate(subdomain, err)
  419. }
  420. func (d *DeployDriver) updateApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  421. color.New(color.FgGreen).Println("Updating existing release:", resource.Name)
  422. if len(appConf.Build.Env) > 0 {
  423. sharedOpts.AdditionalEnv = appConf.Build.Env
  424. }
  425. updateAgent, err := deploy.NewDeployAgent(client, resource.Name, &deploy.DeployOpts{
  426. SharedOpts: sharedOpts,
  427. Local: appConf.Build.Method != "registry",
  428. })
  429. if err != nil {
  430. return nil, err
  431. }
  432. // if the build method is registry, we do not trigger a build
  433. if appConf.Build.Method != "registry" {
  434. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  435. UseNewConfig: true,
  436. NewConfig: appConf.Values,
  437. })
  438. if err != nil {
  439. return nil, err
  440. }
  441. err = updateAgent.SetBuildEnv(buildEnv)
  442. if err != nil {
  443. return nil, err
  444. }
  445. var buildConfig *types.BuildConfig
  446. if appConf.Build.Builder != "" {
  447. buildConfig = &types.BuildConfig{
  448. Builder: appConf.Build.Builder,
  449. Buildpacks: appConf.Build.Buildpacks,
  450. }
  451. }
  452. err = updateAgent.Build(buildConfig)
  453. if err != nil {
  454. return nil, err
  455. }
  456. if !appConf.Build.UseCache {
  457. err = updateAgent.Push()
  458. if err != nil {
  459. return nil, err
  460. }
  461. }
  462. }
  463. err = updateAgent.UpdateImageAndValues(appConf.Values)
  464. if err != nil {
  465. return nil, err
  466. }
  467. return resource, nil
  468. }
  469. func (d *DeployDriver) assignOutput(resource *models.Resource, client *api.Client) error {
  470. release, err := client.GetRelease(
  471. context.Background(),
  472. d.target.Project,
  473. d.target.Cluster,
  474. d.target.Namespace,
  475. resource.Name,
  476. )
  477. if err != nil {
  478. return err
  479. }
  480. d.output = utils.CoalesceValues(d.source.SourceValues, release.Config)
  481. return nil
  482. }
  483. func (d *DeployDriver) Output() (map[string]interface{}, error) {
  484. return d.output, nil
  485. }
  486. func (d *DeployDriver) getApplicationConfig(resource *models.Resource) (*ApplicationConfig, error) {
  487. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  488. RawConf: resource.Config,
  489. LookupTable: *d.lookupTable,
  490. Dependencies: resource.Dependencies,
  491. })
  492. if err != nil {
  493. return nil, err
  494. }
  495. appConf := &ApplicationConfig{}
  496. err = mapstructure.Decode(populatedConf, appConf)
  497. if err != nil {
  498. return nil, err
  499. }
  500. if _, ok := resource.Config["waitForJob"]; !ok && d.source.Name == "job" {
  501. // default to true and wait for the job to finish
  502. appConf.WaitForJob = true
  503. }
  504. return appConf, nil
  505. }
  506. func (d *DeployDriver) getAddonConfig(resource *models.Resource) (map[string]interface{}, error) {
  507. return drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  508. RawConf: resource.Config,
  509. LookupTable: *d.lookupTable,
  510. Dependencies: resource.Dependencies,
  511. })
  512. }
  513. type DeploymentHook struct {
  514. client *api.Client
  515. resourceGroup *switchboardTypes.ResourceGroup
  516. gitInstallationID, projectID, clusterID, prID, actionID, envID uint
  517. branchFrom, branchInto, namespace, repoName, repoOwner, prName, commitSHA string
  518. }
  519. func NewDeploymentHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup, namespace string) (*DeploymentHook, error) {
  520. res := &DeploymentHook{
  521. client: client,
  522. resourceGroup: resourceGroup,
  523. namespace: namespace,
  524. }
  525. ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID")
  526. ghID, err := strconv.Atoi(ghIDStr)
  527. if err != nil {
  528. return nil, err
  529. }
  530. res.gitInstallationID = uint(ghID)
  531. prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID")
  532. prID, err := strconv.Atoi(prIDStr)
  533. if err != nil {
  534. return nil, err
  535. }
  536. res.prID = uint(prID)
  537. res.projectID = cliConf.Project
  538. if res.projectID == 0 {
  539. return nil, fmt.Errorf("project id must be set")
  540. }
  541. res.clusterID = cliConf.Cluster
  542. if res.clusterID == 0 {
  543. return nil, fmt.Errorf("cluster id must be set")
  544. }
  545. branchFrom := os.Getenv("PORTER_BRANCH_FROM")
  546. res.branchFrom = branchFrom
  547. branchInto := os.Getenv("PORTER_BRANCH_INTO")
  548. res.branchInto = branchInto
  549. actionIDStr := os.Getenv("PORTER_ACTION_ID")
  550. actionID, err := strconv.Atoi(actionIDStr)
  551. if err != nil {
  552. return nil, err
  553. }
  554. res.actionID = uint(actionID)
  555. repoName := os.Getenv("PORTER_REPO_NAME")
  556. res.repoName = repoName
  557. repoOwner := os.Getenv("PORTER_REPO_OWNER")
  558. res.repoOwner = repoOwner
  559. prName := os.Getenv("PORTER_PR_NAME")
  560. res.prName = prName
  561. commit, err := git.LastCommit()
  562. if err != nil {
  563. return nil, fmt.Errorf(err.Error())
  564. }
  565. res.commitSHA = commit.Sha[:7]
  566. return res, nil
  567. }
  568. func (t *DeploymentHook) PreApply() error {
  569. envList, err := t.client.ListEnvironments(
  570. context.Background(), t.projectID, t.clusterID,
  571. )
  572. if err != nil {
  573. return err
  574. }
  575. envs := *envList
  576. for _, env := range envs {
  577. if env.GitRepoOwner == t.repoOwner && env.GitRepoName == t.repoName && env.GitInstallationID == t.gitInstallationID {
  578. t.envID = env.ID
  579. break
  580. }
  581. }
  582. if t.envID == 0 {
  583. return fmt.Errorf("could not find environment for deployment")
  584. }
  585. // attempt to read the deployment -- if it doesn't exist, create it
  586. _, err = t.client.GetDeployment(
  587. context.Background(),
  588. t.projectID, t.clusterID, t.envID,
  589. &types.GetDeploymentRequest{
  590. Namespace: t.namespace,
  591. },
  592. )
  593. if err != nil && strings.Contains(err.Error(), "not found") {
  594. // in this case, create the deployment
  595. _, err = t.client.CreateDeployment(
  596. context.Background(),
  597. t.projectID, t.gitInstallationID, t.clusterID,
  598. t.repoOwner, t.repoName,
  599. &types.CreateDeploymentRequest{
  600. Namespace: t.namespace,
  601. PullRequestID: t.prID,
  602. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  603. ActionID: t.actionID,
  604. },
  605. GitHubMetadata: &types.GitHubMetadata{
  606. PRName: t.prName,
  607. RepoName: t.repoName,
  608. RepoOwner: t.repoOwner,
  609. CommitSHA: t.commitSHA,
  610. PRBranchFrom: t.branchFrom,
  611. PRBranchInto: t.branchInto,
  612. },
  613. },
  614. )
  615. } else if err == nil {
  616. _, err = t.client.UpdateDeployment(
  617. context.Background(),
  618. t.projectID, t.gitInstallationID, t.clusterID,
  619. t.repoOwner, t.repoName,
  620. &types.UpdateDeploymentRequest{
  621. Namespace: t.namespace,
  622. CreateGHDeploymentRequest: &types.CreateGHDeploymentRequest{
  623. ActionID: t.actionID,
  624. },
  625. PRBranchFrom: t.branchFrom,
  626. CommitSHA: t.commitSHA,
  627. },
  628. )
  629. }
  630. return err
  631. }
  632. func (t *DeploymentHook) DataQueries() map[string]interface{} {
  633. res := make(map[string]interface{})
  634. // use the resource group to find all web applications that can have an exposed subdomain
  635. // that we can query for
  636. for _, resource := range t.resourceGroup.Resources {
  637. isWeb := false
  638. if sourceNameInter, exists := resource.Source["name"]; exists {
  639. if sourceName, ok := sourceNameInter.(string); ok {
  640. if sourceName == "web" {
  641. isWeb = true
  642. }
  643. }
  644. }
  645. if isWeb {
  646. // determine if we should query for porter_hosts or just hosts
  647. isCustomDomain := false
  648. ingressMap, err := deploy.GetNestedMap(resource.Config, "values", "ingress")
  649. if err == nil {
  650. enabledVal, enabledExists := ingressMap["enabled"]
  651. customDomVal, customDomExists := ingressMap["custom_domain"]
  652. if enabledExists && customDomExists {
  653. enabled, eOK := enabledVal.(bool)
  654. customDomain, cOK := customDomVal.(bool)
  655. if eOK && cOK && enabled {
  656. if customDomain {
  657. // return the first custom domain when one exists
  658. hostsArr, hostsExists := ingressMap["hosts"]
  659. if hostsExists {
  660. hostsArrVal, hostsArrOk := hostsArr.([]interface{})
  661. if hostsArrOk && len(hostsArrVal) > 0 {
  662. if _, ok := hostsArrVal[0].(string); ok {
  663. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.hosts[0] }", resource.Name)
  664. isCustomDomain = true
  665. }
  666. }
  667. }
  668. }
  669. }
  670. }
  671. }
  672. if !isCustomDomain {
  673. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.porter_hosts[0] }", resource.Name)
  674. }
  675. }
  676. }
  677. return res
  678. }
  679. func (t *DeploymentHook) PostApply(populatedData map[string]interface{}) error {
  680. subdomains := make([]string, 0)
  681. for _, data := range populatedData {
  682. domain, ok := data.(string)
  683. if !ok {
  684. continue
  685. }
  686. if _, err := url.Parse("https://" + domain); err == nil {
  687. subdomains = append(subdomains, "https://"+domain)
  688. }
  689. }
  690. req := &types.FinalizeDeploymentRequest{
  691. Namespace: t.namespace,
  692. Subdomain: strings.Join(subdomains, ", "),
  693. }
  694. for _, res := range t.resourceGroup.Resources {
  695. releaseType := getReleaseType(res)
  696. releaseName := getReleaseName(res)
  697. if releaseType != "" && releaseName != "" {
  698. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  699. ReleaseName: releaseName,
  700. ReleaseType: releaseType,
  701. })
  702. }
  703. }
  704. // finalize the deployment
  705. _, err := t.client.FinalizeDeployment(
  706. context.Background(),
  707. t.projectID, t.gitInstallationID, t.clusterID,
  708. t.repoOwner, t.repoName, req,
  709. )
  710. return err
  711. }
  712. func (t *DeploymentHook) OnError(err error) {
  713. // if the deployment exists, throw an error for that deployment
  714. _, getDeplErr := t.client.GetDeployment(
  715. context.Background(),
  716. t.projectID, t.clusterID, t.envID,
  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. ActionID: t.actionID,
  730. },
  731. PRBranchFrom: t.branchFrom,
  732. Status: string(types.DeploymentStatusFailed),
  733. },
  734. )
  735. }
  736. }
  737. func (t *DeploymentHook) OnConsolidatedErrors(allErrors map[string]error) {
  738. // if the deployment exists, throw an error for that deployment
  739. _, getDeplErr := t.client.GetDeployment(
  740. context.Background(),
  741. t.projectID, t.clusterID, t.envID,
  742. &types.GetDeploymentRequest{
  743. Namespace: t.namespace,
  744. },
  745. )
  746. if getDeplErr == nil {
  747. req := &types.FinalizeDeploymentWithErrorsRequest{
  748. Namespace: t.namespace,
  749. Errors: make(map[string]string),
  750. }
  751. for _, res := range t.resourceGroup.Resources {
  752. if _, ok := allErrors[res.Name]; !ok {
  753. req.SuccessfulResources = append(req.SuccessfulResources, &types.SuccessfullyDeployedResource{
  754. ReleaseName: getReleaseName(res),
  755. ReleaseType: getReleaseType(res),
  756. })
  757. }
  758. }
  759. for res, err := range allErrors {
  760. req.Errors[res] = err.Error()
  761. }
  762. // FIXME: handle the error
  763. t.client.FinalizeDeploymentWithErrors(
  764. context.Background(),
  765. t.projectID, t.gitInstallationID, t.clusterID,
  766. t.repoOwner, t.repoName,
  767. req,
  768. )
  769. }
  770. }
  771. type CloneEnvGroupHook struct {
  772. client *api.Client
  773. resGroup *switchboardTypes.ResourceGroup
  774. }
  775. func NewCloneEnvGroupHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup) *CloneEnvGroupHook {
  776. return &CloneEnvGroupHook{
  777. client: client,
  778. resGroup: resourceGroup,
  779. }
  780. }
  781. func (t *CloneEnvGroupHook) PreApply() error {
  782. for _, res := range t.resGroup.Resources {
  783. if res.Driver == "env-group" {
  784. continue
  785. }
  786. appConf := &ApplicationConfig{}
  787. err := mapstructure.Decode(res.Config, &appConf)
  788. if err != nil {
  789. continue
  790. }
  791. if appConf != nil && len(appConf.EnvGroups) > 0 {
  792. target, err := preview.GetTarget(res.Name, res.Target)
  793. if err != nil {
  794. return err
  795. }
  796. for _, group := range appConf.EnvGroups {
  797. if group.Name == "" {
  798. return fmt.Errorf("env group name cannot be empty")
  799. }
  800. _, err := t.client.GetEnvGroup(
  801. context.Background(),
  802. target.Project,
  803. target.Cluster,
  804. target.Namespace,
  805. &types.GetEnvGroupRequest{
  806. Name: group.Name,
  807. Version: group.Version,
  808. },
  809. )
  810. if err != nil && err.Error() == "env group not found" {
  811. if group.Namespace == "" {
  812. return fmt.Errorf("env group namespace cannot be empty")
  813. }
  814. color.New(color.FgBlue, color.Bold).
  815. Printf("Env group '%s' does not exist in the target namespace '%s'\n", group.Name, target.Namespace)
  816. color.New(color.FgBlue, color.Bold).
  817. Printf("Cloning env group '%s' from namespace '%s' to target namespace '%s'\n",
  818. group.Name, group.Namespace, target.Namespace)
  819. _, err = t.client.CloneEnvGroup(
  820. context.Background(), target.Project, target.Cluster, group.Namespace,
  821. &types.CloneEnvGroupRequest{
  822. Name: group.Name,
  823. Namespace: target.Namespace,
  824. },
  825. )
  826. if err != nil {
  827. return err
  828. }
  829. } else if err != nil {
  830. return err
  831. }
  832. }
  833. }
  834. }
  835. return nil
  836. }
  837. func (t *CloneEnvGroupHook) DataQueries() map[string]interface{} {
  838. return nil
  839. }
  840. func (t *CloneEnvGroupHook) PostApply(map[string]interface{}) error {
  841. return nil
  842. }
  843. func (t *CloneEnvGroupHook) OnError(error) {}
  844. func (t *CloneEnvGroupHook) OnConsolidatedErrors(map[string]error) {}
  845. func getReleaseName(res *switchboardTypes.Resource) string {
  846. // can ignore the error because this method is called once
  847. // GetTarget has alrealy been called and validated previously
  848. target, _ := preview.GetTarget(res.Name, res.Target)
  849. if target.AppName != "" {
  850. return target.AppName
  851. }
  852. return res.Name
  853. }
  854. func getReleaseType(res *switchboardTypes.Resource) string {
  855. // can ignore the error because this method is called once
  856. // GetSource has alrealy been called and validated previously
  857. source, _ := preview.GetSource(res.Name, res.Source)
  858. if source != nil && source.Name != "" {
  859. return source.Name
  860. }
  861. return ""
  862. }