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