apply.go 33 KB

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