2
0

apply.go 34 KB

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