s3tables: keep files a deleted table or view did not write (#12953)

* s3tables: let DirHoldsFiles count only files older than a cutoff

A non-zero cutoff skips files created at or after it, and Iceberg metadata
files directly under the walked directory's metadata/ folder, which a create
stages before its record exists. Existing callers pass the zero time and
keep counting every file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: keep files a deleted table or view did not write

DeleteTable purged the table's directory (or its decoupled data location)
recursively, and DeleteView purged the view's directory, so files that
were already there when the record was created, or that were written under
a view, went with it. Those files now stay: the record's attributes are
cleared and the directory is left as a leftover. A table still purges the
files it wrote after its create, and its staged metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: skip the drop purge of a location holding older files

DropTable and DropView purge the dropped entry's location after the
catalog delete. A location that holds files older than the table, or any
file other than metadata for a view, is left alone, matching DeleteTable
and DeleteView.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: count a file from the record's own second as older

File creation times have second granularity, so an upload made in the
same second as the table's create compared equal and was purged. An
equal second now counts as older, and the view cutoff no longer needs the
extra second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: count S3 objects stored on directories in DirHoldsFiles

A trailing-slash key, or a file promoted to a directory by a child write,
is an S3 object on a directory entry. The walk only counted plain files,
so a delete purged such objects, including one on the purged path itself.
They now count like files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: keep every non-metadata file under a deleted view

A view writes nothing but its metadata files, so a file under it counts
whatever its creation time, including one stamped ahead of this clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: count a file from the record's own second as the record's

File times are whole seconds, and a writer's first file (an insert right
after a create, or a CTAS writing in the second it staged) often shares
the record's second. Counting it as older kept the table's own files on
drop, so a re-create at the location found it non-empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: date a staged create's table from its stage

The engine writes a staged create's first files before the commit
registers the table, so they predate its record and a drop kept them.
The commit now passes the time the stage marker recorded, in process
only, and the table's CreatedAt starts there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: say a view name holds plain files instead of a table

A view deleted over files it did not write leaves its directory without
a catalog record. CreateView reported that directory as a table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: keep a view location's metadata files older than the view

A view writes its metadata only after its record, so a metadata file from
an earlier second at the location is not the view's and keeps the
directory on a drop, like any other file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: test that a view drop keeps older metadata at its location

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: date both view drop test files from one record time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: drop only the table or view record the lookup read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: test a drop whose record is replaced after the lookup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: check the location claim again after the drop scan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: test a location claimed while the drop scans it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-11-24 14:06:40 -08:00
1 parent 5354acbe1b
commit 763c3d1bdf
14 files changed
+608 -49

No files matched your search

+6 -1
View File
@@ -116,6 +116,7 @@ type createOnCommitInput struct {
baseMetadataVer int
updates table.Updates
statisticsUpdates []statisticsUpdate
stagedAt time.Time
}
func isS3TablesConflict(err error) bool {
@@ -272,9 +273,13 @@ func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommi
MetadataLocation: newMetadataLocation,
}
var createResp s3tables.CreateTableResponse
createCtx := ctx
if !input.stagedAt.IsZero() {
createCtx = s3tables.WithTableStagedAt(ctx, input.stagedAt)
}
createErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
mgrClient := s3tables.NewManagerClient(client)
return s.tablesManager.Execute(ctx, mgrClient, "CreateTable", createReq, &createResp, input.identityName)
return s.tablesManager.Execute(createCtx, mgrClient, "CreateTable", createReq, &createResp, input.identityName)
})
tableCreatedConcurrently := &icebergRequestError{
status: http.StatusConflict,
+6
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"path"
"strings"
"time"
"github.com/apache/iceberg-go/table"
"github.com/google/uuid"
@@ -217,6 +218,10 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
repairManifests(location)
var stagedAt time.Time
if latestMarker != nil {
stagedAt, _ = time.Parse(time.RFC3339Nano, latestMarker.CreatedAt)
}
result, reqErr := s.finalizeCreateOnCommit(r.Context(), createOnCommitInput{
bucketARN: bucketARN,
markerBucket: bucketName,
@@ -230,6 +235,7 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) {
baseMetadataVer: baseMetadataVersion,
updates: req.Updates,
statisticsUpdates: statisticsUpdates,
stagedAt: stagedAt,
})
if reqErr != nil {
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
+42 -10
View File
@@ -11,6 +11,7 @@ import (
"path"
"strconv"
"strings"
"time"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/table"
@@ -350,7 +351,7 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(metadataPath, tablePath) {
// The name went to another table before this request wrote a
// record, so nothing names the directory the server picked.
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), metadataBucket, metadataPath); cleanupErr != nil {
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), metadataBucket, metadataPath, nil); cleanupErr != nil {
glog.V(1).Infof("Iceberg: CreateTable cleanup %s: %v", metadataPath, cleanupErr)
}
}
@@ -813,7 +814,8 @@ func (s *Server) handleDropTable(w http.ResponseWriter, r *http.Request) {
// delete, so we can purge data files afterwards. The catalog is the
// authoritative owner of this mapping — if the table is not registered,
// there is nothing to clean up and DeleteTable will return NoSuchTable.
var storedMetadataLocation string
var storedMetadataLocation, storedVersionToken string
var storedCreatedAt time.Time
lookupReq := &s3tables.GetTableRequest{
TableBucketARN: bucketARN,
Namespace: namespace,
@@ -826,12 +828,15 @@ func (s *Server) handleDropTable(w http.ResponseWriter, r *http.Request) {
})
if lookupErr == nil {
storedMetadataLocation = lookupResp.MetadataLocation
storedCreatedAt = lookupResp.CreatedAt
storedVersionToken = lookupResp.VersionToken
}
deleteReq := &s3tables.DeleteTableRequest{
TableBucketARN: bucketARN,
Namespace: namespace,
Name: tableName,
VersionToken: storedVersionToken,
}
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
@@ -857,7 +862,13 @@ func (s *Server) handleDropTable(w http.ResponseWriter, r *http.Request) {
if storedMetadataLocation != "" {
if tableLoc := tableLocationFromMetadataLocation(storedMetadataLocation); tableLoc != "" {
if dataBucket, dataPath, parseErr := parseS3Location(tableLoc); parseErr == nil {
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), dataBucket, dataPath); cleanupErr != nil {
var holdsFiles func(filer_pb.SeaweedFilerClient, string) (bool, error)
if !storedCreatedAt.IsZero() {
holdsFiles = func(client filer_pb.SeaweedFilerClient, dir string) (bool, error) {
return s3tables.DirHoldsFiles(r.Context(), client, dir, storedCreatedAt)
}
}
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), dataBucket, dataPath, holdsFiles); cleanupErr != nil {
glog.V(1).Infof("Iceberg: failed to purge dropped table location s3://%s/%s: %v", dataBucket, dataPath, cleanupErr)
}
}
@@ -950,13 +961,14 @@ func isNoSuchTableError(err error) bool {
// empty location (e.g. Trino CTAS) can proceed after a DROP. Callers must
// have confirmed via the catalog that no table is registered at this name —
// live tables must never be touched by this helper. Missing paths are not
// an error.
// an error. A location for which a non-nil holdsFiles reports files the
// dropped entry did not write is left alone.
//
// The tablePath is validated to contain only safe, relative segments before
// being joined with the bucket prefix, so a maliciously crafted location
// (e.g. containing "..") cannot escape the bucket subtree and delete data
// outside of it.
func (s *Server) cleanupStaleTableLocation(ctx context.Context, bucketName, tablePath string) error {
func (s *Server) cleanupStaleTableLocation(ctx context.Context, bucketName, tablePath string, holdsFiles func(filer_pb.SeaweedFilerClient, string) (bool, error)) error {
tablePath = strings.Trim(tablePath, "/")
if bucketName == "" || tablePath == "" {
return nil
@@ -975,14 +987,34 @@ func (s *Server) cleanupStaleTableLocation(ctx context.Context, bucketName, tabl
return fmt.Errorf("cleanupStaleTableLocation: refusing unsafe table path %q", tablePath)
}
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
roots, err := s3tables.CatalogRecordRoots(ctx, client, bucketName)
if err != nil {
checkUnclaimed := func() error {
roots, err := s3tables.CatalogRecordRoots(ctx, client, bucketName)
if err != nil {
return err
}
if s3tables.RootClaimed(roots, "", path.Join(parentDir, name)) {
return s3tables.ErrLocationInUse
}
return nil
}
if err := checkUnclaimed(); err != nil {
return err
}
if s3tables.RootClaimed(roots, "", path.Join(parentDir, name)) {
return s3tables.ErrLocationInUse
if holdsFiles != nil {
holds, err := holdsFiles(client, path.Join(parentDir, name))
if err != nil {
return err
}
if holds {
return fmt.Errorf("keeping %s: it holds files the dropped entry did not write", path.Join(parentDir, name))
}
// The scan takes time in proportion to the tree; a record that
// claimed the location meanwhile keeps it.
if err := checkUnclaimed(); err != nil {
return err
}
}
err = filer_pb.DoRemove(ctx, client, parentDir, name, true, true, true, false, nil)
err := filer_pb.DoRemove(ctx, client, parentDir, name, true, true, true, false, nil)
if err == nil || errors.Is(err, filer_pb.ErrNotFound) {
return nil
}
+13 -5
View File
@@ -8,6 +8,7 @@ import (
"os"
"path"
"strings"
"time"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/view"
@@ -224,7 +225,7 @@ func (s *Server) handleCreateView(w http.ResponseWriter, r *http.Request) {
if err := s.saveMetadataFile(r.Context(), metadataBucket, metadataPath, metadataFileName, metadataBytes, false); err != nil {
// Roll back the registered view so it doesn't linger pointing at metadata
// that was never written.
if dropErr := s.dropView(r, namespace, req.Name); dropErr != nil {
if dropErr := s.dropView(r, namespace, req.Name, ""); dropErr != nil {
glog.V(1).Infof("Iceberg: failed to roll back view %s.%s after metadata write error: %v", flattenNamespacePath(namespace), req.Name, dropErr)
}
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save view metadata file: "+err.Error())
@@ -296,12 +297,15 @@ func (s *Server) handleDropView(w http.ResponseWriter, r *http.Request) {
return
}
var storedMetadataLocation string
var storedMetadataLocation, storedVersionToken string
var storedCreatedAt time.Time
if getResp, err := s.getView(r, namespace, viewName); err == nil {
storedMetadataLocation = getResp.MetadataLocation
storedCreatedAt = getResp.CreatedAt
storedVersionToken = getResp.VersionToken
}
err := s.dropView(r, namespace, viewName)
err := s.dropView(r, namespace, viewName, storedVersionToken)
if err != nil {
if isViewNotFound(err) {
writeError(w, http.StatusNotFound, "NoSuchViewException", fmt.Sprintf("View does not exist: %s", viewName))
@@ -315,7 +319,10 @@ func (s *Server) handleDropView(w http.ResponseWriter, r *http.Request) {
if storedMetadataLocation != "" {
if viewLoc := tableLocationFromMetadataLocation(storedMetadataLocation); viewLoc != "" {
if dataBucket, dataPath, parseErr := parseS3Location(viewLoc); parseErr == nil {
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), dataBucket, dataPath); cleanupErr != nil {
holdsFiles := func(client filer_pb.SeaweedFilerClient, dir string) (bool, error) {
return s3tables.ViewHoldsFiles(r.Context(), client, dir, storedCreatedAt)
}
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), dataBucket, dataPath, holdsFiles); cleanupErr != nil {
glog.V(1).Infof("Iceberg: failed to purge dropped view location s3://%s/%s: %v", dataBucket, dataPath, cleanupErr)
}
}
@@ -326,11 +333,12 @@ func (s *Server) handleDropView(w http.ResponseWriter, r *http.Request) {
}
// dropView removes a view registration from the catalog.
func (s *Server) dropView(r *http.Request, namespace []string, viewName string) error {
func (s *Server) dropView(r *http.Request, namespace []string, viewName, versionToken string) error {
deleteReq := &s3tables.DeleteViewRequest{
TableBucketARN: buildTableBucketARN(getBucketFromPrefix(r)),
Namespace: namespace,
Name: viewName,
VersionToken: versionToken,
}
identityName := s3_constants.GetIdentityNameFromContext(r)
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
@@ -1,13 +1,19 @@
package iceberg
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"path"
"strings"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
@@ -55,3 +61,273 @@ func TestDropViewKeepsAnotherRecordsFiles(t *testing.T) {
t.Errorf("dropping the view deleted the files of finance.orders")
}
}
// A view's location keeps metadata files that predate the view, and loses
// the ones the view wrote.
func TestDropViewKeepsOlderMetadataAtItsLocation(t *testing.T) {
createdAt := time.Now().Truncate(time.Second)
for _, tc := range []struct {
name string
crtime time.Time
kept bool
}{
{"older", createdAt.Add(-time.Hour), true},
{"own", createdAt.Add(time.Second), false},
} {
t.Run(tc.name, func(t *testing.T) {
fc := newMemFiler()
seedNamespace(fc, ownerTestBucket, "finance", "alice")
otherPath := s3tables.GetTablePath(ownerTestBucket, "finance", "other")
fc.seed(otherPath, &filer_pb.Entry{Name: "other", IsDirectory: true})
fc.seed(otherPath+"/metadata", &filer_pb.Entry{Name: "metadata", IsDirectory: true})
fc.seed(otherPath+"/metadata/user.metadata.json", &filer_pb.Entry{Name: "user.metadata.json", Content: []byte("x"),
Attributes: &filer_pb.FuseAttributes{Crtime: tc.crtime.Unix()}})
viewMeta, err := json.Marshal(map[string]any{
"name": "alias",
"namespace": "finance",
"createdAt": createdAt,
"ownerAccountId": "mallory",
"versionToken": "v1",
"metadataVersion": 1,
"metadataLocation": "s3://" + ownerTestBucket + "/finance/other/metadata/v1.metadata.json",
})
if err != nil {
t.Fatal(err)
}
fc.seed(s3tables.GetTablePath(ownerTestBucket, "finance", "alias"), &filer_pb.Entry{
Name: "alias",
IsDirectory: true,
Extended: map[string][]byte{
s3tables.ExtendedKeyMetadata: viewMeta,
s3tables.ExtendedKeyEntryType: []byte(s3tables.EntryTypeView),
},
})
s := NewServer(fc, nil)
r := httptest.NewRequest(http.MethodDelete, "/v1/"+ownerTestBucket+"/namespaces/finance/views/alias", nil)
r = mux.SetURLVars(r, map[string]string{"prefix": ownerTestBucket, "namespace": "finance", "view": "alias"})
w := httptest.NewRecorder()
s.handleDropView(w, withActions(r, "mallory", creatorActions...))
if w.Code != http.StatusNoContent {
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusNoContent, w.Body.String())
}
if _, ok := fc.entries[otherPath+"/metadata/user.metadata.json"]; ok != tc.kept {
t.Errorf("metadata file kept = %v, want %v", ok, tc.kept)
}
})
}
}
// A table recorded over files that were already there drops without purging
// them: they were not written for it.
func TestDropTableKeepsOlderFilesAtItsLocation(t *testing.T) {
fc := newMemFiler()
seedNamespace(fc, ownerTestBucket, "finance", "alice")
otherPath := s3tables.GetTablePath(ownerTestBucket, "finance", "other")
fc.seed(otherPath, &filer_pb.Entry{Name: "other", IsDirectory: true})
fc.seed(otherPath+"/data", &filer_pb.Entry{Name: "data", IsDirectory: true})
fc.seed(otherPath+"/data/f.parquet", &filer_pb.Entry{Name: "f.parquet", Content: []byte("x"),
Attributes: &filer_pb.FuseAttributes{Crtime: time.Now().Add(-time.Hour).Unix()}})
tableMeta, err := json.Marshal(map[string]any{
"name": "alias",
"namespace": "finance",
"format": "ICEBERG",
"createdAt": time.Now(),
"ownerAccountId": "mallory",
"versionToken": "v1",
"metadataVersion": 1,
"metadataLocation": "s3://" + ownerTestBucket + "/finance/other/metadata/v1.metadata.json",
})
if err != nil {
t.Fatal(err)
}
fc.seed(s3tables.GetTablePath(ownerTestBucket, "finance", "alias"), &filer_pb.Entry{
Name: "alias",
IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: tableMeta},
})
s := NewServer(fc, nil)
r := httptest.NewRequest(http.MethodDelete, "/v1/"+ownerTestBucket+"/namespaces/finance/tables/alias", nil)
r = mux.SetURLVars(r, map[string]string{"prefix": ownerTestBucket, "namespace": "finance", "table": "alias"})
w := httptest.NewRecorder()
s.handleDropTable(w, withActions(r, "mallory", creatorActions...))
if w.Code != http.StatusNoContent {
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusNoContent, w.Body.String())
}
if _, ok := fc.entries[otherPath+"/data/f.parquet"]; !ok {
t.Errorf("dropping the table deleted files that predate it")
}
}
// The engine of a staged create writes its first files before the commit
// registers the table. They are the table's, so a drop purges them.
func TestDropStagedTablePurgesFilesWrittenBeforeItsCommit(t *testing.T) {
const bucket = "warehouse"
fc := newMemFiler()
seedNamespace(fc, bucket, "finance", "alice")
s := NewServer(fc, nil)
w := httptest.NewRecorder()
s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"orders","stage-create":true}`, "alice"))
staged := decodeCreated(t, w)
stagedAt := time.Now().Add(-time.Minute)
for p, entry := range fc.entries {
if path.Dir(p) != stageCreateMarkerDir(bucket, []string{"finance"}, "orders") || entry.IsDirectory {
continue
}
var marker stageCreateMarker
if err := json.Unmarshal(entry.Content, &marker); err != nil {
t.Fatal(err)
}
marker.CreatedAt = stagedAt.UTC().Format(time.RFC3339Nano)
entry.Content, _ = json.Marshal(marker)
}
locationPath := path.Join(s3tables.TablesPath, strings.TrimPrefix(staged.Metadata.Location, "s3://"))
fc.seed(locationPath, &filer_pb.Entry{Name: path.Base(locationPath), IsDirectory: true})
fc.seed(locationPath+"/data", &filer_pb.Entry{Name: "data", IsDirectory: true})
fc.seed(locationPath+"/data/f.parquet", &filer_pb.Entry{Name: "f.parquet", Content: []byte("x"),
Attributes: &filer_pb.FuseAttributes{Crtime: stagedAt.Add(30 * time.Second).Unix()}})
body := `{"requirements":[{"type":"assert-create"}],"updates":[{"action":"assign-uuid","uuid":"` + staged.Metadata.TableUUID + `"}]}`
r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/orders", strings.NewReader(body))
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "orders"})
w = httptest.NewRecorder()
s.handleUpdateTable(w, r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")))
decodeCreated(t, w)
r = httptest.NewRequest(http.MethodDelete, "/v1/"+bucket+"/namespaces/finance/tables/orders", nil)
r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "orders"})
w = httptest.NewRecorder()
s.handleDropTable(w, r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")))
if w.Code != http.StatusNoContent {
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusNoContent, w.Body.String())
}
if _, ok := fc.entries[locationPath+"/data/f.parquet"]; ok {
t.Errorf("drop kept a file the staged create wrote before its commit")
}
}
// swapFiler runs before ahead of the n-th WithFilerClient call.
type swapFiler struct {
*memFiler
calls int
n int
before func()
}
func (f *swapFiler) WithFilerClient(streaming bool, fn func(client filer_pb.SeaweedFilerClient) error) error {
f.calls++
if f.calls == f.n {
f.before()
}
return f.memFiler.WithFilerClient(streaming, fn)
}
// A record replaced between a drop's lookup and its delete is not dropped,
// and the files dated after the looked-up record stay.
func TestDropKeepsRecordReplacedAfterLookup(t *testing.T) {
base := time.Now().Add(-2 * time.Hour).Truncate(time.Second)
for _, tc := range []struct {
kind, file, verb string
extended map[string][]byte
}{
{"table", "data/f.parquet", "tables", nil},
{"view", "metadata/user.metadata.json", "views", map[string][]byte{s3tables.ExtendedKeyEntryType: []byte(s3tables.EntryTypeView)}},
} {
t.Run(tc.kind, func(t *testing.T) {
fc := newMemFiler()
seedNamespace(fc, ownerTestBucket, "finance", "alice")
otherPath := s3tables.GetTablePath(ownerTestBucket, "finance", "other")
fc.seed(otherPath, &filer_pb.Entry{Name: "other", IsDirectory: true})
fc.seed(path.Dir(otherPath+"/"+tc.file), &filer_pb.Entry{Name: path.Base(path.Dir(tc.file)), IsDirectory: true})
fc.seed(otherPath+"/"+tc.file, &filer_pb.Entry{Name: path.Base(tc.file), Content: []byte("x"),
Attributes: &filer_pb.FuseAttributes{Crtime: base.Add(30 * time.Minute).Unix()}})
aliasPath := s3tables.GetTablePath(ownerTestBucket, "finance", "alias")
record := func(createdAt time.Time, token string) *filer_pb.Entry {
meta, err := json.Marshal(map[string]any{
"name": "alias",
"namespace": "finance",
"format": "ICEBERG",
"createdAt": createdAt,
"ownerAccountId": "mallory",
"versionToken": token,
"metadataVersion": 1,
"metadataLocation": "s3://" + ownerTestBucket + "/finance/other/metadata/v1.metadata.json",
})
if err != nil {
t.Fatal(err)
}
extended := map[string][]byte{s3tables.ExtendedKeyMetadata: meta}
for k, v := range tc.extended {
extended[k] = v
}
return &filer_pb.Entry{Name: "alias", IsDirectory: true, Extended: extended}
}
fc.seed(aliasPath, record(base, "v1"))
sf := &swapFiler{memFiler: fc, n: 2, before: func() { fc.seed(aliasPath, record(base.Add(time.Hour), "v2")) }}
s := NewServer(sf, nil)
r := httptest.NewRequest(http.MethodDelete, "/v1/"+ownerTestBucket+"/namespaces/finance/"+tc.verb+"/alias", nil)
r = mux.SetURLVars(r, map[string]string{"prefix": ownerTestBucket, "namespace": "finance", "table": "alias", "view": "alias"})
w := httptest.NewRecorder()
if tc.kind == "table" {
s.handleDropTable(w, withActions(r, "mallory", append(creatorActions, "s3tables:DeleteTable")...))
} else {
s.handleDropView(w, withActions(r, "mallory", creatorActions...))
}
if w.Code != http.StatusConflict {
t.Fatalf("status = %d, want %d (body: %s)", w.Code, http.StatusConflict, w.Body.String())
}
if _, ok := fc.entries[aliasPath]; !ok {
t.Errorf("the replacement record was dropped")
}
if _, ok := fc.entries[otherPath+"/"+tc.file]; !ok {
t.Errorf("files dated after the looked-up record were purged")
}
})
}
}
// A record that claims the location while the drop scans it keeps the files.
func TestDropPurgeKeepsLocationClaimedDuringScan(t *testing.T) {
fc := newMemFiler()
seedNamespace(fc, ownerTestBucket, "finance", "alice")
otherPath := s3tables.GetTablePath(ownerTestBucket, "finance", "other")
fc.seed(otherPath, &filer_pb.Entry{Name: "other", IsDirectory: true})
fc.seed(otherPath+"/data", &filer_pb.Entry{Name: "data", IsDirectory: true})
fc.seed(otherPath+"/data/f.parquet", &filer_pb.Entry{Name: "f.parquet", Content: []byte("x")})
meta, err := json.Marshal(map[string]any{
"name": "fresh",
"namespace": "finance",
"format": "ICEBERG",
"ownerAccountId": "alice",
"versionToken": "v1",
"metadataVersion": 1,
"metadataLocation": "s3://" + ownerTestBucket + "/finance/other/metadata/v1.metadata.json",
})
if err != nil {
t.Fatal(err)
}
holdsFiles := func(filer_pb.SeaweedFilerClient, string) (bool, error) {
fc.seed(s3tables.GetTablePath(ownerTestBucket, "finance", "fresh"), &filer_pb.Entry{
Name: "fresh",
IsDirectory: true,
Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: meta},
})
return false, nil
}
s := NewServer(fc, nil)
err = s.cleanupStaleTableLocation(context.Background(), ownerTestBucket, "finance/other", holdsFiles)
if !errors.Is(err, s3tables.ErrLocationInUse) {
t.Fatalf("err = %v, want %v", err, s3tables.ErrLocationInUse)
}
if _, ok := fc.entries[otherPath+"/data/f.parquet"]; !ok {
t.Errorf("the purge deleted the files of a table that claimed the location during the scan")
}
}
+51 -9
View File
@@ -208,6 +208,12 @@ func (h *S3TablesHandler) removeExtendedAttributes(ctx context.Context, client f
})
}
// catalogRecordKeys are the attributes that make a directory a catalog record.
var catalogRecordKeys = []string{
ExtendedKeyMetadata, ExtendedKeyMetadataVersion, ExtendedKeyPolicy, ExtendedKeyTags, ExtendedKeyEntryType,
ExtendedKeyMaintenance, ExtendedKeyMaintenanceStatus, ExtendedKeyDeleting, ExtendedKeyMoving,
}
// removeExtendedAttributesIf drops the given attributes only while they still
// hold the values the caller captured. A rename copies attributes to the
// destination and then clears the source; without this, a write that landed in
@@ -899,18 +905,52 @@ func (w *markRemovalWrites) UpdateEntry(ctx context.Context, in *filer_pb.Update
return resp, err
}
// dirListPageSize is how many entries dirHoldsFiles reads per ListEntries call.
// dirListPageSize is how many entries DirHoldsFiles reads per ListEntries call.
const dirListPageSize = 1024
// dirHoldsFiles reports whether any file sits under dirPath, at any depth. It
// walks breadth-first, pages through each directory, and stops at the first
// file it sees. Returning at that file abandons the page being read, so the
// listings run on a context of their own that ends with the call: otherwise
// the filer keeps producing that page until the whole request is over.
func (h *S3TablesHandler) dirHoldsFiles(ctx context.Context, client filer_pb.SeaweedFilerClient, dirPath string) (bool, error) {
// anyFileTime is a DirHoldsFiles cutoff past every file time.
var anyFileTime = time.Unix(1<<62, 0)
// ViewHoldsFiles reports whether dirPath holds a file a view created at
// createdAt did not write: any file but its metadata, which it writes only
// after its record, and any metadata file from an earlier second.
func ViewHoldsFiles(ctx context.Context, client filer_pb.SeaweedFilerClient, dirPath string, createdAt time.Time) (bool, error) {
if holds, err := DirHoldsFiles(ctx, client, dirPath, anyFileTime); holds || err != nil {
return holds, err
}
return DirHoldsFiles(ctx, client, path.Join(dirPath, "metadata"), createdAt)
}
// DirHoldsFiles reports whether any file sits under dirPath, at any depth, or
// an S3 object is stored on dirPath or a directory under it. A non-zero before
// counts only those created in an earlier second (file times have second
// granularity, and a writer's first file can share the record's second), other
// than Iceberg metadata files in dirPath/metadata, which a create stages ahead
// of its record. It walks breadth-first, pages through
// each directory, and stops at the first file it sees. Returning at that file
// abandons the page being read, so the listings run on a context of their own
// that ends with the call: otherwise the filer keeps producing that page until
// the whole request is over.
func DirHoldsFiles(ctx context.Context, client filer_pb.SeaweedFilerClient, dirPath string, before time.Time) (bool, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
counts := func(dir string, entry *filer_pb.Entry) bool {
if entry.IsDirectory && !entry.IsDirectoryKeyObject() {
return false
}
return before.IsZero() || (entry.GetAttributes().GetCrtime() < before.Unix() &&
!(dir == path.Join(dirPath, "metadata") && strings.HasSuffix(entry.Name, ".metadata.json")))
}
parent, name := path.Split(dirPath)
if resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: strings.TrimSuffix(parent, "/"), Name: name}); err == nil {
if counts(parent, resp.Entry) {
return true, nil
}
} else if !errors.Is(err, filer_pb.ErrNotFound) {
return false, err
}
pending := []string{dirPath}
for len(pending) > 0 {
dir := pending[0]
@@ -946,10 +986,12 @@ func (h *S3TablesHandler) dirHoldsFiles(ctx context.Context, client filer_pb.Sea
}
received = true
lastFileName = entry.Entry.Name
if !entry.Entry.IsDirectory {
if counts(dir, entry.Entry) {
return true, nil
}
pending = append(pending, path.Join(dir, entry.Entry.Name))
if entry.Entry.IsDirectory {
pending = append(pending, path.Join(dir, entry.Entry.Name))
}
}
if !received {
break
@@ -8,6 +8,7 @@ import (
"net/http"
"path"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -442,7 +443,7 @@ func (h *S3TablesHandler) handleDeleteTableBucket(w http.ResponseWriter, r *http
return nil
}
for _, leftover := range leftovers {
holdsFiles, err := h.dirHoldsFiles(r.Context(), client, path.Join(bucketPath, leftover.Name))
holdsFiles, err := DirHoldsFiles(r.Context(), client, path.Join(bucketPath, leftover.Name), time.Time{})
if err != nil {
return err
}
@@ -0,0 +1,141 @@
package s3tables
import (
"context"
"net/http"
"path"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Files a record did not write for itself stay when it is deleted: anything
// but metadata under a view, and files already under a table's path when the
// table was created. The files a table wrote after its create still go.
func TestDeleteKeepsFilesOlderThanTheRecord(t *testing.T) {
older := time.Now().Add(-time.Hour)
nsPath := GetNamespacePath(renameTestBucket, "ns")
upload := func(fs *s3tablestest.MemFiler, name string, crtime time.Time) {
if fs.Get(nsPath, name) == nil {
fs.Put(nsPath, name, nil)
}
fs.Put(path.Join(nsPath, name), "data", nil)
fs.PutFile(path.Join(nsPath, name, "data"), "file.parquet", crtime)
}
t.Run("view", func(t *testing.T) {
fs, m := startRenameManager(t)
requireOK(t, m, fs, "CreateView", &CreateViewRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "v1"})
upload(fs, "v1", time.Now().Add(time.Minute))
requireOK(t, m, fs, "DeleteView", &DeleteViewRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "v1"})
assert.NotNil(t, fs.Get(GetTablePath(renameTestBucket, "ns", "v1")+"/data", "file.parquet"))
require.NotNil(t, fs.Get(nsPath, "v1"))
assert.Empty(t, fs.Get(nsPath, "v1").Extended[ExtendedKeyMetadata])
status, resp := runHandler(t, m, fs.Client, "CreateView", &CreateViewRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "v1"})
assert.Equal(t, http.StatusConflict, status)
assert.Equal(t, "v1 already exists and is not a table or view", resp.Message)
})
t.Run("colocated table", func(t *testing.T) {
fs, m := startRenameManager(t)
upload(fs, "t2", older)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2", Format: FormatIceberg})
requireOK(t, m, fs, "DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2"})
assert.NotNil(t, fs.Get(GetTablePath(renameTestBucket, "ns", "t2")+"/data", "file.parquet"))
require.NotNil(t, fs.Get(nsPath, "t2"))
assert.Empty(t, fs.Get(nsPath, "t2").Extended[ExtendedKeyMetadata])
})
t.Run("table purges a file from its own second", func(t *testing.T) {
fs, m := startRenameManager(t)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/t2/metadata/v1.metadata.json")})
upload(fs, "t2", time.Now())
requireOK(t, m, fs, "DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2"})
assert.Nil(t, fs.Get(nsPath, "t2"))
})
t.Run("staged table purges files written before its commit", func(t *testing.T) {
fs, m := startRenameManager(t)
stagedAt := time.Now().Add(-time.Minute)
upload(fs, "t2", stagedAt.Add(30*time.Second))
require.NoError(t, m.Execute(WithTableStagedAt(context.Background(), stagedAt), NewManagerClient(fs.Client), "CreateTable",
&CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/t2/metadata/v1.metadata.json")}, nil, "admin"))
requireOK(t, m, fs, "DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2"})
assert.Nil(t, fs.Get(nsPath, "t2"))
})
t.Run("table located over other files", func(t *testing.T) {
fs, m := startRenameManager(t)
upload(fs, "other", older)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/other/metadata/v1.metadata.json")})
requireOK(t, m, fs, "DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2"})
assert.NotNil(t, fs.Get(GetTablePath(renameTestBucket, "ns", "other")+"/data", "file.parquet"))
require.NotNil(t, fs.Get(nsPath, "t2"))
assert.Empty(t, fs.Get(nsPath, "t2").Extended[ExtendedKeyMetadata])
})
t.Run("table purges its own files", func(t *testing.T) {
fs, m := startRenameManager(t)
tablePath := GetTablePath(renameTestBucket, "ns", "t2")
fs.PutFile(tablePath+"/metadata", "v1.metadata.json", older)
requireOK(t, m, fs, "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2", Format: FormatIceberg,
MetadataLocation: renameLocation("ns/t2/metadata/v1.metadata.json")})
fs.PutFile(tablePath+"/data", "file.parquet", time.Now().Add(time.Second))
requireOK(t, m, fs, "DeleteTable", &DeleteTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2"})
assert.Nil(t, fs.Get(nsPath, "t2"))
assert.Nil(t, fs.Get(tablePath+"/data", "file.parquet"))
})
}
// An S3 object stored on a directory entry, below the walked path or on it,
// counts like a file.
func TestDirHoldsFilesCountsDirectoryObjects(t *testing.T) {
older := time.Now().Add(-time.Hour)
nsPath := GetNamespacePath(renameTestBucket, "ns")
dirObject := func(name string) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, IsDirectory: true, Content: []byte("x"),
Attributes: &filer_pb.FuseAttributes{Mime: "text/plain", Crtime: older.Unix()}}
}
fs, _ := startRenameManager(t)
ctx := context.Background()
fs.Put(nsPath, "below", nil)
_, err := fs.CreateEntry(ctx, &filer_pb.CreateEntryRequest{Directory: path.Join(nsPath, "below"), Entry: dirObject("checkpoint")})
require.NoError(t, err)
holds, err := DirHoldsFiles(ctx, fs.Client, path.Join(nsPath, "below"), time.Now())
require.NoError(t, err)
assert.True(t, holds, "object on a directory under the path")
_, err = fs.CreateEntry(ctx, &filer_pb.CreateEntryRequest{Directory: nsPath, Entry: dirObject("on")})
require.NoError(t, err)
holds, err = DirHoldsFiles(ctx, fs.Client, path.Join(nsPath, "on"), time.Now())
require.NoError(t, err)
assert.True(t, holds, "object on the path itself")
fs.Put(nsPath, "plain", nil)
fs.Put(path.Join(nsPath, "plain"), "sub", nil)
holds, err = DirHoldsFiles(ctx, fs.Client, path.Join(nsPath, "plain"), time.Now())
require.NoError(t, err)
assert.False(t, holds, "plain directories hold nothing")
}
+1 -1
View File
@@ -958,7 +958,7 @@ func (h *S3TablesHandler) handleDeleteNamespace(w http.ResponseWriter, r *http.R
// namespace: the namespace directory stays, minus its catalog
// record. One such directory settles it, so the rest are not walked.
if entry.Entry.IsDirectory && !keepDir {
holdsFiles, err := h.dirHoldsFiles(r.Context(), client, path.Join(namespacePath, entry.Entry.Name))
holdsFiles, err := DirHoldsFiles(r.Context(), client, path.Join(namespacePath, entry.Entry.Name), time.Time{})
if err != nil {
return err
}
@@ -265,14 +265,14 @@ func (c *listContextClient) ListEntries(ctx context.Context, in *filer_pb.ListEn
// The walk stops at the first file with a page still unread. Its listings must
// end with the call, not with the request, so the filer stops producing that page.
func TestDirHoldsFilesEndsItsListings(t *testing.T) {
fs, m := startRenameManager(t)
fs, _ := startRenameManager(t)
leftover := GetTablePath(renameTestBucket, "ns", "leftover")
fs.Put(leftover, "a-dir", nil)
fs.PutFile(leftover, "b-file", time.Now())
fs.PutFile(leftover, "c-file", time.Now())
client := &listContextClient{SeaweedFilerClient: fs.Client}
holds, err := m.handler.dirHoldsFiles(context.Background(), client, leftover)
holds, err := DirHoldsFiles(context.Background(), client, leftover, time.Time{})
require.NoError(t, err)
assert.True(t, holds)
@@ -7,6 +7,7 @@ import (
"path"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
@@ -42,6 +43,7 @@ func startRenameManager(t *testing.T) (*s3tablestest.MemFiler, *Manager) {
Name: "t",
Namespace: "ns",
Format: "ICEBERG",
CreatedAt: time.Now().Add(-time.Hour),
OwnerAccountID: DefaultAccountID,
MetadataVersion: 3,
MetadataLocation: "s3://" + renameTestBucket + "/ns/t/metadata/v3.metadata.json",
+40 -15
View File
@@ -129,13 +129,17 @@ func (h *S3TablesHandler) handleCreateTable(w http.ResponseWriter, r *http.Reque
// Create the table
now := time.Now()
createdAt := now
if stagedAt, ok := r.Context().Value(tableStagedAtKey{}).(time.Time); ok && stagedAt.Before(now) {
createdAt = stagedAt
}
versionToken := generateVersionToken()
metadata := &tableMetadataInternal{
Name: tableName,
Namespace: namespaceName,
Format: req.Format,
CreatedAt: now,
CreatedAt: createdAt,
ModifiedAt: now,
OwnerAccountID: target.ownerAccountID, // Inherit namespace owner for consistency
VersionToken: versionToken,
@@ -1135,7 +1139,12 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
// Decoupled table (renamed, or created over a leftover): its data
// lives elsewhere. Purge the data, then clear the catalog marker
// without deleting the name path -- it may still hold another
// table's data that was left when this name was reused.
// table's data that was left when this name was reused. Files
// older than the table were not written for it and stay.
keepData, err := DirHoldsFiles(r.Context(), client, dataPath, metadata.CreatedAt)
if err != nil {
return err
}
if req.VersionToken != "" && tableEntry != nil {
// A token caller owns exactly the record it read. Claim it
// under the captured attributes before any data is removed:
@@ -1153,15 +1162,16 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
}
claimed := snapshotExtended(tableEntry.Extended)
claimed[ExtendedKeyDeleting] = []byte("delete")
if err := h.deleteDirectory(r.Context(), client, dataPath); err != nil {
if relErr := h.releaseCatalogRecord(context.WithoutCancel(r.Context()), client, tablePath, claimed); relErr != nil {
glog.Warningf("delete table %s: release claim: %v", tablePath, relErr)
if !keepData {
if err := h.deleteDirectory(r.Context(), client, dataPath); err != nil {
if relErr := h.releaseCatalogRecord(context.WithoutCancel(r.Context()), client, tablePath, claimed); relErr != nil {
glog.Warningf("delete table %s: release claim: %v", tablePath, relErr)
}
return err
}
return err
}
err := h.removeExtendedAttributesIf(context.WithoutCancel(r.Context()), client, tablePath, claimed,
ExtendedKeyMetadata, ExtendedKeyMetadataVersion, ExtendedKeyPolicy, ExtendedKeyTags, ExtendedKeyEntryType,
ExtendedKeyMaintenance, ExtendedKeyMaintenanceStatus, ExtendedKeyDeleting, ExtendedKeyMoving)
catalogRecordKeys...)
if err != nil {
if errors.Is(err, ErrConcurrentUpdate) {
return ErrVersionTokenMismatch
@@ -1196,25 +1206,37 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
}
claimed := snapshotExtended(entry.Extended)
claimed[ExtendedKeyDeleting] = []byte("delete")
if err := h.deleteDirectory(r.Context(), client, dataPath); err != nil {
if relErr := h.releaseCatalogRecord(context.WithoutCancel(r.Context()), client, tablePath, claimed); relErr != nil {
glog.Warningf("delete table %s: release claim: %v", tablePath, relErr)
if !keepData {
if err := h.deleteDirectory(r.Context(), client, dataPath); err != nil {
if relErr := h.releaseCatalogRecord(context.WithoutCancel(r.Context()), client, tablePath, claimed); relErr != nil {
glog.Warningf("delete table %s: release claim: %v", tablePath, relErr)
}
return err
}
return err
}
return h.removeExtendedAttributesIf(context.WithoutCancel(r.Context()), client, tablePath, claimed,
ExtendedKeyMetadata, ExtendedKeyMetadataVersion, ExtendedKeyPolicy, ExtendedKeyTags, ExtendedKeyEntryType,
ExtendedKeyMaintenance, ExtendedKeyMaintenanceStatus, ExtendedKeyDeleting, ExtendedKeyMoving)
catalogRecordKeys...)
}
// Colocated table: the name path holds the data. A token caller's
// delete carries the captured attributes as a filer precondition, so
// compare and removal are one operation under the path lock: an xattr
// write that keeps Mtime, or a delete+recreate in between, refuses it.
// Files older than the table were not written for it, so they stay
// and only the catalog record goes.
keepData, err := DirHoldsFiles(r.Context(), client, tablePath, metadata.CreatedAt)
if err != nil {
return err
}
if req.VersionToken != "" && tableEntry != nil {
if claim := string(tableEntry.Extended[ExtendedKeyDeleting]); claim != "" && claim != "delete" {
return ErrVersionTokenMismatch
}
if err := h.deleteDirectoryIfMatches(r.Context(), client, tablePath, tableEntry); err != nil {
if keepData {
err = h.removeExtendedAttributesIf(r.Context(), client, tablePath, snapshotExtended(tableEntry.Extended), catalogRecordKeys...)
} else {
err = h.deleteDirectoryIfMatches(r.Context(), client, tablePath, tableEntry)
}
if err != nil {
if errors.Is(err, ErrConcurrentUpdate) {
return ErrVersionTokenMismatch
}
@@ -1245,6 +1267,9 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
if err := h.claimCatalogRecord(r.Context(), client, tablePath, snapshotExtended(entry.Extended), "delete"); err != nil {
return err
}
if keepData {
return h.removeExtendedAttributesIf(context.WithoutCancel(r.Context()), client, tablePath, claimed, catalogRecordKeys...)
}
if err := h.deleteDirectoryIfMatches(r.Context(), client, tablePath, &filer_pb.Entry{Extended: claimed}); err != nil {
if relErr := h.releaseCatalogRecord(context.WithoutCancel(r.Context()), client, tablePath, claimed); relErr != nil {
glog.Warningf("delete table %s: release claim: %v", tablePath, relErr)
+16 -5
View File
@@ -96,7 +96,7 @@ func (h *S3TablesHandler) handleCreateView(w http.ResponseWriter, r *http.Reques
// Reject if a table or view already exists at this name.
var existingMetadata tableMetadataInternal
var existingIsTable bool
var conflict string
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
entry, err := h.lookupEntry(r.Context(), client, viewPath)
if err != nil {
@@ -107,8 +107,12 @@ func (h *S3TablesHandler) handleCreateView(w http.ResponseWriter, r *http.Reques
// it is not an existing view; the claim below refuses the name.
return filer_pb.ErrNotFound
}
if _, ok := entry.Extended[ExtendedKeyMetadata]; !ok && EntryType(entry.Extended) != EntryTypeView {
conflict = fmt.Sprintf("%s already exists and is not a table or view", viewName)
return nil
}
if EntryType(entry.Extended) != EntryTypeView {
existingIsTable = true
conflict = fmt.Sprintf("a table named %s already exists", viewName)
return nil
}
data, ok := entry.Extended[ExtendedKeyMetadata]
@@ -118,9 +122,9 @@ func (h *S3TablesHandler) handleCreateView(w http.ResponseWriter, r *http.Reques
return json.Unmarshal(data, &existingMetadata)
})
if err == nil {
if existingIsTable {
h.writeError(w, http.StatusConflict, ErrCodeViewAlreadyExists, fmt.Sprintf("a table named %s already exists", viewName))
return fmt.Errorf("table name conflict: %s", viewName)
if conflict != "" {
h.writeError(w, http.StatusConflict, ErrCodeViewAlreadyExists, conflict)
return fmt.Errorf("view name conflict: %s", conflict)
}
viewARN := h.generateViewARN(existingMetadata.OwnerAccountID, bucketName, namespaceName+"/"+viewName)
h.writeJSON(w, http.StatusOK, &CreateViewResponse{
@@ -714,11 +718,18 @@ func (h *S3TablesHandler) handleDeleteView(w http.ResponseWriter, r *http.Reques
if current.VersionToken != metadata.VersionToken {
return ErrConcurrentUpdate
}
keepData, err := ViewHoldsFiles(r.Context(), client, viewPath, current.CreatedAt)
if err != nil {
return err
}
claimed := snapshotExtended(entry.Extended)
claimed[ExtendedKeyDeleting] = []byte("delete")
if err := h.claimCatalogRecord(r.Context(), client, viewPath, snapshotExtended(entry.Extended), "delete"); err != nil {
return err
}
if keepData {
return h.removeExtendedAttributesIf(context.WithoutCancel(r.Context()), client, viewPath, claimed, catalogRecordKeys...)
}
if err := h.deleteDirectoryIfMatches(r.Context(), client, viewPath, &filer_pb.Entry{Extended: claimed}); err != nil {
if relErr := h.releaseCatalogRecord(context.WithoutCancel(r.Context()), client, viewPath, claimed); relErr != nil {
glog.Warningf("delete view %s: release claim: %v", viewPath, relErr)
+10
View File
@@ -98,6 +98,16 @@ func WithTableBucketCreatedAt(ctx context.Context, createdAt time.Time) context.
return context.WithValue(ctx, tableBucketCreatedAtKey{}, createdAt)
}
type tableStagedAtKey struct{}
// WithTableStagedAt dates a CreateTable run through Execute from stagedAt, when
// a staged create handed out the table's location, so the files the engine
// wrote there before the commit are the table's. In-process only, like
// WithTableBucketCreatedAt.
func WithTableStagedAt(ctx context.Context, stagedAt time.Time) context.Context {
return context.WithValue(ctx, tableStagedAtKey{}, stagedAt)
}
// boundTableBucket returns the bucket creation time ctx binds the request to.
func boundTableBucket(ctx context.Context) (time.Time, bool) {
createdAt, ok := ctx.Value(tableBucketCreatedAtKey{}).(time.Time)