apply.go 35 KB

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