mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
ProcessState is only set by Wait, which ran only at cleanup, so a mini or mount that died at startup was noticed only at the 45s or 90s deadline. Reap each command as it starts and check for its exit while waiting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
260 lines
6.9 KiB
Go
260 lines
6.9 KiB
Go
package postgres_flat
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/aws/aws-sdk-go-v2/aws"
|
|
"github.com/aws/aws-sdk-go-v2/config"
|
|
"github.com/aws/aws-sdk-go-v2/credentials"
|
|
"github.com/aws/aws-sdk-go-v2/service/s3"
|
|
"github.com/seaweedfs/seaweedfs/test/testutil"
|
|
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
|
|
"github.com/seaweedfs/seaweedfs/weed/filer/store_test"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/pgxutil"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
const (
|
|
accessKey = "pgflat_access_key"
|
|
secretKey = "pgflat_secret_key"
|
|
)
|
|
|
|
// cluster is a "weed mini" whose filer keeps its metadata in a postgres_flat
|
|
// store, in a schema of its own.
|
|
type cluster struct {
|
|
t *testing.T
|
|
baseDir string
|
|
weedBinary string
|
|
filerAddr string
|
|
s3Endpoint string
|
|
db *sql.DB
|
|
}
|
|
|
|
func startCluster(t *testing.T) *cluster {
|
|
pg := store_test.NewPostgresTestDatabase(t)
|
|
weedBinary, err := framework.FindOrBuildWeedBinary()
|
|
require.NoError(t, err)
|
|
|
|
c := &cluster{t: t, baseDir: t.TempDir(), weedBinary: weedBinary}
|
|
configDir := filepath.Join(c.baseDir, "config")
|
|
dataDir := filepath.Join(c.baseDir, "data")
|
|
for _, d := range []string{configDir, dataDir} {
|
|
require.NoError(t, os.MkdirAll(d, 0o755))
|
|
}
|
|
require.NoError(t, os.WriteFile(filepath.Join(configDir, "filer.toml"), []byte(filerToml(pg)), 0o644))
|
|
require.NoError(t, os.WriteFile(filepath.Join(configDir, "security.toml"), nil, 0o644))
|
|
s3Config, err := testutil.WriteIAMConfig(configDir, accessKey, secretKey)
|
|
require.NoError(t, err)
|
|
|
|
dsn, _ := pgxutil.BuildDSN(pg)
|
|
c.db, err = sql.Open("pgx", dsn)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() { c.db.Close() })
|
|
|
|
ports := testutil.MustFreeMiniPorts(t, []string{"master", "volume", "filer", "s3", "admin"})
|
|
c.filerAddr = fmt.Sprintf("127.0.0.1:%d", ports[2])
|
|
c.s3Endpoint = fmt.Sprintf("http://127.0.0.1:%d", ports[3])
|
|
args := append([]string{
|
|
"-config_dir=" + configDir,
|
|
"mini",
|
|
"-dir=" + dataDir,
|
|
"-ip=127.0.0.1",
|
|
"-ip.bind=127.0.0.1",
|
|
"-master.port=" + strconv.Itoa(ports[0]),
|
|
"-master.peers=none",
|
|
"-master.volumeSizeLimitMB=32",
|
|
"-master.telemetry=false",
|
|
"-volume.port=" + strconv.Itoa(ports[1]),
|
|
"-volume.max=8",
|
|
"-filer.port=" + strconv.Itoa(ports[2]),
|
|
"-s3.port=" + strconv.Itoa(ports[3]),
|
|
"-s3.config=" + s3Config,
|
|
"-s3.port.iceberg=0",
|
|
"-s3.port.lance=0",
|
|
"-webdav=false",
|
|
"-admin.ui=false",
|
|
}, testutil.MiniAdminArgs(ports[4])...)
|
|
mini := c.start("mini", args...)
|
|
|
|
client := c.s3Client()
|
|
deadline := time.Now().Add(testutil.SeaweedMiniStartupTimeout)
|
|
for {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
_, err := client.ListBuckets(ctx, &s3.ListBucketsInput{})
|
|
cancel()
|
|
if err == nil {
|
|
break
|
|
}
|
|
if exited(mini) || time.Now().After(deadline) {
|
|
t.Fatalf("s3 not ready: %v\n%s", err, c.logTail("mini"))
|
|
}
|
|
time.Sleep(200 * time.Millisecond)
|
|
}
|
|
return c
|
|
}
|
|
|
|
func filerToml(pg pgxutil.DSNOptions) string {
|
|
return fmt.Sprintf(`[postgres_flat]
|
|
enabled = true
|
|
hostname = %q
|
|
port = %d
|
|
username = %q
|
|
password = %q
|
|
database = %q
|
|
schema = %q
|
|
sslmode = "disable"
|
|
`, pg.Hostname, pg.Port, pg.User, pg.Password, pg.Database, pg.Schema)
|
|
}
|
|
|
|
// start runs a weed command until the test ends, logging to <baseDir>/<name>.log.
|
|
// The returned channel is closed once the command exits.
|
|
func (c *cluster) start(name string, args ...string) <-chan struct{} {
|
|
log, err := os.Create(filepath.Join(c.baseDir, name+".log"))
|
|
require.NoError(c.t, err)
|
|
cmd := exec.Command(c.weedBinary, args...)
|
|
cmd.Dir = c.baseDir
|
|
cmd.Stdout = log
|
|
cmd.Stderr = log
|
|
require.NoError(c.t, cmd.Start())
|
|
done := make(chan struct{})
|
|
go func() {
|
|
_ = cmd.Wait()
|
|
close(done)
|
|
}()
|
|
c.t.Cleanup(func() {
|
|
stop(cmd, done)
|
|
log.Close()
|
|
if c.t.Failed() {
|
|
c.t.Logf("%s log tail:\n%s", name, c.logTail(name))
|
|
}
|
|
})
|
|
return done
|
|
}
|
|
|
|
func stop(cmd *exec.Cmd, done <-chan struct{}) {
|
|
if exited(done) {
|
|
return
|
|
}
|
|
_ = cmd.Process.Signal(os.Interrupt)
|
|
select {
|
|
case <-done:
|
|
case <-time.After(10 * time.Second):
|
|
_ = cmd.Process.Kill()
|
|
<-done
|
|
}
|
|
}
|
|
|
|
func exited(done <-chan struct{}) bool {
|
|
select {
|
|
case <-done:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func (c *cluster) logTail(name string) string {
|
|
data, _ := os.ReadFile(filepath.Join(c.baseDir, name+".log"))
|
|
if len(data) > 8192 {
|
|
data = data[len(data)-8192:]
|
|
}
|
|
return string(data)
|
|
}
|
|
|
|
func (c *cluster) s3Client() *s3.Client {
|
|
cfg, err := config.LoadDefaultConfig(context.Background(),
|
|
config.WithRegion("us-east-1"),
|
|
config.WithRetryMaxAttempts(1),
|
|
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
|
|
)
|
|
require.NoError(c.t, err)
|
|
return s3.NewFromConfig(cfg, func(o *s3.Options) {
|
|
o.BaseEndpoint = aws.String(c.s3Endpoint)
|
|
o.UsePathStyle = true
|
|
})
|
|
}
|
|
|
|
// paths returns the path column of a table, in order, under a prefix.
|
|
func (c *cluster) paths(table, prefix string) []string {
|
|
c.t.Helper()
|
|
rows, err := c.db.Query(fmt.Sprintf(`SELECT path FROM "%s" WHERE starts_with(path, $1) ORDER BY path`, table), prefix)
|
|
require.NoError(c.t, err)
|
|
defer rows.Close()
|
|
var paths []string
|
|
for rows.Next() {
|
|
var p string
|
|
require.NoError(c.t, rows.Scan(&p))
|
|
paths = append(paths, p)
|
|
}
|
|
require.NoError(c.t, rows.Err())
|
|
return paths
|
|
}
|
|
|
|
func (c *cluster) tableExists(table string) bool {
|
|
c.t.Helper()
|
|
var exists bool
|
|
require.NoError(c.t, c.db.QueryRow(`SELECT to_regclass(quote_ident($1)) IS NOT NULL`, table).Scan(&exists))
|
|
return exists
|
|
}
|
|
|
|
func (c *cluster) count(query string, args ...interface{}) int {
|
|
c.t.Helper()
|
|
var n int
|
|
require.NoError(c.t, c.db.QueryRow(query, args...).Scan(&n))
|
|
return n
|
|
}
|
|
|
|
// eventually retries check until it passes or the timeout ends; the filer
|
|
// creates and drops bucket tables from its metadata events.
|
|
func eventually(t *testing.T, what string, check func() bool) {
|
|
t.Helper()
|
|
deadline := time.Now().Add(15 * time.Second)
|
|
for !check() {
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("timed out waiting until %s", what)
|
|
}
|
|
time.Sleep(100 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
// filerList pages through a directory listing of the filer's HTTP API.
|
|
func (c *cluster) filerList(dir string, pageSize int) []string {
|
|
c.t.Helper()
|
|
var names []string
|
|
last := ""
|
|
for {
|
|
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s%s/?limit=%d&lastFileName=%s", c.filerAddr, dir, pageSize, url.QueryEscape(last)), nil)
|
|
require.NoError(c.t, err)
|
|
req.Header.Set("Accept", "application/json")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
require.NoError(c.t, err)
|
|
var page struct {
|
|
Entries []struct{ FullPath string }
|
|
LastFileName string
|
|
ShouldDisplayLoadMore bool
|
|
}
|
|
err = json.NewDecoder(resp.Body).Decode(&page)
|
|
resp.Body.Close()
|
|
require.NoError(c.t, err)
|
|
for _, e := range page.Entries {
|
|
names = append(names, e.FullPath[strings.LastIndex(e.FullPath, "/")+1:])
|
|
}
|
|
if !page.ShouldDisplayLoadMore {
|
|
return names
|
|
}
|
|
last = page.LastFileName
|
|
}
|
|
}
|