mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* security: filer token source read from a file FilerTokenFile is the token source of a client that holds a pre-issued filer token rather than a signing key. It reads the file on every call, so an atomic replacement that keeps size and mtime takes effect on the next attempt, and trims surrounding whitespace. A missing, unreadable, empty or malformed file fails the call: there is no fallback to anonymous or admin authority, and errors name the path but not the contents. FilerTokenClaims decodes a token's claims without a key, and FilerTokenGrantCovers compares two grants, so a client can plan reconnects before expiry and know when a replacement narrows what it may see. * mount: -filer.tokenFile authorizes filer calls with a pre-issued token A mount that should not hold a filer signing key can now present a token issued for it. -filer.tokenFile (or -o filer.tokenFile=) names the file; it is read for every filer gRPC attempt, so a replaced file takes effect on the next call or retry without a restart, and a missing or empty file fails the call locally. The source reaches every filer client the mount builds: the startup handshake, each attempt of WithFilerClient, the volume location client, the SSE-S3 reader's configuration call, the peer registrar dial and the lock client. It is attached per call, never to the cached channel, and never to master, volume or peer mount RPCs. The filer refuses MountRegister, MountList and distributed locks to scoped tokens, so the mount refuses to start when -filer.tokenFile is combined with -peer.enable or -dlm instead of failing at run time. Server-side copy_file_range signs its filer HTTP request with the HTTP key, not this token, and is unsupported with it. Without the flag the mount behaves as before. * mount: resubscribe metadata with a replaced filer token A metadata subscription keeps the authority it opened with, so a mount reading -filer.tokenFile would follow with the old token until the filer ended the stream at expiry, and every such end took the gap path that distrusts all cached listings. SubscribeMetaEvents now takes the credentials of each attempt. The mount opens each subscription with the token current at that moment and watches the file; once it holds a different token the attempt ends and the follow resubscribes at once from its checkpoint. This planned resubscribe is not a gap: cached listings stay, unless the new grant may show less than the old one or either token cannot be decoded, in which case they are read again so nothing the old grant showed outlives it. The filer walk treats a resubscribe like a stopped follow, so the same attempt is not replayed on the next filer. Without a token file nothing changes. * mount: hand the mutation stream over to a replaced filer token The mutation stream keeps the token it opened with, and a filer refuses to send on a scoped stream once that token has expired. A mutation applied at that moment loses its reply, the mount reads that as a transport failure, and the unary fallback sends it again. The stream now opens with a snapshot of the token source. Before admitting a request it checks the source: when the file holds another token, or the stream's token would expire before a reply could come back, the stream is retired. New requests wait while the admitted ones are answered, the stream is half-closed so the filer finishes it, and a successor opens with the new token. The waits give up only after filerRPCWait without a response, so a rename that keeps answering is not cut short. A request is never resent by the handover: one still unanswered when the wait gives up fails as on any lost stream, as before. A token too close to expiry to open a stream with is refused before anything is sent, so the request goes out once as a unary call, which the filer checks when it starts. Without a token file nothing changes. * mount: review fixes for the filer token file - A distrust of cached listings now also discards the directory builds in flight, in the meta cache's apply loop: such a build publishes nothing, its entries are wiped and the visit lists the directory again, so a listing read under a grant that has since narrowed is never cached after the distrust. The cached flags are reset again in the loop, after any build that completed before it. - Retiring the mutation stream runs in the background, and a request that waits for the retirement gives up on its own context, unadmitted. - With a token file and no filer signing key, server-side whole-file copy is not tried: its filer HTTP request would go out unsigned and fail as ambiguous. The copy streams through the chunk path instead. - On Windows the token file is opened with delete sharing, so a renewer can replace it by rename while a read holds it open; the missing-file test checks os.ErrNotExist instead of Unix wording. * mount: review fixes for the mutation stream handover A request admitted to the mutation stream with just over one RPC wait left on its token could wait behind a slow send until that margin was gone; its reply could then be refused at expiry and the request was resent over unary. The send loop now checks the margin again right before sending and holds back a request that no longer has it, which is safe to send over unary because the filer never saw it. A sent request whose reply is lost while the token has one RPC wait or less left now fails with EIO instead of a transport error: the filer may have applied it, so it is not resent. Losses with the margin intact fall back to unary as before. A newly opened stream now admits its first request through the same checks as an open one, so a token file replaced, or a token that neared expiry, while the stream opened is caught before anything is sent. A retirement keeps a cancel handle for its stream. Close uses it, so unmount no longer waits for admitted requests to be answered, and a waiter that gives up on a retiring stream stops it as it would stop an open one, so a request still queued there is never sent after that waiter fell back to unary. An ordinary rotation still drains admitted requests. * mount: drop kernel listings when the filer token's grant narrows A replacement token whose grant may not cover the old one already distrusts the mount's own cached listings. The kernel kept its own copy: OpenDir sets FOPEN_CACHE_DIR | FOPEN_KEEP_CACHE, so a directory still reachable under the new grant was listed again from the page cache with names the new grant may hide, until something else invalidated it. On a narrowed or undecodable grant the mount now also notifies the kernel for every directory inode it holds, from the subscription goroutine as the metadata apply path already does, so the next readdir reaches the mount. A readdir already under way on an open handle still finishes from what it read. * mount: drop kernel listings after a subscription gap too distrustCachedListings serves both the narrowed-grant path and the gap path. A gap can lose the very events that would have dropped the kernel's cached listings one directory at a time, and with FOPEN_KEEP_CACHE on OpenDir the kernel then serves those listings on every reopen. Move the kernel drop into distrustCachedListings so both paths get it. 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>
458 lines
17 KiB
Go
458 lines
17 KiB
Go
//go:build linux || darwin || freebsd || windows
|
|
|
|
package command
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"runtime"
|
|
"runtime/debug"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/reflection"
|
|
"google.golang.org/grpc/status"
|
|
|
|
"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/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/mount_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/grace"
|
|
)
|
|
|
|
func runMount(cmd *Command, args []string) bool {
|
|
|
|
if *mountOptions.debug {
|
|
go http.ListenAndServe(fmt.Sprintf(":%d", *mountOptions.debugPort), nil)
|
|
}
|
|
|
|
*mountCpuProfile = util.ResolvePath(*mountCpuProfile)
|
|
*mountMemProfile = util.ResolvePath(*mountMemProfile)
|
|
grace.SetupProfiling(*mountCpuProfile, *mountMemProfile)
|
|
if *mountReadRetryTime < time.Second {
|
|
*mountReadRetryTime = time.Second
|
|
}
|
|
util.RetryWaitTime = *mountReadRetryTime
|
|
|
|
// 32 bits, not 64: os.FileMode is uint32, so a wider parse would let a
|
|
// nonsense umask truncate silently instead of being rejected here.
|
|
umask, umaskErr := strconv.ParseUint(*mountOptions.umaskString, 8, 32)
|
|
if umaskErr != nil {
|
|
fmt.Printf("can not parse umask %s", *mountOptions.umaskString)
|
|
return false
|
|
}
|
|
|
|
if len(args) > 0 {
|
|
return false
|
|
}
|
|
|
|
return RunMount(&mountOptions, os.FileMode(umask))
|
|
}
|
|
|
|
func ensureBucketAllowEmptyFolders(ctx context.Context, filerClient filer_pb.FilerClient, mountRoot, bucketRootPath string) error {
|
|
bucketPath, isBucketRootMount := bucketPathForMountRoot(mountRoot, bucketRootPath)
|
|
if !isBucketRootMount {
|
|
return nil
|
|
}
|
|
|
|
bucketFullPath := util.FullPath(bucketPath)
|
|
parent, _ := bucketFullPath.DirAndName()
|
|
|
|
for attempt := 0; attempt < 5; attempt++ {
|
|
entry, _, _, err := filer_pb.GetEntry(ctx, filerClient, util.FullPath(bucketPath))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if entry == nil {
|
|
return fmt.Errorf("bucket %s not found", bucketPath)
|
|
}
|
|
|
|
if value := strings.TrimSpace(string(entry.Extended[s3_constants.ExtAllowEmptyFolders])); value != "" {
|
|
return nil
|
|
}
|
|
|
|
expected := filer_pb.SnapshotExtended(entry.Extended, s3_constants.ExtAllowEmptyFolders)
|
|
if entry.Extended == nil {
|
|
entry.Extended = make(map[string][]byte)
|
|
}
|
|
entry.Extended[s3_constants.ExtAllowEmptyFolders] = []byte("true")
|
|
|
|
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
_, err := client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
|
|
Directory: parent,
|
|
Entry: entry,
|
|
ExpectedExtended: expected,
|
|
})
|
|
return err
|
|
})
|
|
if err == nil {
|
|
glog.V(3).Infof("RunMount: set bucket %s %s=true", bucketPath, s3_constants.ExtAllowEmptyFolders)
|
|
return nil
|
|
}
|
|
if status.Code(err) != codes.FailedPrecondition {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return fmt.Errorf("bucket %s attributes keep changing", bucketPath)
|
|
}
|
|
|
|
func bucketPathForMountRoot(mountRoot, bucketRootPath string) (string, bool) {
|
|
cleanPath := path.Clean("/" + strings.TrimPrefix(mountRoot, "/"))
|
|
cleanBucketRoot := path.Clean("/" + strings.TrimPrefix(bucketRootPath, "/"))
|
|
if cleanBucketRoot == "/" {
|
|
return "", false
|
|
}
|
|
prefix := cleanBucketRoot + "/"
|
|
if !strings.HasPrefix(cleanPath, prefix) {
|
|
return "", false
|
|
}
|
|
rest := strings.TrimPrefix(cleanPath, prefix)
|
|
|
|
bucketParts := strings.Split(rest, "/")
|
|
if len(bucketParts) != 1 || bucketParts[0] == "" {
|
|
return "", false
|
|
}
|
|
return cleanBucketRoot + "/" + bucketParts[0], true
|
|
}
|
|
|
|
func peerStringOrEmpty(p *string) string {
|
|
if p == nil {
|
|
return ""
|
|
}
|
|
return *p
|
|
}
|
|
|
|
// connectToFiler retries the filer handshake, returning the cluster's cipher
|
|
// setting and bucket root, and adopts the filer's digest.
|
|
func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialOption, cipher bool, bucketRootPath string, ok bool) {
|
|
// try to connect to filer
|
|
filerAddresses = pb.ServerAddresses(*option.filer).ToAddresses()
|
|
util.LoadSecurityConfiguration()
|
|
grpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client")
|
|
var err error
|
|
var digest string
|
|
for i := 0; i < 10; i++ {
|
|
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, mountFilerTokenSource(option), func(client filer_pb.SeaweedFilerClient) error {
|
|
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
|
if err != nil {
|
|
return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err)
|
|
}
|
|
cipher = resp.Cipher
|
|
bucketRootPath = resp.DirBuckets
|
|
digest = resp.Digest
|
|
return nil
|
|
})
|
|
if err == nil {
|
|
break
|
|
}
|
|
glog.V(0).Infof("failed to talk to filer %v: %v", filerAddresses, err)
|
|
glog.V(0).Infof("wait for %d seconds ...", i+1)
|
|
time.Sleep(time.Duration(i+1) * time.Second)
|
|
}
|
|
if err != nil {
|
|
glog.Errorf("failed to talk to filer %v: %v", filerAddresses, err)
|
|
return nil, nil, false, "", false
|
|
}
|
|
if err = util.AdoptFilerDigest(*option.filer, digest); err != nil {
|
|
glog.Errorf("%v", err)
|
|
return nil, nil, false, "", false
|
|
}
|
|
if bucketRootPath == "" {
|
|
bucketRootPath = "/buckets"
|
|
}
|
|
return filerAddresses, grpcDialOption, cipher, bucketRootPath, true
|
|
}
|
|
|
|
// mountFilerTokenSource reads -filer.tokenFile for each filer call, or is nil
|
|
// without it so the mount keeps its existing credentials.
|
|
func mountFilerTokenSource(option *MountOptions) security.FilerTokenSource {
|
|
if option.filerTokenFile == nil || *option.filerTokenFile == "" {
|
|
return nil
|
|
}
|
|
return security.FilerTokenFile(util.ResolvePath(*option.filerTokenFile))
|
|
}
|
|
|
|
// checkFilerTokenFile refuses options a filer token cannot serve. A filer
|
|
// refuses MountRegister, MountList and distributed locks to a scoped token,
|
|
// so peer chunk sharing and -dlm would fail at run time instead of at start.
|
|
func checkFilerTokenFile(option *MountOptions) error {
|
|
if option.filerTokenFile == nil || *option.filerTokenFile == "" {
|
|
return nil
|
|
}
|
|
if option.peerEnabled != nil && *option.peerEnabled {
|
|
return fmt.Errorf("-filer.tokenFile cannot be used with -peer.enable: the filer refuses MountRegister and MountList to scoped tokens")
|
|
}
|
|
if option.distributedLock != nil && *option.distributedLock {
|
|
return fmt.Errorf("-filer.tokenFile cannot be used with -dlm: the filer refuses distributed locks to scoped tokens")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 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
|
|
grpcDialOption grpc.DialOption
|
|
cipher bool
|
|
uidGidMapper *meta_cache.UidGidMapper
|
|
uid uint32
|
|
gid uint32
|
|
mountMode os.FileMode
|
|
mountCtime time.Time
|
|
umask os.FileMode
|
|
chunkSizeLimitMB int
|
|
cacheDirForRead string
|
|
cacheDirForWrite string
|
|
cacheMinFree *util.MinFreeSpace // the parsed -cacheMinFreeSpace
|
|
|
|
// eagerFilerCreate persists a created file's entry at create time rather
|
|
// than at flush. A platform sets it when it cannot run the flush before
|
|
// the application's close returns, so nothing that reads through the
|
|
// filer can race an unflushed close.
|
|
eagerFilerCreate bool
|
|
}
|
|
|
|
func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS {
|
|
readerCacheSizeMB := int64(256)
|
|
if option.readerCacheSizeMB != nil {
|
|
readerCacheSizeMB = *option.readerCacheSizeMB
|
|
}
|
|
return mount.NewSeaweedFileSystem(&mount.Option{
|
|
SSES3Reader: p.sseS3Reader,
|
|
MountDirectory: p.dir,
|
|
FilerAddresses: p.filerAddresses,
|
|
GrpcDialOption: p.grpcDialOption,
|
|
FilerSigningKey: security.SigningKey(util.GetViper().GetString("jwt.filer_signing.key")),
|
|
FilerSigningExpiresAfterSec: util.GetViper().GetInt("jwt.filer_signing.expires_after_seconds"),
|
|
FilerTokenSource: mountFilerTokenSource(option),
|
|
FilerMountRootPath: p.mountRoot,
|
|
VolumeReadAuth: option.volumeReadAuth != nil && *option.volumeReadAuth,
|
|
Collection: *option.collection,
|
|
Replication: *option.replication,
|
|
TtlSec: int32(*option.ttlSec),
|
|
DiskType: types.ToDiskType(*option.diskType),
|
|
ChunkSizeLimit: int64(p.chunkSizeLimitMB) * 1024 * 1024,
|
|
ConcurrentWriters: *option.concurrentWriters,
|
|
ConcurrentReaders: *option.concurrentReaders,
|
|
ReaderCacheSizeMB: readerCacheSizeMB,
|
|
CacheDirForRead: p.cacheDirForRead,
|
|
CacheSizeMBForRead: *option.cacheSizeMBForRead,
|
|
CacheMinFreeSpace: p.cacheMinFree,
|
|
CacheDirForWrite: p.cacheDirForWrite,
|
|
WriteBufferSizeMB: *option.writeBufferSizeMB,
|
|
CacheMetaTTlSec: *option.cacheMetaTtlSec,
|
|
CacheDirMaxEntries: *option.cacheDirMaxEntries,
|
|
DataCenter: *option.dataCenter,
|
|
Quota: int64(*option.collectionQuota) * 1024 * 1024,
|
|
LogicalDiskUsage: *option.logicalDiskUsage,
|
|
MountUid: p.uid,
|
|
MountGid: p.gid,
|
|
MountMode: p.mountMode,
|
|
MountCtime: p.mountCtime,
|
|
MountMtime: time.Now(),
|
|
Umask: p.umask,
|
|
VolumeServerAccess: *mountOptions.volumeServerAccess,
|
|
Cipher: p.cipher,
|
|
UidGidMapper: p.uidGidMapper,
|
|
IncludeSystemEntries: *option.includeSystemEntries,
|
|
DefaultPermissions: *option.defaultPermissions,
|
|
DisableXAttr: *option.disableXAttr,
|
|
IsMacOs: runtime.GOOS == "darwin",
|
|
MetadataFlushSeconds: *option.metadataFlushSeconds,
|
|
DirIdleEvictSec: *option.dirIdleEvictSec,
|
|
EnableDistributedLock: option.distributedLock != nil && *option.distributedLock,
|
|
ConcurrentWriteMerge: option.concurrentWriteMerge != nil && *option.concurrentWriteMerge,
|
|
WritebackCache: option.writebackCache != nil && *option.writebackCache,
|
|
NfsExport: option.nfsExport != nil && *option.nfsExport,
|
|
EagerFilerCreate: p.eagerFilerCreate,
|
|
PosixDirNlink: option.posixDirNlink != nil && *option.posixDirNlink,
|
|
AccessReport: option.accessReport != nil && *option.accessReport,
|
|
AccessReportInterval: *option.accessReportInterval,
|
|
// Peer chunk sharing
|
|
PeerEnabled: option.peerEnabled != nil && *option.peerEnabled,
|
|
PeerListen: peerStringOrEmpty(option.peerListen),
|
|
PeerAdvertise: peerStringOrEmpty(option.peerAdvertise),
|
|
PeerDataCenter: peerStringOrEmpty(option.peerDataCenter),
|
|
PeerRack: peerStringOrEmpty(option.peerRack),
|
|
})
|
|
}
|
|
|
|
// createMountRoot makes the filer-side directory the mount is rooted at.
|
|
func createMountRoot(wfs *mount.WFS, mountRoot, bucketRootPath string, filerAddresses []pb.ServerAddress) bool {
|
|
if err := ensureMountRootDirectory(context.Background(), wfs, mountRoot); err != nil {
|
|
fmt.Printf("failed to create dir %s on filer %s: %v\n", mountRoot, filerAddresses, err)
|
|
return false
|
|
}
|
|
if err := ensureBucketAllowEmptyFolders(context.Background(), wfs, mountRoot, bucketRootPath); err != nil {
|
|
fmt.Printf("failed to set bucket auto-remove-empty-folders policy for %s: %v\n", mountRoot, err)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ensureMountRootDirectory creates the mount root only when it is missing. The
|
|
// filer answers a non-exclusive create of an existing path by replacing the
|
|
// entry, keeping only its crtime and inode, so creating the root again at every
|
|
// mount start would reset its mode and owner and drop what only the filer
|
|
// holds: its extended attributes and, when the root is a bucket, the bucket's
|
|
// quota and the settings S3 keeps on it.
|
|
func ensureMountRootDirectory(ctx context.Context, filerClient filer_pb.FilerClient, mountRoot string) error {
|
|
mountRootPath := util.FullPath(mountRoot)
|
|
if mountRootPath == "/" {
|
|
return nil
|
|
}
|
|
entry, _, _, err := filer_pb.GetEntry(ctx, filerClient, mountRootPath)
|
|
if err == nil {
|
|
return mountRootMustBeDirectory(mountRoot, entry)
|
|
}
|
|
if !errors.Is(err, filer_pb.ErrNotFound) {
|
|
return err
|
|
}
|
|
parent, name := mountRootPath.DirAndName()
|
|
if err := filer_pb.MkdirExclusive(ctx, filerClient, parent, name, nil); err != nil {
|
|
// Another client may have created it since the lookup. A filer that
|
|
// predates error codes reports that only as text, so look again rather
|
|
// than match the error.
|
|
entry, _, _, lookupErr := filer_pb.GetEntry(ctx, filerClient, mountRootPath)
|
|
if lookupErr != nil {
|
|
if errors.Is(lookupErr, filer_pb.ErrNotFound) {
|
|
return fmt.Errorf("mount root %s does not exist and could not be created: %w", mountRoot, err)
|
|
}
|
|
return err
|
|
}
|
|
return mountRootMustBeDirectory(mountRoot, entry)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func mountRootMustBeDirectory(mountRoot string, entry *filer_pb.Entry) error {
|
|
if !entry.GetIsDirectory() {
|
|
return fmt.Errorf("%s: %w", mountRoot, filer_pb.ErrExistingIsFile)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// mountSocketCleanup returns a func that removes the control socket this mount
|
|
// listens on, unless a later mount of the same directory has replaced it.
|
|
func mountSocketCleanup(socketPath string) func() {
|
|
listened, err := os.Lstat(socketPath)
|
|
if err != nil {
|
|
return func() {}
|
|
}
|
|
var once sync.Once
|
|
return func() {
|
|
once.Do(func() {
|
|
current, err := os.Lstat(socketPath)
|
|
if err != nil || !os.SameFile(current, listened) {
|
|
return
|
|
}
|
|
if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {
|
|
glog.Warningf("remove mount socket %s: %v", socketPath, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// serveMountGrpc exposes the local control socket used by "weed mount.stats".
|
|
func serveMountGrpc(wfs *mount.WFS, listener net.Listener) {
|
|
grpcS := pb.NewGrpcServer()
|
|
mount_pb.RegisterSeaweedMountServer(grpcS, wfs)
|
|
reflection.Register(grpcS)
|
|
go grpcS.Serve(listener)
|
|
}
|
|
|
|
// resolveMountRoot trims the trailing slash the filer path must not carry.
|
|
func resolveMountRoot(filerMountRootPath string) string {
|
|
mountRoot := filerMountRootPath
|
|
if mountRoot != "/" && strings.HasSuffix(mountRoot, "/") {
|
|
mountRoot = mountRoot[0 : len(mountRoot)-1]
|
|
}
|
|
return mountRoot
|
|
}
|
|
|
|
// parseCacheMinFreeSpace reads -cacheMinFreeSpace, written like the volume
|
|
// server's -minFreeSpace.
|
|
func parseCacheMinFreeSpace(option *MountOptions) (*util.MinFreeSpace, error) {
|
|
if option.cacheMinFreeSpace == nil {
|
|
return nil, nil
|
|
}
|
|
minFreeSpace, err := util.ParseMinFreeSpace(*option.cacheMinFreeSpace)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cacheMinFreeSpace %q: want a percentage like 1 or a size like 10GiB", *option.cacheMinFreeSpace)
|
|
}
|
|
return minFreeSpace, nil
|
|
}
|
|
|
|
// resolveCacheDirs falls back to the read cache when no write cache is set.
|
|
func resolveCacheDirs(option *MountOptions) (string, string) {
|
|
cacheDirForRead := util.ResolvePath(*option.cacheDirForRead)
|
|
cacheDirForWrite := util.ResolvePath(*option.cacheDirForWrite)
|
|
if cacheDirForWrite == "" {
|
|
cacheDirForWrite = cacheDirForRead
|
|
}
|
|
return cacheDirForRead, cacheDirForWrite
|
|
}
|
|
|
|
// volumeName labels the mount where the platform shows one, in Finder and in
|
|
// Explorer. An explicit override always wins; failing that, the mounted path
|
|
// names the disk, then the mount point; the filer address, which every mount
|
|
// from one filer shares, is the last resort.
|
|
func volumeName(filer, filerMountRootPath, dir, override string) string {
|
|
name := override
|
|
if name == "" {
|
|
name = lastSegment(filerMountRootPath)
|
|
}
|
|
if name == "" {
|
|
name = lastSegment(dir)
|
|
}
|
|
if name == "" {
|
|
name = filer
|
|
}
|
|
return strings.ReplaceAll(name, ",", "+")
|
|
}
|
|
|
|
// lastSegment is the name a path ends with, and "" for the ones that name no
|
|
// disk: the root, "." and a bare Windows drive letter.
|
|
func lastSegment(p string) string {
|
|
name := path.Base(strings.ReplaceAll(p, `\`, "/"))
|
|
if name == "/" || name == "." || strings.HasSuffix(name, ":") {
|
|
return ""
|
|
}
|
|
return name
|
|
}
|
|
|
|
func configureMountMemory(option *MountOptions) error {
|
|
if option.readerCacheSizeMB != nil && (*option.readerCacheSizeMB <= 0 || *option.readerCacheSizeMB > math.MaxInt64>>20) {
|
|
return fmt.Errorf("readerCacheSizeMB must be positive and fit in an int64 byte budget")
|
|
}
|
|
if option.memoryLimitMB != nil {
|
|
if *option.memoryLimitMB < 0 || *option.memoryLimitMB > math.MaxInt64>>20 {
|
|
return fmt.Errorf("memoryLimitMB must be non-negative and fit in an int64 byte limit")
|
|
}
|
|
if *option.memoryLimitMB > 0 {
|
|
debug.SetMemoryLimit(*option.memoryLimitMB << 20)
|
|
}
|
|
}
|
|
return nil
|
|
}
|