apply.go 33 KB

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