Files
seaweedfs/weed/remote_storage/client_cache.go
T
5c92a54a12 remote: reuse one guarded remote storage client per configuration (#12189)
* remote: reuse one guarded remote storage client per configuration

BuildGuardedRemoteStorageClient (the filer's lazy remote stat and list,
remote deletes and renames, the volume server's cold reads, the S3
gateway's remote reads) built a new client, with its own http.Transport,
on every call. Each transport kept its connection idle for
IdleConnTimeout (60s) and was never reused or closed, so a steady stream
of remote lookups held one open connection per request. An endpoint
that caps connections per source then refuses every new connection.

- remote_storage: GetRemoteStorage's per-name cache becomes a bounded
  LRU (WEED_REMOTE_CLIENT_CACHE_MAX, default 64) keyed by kind, name, a
  hash of the whole configuration and a credentials version, built
  outside the lock once per key (singleflight) from a copy of the
  configuration. A client leaving the cache has its idle connections
  closed. GetRemoteStorageWith exposes the cache to other builders.
- BuildGuardedRemoteStorageClient caches the guarded client per
  configuration. The endpoint is checked against the deny-list when a
  client is built; every new connection still dials through the guarded
  dialer. A gcs credentials file, and for an S3-compatible remote using
  the default credential chain the shared credentials file and AWS_*
  variables, are part of the key by content.
- The shared transport keeps 32 idle connections per host, caps
  connections per host (WEED_REMOTE_MAX_CONNS_PER_HOST, default 64) and
  has dial, TLS handshake and response header deadlines, so a hung
  remote frees its slots.
- The filer drops the clients of removed remotes (and all but the newest
  client per name) on every /etc/remote reload, also when /etc/remote
  does not exist; reloads are serialized.

* remote: drop clients whose build spans a reload or whose remote is gone

* server: hash the shared AWS config file into the guarded credential version

* server: bound a stalled body on the shared remote transport

* remote: waive path-injection on the configured credentials file

* remote: keep caching remotes the local filer does not name

* remote: drop the inline codeql waiver the analyzer ignores

* remote: version the plain gcs client's credentials file

* remote: hash the environment's inline gcs credentials

GOOGLE_APPLICATION_CREDENTIALS can hold the JSON itself, which the gcs
client accepts; it is not in the configuration hash, so a changed value
kept the old client.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* remote: version the well-known gcs credentials file

With neither the configuration nor GOOGLE_APPLICATION_CREDENTIALS set,
the SDK reads application_default_credentials.json; rotating it left the
cache key unchanged and the old client behind.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* remote: share the gcs credentials version with the guarded client

The guarded gcs client resolves the same environment and well-known
credentials as the plain one; keying it only on a configured path left
those rotations invisible to the cache.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* remote: version s3 keys resolved from the environment

A remote whose access and secret keys both arrive through its type's
environment fallback (aliyun, baidu, contabo, filebase, storj, tencent)
never entered the default-chain branch of guardedCredentialsVersion, so
an in-process environment change kept serving the stale cached client.
The version now hashes the resolved keys for every S3-compatible remote.

* volume: reuse one remote storage client per configuration (rust)

fetch_and_write_needle built a fresh aws_sdk_s3::Client per request,
so every cold read kept its connector's idle connections without ever
reusing them — the same leak the Go side fixes. Cache clients keyed by
the configuration's protobuf encoding in an LRU of
WEED_REMOTE_CLIENT_CACHE_MAX entries (default 64), mirroring
weed/remote_storage/client_cache.go. An evicted entry drops the client's
last Arc and with it the connector's idle connections. The per-request
endpoint validation is unchanged: Rust has no dial-time guard yet, so
the up-front DNS check stays on every call.

---------

Co-authored-by: user.email <chrislusf@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-29 00:57:37 -07:00

302 lines
10 KiB
Go

package remote_storage
import (
"container/list"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/sync/singleflight"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// Remote storage clients are cached, one per (kind, configuration,
// credentials version).
//
// Each client carries its own HTTP transport. A client built per request keeps
// its connection open for the transport's idle timeout and never reuses it, so
// a steady stream of lazy remote stats, cold reads or remote deletes holds one
// open connection per request; a storage endpoint that caps connections per
// source then refuses every new one. So clients are cached:
// - the key is the kind ("" for the plain client of GetRemoteStorage,
// "guarded" for the servers' SSRF-guarded one; the two are never shared),
// the configuration's name, a hash of the whole configuration and a
// credentials version (the content hash of a credentials file the
// configuration points at, which can change while the configuration does
// not). Two configurations under one name are two entries; neither evicts
// the other.
// - the cache is an LRU of WEED_REMOTE_CLIENT_CACHE_MAX entries (default 64).
// - a client is built outside the cache's lock, once per key at a time
// (singleflight): a slow build (a DNS check, a credentials file) never
// stalls the lookups of other keys.
// - a client leaving the cache (evicted, or dropped by RetainRemoteStorages)
// has its idle connections closed at once and again after a grace period,
// for the connections its in-flight requests return to the pool afterwards.
// - RetainRemoteStorages (every filer reload) also retires, per kind and
// name, every entry but the newest: a key rotation, a new endpoint or a new
// credentials file leaves no client of the old configuration behind. A
// build finishing after a reload never enters the cache either: it is
// retired instead when a reload passed while it was running.
// - the cached client is built from a copy of the configuration, so a caller
// changing its value later changes nothing.
// ClientBuild builds the client of a configuration and, optionally, a function that closes its idle connections.
type ClientBuild func(conf *remote_pb.RemoteConf) (client RemoteStorageClient, closeIdle func(), err error)
type cachedClient struct {
key string
kind string
name string
born uint64 // insertion order: retain keeps only the newest per kind and name
generation uint64 // the retain generation the build started under
client RemoteStorageClient
closeIdle func()
}
type clientCache struct {
mu sync.Mutex
max int
order *list.List // front: most recently used
entries map[string]*list.Element
building singleflight.Group
births uint64
generation uint64 // bumped by every retain: a build started under an older one is stale
grace time.Duration
afterFunc func(time.Duration, func()) // tests
}
var remoteClients = newClientCache(clientCacheMaxFromEnv(), time.Minute)
func newClientCache(max int, grace time.Duration) *clientCache {
return &clientCache{max: max, order: list.New(), entries: map[string]*list.Element{}, grace: grace,
afterFunc: func(d time.Duration, f func()) { time.AfterFunc(d, f) }}
}
func clientCacheMaxFromEnv() int {
if v := os.Getenv("WEED_REMOTE_CLIENT_CACHE_MAX"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
glog.Warningf("WEED_REMOTE_CLIENT_CACHE_MAX=%q is not a positive number; using 64", v)
}
return 64
}
// clientKey names a configuration exactly: kind, name, a hash of its deterministic encoding, and the credentials version.
func clientKey(kind string, conf *remote_pb.RemoteConf, version string) string {
encoded, _ := proto.MarshalOptions{Deterministic: true}.Marshal(conf)
sum := sha256.Sum256(encoded)
return kind + "\x00" + conf.GetName() + "\x00" + hex.EncodeToString(sum[:16]) + "\x00" + version
}
func (c *clientCache) get(kind string, conf *remote_pb.RemoteConf, version string, build ClientBuild) (RemoteStorageClient, error) {
key := clientKey(kind, conf, version)
if client := c.lookup(key); client != nil {
return client, nil
}
own := proto.Clone(conf).(*remote_pb.RemoteConf)
v, err, _ := c.building.Do(key, func() (interface{}, error) {
if client := c.lookup(key); client != nil { // another caller's build finished between the lookup and Do
return client, nil
}
generation := c.generationSnapshot()
client, closeIdle, err := build(own)
if err != nil {
return nil, err
}
c.insert(&cachedClient{key: key, kind: kind, name: own.GetName(), generation: generation, client: client, closeIdle: closeIdle})
return client, nil
})
if err != nil {
return nil, err
}
return v.(RemoteStorageClient), nil
}
func (c *clientCache) lookup(key string) RemoteStorageClient {
c.mu.Lock()
defer c.mu.Unlock()
if el, ok := c.entries[key]; ok {
c.order.MoveToFront(el)
return el.Value.(*cachedClient).client
}
return nil
}
func (c *clientCache) generationSnapshot() uint64 {
c.mu.Lock()
defer c.mu.Unlock()
return c.generation
}
func (c *clientCache) insert(e *cachedClient) {
var evicted []*cachedClient
c.mu.Lock()
if el, ok := c.entries[e.key]; ok { // cannot happen under singleflight; keep the first, retire the newcomer
c.order.MoveToFront(el)
evicted = append(evicted, e)
} else if e.generation < c.generation {
// a reload ran while the build was in flight: the caller keeps the
// client but it never enters the cache
evicted = append(evicted, e)
} else {
c.births++
e.born = c.births
c.entries[e.key] = c.order.PushFront(e)
for c.order.Len() > c.max {
back := c.order.Back()
old := back.Value.(*cachedClient)
c.order.Remove(back)
delete(c.entries, old.key)
evicted = append(evicted, old)
}
}
c.mu.Unlock()
for _, old := range evicted {
c.retire(old)
}
}
// retire closes a client's idle connections now and again after the grace period (requests in flight when it left the
// cache return their connections to its pool afterwards).
func (c *clientCache) retire(e *cachedClient) {
if e.closeIdle == nil {
return
}
e.closeIdle()
c.afterFunc(c.grace, e.closeIdle)
}
func (c *clientCache) retain(names map[string]bool) {
var dropped []*cachedClient
c.mu.Lock()
c.generation++
newest := map[string]uint64{} // kind and name -> the newest entry's birth
for _, el := range c.entries {
e := el.Value.(*cachedClient)
if k := e.kind + "\x00" + e.name; e.born > newest[k] {
newest[k] = e.born
}
}
for key, el := range c.entries {
e := el.Value.(*cachedClient)
if names[e.name] && e.born == newest[e.kind+"\x00"+e.name] {
continue
}
c.order.Remove(el)
delete(c.entries, key)
dropped = append(dropped, e)
}
c.mu.Unlock()
for _, e := range dropped {
c.retire(e)
}
}
func (c *clientCache) len() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.order.Len()
}
// GetRemoteStorage returns the plain client of a configuration (one per configuration).
func GetRemoteStorage(remoteConf *remote_pb.RemoteConf) (RemoteStorageClient, error) {
return GetRemoteStorageWith("", remoteConf, CredentialsVersion(remoteConf), func(conf *remote_pb.RemoteConf) (RemoteStorageClient, func(), error) {
client, err := makeRemoteStorageClient(conf)
if err != nil {
return nil, nil, fmt.Errorf("make remote storage client %s: %w", conf.GetName(), err)
}
return client, nil, nil
})
}
// GetRemoteStorageWith returns the cached client of one kind for a configuration and credentials version, building it with
// build (given a copy of the configuration) when there is none. version names whatever the client reads at build time
// that the configuration does not hold (a credentials file's content hash); "" when nothing.
func GetRemoteStorageWith(kind string, remoteConf *remote_pb.RemoteConf, version string, build ClientBuild) (RemoteStorageClient, error) {
return remoteClients.get(kind, remoteConf, version, build)
}
// CredentialsVersion names what a gcs client, plain or guarded, reads at
// build time that its configuration does not hold: a credentials file's
// content, inline JSON from GOOGLE_APPLICATION_CREDENTIALS, or the well-known
// application default credentials file when neither names one. The
// configuration's own inline JSON needs none; it is already inside the
// configuration's hash. "" for a non-gcs remote.
func CredentialsVersion(remoteConf *remote_pb.RemoteConf) string {
if remoteConf.GetType() != "gcs" {
return ""
}
path := remoteConf.GetGcsGoogleApplicationCredentials()
fromEnv := false
if path == "" {
path, fromEnv = os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"), true
}
if strings.HasPrefix(path, "{") {
if !fromEnv {
return ""
}
sum := sha256.Sum256([]byte(path))
return hex.EncodeToString(sum[:16])
}
if path == "" {
path = wellKnownCredentialsFile()
}
return FileVersion(path)
}
// wellKnownCredentialsFile is the application default credentials file the
// gcs SDK reads when neither the configuration nor
// GOOGLE_APPLICATION_CREDENTIALS names one.
func wellKnownCredentialsFile() string {
const f = "application_default_credentials.json"
if runtime.GOOS == "windows" {
return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
}
home := os.Getenv("HOME")
if home == "" {
if u, err := user.Current(); err == nil {
home = u.HomeDir
}
}
return filepath.Join(home, ".config", "gcloud", f)
}
// RetainRemoteStorages drops, and closes the idle connections of, every cached client whose configuration name is not in
// names, and every client of a name but its newest: a remote removed from /etc/remote, or the old configuration of a
// changed one, keeps no client and no pool. The filer calls it on every reload.
func RetainRemoteStorages(names map[string]bool) {
remoteClients.retain(names)
}
// FileVersion is the credentials version of a file: a hash of its content, "" when it cannot be read (the build then
// reads it, or fails, as it would without the cache).
func FileVersion(path string) string {
if path == "" {
return ""
}
data, err := os.ReadFile(util.ResolvePath(path)) // "~/…" as the gcs client reads it
if err != nil {
return ""
}
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:16])
}
// ResetRemoteStorageClients empties the cache, retiring every client. For tests.
func ResetRemoteStorageClients() {
remoteClients.retain(nil)
}