Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: new embedded pg instance api for owner (#2373)
boojack4697ba66eb2a
diff --git a/resources/postgres/postgres.go b/resources/postgres/postgres.goindex 356ff82b00..ed806db9c9 100644--- a/resources/postgres/postgres.go+++ b/resources/postgres/postgres.go@@ -24,72 +24,10 @@ import (type Instance struct {// BaseDir is the directory where the postgres binary is installed.BaseDir string- // dataDir is the directory where the postgres data is stored.- dataDir string- // port is the port number of the postgres instance.- port int-}--// Port returns the port number of the postgres instance.-func (i Instance) Port() int { return i.port }--// Start starts a postgres instance on given port, outputs to stdout and stderr.-//-// If port is 0, then it will choose a random unused port.-//-// If waitSec > 0, watis at most `waitSec` seconds for the postgres instance to start.-// Otherwise, returns immediately.-func (i *Instance) Start(port int, stdout, stderr io.Writer) (err error) {- pgbin := filepath.Join(i.BaseDir, "bin", "pg_ctl")-- i.port = port-- // See -p -k -h option definitions in the link below.- // https://www.postgresql.org/docs/current/app-postgres.html- p := exec.Command(pgbin, "start", "-w",- "-D", i.dataDir,- "-o", fmt.Sprintf(`-p %d -k %s -h ""`, i.port, common.GetPostgresSocketDir()))-- p.Stdout = stdout- p.Stderr = stderr- uid, _, sameUser, err := shouldSwitchUser()- if err != nil {- return err- }- if !sameUser {- p.SysProcAttr = &syscall.SysProcAttr{- Setpgid: true,- Credential: &syscall.Credential{Uid: uint32(uid)},- }- }-- if err := p.Run(); err != nil {- return errors.Wrapf(err, "failed to start postgres %q", p.String())- }-- return nil-}--// Stop stops a postgres instance, outputs to stdout and stderr.-func (i *Instance) Stop(stdout, stderr io.Writer) error {- pgbin := filepath.Join(i.BaseDir, "bin", "pg_ctl")- p := exec.Command(pgbin, "stop", "-w",- "-D", i.dataDir)-- p.Stderr = stderr- p.Stdout = stdout- uid, _, sameUser, err := shouldSwitchUser()- if err != nil {- return err- }- if !sameUser {- p.SysProcAttr = &syscall.SysProcAttr{- Setpgid: true,- Credential: &syscall.Credential{Uid: uint32(uid)},- }- }-- return p.Run()+ // DataDir is the directory where the postgres data is stored.+ DataDir string+ // Port is the port number of the postgres instance.+ Port int}// Install returns the postgres binary depending on the OS.@@ -149,19 +87,72 @@ func Install(resourceDir, pgDataDir, pgUser string) (*Instance, error) {// We will initialize Postgres only when pgDataDir is set.if pgDataDir != "" {- if err := initDB(pgBinDir, pgDataDir, pgUser); err != nil {+ if err := InitDB(pgBinDir, pgDataDir, pgUser); err != nil {return nil, err}}return &Instance{BaseDir: pgBinDir,- dataDir: pgDataDir,+ DataDir: pgDataDir,}, nil}-// initDB inits a postgres database if not yet.-func initDB(pgBinDir, pgDataDir, pgUser string) error {+// Start starts a postgres database instance.+// If port is 0, then it will choose a random unused port.+func Start(port int, baseDir string, dataDir string, stdout, stderr io.Writer) (err error) {+ pgbin := filepath.Join(baseDir, "bin", "pg_ctl")++ // See -p -k -h option definitions in the link below.+ // https://www.postgresql.org/docs/current/app-postgres.html+ p := exec.Command(pgbin, "start", "-w",+ "-D", dataDir,+ "-o", fmt.Sprintf(`-p %d -k %s -h ""`, port, common.GetPostgresSocketDir()))++ p.Stdout = stdout+ p.Stderr = stderr+ uid, _, sameUser, err := shouldSwitchUser()+ if err != nil {+ return err+ }+ if !sameUser {+ p.SysProcAttr = &syscall.SysProcAttr{+ Setpgid: true,+ Credential: &syscall.Credential{Uid: uint32(uid)},+ }+ }++ if err := p.Run(); err != nil {+ return errors.Wrapf(err, "failed to start postgres %q", p.String())+ }++ return nil+}++// Stop stops a postgres instance, outputs to stdout and stderr.+func Stop(pgBinDir, pgDataDir string, stdout, stderr io.Writer) error {+ pgbin := filepath.Join(pgBinDir, "bin", "pg_ctl")+ p := exec.Command(pgbin, "stop", "-w",+ "-D", pgDataDir)++ p.Stderr = stderr+ p.Stdout = stdout+ uid, _, sameUser, err := shouldSwitchUser()+ if err != nil {+ return err+ }+ if !sameUser {+ p.SysProcAttr = &syscall.SysProcAttr{+ Setpgid: true,+ Credential: &syscall.Credential{Uid: uint32(uid)},+ }+ }++ return p.Run()+}++// InitDB inits a postgres database if not yet.+func InitDB(pgBinDir, pgDataDir, pgUser string) error {versionPath := filepath.Join(pgDataDir, "PG_VERSION")_, err := os.Stat(versionPath)if err != nil && !os.IsNotExist(err) {@@ -246,21 +237,15 @@ func shouldSwitchUser() (int, int, bool, error) {}// StartForTest starts a postgres instance on localhost given port, outputs to stdout and stderr.-//// If port is 0, then it will choose a random unused port.-//-// If waitSec > 0, watis at most `waitSec` seconds for the postgres instance to start.-// Otherwise, returns immediately.-func (i *Instance) StartForTest(port int, stdout, stderr io.Writer) (err error) {- pgbin := filepath.Join(i.BaseDir, "bin", "pg_ctl")-- i.port = port+func StartForTest(port int, pgBinDir, pgDataDir string, stdout, stderr io.Writer) (err error) {+ pgbin := filepath.Join(pgBinDir, "bin", "pg_ctl")// See -p -k -h option definitions in the link below.// https://www.postgresql.org/docs/current/app-postgres.htmlp := exec.Command(pgbin, "start", "-w",- "-D", i.dataDir,- "-o", fmt.Sprintf(`-p %d -k %s -h 127.0.0.1`, i.port, common.GetPostgresSocketDir()))+ "-D", pgDataDir,+ "-o", fmt.Sprintf(`-p %d -k %s -h 127.0.0.1`, port, common.GetPostgresSocketDir()))p.Stdout = stdoutp.Stderr = stderr@@ -282,13 +267,14 @@ func SetupTestInstance(t *testing.T, port int) (*Instance, func()) {t.Fatal(err)}t.Log("Starting PostgreSQL...")- if err := i.StartForTest(port, os.Stdout, os.Stderr); err != nil {+ if err := StartForTest(port, i.BaseDir, i.DataDir, os.Stdout, os.Stderr); err != nil {t.Fatal(err)}+ i.Port = portstopFn := func() {t.Log("Stopping PostgreSQL...")- if err := i.Stop(os.Stdout, os.Stderr); err != nil {+ if err := Stop(i.BaseDir, i.DataDir, os.Stdout, os.Stderr); err != nil {t.Fatal(err)}}diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex 73b1d4fe04..2d3aee33f2 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -43,6 +43,7 @@ p, OWNER, /instance/{id}/migration, POSTp, OWNER, /instance/{id}/migration/status, GETp, OWNER, /instance/{id}/migration/history, GETp, OWNER, /instance/{id}/migration/history/{historyID}, GET+p, OWNER, /instance/new-embedded-pg, POSTp, OWNER, /database, POSTp, OWNER, /database, GETp, OWNER, /database/{id}, GETdiff --git a/server/database.go b/server/database.goindex c4169a65ac..3c3c89e537 100644--- a/server/database.go+++ b/server/database.go@@ -838,7 +838,7 @@ func (s *Server) getAdminDatabaseDriver(ctx context.Context, instance *api.Instactx,instance.Engine,db.DriverConfig{- PgInstanceDir: s.pgInstanceDir,+ PgInstanceDir: s.pgInstance.BaseDir,ResourceDir: common.GetResourceDir(s.profile.DataDir),BinlogDir: getBinlogAbsDir(s.profile.DataDir, instance.ID),},diff --git a/server/instance.go b/server/instance.goindex b566b0997d..8ca557cd7b 100644--- a/server/instance.go+++ b/server/instance.go@@ -4,6 +4,7 @@ import ("context""fmt""net/http"+ "os""strconv""strings"@@ -16,8 +17,16 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/resources/postgres")+// pgConnectionInfo represents the embedded postgres instance connection info.+type pgConnectionInfo struct {+ Host string `json:"host"`+ Port int `json:"port"`+ Username string `json:"username"`+}+func (s *Server) registerInstanceRoutes(g *echo.Group) {// Besides adding the instance to Bytebase, it will also try to create a "bytebase" db in the newly added instance.g.POST("/instance", func(c echo.Context) error {@@ -469,6 +478,28 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {}return nil})++ // Initial and start an embedded postgres instance and there should be only one currently.+ // Its port and dataDir are fixed values.+ g.POST("/instance/new-embedded-pg", func(c echo.Context) error {+ pgUser := "postgres"+ port := 23333+ dataDir := fmt.Sprintf("%s/%s", s.profile.DataDir, "tmp-pgdata")++ if err := postgres.InitDB(s.pgInstance.BaseDir, dataDir, pgUser); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to init embedded postgres database").SetInternal(err)+ }++ if err := postgres.Start(port, s.pgInstance.BaseDir, dataDir, os.Stderr, os.Stderr); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to start embedded postgres instance").SetInternal(err)+ }++ return c.JSON(http.StatusOK, pgConnectionInfo{+ Host: common.GetPostgresSocketDir(),+ Port: port,+ Username: pgUser,+ })+ })}// instanceCountGuard is a feature guard for instance count.diff --git a/server/server.go b/server/server.goindex 8d08d14056..f93c906515 100644--- a/server/server.go+++ b/server/server.go@@ -56,13 +56,13 @@ type Server struct {LicenseService enterpriseAPI.LicenseServicesubscription enterpriseAPI.Subscription- profile Profile- e *echo.Echo- pgInstanceDir string- metaDB *store.MetadataDB- store *store.Store- startedTs int64- secret string+ profile Profile+ e *echo.Echo+ pgInstance *postgres.Instance+ metaDB *store.MetadataDB+ store *store.Store+ startedTs int64+ secret strings3Client *s3bb.Client@@ -157,7 +157,7 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {if err != nil {return nil, err}- s.pgInstanceDir = pgInstance.BaseDir+ s.pgInstance = pgInstance// New MetadataDB instance.if prof.useEmbedDB() {diff --git a/store/metadb.go b/store/metadb.goindex 7cdf48c2a5..bff16e7f08 100644--- a/store/metadb.go+++ b/store/metadb.go@@ -61,9 +61,10 @@ func (m *MetadataDB) Connect(datastorePort int, readonly bool, version string) (// connectEmbed starts the embed postgres server and returns an instance of store.DB.func (m *MetadataDB) connectEmbed(datastorePort int, pgUser string, readonly bool, demoDataDir, version string, mode common.ReleaseMode) (*DB, error) {- if err := m.pgInstance.Start(datastorePort, os.Stderr, os.Stderr); err != nil {+ if err := postgres.Start(datastorePort, m.pgInstance.BaseDir, m.pgInstance.DataDir, os.Stderr, os.Stderr); err != nil {return nil, err}+ m.pgInstance.Port = datastorePort// mark pgStarted if start successfully, used in Close()m.pgStarted = true@@ -152,7 +153,7 @@ func (m *MetadataDB) Close() error {}log.Info("Trying to shutdown postgresql server...")- if err := m.pgInstance.Stop(os.Stdout, os.Stderr); err != nil {+ if err := postgres.Stop(m.pgInstance.BaseDir, m.pgInstance.DataDir, os.Stdout, os.Stderr); err != nil {return err}m.pgStarted = falsediff --git a/store/pg_engine_test.go b/store/pg_engine_test.goindex 169ca3676e..39c5d15a94 100644--- a/store/pg_engine_test.go+++ b/store/pg_engine_test.go@@ -147,9 +147,9 @@ func TestMigrationCompatibility(t *testing.T) {pgDir := t.TempDir()pgInstance, err := postgres.Install(path.Join(pgDir, "resource"), path.Join(pgDir, "data"), pgUser)require.NoError(t, err)- err = pgInstance.Start(pgPort, os.Stdout, os.Stderr)+ err = postgres.Start(pgPort, pgInstance.BaseDir, pgInstance.DataDir, os.Stderr, os.Stderr)require.NoError(t, err)- defer pgInstance.Stop(os.Stdout, os.Stderr)+ pgInstance.Port = pgPortctx := context.Background()connCfg := dbdriver.ConnectionConfig{@@ -210,6 +210,9 @@ func TestMigrationCompatibility(t *testing.T) {require.NoError(t, err)// The extra one is for the initial schema setup.require.Len(t, histories, len(devMigrations)+1)++ err = postgres.Stop(pgInstance.BaseDir, pgInstance.DataDir, os.Stdout, os.Stderr)+ require.NoError(t, err)}func TestGetCutoffVersion(t *testing.T) {diff --git a/tests/external_pg_test.go b/tests/external_pg_test.goindex dd9152db45..8d13158a6b 100644--- a/tests/external_pg_test.go+++ b/tests/external_pg_test.go@@ -33,10 +33,11 @@ func newFakeExternalPg(tmpDir string, port int) (*fakeExternalPg, error) {return nil, errors.Wrap(err, "cannot install postgres")}- err = pgIns.Start(port, os.Stderr, os.Stderr)+ err = postgres.Start(port, pgIns.BaseDir, pgIns.DataDir, os.Stderr, os.Stderr)if err != nil {return nil, errors.Wrap(err, "cannot start postgres server")}+ pgIns.Port = portreturn &fakeExternalPg{pgIns: pgIns,@@ -46,7 +47,7 @@ func newFakeExternalPg(tmpDir string, port int) (*fakeExternalPg, error) {}func (f *fakeExternalPg) Destroy() error {- return f.pgIns.Stop(os.Stderr, os.Stderr)+ return postgres.Stop(f.pgIns.BaseDir, f.pgIns.DataDir, os.Stderr, os.Stderr)}func TestBootWithExternalPg(t *testing.T) {t.Parallel()