mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
chunkstore: import the minimal SeaweedFS client from the D1 PoC
Copied unchanged from the D1 chunkstore PoC (commit 05818b3): the Filer and Blobs interfaces with their sentinel errors, the SWFS client over the filer gRPC API (vendored proto subset) plus plain HTTP to volume servers, its gRPC error-mapping tests, and the in-memory fake filer and needle store. The PoC's demo Backend, volume and flat manifest are not imported: the walstore chunk layer publishes its own HEAD. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c71a2cbc02
commit
a8d02778bf
7 files changed
+2656
No files matched your search
@@ -0,0 +1,144 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"sync"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// fakeFiler is an in-memory filer with the same precondition semantics as
|
||||
// seaweed-mono's UpdateEntry (validateUpdateEntryPreconditions) and
|
||||
// CreateEntry(o_excl). It records every entry ever written so tests can
|
||||
// check that no HEAD or snapshot entry carries chunks.
|
||||
type fakeFiler struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]*filerpb.Entry
|
||||
written []*filerpb.Entry
|
||||
|
||||
// failUpdate, if set, is called before an UpdateEntry is applied; a
|
||||
// non-nil return fails the call and the update is NOT applied.
|
||||
failUpdate func(p string) error
|
||||
// failUpdateAfterApply, if set, is called after an UpdateEntry was
|
||||
// applied; a non-nil return is reported to the caller (ambiguous error).
|
||||
failUpdateAfterApply func(p string) error
|
||||
updates int
|
||||
}
|
||||
|
||||
func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} }
|
||||
|
||||
func (f *fakeFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
e, ok := f.entries[path.Join(dir, name)]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return proto.Clone(e).(*filerpb.Entry), nil
|
||||
}
|
||||
|
||||
func (f *fakeFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
p := path.Join(dir, e.Name)
|
||||
if _, ok := f.entries[p]; ok && oExcl {
|
||||
return fmt.Errorf("%w: %s", ErrExists, p)
|
||||
}
|
||||
c := proto.Clone(e).(*filerpb.Entry)
|
||||
f.entries[p] = c
|
||||
f.written = append(f.written, proto.Clone(e).(*filerpb.Entry))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
p := path.Join(dir, e.Name)
|
||||
if f.failUpdate != nil {
|
||||
if err := f.failUpdate(p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cur, ok := f.entries[p]
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: %s", ErrNotFound, p)
|
||||
}
|
||||
for k, want := range expected {
|
||||
got, has := cur.Extended[k]
|
||||
if has && !bytes.Equal(got, want) || !has && len(want) > 0 {
|
||||
return fmt.Errorf("%w: extended %q changed", ErrPrecondition, k)
|
||||
}
|
||||
}
|
||||
f.entries[p] = proto.Clone(e).(*filerpb.Entry)
|
||||
f.written = append(f.written, proto.Clone(e).(*filerpb.Entry))
|
||||
f.updates++
|
||||
if f.failUpdateAfterApply != nil {
|
||||
if err := f.failUpdateAfterApply(p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// bumpExtended mutates a stored entry's extended key, as another writer would.
|
||||
func (f *fakeFiler) bumpExtended(p, key, val string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.entries[p].Extended[key] = []byte(val)
|
||||
}
|
||||
|
||||
func (f *fakeFiler) allWritten() []*filerpb.Entry {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]*filerpb.Entry(nil), f.written...)
|
||||
}
|
||||
|
||||
// fakeBlobs is an in-memory needle store.
|
||||
type fakeBlobs struct {
|
||||
mu sync.Mutex
|
||||
data map[string][]byte
|
||||
next int
|
||||
puts int
|
||||
gets int
|
||||
failPut func(n int) error
|
||||
}
|
||||
|
||||
func newFakeBlobs() *fakeBlobs { return &fakeBlobs{data: map[string][]byte{}} }
|
||||
|
||||
func (b *fakeBlobs) Put(_ context.Context, d []byte) (string, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.puts++
|
||||
if b.failPut != nil {
|
||||
if err := b.failPut(b.puts); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
b.next++
|
||||
fid := fmt.Sprintf("3,%08x", b.next)
|
||||
b.data[fid] = append([]byte(nil), d...)
|
||||
return fid, nil
|
||||
}
|
||||
|
||||
func (b *fakeBlobs) Get(_ context.Context, fid string) ([]byte, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.gets++
|
||||
d, ok := b.data[fid]
|
||||
if !ok {
|
||||
return nil, errors.New("fake: no such fid " + fid)
|
||||
}
|
||||
return append([]byte(nil), d...), nil
|
||||
}
|
||||
|
||||
func (b *fakeBlobs) counts() (puts, gets, stored int) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.puts, b.gets, len(b.data)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
||||
// Minimal subset of SeaweedFS filer.proto (seaweed-mono 8b582399d,
|
||||
// enterprise/weed/pb/filer.proto) used by the chunkstore PoC client.
|
||||
//
|
||||
// Package, service, message names and field numbers are copied verbatim so
|
||||
// the wire format and the gRPC method paths (/filer_pb.SeaweedFiler/...)
|
||||
// match a real filer. Fields chunkstore never reads or writes are omitted;
|
||||
// protobuf keeps them as unknown fields on decode.
|
||||
//
|
||||
// Regenerate (from this directory):
|
||||
// protoc --go_out=. --go_opt=paths=source_relative \
|
||||
// --go-grpc_out=. --go-grpc_opt=paths=source_relative filer_subset.proto
|
||||
syntax = "proto3";
|
||||
|
||||
package filer_pb;
|
||||
|
||||
option go_package = "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb";
|
||||
|
||||
service SeaweedFiler {
|
||||
rpc LookupDirectoryEntry (LookupDirectoryEntryRequest) returns (LookupDirectoryEntryResponse) {}
|
||||
rpc CreateEntry (CreateEntryRequest) returns (CreateEntryResponse) {}
|
||||
rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {}
|
||||
rpc DeleteEntry (DeleteEntryRequest) returns (DeleteEntryResponse) {}
|
||||
rpc AssignVolume (AssignVolumeRequest) returns (AssignVolumeResponse) {}
|
||||
rpc LookupVolume (LookupVolumeRequest) returns (LookupVolumeResponse) {}
|
||||
}
|
||||
|
||||
message LookupDirectoryEntryRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
}
|
||||
|
||||
message LookupDirectoryEntryResponse {
|
||||
Entry entry = 1;
|
||||
}
|
||||
|
||||
message Entry {
|
||||
string name = 1;
|
||||
bool is_directory = 2;
|
||||
repeated FileChunk chunks = 3;
|
||||
FuseAttributes attributes = 4;
|
||||
map<string, bytes> extended = 5;
|
||||
bytes content = 9; // if not empty, the file content
|
||||
}
|
||||
|
||||
// Only file_id is modelled: chunkstore never writes chunks, and reads them
|
||||
// only to refuse a HEAD entry that carries any.
|
||||
message FileChunk {
|
||||
string file_id = 1;
|
||||
}
|
||||
|
||||
message FuseAttributes {
|
||||
uint64 file_size = 1;
|
||||
int64 mtime = 2; // unix time in seconds
|
||||
uint32 file_mode = 3;
|
||||
uint32 uid = 4;
|
||||
uint32 gid = 5;
|
||||
int64 crtime = 6; // unix time in seconds
|
||||
string mime = 7;
|
||||
}
|
||||
|
||||
message CreateEntryRequest {
|
||||
string directory = 1;
|
||||
Entry entry = 2;
|
||||
bool o_excl = 3;
|
||||
bool is_from_other_cluster = 4;
|
||||
repeated int32 signatures = 5;
|
||||
bool skip_check_parent_directory = 6;
|
||||
}
|
||||
|
||||
enum FilerError {
|
||||
OK = 0;
|
||||
ENTRY_NAME_TOO_LONG = 1;
|
||||
PARENT_IS_FILE = 2;
|
||||
EXISTING_IS_DIRECTORY = 3;
|
||||
EXISTING_IS_FILE = 4;
|
||||
ENTRY_ALREADY_EXISTS = 5;
|
||||
PRECONDITION_FAILED = 6;
|
||||
READ_ONLY = 7;
|
||||
}
|
||||
|
||||
message CreateEntryResponse {
|
||||
string error = 1;
|
||||
FilerError error_code = 3;
|
||||
}
|
||||
|
||||
message UpdateEntryRequest {
|
||||
string directory = 1;
|
||||
Entry entry = 2;
|
||||
bool is_from_other_cluster = 3;
|
||||
repeated int32 signatures = 4;
|
||||
map<string, bytes> expected_extended = 5;
|
||||
}
|
||||
|
||||
message UpdateEntryResponse {
|
||||
}
|
||||
|
||||
message DeleteEntryRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
bool is_delete_data = 4;
|
||||
bool is_recursive = 5;
|
||||
map<string, bytes> expected_extended = 12;
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
string error = 1;
|
||||
}
|
||||
|
||||
message AssignVolumeRequest {
|
||||
int32 count = 1;
|
||||
string collection = 2;
|
||||
string replication = 3;
|
||||
int32 ttl_sec = 4;
|
||||
string data_center = 5;
|
||||
string path = 6;
|
||||
string rack = 7;
|
||||
string disk_type = 8;
|
||||
string data_node = 9;
|
||||
uint64 expected_data_size = 10;
|
||||
}
|
||||
|
||||
message AssignVolumeResponse {
|
||||
string file_id = 1;
|
||||
int32 count = 4;
|
||||
string auth = 5;
|
||||
string collection = 6;
|
||||
string replication = 7;
|
||||
string error = 8;
|
||||
Location location = 9;
|
||||
repeated Location replicas = 10;
|
||||
bool fsync = 11;
|
||||
FilerError error_code = 12;
|
||||
}
|
||||
|
||||
message LookupVolumeRequest {
|
||||
repeated string volume_ids = 1;
|
||||
}
|
||||
|
||||
message Locations {
|
||||
repeated Location locations = 1;
|
||||
}
|
||||
|
||||
message Location {
|
||||
string url = 1;
|
||||
string public_url = 2;
|
||||
uint32 grpc_port = 3;
|
||||
string data_center = 4;
|
||||
bool data_in_remote = 5;
|
||||
}
|
||||
|
||||
message LookupVolumeResponse {
|
||||
map<string, Locations> locations_map = 1;
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Minimal subset of SeaweedFS filer.proto (seaweed-mono 8b582399d,
|
||||
// enterprise/weed/pb/filer.proto) used by the chunkstore PoC client.
|
||||
//
|
||||
// Package, service, message names and field numbers are copied verbatim so
|
||||
// the wire format and the gRPC method paths (/filer_pb.SeaweedFiler/...)
|
||||
// match a real filer. Fields chunkstore never reads or writes are omitted;
|
||||
// protobuf keeps them as unknown fields on decode.
|
||||
//
|
||||
// Regenerate (from this directory):
|
||||
// protoc --go_out=. --go_opt=paths=source_relative \
|
||||
// --go-grpc_out=. --go-grpc_opt=paths=source_relative filer_subset.proto
|
||||
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v7.34.1
|
||||
// source: filer_subset.proto
|
||||
|
||||
package filerpb
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
SeaweedFiler_LookupDirectoryEntry_FullMethodName = "/filer_pb.SeaweedFiler/LookupDirectoryEntry"
|
||||
SeaweedFiler_CreateEntry_FullMethodName = "/filer_pb.SeaweedFiler/CreateEntry"
|
||||
SeaweedFiler_UpdateEntry_FullMethodName = "/filer_pb.SeaweedFiler/UpdateEntry"
|
||||
SeaweedFiler_DeleteEntry_FullMethodName = "/filer_pb.SeaweedFiler/DeleteEntry"
|
||||
SeaweedFiler_AssignVolume_FullMethodName = "/filer_pb.SeaweedFiler/AssignVolume"
|
||||
SeaweedFiler_LookupVolume_FullMethodName = "/filer_pb.SeaweedFiler/LookupVolume"
|
||||
)
|
||||
|
||||
// SeaweedFilerClient is the client API for SeaweedFiler service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type SeaweedFilerClient interface {
|
||||
LookupDirectoryEntry(ctx context.Context, in *LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*LookupDirectoryEntryResponse, error)
|
||||
CreateEntry(ctx context.Context, in *CreateEntryRequest, opts ...grpc.CallOption) (*CreateEntryResponse, error)
|
||||
UpdateEntry(ctx context.Context, in *UpdateEntryRequest, opts ...grpc.CallOption) (*UpdateEntryResponse, error)
|
||||
DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error)
|
||||
AssignVolume(ctx context.Context, in *AssignVolumeRequest, opts ...grpc.CallOption) (*AssignVolumeResponse, error)
|
||||
LookupVolume(ctx context.Context, in *LookupVolumeRequest, opts ...grpc.CallOption) (*LookupVolumeResponse, error)
|
||||
}
|
||||
|
||||
type seaweedFilerClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewSeaweedFilerClient(cc grpc.ClientConnInterface) SeaweedFilerClient {
|
||||
return &seaweedFilerClient{cc}
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) LookupDirectoryEntry(ctx context.Context, in *LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*LookupDirectoryEntryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(LookupDirectoryEntryResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_LookupDirectoryEntry_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) CreateEntry(ctx context.Context, in *CreateEntryRequest, opts ...grpc.CallOption) (*CreateEntryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(CreateEntryResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_CreateEntry_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) UpdateEntry(ctx context.Context, in *UpdateEntryRequest, opts ...grpc.CallOption) (*UpdateEntryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(UpdateEntryResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_UpdateEntry_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeleteEntryResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_DeleteEntry_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) AssignVolume(ctx context.Context, in *AssignVolumeRequest, opts ...grpc.CallOption) (*AssignVolumeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(AssignVolumeResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_AssignVolume_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *seaweedFilerClient) LookupVolume(ctx context.Context, in *LookupVolumeRequest, opts ...grpc.CallOption) (*LookupVolumeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(LookupVolumeResponse)
|
||||
err := c.cc.Invoke(ctx, SeaweedFiler_LookupVolume_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SeaweedFilerServer is the server API for SeaweedFiler service.
|
||||
// All implementations must embed UnimplementedSeaweedFilerServer
|
||||
// for forward compatibility.
|
||||
type SeaweedFilerServer interface {
|
||||
LookupDirectoryEntry(context.Context, *LookupDirectoryEntryRequest) (*LookupDirectoryEntryResponse, error)
|
||||
CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error)
|
||||
UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error)
|
||||
DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error)
|
||||
AssignVolume(context.Context, *AssignVolumeRequest) (*AssignVolumeResponse, error)
|
||||
LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error)
|
||||
mustEmbedUnimplementedSeaweedFilerServer()
|
||||
}
|
||||
|
||||
// UnimplementedSeaweedFilerServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedSeaweedFilerServer struct{}
|
||||
|
||||
func (UnimplementedSeaweedFilerServer) LookupDirectoryEntry(context.Context, *LookupDirectoryEntryRequest) (*LookupDirectoryEntryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method LookupDirectoryEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method CreateEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method UpdateEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteEntry not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) AssignVolume(context.Context, *AssignVolumeRequest) (*AssignVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method AssignVolume not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method LookupVolume not implemented")
|
||||
}
|
||||
func (UnimplementedSeaweedFilerServer) mustEmbedUnimplementedSeaweedFilerServer() {}
|
||||
func (UnimplementedSeaweedFilerServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeSeaweedFilerServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to SeaweedFilerServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeSeaweedFilerServer interface {
|
||||
mustEmbedUnimplementedSeaweedFilerServer()
|
||||
}
|
||||
|
||||
func RegisterSeaweedFilerServer(s grpc.ServiceRegistrar, srv SeaweedFilerServer) {
|
||||
// If the following call panics, it indicates UnimplementedSeaweedFilerServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&SeaweedFiler_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_LookupDirectoryEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LookupDirectoryEntryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).LookupDirectoryEntry(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_LookupDirectoryEntry_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).LookupDirectoryEntry(ctx, req.(*LookupDirectoryEntryRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_CreateEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(CreateEntryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).CreateEntry(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_CreateEntry_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).CreateEntry(ctx, req.(*CreateEntryRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_UpdateEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(UpdateEntryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).UpdateEntry(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_UpdateEntry_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).UpdateEntry(ctx, req.(*UpdateEntryRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_DeleteEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DeleteEntryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).DeleteEntry(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_DeleteEntry_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).DeleteEntry(ctx, req.(*DeleteEntryRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_AssignVolume_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(AssignVolumeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).AssignVolume(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_AssignVolume_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).AssignVolume(ctx, req.(*AssignVolumeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _SeaweedFiler_LookupVolume_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LookupVolumeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SeaweedFilerServer).LookupVolume(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SeaweedFiler_LookupVolume_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SeaweedFilerServer).LookupVolume(ctx, req.(*LookupVolumeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// SeaweedFiler_ServiceDesc is the grpc.ServiceDesc for SeaweedFiler service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "filer_pb.SeaweedFiler",
|
||||
HandlerType: (*SeaweedFilerServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "LookupDirectoryEntry",
|
||||
Handler: _SeaweedFiler_LookupDirectoryEntry_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "CreateEntry",
|
||||
Handler: _SeaweedFiler_CreateEntry_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "UpdateEntry",
|
||||
Handler: _SeaweedFiler_UpdateEntry_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "DeleteEntry",
|
||||
Handler: _SeaweedFiler_DeleteEntry_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "AssignVolume",
|
||||
Handler: _SeaweedFiler_AssignVolume_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "LookupVolume",
|
||||
Handler: _SeaweedFiler_LookupVolume_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "filer_subset.proto",
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// Filer is the metadata side chunkstore needs from a SeaweedFS filer: one
|
||||
// entry per volume HEAD (and per snapshot), written with a precondition.
|
||||
//
|
||||
// The two SeaweedFS failure styles are normalised here:
|
||||
// - CreateEntry reports a failed o_excl / condition in the response's
|
||||
// ErrorCode with a nil gRPC error;
|
||||
// - UpdateEntry reports a failed expected_extended as gRPC FailedPrecondition.
|
||||
//
|
||||
// Both become ErrExists / ErrPrecondition so callers branch on one thing.
|
||||
type Filer interface {
|
||||
// LookupEntry returns ErrNotFound when dir/name does not exist.
|
||||
LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error)
|
||||
// CreateEntry with oExcl returns ErrExists when dir/name already exists.
|
||||
CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error
|
||||
// UpdateEntry applies e only if every expected extended key still holds
|
||||
// the given value; otherwise ErrPrecondition. ErrNotFound if absent.
|
||||
UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error
|
||||
}
|
||||
|
||||
// Blobs stores immutable chunk payloads as SeaweedFS needles.
|
||||
type Blobs interface {
|
||||
// Put stores data as a new needle and returns its fid. A fid is never
|
||||
// reused, so a Put can never overwrite data another manifest references.
|
||||
Put(ctx context.Context, data []byte) (fid string, err error)
|
||||
// Get returns the whole needle payload.
|
||||
Get(ctx context.Context, fid string) ([]byte, error)
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrNotFound: the filer entry does not exist.
|
||||
ErrNotFound = errors.New("chunkstore: entry not found")
|
||||
// ErrExists: an exclusive create found the entry already there.
|
||||
ErrExists = errors.New("chunkstore: entry already exists")
|
||||
// ErrPrecondition: a conditional write lost (HEAD changed under us).
|
||||
ErrPrecondition = errors.New("chunkstore: precondition failed")
|
||||
)
|
||||
@@ -0,0 +1,265 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// SWFSConfig configures the minimal SeaweedFS client.
|
||||
type SWFSConfig struct {
|
||||
FilerGRPC string // filer gRPC address, host:port (default: filer HTTP port + 10000)
|
||||
Collection string // collection for chunk needles (empty = filer default / storage rule)
|
||||
Replication string // replication for chunk needles (empty = filer default / storage rule)
|
||||
AssignPath string // path passed to AssignVolume so filer storage rules (fsync, collection) apply
|
||||
HTTPTimeout time.Duration
|
||||
}
|
||||
|
||||
// SWFS is a minimal SeaweedFS client built for the chunkstore PoC:
|
||||
// - filer gRPC (vendored proto subset, package filerpb) for HEAD/snapshot
|
||||
// entries, AssignVolume and LookupVolume;
|
||||
// - plain HTTP to volume servers for needle upload (POST) and read (GET).
|
||||
//
|
||||
// It deliberately does not import the SeaweedFS module.
|
||||
type SWFS struct {
|
||||
cfg SWFSConfig
|
||||
conn *grpc.ClientConn
|
||||
fc filerpb.SeaweedFilerClient
|
||||
http *http.Client
|
||||
|
||||
mu sync.Mutex
|
||||
vidCache map[string][]string // volume id -> volume server urls
|
||||
}
|
||||
|
||||
// filerNotFoundText is the text of seaweed-mono's filer_pb.ErrNotFound
|
||||
// (pb/filer_pb/filer_pb_helper.go:261). LookupDirectoryEntry returns that raw
|
||||
// sentinel, which crosses gRPC as codes.Unknown carrying only this text.
|
||||
const filerNotFoundText = "no entry is found in filer store"
|
||||
|
||||
// DialSWFS connects to the filer's gRPC port. The connection is lazy.
|
||||
func DialSWFS(cfg SWFSConfig) (*SWFS, error) {
|
||||
if cfg.FilerGRPC == "" {
|
||||
return nil, errors.New("chunkstore: filer gRPC address required")
|
||||
}
|
||||
if cfg.HTTPTimeout == 0 {
|
||||
cfg.HTTPTimeout = 60 * time.Second
|
||||
}
|
||||
conn, err := grpc.NewClient(cfg.FilerGRPC,
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(64<<20), grpc.MaxCallSendMsgSize(64<<20)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("chunkstore: dial filer %s: %w", cfg.FilerGRPC, err)
|
||||
}
|
||||
return &SWFS{
|
||||
cfg: cfg,
|
||||
conn: conn,
|
||||
fc: filerpb.NewSeaweedFilerClient(conn),
|
||||
http: &http.Client{Timeout: cfg.HTTPTimeout},
|
||||
vidCache: map[string][]string{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Close releases the gRPC connection.
|
||||
func (c *SWFS) Close() error {
|
||||
if c.conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// LookupEntry implements Filer.
|
||||
func (c *SWFS) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
resp, err := c.fc.LookupDirectoryEntry(ctx, &filerpb.LookupDirectoryEntryRequest{Directory: dir, Name: name})
|
||||
if err != nil {
|
||||
if st, ok := status.FromError(err); ok {
|
||||
if st.Code() == codes.NotFound ||
|
||||
(st.Code() == codes.Unknown && strings.Contains(st.Message(), filerNotFoundText)) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("chunkstore: lookup %s/%s: %w", dir, name, err)
|
||||
}
|
||||
if resp.GetEntry() == nil {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return resp.Entry, nil
|
||||
}
|
||||
|
||||
// CreateEntry implements Filer. A failed o_excl or condition is reported by
|
||||
// the filer in CreateEntryResponse.ErrorCode with a nil gRPC error.
|
||||
func (c *SWFS) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
|
||||
resp, err := c.fc.CreateEntry(ctx, &filerpb.CreateEntryRequest{Directory: dir, Entry: e, OExcl: oExcl})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.FailedPrecondition {
|
||||
return fmt.Errorf("%w: create %s/%s: %v", ErrPrecondition, dir, e.GetName(), err)
|
||||
}
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %w", dir, e.GetName(), err)
|
||||
}
|
||||
switch resp.GetErrorCode() {
|
||||
case filerpb.FilerError_OK:
|
||||
if resp.GetError() != "" {
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %s", dir, e.GetName(), resp.GetError())
|
||||
}
|
||||
return nil
|
||||
case filerpb.FilerError_ENTRY_ALREADY_EXISTS:
|
||||
return fmt.Errorf("%w: %s/%s", ErrExists, dir, e.GetName())
|
||||
case filerpb.FilerError_PRECONDITION_FAILED:
|
||||
return fmt.Errorf("%w: create %s/%s", ErrPrecondition, dir, e.GetName())
|
||||
default:
|
||||
return fmt.Errorf("chunkstore: create %s/%s: %s (%s)", dir, e.GetName(), resp.GetError(), resp.GetErrorCode())
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateEntry implements Filer. A failed expected_extended comes back as gRPC
|
||||
// FailedPrecondition. Any other error is ambiguous (the write may or may not
|
||||
// have applied) and is returned unwrapped from the sentinels.
|
||||
func (c *SWFS) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
_, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch status.Code(err) {
|
||||
case codes.FailedPrecondition:
|
||||
return fmt.Errorf("%w: update %s/%s: %v", ErrPrecondition, dir, e.GetName(), err)
|
||||
case codes.NotFound:
|
||||
return fmt.Errorf("%w: update %s/%s", ErrNotFound, dir, e.GetName())
|
||||
}
|
||||
return fmt.Errorf("chunkstore: update %s/%s: %w", dir, e.GetName(), err)
|
||||
}
|
||||
|
||||
// Put implements Blobs: filer AssignVolume, then a raw HTTP POST of data to
|
||||
// the assigned volume server. The body is sent as application/octet-stream
|
||||
// with no Content-Encoding, so the volume server stores it uncompressed (its
|
||||
// auto-compress only fires for types it is sure about; octet-stream is
|
||||
// cleared to "" first, storage/needle/needle_parse_upload.go:116-119).
|
||||
func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) {
|
||||
ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{
|
||||
Count: 1,
|
||||
Collection: c.cfg.Collection,
|
||||
Replication: c.cfg.Replication,
|
||||
Path: c.cfg.AssignPath,
|
||||
ExpectedDataSize: uint64(len(data)),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("chunkstore: assign: %w", err)
|
||||
}
|
||||
if ar.GetError() != "" {
|
||||
return "", fmt.Errorf("chunkstore: assign: %s", ar.GetError())
|
||||
}
|
||||
if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" {
|
||||
return "", fmt.Errorf("chunkstore: assign returned no fid/location")
|
||||
}
|
||||
u := "http://" + ar.Location.Url + "/" + ar.FileId
|
||||
if ar.GetFsync() {
|
||||
u += "?fsync=true"
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
if ar.GetAuth() != "" {
|
||||
req.Header.Set("Authorization", "BEARER "+ar.Auth)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("chunkstore: upload %s: %w", ar.FileId, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return "", fmt.Errorf("chunkstore: upload %s: http %d: %s", ar.FileId, resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
var ur struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(body, &ur) == nil && ur.Error != "" {
|
||||
return "", fmt.Errorf("chunkstore: upload %s: %s", ar.FileId, ur.Error)
|
||||
}
|
||||
return ar.FileId, nil
|
||||
}
|
||||
|
||||
// Get implements Blobs: resolve the fid's volume through the filer, then GET
|
||||
// the needle from each location until one answers.
|
||||
func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) {
|
||||
vid, _, ok := strings.Cut(fid, ",")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("chunkstore: bad fid %q", fid)
|
||||
}
|
||||
urls, err := c.lookupVolume(ctx, vid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var lastErr error
|
||||
for _, host := range urls {
|
||||
b, err := c.getFrom(ctx, host, fid)
|
||||
if err == nil {
|
||||
return b, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.vidCache, vid)
|
||||
c.mu.Unlock()
|
||||
return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr)
|
||||
}
|
||||
|
||||
func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+host+"/"+fid, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("http %d from %s", resp.StatusCode, host)
|
||||
}
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) {
|
||||
c.mu.Lock()
|
||||
urls, ok := c.vidCache[vid]
|
||||
c.mu.Unlock()
|
||||
if ok && len(urls) > 0 {
|
||||
return urls, nil
|
||||
}
|
||||
resp, err := c.fc.LookupVolume(ctx, &filerpb.LookupVolumeRequest{VolumeIds: []string{vid}})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err)
|
||||
}
|
||||
for _, l := range resp.GetLocationsMap()[vid].GetLocations() {
|
||||
if l.GetUrl() != "" {
|
||||
urls = append(urls, l.Url)
|
||||
}
|
||||
}
|
||||
if len(urls) == 0 {
|
||||
return nil, fmt.Errorf("chunkstore: volume %s has no locations", vid)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.vidCache[vid] = urls
|
||||
c.mu.Unlock()
|
||||
return urls, nil
|
||||
}
|
||||
|
||||
var (
|
||||
_ Filer = (*SWFS)(nil)
|
||||
_ Blobs = (*SWFS)(nil)
|
||||
)
|
||||
@@ -0,0 +1,270 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// fakeFilerGRPC answers the real gRPC method paths with canned replies so the
|
||||
// client's error mapping is tested against both SeaweedFS failure styles.
|
||||
type fakeFilerGRPC struct {
|
||||
filerpb.UnimplementedSeaweedFilerServer
|
||||
|
||||
mu sync.Mutex
|
||||
createResp *filerpb.CreateEntryResponse
|
||||
createErr error
|
||||
updateErr error
|
||||
lookupResp *filerpb.LookupDirectoryEntryResponse
|
||||
lookupErr error
|
||||
assignResp *filerpb.AssignVolumeResponse
|
||||
lookupVol *filerpb.LookupVolumeResponse
|
||||
|
||||
lastCreate *filerpb.CreateEntryRequest
|
||||
lastUpdate *filerpb.UpdateEntryRequest
|
||||
lastAssign *filerpb.AssignVolumeRequest
|
||||
}
|
||||
|
||||
func (f *fakeFilerGRPC) CreateEntry(_ context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.lastCreate = r
|
||||
if f.createErr != nil {
|
||||
return nil, f.createErr
|
||||
}
|
||||
if f.createResp != nil {
|
||||
return f.createResp, nil
|
||||
}
|
||||
return &filerpb.CreateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeFilerGRPC) UpdateEntry(_ context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.lastUpdate = r
|
||||
if f.updateErr != nil {
|
||||
return nil, f.updateErr
|
||||
}
|
||||
return &filerpb.UpdateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeFilerGRPC) LookupDirectoryEntry(_ context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.lookupErr != nil {
|
||||
return nil, f.lookupErr
|
||||
}
|
||||
return f.lookupResp, nil
|
||||
}
|
||||
|
||||
func (f *fakeFilerGRPC) AssignVolume(_ context.Context, r *filerpb.AssignVolumeRequest) (*filerpb.AssignVolumeResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.lastAssign = r
|
||||
return f.assignResp, nil
|
||||
}
|
||||
|
||||
func (f *fakeFilerGRPC) LookupVolume(_ context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.lookupVol, nil
|
||||
}
|
||||
|
||||
func startFakeFiler(t *testing.T, f *fakeFilerGRPC) *SWFS {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
filerpb.RegisterSeaweedFilerServer(srv, f)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
c, err := DialSWFS(SWFSConfig{FilerGRPC: lis.Addr().String(), Collection: "swblock", Replication: "000", AssignPath: "/swblock/vols/v1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = c.Close() })
|
||||
return c
|
||||
}
|
||||
|
||||
func TestSWFS_CreateEntry_ErrorCodeStyle(t *testing.T) {
|
||||
f := &fakeFilerGRPC{}
|
||||
c := startFakeFiler(t, f)
|
||||
ctx := context.Background()
|
||||
|
||||
// CreateEntry reports o_excl loss in ErrorCode with a nil gRPC error
|
||||
// (seaweed-mono server/filer_grpc_server.go CreateEntry).
|
||||
f.createResp = &filerpb.CreateEntryResponse{Error: "exists", ErrorCode: filerpb.FilerError_ENTRY_ALREADY_EXISTS}
|
||||
err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true)
|
||||
if !errors.Is(err, ErrExists) {
|
||||
t.Fatalf("ENTRY_ALREADY_EXISTS: got %v want ErrExists", err)
|
||||
}
|
||||
if !f.lastCreate.OExcl {
|
||||
t.Fatalf("o_excl not sent")
|
||||
}
|
||||
|
||||
f.createResp = &filerpb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filerpb.FilerError_PRECONDITION_FAILED}
|
||||
if err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true); !errors.Is(err, ErrPrecondition) {
|
||||
t.Fatalf("PRECONDITION_FAILED: got %v want ErrPrecondition", err)
|
||||
}
|
||||
|
||||
// Any other non-empty Error is still a failure, never silent success.
|
||||
f.createResp = &filerpb.CreateEntryResponse{Error: "parent is a file", ErrorCode: filerpb.FilerError_PARENT_IS_FILE}
|
||||
if err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true); err == nil {
|
||||
t.Fatalf("PARENT_IS_FILE: got nil error")
|
||||
}
|
||||
|
||||
f.createResp = &filerpb.CreateEntryResponse{}
|
||||
if err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true); err != nil {
|
||||
t.Fatalf("ok create: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSWFS_UpdateEntry_FailedPreconditionStyle(t *testing.T) {
|
||||
f := &fakeFilerGRPC{}
|
||||
c := startFakeFiler(t, f)
|
||||
ctx := context.Background()
|
||||
exp := map[string][]byte{"swb.gen": []byte("3"), "swb.epoch": []byte("1")}
|
||||
|
||||
f.updateErr = status.Error(codes.FailedPrecondition, `extended attribute "swb.gen" changed`)
|
||||
if err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp); !errors.Is(err, ErrPrecondition) {
|
||||
t.Fatalf("FailedPrecondition: got %v want ErrPrecondition", err)
|
||||
}
|
||||
if string(f.lastUpdate.ExpectedExtended["swb.gen"]) != "3" || string(f.lastUpdate.ExpectedExtended["swb.epoch"]) != "1" {
|
||||
t.Fatalf("expected_extended not sent: %v", f.lastUpdate.ExpectedExtended)
|
||||
}
|
||||
|
||||
f.updateErr = status.Error(codes.NotFound, "not found /d/x")
|
||||
if err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("NotFound: got %v want ErrNotFound", err)
|
||||
}
|
||||
|
||||
f.updateErr = status.Error(codes.Unavailable, "down")
|
||||
err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp)
|
||||
if err == nil || errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("Unavailable: got %v, want a plain (ambiguous) error", err)
|
||||
}
|
||||
|
||||
f.updateErr = nil
|
||||
if err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp); err != nil {
|
||||
t.Fatalf("ok update: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSWFS_LookupEntry_NotFoundStyles(t *testing.T) {
|
||||
f := &fakeFilerGRPC{}
|
||||
c := startFakeFiler(t, f)
|
||||
ctx := context.Background()
|
||||
|
||||
// The filer returns its raw sentinel, which crosses gRPC as Unknown.
|
||||
f.lookupErr = errors.New("filer: no entry is found in filer store")
|
||||
if _, err := c.LookupEntry(ctx, "/d", "x"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("Unknown+sentinel: got %v want ErrNotFound", err)
|
||||
}
|
||||
f.lookupErr = status.Error(codes.NotFound, "nope")
|
||||
if _, err := c.LookupEntry(ctx, "/d", "x"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("NotFound: got %v want ErrNotFound", err)
|
||||
}
|
||||
f.lookupErr = nil
|
||||
f.lookupResp = &filerpb.LookupDirectoryEntryResponse{Entry: &filerpb.Entry{Name: "x", Content: []byte("m")}}
|
||||
e, err := c.LookupEntry(ctx, "/d", "x")
|
||||
if err != nil || string(e.Content) != "m" {
|
||||
t.Fatalf("found: %v %v", e, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSWFS_PutGet_RawUncompressedUpload(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
stored = map[string][]byte{}
|
||||
gotReq *http.Request
|
||||
)
|
||||
vol := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fid := strings.TrimPrefix(r.URL.Path, "/")
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
gotReq = r.Clone(context.Background())
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
stored[fid] = b
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"size":` + "1" + `}`))
|
||||
case http.MethodGet:
|
||||
b, ok := stored[fid]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(b)
|
||||
}
|
||||
}))
|
||||
defer vol.Close()
|
||||
host := strings.TrimPrefix(vol.URL, "http://")
|
||||
|
||||
f := &fakeFilerGRPC{
|
||||
assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef", Auth: "tok", Fsync: true, Location: &filerpb.Location{Url: host}},
|
||||
lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: host}}}}},
|
||||
}
|
||||
c := startFakeFiler(t, f)
|
||||
ctx := context.Background()
|
||||
// Text-looking data: must still go up raw (no gzip, no type sniffing).
|
||||
data := bytes.Repeat([]byte("hello world\n"), 1000)
|
||||
fid, err := c.Put(ctx, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fid != "7,01abcdef" {
|
||||
t.Fatalf("fid %q", fid)
|
||||
}
|
||||
if f.lastAssign.Collection != "swblock" || f.lastAssign.Path != "/swblock/vols/v1" || f.lastAssign.Count != 1 {
|
||||
t.Fatalf("assign request %+v", f.lastAssign)
|
||||
}
|
||||
mu.Lock()
|
||||
r := gotReq
|
||||
mu.Unlock()
|
||||
if r.URL.Query().Get("fsync") != "true" {
|
||||
t.Fatalf("fsync not carried onto upload: %s", r.URL.RawQuery)
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); ct != "application/octet-stream" {
|
||||
t.Fatalf("content-type %q", ct)
|
||||
}
|
||||
if ce := r.Header.Get("Content-Encoding"); ce != "" {
|
||||
t.Fatalf("content-encoding %q, want none", ce)
|
||||
}
|
||||
if a := r.Header.Get("Authorization"); a != "BEARER tok" {
|
||||
t.Fatalf("authorization %q", a)
|
||||
}
|
||||
got, err := c.Get(ctx, fid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, data) {
|
||||
t.Fatalf("get mismatch")
|
||||
}
|
||||
if _, err := c.Get(ctx, "7,0000dead"); err == nil {
|
||||
t.Fatalf("get of missing fid returned nil error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSWFS_Put_AssignErrorIsFailure(t *testing.T) {
|
||||
f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{Error: "no free volumes"}}
|
||||
c := startFakeFiler(t, f)
|
||||
if _, err := c.Put(context.Background(), []byte("x")); err == nil {
|
||||
t.Fatalf("assign error swallowed")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user