mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
mount: read SSE-S3 objects through the S3 gateway (#12909)
* mount: read SSE-S3 objects through an authenticated S3 gateway * mount: check each comma-joined mount option against -sseS3ReadEndpoint Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: read a mounted version file by its object key and version id Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: read a current null-version object without s3:GetObjectVersion Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: declare -sseS3ReadEndpoint with the other mount options so weed fuse accepts it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: require the canonical bucket path as the root of an SSE-S3 read mount Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: fall back to the null version when the current object is another version Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * master: list the S3 endpoint each S3 gateway advertises Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: advertise the gateway's S3 endpoint to the master Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: find the S3 gateway through the masters instead of -sseS3ReadEndpoint -sseS3Read turns gateway reads on. The reader lists the S3 endpoints the filer's masters have registered, prefers HTTPS, and picks another gateway when the current one cannot be reached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: retry an unreachable S3 gateway read on a different gateway Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: warn when -sseS3Read falls back to a plain-HTTP gateway Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: do not retry an unreachable HTTPS gateway over plain HTTP Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: tell HTTPS gateways apart by the parsed URL scheme An S3 gateway advertised as HTTPS://host lost the HTTPS preference and the plain-HTTP fallback guard, since the check matched the raw string. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
25 files changed
+746
-24
No files matched your search
@@ -25,6 +25,7 @@ fn registration(client_addr: &str, filer_group: &str, metrics_port: u16) -> Keep
|
||||
leave_lock_ring: false,
|
||||
metrics_port: metrics_port.into(),
|
||||
lance_port: 0,
|
||||
s3_endpoint: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -236,6 +236,8 @@ message KeepConnectedRequest {
|
||||
uint32 metrics_port = 9;
|
||||
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
|
||||
uint32 lance_port = 10;
|
||||
// URL an S3 gateway serves the S3 API on, or empty when it advertises none.
|
||||
string s3_endpoint = 11;
|
||||
}
|
||||
|
||||
message VolumeLocation {
|
||||
@@ -562,6 +564,7 @@ message ListClusterNodesResponse {
|
||||
string version = 2;
|
||||
int64 created_at_ns = 4;
|
||||
uint32 lance_port = 7;
|
||||
string s3_endpoint = 8;
|
||||
string data_center = 5;
|
||||
string rack = 6;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ type ClusterNode struct {
|
||||
Address pb.ServerAddress
|
||||
Version string
|
||||
LancePort atomic.Uint32 // set after the node is listed, so read atomically
|
||||
S3Endpoint atomic.Pointer[string]
|
||||
counter int
|
||||
CreatedTs time.Time
|
||||
DataCenter DataCenter
|
||||
@@ -217,3 +218,22 @@ func (cluster *Cluster) SetLancePort(ns string, address pb.ServerAddress, port u
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SetS3Endpoint records the URL a registered S3 gateway serves the S3 API on.
|
||||
func (cluster *Cluster) SetS3Endpoint(ns string, address pb.ServerAddress, endpoint string) {
|
||||
g := cluster.s3Groups
|
||||
g.RLock()
|
||||
defer g.RUnlock()
|
||||
if m := g.getGroupMembers(FilerGroupName(ns), false); m != nil {
|
||||
if node, found := m.members[address]; found {
|
||||
node.S3Endpoint.Store(&endpoint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (node *ClusterNode) GetS3Endpoint() string {
|
||||
if endpoint := node.S3Endpoint.Load(); endpoint != nil {
|
||||
return *endpoint
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -13,13 +13,15 @@ func TestSetLancePort(t *testing.T) {
|
||||
c.s3Groups.getGroupMembers("group", true).members[gateway] = &ClusterNode{Address: gateway}
|
||||
|
||||
c.SetLancePort("group", gateway, 9101)
|
||||
c.SetS3Endpoint("group", gateway, "https://s3.example.com")
|
||||
// A gateway of another group, or one that never registered, records nothing.
|
||||
c.SetLancePort("", gateway, 9200)
|
||||
c.SetLancePort("group", pb.ServerAddress("10.0.0.31:18333"), 9300)
|
||||
c.SetS3Endpoint("", gateway, "http://other:8333")
|
||||
|
||||
nodes := c.ListClusterNode("group", S3Type)
|
||||
if len(nodes) != 1 || nodes[0].LancePort.Load() != 9101 {
|
||||
t.Fatalf("want the gateway listed with port 9101, got %d nodes", len(nodes))
|
||||
if len(nodes) != 1 || nodes[0].LancePort.Load() != 9101 || nodes[0].GetS3Endpoint() != "https://s3.example.com" {
|
||||
t.Fatalf("want the gateway listed with port 9101 and its S3 endpoint, got %d nodes", len(nodes))
|
||||
}
|
||||
if nodes := c.ListClusterNode("", S3Type); len(nodes) != 0 {
|
||||
t.Fatalf("SetLancePort must not register a node, got %d", len(nodes))
|
||||
|
||||
@@ -214,6 +214,12 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
}
|
||||
case "volumeServerAccess":
|
||||
mountOptions.volumeServerAccess = ¶meter.value
|
||||
case "sseS3Read":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.sseS3Read = &parsed
|
||||
} else {
|
||||
panic(fmt.Errorf("sseS3Read: %s", err))
|
||||
}
|
||||
case "map.uid":
|
||||
mountOptions.uidMap = ¶meter.value
|
||||
case "map.gid":
|
||||
|
||||
@@ -35,6 +35,7 @@ type MountOptions struct {
|
||||
umaskString *string
|
||||
nonempty *bool
|
||||
volumeServerAccess *string
|
||||
sseS3Read *bool
|
||||
uidMap *string
|
||||
gidMap *string
|
||||
readOnly *bool
|
||||
@@ -126,6 +127,7 @@ func init() {
|
||||
mountOptions.umaskString = cmdMount.Flag.String("umask", "022", "octal umask, e.g., 022, 0111")
|
||||
mountOptions.nonempty = cmdMount.Flag.Bool("nonempty", false, "allows the mounting over a non-empty directory")
|
||||
mountOptions.volumeServerAccess = cmdMount.Flag.String("volumeServerAccess", "direct", "access volume servers by [direct|publicUrl|filerProxy]")
|
||||
mountOptions.sseS3Read = cmdMount.Flag.Bool("sseS3Read", false, "read SSE-S3 objects through a registered S3 gateway using the mount user's AWS credentials (single-user, read-only bucket mount); uses plain HTTP when no HTTPS gateway is registered")
|
||||
mountOptions.uidMap = cmdMount.Flag.String("map.uid", "", "map local uid to uid on filer, comma-separated <local_uid>:<filer_uid>")
|
||||
mountOptions.gidMap = cmdMount.Flag.String("map.gid", "", "map local gid to gid on filer, comma-separated <local_gid>:<filer_gid>")
|
||||
mountOptions.readOnly = cmdMount.Flag.Bool("readOnly", false, "read only")
|
||||
|
||||
@@ -177,6 +177,7 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr
|
||||
// fileSystemParams are the pieces of a mount that each platform works out for
|
||||
// itself: where it is attached, and whose identity the entries carry.
|
||||
type fileSystemParams struct {
|
||||
sseS3Reader *mount.SSES3Reader
|
||||
dir string
|
||||
mountRoot string
|
||||
filerAddresses []pb.ServerAddress
|
||||
@@ -205,6 +206,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
|
||||
readerCacheSizeMB = *option.readerCacheSizeMB
|
||||
}
|
||||
return mount.NewSeaweedFileSystem(&mount.Option{
|
||||
SSES3Reader: p.sseS3Reader,
|
||||
MountDirectory: p.dir,
|
||||
FilerAddresses: p.filerAddresses,
|
||||
GrpcDialOption: p.grpcDialOption,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount/unmount"
|
||||
|
||||
@@ -42,6 +44,33 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
}
|
||||
|
||||
filerMountRootPath := *option.filerMountRootPath
|
||||
var sseReader *mount.SSES3Reader
|
||||
if *option.sseS3Read {
|
||||
bucketPath, ok := bucketPathForMountRoot(filerMountRootPath, bucketRootPath)
|
||||
if !ok || !*option.readOnly || *option.allowOthers {
|
||||
glog.Errorf("-sseS3Read requires a bucket-root mount, -readOnly and -allowOthers=false")
|
||||
return false
|
||||
}
|
||||
if resolveMountRoot(filerMountRootPath) != bucketPath {
|
||||
glog.Errorf("-sseS3Read requires -filer.path=%s", bucketPath)
|
||||
return false
|
||||
}
|
||||
for _, opt := range option.extraOptions {
|
||||
for _, token := range strings.Split(opt, ",") {
|
||||
switch token {
|
||||
case "allow_other", "allow_root", "rw":
|
||||
glog.Errorf("-sseS3Read is incompatible with mount option %q", token)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
var err error
|
||||
sseReader, err = mount.NewSSES3Reader(context.Background(), bucketPath, filerAddresses, grpcDialOption)
|
||||
if err != nil {
|
||||
glog.Errorf("configure SSE-S3 reads: %v", err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// clean up mount point
|
||||
dir := util.ResolvePath(*option.dir)
|
||||
@@ -212,6 +241,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
cacheDirForRead, cacheDirForWrite := resolveCacheDirs(option)
|
||||
|
||||
seaweedFileSystem := buildSeaweedFileSystem(option, fileSystemParams{
|
||||
sseS3Reader: sseReader,
|
||||
dir: dir,
|
||||
mountRoot: mountRoot,
|
||||
filerAddresses: filerAddresses,
|
||||
|
||||
+16
-13
@@ -434,6 +434,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
AllowUntrustedRemoteEndpoints: *s3opt.allowUntrustedRemoteEndpoints,
|
||||
AllowBackslashInKey: *s3opt.allowBackslashInKey,
|
||||
LancePort: s3opt.lancePort(),
|
||||
S3Endpoint: s3opt.s3Endpoint(),
|
||||
IamSelfServiceRequiresGrant: *s3opt.iamSelfServiceRequiresGrant,
|
||||
RoutedLookupTimeout: *s3opt.routedLookupTimeout,
|
||||
UnreachableOwnerTTL: *s3opt.unreachableOwnerTTL,
|
||||
@@ -882,6 +883,20 @@ func (s3opt *S3Options) deriveLanceStorageEndpoint() string {
|
||||
case "", "0.0.0.0", "::", "[::]":
|
||||
return ""
|
||||
}
|
||||
return s3opt.endpointOn(host)
|
||||
}
|
||||
|
||||
// s3Endpoint is the URL advertised to the master. Unlike the Lance endpoint it
|
||||
// falls back to the detected address, as the gateway's own registration does.
|
||||
func (s3opt *S3Options) s3Endpoint() string {
|
||||
if endpoint := s3opt.deriveLanceStorageEndpoint(); endpoint != "" {
|
||||
return endpoint
|
||||
}
|
||||
return s3opt.endpointOn(util.DetectedHostAddress())
|
||||
}
|
||||
|
||||
// endpointOn is the S3 URL on host, using the TLS port when TLS is on.
|
||||
func (s3opt *S3Options) endpointOn(host string) string {
|
||||
scheme := "http"
|
||||
port := 0
|
||||
if s3opt.port != nil {
|
||||
@@ -921,19 +936,7 @@ func (s3opt *S3Options) deriveS3AdvertisedEndpoint() string {
|
||||
case "", "0.0.0.0", "::", "[::]":
|
||||
return ""
|
||||
}
|
||||
|
||||
scheme := "http"
|
||||
port := 0
|
||||
if s3opt.port != nil {
|
||||
port = *s3opt.port
|
||||
}
|
||||
if s3opt.tlsPrivateKey != nil && *s3opt.tlsPrivateKey != "" {
|
||||
scheme = "https"
|
||||
if s3opt.portHttps != nil && *s3opt.portHttps > 0 {
|
||||
port = *s3opt.portHttps
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%s://%s", scheme, util.JoinHostPort(host, port))
|
||||
return s3opt.endpointOn(host)
|
||||
}
|
||||
|
||||
// icebergCredentialVendor adapts the S3 gateway's STS-backed vending to the
|
||||
|
||||
@@ -2,6 +2,8 @@ package command
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func strp(s string) *string { return &s }
|
||||
@@ -102,3 +104,25 @@ func TestDeriveS3AdvertisedEndpoint(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3Endpoint(t *testing.T) {
|
||||
tls := S3Options{
|
||||
ip: strp(""),
|
||||
bindIp: strp("0.0.0.0"),
|
||||
port: intp(8333),
|
||||
portHttps: intp(8443),
|
||||
tlsPrivateKey: strp("/etc/seaweed/tls.key"),
|
||||
externalUrl: strp(""),
|
||||
}
|
||||
if got, want := tls.s3Endpoint(), "https://"+util.JoinHostPort(util.DetectedHostAddress(), 8443); got != want {
|
||||
t.Fatalf("wildcard bind: got %q, want %q", got, want)
|
||||
}
|
||||
tls.ip = strp("10.0.0.7")
|
||||
if got := tls.s3Endpoint(); got != "https://10.0.0.7:8443" {
|
||||
t.Fatalf("explicit -ip: got %q", got)
|
||||
}
|
||||
tls.externalUrl = strp("https://s3.example.com/")
|
||||
if got := tls.s3Endpoint(); got != "https://s3.example.com" {
|
||||
t.Fatalf("externalUrl: got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
@@ -10,8 +11,11 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
var errNativeSSES3Read = errors.New("native mount cannot decrypt SSE-S3 data")
|
||||
|
||||
func (fh *FileHandle) lockForRead(startOffset int64, size int) {
|
||||
fh.dirtyPages.LockForRead(startOffset, startOffset+int64(size))
|
||||
}
|
||||
@@ -62,6 +66,18 @@ func (fh *FileHandle) readFromChunksWithContext(ctx context.Context, buff []byte
|
||||
if fileSize == 0 {
|
||||
fileSize = int64(filer.FileSize(pbEntry))
|
||||
}
|
||||
if entry.hasSSES3DataLocked() {
|
||||
reader := fh.wfs.option.SSES3Reader
|
||||
if reader == nil {
|
||||
entry.RUnlock()
|
||||
return 0, 0, errNativeSSES3Read
|
||||
}
|
||||
etag := sseObjectETag(pbEntry)
|
||||
version := string(pbEntry.GetExtended()[s3_constants.ExtVersionIdKey])
|
||||
entry.RUnlock()
|
||||
n, err := reader.readAt(ctx, string(fileFullPath), etag, version, fileSize, buff, offset)
|
||||
return n, 0, err
|
||||
}
|
||||
content := pbEntry.Content
|
||||
chunks := pbEntry.Chunks
|
||||
entry.RUnlock()
|
||||
|
||||
@@ -1,14 +1,40 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
type LockedEntry struct {
|
||||
*filer_pb.Entry
|
||||
sync.RWMutex
|
||||
sseS3Check sync.Once
|
||||
sseS3 bool
|
||||
}
|
||||
|
||||
// Native reads cannot decrypt S3 objects. Check the entry once per metadata
|
||||
// change so reads of ordinary files do not repeatedly scan their chunk list.
|
||||
func (le *LockedEntry) hasSSES3Data() bool {
|
||||
le.RLock()
|
||||
defer le.RUnlock()
|
||||
return le.hasSSES3DataLocked()
|
||||
}
|
||||
|
||||
func (le *LockedEntry) hasSSES3DataLocked() bool {
|
||||
le.sseS3Check.Do(func() {
|
||||
metadata := le.Entry.GetExtended()
|
||||
_, hasKey := metadata[s3_constants.SeaweedFSSSES3Key]
|
||||
le.sseS3 = hasKey && string(metadata[s3_constants.AmzServerSideEncryption]) == s3_constants.SSEAlgorithmAES256
|
||||
if !le.sseS3 {
|
||||
le.sseS3 = slices.ContainsFunc(le.Entry.GetChunks(), func(chunk *filer_pb.FileChunk) bool {
|
||||
return chunk.GetSseType() == filer_pb.SSEType_SSE_S3
|
||||
})
|
||||
}
|
||||
})
|
||||
return le.sseS3
|
||||
}
|
||||
|
||||
func (le *LockedEntry) GetEntry() *filer_pb.Entry {
|
||||
@@ -23,12 +49,14 @@ func (le *LockedEntry) SetEntry(entry *filer_pb.Entry) {
|
||||
le.Lock()
|
||||
defer le.Unlock()
|
||||
le.Entry = entry
|
||||
le.sseS3Check = sync.Once{}
|
||||
}
|
||||
|
||||
func (le *LockedEntry) UpdateEntry(fn func(entry *filer_pb.Entry)) *filer_pb.Entry {
|
||||
le.Lock()
|
||||
defer le.Unlock()
|
||||
fn(le.Entry)
|
||||
le.sseS3Check = sync.Once{}
|
||||
return le.Entry
|
||||
}
|
||||
|
||||
@@ -42,4 +70,5 @@ func (le *LockedEntry) AppendChunks(newChunks []*filer_pb.FileChunk) {
|
||||
le.Lock()
|
||||
defer le.Unlock()
|
||||
le.Entry.Chunks = append(le.Entry.Chunks, newChunks...)
|
||||
le.sseS3Check = sync.Once{}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net/url"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
var (
|
||||
errSSES3Permission = errors.New("S3 gateway denied object read")
|
||||
errNoS3Gateway = errors.New("no S3 gateway is registered with the masters")
|
||||
)
|
||||
|
||||
// SSES3Reader makes signed range requests for one mounted bucket. The S3
|
||||
// gateway owns the encryption keys and applies its normal GetObject policy.
|
||||
type SSES3Reader struct {
|
||||
cfg aws.Config
|
||||
endpoints func(context.Context) ([]string, error)
|
||||
root string
|
||||
bucket string
|
||||
|
||||
clientLock sync.Mutex
|
||||
client *s3.Client
|
||||
endpoint string
|
||||
}
|
||||
|
||||
// NewSSES3Reader reads through the S3 gateways the filer's masters list for
|
||||
// its filer group.
|
||||
func NewSSES3Reader(ctx context.Context, bucketPath string, filers []pb.ServerAddress, grpcDialOption grpc.DialOption) (*SSES3Reader, error) {
|
||||
cfg, err := config.LoadDefaultConfig(ctx, config.WithDefaultRegion("us-east-1"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &SSES3Reader{
|
||||
cfg: cfg,
|
||||
endpoints: func(ctx context.Context) ([]string, error) {
|
||||
return listS3Endpoints(ctx, filers, grpcDialOption)
|
||||
},
|
||||
root: bucketPath + "/",
|
||||
bucket: path.Base(bucketPath),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func listS3Endpoints(ctx context.Context, filers []pb.ServerAddress, grpcDialOption grpc.DialOption) ([]string, error) {
|
||||
var masters []string
|
||||
var filerGroup string
|
||||
if err := pb.WithOneOfGrpcFilerClients(false, filers, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
masters, filerGroup = resp.Masters, resp.FilerGroup
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var endpoints []string
|
||||
var err error
|
||||
// Only the leader lists the gateways, so a follower answers with none.
|
||||
for _, master := range masters {
|
||||
err = pb.WithMasterClient(ctx, false, pb.ServerAddress(master), grpcDialOption, false, func(client master_pb.SeaweedClient) error {
|
||||
resp, err := client.ListClusterNodes(ctx, &master_pb.ListClusterNodesRequest{ClientType: cluster.S3Type, FilerGroup: filerGroup})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, node := range resp.ClusterNodes {
|
||||
if node.S3Endpoint != "" {
|
||||
endpoints = append(endpoints, node.S3Endpoint)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if len(endpoints) > 0 {
|
||||
return endpoints, nil
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errNoS3Gateway
|
||||
}
|
||||
|
||||
// gatewayClient picks one of the registered gateways other than failed, using
|
||||
// HTTPS whenever an HTTPS gateway is registered, and keeps it until a request
|
||||
// cannot reach it.
|
||||
func (r *SSES3Reader) gatewayClient(ctx context.Context, failed string) (*s3.Client, string, error) {
|
||||
r.clientLock.Lock()
|
||||
defer r.clientLock.Unlock()
|
||||
if r.client != nil && r.endpoint != failed {
|
||||
return r.client, r.endpoint, nil
|
||||
}
|
||||
endpoints, err := r.endpoints(ctx)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
endpoints = slices.DeleteFunc(endpoints, func(endpoint string) bool {
|
||||
u, err := url.Parse(endpoint)
|
||||
return err != nil || u.Scheme != "https" && u.Scheme != "http" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != ""
|
||||
})
|
||||
isHTTPS := func(endpoint string) bool {
|
||||
u, err := url.Parse(endpoint)
|
||||
return err == nil && u.Scheme == "https"
|
||||
}
|
||||
if https := slices.DeleteFunc(slices.Clone(endpoints), func(endpoint string) bool { return !isHTTPS(endpoint) }); len(https) > 0 {
|
||||
endpoints = https
|
||||
}
|
||||
endpoints = slices.DeleteFunc(endpoints, func(endpoint string) bool { return endpoint == failed })
|
||||
if len(endpoints) == 0 {
|
||||
return nil, "", errNoS3Gateway
|
||||
}
|
||||
endpoint := endpoints[rand.IntN(len(endpoints))]
|
||||
if !isHTTPS(endpoint) {
|
||||
glog.Warningf("-sseS3Read: no HTTPS S3 gateway is registered, reading %s over plain HTTP", endpoint)
|
||||
}
|
||||
r.client = s3.NewFromConfig(r.cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
r.endpoint = endpoint
|
||||
return r.client, endpoint, nil
|
||||
}
|
||||
|
||||
// getObject retries once on another gateway when the current one cannot be
|
||||
// reached.
|
||||
func (r *SSES3Reader) getObject(ctx context.Context, req *s3.GetObjectInput) (*s3.GetObjectOutput, error) {
|
||||
client, endpoint, err := r.gatewayClient(ctx, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
obj, err := client.GetObject(ctx, req)
|
||||
var sendErr *smithyhttp.RequestSendError
|
||||
if !errors.As(err, &sendErr) || ctx.Err() != nil {
|
||||
return obj, err
|
||||
}
|
||||
r.clientLock.Lock()
|
||||
if r.client == client {
|
||||
r.client = nil
|
||||
}
|
||||
r.clientLock.Unlock()
|
||||
retry, _, pickErr := r.gatewayClient(ctx, endpoint)
|
||||
if pickErr != nil {
|
||||
return nil, err
|
||||
}
|
||||
return retry.GetObject(ctx, req)
|
||||
}
|
||||
|
||||
func sseObjectETag(entry *filer_pb.Entry) string {
|
||||
if stored := string(entry.GetExtended()[s3_constants.ExtETagKey]); stored != "" {
|
||||
return `"` + strings.Trim(stored, `"`) + `"`
|
||||
}
|
||||
return `"` + filer.ETag(entry) + `"`
|
||||
}
|
||||
|
||||
func (r *SSES3Reader) readAt(ctx context.Context, fullPath, etag, version string, size int64, buf []byte, offset int64) (int64, error) {
|
||||
key, ok := strings.CutPrefix(fullPath, r.root)
|
||||
if !ok || key == "" || key == "." || key == ".." || path.IsAbs(key) || path.Clean(key) != key || strings.HasPrefix(key, "../") {
|
||||
return 0, errNativeSSES3Read
|
||||
}
|
||||
versionFile := false
|
||||
if dir, name := path.Split(key); version != "" && name == "v_"+version {
|
||||
if object, found := strings.CutSuffix(strings.TrimSuffix(dir, "/"), s3_constants.VersionsFolder); found && object != "" {
|
||||
key, versionFile = object, true
|
||||
}
|
||||
}
|
||||
if offset < 0 || size < 0 {
|
||||
return 0, errors.New("invalid S3 object range")
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if offset >= size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := min(int64(len(buf)), size-offset)
|
||||
last := offset + n - 1
|
||||
req := &s3.GetObjectInput{
|
||||
Bucket: aws.String(r.bucket), Key: aws.String(key),
|
||||
IfMatch: aws.String(etag), Range: aws.String(fmt.Sprintf("bytes=%d-%d", offset, last)),
|
||||
}
|
||||
currentNull := version == "null" && !versionFile
|
||||
if version != "" && !currentNull {
|
||||
req.VersionId = aws.String(version)
|
||||
}
|
||||
obj, err := r.getObject(ctx, req)
|
||||
if currentNull && (err == nil && aws.ToString(obj.VersionId) != "" && aws.ToString(obj.VersionId) != version || err != nil && !isS3PermissionError(err)) {
|
||||
if err == nil {
|
||||
obj.Body.Close()
|
||||
}
|
||||
req.VersionId = aws.String(version)
|
||||
obj, err = r.getObject(ctx, req)
|
||||
}
|
||||
if err != nil {
|
||||
if isS3PermissionError(err) {
|
||||
return 0, errSSES3Permission
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
defer obj.Body.Close()
|
||||
wantRange := fmt.Sprintf("bytes %d-%d/%d", offset, last, size)
|
||||
if aws.ToString(obj.ContentRange) != wantRange || aws.ToInt64(obj.ContentLength) != n ||
|
||||
aws.ToString(obj.ETag) != etag || obj.ServerSideEncryption != types.ServerSideEncryptionAes256 ||
|
||||
(version != "" && aws.ToString(obj.VersionId) != version && (req.VersionId != nil || aws.ToString(obj.VersionId) != "")) {
|
||||
return 0, errors.New("S3 response did not match the encrypted object range")
|
||||
}
|
||||
if _, err := io.ReadFull(obj.Body, buf[:n]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func isS3PermissionError(err error) bool {
|
||||
var respErr *smithyhttp.ResponseError
|
||||
return errors.As(err, &respErr) && (respErr.HTTPStatusCode() == 403 || respErr.HTTPStatusCode() == 401)
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
)
|
||||
|
||||
func gatewayReader(t *testing.T, bucketPath string, endpoints ...string) *SSES3Reader {
|
||||
t.Helper()
|
||||
reader, err := NewSSES3Reader(context.Background(), bucketPath, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader.endpoints = func(context.Context) ([]string, error) { return endpoints, nil }
|
||||
return reader
|
||||
}
|
||||
|
||||
func TestSSES3GatewayReadAt(t *testing.T) {
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "local-test-reader")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "local-test-secret")
|
||||
t.Setenv("AWS_SESSION_TOKEN", "")
|
||||
t.Setenv("AWS_REGION", "us-east-1")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
rangeHeader string
|
||||
etag string
|
||||
wantOK bool
|
||||
}{
|
||||
{"signed range", http.StatusPartialContent, "bytes 3-5/10", `"fixture"`, true},
|
||||
{"wrong offset", http.StatusPartialContent, "bytes 0-2/10", `"fixture"`, false},
|
||||
{"object replaced", http.StatusPartialContent, "bytes 3-5/10", `"replacement"`, false},
|
||||
{"read denied", http.StatusForbidden, "", "", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path != "/bucket/dir/a+b" || req.URL.Query().Get("versionId") != "v1" ||
|
||||
req.Header.Get("Range") != "bytes=3-5" || req.Header.Get("If-Match") != `"fixture"` ||
|
||||
!strings.HasPrefix(req.Header.Get("Authorization"), "AWS4-HMAC-SHA256 ") {
|
||||
t.Errorf("unexpected signed range request for %q", req.URL.Path)
|
||||
}
|
||||
if tc.status == http.StatusForbidden {
|
||||
w.WriteHeader(tc.status)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", tc.etag)
|
||||
w.Header().Set("Content-Range", tc.rangeHeader)
|
||||
w.Header().Set("Content-Length", "3")
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption", "AES256")
|
||||
w.Header().Set("X-Amz-Version-Id", "v1")
|
||||
w.WriteHeader(tc.status)
|
||||
_, _ = w.Write([]byte("345"))
|
||||
}))
|
||||
defer server.Close()
|
||||
reader := gatewayReader(t, "/custom/bucket", server.URL)
|
||||
buf := make([]byte, 3)
|
||||
n, err := reader.readAt(context.Background(), "/custom/bucket/dir/a+b", `"fixture"`, "v1", 10, buf, 3)
|
||||
if tc.wantOK {
|
||||
if err != nil || n != 3 || string(buf) != "345" {
|
||||
t.Fatalf("read = %d, %v, bytes %q", n, err, buf)
|
||||
}
|
||||
} else if err == nil || n != 0 {
|
||||
t.Fatalf("invalid response returned %d bytes, error %v", n, err)
|
||||
}
|
||||
if tc.status == http.StatusForbidden && !errors.Is(err, errSSES3Permission) {
|
||||
t.Fatalf("read error = %v, want denied", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSES3GatewayReadAtVersionFile(t *testing.T) {
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "local-test-reader")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "local-test-secret")
|
||||
t.Setenv("AWS_SESSION_TOKEN", "")
|
||||
t.Setenv("AWS_REGION", "us-east-1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path != "/bucket/dir/report.csv" || req.URL.Query().Get("versionId") != "v1" {
|
||||
t.Errorf("version file read sent %s?%s", req.URL.Path, req.URL.RawQuery)
|
||||
}
|
||||
w.Header().Set("ETag", `"fixture"`)
|
||||
w.Header().Set("Content-Range", "bytes 0-2/3")
|
||||
w.Header().Set("Content-Length", "3")
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption", "AES256")
|
||||
w.Header().Set("X-Amz-Version-Id", "v1")
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = w.Write([]byte("abc"))
|
||||
}))
|
||||
defer server.Close()
|
||||
reader := gatewayReader(t, "/buckets/bucket", server.URL)
|
||||
buf := make([]byte, 3)
|
||||
n, err := reader.readAt(context.Background(), "/buckets/bucket/dir/report.csv.versions/v_v1", `"fixture"`, "v1", 3, buf, 0)
|
||||
if err != nil || n != 3 || string(buf) != "abc" {
|
||||
t.Fatalf("read = %d, %v, bytes %q", n, err, buf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSES3GatewayReadAtNullVersion(t *testing.T) {
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "local-test-reader")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "local-test-secret")
|
||||
t.Setenv("AWS_SESSION_TOKEN", "")
|
||||
t.Setenv("AWS_REGION", "us-east-1")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
currentETag string
|
||||
wantRequests []string
|
||||
}{
|
||||
{"current", `"fixture"`, []string{""}},
|
||||
{"superseded", `"newer"`, []string{"", "null"}},
|
||||
{"superseded by identical bytes", `"fixture"`, []string{"", "null"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var got []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
versionId := req.URL.Query().Get("versionId")
|
||||
got = append(got, versionId)
|
||||
if versionId == "" && req.Header.Get("If-Match") != tc.currentETag {
|
||||
w.WriteHeader(http.StatusPreconditionFailed)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", `"fixture"`)
|
||||
w.Header().Set("Content-Range", "bytes 0-2/3")
|
||||
w.Header().Set("Content-Length", "3")
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption", "AES256")
|
||||
if versionId == "" && tc.name == "superseded by identical bytes" {
|
||||
w.Header().Set("X-Amz-Version-Id", "v2")
|
||||
} else {
|
||||
w.Header().Set("X-Amz-Version-Id", "null")
|
||||
}
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = w.Write([]byte("abc"))
|
||||
}))
|
||||
defer server.Close()
|
||||
reader := gatewayReader(t, "/buckets/bucket", server.URL)
|
||||
buf := make([]byte, 3)
|
||||
n, err := reader.readAt(context.Background(), "/buckets/bucket/report.csv", `"fixture"`, "null", 3, buf, 0)
|
||||
if err != nil || n != 3 || string(buf) != "abc" {
|
||||
t.Fatalf("read = %d, %v, bytes %q", n, err, buf)
|
||||
}
|
||||
if strings.Join(got, ",") != strings.Join(tc.wantRequests, ",") {
|
||||
t.Fatalf("versionId requests = %q, want %q", got, tc.wantRequests)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSES3GatewayChoice(t *testing.T) {
|
||||
reader := gatewayReader(t, "/buckets/bucket", "ftp://a:21", "http://b:8333", "https://user@c:8443", "https://d:8443")
|
||||
client, _, err := reader.gatewayClient(context.Background(), "")
|
||||
if err != nil || aws.ToString(client.Options().BaseEndpoint) != "https://d:8443" {
|
||||
t.Fatalf("gateway = %v, %v; want the valid HTTPS one", err, client)
|
||||
}
|
||||
|
||||
reader = gatewayReader(t, "/buckets/bucket", "ftp://a:21")
|
||||
if _, _, err := reader.gatewayClient(context.Background(), ""); !errors.Is(err, errNoS3Gateway) {
|
||||
t.Fatalf("no usable gateway: err = %v", err)
|
||||
}
|
||||
|
||||
reader = gatewayReader(t, "/buckets/bucket", "http://b:8333", "https://d:8443")
|
||||
if client, _, err := reader.gatewayClient(context.Background(), "https://d:8443"); !errors.Is(err, errNoS3Gateway) {
|
||||
t.Fatalf("retry after the only HTTPS gateway failed = %v, %v; want no plain-HTTP fallback", err, client)
|
||||
}
|
||||
|
||||
for range 20 {
|
||||
reader = gatewayReader(t, "/buckets/bucket", "http://b:8333", "HTTPS://d:8443")
|
||||
if client, _, err := reader.gatewayClient(context.Background(), ""); err != nil || aws.ToString(client.Options().BaseEndpoint) != "HTTPS://d:8443" {
|
||||
t.Fatalf("mixed-case HTTPS scheme: gateway = %v, %v; want the HTTPS one", err, client)
|
||||
}
|
||||
}
|
||||
reader = gatewayReader(t, "/buckets/bucket", "http://b:8333", "HTTPS://d:8443")
|
||||
if client, _, err := reader.gatewayClient(context.Background(), "HTTPS://d:8443"); !errors.Is(err, errNoS3Gateway) {
|
||||
t.Fatalf("retry after the mixed-case HTTPS gateway failed = %v, %v; want no plain-HTTP fallback", err, client)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSES3GatewayReadAtPicksAnotherGateway(t *testing.T) {
|
||||
t.Setenv("AWS_ACCESS_KEY_ID", "local-test-reader")
|
||||
t.Setenv("AWS_SECRET_ACCESS_KEY", "local-test-secret")
|
||||
t.Setenv("AWS_SESSION_TOKEN", "")
|
||||
t.Setenv("AWS_REGION", "us-east-1")
|
||||
stopped := httptest.NewServer(http.NotFoundHandler())
|
||||
stopped.Close()
|
||||
live := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
w.Header().Set("ETag", `"fixture"`)
|
||||
w.Header().Set("Content-Range", "bytes 0-2/3")
|
||||
w.Header().Set("Content-Length", "3")
|
||||
w.Header().Set("X-Amz-Server-Side-Encryption", "AES256")
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = w.Write([]byte("abc"))
|
||||
}))
|
||||
defer live.Close()
|
||||
|
||||
buf := make([]byte, 3)
|
||||
for range 20 {
|
||||
reader := gatewayReader(t, "/buckets/bucket", stopped.URL, live.URL)
|
||||
reader.cfg.Retryer = func() aws.Retryer { return aws.NopRetryer{} }
|
||||
if n, err := reader.readAt(context.Background(), "/buckets/bucket/a", `"fixture"`, "", 3, buf, 0); err != nil || string(buf[:n]) != "abc" {
|
||||
t.Fatalf("read = %d, %v, bytes %q", n, err, buf)
|
||||
}
|
||||
}
|
||||
|
||||
reader := gatewayReader(t, "/buckets/bucket", stopped.URL)
|
||||
reader.cfg.Retryer = func() aws.Retryer { return aws.NopRetryer{} }
|
||||
var sendErr *smithyhttp.RequestSendError
|
||||
if _, err := reader.readAt(context.Background(), "/buckets/bucket/a", `"fixture"`, "", 3, buf, 0); !errors.As(err, &sendErr) {
|
||||
t.Fatalf("only gateway unreachable: err = %v, want the send error", err)
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,8 @@ type Option struct {
|
||||
MountParentInode uint64
|
||||
|
||||
VolumeServerAccess string // how to access volume servers
|
||||
Cipher bool // whether encrypt data on volume server
|
||||
SSES3Reader *SSES3Reader
|
||||
Cipher bool // whether encrypt data on volume server
|
||||
UidGidMapper *meta_cache.UidGidMapper
|
||||
IncludeSystemEntries bool
|
||||
|
||||
|
||||
@@ -109,6 +109,9 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
|
||||
if fhIn.entry.IsDirectory || fhOut.entry.IsDirectory {
|
||||
return 0, fuse.EISDIR
|
||||
}
|
||||
if fhIn.entry.hasSSES3Data() {
|
||||
return 0, fuse.ENOTSUP
|
||||
}
|
||||
|
||||
glog.V(4).Infof(
|
||||
"CopyFileRange %s fhIn %d -> %s fhOut %d, [%d,%d) -> [%d,%d)",
|
||||
@@ -159,6 +162,9 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
|
||||
numBytesRead, err := readDataByFileHandle(
|
||||
buff[:readLen], fhIn, offsetIn)
|
||||
if err != nil {
|
||||
if err == errNativeSSES3Read {
|
||||
return 0, fuse.ENOTSUP
|
||||
}
|
||||
glog.Warningf("file handle read %s %d (total %d): %v",
|
||||
fhIn.FullPath(), numBytesRead, totalCopied, err)
|
||||
return 0, fuse.EIO
|
||||
|
||||
@@ -70,6 +70,11 @@ func (wfs *WFS) Open(cancel <-chan struct{}, in *fuse.OpenIn, out *fuse.OpenOut)
|
||||
defer cancelFunc()
|
||||
fileHandle, openFh, status = wfs.AcquireHandle(ctx, in.NodeId, in.Flags, in.Uid, in.Gid)
|
||||
if status == fuse.OK {
|
||||
encrypted := openFlagsToAccessMask(in.Flags)&fuse.R_OK != 0 && fileHandle.GetEntry().hasSSES3Data()
|
||||
if encrypted && wfs.option.SSES3Reader == nil {
|
||||
wfs.ReleaseHandle(openFh)
|
||||
return fuse.ENOTSUP
|
||||
}
|
||||
out.Fh = uint64(openFh)
|
||||
out.OpenFlags = 0
|
||||
wfs.reportOpen(in.Flags, in.NodeId, fileHandle.GetEntry().GetEntry())
|
||||
@@ -77,7 +82,10 @@ func (wfs *WFS) Open(cancel <-chan struct{}, in *fuse.OpenIn, out *fuse.OpenOut)
|
||||
// For read-only opens, set FOPEN_KEEP_CACHE when the file's mtime
|
||||
// has not changed since the last open. This tells the kernel to
|
||||
// preserve its existing page cache, avoiding redundant reads.
|
||||
if in.Flags&fuse.O_ANYWRITE == 0 {
|
||||
if encrypted {
|
||||
// Authorize each read with the gateway, including on a reopened inode.
|
||||
out.OpenFlags = fuse.FOPEN_DIRECT_IO
|
||||
} else if in.Flags&fuse.O_ANYWRITE == 0 {
|
||||
if entry := fileHandle.GetEntry(); entry != nil && entry.Attributes != nil {
|
||||
wfs.applyKeepCacheFlag(in.NodeId, entry, out)
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func (wfs *WFS) Read(cancel <-chan struct{}, in *fuse.ReadIn, buff []byte) (fuse
|
||||
|
||||
offset := int64(in.Offset)
|
||||
totalRead, err := readDataByFileHandleWithContext(ctx, buff, fh, offset)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
if err != nil && err != errNativeSSES3Read && err != errSSES3Permission && ctx.Err() == nil {
|
||||
// The chunk views a read resolves can name data a concurrent overwrite
|
||||
// already replaced: the filer queues replaced file ids for deletion at
|
||||
// commit while this handle only learns the new list when the metadata
|
||||
@@ -66,6 +66,12 @@ func (wfs *WFS) Read(cancel <-chan struct{}, in *fuse.ReadIn, buff []byte) (fuse
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
if err == errNativeSSES3Read {
|
||||
return nil, fuse.ENOTSUP
|
||||
}
|
||||
if err == errSSES3Permission {
|
||||
return nil, fuse.EACCES
|
||||
}
|
||||
// The kernel's FUSE contract answers an interrupted request with EINTR
|
||||
// on the original request, never EIO. Interrupts come from any signal
|
||||
// the reader handles, Go's preemption SIGURG included, so they are
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestNativeReadSSES3(t *testing.T) {
|
||||
content := []byte("test payload")
|
||||
header := s3_constants.AmzServerSideEncryption
|
||||
key := s3_constants.SeaweedFSSSES3Key
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
extended map[string][]byte
|
||||
chunks []*filer_pb.FileChunk
|
||||
want fuse.Status
|
||||
}{
|
||||
{name: "plain", want: fuse.OK},
|
||||
{name: "stale algorithm header", extended: map[string][]byte{header: []byte("AES256")}, want: fuse.OK},
|
||||
{name: "native cipher key", chunks: []*filer_pb.FileChunk{{CipherKey: []byte("native test key")}}, want: fuse.OK},
|
||||
{name: "object metadata", extended: map[string][]byte{header: []byte("AES256"), key: []byte("test metadata")}, want: fuse.ENOTSUP},
|
||||
{name: "multipart chunk metadata", chunks: []*filer_pb.FileChunk{{}, {SseType: filer_pb.SSEType_SSE_S3, SseMetadata: []byte("test metadata")}}, want: fuse.ENOTSUP},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
wfs.openMtimeCache = make(map[uint64][2]int64)
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/file"), 1, false, false, 0, false)
|
||||
entry := &filer_pb.Entry{Name: "file", Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content)), FileMode: 0o644}, Content: content}
|
||||
fh, id, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
|
||||
defer wfs.ReleaseHandle(id)
|
||||
|
||||
read := &fuse.ReadIn{InHeader: fuse.InHeader{NodeId: inode}, Fh: uint64(id), Offset: 1, Size: 4}
|
||||
buf := make([]byte, read.Size)
|
||||
if _, status := wfs.Read(nil, read, buf); status != fuse.OK {
|
||||
t.Fatalf("initial read: %v", status)
|
||||
}
|
||||
// A reader may already hold the inode when S3 replaces the object.
|
||||
fh.SetEntry(&filer_pb.Entry{Name: "file", Attributes: entry.Attributes, Content: content, Extended: tc.extended, Chunks: tc.chunks})
|
||||
clear(buf)
|
||||
data, status := wfs.Read(nil, read, buf)
|
||||
if status != tc.want {
|
||||
t.Fatalf("read status = %v, want %v", status, tc.want)
|
||||
}
|
||||
if tc.want == fuse.OK {
|
||||
if !bytes.Equal(buf, content[1:5]) {
|
||||
t.Errorf("read = %q, want %q", buf, content[1:5])
|
||||
}
|
||||
} else if data != nil || !bytes.Equal(buf, make([]byte, len(buf))) {
|
||||
t.Error("unsupported read returned file bytes")
|
||||
}
|
||||
|
||||
out := &fuse.OpenOut{}
|
||||
status = wfs.Open(nil, &fuse.OpenIn{InHeader: read.InHeader, Flags: syscall.O_RDONLY}, out)
|
||||
if status == fuse.OK {
|
||||
defer wfs.ReleaseHandle(FileHandleId(out.Fh))
|
||||
}
|
||||
if status != tc.want {
|
||||
t.Errorf("open status = %v, want %v", status, tc.want)
|
||||
}
|
||||
if tc.want == fuse.ENOTSUP {
|
||||
copyRange := &fuse.CopyFileRangeIn{InHeader: read.InHeader, FhIn: uint64(id), FhOut: uint64(id), Len: 1}
|
||||
if n, status := wfs.CopyFileRange(nil, copyRange); n != 0 || status != fuse.ENOTSUP {
|
||||
t.Errorf("copy = (%d, %v), want (0, ENOTSUP)", n, status)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -236,6 +236,8 @@ message KeepConnectedRequest {
|
||||
uint32 metrics_port = 9;
|
||||
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
|
||||
uint32 lance_port = 10;
|
||||
// URL an S3 gateway serves the S3 API on, or empty when it advertises none.
|
||||
string s3_endpoint = 11;
|
||||
}
|
||||
|
||||
message VolumeLocation {
|
||||
@@ -562,6 +564,7 @@ message ListClusterNodesResponse {
|
||||
string version = 2;
|
||||
int64 created_at_ns = 4;
|
||||
uint32 lance_port = 7;
|
||||
string s3_endpoint = 8;
|
||||
string data_center = 5;
|
||||
string rack = 6;
|
||||
}
|
||||
|
||||
@@ -1045,7 +1045,9 @@ type KeepConnectedRequest struct {
|
||||
// exposing metrics on the client-facing service port.
|
||||
MetricsPort uint32 `protobuf:"varint,9,opt,name=metrics_port,json=metricsPort,proto3" json:"metrics_port,omitempty"`
|
||||
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
|
||||
LancePort uint32 `protobuf:"varint,10,opt,name=lance_port,json=lancePort,proto3" json:"lance_port,omitempty"`
|
||||
LancePort uint32 `protobuf:"varint,10,opt,name=lance_port,json=lancePort,proto3" json:"lance_port,omitempty"`
|
||||
// URL an S3 gateway serves the S3 API on, or empty when it advertises none.
|
||||
S3Endpoint string `protobuf:"bytes,11,opt,name=s3_endpoint,json=s3Endpoint,proto3" json:"s3_endpoint,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -1143,6 +1145,13 @@ func (x *KeepConnectedRequest) GetLancePort() uint32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *KeepConnectedRequest) GetS3Endpoint() string {
|
||||
if x != nil {
|
||||
return x.S3Endpoint
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type VolumeLocation struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
|
||||
@@ -5050,6 +5059,7 @@ type ListClusterNodesResponse_ClusterNode struct {
|
||||
Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"`
|
||||
CreatedAtNs int64 `protobuf:"varint,4,opt,name=created_at_ns,json=createdAtNs,proto3" json:"created_at_ns,omitempty"`
|
||||
LancePort uint32 `protobuf:"varint,7,opt,name=lance_port,json=lancePort,proto3" json:"lance_port,omitempty"`
|
||||
S3Endpoint string `protobuf:"bytes,8,opt,name=s3_endpoint,json=s3Endpoint,proto3" json:"s3_endpoint,omitempty"`
|
||||
DataCenter string `protobuf:"bytes,5,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"`
|
||||
Rack string `protobuf:"bytes,6,opt,name=rack,proto3" json:"rack,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -5114,6 +5124,13 @@ func (x *ListClusterNodesResponse_ClusterNode) GetLancePort() uint32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *ListClusterNodesResponse_ClusterNode) GetS3Endpoint() string {
|
||||
if x != nil {
|
||||
return x.S3Endpoint
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ListClusterNodesResponse_ClusterNode) GetDataCenter() string {
|
||||
if x != nil {
|
||||
return x.DataCenter
|
||||
@@ -5331,7 +5348,7 @@ const file_master_proto_rawDesc = "" +
|
||||
"\x04data\x18\x01 \x01(\rR\x04data\x12\x16\n" +
|
||||
"\x06parity\x18\x02 \x01(\rR\x06parity\x12\x1d\n" +
|
||||
"\n" +
|
||||
"volume_ids\x18\x03 \x03(\rR\tvolumeIds\"\xb8\x02\n" +
|
||||
"volume_ids\x18\x03 \x03(\rR\tvolumeIds\"\xd9\x02\n" +
|
||||
"\x14KeepConnectedRequest\x12\x1f\n" +
|
||||
"\vclient_type\x18\x01 \x01(\tR\n" +
|
||||
"clientType\x12%\n" +
|
||||
@@ -5346,7 +5363,9 @@ const file_master_proto_rawDesc = "" +
|
||||
"\fmetrics_port\x18\t \x01(\rR\vmetricsPort\x12\x1d\n" +
|
||||
"\n" +
|
||||
"lance_port\x18\n" +
|
||||
" \x01(\rR\tlancePort\"\x9e\x03\n" +
|
||||
" \x01(\rR\tlancePort\x12\x1f\n" +
|
||||
"\vs3_endpoint\x18\v \x01(\tR\n" +
|
||||
"s3Endpoint\"\x9e\x03\n" +
|
||||
"\x0eVolumeLocation\x12\x10\n" +
|
||||
"\x03url\x18\x01 \x01(\tR\x03url\x12\x1d\n" +
|
||||
"\n" +
|
||||
@@ -5606,15 +5625,17 @@ const file_master_proto_rawDesc = "" +
|
||||
"clientType\x12\x1f\n" +
|
||||
"\vfiler_group\x18\x02 \x01(\tR\n" +
|
||||
"filerGroup\x12\x14\n" +
|
||||
"\x05limit\x18\x04 \x01(\x05R\x05limit\"\xac\x02\n" +
|
||||
"\x05limit\x18\x04 \x01(\x05R\x05limit\"\xcd\x02\n" +
|
||||
"\x18ListClusterNodesResponse\x12T\n" +
|
||||
"\rcluster_nodes\x18\x01 \x03(\v2/.master_pb.ListClusterNodesResponse.ClusterNodeR\fclusterNodes\x1a\xb9\x01\n" +
|
||||
"\rcluster_nodes\x18\x01 \x03(\v2/.master_pb.ListClusterNodesResponse.ClusterNodeR\fclusterNodes\x1a\xda\x01\n" +
|
||||
"\vClusterNode\x12\x18\n" +
|
||||
"\aaddress\x18\x01 \x01(\tR\aaddress\x12\x18\n" +
|
||||
"\aversion\x18\x02 \x01(\tR\aversion\x12\"\n" +
|
||||
"\rcreated_at_ns\x18\x04 \x01(\x03R\vcreatedAtNs\x12\x1d\n" +
|
||||
"\n" +
|
||||
"lance_port\x18\a \x01(\rR\tlancePort\x12\x1f\n" +
|
||||
"\vs3_endpoint\x18\b \x01(\tR\n" +
|
||||
"s3Endpoint\x12\x1f\n" +
|
||||
"\vdata_center\x18\x05 \x01(\tR\n" +
|
||||
"dataCenter\x12\x12\n" +
|
||||
"\x04rack\x18\x06 \x01(\tR\x04rack\"\xc5\x01\n" +
|
||||
|
||||
@@ -86,6 +86,9 @@ type S3ApiServerOption struct {
|
||||
// LancePort is advertised to the master so admin can point workers at the
|
||||
// Lance Namespace; 0 when this gateway serves none.
|
||||
LancePort uint32
|
||||
// S3Endpoint is advertised to the master so mounts can read SSE-S3 objects
|
||||
// through this gateway.
|
||||
S3Endpoint string
|
||||
// IamSelfServiceRequiresGrant makes managing one's own access keys
|
||||
// (CreateAccessKey, DeleteAccessKey, UpdateAccessKey, ListAccessKeys,
|
||||
// GetUser) need an explicit iam: grant instead of being allowed to every
|
||||
@@ -269,6 +272,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
|
||||
masterClient.SetOnVolumeLocationChangeFn(filerClient.OnVolumeLocationChange)
|
||||
masterClient.SetOnVidMapResetFn(filerClient.OnVidMapReset)
|
||||
masterClient.SetLancePort(option.LancePort)
|
||||
masterClient.SetS3Endpoint(option.S3Endpoint)
|
||||
|
||||
// Start the master client connection loop - required for GetMaster() to work
|
||||
go masterClient.KeepConnectedToMaster(context.Background())
|
||||
|
||||
@@ -573,6 +573,7 @@ func (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServ
|
||||
}
|
||||
if req.ClientType == cluster.S3Type {
|
||||
ms.Cluster.SetLancePort(req.FilerGroup, peerAddress, req.LancePort)
|
||||
ms.Cluster.SetS3Endpoint(req.FilerGroup, peerAddress, req.S3Endpoint)
|
||||
}
|
||||
ms.updateLockRing(req, peerAddress)
|
||||
ms.clusterNodeLock.Unlock()
|
||||
|
||||
@@ -20,6 +20,7 @@ func (ms *MasterServer) ListClusterNodes(ctx context.Context, req *master_pb.Lis
|
||||
Address: string(node.Address),
|
||||
Version: node.Version,
|
||||
LancePort: node.LancePort.Load(),
|
||||
S3Endpoint: node.GetS3Endpoint(),
|
||||
CreatedAtNs: node.CreatedTs.UnixNano(),
|
||||
DataCenter: string(node.DataCenter),
|
||||
Rack: string(node.Rack),
|
||||
|
||||
@@ -199,7 +199,8 @@ type MasterClient struct {
|
||||
// before it is ready to be routed to.
|
||||
announceCh chan struct{}
|
||||
|
||||
lancePort uint32
|
||||
lancePort uint32
|
||||
s3Endpoint string
|
||||
}
|
||||
|
||||
// SetAnnounceCh sets a channel that must be closed before this client
|
||||
@@ -214,6 +215,12 @@ func (mc *MasterClient) SetLancePort(port uint32) {
|
||||
mc.lancePort = port
|
||||
}
|
||||
|
||||
// SetS3Endpoint advertises the URL this S3 gateway serves the S3 API on. Must
|
||||
// be called before KeepConnectedToMaster starts.
|
||||
func (mc *MasterClient) SetS3Endpoint(endpoint string) {
|
||||
mc.s3Endpoint = endpoint
|
||||
}
|
||||
|
||||
// ListMasters returns the configured master addresses without waiting for a
|
||||
// connection, for callers that run before KeepConnectedToMaster is connected.
|
||||
func (mc *MasterClient) ListMasters() []pb.ServerAddress {
|
||||
@@ -389,6 +396,7 @@ func (mc *MasterClient) tryConnectToMaster(ctx context.Context, master pb.Server
|
||||
Version: version.Version(),
|
||||
LeaveLockRing: mc.leavingLockRing,
|
||||
LancePort: mc.lancePort,
|
||||
S3Endpoint: mc.s3Endpoint,
|
||||
})
|
||||
if err == nil {
|
||||
mc.stream = stream
|
||||
|
||||
Reference in new issue
Block a user