Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

test: add TestBootWithExternalPg for external postgres (#1238)

h3n4l52914d4950d4
diff --git a/bin/server/cmd/profile_dev.go b/bin/server/cmd/profile_dev.go
index a9b51fb6c6..1f4ea0995a 100644
--- a/bin/server/cmd/profile_dev.go
+++ b/bin/server/cmd/profile_dev.go
@@ -49,3 +49,18 @@ func GetTestProfile(dataDir string, port int) server.Profile {
BackupRunnerInterval: 10 * time.Second,
}
}
+
+// GetTestProfileWithExternalPg will return a profile for testing with external Postgres.
+// We require port as an argument of GetTestProfile so that test can run in parallel in different ports,
+// pgURL for connect to Postgres.
+func GetTestProfileWithExternalPg(port int, pgUser string, pgURL string) server.Profile {
+ return server.Profile{
+ Mode: common.ReleaseModeDev,
+ BackendHost: flags.host,
+ BackendPort: port,
+ PgUser: pgUser,
+ DemoDataDir: fmt.Sprintf("demo/%s", common.ReleaseModeDev),
+ BackupRunnerInterval: 10 * time.Second,
+ PgURL: pgURL,
+ }
+}
diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.go
index 5a26ad9c8c..709b94fe97 100644
--- a/plugin/db/pg/pg.go
+++ b/plugin/db/pg/pg.go
@@ -160,6 +160,7 @@ func guessDSN(username, password, hostname, port, database, sslCA, sslCert, sslK
}
return dsn, nil
}
+
if database != "" {
return "", fmt.Errorf("cannot connecting %q, make sure the connection info is correct and the database exists", database)
}
diff --git a/store/metadb.go b/store/metadb.go
index e8e604d00a..044f32dd6d 100644
--- a/store/metadb.go
+++ b/store/metadb.go
@@ -101,6 +101,8 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)
return nil, err
}
+ q := u.Query()
+
m.l.Info("Establishing external PostgreSQL connection...", zap.String("pgURL", u.Redacted()))
if u.Scheme != "postgresql" {
@@ -123,7 +125,23 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)
if host, port, err := net.SplitHostPort(u.Host); err != nil {
connCfg.Host = u.Host
} else {
+ // There is a hack. PostgreSQL document(https://www.postgresql.org/docs/14/libpq-connect.html)
+ // specifies that a Unix-domain socket connection is chosen if the host part is either empty or **looks like an absolute path name**.
+ // But url.Parse() does not meet this standard, for example:
+ // url.Parse("postgresql://bbexternal@/tmp:3456/postgres"), it will consider `tmp:3456/postgres` as `path`,
+ // and we use path as dbasename(same as PostgreSQL document) so that we get a wrong dbname.
+ // So we put the socket path in the `host` key in the query,
+ // note that in order to comply with the Postgresql document we are not using the `socket` key with obvious semantics.
+ // To give a correct example: postgresql://bbexternal@:3456/postgres?host=/tmp
+ hostInQuery := q.Get("host")
+ if hostInQuery != "" && host != "" {
+ // In this case, it is impossible to decide whether to use socket or tcp.
+ return nil, fmt.Errorf("please only using socket or host instead of both")
+ }
connCfg.Host = host
+ if hostInQuery != "" {
+ connCfg.Host = hostInQuery
+ }
connCfg.Port = port
}
@@ -132,7 +150,6 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)
}
connCfg.Database = u.Path[1:]
- q := u.Query()
connCfg.TLSConfig = dbdriver.TLSConfig{
SslCA: q.Get("sslrootcert"),
SslKey: q.Get("sslkey"),
diff --git a/tests/external_pg_test.go b/tests/external_pg_test.go
new file mode 100644
index 0000000000..67ddbb4d11
--- /dev/null
+++ b/tests/external_pg_test.go
@@ -0,0 +1,68 @@
+package tests
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path"
+ "testing"
+
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/resources/postgres"
+ "github.com/stretchr/testify/require"
+)
+
+type fakeExternalPg struct {
+ pgIns *postgres.Instance
+ pgURL string
+ pgUser string
+}
+
+// newFakeExternalPg will install postgres in tmpDir and listen on Unix domain socket with port
+func newFakeExternalPg(tmpDir string, port int) (*fakeExternalPg, error) {
+ resourceDir := path.Join(tmpDir, "resources")
+ dataDir := path.Join(tmpDir, "pgdata")
+ pgUser := "bbexternal"
+ pgIns, err := postgres.Install(resourceDir, dataDir, pgUser)
+ if err != nil {
+ return nil, fmt.Errorf("cannot install postgres, error: %w", err)
+ }
+
+ err = pgIns.Start(port, os.Stderr, os.Stderr)
+ if err != nil {
+ return nil, fmt.Errorf("cannot start postgres server, error: %w", err)
+ }
+
+ return &fakeExternalPg{
+ pgIns: pgIns,
+ pgURL: fmt.Sprintf("postgresql://%s@:%d/%s?host=%s", pgUser, port, "postgres", common.GetPostgresSocketDir()),
+ pgUser: pgUser,
+ }, nil
+}
+
+func (f *fakeExternalPg) Destroy() error {
+ return f.pgIns.Stop(os.Stderr, os.Stderr)
+}
+func TestBootWithExternalPg(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+
+ pgTmpDir := t.TempDir()
+
+ port := getTestPort(t.Name())
+ serverPort := port + 1
+
+ externalPg, err := newFakeExternalPg(pgTmpDir, port)
+ require.NoError(t, err)
+ defer func() {
+ if err = externalPg.Destroy(); err != nil {
+ fmt.Printf("cannot destroy pginstance, error: %s", err.Error())
+ t.FailNow()
+ }
+ }()
+
+ ctl := &controller{}
+ err = ctl.StartServerWithExternalPg(ctx, serverPort, externalPg.pgUser, externalPg.pgURL)
+ require.NoError(t, err)
+ defer ctl.Close(ctx)
+}
diff --git a/tests/tests.go b/tests/tests.go
index 8969fa58ed..b11cf476cb 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -130,11 +130,32 @@ func getTestPort(testName string) int {
return 1258
case "TestTenantVCSDatabaseNameTemplate":
return 1261
+ case "TestBootWithExternalPg":
+ return 1264
+ case "NEXT": // TestBootWithExternalPg need 4 ports for test, modify here for your test.
+ return 1268
}
panic(fmt.Sprintf("test %q doesn't have assigned port, please set it in getTestPort()", testName))
}
-// StartServer starts the main server.
+// StartServerWithExternalPg starts the main server with external Postgres.
+func (ctl *controller) StartServerWithExternalPg(ctx context.Context, port int, pgUser, pgURL string) error {
+ logger, lvl, err := cmd.GetLogger()
+ if err != nil {
+ return fmt.Errorf("failed to get logger, error: %w", err)
+ }
+ defer logger.Sync()
+
+ profile := cmd.GetTestProfileWithExternalPg(port, pgUser, pgURL)
+ ctl.server, err = server.NewServer(ctx, profile, logger, lvl)
+ if err != nil {
+ return err
+ }
+
+ return ctl.start(ctx, port)
+}
+
+// StartServer starts the main server with embed Postgres.
func (ctl *controller) StartServer(ctx context.Context, dataDir string, port int) error {
// start main server.
logger, lvl, err := cmd.GetLogger()
@@ -149,6 +170,11 @@ func (ctl *controller) StartServer(ctx context.Context, dataDir string, port int
return err
}
+ return ctl.start(ctx, port)
+}
+
+// start only called by StartServer() and StartServerWithExternalPg
+func (ctl *controller) start(ctx context.Context, port int) error {
ctl.rootURL = fmt.Sprintf("http://localhost:%d", port)
ctl.apiURL = fmt.Sprintf("http://localhost:%d/api", port)
@@ -240,37 +266,46 @@ func waitForGitLabStart(g *fake.GitLab, errChan <-chan error) error {
}
func (ctl *controller) waitForHealthz() error {
- timer := time.NewTimer(1 * time.Second)
+ begin := time.Now()
+ ticker := time.NewTicker(100 * time.Microsecond)
+ timer := time.NewTimer(5 * time.Second)
+ defer ticker.Stop()
defer timer.Stop()
-
- healthzURL := "/healthz"
-
for {
select {
- case <-timer.C:
- return nil
- default:
+ case <-ticker.C:
+ healthzURL := "/healthz"
gURL := fmt.Sprintf("%s%s", ctl.rootURL, healthzURL)
req, err := http.NewRequest(http.MethodGet, gURL, nil)
if err != nil {
- return fmt.Errorf("fail to create a new GET request(%q), error: %w", gURL, err)
+ fmt.Printf("fail to create a new GET request(%q), error: %s", gURL, err.Error())
+ continue
+
}
resp, err := ctl.client.Do(req)
-
if err != nil {
- return fmt.Errorf("fail to send a GET request(%q), error: %w", gURL, err)
+ fmt.Printf("fail to send a GET request(%q), error: %s", gURL, err.Error())
+ continue
}
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
- return fmt.Errorf("failed to read http response body, error: %w", err)
+ fmt.Printf("failed to read http response body, error: %s", err.Error())
}
- return fmt.Errorf("http response error code %v body %q", resp.StatusCode, string(body))
+ fmt.Printf("http response error code %v body %q", resp.StatusCode, string(body))
+ continue
}
+
+ return nil
+
+ case end := <-timer.C:
+ return fmt.Errorf("cannot wait for healthz in duration: %v", end.Sub(begin).Seconds())
+
}
}
+
}
func (ctl *controller) Close(ctx context.Context) error {