2018-06-24 16:40:48 +03:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/fatih/color"
|
|
|
|
"github.com/gin-contrib/cors"
|
2018-07-18 13:52:07 +03:00
|
|
|
"github.com/gin-contrib/static"
|
2018-06-24 16:40:48 +03:00
|
|
|
"github.com/gin-gonic/gin"
|
2018-06-24 16:47:01 +03:00
|
|
|
"github.com/hasura/graphql-engine/cli"
|
2019-09-18 08:36:16 +03:00
|
|
|
"github.com/hasura/graphql-engine/cli/migrate"
|
2018-06-24 16:40:48 +03:00
|
|
|
"github.com/hasura/graphql-engine/cli/migrate/api"
|
2018-06-24 16:47:01 +03:00
|
|
|
"github.com/hasura/graphql-engine/cli/util"
|
2018-06-24 16:40:48 +03:00
|
|
|
"github.com/pkg/errors"
|
2018-07-09 16:47:38 +03:00
|
|
|
"github.com/sirupsen/logrus"
|
2018-06-24 16:40:48 +03:00
|
|
|
"github.com/skratchdot/open-golang/open"
|
|
|
|
"github.com/spf13/cobra"
|
2018-06-24 16:47:01 +03:00
|
|
|
"github.com/spf13/viper"
|
2018-06-24 16:40:48 +03:00
|
|
|
)
|
|
|
|
|
2019-01-28 16:55:28 +03:00
|
|
|
// NewConsoleCmd returns the console command
|
2018-06-24 16:40:48 +03:00
|
|
|
func NewConsoleCmd(ec *cli.ExecutionContext) *cobra.Command {
|
2018-06-24 16:47:01 +03:00
|
|
|
v := viper.New()
|
2018-06-24 16:40:48 +03:00
|
|
|
opts := &consoleOptions{
|
|
|
|
EC: ec,
|
|
|
|
}
|
|
|
|
consoleCmd := &cobra.Command{
|
|
|
|
Use: "console",
|
|
|
|
Short: "Open console to manage database and try out APIs",
|
|
|
|
Long: "Run a web server to serve Hasura Console for GraphQL Engine to manage database and build queries",
|
|
|
|
Example: ` # Start console:
|
|
|
|
hasura console
|
|
|
|
|
|
|
|
# Start console on a different address and ports:
|
2019-12-12 08:16:36 +03:00
|
|
|
hasura console --address 0.0.0.0 --console-port 8080 --api-port 8081
|
|
|
|
|
|
|
|
# Start console without opening the browser automatically
|
|
|
|
hasura console --no-browser
|
|
|
|
|
|
|
|
# Use with admin secret:
|
|
|
|
hasura console --admin-secret "<admin-secret>"
|
|
|
|
|
|
|
|
# Connect to an instance specified by the flag, overrides the one mentioned in config.yaml:
|
|
|
|
hasura console --endpoint "<endpoint>"`,
|
2018-06-24 16:40:48 +03:00
|
|
|
SilenceUsage: true,
|
2018-06-24 16:47:01 +03:00
|
|
|
PreRunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
ec.Viper = v
|
|
|
|
return ec.Validate()
|
|
|
|
},
|
2018-06-24 16:40:48 +03:00
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
2018-06-28 11:36:25 +03:00
|
|
|
return opts.run()
|
2018-06-24 16:40:48 +03:00
|
|
|
},
|
|
|
|
}
|
|
|
|
f := consoleCmd.Flags()
|
|
|
|
|
|
|
|
f.StringVar(&opts.APIPort, "api-port", "9693", "port for serving migrate api")
|
|
|
|
f.StringVar(&opts.ConsolePort, "console-port", "9695", "port for serving console")
|
2019-01-29 19:02:49 +03:00
|
|
|
f.StringVar(&opts.Address, "address", "localhost", "address to serve console and migration API from")
|
2018-06-27 15:04:09 +03:00
|
|
|
f.BoolVar(&opts.DontOpenBrowser, "no-browser", false, "do not automatically open console in browser")
|
2018-07-18 13:52:07 +03:00
|
|
|
f.StringVar(&opts.StaticDir, "static-dir", "", "directory where static assets mentioned in the console html template can be served from")
|
2018-06-24 16:47:01 +03:00
|
|
|
|
|
|
|
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL Engine")
|
2019-02-14 12:37:47 +03:00
|
|
|
f.String("admin-secret", "", "admin secret for Hasura GraphQL Engine")
|
2018-06-24 16:47:01 +03:00
|
|
|
f.String("access-key", "", "access key for Hasura GraphQL Engine")
|
2019-02-14 12:37:47 +03:00
|
|
|
f.MarkDeprecated("access-key", "use --admin-secret instead")
|
2018-06-24 16:47:01 +03:00
|
|
|
|
|
|
|
// need to create a new viper because https://github.com/spf13/viper/issues/233
|
|
|
|
v.BindPFlag("endpoint", f.Lookup("endpoint"))
|
2019-02-14 12:37:47 +03:00
|
|
|
v.BindPFlag("admin_secret", f.Lookup("admin-secret"))
|
2018-06-24 16:47:01 +03:00
|
|
|
v.BindPFlag("access_key", f.Lookup("access-key"))
|
2018-06-24 16:40:48 +03:00
|
|
|
return consoleCmd
|
|
|
|
}
|
|
|
|
|
|
|
|
type consoleOptions struct {
|
|
|
|
EC *cli.ExecutionContext
|
|
|
|
|
|
|
|
APIPort string
|
|
|
|
ConsolePort string
|
|
|
|
Address string
|
2018-06-27 15:04:09 +03:00
|
|
|
|
|
|
|
DontOpenBrowser bool
|
|
|
|
|
|
|
|
WG *sync.WaitGroup
|
2018-07-18 13:52:07 +03:00
|
|
|
|
|
|
|
StaticDir string
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
2018-06-28 11:36:25 +03:00
|
|
|
func (o *consoleOptions) run() error {
|
2018-06-24 16:40:48 +03:00
|
|
|
log := o.EC.Logger
|
|
|
|
// Switch to "release" mode in production.
|
|
|
|
gin.SetMode(gin.ReleaseMode)
|
|
|
|
|
|
|
|
// An Engine instance with the Logger and Recovery middleware already attached.
|
2019-09-18 08:36:16 +03:00
|
|
|
g := gin.New()
|
2018-06-24 16:40:48 +03:00
|
|
|
|
2019-09-18 08:36:16 +03:00
|
|
|
g.Use(allowCors())
|
2018-06-24 16:40:48 +03:00
|
|
|
|
2018-07-06 08:06:27 +03:00
|
|
|
if o.EC.Version == nil {
|
|
|
|
return errors.New("cannot validate version, object is nil")
|
|
|
|
}
|
2019-02-14 12:37:47 +03:00
|
|
|
|
2019-03-20 08:10:06 +03:00
|
|
|
metadataPath, err := o.EC.GetMetadataFilePath("yaml")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-09-18 08:36:16 +03:00
|
|
|
t, err := newMigrate(o.EC.MigrationDir, o.EC.ServerConfig.ParsedEndpoint, o.EC.ServerConfig.AdminSecret, o.EC.Logger, o.EC.Version, false)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// My Router struct
|
|
|
|
r := &cRouter{
|
|
|
|
g,
|
|
|
|
t,
|
|
|
|
}
|
|
|
|
|
|
|
|
r.setRoutes(o.EC.MigrationDir, metadataPath, o.EC.Logger)
|
2019-02-14 12:37:47 +03:00
|
|
|
|
2018-07-04 15:43:52 +03:00
|
|
|
consoleTemplateVersion := o.EC.Version.GetConsoleTemplateVersion()
|
|
|
|
consoleAssetsVersion := o.EC.Version.GetConsoleAssetsVersion()
|
|
|
|
|
|
|
|
o.EC.Logger.Debugf("rendering console template [%s] with assets [%s]", consoleTemplateVersion, consoleAssetsVersion)
|
2018-06-24 16:40:48 +03:00
|
|
|
|
2019-02-14 12:37:47 +03:00
|
|
|
adminSecretHeader := getAdminSecretHeaderName(o.EC.Version)
|
|
|
|
|
2018-07-18 13:52:07 +03:00
|
|
|
consoleRouter, err := serveConsole(consoleTemplateVersion, o.StaticDir, gin.H{
|
2019-01-28 16:55:28 +03:00
|
|
|
"apiHost": "http://" + o.Address,
|
|
|
|
"apiPort": o.APIPort,
|
|
|
|
"cliVersion": o.EC.Version.GetCLIVersion(),
|
2019-07-02 15:44:29 +03:00
|
|
|
"serverVersion": o.EC.Version.GetServerVersion(),
|
2019-02-14 12:37:47 +03:00
|
|
|
"dataApiUrl": o.EC.ServerConfig.ParsedEndpoint.String(),
|
2019-01-28 16:55:28 +03:00
|
|
|
"dataApiVersion": "",
|
2019-02-14 12:37:47 +03:00
|
|
|
"hasAccessKey": adminSecretHeader == XHasuraAccessKey,
|
|
|
|
"adminSecret": o.EC.ServerConfig.AdminSecret,
|
2019-01-28 16:55:28 +03:00
|
|
|
"assetsVersion": consoleAssetsVersion,
|
|
|
|
"enableTelemetry": o.EC.GlobalConfig.EnableTelemetry,
|
|
|
|
"cliUUID": o.EC.GlobalConfig.UUID,
|
2018-06-24 16:40:48 +03:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "error serving console")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create WaitGroup for running 3 servers
|
|
|
|
wg := &sync.WaitGroup{}
|
2018-06-27 15:04:09 +03:00
|
|
|
o.WG = wg
|
2018-06-24 16:40:48 +03:00
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
2019-09-18 08:36:16 +03:00
|
|
|
err = r.router.Run(o.Address + ":" + o.APIPort)
|
2018-06-24 16:40:48 +03:00
|
|
|
if err != nil {
|
|
|
|
o.EC.Logger.WithError(err).Errorf("error listening on port %s", o.APIPort)
|
|
|
|
}
|
|
|
|
wg.Done()
|
|
|
|
}()
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
err = consoleRouter.Run(o.Address + ":" + o.ConsolePort)
|
|
|
|
if err != nil {
|
|
|
|
o.EC.Logger.WithError(err).Errorf("error listening on port %s", o.ConsolePort)
|
|
|
|
}
|
|
|
|
wg.Done()
|
|
|
|
}()
|
|
|
|
|
2018-07-18 13:52:07 +03:00
|
|
|
consoleURL := fmt.Sprintf("http://%s:%s/", o.Address, o.ConsolePort)
|
2018-06-24 16:40:48 +03:00
|
|
|
|
2018-06-27 15:04:09 +03:00
|
|
|
if !o.DontOpenBrowser {
|
|
|
|
o.EC.Spin(color.CyanString("Opening console using default browser..."))
|
|
|
|
defer o.EC.Spinner.Stop()
|
2018-06-24 16:40:48 +03:00
|
|
|
|
2018-06-27 15:04:09 +03:00
|
|
|
err = open.Run(consoleURL)
|
|
|
|
if err != nil {
|
|
|
|
o.EC.Logger.WithError(err).Warn("Error opening browser, try to open the url manually?")
|
|
|
|
}
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
o.EC.Spinner.Stop()
|
|
|
|
log.Infof("console running at: %s", consoleURL)
|
|
|
|
|
2019-01-28 16:55:28 +03:00
|
|
|
o.EC.Telemetry.Beam()
|
|
|
|
|
2018-06-24 16:40:48 +03:00
|
|
|
wg.Wait()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-07-18 13:52:07 +03:00
|
|
|
type cRouter struct {
|
2019-09-18 08:36:16 +03:00
|
|
|
router *gin.Engine
|
|
|
|
migrate *migrate.Migrate
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
2019-09-18 08:36:16 +03:00
|
|
|
func (r *cRouter) setRoutes(migrationDir, metadataFile string, logger *logrus.Logger) {
|
|
|
|
apis := r.router.Group("/apis")
|
2018-06-24 16:40:48 +03:00
|
|
|
{
|
2018-07-09 16:47:38 +03:00
|
|
|
apis.Use(setLogger(logger))
|
|
|
|
apis.Use(setFilePath(migrationDir))
|
2019-09-18 08:36:16 +03:00
|
|
|
apis.Use(setMigrate(r.migrate))
|
2018-06-24 16:40:48 +03:00
|
|
|
// Migrate api endpoints and middleware
|
|
|
|
migrateAPIs := apis.Group("/migrate")
|
|
|
|
{
|
|
|
|
settingsAPIs := migrateAPIs.Group("/settings")
|
|
|
|
{
|
|
|
|
settingsAPIs.Any("", api.SettingsAPI)
|
|
|
|
}
|
cli(migrations): new folder structure and squash (#3072)
### Description
This PR introduces three new features:
- Support for a new migrations folder structure.
- Add `squash` command in preview.
- ~List of migrations on the Console and ability to squash them from console.~
#### New migrations folder structure
Starting with this commit, Hasura CLI supports a new directory structure for migrations folder and defaults to that for all new migrations created.
Each migration will get a new directory with the name format `timestamp_name` and inside the directory, there will be four files:
```bash
└── migrations
├── 1572237730898_squashed
│ ├── up.sql
│ ├── up.yaml
│ ├── down.yaml
│ └── down.sql
```
Existing files old migration format `timestamp_name.up|down.yaml|sql` will continue to work alongside new migration files.
#### Squash command
Lots of users have expressed their interest in squashing migrations (see #2724 and #2254) and some even built [their own tools](https://github.com/domasx2/hasura-squasher) to do squash. In this PR, we take a systematic approach to squash migrations.
A new command called `migrate squash` is introduced. Note that this command is in **PREVIEW** and the correctness of squashed migration is not guaranteed (especially for down migrations). From our tests, **it works for most use cases**, but we have found some issues with squashing all the down migrations, partly because the console doesn't generate down migrations for all actions.
Hence, until we add an extensive test suite for squashing, we'll keep the command in preview. We recommend you to confirm the correctness yourself by diffing the SQL and Metadata before and after applying the squashed migrations (we're also thinking about embedding some checks into the command itself).
```bash
$ hasura migrate squash --help
(PREVIEW) Squash multiple migrations leading upto the latest one into a single migration file
Usage:
hasura migrate squash [flags]
Examples:
# NOTE: This command is in PREVIEW, correctness is not guaranteed and the usage may change.
# squash all migrations from version 1572238297262 to the latest one:
hasura migrate squash --from 1572238297262
Flags:
--from uint start squashing form this version
--name string name for the new squashed migration (default "squashed")
--delete-source delete the source files after squashing without any confirmation
```
### Affected components
<!-- Remove non-affected components from the list -->
- CLI
### Related Issues
<!-- Please make sure you have an issue associated with this Pull Request -->
<!-- And then add `(close #<issue-no>)` to the pull request title -->
<!-- Add the issue number below (e.g. #234) -->
Close #2724, Close #2254,
### Solution and Design
<!-- How is this issue solved/fixed? What is the design? -->
<!-- It's better if we elaborate -->
For the squash command, a state machine is implemented to track changes to Hasura metadata. After applying each action on the metadata state, a list of incremental changes is created.
### Steps to test and verify
1. Open console via cli and create some migrations.
2. Run `hasura migrate squash --from <version>`
### Limitations, known bugs & workarounds
<!-- Limitations of the PR, known bugs and suggested workarounds -->
<!-- Feel free to delete these comment lines -->
- The `squash` command is in preview
- Support for squashing from the console is WIP
- Support for squashing migrations that are not committed yet is planned.
- Un-tracking or dropping a table will cause inconsistent squashed down migration since console doesn't generate correct down migration.
- If cascade setting is set to `true` on any of the metadata action, generated migration may be wrong
2019-10-31 05:21:15 +03:00
|
|
|
squashAPIs := migrateAPIs.Group("/squash")
|
|
|
|
{
|
|
|
|
squashAPIs.POST("/create", api.SquashCreateAPI)
|
|
|
|
squashAPIs.POST("/delete", api.SquashDeleteAPI)
|
|
|
|
}
|
2018-06-24 16:40:48 +03:00
|
|
|
migrateAPIs.Any("", api.MigrateAPI)
|
|
|
|
}
|
|
|
|
// Migrate api endpoints and middleware
|
|
|
|
metadataAPIs := apis.Group("/metadata")
|
|
|
|
{
|
2018-07-12 15:52:25 +03:00
|
|
|
metadataAPIs.Use(setMetadataFile(metadataFile))
|
2018-06-24 16:40:48 +03:00
|
|
|
metadataAPIs.Any("", api.MetadataAPI)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-18 08:36:16 +03:00
|
|
|
func setMigrate(t *migrate.Migrate) gin.HandlerFunc {
|
2018-06-24 16:40:48 +03:00
|
|
|
return func(c *gin.Context) {
|
2019-09-18 08:36:16 +03:00
|
|
|
c.Set("migrate", t)
|
2018-06-24 16:40:48 +03:00
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func setFilePath(dir string) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
2018-07-09 16:47:38 +03:00
|
|
|
host := getFilePath(dir)
|
|
|
|
c.Set("filedir", host)
|
|
|
|
c.Next()
|
2018-07-12 15:52:25 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func setMetadataFile(file string) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
c.Set("metadataFile", file)
|
|
|
|
c.Next()
|
2018-07-09 16:47:38 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func setLogger(logger *logrus.Logger) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
c.Set("logger", logger)
|
2018-06-24 16:40:48 +03:00
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func allowCors() gin.HandlerFunc {
|
|
|
|
config := cors.DefaultConfig()
|
|
|
|
config.AddAllowHeaders("X-Hasura-User-Id")
|
2019-02-14 12:37:47 +03:00
|
|
|
config.AddAllowHeaders(XHasuraAccessKey)
|
|
|
|
config.AddAllowHeaders(XHasuraAdminSecret)
|
2018-06-24 16:40:48 +03:00
|
|
|
config.AddAllowHeaders("X-Hasura-Role")
|
|
|
|
config.AddAllowHeaders("X-Hasura-Allowed-Roles")
|
|
|
|
config.AddAllowMethods("DELETE")
|
|
|
|
config.AllowAllOrigins = true
|
|
|
|
config.AllowCredentials = false
|
|
|
|
return cors.New(config)
|
|
|
|
}
|
|
|
|
|
2018-07-18 13:52:07 +03:00
|
|
|
func serveConsole(assetsVersion, staticDir string, opts gin.H) (*gin.Engine, error) {
|
2018-06-24 16:40:48 +03:00
|
|
|
// An Engine instance with the Logger and Recovery middleware already attached.
|
|
|
|
r := gin.New()
|
|
|
|
|
2018-07-06 08:06:27 +03:00
|
|
|
// Template console.html
|
2018-07-03 20:10:13 +03:00
|
|
|
templateRender, err := util.LoadTemplates("assets/"+assetsVersion+"/", "console.html")
|
2018-06-24 16:40:48 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "cannot fetch template")
|
|
|
|
}
|
|
|
|
r.HTMLRender = templateRender
|
|
|
|
|
2018-07-18 13:52:07 +03:00
|
|
|
if staticDir != "" {
|
|
|
|
r.Use(static.Serve("/static", static.LocalFile(staticDir, false)))
|
|
|
|
opts["cliStaticDir"] = staticDir
|
|
|
|
}
|
|
|
|
r.GET("/*action", func(c *gin.Context) {
|
2018-06-24 16:40:48 +03:00
|
|
|
c.HTML(http.StatusOK, "console.html", &opts)
|
|
|
|
})
|
|
|
|
|
|
|
|
return r, nil
|
|
|
|
}
|