apply.go 32 KB

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