apply.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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/deploy"
  18. "github.com/porter-dev/porter/internal/templater/utils"
  19. "github.com/porter-dev/switchboard/pkg/drivers"
  20. "github.com/porter-dev/switchboard/pkg/models"
  21. "github.com/porter-dev/switchboard/pkg/parser"
  22. switchboardTypes "github.com/porter-dev/switchboard/pkg/types"
  23. "github.com/porter-dev/switchboard/pkg/worker"
  24. "github.com/rs/zerolog"
  25. "github.com/spf13/cobra"
  26. )
  27. // applyCmd represents the "porter apply" base command when called
  28. // with a porter.yaml file as an argument
  29. var applyCmd = &cobra.Command{
  30. Use: "apply",
  31. Short: "Applies a configuration to an application",
  32. Long: fmt.Sprintf(`
  33. %s
  34. Applies a configuration to an application by either creating a new one or updating an existing
  35. one. For example:
  36. %s
  37. This command will apply the configuration contained in porter.yaml to the requested project and
  38. cluster either provided inside the porter.yaml file or through environment variables. Note that
  39. environment variables will always take precendence over values specified in the porter.yaml file.
  40. By default, this command expects to be run from a local git repository.
  41. The following are the environment variables that can be used to set certain values while
  42. applying a configuration:
  43. PORTER_CLUSTER Cluster ID that contains the project
  44. PORTER_PROJECT Project ID that contains the application
  45. PORTER_NAMESPACE The Kubernetes namespace that the application belongs to
  46. PORTER_SOURCE_NAME Name of the source Helm chart
  47. PORTER_SOURCE_REPO The URL of the Helm charts registry
  48. PORTER_SOURCE_VERSION The version of the Helm chart to use
  49. PORTER_TAG The Docker image tag to use (like the git commit hash)
  50. `,
  51. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter apply\":"),
  52. color.New(color.FgGreen, color.Bold).Sprintf("porter apply -f porter.yaml"),
  53. ),
  54. Run: func(cmd *cobra.Command, args []string) {
  55. err := checkLoginAndRun(args, apply)
  56. if err != nil {
  57. os.Exit(1)
  58. }
  59. },
  60. }
  61. var porterYAML string
  62. func init() {
  63. rootCmd.AddCommand(applyCmd)
  64. applyCmd.Flags().StringVarP(&porterYAML, "file", "f", "", "path to porter.yaml")
  65. applyCmd.MarkFlagRequired("file")
  66. }
  67. func apply(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  68. fileBytes, err := ioutil.ReadFile(porterYAML)
  69. if err != nil {
  70. return err
  71. }
  72. resGroup, err := parser.ParseRawBytes(fileBytes)
  73. if err != nil {
  74. return err
  75. }
  76. basePath, err := os.Getwd()
  77. if err != nil {
  78. return err
  79. }
  80. worker := worker.NewWorker()
  81. worker.RegisterDriver("porter.deploy", NewPorterDriver)
  82. worker.SetDefaultDriver("porter.deploy")
  83. deplNamespace := os.Getenv("PORTER_NAMESPACE")
  84. if deplNamespace == "" {
  85. return fmt.Errorf("namespace must be set by PORTER_NAMESPACE")
  86. }
  87. deploymentHook, err := NewDeploymentHook(client, resGroup, deplNamespace)
  88. if err != nil {
  89. return err
  90. }
  91. worker.RegisterHook("deployment", deploymentHook)
  92. return worker.Apply(resGroup, &switchboardTypes.ApplyOpts{
  93. BasePath: basePath,
  94. })
  95. }
  96. type Source struct {
  97. Name string
  98. Repo string
  99. Version string
  100. IsApplication bool
  101. SourceValues map[string]interface{}
  102. }
  103. type Target struct {
  104. Project uint
  105. Cluster uint
  106. Namespace string
  107. }
  108. type ApplicationConfig struct {
  109. Build struct {
  110. Method string
  111. Context string
  112. Dockerfile string
  113. }
  114. Values map[string]interface{}
  115. }
  116. type Driver struct {
  117. source *Source
  118. target *Target
  119. output map[string]interface{}
  120. lookupTable *map[string]drivers.Driver
  121. logger *zerolog.Logger
  122. }
  123. func NewPorterDriver(resource *models.Resource, opts *drivers.SharedDriverOpts) (drivers.Driver, error) {
  124. driver := &Driver{
  125. lookupTable: opts.DriverLookupTable,
  126. logger: opts.Logger,
  127. output: make(map[string]interface{}),
  128. }
  129. err := driver.getSource(resource.Source)
  130. if err != nil {
  131. return nil, err
  132. }
  133. err = driver.getTarget(resource.Target)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return driver, nil
  138. }
  139. func (d *Driver) ShouldApply(resource *models.Resource) bool {
  140. return true
  141. }
  142. func (d *Driver) Apply(resource *models.Resource) (*models.Resource, error) {
  143. client := GetAPIClient(config)
  144. name := resource.Name
  145. if name == "" {
  146. return nil, fmt.Errorf("empty app name")
  147. }
  148. _, err := client.GetRelease(
  149. context.Background(),
  150. d.target.Project,
  151. d.target.Cluster,
  152. d.target.Namespace,
  153. resource.Name,
  154. )
  155. shouldCreate := err != nil
  156. if err != nil {
  157. color.New(color.FgYellow).Printf("Could not read release %s/%s (%s): attempting creation\n", d.target.Namespace, resource.Name, err.Error())
  158. }
  159. if d.source.IsApplication {
  160. return d.applyApplication(resource, client, shouldCreate)
  161. }
  162. return d.applyAddon(resource, client, shouldCreate)
  163. }
  164. // Simple apply for addons
  165. func (d *Driver) applyAddon(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  166. var err error
  167. if shouldCreate {
  168. err = client.DeployAddon(
  169. context.Background(),
  170. d.target.Project,
  171. d.target.Cluster,
  172. d.target.Namespace,
  173. &types.CreateAddonRequest{
  174. CreateReleaseBaseRequest: &types.CreateReleaseBaseRequest{
  175. RepoURL: d.source.Repo,
  176. TemplateName: d.source.Name,
  177. TemplateVersion: d.source.Version,
  178. Values: resource.Config,
  179. Name: resource.Name,
  180. },
  181. },
  182. )
  183. } else {
  184. bytes, err := json.Marshal(resource.Config)
  185. if err != nil {
  186. return nil, err
  187. }
  188. err = client.UpgradeRelease(
  189. context.Background(),
  190. d.target.Project,
  191. d.target.Cluster,
  192. d.target.Namespace,
  193. resource.Name,
  194. &types.UpgradeReleaseRequest{
  195. Values: string(bytes),
  196. },
  197. )
  198. }
  199. if err != nil {
  200. return nil, err
  201. }
  202. if err = d.assignOutput(resource, client); err != nil {
  203. return nil, err
  204. }
  205. return resource, err
  206. }
  207. func (d *Driver) applyApplication(resource *models.Resource, client *api.Client, shouldCreate bool) (*models.Resource, error) {
  208. appConfig, err := d.getApplicationConfig(resource)
  209. if err != nil {
  210. return nil, err
  211. }
  212. method := appConfig.Build.Method
  213. if method != "pack" && method != "docker" {
  214. return nil, fmt.Errorf("method should either be \"docker\" or \"pack\"")
  215. }
  216. fullPath, err := filepath.Abs(appConfig.Build.Context)
  217. if err != nil {
  218. return nil, err
  219. }
  220. tag := os.Getenv("PORTER_TAG")
  221. if tag == "" {
  222. commit, err := git.LastCommit()
  223. if err != nil {
  224. return nil, err
  225. }
  226. tag = commit.Sha[:7]
  227. }
  228. sharedOpts := &deploy.SharedOpts{
  229. ProjectID: d.target.Project,
  230. ClusterID: d.target.Cluster,
  231. Namespace: d.target.Namespace,
  232. LocalPath: fullPath,
  233. LocalDockerfile: appConfig.Build.Dockerfile,
  234. OverrideTag: tag,
  235. Method: deploy.DeployBuildType(method),
  236. }
  237. if shouldCreate {
  238. resource, err = d.createApplication(resource, client, sharedOpts, appConfig)
  239. }
  240. resource, err = d.updateApplication(resource, client, sharedOpts, appConfig)
  241. if err != nil {
  242. return nil, err
  243. }
  244. if err = d.assignOutput(resource, client); err != nil {
  245. return nil, err
  246. }
  247. return resource, err
  248. }
  249. func (d *Driver) createApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  250. // create new release
  251. color.New(color.FgGreen).Printf("Creating %s release: %s\n", d.source.Name, resource.Name)
  252. regList, err := client.ListRegistries(context.Background(), d.target.Project)
  253. if err != nil {
  254. return nil, err
  255. }
  256. var registryURL string
  257. if len(*regList) == 0 {
  258. return nil, fmt.Errorf("no registry found")
  259. } else {
  260. registryURL = (*regList)[0].URL
  261. }
  262. createAgent := &deploy.CreateAgent{
  263. Client: client,
  264. CreateOpts: &deploy.CreateOpts{
  265. SharedOpts: sharedOpts,
  266. Kind: d.source.Name,
  267. ReleaseName: resource.Name,
  268. RegistryURL: registryURL,
  269. },
  270. }
  271. subdomain, err := createAgent.CreateFromDocker(appConf.Values, sharedOpts.OverrideTag)
  272. return resource, handleSubdomainCreate(subdomain, err)
  273. }
  274. func (d *Driver) updateApplication(resource *models.Resource, client *api.Client, sharedOpts *deploy.SharedOpts, appConf *ApplicationConfig) (*models.Resource, error) {
  275. color.New(color.FgGreen).Println("Updating existing release:", resource.Name)
  276. updateAgent, err := deploy.NewDeployAgent(client, resource.Name, &deploy.DeployOpts{
  277. SharedOpts: sharedOpts,
  278. Local: true,
  279. })
  280. if err != nil {
  281. return nil, err
  282. }
  283. buildEnv, err := updateAgent.GetBuildEnv()
  284. if err != nil {
  285. return nil, err
  286. }
  287. err = updateAgent.SetBuildEnv(buildEnv)
  288. if err != nil {
  289. return nil, err
  290. }
  291. err = updateAgent.Build()
  292. if err != nil {
  293. return nil, err
  294. }
  295. err = updateAgent.Push()
  296. if err != nil {
  297. return nil, err
  298. }
  299. err = updateAgent.UpdateImageAndValues(appConf.Values)
  300. if err != nil {
  301. return nil, err
  302. }
  303. return resource, nil
  304. }
  305. func (d *Driver) assignOutput(resource *models.Resource, client *api.Client) error {
  306. release, err := client.GetRelease(
  307. context.Background(),
  308. d.target.Project,
  309. d.target.Cluster,
  310. d.target.Namespace,
  311. resource.Name,
  312. )
  313. if err != nil {
  314. return err
  315. }
  316. d.output = utils.CoalesceValues(d.source.SourceValues, release.Config)
  317. return nil
  318. }
  319. func (d *Driver) Output() (map[string]interface{}, error) {
  320. return d.output, nil
  321. }
  322. func (d *Driver) getSource(genericSource map[string]interface{}) error {
  323. d.source = &Source{}
  324. // first read from env vars
  325. d.source.Name = os.Getenv("PORTER_SOURCE_NAME")
  326. d.source.Repo = os.Getenv("PORTER_SOURCE_REPO")
  327. d.source.Version = os.Getenv("PORTER_SOURCE_VERSION")
  328. // next, check for values in the YAML file
  329. if d.source.Name == "" {
  330. if name, ok := genericSource["name"]; ok {
  331. nameVal, ok := name.(string)
  332. if !ok {
  333. return fmt.Errorf("invalid name provided")
  334. }
  335. d.source.Name = nameVal
  336. }
  337. }
  338. if d.source.Name == "" {
  339. return fmt.Errorf("source name required")
  340. }
  341. if d.source.Repo == "" {
  342. if repo, ok := genericSource["repo"]; ok {
  343. repoVal, ok := repo.(string)
  344. if !ok {
  345. return fmt.Errorf("invalid repo provided")
  346. }
  347. d.source.Repo = repoVal
  348. }
  349. }
  350. if d.source.Version == "" {
  351. if version, ok := genericSource["version"]; ok {
  352. versionVal, ok := version.(string)
  353. if !ok {
  354. return fmt.Errorf("invalid version provided")
  355. }
  356. d.source.Version = versionVal
  357. }
  358. }
  359. // lastly, just put in the defaults
  360. if d.source.Version == "" {
  361. d.source.Version = "latest"
  362. }
  363. d.source.IsApplication = d.source.Repo == "https://charts.getporter.dev"
  364. if d.source.Repo == "" {
  365. d.source.Repo = "https://charts.getporter.dev"
  366. values, err := existsInRepo(d.source.Name, d.source.Version, d.source.Repo)
  367. if err == nil {
  368. // found in "https://charts.getporter.dev"
  369. d.source.SourceValues = values
  370. d.source.IsApplication = true
  371. return nil
  372. }
  373. d.source.Repo = "https://chart-addons.getporter.dev"
  374. values, err = existsInRepo(d.source.Name, d.source.Version, d.source.Repo)
  375. if err == nil {
  376. // found in https://chart-addons.getporter.dev
  377. d.source.SourceValues = values
  378. return nil
  379. }
  380. return fmt.Errorf("source does not exist in any repo")
  381. }
  382. return fmt.Errorf("source '%s' does not exist in repo '%s'", d.source.Name, d.source.Repo)
  383. }
  384. func (d *Driver) getTarget(genericTarget map[string]interface{}) error {
  385. d.target = &Target{}
  386. // first read from env vars
  387. if projectEnv := os.Getenv("PORTER_PROJECT"); projectEnv != "" {
  388. project, err := strconv.Atoi(projectEnv)
  389. if err != nil {
  390. return err
  391. }
  392. d.target.Project = uint(project)
  393. }
  394. if clusterEnv := os.Getenv("PORTER_CLUSTER"); clusterEnv != "" {
  395. cluster, err := strconv.Atoi(clusterEnv)
  396. if err != nil {
  397. return err
  398. }
  399. d.target.Cluster = uint(cluster)
  400. }
  401. d.target.Namespace = os.Getenv("PORTER_NAMESPACE")
  402. // next, check for values in the YAML file
  403. if d.target.Project == 0 {
  404. if project, ok := genericTarget["project"]; ok {
  405. projectVal, ok := project.(uint)
  406. if !ok {
  407. return fmt.Errorf("project value must be an integer")
  408. }
  409. d.target.Project = projectVal
  410. }
  411. }
  412. if d.target.Cluster == 0 {
  413. if cluster, ok := genericTarget["cluster"]; ok {
  414. clusterVal, ok := cluster.(uint)
  415. if !ok {
  416. return fmt.Errorf("cluster value must be an integer")
  417. }
  418. d.target.Cluster = clusterVal
  419. }
  420. }
  421. if d.target.Namespace == "" {
  422. if namespace, ok := genericTarget["namespace"]; ok {
  423. namespaceVal, ok := namespace.(string)
  424. if !ok {
  425. return fmt.Errorf("invalid namespace provided")
  426. }
  427. d.target.Namespace = namespaceVal
  428. }
  429. }
  430. // lastly, just put in the defaults
  431. if d.target.Project == 0 {
  432. d.target.Project = config.Project
  433. }
  434. if d.target.Cluster == 0 {
  435. d.target.Cluster = config.Cluster
  436. }
  437. if d.target.Namespace == "" {
  438. d.target.Namespace = "default"
  439. }
  440. return nil
  441. }
  442. func (d *Driver) getApplicationConfig(resource *models.Resource) (*ApplicationConfig, error) {
  443. populatedConf, err := drivers.ConstructConfig(&drivers.ConstructConfigOpts{
  444. RawConf: resource.Config,
  445. LookupTable: *d.lookupTable,
  446. Dependencies: resource.Dependencies,
  447. })
  448. if err != nil {
  449. return nil, err
  450. }
  451. config := &ApplicationConfig{}
  452. err = mapstructure.Decode(populatedConf, config)
  453. if err != nil {
  454. return nil, err
  455. }
  456. return config, nil
  457. }
  458. func existsInRepo(name, version, url string) (map[string]interface{}, error) {
  459. chart, err := GetAPIClient(config).GetTemplate(
  460. context.Background(),
  461. name, version,
  462. &types.GetTemplateRequest{
  463. TemplateGetBaseRequest: types.TemplateGetBaseRequest{
  464. RepoURL: url,
  465. },
  466. },
  467. )
  468. if err != nil {
  469. return nil, err
  470. }
  471. return chart.Values, nil
  472. }
  473. type DeploymentHook struct {
  474. client *api.Client
  475. resourceGroup *switchboardTypes.ResourceGroup
  476. gitInstallationID, projectID, clusterID, prID, actionID uint
  477. branch, namespace string
  478. }
  479. func NewDeploymentHook(client *api.Client, resourceGroup *switchboardTypes.ResourceGroup, namespace string) (*DeploymentHook, error) {
  480. res := &DeploymentHook{
  481. client: client,
  482. resourceGroup: resourceGroup,
  483. namespace: namespace,
  484. }
  485. if ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID"); ghIDStr != "" {
  486. ghID, err := strconv.Atoi(ghIDStr)
  487. if err != nil {
  488. return nil, err
  489. }
  490. res.gitInstallationID = uint(ghID)
  491. } else if ghIDStr == "" {
  492. return nil, fmt.Errorf("Git installation ID must be defined, set by PORTER_GIT_INSTALLATION_ID")
  493. }
  494. if prIDStr := os.Getenv("PORTER_PULL_REQUEST_ID"); prIDStr != "" {
  495. prID, err := strconv.Atoi(prIDStr)
  496. if err != nil {
  497. return nil, err
  498. }
  499. res.prID = uint(prID)
  500. } else if prIDStr == "" {
  501. return nil, fmt.Errorf("Pull request ID must be defined, set by PORTER_PULL_REQUEST_ID")
  502. }
  503. res.projectID = config.Project
  504. if res.projectID == 0 {
  505. return nil, fmt.Errorf("project id must be set")
  506. }
  507. res.clusterID = config.Cluster
  508. if res.clusterID == 0 {
  509. return nil, fmt.Errorf("cluster id must be set")
  510. }
  511. if branchName := os.Getenv("PORTER_BRANCH_NAME"); branchName != "" {
  512. res.branch = branchName
  513. } else if branchName == "" {
  514. return nil, fmt.Errorf("Branch name must be defined, set by PORTER_BRANCH_NAME")
  515. }
  516. if actionIDStr := os.Getenv("PORTER_ACTION_ID"); actionIDStr != "" {
  517. actionID, err := strconv.Atoi(actionIDStr)
  518. if err != nil {
  519. return nil, err
  520. }
  521. res.actionID = uint(actionID)
  522. } else if actionIDStr == "" {
  523. return nil, fmt.Errorf("Action Run ID must be defined, set by PORTER_ACTION_ID")
  524. }
  525. return res, nil
  526. }
  527. func (t *DeploymentHook) PreApply() error {
  528. // attempt to read the deployment -- if it doesn't exist, create it
  529. _, err := t.client.GetDeployment(
  530. context.Background(),
  531. t.projectID, t.gitInstallationID, t.clusterID,
  532. &types.GetDeploymentRequest{
  533. Namespace: t.namespace,
  534. },
  535. )
  536. // TODO: case this on the response status code rather than text
  537. if err != nil && strings.Contains(err.Error(), "deployment not found") {
  538. // in this case, create the deployment
  539. _, err = t.client.CreateDeployment(
  540. context.Background(),
  541. t.projectID, t.gitInstallationID, t.clusterID,
  542. &types.CreateDeploymentRequest{
  543. Namespace: t.namespace,
  544. PullRequestID: t.prID,
  545. Branch: t.branch,
  546. ActionID: t.actionID,
  547. },
  548. )
  549. return err
  550. }
  551. return err
  552. }
  553. func (t *DeploymentHook) DataQueries() map[string]interface{} {
  554. res := make(map[string]interface{})
  555. // use the resource group to find all web applications that can have an exposed subdomain
  556. // that we can query for
  557. for _, resource := range t.resourceGroup.Resources {
  558. isWeb := false
  559. if sourceNameInter, exists := resource.Source["name"]; exists {
  560. if sourceName, ok := sourceNameInter.(string); ok {
  561. if sourceName == "web" {
  562. isWeb = true
  563. }
  564. }
  565. }
  566. if isWeb {
  567. res[resource.Name] = fmt.Sprintf("{ .%s.ingress.porter_hosts[0] }", resource.Name)
  568. fmt.Printf("registered data query for %s\n", resource.Name)
  569. }
  570. }
  571. return res
  572. }
  573. func (t *DeploymentHook) PostApply(populatedData map[string]interface{}) error {
  574. subdomains := make([]string, 0)
  575. fmt.Printf("populated data is %v\n", populatedData)
  576. for _, data := range populatedData {
  577. domain, ok := data.(string)
  578. if !ok {
  579. continue
  580. }
  581. if _, err := url.Parse("https://" + domain); err == nil {
  582. subdomains = append(subdomains, "https://"+domain)
  583. }
  584. }
  585. // finalize the deployment
  586. _, err := t.client.FinalizeDeployment(
  587. context.Background(),
  588. t.projectID, t.gitInstallationID, t.clusterID,
  589. &types.FinalizeDeploymentRequest{
  590. Namespace: t.namespace,
  591. Subdomain: strings.Join(subdomains, ","),
  592. },
  593. )
  594. return err
  595. }