mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c52e2b9d51 | ||
|
|
ba31775360 | ||
|
|
4a43a9f014 | ||
|
|
e1aca2255c | ||
|
|
ad4015eecd | ||
|
|
d001a706fb | ||
|
|
ce7a80ca9f | ||
|
|
a4fae5a244 |
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
[codespell]
|
||||
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
|
||||
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go,./seaweed-block
|
||||
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go
|
||||
check-hidden = true
|
||||
# Ignore camelCase and PascalCase identifiers (very common in Go/Rust/JS
|
||||
# source, e.g. allLocations, publishErr, ReadInside, FlushInterval).
|
||||
|
||||
@@ -93,8 +93,8 @@ RUN mkdir -p /etc/seaweedfs
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer.toml /etc/seaweedfs/filer.toml
|
||||
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
|
||||
|
||||
# FIPS 140-3 mode is on by default for every process (entrypoint.sh)
|
||||
# To disable: docker run -e WEED_FIPS_MODE=off ...
|
||||
# FIPS 140-3 mode is ON by default (Go 1.24+)
|
||||
# To disable: docker run -e GODEBUG=fips140=off ...
|
||||
|
||||
# Install dependencies and create non-root user
|
||||
RUN apk upgrade --no-cache && \
|
||||
|
||||
+9
-30
@@ -1,5 +1,14 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Enable FIPS 140-3 mode by default (Go 1.24+)
|
||||
# To disable: docker run -e GODEBUG=fips140=off ...
|
||||
# For strict mode: docker run -e GODEBUG=fips140=only ...
|
||||
# The default goes first: Go applies the last of repeated GODEBUG settings, so
|
||||
# the caller's fips140 value wins.
|
||||
# Transparent huge pages are a host-wide setting this image cannot change; to
|
||||
# turn them off for this process only, append GODEBUG=disablethp=1.
|
||||
export GODEBUG="fips140=on${GODEBUG:+,$GODEBUG}"
|
||||
|
||||
# Fix permissions for mounted volumes
|
||||
# If /data is mounted from host, it might have different ownership
|
||||
# Fix this by ensuring seaweed user owns the directory
|
||||
@@ -40,36 +49,6 @@ if [ "$(id -u)" = "0" ]; then
|
||||
exec su-exec seaweed "$0" "$@"
|
||||
fi
|
||||
|
||||
# FIPS 140-3 mode is on by default, for the Go processes and the Rust
|
||||
# binaries alike. To pick another mode: docker run -e WEED_FIPS_MODE=off (or
|
||||
# strict). A fips.mode in security.toml alone cannot change it, since Go
|
||||
# processes would still get this mode's fips140 and refuse to start.
|
||||
# WEED_FIPS_MODE_DEFAULT is the mode when nothing else sets one; set it empty
|
||||
# to leave every process in its own default (fips140=off for Go, off for Rust).
|
||||
# A fips140 the caller puts in GODEBUG still picks the mode, for the Rust
|
||||
# binaries as well, unless WEED_FIPS_MODE is set, but is deprecated and warns;
|
||||
# a Go process refuses to start when its fips140 differs from WEED_FIPS_MODE or
|
||||
# fips.mode.
|
||||
# Transparent huge pages are a host-wide setting this image cannot change; to
|
||||
# turn them off for this process only, append GODEBUG=disablethp=1.
|
||||
export WEED_FIPS_MODE_DEFAULT="${WEED_FIPS_MODE_DEFAULT-on}"
|
||||
godebug_fips140="$(printf '%s\n' "$GODEBUG" | tr ',' '\n' | sed -n 's/^fips140=/=/p' | tail -n 1)"
|
||||
case "$godebug_fips140" in
|
||||
=off | =) WEED_FIPS_MODE_DEFAULT=off ;;
|
||||
=on | =debug) WEED_FIPS_MODE_DEFAULT=on ;;
|
||||
=only) WEED_FIPS_MODE_DEFAULT=strict ;;
|
||||
esac
|
||||
if [ -n "$godebug_fips140" ] && [ -z "$WEED_FIPS_MODE" ]; then
|
||||
echo "Warning: choosing the FIPS mode with GODEBUG=fips140 is deprecated; set WEED_FIPS_MODE=off, on or strict, which also covers the Rust binaries when they start without this entrypoint." >&2
|
||||
fi
|
||||
case "${WEED_FIPS_MODE:-$WEED_FIPS_MODE_DEFAULT}" in
|
||||
off) fips140=off ;;
|
||||
on) fips140=on ;;
|
||||
strict) fips140=only ;;
|
||||
*) fips140= ;;
|
||||
esac
|
||||
export GODEBUG="${fips140:+fips140=$fips140}${fips140:+${GODEBUG:+,}}${GODEBUG}"
|
||||
|
||||
for f in /etc/resolv.conf /etc/hosts; do
|
||||
if [ -f "$f" ] && [ ! -r "$f" ]; then
|
||||
echo "Warning: $f is not readable by uid $(id -u), so host name lookups may fail. Make it world-readable (0644)." >&2
|
||||
|
||||
@@ -385,16 +385,11 @@ filer:
|
||||
apply without a restart. Other files in the Secret, such as an audit log config, still
|
||||
need one, and so do changes to the values the chart generates its own Secret from, such
|
||||
as `s3.credentials`.
|
||||
- Every reload also re-creates the KMS providers configured in the identities file, and
|
||||
drops the ones it no longer lists. A file whose identities don't parse changes neither.
|
||||
A provider that fails to load keeps its previous instance, unless it's the one S3 uses,
|
||||
which fails the KMS reload. S3 uses `default_provider`, or the first provider by name
|
||||
when it isn't set, so set it when you list more than one, as adding a provider whose
|
||||
name sorts first would switch S3 to it. The `local` provider reads its `keys` list
|
||||
again, so objects encrypted under those keys stay readable. The keys it generates in
|
||||
memory are lost on a reload, as on a restart, so list every key that protects objects
|
||||
you need to keep, and give the alias `aws/s3` to the one that should serve requests
|
||||
naming no key.
|
||||
- Every reload also re-creates the KMS providers configured in the identities file. The
|
||||
`local` provider reads its `keys` list again, so objects encrypted under those keys stay
|
||||
readable. The keys it generates in memory are lost on a reload, as on a restart, so list
|
||||
every key that protects objects you need to keep, and give the alias `aws/s3` to the one
|
||||
that should serve requests naming no key.
|
||||
- The pod shares its process namespace (see [Sharing the process namespace](#sharing-the-process-namespace)),
|
||||
so the sidecar can see SeaweedFS. It uses the component's image and container security
|
||||
context, because it must run as the same user as SeaweedFS to signal it. If it can't
|
||||
|
||||
+1040
-1025
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 54 KiB |
@@ -22,10 +22,6 @@ use std::sync::OnceLock;
|
||||
pub const SETTING: &str = "fips.mode";
|
||||
/// The environment variable that overrides [`SETTING`].
|
||||
pub const ENV: &str = "WEED_FIPS_MODE";
|
||||
/// The environment variable holding the mode that applies when neither
|
||||
/// [`ENV`] nor [`SETTING`] sets one; the Docker image's entrypoint sets it to
|
||||
/// the mode it runs every process in.
|
||||
pub const DEFAULT_ENV: &str = "WEED_FIPS_MODE_DEFAULT";
|
||||
|
||||
/// The modes `fips.mode` names. Unset reads as [`FipsMode::Off`], which is
|
||||
/// how every Rust binary behaved before the setting existed.
|
||||
@@ -129,30 +125,24 @@ impl fmt::Display for Setting {
|
||||
/// Resolves the mode of a process whose own security.toml loader read
|
||||
/// `file_value` for `fips.mode` from `file` (`None` when there is no file or
|
||||
/// it does not set the key): `WEED_FIPS_MODE` when set and non-empty, else
|
||||
/// `file_value` when non-empty, else `WEED_FIPS_MODE_DEFAULT`, the mode the
|
||||
/// Docker image's entrypoint states, else [`FipsMode::Off`]. An unknown value
|
||||
/// is an error naming where it came from.
|
||||
/// `file_value`, else [`FipsMode::Off`]. An unknown value is an error naming
|
||||
/// where it came from.
|
||||
pub fn resolve(
|
||||
file: Option<&Path>,
|
||||
file_value: Option<&str>,
|
||||
env: &dyn Fn(&str) -> Option<OsString>,
|
||||
) -> Result<Setting, FipsModeError> {
|
||||
let from = |name: &'static str| {
|
||||
env(name)
|
||||
.map(|v| v.to_string_lossy().into_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(|v| (name.to_string(), v))
|
||||
};
|
||||
let from_env = env(ENV)
|
||||
.map(|v| v.to_string_lossy().into_owned())
|
||||
.filter(|v| !v.is_empty());
|
||||
let from_file = || {
|
||||
let source = match file {
|
||||
Some(path) => format!("{}: {SETTING}", path.display()),
|
||||
None => SETTING.to_string(),
|
||||
};
|
||||
file_value
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| (source, value.to_string()))
|
||||
file_value.map(|value| (source, value.to_string()))
|
||||
};
|
||||
let Some((source, value)) = from(ENV).or_else(from_file).or_else(|| from(DEFAULT_ENV)) else {
|
||||
let Some((source, value)) = from_env.map(|v| (ENV.to_string(), v)).or_else(from_file) else {
|
||||
return Ok(Setting {
|
||||
mode: FipsMode::Off,
|
||||
source: None,
|
||||
@@ -257,28 +247,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_default_applies_only_when_nothing_else_sets_the_mode() {
|
||||
let env = env_of(&[("WEED_FIPS_MODE_DEFAULT", "on")]);
|
||||
let setting = resolve(Some(Path::new(FILE_PATH)), Some(""), &env).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
assert_eq!(setting.to_string(), "FIPS mode on (WEED_FIPS_MODE_DEFAULT)");
|
||||
assert_eq!(resolve(None, None, &env).unwrap().mode, FipsMode::On);
|
||||
assert_eq!(
|
||||
resolve(Some(Path::new(FILE_PATH)), Some("strict"), &env)
|
||||
.unwrap()
|
||||
.mode,
|
||||
FipsMode::Strict
|
||||
);
|
||||
let both = env_of(&[("WEED_FIPS_MODE_DEFAULT", "on"), ("WEED_FIPS_MODE", "off")]);
|
||||
assert_eq!(resolve(None, None, &both).unwrap().mode, FipsMode::Off);
|
||||
let unknown = env_of(&[("WEED_FIPS_MODE_DEFAULT", "yes")]);
|
||||
assert_eq!(
|
||||
resolve(None, None, &unknown).unwrap_err().to_string(),
|
||||
"WEED_FIPS_MODE_DEFAULT is \"yes\"; want off, on or strict"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_environment_variable_counts_as_unset() {
|
||||
let env = env_of(&[("WEED_FIPS_MODE", "")]);
|
||||
|
||||
@@ -828,41 +828,6 @@ fn replica_request_timeout(body_len: usize) -> std::time::Duration {
|
||||
)
|
||||
}
|
||||
|
||||
/// How a pooled connection the peer has closed fails a request, depending on
|
||||
/// when its close reached this side. Mirrors Go's inner resend in
|
||||
/// `upload_content`.
|
||||
fn is_stale_connection_error(err: &reqwest::Error) -> bool {
|
||||
let mut source = std::error::Error::source(err);
|
||||
while let Some(e) = source {
|
||||
if let Some(io) = e.downcast_ref::<std::io::Error>()
|
||||
&& matches!(
|
||||
io.kind(),
|
||||
std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
source = e.source();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Sends a replica forward, once more on a new connection when the first
|
||||
/// attempt rode a pooled connection the peer had closed.
|
||||
async fn send_replica_request(
|
||||
request: reqwest::RequestBuilder,
|
||||
) -> reqwest::Result<reqwest::Response> {
|
||||
let resend = request.try_clone();
|
||||
let sent = request.send().await;
|
||||
match resend {
|
||||
Some(resend) if sent.as_ref().is_err_and(is_stale_connection_error) => {
|
||||
tracing::debug!("resend replica request: {:?}", sent.err());
|
||||
resend.send().await
|
||||
}
|
||||
_ => sent,
|
||||
}
|
||||
}
|
||||
|
||||
fn replica_request(
|
||||
client: &reqwest::Client,
|
||||
method: axum::http::Method,
|
||||
@@ -1013,7 +978,7 @@ async fn do_replicated_request(
|
||||
}
|
||||
|
||||
futures.push(async move {
|
||||
match send_replica_request(req_builder).await {
|
||||
match req_builder.send().await {
|
||||
Ok(r)
|
||||
if r.status().is_success()
|
||||
|| (allow_delete && r.status() == StatusCode::NOT_FOUND) =>
|
||||
@@ -5742,46 +5707,6 @@ pub(crate) mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A replica that resets the connection mid-body, as one closing a
|
||||
/// pooled connection at its idle timeout does, gets the forward once more.
|
||||
#[tokio::test]
|
||||
async fn test_replicated_write_resends_after_a_connection_reset() {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let peer = listener.local_addr().unwrap();
|
||||
let (received, mut receipts) = tokio::sync::mpsc::unbounded_channel();
|
||||
tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut head = vec![0u8; 1024];
|
||||
let _ = socket.read(&mut head).await;
|
||||
socket.set_zero_linger().unwrap();
|
||||
drop(socket);
|
||||
let app = axum::Router::new()
|
||||
.fallback(move |body: bytes::Bytes| {
|
||||
let _ = received.send(body.len());
|
||||
async { StatusCode::CREATED }
|
||||
})
|
||||
.layer(axum::extract::DefaultBodyLimit::disable());
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
let state = remote_manifest_state(&tmp, spawn_lookup(peer).await);
|
||||
let body = bytes::Bytes::from(vec![7u8; 8 << 20]);
|
||||
let sent = do_replicated_request(
|
||||
&state,
|
||||
1,
|
||||
axum::http::Method::POST,
|
||||
"/1,01ab",
|
||||
"",
|
||||
&axum::http::HeaderMap::new(),
|
||||
Some(body.clone()),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
sent.expect("the resend reaches the replica on a new connection");
|
||||
assert_eq!(receipts.try_recv(), Ok(body.len()));
|
||||
}
|
||||
|
||||
/// A peer that accepts the connection but never answers (a silent
|
||||
/// partition after connect) must fail the forward at the bound, not hold
|
||||
/// the write until TCP gives up.
|
||||
|
||||
@@ -26,3 +26,8 @@ TestIntegration/FsMkdir/FsEncoding/trailing_VT # name with a vertical tab liste
|
||||
# BucketAlreadyOwnedByYou, which rclone expects only with use_already_exists set;
|
||||
# the SeaweedFS provider defaults it to false and rclone.conf keeps that (see there).
|
||||
TestIntegration/FsMkdir/FsPutFiles/Internal/Versions/Mkdir # rclone provider quirk use_already_exists=false
|
||||
|
||||
# The test itself, not its subtests: FsMkdir ends by removing the test bucket,
|
||||
# and DeleteBucket answers 409 BucketNotEmpty although no keys are left -
|
||||
# leftover empty directories or FsEncoding objects that were not deleted.
|
||||
TestIntegration/FsMkdir # DeleteBucket returns BucketNotEmpty at the end of the run
|
||||
@@ -48,7 +48,7 @@ func main() {
|
||||
|
||||
assignResult, targetUrl := genFile(grpcDialOption, i)
|
||||
|
||||
util_http.Delete(context.Background(), targetUrl, string(assignResult.Auth))
|
||||
util_http.Delete(targetUrl, string(assignResult.Auth))
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,6 @@ var jobTypeLaneMap = map[string]SchedulerLane{
|
||||
"s3_lifecycle": LaneLifecycle,
|
||||
"filer_ttl": LaneLifecycle,
|
||||
"meta_log_purge": LaneLifecycle,
|
||||
"dir_usage": LaneLifecycle,
|
||||
|
||||
// Lance table maintenance. Without these the job types fall back to the
|
||||
// default lane, which serialises everything under the cluster admin lock
|
||||
|
||||
@@ -240,7 +240,7 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
|
||||
if isSecure {
|
||||
jwtAuthorization = operation.LookupJwt(context.Background(), b.masterClient.GetMaster(context.Background()), b.grpcDialOption, df.fp.Fid)
|
||||
}
|
||||
if e := util_http.Delete(context.Background(), fmt.Sprintf("http://%s/%s", df.fp.Server, df.fp.Fid), string(jwtAuthorization)); e == nil {
|
||||
if e := util_http.Delete(fmt.Sprintf("http://%s/%s", df.fp.Server, df.fp.Fid), string(jwtAuthorization)); e == nil {
|
||||
s.completed++
|
||||
} else {
|
||||
s.failed++
|
||||
|
||||
@@ -15,7 +15,7 @@ func TestMiniDefaultPluginJobTypes(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("buildPluginWorkerHandlers(mini default) err = %v", err)
|
||||
}
|
||||
if len(handlers) != 11 {
|
||||
t.Fatalf("expected mini default job types to include 11 handlers, got %d", len(handlers))
|
||||
if len(handlers) != 10 {
|
||||
t.Fatalf("expected mini default job types to include 10 handlers, got %d", len(handlers))
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,9 @@
|
||||
# A set env var wins over the file, so the file can stay empty (or absent).
|
||||
|
||||
# The FIPS 140-3 mode of every process that reads this file: "off", "on" or
|
||||
# "strict" (WEED_FIPS_MODE). Unset, WEED_FIPS_MODE_DEFAULT applies, which the
|
||||
# Docker image's entrypoint sets to "on"; without it each process stays as it
|
||||
# is. Go processes take the mode from GODEBUG and refuse to start when it
|
||||
# differs: "off" needs fips140=off, "on" needs fips140=on, "strict" needs
|
||||
# fips140=only. The Rust
|
||||
# "strict" (WEED_FIPS_MODE). Unset leaves each process as it is. Go processes
|
||||
# take the mode from GODEBUG and refuse to start when it differs: "off" needs
|
||||
# fips140=off, "on" needs fips140=on, "strict" needs fips140=only. The Rust
|
||||
# volume server, workers and vector engine take it from here: under "on" and
|
||||
# "strict" their TLS offers and accepts only the FIPS 140-3 versions, cipher
|
||||
# suites, key exchange groups and signature schemes Go allows in that mode.
|
||||
|
||||
@@ -17,7 +17,6 @@ func TestWorkerDefaultJobTypes(t *testing.T) {
|
||||
}
|
||||
want := []string{
|
||||
"admin_script",
|
||||
"dir_usage",
|
||||
"ec_balance",
|
||||
"erasure_coding",
|
||||
"filer_ttl",
|
||||
|
||||
@@ -1,327 +0,0 @@
|
||||
// Package dirusage holds what the dir_usage worker job keeps of a filer
|
||||
// store: the totals of each bucket, and of the directories in it that hold at
|
||||
// least MinSharePercent of it, in one file per bucket under Dir.
|
||||
package dirusage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const (
|
||||
// Dir holds the records, in a directory per store signature, so the
|
||||
// copies filer.sync makes in another cluster are never read there, and
|
||||
// the cursor of each store, which meta_log_purge reads.
|
||||
Dir = filer.DirectoryEtcSeaweedFS + "/dir_usage"
|
||||
// Version is the version of the record format and of the rules that
|
||||
// pick the directories; a record of another version is made again.
|
||||
Version = 1
|
||||
// MinSharePercent is the share of its bucket's bytes a directory holds
|
||||
// at least to get a record of its own. Directories at one depth do not
|
||||
// overlap, so a bucket has at most 100/MinSharePercent records per level.
|
||||
MinSharePercent = 1
|
||||
// MaxDepth is how many levels below its bucket a directory is at most to
|
||||
// get a record of its own.
|
||||
MaxDepth = 10
|
||||
)
|
||||
|
||||
// Usage is what fs.du adds up for a directory, everything below it included:
|
||||
// the logical size, the chunks, the files and the directories.
|
||||
type Usage struct {
|
||||
Bytes int64 `json:"bytes"`
|
||||
Chunks int64 `json:"chunks"`
|
||||
Files int64 `json:"files"`
|
||||
Dirs int64 `json:"dirs"`
|
||||
}
|
||||
|
||||
// EntryUsage is what one entry adds to the directories above it.
|
||||
func EntryUsage(entry *filer_pb.Entry) Usage {
|
||||
if entry == nil {
|
||||
return Usage{}
|
||||
}
|
||||
if entry.IsDirectory {
|
||||
return Usage{Dirs: 1}
|
||||
}
|
||||
return Usage{Bytes: int64(min(filer.FileSize(entry), math.MaxInt64)), Chunks: int64(len(entry.GetChunks())), Files: 1}
|
||||
}
|
||||
|
||||
func (u *Usage) Add(other Usage) {
|
||||
u.Bytes += other.Bytes
|
||||
u.Chunks += other.Chunks
|
||||
u.Files += other.Files
|
||||
u.Dirs += other.Dirs
|
||||
}
|
||||
|
||||
func (u *Usage) Sub(other Usage) {
|
||||
u.Bytes -= other.Bytes
|
||||
u.Chunks -= other.Chunks
|
||||
u.Files -= other.Files
|
||||
u.Dirs -= other.Dirs
|
||||
}
|
||||
|
||||
func (u Usage) IsZero() bool {
|
||||
return u == Usage{}
|
||||
}
|
||||
|
||||
// Record is what the job keeps of one bucket, or of one directory directly
|
||||
// under / outside the buckets folder.
|
||||
type Record struct {
|
||||
Version int `json:"version"`
|
||||
Root string `json:"root"`
|
||||
// TsNs is the log position the totals are at.
|
||||
TsNs int64 `json:"ts_ns"`
|
||||
// SeededNs is when the walk the totals started from ended.
|
||||
SeededNs int64 `json:"seeded_ns"`
|
||||
// Dirs are the totals of Root, at "", and of each directory below it
|
||||
// with a record of its own, by its path relative to Root.
|
||||
Dirs map[string]Usage `json:"dirs"`
|
||||
}
|
||||
|
||||
// Relative is path relative to root, "" for root itself.
|
||||
func Relative(root, path util.FullPath) string {
|
||||
if path == root {
|
||||
return ""
|
||||
}
|
||||
if root == "/" {
|
||||
return strings.TrimPrefix(string(path), "/")
|
||||
}
|
||||
return strings.TrimPrefix(string(path), string(root)+"/")
|
||||
}
|
||||
|
||||
// Roots tells which bucket, or top-level directory outside the buckets folder,
|
||||
// a path counts toward.
|
||||
type Roots struct {
|
||||
Buckets util.FullPath
|
||||
}
|
||||
|
||||
// RootsOf reads the buckets folder of the filer behind client.
|
||||
func RootsOf(ctx context.Context, client filer_pb.SeaweedFilerClient) (Roots, int32, error) {
|
||||
conf, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return Roots{}, 0, fmt.Errorf("filer configuration: %w", err)
|
||||
}
|
||||
return NewRoots(conf.GetDirBuckets()), conf.Signature, nil
|
||||
}
|
||||
|
||||
// NewRoots takes the buckets folder as filer.toml spells it.
|
||||
func NewRoots(buckets string) Roots {
|
||||
if buckets = strings.TrimRight(buckets, "/"); buckets == "" {
|
||||
buckets = "/buckets"
|
||||
}
|
||||
return Roots{Buckets: util.FullPath(buckets)}
|
||||
}
|
||||
|
||||
// List lists the buckets and the top-level directories outside the buckets
|
||||
// folder.
|
||||
func (r Roots) List(ctx context.Context, client filer_pb.FilerClient) (map[util.FullPath]bool, error) {
|
||||
roots := make(map[util.FullPath]bool)
|
||||
for _, dir := range []util.FullPath{"/", r.Buckets} {
|
||||
err := filer_pb.List(ctx, client, string(dir), "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
if path := dir.Child(entry.Name); entry.IsDirectory && r.IsRoot(path) {
|
||||
roots[path] = true
|
||||
}
|
||||
return nil
|
||||
}, "", false, math.MaxInt32)
|
||||
// no buckets folder yet: no buckets
|
||||
if err != nil && !(dir == r.Buckets && errors.Is(err, filer_pb.ErrNotFound)) {
|
||||
return nil, fmt.Errorf("list %s: %w", dir, err)
|
||||
}
|
||||
}
|
||||
return roots, nil
|
||||
}
|
||||
|
||||
// container is the top-level directory the buckets folder is in. Outside the
|
||||
// buckets folder, nothing in it is counted.
|
||||
func (r Roots) container() string {
|
||||
if parts := r.Buckets.Split(); len(parts) > 0 {
|
||||
return parts[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RootOf is the bucket or top-level directory path is in, or path itself if
|
||||
// it is one. ok is false for /, the buckets folder and what holds it, and
|
||||
// what is left out of the counts.
|
||||
func (r Roots) RootOf(path util.FullPath) (root util.FullPath, ok bool) {
|
||||
if Skipped(path) {
|
||||
return "", false
|
||||
}
|
||||
if path.IsUnder(r.Buckets) {
|
||||
name := strings.SplitN(Relative(r.Buckets, path), "/", 2)[0]
|
||||
return r.Buckets.Child(name), true
|
||||
}
|
||||
parts := path.Split()
|
||||
if len(parts) == 0 || parts[0] == r.container() {
|
||||
return "", false
|
||||
}
|
||||
return util.FullPath("/" + parts[0]), true
|
||||
}
|
||||
|
||||
// IsRoot reports whether path is a bucket or a top-level directory.
|
||||
func (r Roots) IsRoot(path util.FullPath) bool {
|
||||
root, ok := r.RootOf(path)
|
||||
return ok && root == path
|
||||
}
|
||||
|
||||
// Skipped reports whether path is in a part of the tree the counts leave
|
||||
// out: the metadata log, which logs no events about itself, and the records.
|
||||
func Skipped(path util.FullPath) bool {
|
||||
for _, dir := range []util.FullPath{filer.SystemLogDir, Dir} {
|
||||
if path == dir || path.IsUnder(dir) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Store reads and writes the records of one filer store.
|
||||
type Store struct {
|
||||
Client filer_pb.FilerClient
|
||||
Signature int32
|
||||
Roots Roots
|
||||
}
|
||||
|
||||
// location is the directory and the name of root's record.
|
||||
func (s *Store) location(root util.FullPath) (dir, name string) {
|
||||
kind := "top"
|
||||
if root.IsUnder(s.Roots.Buckets) {
|
||||
kind = "buckets"
|
||||
}
|
||||
return fmt.Sprintf("%s/%d/%s", Dir, s.Signature, kind), root.Name() + ".json"
|
||||
}
|
||||
|
||||
func (s *Store) cursorName() string {
|
||||
return fmt.Sprintf("cursor-%d.json", s.Signature)
|
||||
}
|
||||
|
||||
// Load reads root's record; it is nil if there is none, or none of this
|
||||
// version.
|
||||
func (s *Store) Load(ctx context.Context, root util.FullPath) (*Record, error) {
|
||||
dir, name := s.location(root)
|
||||
var content []byte
|
||||
err := s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var err error
|
||||
content, err = filer.ReadInsideFiler(ctx, client, dir, name)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s/%s: %w", dir, name, err)
|
||||
}
|
||||
return decode(content, root), nil
|
||||
}
|
||||
|
||||
func decode(content []byte, root util.FullPath) *Record {
|
||||
var record Record
|
||||
if json.Unmarshal(content, &record) != nil || record.Version != Version || record.Root != string(root) || record.Dirs == nil {
|
||||
return nil
|
||||
}
|
||||
return &record
|
||||
}
|
||||
|
||||
// Cursor is the log position the last replay that finished reached. A
|
||||
// record at or before it is at it: a replay writes only the records it
|
||||
// changed.
|
||||
func (s *Store) Cursor(ctx context.Context) (int64, error) {
|
||||
var tsNs int64
|
||||
err := s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
content, err := filer.ReadInsideFiler(ctx, client, Dir, s.cursorName())
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s/%s: %w", Dir, s.cursorName(), err)
|
||||
}
|
||||
var cursor struct {
|
||||
TsNs int64 `json:"ts_ns"`
|
||||
}
|
||||
if json.Unmarshal(content, &cursor) == nil {
|
||||
tsNs = cursor.TsNs
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return tsNs, err
|
||||
}
|
||||
|
||||
// LoadAll reads every record of the store, by root, and the cursor.
|
||||
func (s *Store) LoadAll(ctx context.Context) (records map[util.FullPath]*Record, cursorTsNs int64, err error) {
|
||||
if cursorTsNs, err = s.Cursor(ctx); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
records = make(map[util.FullPath]*Record)
|
||||
err = s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
for _, kind := range []string{"buckets", "top"} {
|
||||
dir := fmt.Sprintf("%s/%d/%s", Dir, s.Signature, kind)
|
||||
err := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
name, found := strings.CutSuffix(entry.Name, ".json")
|
||||
if entry.IsDirectory || !found {
|
||||
return nil
|
||||
}
|
||||
root := s.Roots.Buckets.Child(name)
|
||||
if kind == "top" {
|
||||
root = util.FullPath("/" + name)
|
||||
}
|
||||
if record := decode(entry.Content, root); record != nil {
|
||||
records[root] = record
|
||||
}
|
||||
return nil
|
||||
}, "", false, math.MaxInt32)
|
||||
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("list %s: %w", dir, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return records, cursorTsNs, err
|
||||
}
|
||||
|
||||
// Save writes root's record.
|
||||
func (s *Store) Save(ctx context.Context, record *Record) error {
|
||||
content, err := json.Marshal(record)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dir, name := s.location(util.FullPath(record.Root))
|
||||
return s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
if err := filer.SaveInsideFiler(ctx, client, dir, name, content); err != nil {
|
||||
return fmt.Errorf("save %s/%s: %w", dir, name, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Delete removes root's record.
|
||||
func (s *Store) Delete(ctx context.Context, root util.FullPath) error {
|
||||
dir, name := s.location(root)
|
||||
err := filer_pb.Remove(ctx, s.Client, dir, name, true, false, false, false, nil)
|
||||
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("delete %s/%s: %w", dir, name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveCursor writes the log position a replay of every record reached.
|
||||
func (s *Store) SaveCursor(ctx context.Context, tsNs int64) error {
|
||||
content, err := json.Marshal(struct {
|
||||
TsNs int64 `json:"ts_ns"`
|
||||
}{tsNs})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
if err := filer.SaveInsideFiler(ctx, client, Dir, s.cursorName(), content); err != nil {
|
||||
return fmt.Errorf("save %s/%s: %w", Dir, s.cursorName(), err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package dirusage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestRootsOfAPath(t *testing.T) {
|
||||
for _, buckets := range []string{"/buckets", "/buckets/", ""} {
|
||||
roots := NewRoots(buckets)
|
||||
for path, want := range map[util.FullPath]util.FullPath{
|
||||
"/buckets/b": "/buckets/b",
|
||||
"/buckets/b/x/y": "/buckets/b",
|
||||
"/home/u/f": "/home",
|
||||
"/topics/.system": "/topics",
|
||||
"/topics/.system/log/2026-12-03": "",
|
||||
"/etc/seaweedfs/dir_usage/1/top/x": "",
|
||||
"/buckets": "",
|
||||
"/": "",
|
||||
} {
|
||||
root, ok := roots.RootOf(path)
|
||||
if !ok {
|
||||
root = ""
|
||||
}
|
||||
if root != want {
|
||||
t.Errorf("buckets folder %q: %s counts toward %q, want %q", buckets, path, root, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
nested := NewRoots("/tenant/buckets/")
|
||||
if root, ok := nested.RootOf("/tenant/buckets/b/f"); !ok || root != "/tenant/buckets/b" {
|
||||
t.Errorf("/tenant/buckets/b/f counts toward %q, %v", root, ok)
|
||||
}
|
||||
if _, ok := nested.RootOf("/tenant/other"); ok {
|
||||
t.Errorf("what holds the buckets folder counts")
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package elastic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
@@ -170,9 +169,6 @@ func (store *ElasticStore) FindEntry(ctx context.Context, fullpath weed_util.Ful
|
||||
if elastic.IsNotFound(err) {
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find %s: %w", fullpath, err)
|
||||
}
|
||||
if searchResult != nil && searchResult.Found {
|
||||
esEntry := &ESEntry{
|
||||
ParentId: "",
|
||||
@@ -181,6 +177,7 @@ func (store *ElasticStore) FindEntry(ctx context.Context, fullpath weed_util.Ful
|
||||
err := jsoniter.Unmarshal(searchResult.Source, esEntry)
|
||||
return esEntry.Entry, err
|
||||
}
|
||||
glog.ErrorfCtx(ctx, "find entry(%s),%v.", string(fullpath), err)
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
@@ -193,9 +190,6 @@ func (store *ElasticStore) DeleteEntry(ctx context.Context, fullpath weed_util.F
|
||||
// If we delete an entry at the top level, we should attempt to delete the corresponding Elasticsearch index.
|
||||
if strings.Count(strFullpath, "/") == 1 {
|
||||
entry, err2 := store.FindEntry(ctx, fullpath)
|
||||
if err2 != nil && !errors.Is(err2, filer_pb.ErrNotFound) {
|
||||
return err2
|
||||
}
|
||||
if err2 == nil && entry.IsDirectory() {
|
||||
bucketIndex := indexPrefix + strFullpath[1:]
|
||||
store.deleteIndex(ctx, bucketIndex)
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
//go:build elastic
|
||||
|
||||
package elastic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
elastic "github.com/olivere/elastic/v7"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// storeAnswering returns a store whose cluster answers every request with
|
||||
// status and body.
|
||||
func storeAnswering(t *testing.T, status int, body string) *ElasticStore {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
fmt.Fprint(w, body)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
client, err := elastic.NewClient(elastic.SetURL(server.URL), elastic.SetSniff(false), elastic.SetHealthcheck(false))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &ElasticStore{client: client}
|
||||
}
|
||||
|
||||
func TestFindEntryReportsAFailedReadAsAnError(t *testing.T) {
|
||||
store := storeAnswering(t, http.StatusServiceUnavailable, `{"error":{"type":"cluster_block_exception","reason":"blocked"},"status":503}`)
|
||||
|
||||
_, err := store.FindEntry(context.Background(), util.FullPath("/buckets/b/kept.bin"))
|
||||
if err == nil {
|
||||
t.Fatal("find succeeded although the cluster failed the read")
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
t.Fatalf("a failed read was reported as a missing entry: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindEntryReportsAMissingEntryAsNotFound(t *testing.T) {
|
||||
for name, body := range map[string]string{
|
||||
"missing document": `{"_index":".seaweedfs_buckets","_type":"_doc","_id":"x","found":false}`,
|
||||
"missing index": `{"error":{"type":"index_not_found_exception","reason":"no such index"},"status":404}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
store := storeAnswering(t, http.StatusNotFound, body)
|
||||
|
||||
_, err := store.FindEntry(context.Background(), util.FullPath("/buckets/b/gone.bin"))
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
t.Fatalf("find = %v, want filer_pb.ErrNotFound", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKvGetReportsAValueItCannotDecodeAsAnError(t *testing.T) {
|
||||
store := storeAnswering(t, http.StatusOK, `{"_index":".seaweedfs_kv_entries","_type":"_doc","_id":"k","found":true,"_source":"not an object"}`)
|
||||
|
||||
_, err := store.KvGet(context.Background(), []byte("k"))
|
||||
if err == nil {
|
||||
t.Fatal("KvGet succeeded on a value it cannot decode")
|
||||
}
|
||||
if errors.Is(err, filer.ErrKvNotFound) {
|
||||
t.Fatalf("a value that cannot be decoded was reported as missing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteEntryKeepsATopLevelDirectoryItCannotRead(t *testing.T) {
|
||||
deleted := false
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.Method == http.MethodDelete {
|
||||
deleted = true
|
||||
fmt.Fprint(w, `{"result":"deleted"}`)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprint(w, `{"error":{"type":"cluster_block_exception","reason":"blocked"},"status":503}`)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
client, err := elastic.NewClient(elastic.SetURL(server.URL), elastic.SetSniff(false), elastic.SetHealthcheck(false))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &ElasticStore{client: client}
|
||||
|
||||
if err := store.DeleteEntry(context.Background(), util.FullPath("/topdir")); err == nil {
|
||||
t.Fatal("delete succeeded although the directory could not be read")
|
||||
}
|
||||
if deleted {
|
||||
t.Fatal("the entry was deleted without its index")
|
||||
}
|
||||
}
|
||||
@@ -43,10 +43,9 @@ func (store *ElasticStore) KvGet(ctx context.Context, key []byte) (value []byte,
|
||||
}
|
||||
if searchResult != nil && searchResult.Found {
|
||||
esEntry := &ESKVEntry{}
|
||||
if err := jsoniter.Unmarshal(searchResult.Source, esEntry); err != nil {
|
||||
return value, fmt.Errorf("decode key %q: %w", key, err)
|
||||
if err := jsoniter.Unmarshal(searchResult.Source, esEntry); err == nil {
|
||||
return esEntry.Value, nil
|
||||
}
|
||||
return esEntry.Value, nil
|
||||
}
|
||||
return value, filer.ErrKvNotFound
|
||||
}
|
||||
|
||||
@@ -238,12 +238,11 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
}
|
||||
}
|
||||
if err != nil && !ignoreRecursiveError {
|
||||
return err
|
||||
break
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, deleteEventEntry(ctx, sub), nil, shouldDeleteChunks, isFromOtherCluster, nil)
|
||||
subRule := f.FilerConf.MatchStorageRule(string(sub.FullPath))
|
||||
subChunksToDelete := &chunksToDelete
|
||||
if shouldDeleteChunks && subRule.GetFsync() {
|
||||
if shouldDeleteChunks && f.FilerConf.MatchStorageRule(string(sub.FullPath)).GetFsync() {
|
||||
subChunksToDelete = &fsyncChunksToDelete
|
||||
}
|
||||
if len(sub.HardLinkId) != 0 {
|
||||
@@ -251,7 +250,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
// DeleteFolderChildren below takes the other children
|
||||
err = f.deleteLinkedName(ctx, sub, shouldDeleteChunks)
|
||||
} else {
|
||||
if shouldDeleteChunks && !subRule.DisableChunkDeletion {
|
||||
if shouldDeleteChunks {
|
||||
*subChunksToDelete = append(*subChunksToDelete, sub.GetChunks()...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,35 +394,3 @@ func TestDurableDeleteRetriesAServerError(t *testing.T) {
|
||||
t.Fatalf("the failed durable delete lost its pending record or fsync mark")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecursiveDeleteKeepsChunksAChildRuleRetains(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
if err := f.FilerConf.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/d/keep", DisableChunkDeletion: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := f.CreateEntry(ctx, &Entry{FullPath: "/d", Attr: Attr{Mode: os.ModeDir | 0755}}, nil, false, false, nil, true, 255); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files := map[string]string{
|
||||
"/d/keep.txt": "5,01637037d6",
|
||||
"/d/other.txt": "5,02637037d6",
|
||||
}
|
||||
for path, fid := range files {
|
||||
entry := &Entry{FullPath: util.FullPath(path), Attr: Attr{Mode: 0644, Mtime: time.Now()}, Chunks: []*filer_pb.FileChunk{{FileId: fid}}}
|
||||
if err := f.CreateEntry(ctx, entry, nil, false, false, nil, true, 255); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := f.DeleteEntryMetaAndData(ctx, "/d", true, false, true, false, nil, time.Time{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for path, fid := range files {
|
||||
if got, want := f.deletionEpoch(fid) != 0, path == "/d/other.txt"; got != want {
|
||||
t.Errorf("%s: chunk queued %v, want %v", path, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1625,40 +1625,3 @@ func TestMaybeLazyListFromRemote_ContextGuardPreventsRecursion(t *testing.T) {
|
||||
f.maybeLazyListFromRemote(fetchCtx, util.FullPath("/buckets/mybucket"))
|
||||
assert.Equal(t, 0, stub.listDirCalls)
|
||||
}
|
||||
|
||||
func TestDeleteEntryMetaAndData_RecursiveRemoteChildDeleteErrorKeepsFolder(t *testing.T) {
|
||||
const storageType = "stub_lazy_delete_folder_child_error"
|
||||
stub := &stubRemoteClient{deleteErr: errors.New("remote delete failed")}
|
||||
defer registerStubMaker(t, storageType, stub)()
|
||||
|
||||
conf := &remote_pb.RemoteConf{Name: "childerr", Type: storageType}
|
||||
rs := NewFilerRemoteStorage()
|
||||
rs.storageNameToConf[conf.Name] = conf
|
||||
rs.mapDirectoryToRemoteStorage("/buckets/mybucket", &remote_pb.RemoteStorageLocation{
|
||||
Name: "childerr",
|
||||
Bucket: "mybucket",
|
||||
Path: "/",
|
||||
})
|
||||
|
||||
store := newStubFilerStore()
|
||||
dirPath := util.FullPath("/buckets/mybucket/subdir")
|
||||
store.entries[string(dirPath)] = &Entry{
|
||||
FullPath: dirPath,
|
||||
Attr: Attr{Mtime: time.Unix(1700000000, 0), Crtime: time.Unix(1700000000, 0), Mode: os.ModeDir | 0755},
|
||||
}
|
||||
childPath := util.FullPath("/buckets/mybucket/subdir/child.txt")
|
||||
store.entries[string(childPath)] = &Entry{
|
||||
FullPath: childPath,
|
||||
Attr: Attr{Mtime: time.Unix(1700000000, 0), Crtime: time.Unix(1700000000, 0), Mode: 0644, FileSize: 50},
|
||||
Remote: &filer_pb.RemoteEntry{RemoteMtime: 1700000000, RemoteSize: 50},
|
||||
}
|
||||
f := newTestFiler(t, store, rs)
|
||||
|
||||
err := f.DeleteEntryMetaAndData(context.Background(), dirPath, true, false, false, false, nil, time.Time{})
|
||||
require.Error(t, err)
|
||||
for _, p := range []util.FullPath{dirPath, childPath} {
|
||||
_, findErr := store.FindEntry(context.Background(), p)
|
||||
require.NoError(t, findErr, "%s was deleted after its remote delete failed", p)
|
||||
}
|
||||
require.Empty(t, stub.removeCalls)
|
||||
}
|
||||
@@ -487,19 +487,13 @@ func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath u
|
||||
return actualStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, eachEntryFunc)
|
||||
}
|
||||
|
||||
orderedByName := fsw.listsInNameOrder(dirPath)
|
||||
// An unordered store may have to be read to its end, so read it in full pages.
|
||||
scanLimit := limit
|
||||
if !orderedByName {
|
||||
scanLimit = max(limit, PaginationSize)
|
||||
}
|
||||
// lastFileName must stay at the last name delivered to eachEntryFunc; the
|
||||
// raw scan cursor runs ahead over non-matching names and cannot be returned.
|
||||
count := int64(0)
|
||||
scanName, scanInclusive := startFileName, includeStartFile
|
||||
for count < limit {
|
||||
var page []*Entry
|
||||
if scanName, err = actualStore.ListDirectoryEntries(ctx, dirPath, scanName, scanInclusive, scanLimit, func(entry *Entry) (bool, error) {
|
||||
if scanName, err = actualStore.ListDirectoryEntries(ctx, dirPath, scanName, scanInclusive, limit, func(entry *Entry) (bool, error) {
|
||||
page = append(page, entry)
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
@@ -524,8 +518,7 @@ func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath u
|
||||
return
|
||||
}
|
||||
}
|
||||
// A store that pages by path hash can still have matches on later pages.
|
||||
if orderedByName && scanName >= prefix && !strings.HasPrefix(scanName, prefix) {
|
||||
if scanName >= prefix && !strings.HasPrefix(scanName, prefix) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,64 +243,3 @@ func TestPrefixFilterEntriesCursorStaysAtLastDelivered(t *testing.T) {
|
||||
assert.Equal(t, []string{"b3", "b4"}, delivered)
|
||||
assert.Equal(t, "b4", lastFileName)
|
||||
}
|
||||
|
||||
type unorderedPrefixListStore struct {
|
||||
noPrefixListStore
|
||||
nextName map[string]string // next entry in store order for each cursor
|
||||
scans int
|
||||
}
|
||||
|
||||
func (*unorderedPrefixListStore) ListsUnordered() bool { return true }
|
||||
|
||||
func (s *unorderedPrefixListStore) ListDirectoryEntries(_ context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, each ListEachEntryFunc) (string, error) {
|
||||
s.scans++
|
||||
name := s.nextName[startFileName]
|
||||
if includeStartFile && startFileName != "" {
|
||||
name = startFileName
|
||||
}
|
||||
var last string
|
||||
for name != "" && limit > 0 {
|
||||
more, err := each(&Entry{FullPath: dirPath.Child(name)})
|
||||
if err != nil {
|
||||
return last, err
|
||||
}
|
||||
last = name
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
name = s.nextName[name]
|
||||
limit--
|
||||
}
|
||||
return last, nil
|
||||
}
|
||||
|
||||
func TestPrefixFilterEntriesOnUnorderedStore(t *testing.T) {
|
||||
// Elasticsearch lists these names in descending order of their /d path hashes.
|
||||
store := &unorderedPrefixListStore{
|
||||
noPrefixListStore: noPrefixListStore{newStubFilerStore()},
|
||||
nextName: map[string]string{
|
||||
"": "omega",
|
||||
"omega": "apricot",
|
||||
"apricot": "zeta",
|
||||
"zeta": "alpha",
|
||||
"alpha": "cedar",
|
||||
},
|
||||
}
|
||||
wrapper := NewFilerStoreWrapper(newStubFilerStore())
|
||||
wrapper.AddPathSpecificStore("/es/", "elastic", store)
|
||||
|
||||
var cursor string
|
||||
var delivered []string
|
||||
for _, want := range []string{"apricot", "alpha", ""} {
|
||||
last, err := wrapper.ListDirectoryPrefixedEntries(context.Background(), "/es/d", cursor, false, 1, "a", func(entry *Entry) (bool, error) {
|
||||
delivered = append(delivered, entry.Name())
|
||||
return true, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, last, "listing after %q", cursor)
|
||||
cursor = last
|
||||
}
|
||||
require.Equal(t, []string{"apricot", "alpha"}, delivered)
|
||||
// One raw page per call, plus the empty page that ends the listing.
|
||||
require.Equal(t, 4, store.scans)
|
||||
}
|
||||
@@ -110,7 +110,7 @@ func (store *HbaseStore) DeleteEntry(ctx context.Context, path util.FullPath) (e
|
||||
return store.doDelete(ctx, store.cfMetaDir, []byte(path))
|
||||
}
|
||||
|
||||
func (store *HbaseStore) DeleteFolderChildren(ctx context.Context, path util.FullPath) error {
|
||||
func (store *HbaseStore) DeleteFolderChildren(ctx context.Context, path util.FullPath) (err error) {
|
||||
|
||||
family := map[string][]string{store.cfMetaDir: {COLUMN_NAME}}
|
||||
expectedPrefix := []byte(path.Child(""))
|
||||
@@ -123,11 +123,8 @@ func (store *HbaseStore) DeleteFolderChildren(ctx context.Context, path util.Ful
|
||||
defer scanner.Close()
|
||||
for {
|
||||
res, err := scanner.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
break
|
||||
}
|
||||
if len(res.Cells) == 0 {
|
||||
continue
|
||||
@@ -143,11 +140,13 @@ func (store *HbaseStore) DeleteFolderChildren(ctx context.Context, path util.Ful
|
||||
continue
|
||||
}
|
||||
|
||||
if err := store.doDelete(ctx, store.cfMetaDir, cell.Row); err != nil {
|
||||
return err
|
||||
err = store.doDelete(ctx, store.cfMetaDir, cell.Row)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
func (store *HbaseStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (string, error) {
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
package hbase
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tsuna/gohbase"
|
||||
"github.com/tsuna/gohbase/hrpc"
|
||||
)
|
||||
|
||||
type deleteFolderScanner struct {
|
||||
rows []string
|
||||
endErr error
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (s *deleteFolderScanner) Next() (*hrpc.Result, error) {
|
||||
if len(s.rows) == 0 {
|
||||
return nil, s.endErr
|
||||
}
|
||||
row := s.rows[0]
|
||||
s.rows = s.rows[1:]
|
||||
return &hrpc.Result{Cells: []*hrpc.Cell{{Row: []byte(row)}}}, nil
|
||||
}
|
||||
|
||||
func (s *deleteFolderScanner) Close() error {
|
||||
s.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type deleteFolderClient struct {
|
||||
gohbase.Client
|
||||
scanner *deleteFolderScanner
|
||||
failAt string
|
||||
deleteErr error
|
||||
attempted []string
|
||||
}
|
||||
|
||||
func (c *deleteFolderClient) Scan(*hrpc.Scan) hrpc.Scanner { return c.scanner }
|
||||
|
||||
func (c *deleteFolderClient) Delete(m *hrpc.Mutate) (*hrpc.Result, error) {
|
||||
c.attempted = append(c.attempted, string(m.Key()))
|
||||
if string(m.Key()) == c.failAt {
|
||||
return nil, c.deleteErr
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestDeleteFolderChildren(t *testing.T) {
|
||||
scanErr := errors.New("scan failed")
|
||||
deleteErr := errors.New("delete failed")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rows []string
|
||||
endErr error
|
||||
failAt string
|
||||
deleteErr error
|
||||
wantErr error
|
||||
attempts int
|
||||
}{
|
||||
{name: "EOF", rows: []string{"/dir/a"}, endErr: io.EOF, attempts: 1},
|
||||
{name: "prefix boundary", rows: []string{"/dir/a", "/other/b"}, endErr: scanErr, attempts: 1},
|
||||
{name: "scan error after a row", rows: []string{"/dir/a"}, endErr: scanErr, wantErr: scanErr, attempts: 1},
|
||||
{name: "row delete error", rows: []string{"/dir/a", "/dir/b"}, endErr: io.EOF, failAt: "/dir/a", deleteErr: deleteErr, wantErr: deleteErr, attempts: 1},
|
||||
{name: "row delete error after a row", rows: []string{"/dir/a", "/dir/b", "/dir/c"}, endErr: io.EOF, failAt: "/dir/b", deleteErr: deleteErr, wantErr: deleteErr, attempts: 2},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
scanner := &deleteFolderScanner{rows: tc.rows, endErr: tc.endErr}
|
||||
client := &deleteFolderClient{scanner: scanner, failAt: tc.failAt, deleteErr: tc.deleteErr}
|
||||
store := &HbaseStore{Client: client, table: []byte("filemeta"), cfMetaDir: "meta"}
|
||||
|
||||
err := store.DeleteFolderChildren(t.Context(), "/dir")
|
||||
require.ErrorIs(t, err, tc.wantErr)
|
||||
require.Equal(t, tc.rows[:tc.attempts], client.attempted)
|
||||
require.True(t, scanner.closed)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
package treewalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Follow reads the metadata events under prefix logged after sinceNs and up
|
||||
// to untilNs, in log order, and passes each to each. Responses that carry no
|
||||
// event are left out. It returns the position of the last event read, or
|
||||
// sinceNs if there was none.
|
||||
func Follow(ctx context.Context, client filer_pb.FilerClient, clientName, prefix string, sinceNs, untilNs int64, each func(event *filer_pb.SubscribeMetadataResponse) error) (int64, error) {
|
||||
if untilNs == 0 {
|
||||
return sinceNs, fmt.Errorf("follow %s: no end", prefix)
|
||||
}
|
||||
last := sinceNs
|
||||
err := subscribe(ctx, client, clientName, prefix, sinceNs, untilNs, func(event *filer_pb.SubscribeMetadataResponse) error {
|
||||
if event.EventNotification == nil || event.TsNs <= last {
|
||||
return nil
|
||||
}
|
||||
if err := each(event); err != nil {
|
||||
return err
|
||||
}
|
||||
last = event.TsNs
|
||||
return nil
|
||||
})
|
||||
return last, err
|
||||
}
|
||||
|
||||
// subscribe streams the responses of one metadata subscription to each, up to
|
||||
// untilNs, or until ctx ends when untilNs is 0. With no end it asks for idle
|
||||
// heartbeats, so a caller learns how far the log is read while nothing happens.
|
||||
func subscribe(ctx context.Context, client filer_pb.FilerClient, clientName, prefix string, sinceNs, untilNs int64, each func(event *filer_pb.SubscribeMetadataResponse) error) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
return client.WithFilerClient(true, func(c filer_pb.SeaweedFilerClient) error {
|
||||
stream, err := c.SubscribeMetadata(ctx, &filer_pb.SubscribeMetadataRequest{
|
||||
ClientName: clientName,
|
||||
PathPrefix: prefix,
|
||||
SinceNs: sinceNs,
|
||||
UntilNs: untilNs,
|
||||
ClientId: util.RandomInt32(),
|
||||
ClientSupportsBatching: true,
|
||||
ClientSupportsIdleHeartbeat: untilNs == 0,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("subscribe %s: %w", prefix, err)
|
||||
}
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, event := range append([]*filer_pb.SubscribeMetadataResponse{resp}, resp.Events...) {
|
||||
if untilNs != 0 && event.TsNs > untilNs {
|
||||
return nil
|
||||
}
|
||||
if err := each(event); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// LogStartTsNs is when the oldest metadata log the filer keeps starts; the
|
||||
// events before it are gone. It is 0 when no log is kept. A day with no log
|
||||
// left in it, as a purge that stopped midway leaves, is passed over.
|
||||
func LogStartTsNs(ctx context.Context, client filer_pb.SeaweedFilerClient) (int64, error) {
|
||||
days, err := names(ctx, client, filer.SystemLogDir, func(name string) bool {
|
||||
_, err := time.Parse("2006-01-02", name)
|
||||
return err == nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
sort.Strings(days)
|
||||
for _, day := range days {
|
||||
minutes, err := names(ctx, client, filer.SystemLogDir+"/"+day, func(name string) bool {
|
||||
if len(name) < 5 {
|
||||
return false
|
||||
}
|
||||
_, err := time.Parse("15-04", name[:5])
|
||||
return err == nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(minutes) == 0 {
|
||||
continue
|
||||
}
|
||||
sort.Strings(minutes)
|
||||
t, err := time.Parse("2006-01-02-15-04", day+"-"+minutes[0][:5])
|
||||
return t.UnixNano(), err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// SnapshotTsNs is the log position the filer says it has logged every event
|
||||
// up to, from a listing of dir that reads one entry; 0 when the filer does
|
||||
// not say.
|
||||
func SnapshotTsNs(ctx context.Context, client filer_pb.FilerClient, dir util.FullPath) (int64, error) {
|
||||
var snapshot int64
|
||||
err := client.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
|
||||
var err error
|
||||
snapshot, err = filer_pb.DoSeaweedListWithSnapshot(ctx, c, dir, "", func(*filer_pb.Entry, bool) error { return nil }, "", false, 1, 0)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("list %s: %w", dir, err)
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
// waitForSnapshot returns once the filer says it has logged every event up
|
||||
// to tsNs. A filer that does not say is taken to have.
|
||||
func waitForSnapshot(ctx context.Context, client filer_pb.FilerClient, dir util.FullPath, tsNs int64) error {
|
||||
for {
|
||||
snapshot, err := SnapshotTsNs(ctx, client, dir)
|
||||
if err != nil || snapshot == 0 || snapshot >= tsNs {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
case <-ctx.Done():
|
||||
return context.Cause(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// names are the names in dir that valid accepts.
|
||||
func names(ctx context.Context, client filer_pb.SeaweedFilerClient, dir string, valid func(string) bool) ([]string, error) {
|
||||
var found []string
|
||||
err := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
if valid(entry.Name) {
|
||||
found = append(found, entry.Name)
|
||||
}
|
||||
return nil
|
||||
}, "", false, math.MaxInt32)
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list %s: %w", dir, err)
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
@@ -1,584 +0,0 @@
|
||||
package treewalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// seedMargin is the Margin of a Seed that sets none.
|
||||
const seedMargin = time.Minute
|
||||
|
||||
// maxFollowFailures is how often in a row the subscription of a seed can
|
||||
// break before the seed fails.
|
||||
const maxFollowFailures = 5
|
||||
|
||||
// seedMaxHeld bounds the names the pages of a seed keep. A walk that gets this
|
||||
// far ahead of the events waits for them.
|
||||
const seedMaxHeld = 1 << 20
|
||||
|
||||
// Seed adds up a directory tree from a walk of it and from the metadata events
|
||||
// logged while the walk runs, so that the two together give the tree as of
|
||||
// one log position, the one Run returns. Change is called for every listed
|
||||
// entry and for every event that changes what the walk counted:
|
||||
//
|
||||
// - An event at or before the snapshot of the page that lists its name
|
||||
// shows in that page and is left out, and so is an event in a directory
|
||||
// the walk has not listed yet: the listing will show it.
|
||||
// - An event after the page's snapshot replaces what the page counted for
|
||||
// the name, since the page may or may not show it.
|
||||
// - An event after the page stopped keeping its names, a margin after its
|
||||
// listing ended, changes the entry from the event's old entry to its new
|
||||
// one.
|
||||
//
|
||||
// A directory that is not in its parent's listing is counted from its events
|
||||
// if it was created after that page's snapshot, and left out otherwise. This
|
||||
// is how the mount's metadata cache builds a directory from a listing and the
|
||||
// events around it, with the per-name replace standing in for the cache's
|
||||
// overwrite, which a running total cannot do.
|
||||
//
|
||||
// A directory removed with one event for itself alone, as when a store drops
|
||||
// a whole bucket, leaves what was listed below it counted: Change is told of
|
||||
// the directory going, and the caller drops what it counted below it.
|
||||
type Seed[V any] struct {
|
||||
Client filer_pb.FilerClient
|
||||
ClientName string
|
||||
Concurrency int
|
||||
PageSize uint32
|
||||
|
||||
// Value is what Change is told of an entry, and what a page keeps of
|
||||
// each name it lists.
|
||||
Value func(entry *filer_pb.Entry) V
|
||||
// Change reports that name in dir went from from to to; nil is no entry.
|
||||
// Change, Started and Done are called one at a time.
|
||||
Change func(dir util.FullPath, name string, from, to *V)
|
||||
// Started and Done, if set, are told when the listing of a directory
|
||||
// starts, and when the directory and everything below it are listed.
|
||||
Started func(dir util.FullPath, depth int)
|
||||
Done func(dir util.FullPath, depth int)
|
||||
// Skip, if set, reports whether dir is in a part of the tree to leave
|
||||
// out. It is asked about each directory the walk would go into and each
|
||||
// directory an event names.
|
||||
Skip func(dir util.FullPath) bool
|
||||
|
||||
// Margin is how long after a change its event is logged at most; 0 is a
|
||||
// minute. A rename logs the events of everything it moved once it is
|
||||
// done, so a page can show a change whose event comes later, and a page
|
||||
// keeps its names this long after its listing ended to recognize such
|
||||
// events.
|
||||
Margin time.Duration
|
||||
|
||||
maxHeld int // seedMaxHeld unless a test sets it
|
||||
}
|
||||
|
||||
// seedPage is a listed page and, until it expires, what it counted per name.
|
||||
type seedPage[V any] struct {
|
||||
dir *seedDir[V]
|
||||
after string
|
||||
last string
|
||||
final bool
|
||||
snapshot int64
|
||||
endNs int64
|
||||
values map[string]*V // nil once the page expired
|
||||
}
|
||||
|
||||
func (p *seedPage[V]) covers(name string) bool {
|
||||
return name > p.after && (p.final || name <= p.last)
|
||||
}
|
||||
|
||||
// seedDir is a directory the walk went into, kept while events about it can
|
||||
// still need its pages: until it and everything below it are listed and its
|
||||
// pages expired.
|
||||
type seedDir[V any] struct {
|
||||
path util.FullPath
|
||||
parent *seedDir[V]
|
||||
pages []*seedPage[V] // in name order
|
||||
children map[string]*seedDir[V]
|
||||
// gone are subdirectories missing from the listing that went away after
|
||||
// it; what was below them was never counted, so their events are left out
|
||||
gone map[string]bool
|
||||
// held counts what keeps the directory: one until it is done, each page
|
||||
// not expired and each child kept
|
||||
held int
|
||||
}
|
||||
|
||||
func (d *seedDir[V]) pageFor(name string) *seedPage[V] {
|
||||
i := sort.Search(len(d.pages), func(i int) bool { return d.pages[i].after >= name })
|
||||
if i == 0 {
|
||||
return nil
|
||||
}
|
||||
if p := d.pages[i-1]; p.covers(name) {
|
||||
return p
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type seedRun[V any] struct {
|
||||
seed *Seed[V]
|
||||
root *seedDir[V]
|
||||
margin int64
|
||||
cancel context.CancelCauseFunc
|
||||
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
dirs map[util.FullPath]*seedDir[V]
|
||||
// pages in the order they were listed, which expire in about that order
|
||||
expiring []*seedPage[V]
|
||||
held int
|
||||
maxHeld int
|
||||
// the directories with a page request out, and when it was sent
|
||||
inFlight map[util.FullPath]time.Time
|
||||
// position is how far the events are applied; lastEvent the newest one
|
||||
position int64
|
||||
lastEvent int64
|
||||
// untilNs, once the walk is done, is where the seed ends
|
||||
untilNs int64
|
||||
// ahead is how far the filer's clock is known to run ahead of this one:
|
||||
// the filer cannot stamp a position later than its own now
|
||||
ahead int64
|
||||
failure error
|
||||
}
|
||||
|
||||
// Run walks root and follows the events under it, and returns the log position
|
||||
// the result is at: Change was told of every change under root up to it, and
|
||||
// of none after it.
|
||||
func (s *Seed[V]) Run(ctx context.Context, root util.FullPath) (int64, error) {
|
||||
r := &seedRun[V]{
|
||||
seed: s,
|
||||
margin: int64(s.Margin),
|
||||
dirs: make(map[util.FullPath]*seedDir[V]),
|
||||
inFlight: make(map[util.FullPath]time.Time),
|
||||
maxHeld: s.maxHeld,
|
||||
}
|
||||
if r.margin == 0 {
|
||||
r.margin = int64(seedMargin)
|
||||
}
|
||||
if r.maxHeld == 0 {
|
||||
r.maxHeld = seedMaxHeld
|
||||
}
|
||||
r.cond = sync.NewCond(&r.mu)
|
||||
r.root = r.newDir(nil, root)
|
||||
|
||||
ctx, r.cancel = context.WithCancelCause(ctx)
|
||||
defer r.cancel(nil)
|
||||
stopWaking := context.AfterFunc(ctx, func() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.fail(context.Cause(ctx))
|
||||
r.cond.Broadcast()
|
||||
})
|
||||
defer stopWaking()
|
||||
|
||||
// Every page is complete through a position at least as late as this
|
||||
// one, so the events after it are all the walk needs.
|
||||
sinceNs, err := SnapshotTsNs(ctx, s.Client, root)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if sinceNs == 0 {
|
||||
// a filer that does not say: start a margin before the walk
|
||||
sinceNs = time.Now().UnixNano() - r.margin
|
||||
}
|
||||
followCtx, stopFollowing := context.WithCancel(ctx)
|
||||
defer stopFollowing()
|
||||
followed := make(chan struct{})
|
||||
go func() {
|
||||
defer close(followed)
|
||||
r.follow(followCtx, sinceNs)
|
||||
}()
|
||||
|
||||
walker := &Walker{Client: s.Client, Concurrency: s.Concurrency, PageSize: s.PageSize}
|
||||
err = walker.Walk(ctx, root, "", r)
|
||||
// a failure below root cancels the walk, and root's listing then fails
|
||||
// with the cancellation instead
|
||||
if failure := r.err(); failure != nil {
|
||||
err = failure
|
||||
}
|
||||
if err != nil {
|
||||
stopFollowing()
|
||||
<-followed
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// The last page ended before now, so every page has expired by untilNs.
|
||||
r.mu.Lock()
|
||||
ahead := r.ahead
|
||||
untilNs := time.Now().UnixNano() + ahead + r.margin
|
||||
r.untilNs = untilNs
|
||||
r.mu.Unlock()
|
||||
select {
|
||||
case <-time.After(time.Until(time.Unix(0, untilNs-ahead))):
|
||||
case <-ctx.Done():
|
||||
stopFollowing()
|
||||
<-followed
|
||||
return 0, context.Cause(ctx)
|
||||
}
|
||||
// A subscription that ends at untilNs stops once it has read all the
|
||||
// filer logged, so the filer must have logged everything up to untilNs
|
||||
// first, on its own clock.
|
||||
if err := waitForSnapshot(ctx, s.Client, root, untilNs); err != nil {
|
||||
stopFollowing()
|
||||
<-followed
|
||||
return 0, err
|
||||
}
|
||||
// The open subscription may not have delivered everything up to untilNs
|
||||
// yet. One that ends there reads what is left.
|
||||
stopFollowing()
|
||||
<-followed
|
||||
if err := r.err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
r.mu.Lock()
|
||||
resumeNs := max(r.lastEvent, sinceNs)
|
||||
r.mu.Unlock()
|
||||
if err := subscribe(ctx, s.Client, s.ClientName, string(root), resumeNs, untilNs, r.receive); err != nil {
|
||||
return 0, fmt.Errorf("follow %s: %w", root, err)
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.failure != nil {
|
||||
return 0, r.failure
|
||||
}
|
||||
r.advance(untilNs)
|
||||
if r.held != 0 || len(r.root.children) != 0 {
|
||||
return 0, fmt.Errorf("seed %s: %d names and %d directories still kept at the end", root, r.held, len(r.root.children))
|
||||
}
|
||||
return untilNs, nil
|
||||
}
|
||||
|
||||
// follow keeps a subscription open from sinceNs until ctx ends, and opens it
|
||||
// again from the last event when it breaks. When it cannot, the seed fails.
|
||||
func (r *seedRun[V]) follow(ctx context.Context, sinceNs int64) {
|
||||
failures := 0
|
||||
for {
|
||||
r.mu.Lock()
|
||||
from := max(r.lastEvent, sinceNs)
|
||||
r.mu.Unlock()
|
||||
err := subscribe(ctx, r.seed.Client, r.seed.ClientName, string(r.root.path), from, 0, r.receive)
|
||||
if ctx.Err() != nil || r.err() != nil {
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
if r.lastEvent > from {
|
||||
failures = 0
|
||||
}
|
||||
failures++
|
||||
if failures > maxFollowFailures {
|
||||
r.fail(fmt.Errorf("follow %s: %w", r.root.path, err))
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
r.mu.Unlock()
|
||||
glog.V(0).Infof("%s: follow %s again after: %v", r.seed.ClientName, r.root.path, err)
|
||||
select {
|
||||
case <-time.After(time.Duration(failures) * time.Second):
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) newDir(parent *seedDir[V], path util.FullPath) *seedDir[V] {
|
||||
d := &seedDir[V]{path: path, parent: parent, held: 1}
|
||||
r.dirs[path] = d
|
||||
if parent != nil {
|
||||
if parent.children == nil {
|
||||
parent.children = make(map[string]*seedDir[V])
|
||||
}
|
||||
parent.children[path.Name()] = d
|
||||
parent.held++
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// release drops one hold on d, and forgets d once nothing holds it.
|
||||
func (r *seedRun[V]) release(d *seedDir[V]) {
|
||||
for d != nil {
|
||||
d.held--
|
||||
if d.held > 0 || d.parent == nil {
|
||||
return
|
||||
}
|
||||
delete(d.parent.children, d.path.Name())
|
||||
delete(r.dirs, d.path)
|
||||
d = d.parent
|
||||
}
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) err() error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.failure
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) fail(err error) {
|
||||
if r.failure == nil {
|
||||
r.failure = err
|
||||
r.cancel(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) value(entry *filer_pb.Entry) *V {
|
||||
if entry == nil {
|
||||
return nil
|
||||
}
|
||||
v := r.seed.Value(entry)
|
||||
return &v
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) Started(dir util.FullPath, depth int) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.seed.Started != nil {
|
||||
r.seed.Started(dir, depth)
|
||||
}
|
||||
}
|
||||
|
||||
// Listing holds the walk back while the pages keep too many names, and
|
||||
// records the request, so that no event is applied before the page it may
|
||||
// show in is known.
|
||||
func (r *seedRun[V]) Listing(ctx context.Context, dir util.FullPath) error {
|
||||
stopWaking := context.AfterFunc(ctx, func() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.cond.Broadcast()
|
||||
})
|
||||
defer stopWaking()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for r.held >= r.maxHeld && r.failure == nil && ctx.Err() == nil {
|
||||
r.cond.Wait()
|
||||
}
|
||||
if r.failure != nil {
|
||||
return r.failure
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.inFlight[dir] = time.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) Listed(page *Page) []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
delete(r.inFlight, page.Dir)
|
||||
defer r.cond.Broadcast()
|
||||
d := r.dirs[page.Dir]
|
||||
if d == nil || r.failure != nil {
|
||||
return nil
|
||||
}
|
||||
p := &seedPage[V]{
|
||||
dir: d,
|
||||
after: page.After,
|
||||
final: page.Last,
|
||||
snapshot: page.Snapshot,
|
||||
endNs: page.End.UnixNano(),
|
||||
values: make(map[string]*V, len(page.Entries)),
|
||||
}
|
||||
r.noteFilerClock(page.Snapshot, page.End)
|
||||
var subDirs []string
|
||||
for _, entry := range page.Entries {
|
||||
p.last = entry.Name
|
||||
v := r.value(entry)
|
||||
p.values[entry.Name] = v
|
||||
r.seed.Change(page.Dir, entry.Name, nil, v)
|
||||
if entry.IsDirectory {
|
||||
child := page.Dir.Child(entry.Name)
|
||||
if r.seed.Skip == nil || !r.seed.Skip(child) {
|
||||
r.newDir(d, child)
|
||||
subDirs = append(subDirs, entry.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
d.pages = append(d.pages, p)
|
||||
d.held++
|
||||
r.held += len(p.values)
|
||||
r.expiring = append(r.expiring, p)
|
||||
return subDirs
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) Done(dir util.FullPath, depth int, err error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
delete(r.inFlight, dir)
|
||||
defer r.cond.Broadcast()
|
||||
// a directory removed since its parent was listed has nothing to count
|
||||
if err != nil && (depth == 0 || !errors.Is(err, filer_pb.ErrNotFound)) {
|
||||
r.fail(fmt.Errorf("list %s: %w", dir, err))
|
||||
}
|
||||
if r.failure != nil {
|
||||
return
|
||||
}
|
||||
if r.seed.Done != nil {
|
||||
r.seed.Done(dir, depth)
|
||||
}
|
||||
if d := r.dirs[dir]; d != nil {
|
||||
r.release(d)
|
||||
}
|
||||
}
|
||||
|
||||
// receive applies one response of the subscription. An event waits for the
|
||||
// pages that were being listed when it arrived, since it may show in them.
|
||||
func (r *seedRun[V]) receive(event *filer_pb.SubscribeMetadataResponse) error {
|
||||
arrived := time.Now()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for r.failure == nil && r.listingSince(arrived) {
|
||||
r.cond.Wait()
|
||||
}
|
||||
if r.failure != nil {
|
||||
return r.failure
|
||||
}
|
||||
r.noteFilerClock(event.TsNs, arrived)
|
||||
if r.untilNs != 0 && event.TsNs > r.untilNs {
|
||||
return nil
|
||||
}
|
||||
if event.EventNotification == nil {
|
||||
// a heartbeat: no event older than a margin before it is still coming
|
||||
if event.TsNs > 0 {
|
||||
r.advance(event.TsNs - r.margin)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if event.TsNs <= r.lastEvent {
|
||||
return nil
|
||||
}
|
||||
r.lastEvent = event.TsNs
|
||||
r.advance(event.TsNs)
|
||||
r.apply(event)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) listingSince(t time.Time) bool {
|
||||
for _, sent := range r.inFlight {
|
||||
if !sent.After(t) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// noteFilerClock learns from a position the filer had reached by local time
|
||||
// at how far its clock runs ahead. It stops learning once the seed's end is
|
||||
// set, so that every page expires by then.
|
||||
func (r *seedRun[V]) noteFilerClock(tsNs int64, at time.Time) {
|
||||
if tsNs > 0 && r.untilNs == 0 {
|
||||
r.ahead = max(r.ahead, tsNs-at.UnixNano())
|
||||
}
|
||||
}
|
||||
|
||||
// advance expires the pages whose listing ended more than a margin before
|
||||
// position: the events from there on are after anything the pages show.
|
||||
func (r *seedRun[V]) advance(position int64) {
|
||||
if position <= r.position {
|
||||
return
|
||||
}
|
||||
r.position = position
|
||||
expired := 0
|
||||
for _, p := range r.expiring {
|
||||
if p.endNs+r.ahead+r.margin >= position {
|
||||
break
|
||||
}
|
||||
r.held -= len(p.values)
|
||||
p.values = nil
|
||||
r.release(p.dir)
|
||||
expired++
|
||||
}
|
||||
if expired > 0 {
|
||||
r.expiring = r.expiring[expired:]
|
||||
r.cond.Broadcast()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *seedRun[V]) apply(event *filer_pb.SubscribeMetadataResponse) {
|
||||
n := event.EventNotification
|
||||
oldDir := util.FullPath(event.Directory)
|
||||
newDir := util.FullPath(filer_pb.MetadataEventTargetDirectory(event))
|
||||
if n.OldEntry != nil && n.NewEntry != nil && oldDir == newDir && n.OldEntry.Name == n.NewEntry.Name {
|
||||
r.applySide(oldDir, n.OldEntry.Name, event.TsNs, n.OldEntry, n.NewEntry)
|
||||
return
|
||||
}
|
||||
if n.OldEntry != nil {
|
||||
r.applySide(oldDir, n.OldEntry.Name, event.TsNs, n.OldEntry, nil)
|
||||
}
|
||||
if n.NewEntry != nil {
|
||||
r.applySide(newDir, n.NewEntry.Name, event.TsNs, nil, n.NewEntry)
|
||||
}
|
||||
}
|
||||
|
||||
// applySide applies what an event did to one name: from and to are the entry
|
||||
// before and after, nil where there was none.
|
||||
func (r *seedRun[V]) applySide(dir util.FullPath, name string, tsNs int64, from, to *filer_pb.Entry) {
|
||||
if dir != r.root.path && !dir.IsUnder(r.root.path) {
|
||||
return
|
||||
}
|
||||
if r.seed.Skip != nil && r.seed.Skip(dir) {
|
||||
return
|
||||
}
|
||||
d := r.root
|
||||
for _, part := range relativeParts(r.root.path, dir) {
|
||||
p := d.pageFor(part)
|
||||
if p == nil || d.gone[part] {
|
||||
// not listed yet, so the listing will show it; or below a
|
||||
// directory that was never counted
|
||||
return
|
||||
}
|
||||
if child := d.children[part]; child != nil {
|
||||
d = child
|
||||
continue
|
||||
}
|
||||
if _, listed := p.values[part]; p.values == nil || listed {
|
||||
// the directory was walked and is no longer kept, or was created
|
||||
// after its page: its entries change by the event
|
||||
r.seed.Change(dir, name, r.value(from), r.value(to))
|
||||
return
|
||||
}
|
||||
// missing from the walk and not created since: never counted
|
||||
return
|
||||
}
|
||||
|
||||
p := d.pageFor(name)
|
||||
if p == nil || tsNs <= p.snapshot {
|
||||
return
|
||||
}
|
||||
toValue := r.value(to)
|
||||
if p.values == nil {
|
||||
r.seed.Change(dir, name, r.value(from), toValue)
|
||||
} else {
|
||||
counted, listed := p.values[name]
|
||||
if !listed {
|
||||
r.held++
|
||||
}
|
||||
p.values[name] = toValue
|
||||
r.seed.Change(dir, name, counted, toValue)
|
||||
if to == nil && from != nil && from.IsDirectory && counted == nil && d.children[name] == nil {
|
||||
if d.gone == nil {
|
||||
d.gone = make(map[string]bool)
|
||||
}
|
||||
d.gone[name] = true
|
||||
}
|
||||
}
|
||||
if to != nil && to.IsDirectory {
|
||||
delete(d.gone, name)
|
||||
}
|
||||
}
|
||||
|
||||
// relativeParts are the names from root down to dir, which is root or below it.
|
||||
func relativeParts(root, dir util.FullPath) []string {
|
||||
if dir == root {
|
||||
return nil
|
||||
}
|
||||
rest := string(dir)
|
||||
if root != "/" {
|
||||
rest = rest[len(root):]
|
||||
}
|
||||
return util.FullPath(rest).Split()
|
||||
}
|
||||
@@ -1,469 +0,0 @@
|
||||
package treewalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer/treewalk/treewalktest"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type testValue struct {
|
||||
size uint64
|
||||
dir bool
|
||||
}
|
||||
|
||||
func testValueOf(entry *filer_pb.Entry) testValue {
|
||||
return testValue{size: entry.GetAttributes().GetFileSize(), dir: entry.IsDirectory}
|
||||
}
|
||||
|
||||
func sameValue(a, b *testValue) bool {
|
||||
return a == nil && b == nil || a != nil && b != nil && *a == *b
|
||||
}
|
||||
|
||||
// countedTree keeps what Change says of each name, and checks each change
|
||||
// starts from what it said before.
|
||||
type countedTree struct {
|
||||
t *testing.T
|
||||
entries map[util.FullPath]*testValue
|
||||
mismatch int
|
||||
}
|
||||
|
||||
func newSeedForTest(t *testing.T, client filer_pb.FilerClient, concurrency int, pageSize uint32) (*Seed[testValue], *countedTree) {
|
||||
counted := &countedTree{t: t, entries: map[util.FullPath]*testValue{}}
|
||||
seed := &Seed[testValue]{
|
||||
Client: client,
|
||||
ClientName: "test",
|
||||
Concurrency: concurrency,
|
||||
PageSize: pageSize,
|
||||
Value: testValueOf,
|
||||
Change: func(dir util.FullPath, name string, from, to *testValue) {
|
||||
path := dir.Child(name)
|
||||
if !sameValue(counted.entries[path], from) {
|
||||
if counted.mismatch++; counted.mismatch <= 5 {
|
||||
t.Errorf("change of %s from %v, but %v was counted", path, from, counted.entries[path])
|
||||
}
|
||||
}
|
||||
if to == nil {
|
||||
delete(counted.entries, path)
|
||||
} else {
|
||||
counted.entries[path] = to
|
||||
}
|
||||
},
|
||||
Margin: 300 * time.Millisecond,
|
||||
}
|
||||
return seed, counted
|
||||
}
|
||||
|
||||
// compare checks counted holds exactly the entries below root in tree, except
|
||||
// those below a skipped directory.
|
||||
func (c *countedTree) compare(tree map[util.FullPath]*filer_pb.Entry, root util.FullPath, skipped util.FullPath) {
|
||||
c.t.Helper()
|
||||
want := map[util.FullPath]testValue{}
|
||||
for path, entry := range tree {
|
||||
if !path.IsUnder(root) || root == "/" && path == "/" || skipped != "" && path.IsUnder(skipped) {
|
||||
continue
|
||||
}
|
||||
want[path] = testValueOf(entry)
|
||||
}
|
||||
errors := 0
|
||||
for path, v := range want {
|
||||
if got := c.entries[path]; got == nil || *got != v {
|
||||
if errors++; errors <= 10 {
|
||||
c.t.Errorf("%s: counted %v, the tree has %v", path, got, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
for path, got := range c.entries {
|
||||
if _, found := want[path]; !found {
|
||||
if errors++; errors <= 10 {
|
||||
c.t.Errorf("%s: counted %v, not in the tree", path, *got)
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors > 10 {
|
||||
c.t.Errorf("%d differences in all", errors)
|
||||
}
|
||||
}
|
||||
|
||||
// mutate changes the tree at random under /r and /o until stop is closed.
|
||||
func mutate(f *treewalktest.Filer, rng *rand.Rand, stop <-chan struct{}, done chan<- int) {
|
||||
ops := 0
|
||||
defer func() { done <- ops }()
|
||||
names := []string{"a", "b", "c", "d", "e"}
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
var dirs, files []util.FullPath
|
||||
for path, entry := range f.Entries() {
|
||||
if path == "/" {
|
||||
continue
|
||||
}
|
||||
if entry.IsDirectory {
|
||||
dirs = append(dirs, path)
|
||||
} else {
|
||||
files = append(files, path)
|
||||
}
|
||||
}
|
||||
sort.Slice(dirs, func(i, j int) bool { return dirs[i] < dirs[j] })
|
||||
sort.Slice(files, func(i, j int) bool { return files[i] < files[j] })
|
||||
dir := dirs[rng.Intn(len(dirs))]
|
||||
target := dir.Child(names[rng.Intn(len(names))])
|
||||
existing := f.Entry(target)
|
||||
switch op := rng.Intn(10); {
|
||||
case op < 4:
|
||||
if existing == nil || !existing.IsDirectory {
|
||||
f.Put(target, uint64(rng.Intn(1000)+1), rng.Intn(3))
|
||||
}
|
||||
case op < 5:
|
||||
if len(files) > 0 {
|
||||
f.Remove(files[rng.Intn(len(files))])
|
||||
}
|
||||
case op < 6:
|
||||
if existing == nil && len(strings.Split(string(target), "/")) <= 5 {
|
||||
f.Mkdir(target)
|
||||
}
|
||||
case op < 7:
|
||||
if victim := dirs[rng.Intn(len(dirs))]; victim != "/r" && victim != "/o" {
|
||||
f.Remove(victim)
|
||||
}
|
||||
default:
|
||||
var source util.FullPath
|
||||
if rng.Intn(2) == 0 && len(files) > 0 {
|
||||
source = files[rng.Intn(len(files))]
|
||||
} else {
|
||||
source = dirs[rng.Intn(len(dirs))]
|
||||
}
|
||||
sourceEntry := f.Entry(source)
|
||||
if source == "/r" || source == "/o" || target == source || target.IsUnder(source) || sourceEntry == nil {
|
||||
continue
|
||||
}
|
||||
if existing != nil && (existing.IsDirectory || sourceEntry.IsDirectory) {
|
||||
continue
|
||||
}
|
||||
f.Rename(source, target)
|
||||
}
|
||||
ops++
|
||||
time.Sleep(time.Duration(rng.Intn(1500)) * time.Microsecond)
|
||||
}
|
||||
}
|
||||
|
||||
func buildTree(f *treewalktest.Filer, rng *rand.Rand) {
|
||||
f.Mkdir("/r")
|
||||
f.Mkdir("/o")
|
||||
stop := make(chan struct{})
|
||||
done := make(chan int, 1)
|
||||
go mutate(f, rng, stop, done)
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
close(stop)
|
||||
<-done
|
||||
}
|
||||
|
||||
// TestSeedAddsUpToTheTreeAtItsPosition walks trees that change throughout the
|
||||
// walk, in pages of a few names, with listings that see changes land midway
|
||||
// and renames that move entries long before they log them, and checks that
|
||||
// what the seed counts is the tree as of the position it returns, name by
|
||||
// name.
|
||||
func TestSeedAddsUpToTheTreeAtItsPosition(t *testing.T) {
|
||||
for round := 0; round < 12; round++ {
|
||||
t.Run(fmt.Sprintf("round%d", round), func(t *testing.T) {
|
||||
rng := rand.New(rand.NewSource(int64(round)))
|
||||
f := treewalktest.NewFiler()
|
||||
buildTree(f, rng)
|
||||
var pauseLock sync.Mutex
|
||||
pauseRng := rand.New(rand.NewSource(int64(round) + 100))
|
||||
f.Pause = func() {
|
||||
pauseLock.Lock()
|
||||
d := time.Duration(pauseRng.Intn(1000)) * time.Microsecond
|
||||
pauseLock.Unlock()
|
||||
time.Sleep(d)
|
||||
}
|
||||
client := treewalktest.Serve(t, f)
|
||||
|
||||
concurrency := 1 + round%3
|
||||
pageSize := uint32(1 + round%4)
|
||||
seed, counted := newSeedForTest(t, client, concurrency, pageSize)
|
||||
stop := make(chan struct{})
|
||||
mutated := make(chan int, 1)
|
||||
go mutate(f, rng, stop, mutated)
|
||||
atNs, err := seed.Run(context.Background(), "/r")
|
||||
close(stop)
|
||||
ops := <-mutated
|
||||
if err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
if ops < 20 {
|
||||
t.Fatalf("only %d changes during the seed", ops)
|
||||
}
|
||||
counted.compare(f.At(atNs), "/r", "")
|
||||
if counted.mismatch > 0 {
|
||||
t.Errorf("%d changes did not start from what was counted", counted.mismatch)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedOfAQuietTreeCountsTheListing(t *testing.T) {
|
||||
rng := rand.New(rand.NewSource(7))
|
||||
f := treewalktest.NewFiler()
|
||||
buildTree(f, rng)
|
||||
client := treewalktest.Serve(t, f)
|
||||
seed, counted := newSeedForTest(t, client, 2, 2)
|
||||
var mu sync.Mutex
|
||||
started, done := map[util.FullPath]int{}, map[util.FullPath]int{}
|
||||
seed.Started = func(dir util.FullPath, depth int) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
started[dir]++
|
||||
}
|
||||
seed.Done = func(dir util.FullPath, depth int) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if started[dir] != 1 {
|
||||
t.Errorf("%s done before it started", dir)
|
||||
}
|
||||
done[dir]++
|
||||
}
|
||||
atNs, err := seed.Run(context.Background(), "/r")
|
||||
if err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
tree := f.At(atNs)
|
||||
counted.compare(tree, "/r", "")
|
||||
for path, entry := range tree {
|
||||
if entry.IsDirectory && (path == "/r" || path.IsUnder("/r")) && (started[path] != 1 || done[path] != 1) {
|
||||
t.Errorf("%s: started %d times, done %d times", path, started[path], done[path])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedLeavesOutASkippedDirectory(t *testing.T) {
|
||||
rng := rand.New(rand.NewSource(11))
|
||||
f := treewalktest.NewFiler()
|
||||
buildTree(f, rng)
|
||||
f.Mkdir("/r/skip")
|
||||
f.Put("/r/skip/file", 10, 1)
|
||||
client := treewalktest.Serve(t, f)
|
||||
seed, counted := newSeedForTest(t, client, 2, 2)
|
||||
seed.Skip = func(dir util.FullPath) bool { return dir == "/r/skip" || dir.IsUnder("/r/skip") }
|
||||
stop := make(chan struct{})
|
||||
mutated := make(chan int, 1)
|
||||
go func() {
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
mutated <- i
|
||||
return
|
||||
default:
|
||||
}
|
||||
f.Put(util.FullPath(fmt.Sprintf("/r/skip/f%d", i%7)), uint64(i), 1)
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}()
|
||||
atNs, err := seed.Run(context.Background(), "/r")
|
||||
close(stop)
|
||||
<-mutated
|
||||
if err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
counted.compare(f.At(atNs), "/r", "/r/skip")
|
||||
if counted.entries["/r/skip"] == nil {
|
||||
t.Errorf("the skipped directory itself is not counted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeedWaitsForThePageAnEventMayShowIn changes a file a page already
|
||||
// listed while the page is still being listed, and holds the page until the
|
||||
// event has had time to arrive. The event must wait for the page, which shows
|
||||
// the file as it was, and then replace it.
|
||||
func TestSeedWaitsForThePageAnEventMayShowIn(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Mkdir("/r")
|
||||
f.Put("/r/a", 1, 1)
|
||||
f.Put("/r/b", 2, 1)
|
||||
// the seed lists /r once for its starting snapshot before the walk does
|
||||
var listings atomic.Int32
|
||||
f.BeforeList = func(dir string) {
|
||||
if dir == "/r" {
|
||||
listings.Add(1)
|
||||
}
|
||||
}
|
||||
f.Listed = func(dir, name string) {
|
||||
if dir == "/r" && name == "a" && listings.Load() == 2 {
|
||||
f.Put("/r/a", 100, 1)
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
client := treewalktest.Serve(t, f)
|
||||
seed, counted := newSeedForTest(t, client, 1, 10)
|
||||
atNs, err := seed.Run(context.Background(), "/r")
|
||||
if err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
counted.compare(f.At(atNs), "/r", "")
|
||||
}
|
||||
|
||||
// TestSeedLeavesOutADirectoryRenamedAwayBeforeItsParentWasListed moves a
|
||||
// directory out of the tree after its parent's listing took its snapshot and
|
||||
// before the listing reads it, and logs the move only afterwards. Nothing of
|
||||
// the directory was counted, so none of its events may change the count.
|
||||
func TestSeedLeavesOutADirectoryRenamedAwayBeforeItsParentWasListed(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Mkdir("/r")
|
||||
f.Mkdir("/o")
|
||||
f.Mkdir("/r/p")
|
||||
f.Mkdir("/r/p/x")
|
||||
f.Put("/r/p/x/f1", 10, 1)
|
||||
f.Put("/r/p/x/f2", 20, 1)
|
||||
f.Put("/r/p/keep", 5, 1)
|
||||
var logMove func()
|
||||
f.BeforeList = func(dir string) {
|
||||
if dir == "/r/p" && logMove == nil {
|
||||
logMove = f.MoveQuietly("/r/p/x", "/o/x")
|
||||
}
|
||||
}
|
||||
f.Listed = func(dir, name string) {
|
||||
if dir == "/r/p" && name == "keep" && logMove != nil {
|
||||
logMove()
|
||||
}
|
||||
}
|
||||
client := treewalktest.Serve(t, f)
|
||||
seed, counted := newSeedForTest(t, client, 1, 10)
|
||||
atNs, err := seed.Run(context.Background(), "/r")
|
||||
if err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
counted.compare(f.At(atNs), "/r", "")
|
||||
if counted.mismatch > 0 {
|
||||
t.Errorf("%d changes did not start from what was counted", counted.mismatch)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeedRecognizesAMoveListedBeforeItsEvents moves a directory into the tree
|
||||
// before the walk lists its new parent, and logs the move a while after that
|
||||
// listing ended. The listing already counted what the events report.
|
||||
func TestSeedRecognizesAMoveListedBeforeItsEvents(t *testing.T) {
|
||||
testSeedRecognizesAMoveListedBeforeItsEvents(t, 0)
|
||||
}
|
||||
|
||||
// TestSeedRecognizesAMoveOnAFilerClockAhead has the filer stamp its events
|
||||
// on a clock that runs ahead of the worker's by more than the margin.
|
||||
func TestSeedRecognizesAMoveOnAFilerClockAhead(t *testing.T) {
|
||||
testSeedRecognizesAMoveListedBeforeItsEvents(t, 2*time.Second)
|
||||
}
|
||||
|
||||
func testSeedRecognizesAMoveListedBeforeItsEvents(t *testing.T, skew time.Duration) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Skew = skew
|
||||
f.Mkdir("/r")
|
||||
f.Mkdir("/o")
|
||||
f.Mkdir("/r/q")
|
||||
f.Mkdir("/o/y")
|
||||
f.Put("/o/y/f1", 10, 1)
|
||||
f.Put("/o/y/f2", 20, 1)
|
||||
var logMove func()
|
||||
f.BeforeList = func(dir string) {
|
||||
if dir == "/r/q" && logMove == nil {
|
||||
logMove = f.MoveQuietly("/o/y", "/r/q/y")
|
||||
}
|
||||
}
|
||||
var once sync.Once
|
||||
f.Listed = func(dir, name string) {
|
||||
if dir == "/r/q/y" && name == "f2" {
|
||||
once.Do(func() {
|
||||
go func() {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
logMove()
|
||||
}()
|
||||
})
|
||||
}
|
||||
}
|
||||
client := treewalktest.Serve(t, f)
|
||||
seed, counted := newSeedForTest(t, client, 1, 10)
|
||||
atNs, err := seed.Run(context.Background(), "/r")
|
||||
if err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
counted.compare(f.At(atNs), "/r", "")
|
||||
if counted.mismatch > 0 {
|
||||
t.Errorf("%d changes did not start from what was counted", counted.mismatch)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeedStopsWaitingWhenCanceled cancels a seed whose walk waits for the
|
||||
// pages to free names that no event will free.
|
||||
func TestSeedStopsWaitingWhenCanceled(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
for i := 0; i < 5; i++ {
|
||||
f.Put(util.FullPath(fmt.Sprintf("/r/d%d/f", i)), 1, 1)
|
||||
}
|
||||
client := treewalktest.Serve(t, f)
|
||||
seed, _ := newSeedForTest(t, client, 2, 1)
|
||||
seed.Margin = time.Hour
|
||||
seed.maxHeld = 1
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
time.AfterFunc(200*time.Millisecond, cancel)
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := seed.Run(ctx, "/r")
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil {
|
||||
t.Errorf("a canceled seed succeeded")
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("the seed still runs 10s after it was canceled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedReportsTheListingThatFailed(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Put("/r/a/f", 1, 1)
|
||||
f.Put("/r/b/f", 1, 1)
|
||||
f.Fail = func(dir string) error {
|
||||
if dir == "/r/a" {
|
||||
return status.Error(codes.PermissionDenied, "not yours")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
client := treewalktest.Serve(t, f)
|
||||
seed, _ := newSeedForTest(t, client, 2, 1)
|
||||
_, err := seed.Run(context.Background(), "/r")
|
||||
if err == nil || !strings.Contains(err.Error(), "/r/a") || !strings.Contains(err.Error(), "not yours") {
|
||||
t.Errorf("seed error %v, want the failed listing of /r/a", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogStartPassesOverADayLeftEmpty(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Mkdir(filer.SystemLogDir + "/2026-12-01")
|
||||
f.Put(filer.SystemLogDir+"/2026-12-02/08-30.00000001", 1, 0)
|
||||
f.Put(filer.SystemLogDir+"/2026-12-03/00-00.00000001", 1, 0)
|
||||
client := treewalktest.Serve(t, f)
|
||||
err := client.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
|
||||
got, err := LogStartTsNs(context.Background(), c)
|
||||
if want := time.Date(2026, 12, 2, 8, 30, 0, 0, time.UTC).UnixNano(); err != nil || got != want {
|
||||
t.Errorf("log start %v, %v, want %v", time.Unix(0, got).UTC(), err, time.Unix(0, want).UTC())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,452 +0,0 @@
|
||||
// Package treewalktest has a filer for tests of walks and replays: it serves
|
||||
// a tree from memory and logs an event for each change.
|
||||
package treewalktest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
)
|
||||
|
||||
// Filer serves a tree from memory and logs an event for each change the way
|
||||
// the filer does: a recursive delete logs the entries below a directory
|
||||
// before the directory, and a rename logs the directory and then everything
|
||||
// it moved, once the whole move is done. A listing says it is complete
|
||||
// through the time it started, when every change stamped before is logged.
|
||||
type Filer struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
|
||||
Signature int32
|
||||
DirBuckets string
|
||||
|
||||
// Pause, if set, is called between the entries of a listing, a recursive
|
||||
// delete and a rename, without the lock, so changes land inside listings
|
||||
// and listings see deletes and renames half done.
|
||||
Pause func()
|
||||
// BeforeList is called once a listing took its snapshot, and Listed after
|
||||
// each entry the listing sent, both without the lock.
|
||||
BeforeList func(dir string)
|
||||
Listed func(dir string, name string)
|
||||
// Fail, if set, can refuse a listing of dir with an error.
|
||||
Fail func(dir string) error
|
||||
// Skew is how far the filer's clock runs ahead of the test's.
|
||||
Skew time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
entries map[util.FullPath]*filer_pb.Entry
|
||||
lastTs int64
|
||||
log []*filer_pb.SubscribeMetadataResponse
|
||||
// the events of directories dropped with what was below them
|
||||
dropped map[int64]bool
|
||||
}
|
||||
|
||||
func NewFiler() *Filer {
|
||||
return &Filer{
|
||||
Signature: 1,
|
||||
DirBuckets: "/buckets",
|
||||
entries: map[util.FullPath]*filer_pb.Entry{"/": {IsDirectory: true}},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) now() int64 {
|
||||
return time.Now().Add(f.Skew).UnixNano()
|
||||
}
|
||||
|
||||
func (f *Filer) stamp() int64 {
|
||||
ts := f.now()
|
||||
if ts <= f.lastTs {
|
||||
ts = f.lastTs + 1
|
||||
}
|
||||
f.lastTs = ts
|
||||
return ts
|
||||
}
|
||||
|
||||
func (f *Filer) logEvent(dir util.FullPath, oldEntry, newEntry *filer_pb.Entry, newParent util.FullPath) {
|
||||
event := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: string(dir),
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: oldEntry, NewEntry: newEntry},
|
||||
TsNs: f.stamp(),
|
||||
}
|
||||
if newParent != "" && newParent != dir {
|
||||
event.EventNotification.NewParentPath = string(newParent)
|
||||
}
|
||||
f.log = append(f.log, event)
|
||||
}
|
||||
|
||||
func (f *Filer) giveWay() {
|
||||
if f.Pause != nil {
|
||||
f.mu.Unlock()
|
||||
f.Pause()
|
||||
f.mu.Lock()
|
||||
}
|
||||
}
|
||||
|
||||
func parentOf(path util.FullPath) util.FullPath {
|
||||
dir, _ := path.DirAndName()
|
||||
return util.FullPath(dir)
|
||||
}
|
||||
|
||||
// LastTs is the time of the last event logged.
|
||||
func (f *Filer) LastTs() int64 {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.lastTs
|
||||
}
|
||||
|
||||
// Entry is the entry at path, or nil.
|
||||
func (f *Filer) Entry(path util.FullPath) *filer_pb.Entry {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.entries[path]
|
||||
}
|
||||
|
||||
// Entries are all entries, directories included, by path.
|
||||
func (f *Filer) Entries() map[util.FullPath]*filer_pb.Entry {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
entries := make(map[util.FullPath]*filer_pb.Entry, len(f.entries))
|
||||
for path, entry := range f.entries {
|
||||
entries[path] = entry
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// mkdirAll creates the missing directories down to dir, each with its event.
|
||||
func (f *Filer) mkdirAll(dir util.FullPath) {
|
||||
if dir == "/" || f.entries[dir] != nil {
|
||||
return
|
||||
}
|
||||
f.mkdirAll(parentOf(dir))
|
||||
entry := &filer_pb.Entry{Name: dir.Name(), IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}
|
||||
f.entries[dir] = entry
|
||||
f.logEvent(parentOf(dir), nil, entry, "")
|
||||
}
|
||||
|
||||
func (f *Filer) putEntry(dir util.FullPath, entry *filer_pb.Entry) {
|
||||
f.mkdirAll(dir)
|
||||
path := dir.Child(entry.Name)
|
||||
old := f.entries[path]
|
||||
f.entries[path] = entry
|
||||
f.logEvent(dir, old, entry, "")
|
||||
}
|
||||
|
||||
// Put writes a file of size at path, with chunks chunks.
|
||||
func (f *Filer) Put(path util.FullPath, size uint64, chunks int) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
entry := &filer_pb.Entry{Name: path.Name(), Attributes: &filer_pb.FuseAttributes{FileSize: size}}
|
||||
for i := 0; i < chunks; i++ {
|
||||
entry.Chunks = append(entry.Chunks, &filer_pb.FileChunk{FileId: strconv.Itoa(i), Size: size / uint64(chunks)})
|
||||
}
|
||||
f.putEntry(parentOf(path), entry)
|
||||
}
|
||||
|
||||
// Mkdir creates a directory at path, and the missing ones above it.
|
||||
func (f *Filer) Mkdir(path util.FullPath) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.mkdirAll(path)
|
||||
}
|
||||
|
||||
// subtree is path and everything below it, each directory before its entries.
|
||||
func (f *Filer) subtree(path util.FullPath) []util.FullPath {
|
||||
var paths []util.FullPath
|
||||
for p := range f.entries {
|
||||
if p == path || p.IsUnder(path) {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
}
|
||||
sort.Slice(paths, func(i, j int) bool { return paths[i] < paths[j] })
|
||||
return paths
|
||||
}
|
||||
|
||||
// Remove deletes path and what is below it, the deepest first, one at a time.
|
||||
func (f *Filer) Remove(path util.FullPath) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.remove(path, true)
|
||||
}
|
||||
|
||||
// DropQuietly deletes path and what is below it with one event for path
|
||||
// alone, the way a store that drops a whole bucket does.
|
||||
func (f *Filer) DropQuietly(path util.FullPath) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
old := f.entries[path]
|
||||
for _, p := range f.subtree(path) {
|
||||
delete(f.entries, p)
|
||||
}
|
||||
if old != nil {
|
||||
f.logEvent(parentOf(path), old, nil, "")
|
||||
if f.dropped == nil {
|
||||
f.dropped = make(map[int64]bool)
|
||||
}
|
||||
f.dropped[f.lastTs] = true
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) remove(path util.FullPath, giveWay bool) {
|
||||
paths := f.subtree(path)
|
||||
for i := len(paths) - 1; i >= 0; i-- {
|
||||
old := f.entries[paths[i]]
|
||||
if old == nil {
|
||||
continue
|
||||
}
|
||||
delete(f.entries, paths[i])
|
||||
f.logEvent(parentOf(paths[i]), old, nil, "")
|
||||
if giveWay {
|
||||
f.giveWay()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rename moves path to target an entry at a time, replacing a file already
|
||||
// at target, and logs the events once everything is moved.
|
||||
func (f *Filer) Rename(path, target util.FullPath) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.logAll(f.move(path, target))
|
||||
}
|
||||
|
||||
// MoveQuietly moves path to target without logging anything yet, and returns
|
||||
// what logs the move's events.
|
||||
func (f *Filer) MoveQuietly(path, target util.FullPath) (logEvents func()) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
events := f.move(path, target)
|
||||
return func() {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.logAll(events)
|
||||
}
|
||||
}
|
||||
|
||||
type pendingEvent struct {
|
||||
dir, newParent util.FullPath
|
||||
oldEntry, toEntry *filer_pb.Entry
|
||||
}
|
||||
|
||||
func (f *Filer) move(path, target util.FullPath) []pendingEvent {
|
||||
var events []pendingEvent
|
||||
if replaced := f.entries[target]; replaced != nil {
|
||||
delete(f.entries, target)
|
||||
events = append(events, pendingEvent{dir: parentOf(target), oldEntry: replaced})
|
||||
}
|
||||
for _, p := range f.subtree(path) {
|
||||
old := f.entries[p]
|
||||
to := target + p[len(path):]
|
||||
moved := &filer_pb.Entry{Name: to.Name(), IsDirectory: old.IsDirectory, Attributes: old.Attributes, Chunks: old.Chunks}
|
||||
events = append(events, pendingEvent{dir: parentOf(p), newParent: parentOf(to), oldEntry: old, toEntry: moved})
|
||||
f.entries[to] = moved
|
||||
delete(f.entries, p)
|
||||
f.giveWay()
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
func (f *Filer) logAll(events []pendingEvent) {
|
||||
for _, e := range events {
|
||||
f.logEvent(e.dir, e.oldEntry, e.toEntry, e.newParent)
|
||||
}
|
||||
}
|
||||
|
||||
// At replays the log up to tsNs.
|
||||
func (f *Filer) At(tsNs int64) map[util.FullPath]*filer_pb.Entry {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
tree := map[util.FullPath]*filer_pb.Entry{"/": f.entries["/"]}
|
||||
for _, event := range f.log {
|
||||
if event.TsNs > tsNs {
|
||||
break
|
||||
}
|
||||
n := event.EventNotification
|
||||
if n.OldEntry != nil {
|
||||
path := util.FullPath(event.Directory).Child(n.OldEntry.Name)
|
||||
delete(tree, path)
|
||||
if f.dropped[event.TsNs] {
|
||||
for below := range tree {
|
||||
if below.IsUnder(path) {
|
||||
delete(tree, below)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if n.NewEntry != nil {
|
||||
tree[util.FullPath(filer_pb.MetadataEventTargetDirectory(event)).Child(n.NewEntry.Name)] = n.NewEntry
|
||||
}
|
||||
}
|
||||
return tree
|
||||
}
|
||||
|
||||
func (f *Filer) nextChild(dir util.FullPath, after, prefix string) *filer_pb.Entry {
|
||||
var next *filer_pb.Entry
|
||||
for p, entry := range f.entries {
|
||||
if p == "/" || parentOf(p) != dir {
|
||||
continue
|
||||
}
|
||||
name := p.Name()
|
||||
if name > after && strings.HasPrefix(name, prefix) && (next == nil || name < next.Name) {
|
||||
next = entry
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (f *Filer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
|
||||
f.mu.Lock()
|
||||
// with nothing in flight, the filer has logged everything up to now
|
||||
snapshot := max(f.lastTs, f.now())
|
||||
f.mu.Unlock()
|
||||
if f.BeforeList != nil {
|
||||
f.BeforeList(req.Directory)
|
||||
}
|
||||
if f.Fail != nil {
|
||||
if err := f.Fail(req.Directory); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
after := req.StartFromFileName
|
||||
var sent uint32
|
||||
for req.Limit == 0 || sent < req.Limit {
|
||||
entry := f.nextChild(util.FullPath(req.Directory), after, req.Prefix)
|
||||
if entry == nil {
|
||||
break
|
||||
}
|
||||
resp := &filer_pb.ListEntriesResponse{Entry: entry}
|
||||
if sent == 0 {
|
||||
resp.SnapshotTsNs = snapshot
|
||||
}
|
||||
if err := stream.Send(resp); err != nil {
|
||||
return err
|
||||
}
|
||||
sent++
|
||||
after = entry.Name
|
||||
if f.Listed != nil {
|
||||
f.mu.Unlock()
|
||||
f.Listed(req.Directory, entry.Name)
|
||||
f.mu.Lock()
|
||||
}
|
||||
f.giveWay()
|
||||
}
|
||||
if sent == 0 {
|
||||
stream.SetTrailer(metadata.Pairs(filer_pb.ListSnapshotTsNsTrailerKey, strconv.FormatInt(snapshot, 10)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Filer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error {
|
||||
cursor := req.SinceNs
|
||||
for {
|
||||
f.mu.Lock()
|
||||
// every event stamped at or before now is in the log
|
||||
now := f.now()
|
||||
i := sort.Search(len(f.log), func(i int) bool { return f.log[i].TsNs > cursor })
|
||||
batch := append([]*filer_pb.SubscribeMetadataResponse(nil), f.log[i:]...)
|
||||
f.mu.Unlock()
|
||||
for _, event := range batch {
|
||||
if req.UntilNs != 0 && event.TsNs > req.UntilNs {
|
||||
return nil
|
||||
}
|
||||
cursor = event.TsNs
|
||||
if !filer_pb.MetadataEventMatchesSubscription(event, req.PathPrefix, req.PathPrefixes, req.Directories) {
|
||||
continue
|
||||
}
|
||||
if err := stream.Send(event); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if req.UntilNs != 0 && now > req.UntilNs {
|
||||
return nil
|
||||
}
|
||||
if req.ClientSupportsIdleHeartbeat && len(batch) == 0 {
|
||||
if err := stream.Send(&filer_pb.SubscribeMetadataResponse{TsNs: now}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-stream.Context().Done():
|
||||
return stream.Context().Err()
|
||||
case <-time.After(200 * time.Microsecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
entry := f.entries[util.FullPath(req.Directory).Child(req.Name)]
|
||||
if entry == nil {
|
||||
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: entry}, nil
|
||||
}
|
||||
|
||||
func (f *Filer) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.putEntry(util.FullPath(req.Directory), req.Entry)
|
||||
return &filer_pb.CreateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *Filer) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.putEntry(util.FullPath(req.Directory), req.Entry)
|
||||
return &filer_pb.UpdateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *Filer) DeleteEntry(_ context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.remove(util.FullPath(req.Directory).Child(req.Name), false)
|
||||
return &filer_pb.DeleteEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *Filer) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
|
||||
return &filer_pb.GetFilerConfigurationResponse{Signature: f.Signature, DirBuckets: f.DirBuckets}, nil
|
||||
}
|
||||
|
||||
// Client reaches a Filer over an in-memory connection.
|
||||
type Client struct {
|
||||
conn *grpc.ClientConn
|
||||
}
|
||||
|
||||
func (c *Client) WithFilerClient(_ bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return fn(filer_pb.NewSeaweedFilerClient(c.conn))
|
||||
}
|
||||
func (c *Client) AdjustedUrl(location *filer_pb.Location) string { return location.Url }
|
||||
func (c *Client) GetDataCenter() string { return "" }
|
||||
|
||||
// Serve serves f until the test ends.
|
||||
func Serve(t testing.TB, f *Filer) *Client {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(server, f)
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(server.Stop)
|
||||
conn, err := grpc.NewClient("passthrough:///bufnet",
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }),
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return &Client{conn: conn}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
// Package treewalk walks a filer directory tree a page at a time, and adds up
|
||||
// such a walk with the metadata events that arrive while it runs, so that the
|
||||
// walk and the events add up to the tree as of one log position.
|
||||
package treewalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// Page is one page of a directory listing.
|
||||
type Page struct {
|
||||
Dir util.FullPath
|
||||
Depth int // levels below the directory the walk started at
|
||||
// After is the name the page was listed after, "" for the first page. The
|
||||
// page covers the names after it up to its last entry's name, or up to the
|
||||
// end of the directory when Last is set.
|
||||
After string
|
||||
Entries []*filer_pb.Entry
|
||||
Last bool
|
||||
// Snapshot is the log position the filer said the page is complete
|
||||
// through: every change logged at or before it shows in the page. It is 0
|
||||
// when the filer did not say.
|
||||
Snapshot int64
|
||||
// Start is when the page was asked for and End when its stream ended, on
|
||||
// this process's clock.
|
||||
Start, End time.Time
|
||||
}
|
||||
|
||||
// Visitor is told about a walk as it goes. Its methods are called from
|
||||
// several goroutines at once.
|
||||
type Visitor interface {
|
||||
// Started is called before the first page of dir is listed.
|
||||
Started(dir util.FullPath, depth int)
|
||||
// Listing is called before each page is asked for. It can hold the walk
|
||||
// back by not returning yet, and stop the listing of dir with an error.
|
||||
// It returns once ctx ends.
|
||||
Listing(ctx context.Context, dir util.FullPath) error
|
||||
// Listed is called with each page once its stream is done. It returns the
|
||||
// subdirectories among the page's entries to walk.
|
||||
Listed(page *Page) (subDirs []string)
|
||||
// Done is called once dir, and every directory below it the walk went
|
||||
// into, is listed. err is what ended the listing of dir early, if anything.
|
||||
Done(dir util.FullPath, depth int, err error)
|
||||
}
|
||||
|
||||
// Walker lists a directory tree depth first, up to Concurrency directories at
|
||||
// a time. A subdirectory gets a goroutine of its own while the concurrency
|
||||
// allows one and is walked in place otherwise. Each directory is listed a page
|
||||
// at a time, and the walks of a page's subdirectories are under way before the
|
||||
// next page is listed, so memory grows with the depth of the tree and the
|
||||
// concurrency, not with the number or the width of its directories.
|
||||
type Walker struct {
|
||||
Client filer_pb.FilerClient
|
||||
Concurrency int
|
||||
PageSize uint32
|
||||
}
|
||||
|
||||
type walk struct {
|
||||
*Walker
|
||||
visitor Visitor
|
||||
// one slot per goroutine walking beside the caller's
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
// Walk walks dir and everything below it, or with a prefix only the entries
|
||||
// of dir whose names start with it and what is below them. A directory below
|
||||
// dir that cannot be listed is reported to the visitor's Done and the walk
|
||||
// goes on. Walk returns what ended the listing of dir itself, after stopping
|
||||
// the walks under way.
|
||||
func (w *Walker) Walk(ctx context.Context, dir util.FullPath, prefix string, visitor Visitor) error {
|
||||
if w.PageSize == 0 {
|
||||
return fmt.Errorf("walk %s: page size 0", dir)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
walking := &walk{Walker: w, visitor: visitor, slots: make(chan struct{}, max(w.Concurrency, 1)-1)}
|
||||
|
||||
visitor.Started(dir, 0)
|
||||
var children sync.WaitGroup
|
||||
err := walking.list(ctx, dir, 0, prefix, &children)
|
||||
if err != nil {
|
||||
// nothing below dir is wanted once its own listing failed
|
||||
cancel()
|
||||
}
|
||||
children.Wait()
|
||||
visitor.Done(dir, 0, err)
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *walk) walkDir(ctx context.Context, dir util.FullPath, depth int) {
|
||||
w.visitor.Started(dir, depth)
|
||||
var children sync.WaitGroup
|
||||
err := w.list(ctx, dir, depth, "", &children)
|
||||
children.Wait()
|
||||
w.visitor.Done(dir, depth, err)
|
||||
}
|
||||
|
||||
// pageRetryFor is how long a page that fails with a transient error, as when
|
||||
// the filer restarts, is asked for again before the listing fails.
|
||||
const pageRetryFor = time.Minute
|
||||
|
||||
// list lists dir a page at a time and starts the walks of the subdirectories
|
||||
// the visitor picks from each page before listing the next. A page that fails
|
||||
// is dropped and its error returned.
|
||||
func (w *walk) list(ctx context.Context, dir util.FullPath, depth int, prefix string, children *sync.WaitGroup) error {
|
||||
after := ""
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.visitor.Listing(ctx, dir); err != nil {
|
||||
return err
|
||||
}
|
||||
page := &Page{Dir: dir, Depth: depth, After: after, Start: time.Now()}
|
||||
err := util.RetryWithBackoff(ctx, "list "+string(dir), pageRetryFor, util.IsTransientError, func() error {
|
||||
page.Entries = nil
|
||||
return w.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
var err error
|
||||
page.Snapshot, err = filer_pb.DoSeaweedListWithSnapshot(ctx, client, dir, prefix, func(entry *filer_pb.Entry, isLast bool) error {
|
||||
page.Entries = append(page.Entries, entry)
|
||||
return nil
|
||||
}, after, false, w.PageSize, 0)
|
||||
return err
|
||||
})
|
||||
})
|
||||
page.End = time.Now()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
page.Last = uint32(len(page.Entries)) < w.PageSize
|
||||
subDirs := w.visitor.Listed(page)
|
||||
w.walkSubDirs(ctx, dir, subDirs, depth+1, children)
|
||||
if page.Last {
|
||||
// a walk stopped midway may have left out some of the page's
|
||||
// subdirectories
|
||||
return ctx.Err()
|
||||
}
|
||||
// a store that does not move past the cursor would page forever
|
||||
last := page.Entries[len(page.Entries)-1].Name
|
||||
if last == after {
|
||||
return fmt.Errorf("list %s: pagination stuck at %q", dir, after)
|
||||
}
|
||||
after = last
|
||||
}
|
||||
}
|
||||
|
||||
// walkSubDirs walks the named subdirectories of parent, which are depth levels
|
||||
// below the top, each in a goroutine of its own while a slot is free and in
|
||||
// place otherwise.
|
||||
func (w *walk) walkSubDirs(ctx context.Context, parent util.FullPath, names []string, depth int, children *sync.WaitGroup) {
|
||||
for _, name := range names {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
child := parent.Child(name)
|
||||
select {
|
||||
case w.slots <- struct{}{}:
|
||||
children.Add(1)
|
||||
go func() {
|
||||
defer children.Done()
|
||||
w.walkDir(ctx, child, depth)
|
||||
<-w.slots
|
||||
}()
|
||||
default:
|
||||
w.walkDir(ctx, child, depth)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
package treewalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer/treewalk/treewalktest"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// recordingVisitor keeps what a walk told it, and walks every subdirectory.
|
||||
type recordingVisitor struct {
|
||||
mu sync.Mutex
|
||||
pages []string
|
||||
started map[util.FullPath]int
|
||||
done map[util.FullPath]int
|
||||
failed map[util.FullPath]error
|
||||
// directories a page lists, which must be done before their parent is
|
||||
order []util.FullPath
|
||||
}
|
||||
|
||||
func newRecordingVisitor() *recordingVisitor {
|
||||
return &recordingVisitor{started: map[util.FullPath]int{}, done: map[util.FullPath]int{}, failed: map[util.FullPath]error{}}
|
||||
}
|
||||
|
||||
func (v *recordingVisitor) Started(dir util.FullPath, depth int) {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
v.started[dir]++
|
||||
}
|
||||
|
||||
func (v *recordingVisitor) Listing(context.Context, util.FullPath) error { return nil }
|
||||
|
||||
func (v *recordingVisitor) Listed(page *Page) []string {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
var names, subDirs []string
|
||||
for _, entry := range page.Entries {
|
||||
names = append(names, entry.Name)
|
||||
if entry.IsDirectory {
|
||||
subDirs = append(subDirs, entry.Name)
|
||||
}
|
||||
}
|
||||
if page.Snapshot == 0 || page.End.Before(page.Start) {
|
||||
v.failed[page.Dir] = fmt.Errorf("page after %q: snapshot %d, %s to %s", page.After, page.Snapshot, page.Start, page.End)
|
||||
}
|
||||
v.pages = append(v.pages, fmt.Sprintf("%s@%d after %q: %s last=%v", page.Dir, page.Depth, page.After, strings.Join(names, ","), page.Last))
|
||||
return subDirs
|
||||
}
|
||||
|
||||
func (v *recordingVisitor) Done(dir util.FullPath, depth int, err error) {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
v.done[dir]++
|
||||
v.order = append(v.order, dir)
|
||||
if err != nil {
|
||||
v.failed[dir] = err
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkerListsEachDirectoryAPageAtATime(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Put("/top/a/x", 1, 1)
|
||||
f.Put("/top/a/y", 1, 1)
|
||||
f.Put("/top/b/z", 1, 1)
|
||||
f.Put("/top/c", 1, 1)
|
||||
f.Mkdir("/top/d")
|
||||
client := treewalktest.Serve(t, f)
|
||||
|
||||
v := newRecordingVisitor()
|
||||
walker := &Walker{Client: client, Concurrency: 1, PageSize: 2}
|
||||
if err := walker.Walk(context.Background(), "/top", "", v); err != nil {
|
||||
t.Fatalf("walk: %v", err)
|
||||
}
|
||||
want := []string{
|
||||
`/top@0 after "": a,b last=false`,
|
||||
`/top/a@1 after "": x,y last=false`,
|
||||
`/top/a@1 after "y": ` + ` last=true`,
|
||||
`/top/b@1 after "": z last=true`,
|
||||
`/top@0 after "b": c,d last=false`,
|
||||
`/top/d@1 after "": ` + ` last=true`,
|
||||
`/top@0 after "d": ` + ` last=true`,
|
||||
}
|
||||
if got := strings.Join(v.pages, "\n"); got != strings.Join(want, "\n") {
|
||||
t.Errorf("pages:\n%s\nwant\n%s", got, strings.Join(want, "\n"))
|
||||
}
|
||||
for _, dir := range []util.FullPath{"/top", "/top/a", "/top/b", "/top/d"} {
|
||||
if v.started[dir] != 1 || v.done[dir] != 1 {
|
||||
t.Errorf("%s started %d times and done %d times", dir, v.started[dir], v.done[dir])
|
||||
}
|
||||
}
|
||||
if v.order[len(v.order)-1] != "/top" {
|
||||
t.Errorf("the top is done before what is below it: %v", v.order)
|
||||
}
|
||||
for dir, err := range v.failed {
|
||||
t.Errorf("%s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
// countingVisitor counts the page requests out at once.
|
||||
type countingVisitor struct {
|
||||
*recordingVisitor
|
||||
mu sync.Mutex
|
||||
out int
|
||||
most int
|
||||
requests int
|
||||
}
|
||||
|
||||
func (v *countingVisitor) Listing(context.Context, util.FullPath) error {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
v.out++
|
||||
v.requests++
|
||||
v.most = max(v.most, v.out)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *countingVisitor) Listed(page *Page) []string {
|
||||
v.mu.Lock()
|
||||
v.out--
|
||||
v.mu.Unlock()
|
||||
return v.recordingVisitor.Listed(page)
|
||||
}
|
||||
|
||||
func TestWalkerListsUpToConcurrencyDirectoriesAtOnce(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
for i := 0; i < 20; i++ {
|
||||
f.Put(util.FullPath(fmt.Sprintf("/top/d%02d/e/f", i)), 1, 1)
|
||||
}
|
||||
f.Pause = func() { time.Sleep(time.Millisecond) }
|
||||
client := treewalktest.Serve(t, f)
|
||||
for _, concurrency := range []int{1, 4} {
|
||||
v := &countingVisitor{recordingVisitor: newRecordingVisitor()}
|
||||
walker := &Walker{Client: client, Concurrency: concurrency, PageSize: 100}
|
||||
if err := walker.Walk(context.Background(), "/top", "", v); err != nil {
|
||||
t.Fatalf("walk: %v", err)
|
||||
}
|
||||
if len(v.done) != 41 {
|
||||
t.Errorf("concurrency %d: walked %d directories", concurrency, len(v.done))
|
||||
}
|
||||
if v.most > concurrency || concurrency > 1 && v.most < 2 {
|
||||
t.Errorf("concurrency %d: %d listings out at once", concurrency, v.most)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cancelingVisitor cancels the walk as the last page of its top directory
|
||||
// is listed.
|
||||
type cancelingVisitor struct {
|
||||
*recordingVisitor
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (v *cancelingVisitor) Listed(page *Page) []string {
|
||||
subDirs := v.recordingVisitor.Listed(page)
|
||||
if page.Depth == 0 && page.Last {
|
||||
v.cancel()
|
||||
}
|
||||
return subDirs
|
||||
}
|
||||
|
||||
func TestWalkerFailsAWalkStoppedOnTheLastPage(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Put("/top/a/f", 1, 1)
|
||||
f.Put("/top/b/f", 1, 1)
|
||||
client := treewalktest.Serve(t, f)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
v := &cancelingVisitor{recordingVisitor: newRecordingVisitor(), cancel: cancel}
|
||||
walker := &Walker{Client: client, Concurrency: 1, PageSize: 100}
|
||||
if err := walker.Walk(ctx, "/top", "", v); err == nil {
|
||||
t.Errorf("a walk stopped before its subdirectories succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// flakyClient breaks the first listing of each page it names with the code
|
||||
// given, once the page handed its first entry on, the way a filer that
|
||||
// restarts mid-stream does.
|
||||
type flakyClient struct {
|
||||
*treewalktest.Client
|
||||
mu sync.Mutex
|
||||
failing map[string]codes.Code
|
||||
broke []string
|
||||
}
|
||||
|
||||
func (c *flakyClient) WithFilerClient(streaming bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return c.Client.WithFilerClient(streaming, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return fn(&flakyFilerClient{SeaweedFilerClient: client, c: c})
|
||||
})
|
||||
}
|
||||
|
||||
type flakyFilerClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
c *flakyClient
|
||||
}
|
||||
|
||||
func (f *flakyFilerClient) ListEntries(ctx context.Context, req *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (filer_pb.SeaweedFiler_ListEntriesClient, error) {
|
||||
stream, err := f.SeaweedFilerClient.ListEntries(ctx, req, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page := fmt.Sprintf("%s after %q", req.Directory, req.StartFromFileName)
|
||||
f.c.mu.Lock()
|
||||
defer f.c.mu.Unlock()
|
||||
code, failing := f.c.failing[page]
|
||||
if !failing {
|
||||
return stream, nil
|
||||
}
|
||||
delete(f.c.failing, page)
|
||||
f.c.broke = append(f.c.broke, page)
|
||||
return &brokenStream{SeaweedFiler_ListEntriesClient: stream, code: code}, nil
|
||||
}
|
||||
|
||||
// brokenStream fails once two entries are read: the lister hands an entry on
|
||||
// when the next one arrives.
|
||||
type brokenStream struct {
|
||||
filer_pb.SeaweedFiler_ListEntriesClient
|
||||
code codes.Code
|
||||
received int
|
||||
}
|
||||
|
||||
func (s *brokenStream) Recv() (*filer_pb.ListEntriesResponse, error) {
|
||||
if s.received == 2 {
|
||||
return nil, status.Error(s.code, "listing broken")
|
||||
}
|
||||
s.received++
|
||||
return s.SeaweedFiler_ListEntriesClient.Recv()
|
||||
}
|
||||
|
||||
func TestWalkerListsAPageAgainAfterATransientFailure(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Put("/top/a/x", 1, 1)
|
||||
f.Put("/top/a/y", 1, 1)
|
||||
f.Put("/top/b/z", 1, 1)
|
||||
f.Put("/top/c", 1, 1)
|
||||
f.Mkdir("/top/d")
|
||||
client := &flakyClient{Client: treewalktest.Serve(t, f), failing: map[string]codes.Code{
|
||||
`/top/a after ""`: codes.Unavailable,
|
||||
`/top after "b"`: codes.Unavailable,
|
||||
}}
|
||||
|
||||
v := newRecordingVisitor()
|
||||
walker := &Walker{Client: client, Concurrency: 1, PageSize: 2}
|
||||
if err := walker.Walk(context.Background(), "/top", "", v); err != nil {
|
||||
t.Fatalf("walk: %v", err)
|
||||
}
|
||||
if len(client.broke) != 2 {
|
||||
t.Fatalf("broke %v, want both pages broken once", client.broke)
|
||||
}
|
||||
want := []string{
|
||||
`/top@0 after "": a,b last=false`,
|
||||
`/top/a@1 after "": x,y last=false`,
|
||||
`/top/a@1 after "y": ` + ` last=true`,
|
||||
`/top/b@1 after "": z last=true`,
|
||||
`/top@0 after "b": c,d last=false`,
|
||||
`/top/d@1 after "": ` + ` last=true`,
|
||||
`/top@0 after "d": ` + ` last=true`,
|
||||
}
|
||||
if got := strings.Join(v.pages, "\n"); got != strings.Join(want, "\n") {
|
||||
t.Errorf("pages:\n%s\nwant\n%s", got, strings.Join(want, "\n"))
|
||||
}
|
||||
for dir, err := range v.failed {
|
||||
t.Errorf("%s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkerDoesNotListAgainAfterAPermanentFailure(t *testing.T) {
|
||||
f := treewalktest.NewFiler()
|
||||
f.Put("/top/a/x", 1, 1)
|
||||
f.Put("/top/a/y", 1, 1)
|
||||
client := &flakyClient{Client: treewalktest.Serve(t, f), failing: map[string]codes.Code{
|
||||
`/top/a after ""`: codes.PermissionDenied,
|
||||
}}
|
||||
|
||||
v := newRecordingVisitor()
|
||||
walker := &Walker{Client: client, Concurrency: 1, PageSize: 2}
|
||||
if err := walker.Walk(context.Background(), "/top", "", v); err != nil {
|
||||
t.Fatalf("walk: %v", err)
|
||||
}
|
||||
if status.Code(v.failed["/top/a"]) != codes.PermissionDenied {
|
||||
t.Errorf("/top/a failed with %v, want the permission error", v.failed["/top/a"])
|
||||
}
|
||||
}
|
||||
@@ -237,6 +237,7 @@ func TestAddKMSProviderWiresCache(t *testing.T) {
|
||||
|
||||
mgr := &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
|
||||
|
||||
+17
-121
@@ -15,13 +15,11 @@ import (
|
||||
|
||||
// KMSManager manages KMS provider instances and configurations
|
||||
type KMSManager struct {
|
||||
// writeMu serializes the changes to providers, which can wait on a provider being created,
|
||||
// so a load can't swap back in an instance another change has already closed.
|
||||
writeMu sync.Mutex
|
||||
mu sync.RWMutex
|
||||
providers map[string]KMSProvider // provider name -> provider instance
|
||||
configs map[string]*KMSConfig // provider name -> configuration
|
||||
bucketKMS map[string]string // bucket name -> provider name
|
||||
defaultKMS string // default KMS provider name, the one S3 uses
|
||||
defaultKMS string // default KMS provider name
|
||||
}
|
||||
|
||||
// KMSConfig represents a complete KMS provider configuration
|
||||
@@ -224,6 +222,7 @@ func InitializeKMSManager() *KMSManager {
|
||||
if globalKMSManager == nil {
|
||||
globalKMSManager = &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
glog.V(1).Infof("KMS Manager initialized")
|
||||
@@ -255,17 +254,25 @@ func (km *KMSManager) AddKMSProvider(name string, config *KMSConfig) error {
|
||||
return fmt.Errorf("KMS configuration cannot be nil")
|
||||
}
|
||||
|
||||
km.writeMu.Lock()
|
||||
defer km.writeMu.Unlock()
|
||||
|
||||
provider, err := newManagedProvider(config)
|
||||
// Create a new provider instance of its own: a cached registry instance would be the
|
||||
// one closed below and then handed back still in use. It is created before the lock is
|
||||
// taken and the current provider closed, so a slow configuration does not hold up other
|
||||
// lookups and one that fails leaves the current provider working.
|
||||
settings := &configAdapter{config: config.Config}
|
||||
provider, err := settings.checked(NewProvider(config.Provider, settings))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create KMS provider %s: %w", name, err)
|
||||
}
|
||||
|
||||
// Wrap with a decrypted-data-key cache when enabled so repeated reads of
|
||||
// the same SSE-KMS object avoid a KMS round-trip per read.
|
||||
provider = wrapWithCacheIfEnabled(provider, config)
|
||||
|
||||
// Store provider and configuration
|
||||
km.mu.Lock()
|
||||
existingProvider, exists := km.providers[name]
|
||||
km.providers[name] = provider
|
||||
km.configs[name] = config
|
||||
km.mu.Unlock()
|
||||
|
||||
// Close the provider it replaces
|
||||
@@ -279,115 +286,6 @@ func (km *KMSManager) AddKMSProvider(name string, config *KMSConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// newManagedProvider builds an instance of its own, as a cached registry instance would be the
|
||||
// one a reload closes and then hands back. It runs without the manager's lock, so a slow
|
||||
// provider doesn't hold up lookups.
|
||||
func newManagedProvider(config *KMSConfig) (KMSProvider, error) {
|
||||
settings := &configAdapter{config: config.Config}
|
||||
provider, err := settings.checked(NewProvider(config.Provider, settings))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Wrap with a decrypted-data-key cache when enabled so repeated reads of
|
||||
// the same SSE-KMS object avoid a KMS round-trip per read.
|
||||
return wrapWithCacheIfEnabled(provider, config), nil
|
||||
}
|
||||
|
||||
// load builds a new instance of every provider, so a configuration change always takes
|
||||
// effect. Only the default provider, which S3 uses, failing fails the load; any other provider
|
||||
// that fails keeps its previous instance.
|
||||
func (km *KMSManager) load(s *kmsSettings) error {
|
||||
km.writeMu.Lock()
|
||||
defer km.writeMu.Unlock()
|
||||
|
||||
km.mu.RLock()
|
||||
current, previousDefault := km.providers, km.defaultKMS
|
||||
km.mu.RUnlock()
|
||||
|
||||
build := func(name string) (KMSProvider, error) {
|
||||
config, err := kmsProviderConfig(name, s.providers[name])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
provider, err := newManagedProvider(config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create KMS provider %s: %w", name, err)
|
||||
}
|
||||
return provider, nil
|
||||
}
|
||||
providers := make(map[string]KMSProvider, len(s.providers))
|
||||
if s.defaultProvider != "" {
|
||||
provider, err := build(s.defaultProvider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
providers[s.defaultProvider] = provider
|
||||
}
|
||||
for _, name := range s.names {
|
||||
if name == s.defaultProvider {
|
||||
continue
|
||||
}
|
||||
provider, err := build(name)
|
||||
if err != nil {
|
||||
glog.Errorf("%v, keeping its previous instance if any", err)
|
||||
if previous, ok := current[name]; ok {
|
||||
providers[name] = previous
|
||||
}
|
||||
continue
|
||||
}
|
||||
providers[name] = provider
|
||||
}
|
||||
|
||||
buckets := make(map[string]string, len(s.buckets))
|
||||
for bucket, name := range s.buckets {
|
||||
if _, ok := providers[name]; !ok {
|
||||
glog.Errorf("KMS provider %s for bucket %s isn't loaded, skipping the mapping", name, bucket)
|
||||
continue
|
||||
}
|
||||
buckets[bucket] = name
|
||||
}
|
||||
|
||||
// The global provider changes in the same step, so it's never one this load has closed.
|
||||
globalKMSMutex.Lock()
|
||||
km.mu.Lock()
|
||||
km.providers, km.bucketKMS, km.defaultKMS = providers, buckets, s.defaultProvider
|
||||
km.mu.Unlock()
|
||||
var previousGlobal KMSProvider
|
||||
if km == globalKMSManager {
|
||||
previousGlobal, globalKMSProvider = globalKMSProvider, providers[s.defaultProvider]
|
||||
}
|
||||
globalKMSMutex.Unlock()
|
||||
|
||||
switch {
|
||||
case previousDefault == "" || previousDefault == s.defaultProvider:
|
||||
case s.defaultProvider == "":
|
||||
glog.Warningf("The KMS configuration lists no providers anymore, so SSE-KMS requests fail")
|
||||
default:
|
||||
glog.Warningf("The default KMS provider changes from %s to %s", previousDefault, s.defaultProvider)
|
||||
}
|
||||
for name, provider := range current {
|
||||
if providers[name] != provider {
|
||||
if err := provider.Close(); err != nil {
|
||||
glog.Errorf("Failed to close KMS provider %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if previousGlobal != nil && !containsProvider(current, previousGlobal) {
|
||||
previousGlobal.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func containsProvider(providers map[string]KMSProvider, provider KMSProvider) bool {
|
||||
for _, p := range providers {
|
||||
if p == provider {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetDefaultKMSProvider sets the default KMS provider
|
||||
func (km *KMSManager) SetDefaultKMSProvider(name string) error {
|
||||
km.mu.Lock()
|
||||
@@ -492,8 +390,6 @@ func (km *KMSManager) GetBucketKMSProvider(bucket string) string {
|
||||
|
||||
// RemoveKMSProvider removes a KMS provider
|
||||
func (km *KMSManager) RemoveKMSProvider(name string) error {
|
||||
km.writeMu.Lock()
|
||||
defer km.writeMu.Unlock()
|
||||
km.mu.Lock()
|
||||
defer km.mu.Unlock()
|
||||
|
||||
@@ -509,6 +405,7 @@ func (km *KMSManager) RemoveKMSProvider(name string) error {
|
||||
|
||||
// Remove from maps
|
||||
delete(km.providers, name)
|
||||
delete(km.configs, name)
|
||||
|
||||
// Remove from bucket associations
|
||||
for bucket, providerName := range km.bucketKMS {
|
||||
@@ -528,8 +425,6 @@ func (km *KMSManager) RemoveKMSProvider(name string) error {
|
||||
|
||||
// Close closes all KMS providers and cleans up resources
|
||||
func (km *KMSManager) Close() error {
|
||||
km.writeMu.Lock()
|
||||
defer km.writeMu.Unlock()
|
||||
km.mu.Lock()
|
||||
defer km.mu.Unlock()
|
||||
|
||||
@@ -542,6 +437,7 @@ func (km *KMSManager) Close() error {
|
||||
|
||||
// Clear all maps
|
||||
km.providers = make(map[string]KMSProvider)
|
||||
km.configs = make(map[string]*KMSConfig)
|
||||
km.bucketKMS = make(map[string]string)
|
||||
km.defaultKMS = ""
|
||||
|
||||
|
||||
+80
-23
@@ -53,28 +53,38 @@ func (loader *ConfigLoader) LoadConfigurations() error {
|
||||
}
|
||||
|
||||
func (loader *ConfigLoader) load(s *kmsSettings) error {
|
||||
// S3 wraps and unwraps data keys with the default provider alone, so it comes from this
|
||||
// config.
|
||||
if _, listed := s.providers[s.defaultProvider]; s.defaultProvider != "" && !listed {
|
||||
return fmt.Errorf("default KMS provider %s isn't listed under providers", s.defaultProvider)
|
||||
for _, name := range s.names {
|
||||
if err := loader.loadSingleKMSProvider(name, s.providers[name]); err != nil {
|
||||
glog.Errorf("Failed to load KMS provider %s: %v", name, err)
|
||||
continue
|
||||
}
|
||||
glog.V(1).Infof("Loaded KMS provider: %s", name)
|
||||
}
|
||||
if s.defaultProvider == "" && len(s.names) > 0 {
|
||||
s.defaultProvider = s.names[0]
|
||||
if len(s.names) > 1 {
|
||||
glog.Warningf("KMS default_provider isn't set, so S3 uses %s, the first provider by name. Adding a provider whose name sorts first would switch S3 to it, and objects encrypted before would be unreadable until default_provider names %s", s.defaultProvider, s.defaultProvider)
|
||||
|
||||
if s.defaultProvider != "" {
|
||||
if err := loader.manager.SetDefaultKMSProvider(s.defaultProvider); err != nil {
|
||||
return fmt.Errorf("failed to set default KMS provider: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := loader.manager.load(s); err != nil {
|
||||
return fmt.Errorf("failed to load KMS providers: %w", err)
|
||||
// Initialize global KMS provider for backwards compatibility
|
||||
if err := loader.initializeGlobalKMSProvider(s.defaultProvider); err != nil {
|
||||
glog.Warningf("Failed to initialize global KMS provider: %v", err)
|
||||
}
|
||||
|
||||
for bucket, name := range s.buckets {
|
||||
if err := loader.manager.SetBucketKMSProvider(bucket, name); err != nil {
|
||||
glog.Errorf("Failed to set KMS provider for bucket %s: %v", bucket, err)
|
||||
continue
|
||||
}
|
||||
glog.V(2).Infof("Set KMS provider for bucket %s to %s", bucket, name)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("KMS configuration loaded successfully")
|
||||
return loader.ValidateConfiguration()
|
||||
return nil
|
||||
}
|
||||
|
||||
type kmsSettings struct {
|
||||
// providers holds each provider's entry as given, parsed when it's built, so an invalid
|
||||
// one fails the load only if it's the default provider, like one that fails to build.
|
||||
providers map[string]interface{}
|
||||
names []string
|
||||
defaultProvider string
|
||||
@@ -110,10 +120,6 @@ func parseKMSSettings(kmsConfig map[string]interface{}, providerName func(string
|
||||
return nil, err
|
||||
}
|
||||
for bucket, raw := range buckets {
|
||||
if bucket == "" {
|
||||
glog.Errorf("Skipping a KMS bucket mapping with an empty bucket name")
|
||||
continue
|
||||
}
|
||||
fields, ok := raw.(map[string]interface{})
|
||||
if !ok {
|
||||
glog.Errorf("Invalid KMS configuration for bucket %s, skipping the mapping", bucket)
|
||||
@@ -201,6 +207,58 @@ func kmsProviderConfig(providerName string, raw interface{}) (*KMSConfig, error)
|
||||
}, nil
|
||||
}
|
||||
|
||||
// loadSingleKMSProvider loads a single KMS provider configuration
|
||||
func (loader *ConfigLoader) loadSingleKMSProvider(providerName string, config interface{}) error {
|
||||
kmsConfig, err := kmsProviderConfig(providerName, config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add the provider to the KMS manager
|
||||
if err := loader.manager.AddKMSProvider(providerName, kmsConfig); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Test the provider with a health check
|
||||
if provider, err := loader.manager.GetKMSProviderByName(providerName); err == nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := checkHealth(ctx, provider); err != nil {
|
||||
glog.Warningf("KMS provider %s health check failed: %v", providerName, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// initializeGlobalKMSProvider initializes the global KMS provider for backwards compatibility
|
||||
func (loader *ConfigLoader) initializeGlobalKMSProvider(defaultProviderName string) error {
|
||||
if defaultProviderName == "" {
|
||||
// If no default provider, try to use the first available provider
|
||||
providers := loader.manager.ListKMSProviders()
|
||||
if len(providers) > 0 {
|
||||
defaultProviderName = providers[0]
|
||||
}
|
||||
}
|
||||
|
||||
if defaultProviderName == "" {
|
||||
glog.V(2).Infof("No KMS providers configured, skipping global KMS initialization")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get the provider from the manager
|
||||
provider, err := loader.manager.GetKMSProviderByName(defaultProviderName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get KMS provider %s: %w", defaultProviderName, err)
|
||||
}
|
||||
|
||||
// Set as global KMS provider
|
||||
SetGlobalKMSProvider(provider)
|
||||
glog.V(1).Infof("Initialized global KMS provider: %s", defaultProviderName)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateConfiguration validates the KMS configuration
|
||||
func (loader *ConfigLoader) ValidateConfiguration() error {
|
||||
providers := loader.manager.ListKMSProviders()
|
||||
@@ -232,12 +290,8 @@ func (loader *ConfigLoader) ValidateConfiguration() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadKMSFromConfig loads KMS configuration directly from parsed JSON data. A nil section,
|
||||
// which is what a missing or null one in the JSON gives, loads as empty and drops the providers.
|
||||
// LoadKMSFromConfig loads KMS configuration directly from parsed JSON data
|
||||
func LoadKMSFromConfig(kmsConfig interface{}) error {
|
||||
if kmsConfig == nil {
|
||||
kmsConfig = map[string]interface{}{}
|
||||
}
|
||||
kmsMap, ok := kmsConfig.(map[string]interface{})
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid KMS configuration format")
|
||||
@@ -248,5 +302,8 @@ func LoadKMSFromConfig(kmsConfig interface{}) error {
|
||||
return err
|
||||
}
|
||||
loader := &ConfigLoader{manager: GetKMSManager()}
|
||||
return loader.load(settings)
|
||||
if err := loader.load(settings); err != nil {
|
||||
return err
|
||||
}
|
||||
return loader.ValidateConfiguration()
|
||||
}
|
||||
+30
-296
@@ -17,14 +17,6 @@ type closeTracker struct {
|
||||
closed bool
|
||||
}
|
||||
|
||||
func newCloseTracker() *closeTracker {
|
||||
return &closeTracker{KMSProvider: newCountingKMSProvider()}
|
||||
}
|
||||
|
||||
func (c *closeTracker) isClosed() bool {
|
||||
return c.closed
|
||||
}
|
||||
|
||||
func (c *closeTracker) Close() error {
|
||||
c.closed = true
|
||||
return nil
|
||||
@@ -46,6 +38,7 @@ func TestAddKMSProviderReplacesTheInstance(t *testing.T) {
|
||||
})
|
||||
mgr := &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
add := func() error { return mgr.AddKMSProvider("p", &KMSConfig{Provider: "replace-test"}) }
|
||||
@@ -91,6 +84,7 @@ func TestAddKMSProviderDoesNotBlockLookups(t *testing.T) {
|
||||
})
|
||||
mgr := &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
if err := mgr.AddKMSProvider("ready", &KMSConfig{Provider: "lookup-test"}); err != nil {
|
||||
@@ -120,247 +114,6 @@ func TestAddKMSProviderDoesNotBlockLookups(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultProviderComesFromTheConfig(t *testing.T) {
|
||||
created := map[string]*closeTracker{}
|
||||
RegisterProvider("pick-test", func(c util.Configuration) (KMSProvider, error) {
|
||||
p := newCloseTracker()
|
||||
created[c.GetString("name")] = p
|
||||
return p, nil
|
||||
})
|
||||
provider := func(name string) map[string]interface{} {
|
||||
return map[string]interface{}{"type": "pick-test", "name": name, "cache_enabled": false}
|
||||
}
|
||||
defer LoadKMSFromConfig(nil)
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"providers": map[string]interface{}{"pick-a": provider("pick-a")},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"providers": map[string]interface{}{"pick-c": provider("pick-c"), "pick-b": provider("pick-b")},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if GetGlobalKMS() != created["pick-b"] || GetKMSManager().GetBucketKMSProvider("any") != "pick-b" {
|
||||
t.Fatal("S3 doesn't use the first provider by name in the config it loaded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlistedDefaultProviderKeepsThePreviousProviders(t *testing.T) {
|
||||
RegisterProvider("default-test", func(util.Configuration) (KMSProvider, error) {
|
||||
return newCloseTracker(), nil
|
||||
})
|
||||
provider := map[string]interface{}{"type": "default-test", "cache_enabled": false}
|
||||
defer SetGlobalKMSProvider(nil)
|
||||
defer GetKMSManager().RemoveKMSProvider("default-old")
|
||||
defer GetKMSManager().RemoveKMSProvider("default-new")
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"providers": map[string]interface{}{"default-old": provider},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := GetGlobalKMS()
|
||||
err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"default_provider": "default-old",
|
||||
"providers": map[string]interface{}{"default-new": provider},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("a default_provider that isn't listed under providers was accepted")
|
||||
}
|
||||
if _, err := GetKMSManager().GetKMSProviderByName("default-old"); err != nil {
|
||||
t.Fatal("a reload with an unlisted default_provider dropped the previous provider")
|
||||
}
|
||||
if GetGlobalKMS() != previous {
|
||||
t.Fatal("a reload with an unlisted default_provider changed the global provider")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultProviderThatFailsKeepsTheGlobalProviderOpen(t *testing.T) {
|
||||
RegisterProvider("failing-default-test", func(c util.Configuration) (KMSProvider, error) {
|
||||
if c.GetBool("fail") {
|
||||
return nil, errors.New("bad configuration")
|
||||
}
|
||||
return newCloseTracker(), nil
|
||||
})
|
||||
provider := func(fail bool) map[string]interface{} {
|
||||
return map[string]interface{}{"type": "failing-default-test", "fail": fail, "cache_enabled": false}
|
||||
}
|
||||
defer SetGlobalKMSProvider(nil)
|
||||
defer GetKMSManager().RemoveKMSProvider("failing-a")
|
||||
defer GetKMSManager().RemoveKMSProvider("failing-b")
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"providers": map[string]interface{}{"failing-b": provider(false)},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := GetGlobalKMS().(*closeTracker)
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"providers": map[string]interface{}{"failing-a": provider(true), "failing-b": provider(false)},
|
||||
}); err == nil {
|
||||
t.Fatal("a load whose default provider fails succeeded")
|
||||
}
|
||||
if GetGlobalKMS() != previous || previous.closed {
|
||||
t.Fatal("a load whose default provider fails left S3 on a closed provider")
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnlyTheGlobalProviderFailsAReload checks that another provider that fails to load
|
||||
// keeps its previous instance, or is left out without one, while the global provider failing,
|
||||
// or a configuration that doesn't parse, changes nothing.
|
||||
func TestOnlyTheGlobalProviderFailsAReload(t *testing.T) {
|
||||
created := map[string]*closeTracker{}
|
||||
RegisterProvider("atomic-test", func(c util.Configuration) (KMSProvider, error) {
|
||||
if c.GetString("version") == "broken" {
|
||||
return nil, errors.New("bad configuration")
|
||||
}
|
||||
p := newCloseTracker()
|
||||
created[c.GetString("version")] = p
|
||||
return p, nil
|
||||
})
|
||||
provider := func(version string) map[string]interface{} {
|
||||
return map[string]interface{}{"type": "atomic-test", "version": version, "cache_enabled": false}
|
||||
}
|
||||
onBucket := map[string]interface{}{"bucket": map[string]interface{}{"provider": "atomic-b"}}
|
||||
bucketProvider := func() KMSProvider {
|
||||
p, _ := GetKMSManager().GetKMSProvider("bucket")
|
||||
return p
|
||||
}
|
||||
defer LoadKMSFromConfig(nil)
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"default_provider": "atomic-a",
|
||||
"providers": map[string]interface{}{
|
||||
"atomic-a": provider("a1"), "atomic-b": provider("b1"), "atomic-c": provider("broken"), "": provider("unnamed"),
|
||||
},
|
||||
"buckets": onBucket,
|
||||
}); err != nil {
|
||||
t.Fatalf("a provider S3 doesn't use failed the load: %v", err)
|
||||
}
|
||||
if _, err := GetKMSManager().GetKMSProviderByName("atomic-c"); err == nil {
|
||||
t.Fatal("a provider that failed to load is listed")
|
||||
}
|
||||
if _, err := GetKMSManager().GetKMSProviderByName(""); err == nil || created["unnamed"] != nil {
|
||||
t.Fatal("a provider with an empty name was loaded")
|
||||
}
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"default_provider": "atomic-a",
|
||||
"providers": map[string]interface{}{"atomic-a": provider("a2"), "atomic-b": provider("broken")},
|
||||
"buckets": onBucket,
|
||||
}); err != nil {
|
||||
t.Fatalf("a provider S3 doesn't use failed the reload: %v", err)
|
||||
}
|
||||
if GetGlobalKMS() != created["a2"] {
|
||||
t.Fatal("the reload didn't apply the provider that loaded")
|
||||
}
|
||||
if bucketProvider() != created["b1"] || created["b1"].isClosed() {
|
||||
t.Fatal("the provider that failed didn't keep its previous instance")
|
||||
}
|
||||
if !created["a1"].isClosed() {
|
||||
t.Fatal("the replaced instance wasn't closed")
|
||||
}
|
||||
|
||||
for name, cfg := range map[string]map[string]interface{}{
|
||||
"the global provider fails": {
|
||||
"default_provider": "atomic-a",
|
||||
"providers": map[string]interface{}{"atomic-a": provider("broken"), "atomic-b": provider("b3")},
|
||||
"buckets": onBucket,
|
||||
},
|
||||
"a configuration that doesn't parse": {
|
||||
"default_provider": "atomic-a",
|
||||
"providers": map[string]interface{}{"atomic-a": provider("a4")},
|
||||
"buckets": "atomic-b",
|
||||
},
|
||||
} {
|
||||
if err := LoadKMSFromConfig(cfg); err == nil {
|
||||
t.Fatalf("%s: the reload was accepted", name)
|
||||
}
|
||||
if GetGlobalKMS() != created["a2"] {
|
||||
t.Fatalf("%s: the reload changed the global provider", name)
|
||||
}
|
||||
if bucketProvider() != created["b1"] {
|
||||
t.Fatalf("%s: the reload changed the bucket's provider", name)
|
||||
}
|
||||
}
|
||||
if created["b3"] != nil || created["a4"] != nil {
|
||||
t.Fatal("a reload that failed created a provider")
|
||||
}
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"default_provider": "atomic-a",
|
||||
"providers": map[string]interface{}{"atomic-a": provider("a5")},
|
||||
"buckets": onBucket,
|
||||
}); err != nil {
|
||||
t.Fatalf("a bucket on an unlisted provider failed the reload: %v", err)
|
||||
}
|
||||
if bucketProvider() != created["a5"] {
|
||||
t.Fatal("a bucket on an unlisted provider didn't fall back to the default one")
|
||||
}
|
||||
if !created["b1"].isClosed() {
|
||||
t.Fatal("the instance of the unlisted provider wasn't closed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnInvalidEntryFailsLikeAProviderThatDoesntBuild checks that an invalid provider entry
|
||||
// fails the load only when it's the global provider, and that an invalid bucket entry is
|
||||
// skipped.
|
||||
func TestAnInvalidEntryFailsLikeAProviderThatDoesntBuild(t *testing.T) {
|
||||
RegisterProvider("entry-test", func(util.Configuration) (KMSProvider, error) {
|
||||
return newCloseTracker(), nil
|
||||
})
|
||||
valid := map[string]interface{}{"type": "entry-test", "cache_enabled": false}
|
||||
defer LoadKMSFromConfig(nil)
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"default_provider": "entry-a",
|
||||
"providers": map[string]interface{}{"entry-a": valid, "entry-b": valid},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous, _ := GetKMSManager().GetKMSProviderByName("entry-b")
|
||||
|
||||
for _, invalid := range []interface{}{"entry-test", map[string]interface{}{"cache_enabled": false}} {
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"default_provider": "entry-a",
|
||||
"providers": map[string]interface{}{"entry-a": valid, "entry-b": invalid},
|
||||
"buckets": map[string]interface{}{
|
||||
"on-b": map[string]interface{}{"provider": "entry-b"},
|
||||
"not-a-table": "entry-b",
|
||||
"not-a-string": map[string]interface{}{"provider": 1},
|
||||
"": map[string]interface{}{"provider": "entry-b"},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("an invalid entry S3 doesn't use failed the reload: %v", err)
|
||||
}
|
||||
if p, _ := GetKMSManager().GetKMSProvider("on-b"); p != previous {
|
||||
t.Fatal("a provider with an invalid entry didn't keep its previous instance")
|
||||
}
|
||||
a, _ := GetKMSManager().GetKMSProviderByName("entry-a")
|
||||
for _, bucket := range []string{"not-a-table", "not-a-string"} {
|
||||
if p, _ := GetKMSManager().GetKMSProvider(bucket); p != a {
|
||||
t.Fatalf("the invalid bucket entry %s wasn't skipped", bucket)
|
||||
}
|
||||
}
|
||||
if name := GetKMSManager().GetBucketKMSProvider(""); name != "entry-a" {
|
||||
t.Fatalf("the bucket entry without a name was mapped to %s", name)
|
||||
}
|
||||
|
||||
global := GetGlobalKMS()
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"default_provider": "entry-a",
|
||||
"providers": map[string]interface{}{"entry-a": invalid, "entry-b": valid},
|
||||
}); err == nil {
|
||||
t.Fatal("an invalid entry for the global provider was accepted")
|
||||
}
|
||||
if GetGlobalKMS() != global {
|
||||
t.Fatal("a reload with an invalid entry for the global provider changed it")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestViperConfigMatchesMixedCaseProviderNames(t *testing.T) {
|
||||
RegisterProvider("case-test", func(util.Configuration) (KMSProvider, error) {
|
||||
return newCountingKMSProvider(), nil
|
||||
@@ -380,7 +133,10 @@ provider = "MyVault"
|
||||
`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer LoadKMSFromConfig(nil)
|
||||
defer func() {
|
||||
GetKMSManager().RemoveKMSProvider("myvault")
|
||||
SetGlobalKMSProvider(nil)
|
||||
}()
|
||||
|
||||
if err := NewConfigLoader(v).LoadConfigurations(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -393,32 +149,6 @@ provider = "MyVault"
|
||||
}
|
||||
}
|
||||
|
||||
func TestReloadWithoutProvidersDropsThem(t *testing.T) {
|
||||
RegisterProvider("drop-test", func(util.Configuration) (KMSProvider, error) {
|
||||
return newCloseTracker(), nil
|
||||
})
|
||||
defer SetGlobalKMSProvider(nil)
|
||||
defer GetKMSManager().RemoveKMSProvider("drop-p")
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{
|
||||
"providers": map[string]interface{}{"drop-p": map[string]interface{}{"type": "drop-test", "cache_enabled": false}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := GetKMSManager().GetKMSProviderByName("drop-p"); err == nil {
|
||||
t.Fatal("a reload without providers kept the provider")
|
||||
}
|
||||
if GetGlobalKMS() != nil {
|
||||
t.Fatal("a reload without providers kept the global provider")
|
||||
}
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{"providers": "drop-p"}); err == nil {
|
||||
t.Fatal("providers that aren't a map were accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigKeysDifferingInCaseReadTheSameValue(t *testing.T) {
|
||||
config := map[string]interface{}{"KEYID": "upper", "KeyId": "mixed", "keyId": "lower"}
|
||||
for i := 0; i < 50; i++ {
|
||||
@@ -464,32 +194,29 @@ func TestSettingOfTheWrongTypeFailsTheProvider(t *testing.T) {
|
||||
var built []*closeTracker
|
||||
RegisterProvider("typed-test", func(c util.Configuration) (KMSProvider, error) {
|
||||
c.GetInt("size")
|
||||
p := newCloseTracker()
|
||||
p := &closeTracker{KMSProvider: newCountingKMSProvider()}
|
||||
built = append(built, p)
|
||||
return p, nil
|
||||
})
|
||||
defer LoadKMSFromConfig(nil)
|
||||
|
||||
if err := LoadKMSFromConfig(map[string]interface{}{"providers": map[string]interface{}{
|
||||
"typed": map[string]interface{}{"type": "typed-test", "size": int64(3)},
|
||||
}}); err != nil {
|
||||
t.Fatalf("an int64 setting, as TOML gives, failed the load: %v", err)
|
||||
mgr := &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
err := LoadKMSFromConfig(map[string]interface{}{"providers": map[string]interface{}{
|
||||
"typed": map[string]interface{}{"type": "typed-test", "size": "three"},
|
||||
}})
|
||||
add := func(size interface{}) error {
|
||||
return mgr.AddKMSProvider("typed", &KMSConfig{Provider: "typed-test", Config: map[string]interface{}{"size": size}})
|
||||
}
|
||||
|
||||
if err := add(int64(3)); err != nil {
|
||||
t.Fatalf("an int64 setting, as TOML gives, failed the provider: %v", err)
|
||||
}
|
||||
err := add("three")
|
||||
if err == nil || !strings.Contains(err.Error(), "size") {
|
||||
t.Fatalf("a string setting read as an int = %v, want an error naming size", err)
|
||||
}
|
||||
if len(built) != 2 {
|
||||
t.Fatalf("built %d providers, want 2", len(built))
|
||||
}
|
||||
if !built[1].isClosed() {
|
||||
if !built[len(built)-1].closed {
|
||||
t.Fatal("the provider that read a setting of the wrong type wasn't closed")
|
||||
}
|
||||
if built[0].isClosed() {
|
||||
t.Fatal("the rejected load closed the installed provider")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheSettings(t *testing.T) {
|
||||
@@ -538,6 +265,7 @@ func TestHealthCheckDoesNotBlockChanges(t *testing.T) {
|
||||
stalled := &stalledDescribe{KMSProvider: newCountingKMSProvider(), started: make(chan struct{}), release: make(chan struct{})}
|
||||
mgr := &KMSManager{
|
||||
providers: map[string]KMSProvider{"remote": stalled},
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
|
||||
@@ -572,7 +300,7 @@ func (d *describeCounter) DescribeKey(ctx context.Context, req *DescribeKeyReque
|
||||
return nil, &KMSError{Code: ErrCodeNotFoundException}
|
||||
}
|
||||
|
||||
func TestALoadChecksEachProviderOnce(t *testing.T) {
|
||||
func TestLoadingAProviderChecksOnlyThatProvider(t *testing.T) {
|
||||
var created []*describeCounter
|
||||
RegisterProvider("load-check-test", func(util.Configuration) (KMSProvider, error) {
|
||||
p := &describeCounter{KMSProvider: newCountingKMSProvider()}
|
||||
@@ -581,6 +309,7 @@ func TestALoadChecksEachProviderOnce(t *testing.T) {
|
||||
})
|
||||
loader := &ConfigLoader{manager: &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}}
|
||||
settings := &kmsSettings{providers: make(map[string]interface{}), names: []string{"a", "b", "c"}}
|
||||
@@ -608,6 +337,7 @@ func TestHealthChecksDoNotWaitForEachOther(t *testing.T) {
|
||||
b := &stalledDescribe{KMSProvider: newCountingKMSProvider(), started: make(chan struct{}), release: release}
|
||||
mgr := &KMSManager{
|
||||
providers: map[string]KMSProvider{"a": a, "b": b},
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}
|
||||
|
||||
@@ -631,9 +361,13 @@ func TestGlobalProviderWithoutADefaultIsTheFirstByName(t *testing.T) {
|
||||
RegisterProvider("first-by-name-test", func(util.Configuration) (KMSProvider, error) {
|
||||
return newCountingKMSProvider(), nil
|
||||
})
|
||||
defer LoadKMSFromConfig(nil)
|
||||
loader := &ConfigLoader{manager: GetKMSManager()}
|
||||
defer SetGlobalKMSProvider(nil)
|
||||
for i := 0; i < 20; i++ {
|
||||
loader := &ConfigLoader{manager: &KMSManager{
|
||||
providers: make(map[string]KMSProvider),
|
||||
configs: make(map[string]*KMSConfig),
|
||||
bucketKMS: make(map[string]string),
|
||||
}}
|
||||
settings := &kmsSettings{providers: make(map[string]interface{}), names: []string{"a", "b", "c"}}
|
||||
for _, name := range settings.names {
|
||||
settings.providers[name] = map[string]interface{}{"type": "first-by-name-test", "cache_enabled": false}
|
||||
|
||||
+28
-91
@@ -8,7 +8,6 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
@@ -61,21 +60,6 @@ func aliasName(alias string) string {
|
||||
return "alias/" + alias
|
||||
}
|
||||
|
||||
// keyName returns the name a key or alias ARN is stored under, as AWS KMS accepts either form.
|
||||
func keyName(keyIdentifier string) string {
|
||||
rest, ok := strings.CutPrefix(keyIdentifier, localARNPrefix)
|
||||
if !ok {
|
||||
return keyIdentifier
|
||||
}
|
||||
if keyID, ok := strings.CutPrefix(rest, "key/"); ok {
|
||||
return keyID
|
||||
}
|
||||
if strings.HasPrefix(rest, "alias/") {
|
||||
return rest
|
||||
}
|
||||
return keyIdentifier
|
||||
}
|
||||
|
||||
func newLocalKey(keyID, description string, material []byte, origin kms.KeyOrigin, aliases []string) *LocalKey {
|
||||
return &LocalKey{
|
||||
KeyID: keyID,
|
||||
@@ -246,10 +230,7 @@ func configuredKey(fields map[string]interface{}) (*LocalKey, error) {
|
||||
func aliasNames(aliases []string) ([]string, error) {
|
||||
names := make([]string, len(aliases))
|
||||
for i, alias := range aliases {
|
||||
if strings.HasPrefix(alias, localARNPrefix+"key/") {
|
||||
return nil, fmt.Errorf("aliases[%d] is a key ARN, not an alias", i)
|
||||
}
|
||||
names[i] = aliasName(keyName(alias))
|
||||
names[i] = aliasName(alias)
|
||||
if err := checkName(fmt.Sprintf("aliases[%d]", i), strings.TrimPrefix(names[i], "alias/")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -258,16 +239,12 @@ func aliasNames(aliases []string) ([]string, error) {
|
||||
}
|
||||
|
||||
func keyIDName(field, keyID string) (string, error) {
|
||||
keyID = keyName(keyID)
|
||||
if err := checkName(field, keyID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if strings.HasPrefix(keyID, "alias/") {
|
||||
return "", fmt.Errorf("%s is an alias, not a key ID", field)
|
||||
}
|
||||
if keyName(keyID) != keyID {
|
||||
return "", fmt.Errorf("%s is an ARN inside an ARN", field)
|
||||
}
|
||||
return keyID, nil
|
||||
}
|
||||
|
||||
@@ -401,7 +378,7 @@ func (p *LocalKMSProvider) GenerateDataKey(ctx context.Context, req *kms.Generat
|
||||
}
|
||||
|
||||
// Resolve the key
|
||||
key, err := p.getOrCreateKey(req.KeyID)
|
||||
key, err := p.getKey(req.KeyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -485,13 +462,8 @@ func (p *LocalKMSProvider) Decrypt(ctx context.Context, req *kms.DecryptRequest)
|
||||
}
|
||||
}
|
||||
|
||||
// A key configured by its ARN once had that ARN as its ID, and callers stored it.
|
||||
keyID := key.KeyID
|
||||
if keyName(metadata.KeyID) == key.KeyID {
|
||||
keyID = metadata.KeyID
|
||||
}
|
||||
return &kms.DecryptResponse{
|
||||
KeyID: keyID,
|
||||
KeyID: key.KeyID,
|
||||
Plaintext: dataKey,
|
||||
}, nil
|
||||
}
|
||||
@@ -535,17 +507,12 @@ func (p *LocalKMSProvider) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// getKey retrieves a key by ID, alias or ARN.
|
||||
// getKey retrieves a key by ID or alias, creating it on-demand if it doesn't exist
|
||||
func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) {
|
||||
name := keyName(keyIdentifier)
|
||||
// A key ARN names a key ID, never an alias its ID happens to spell.
|
||||
namedKey := func(key *LocalKey) bool {
|
||||
return !strings.HasPrefix(keyIdentifier, localARNPrefix+"key/") || key.KeyID == name
|
||||
}
|
||||
p.mu.RLock()
|
||||
|
||||
// Try direct lookup first. An ARN with an empty key ID names "", which is no key.
|
||||
if key, exists := p.keys[name]; exists && namedKey(key) {
|
||||
// Try direct lookup first
|
||||
if key, exists := p.keys[keyIdentifier]; exists {
|
||||
p.mu.RUnlock()
|
||||
return key, nil
|
||||
}
|
||||
@@ -563,6 +530,20 @@ func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) {
|
||||
|
||||
p.mu.RUnlock()
|
||||
|
||||
// Key doesn't exist - create on-demand if enabled and key identifier is reasonable
|
||||
if keyIdentifier != "" && p.enableOnDemandCreate && p.isReasonableKeyIdentifier(keyIdentifier) {
|
||||
glog.V(1).Infof("Creating on-demand local KMS key: %s", keyIdentifier)
|
||||
key, err := p.createOnDemandKey(keyIdentifier)
|
||||
if err != nil {
|
||||
return nil, &kms.KMSError{
|
||||
Code: kms.ErrCodeKMSInternalFailure,
|
||||
Message: fmt.Sprintf("Failed to create on-demand key %s: %v", keyIdentifier, err),
|
||||
KeyID: keyIdentifier,
|
||||
}
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
return nil, &kms.KMSError{
|
||||
Code: kms.ErrCodeNotFoundException,
|
||||
Message: fmt.Sprintf("Key not found: %s", keyIdentifier),
|
||||
@@ -570,31 +551,6 @@ func (p *LocalKMSProvider) getKey(keyIdentifier string) (*LocalKey, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// getOrCreateKey is getKey that creates a missing key on demand if enabled. Only new data
|
||||
// keys create keys, as no other request can succeed with a key that didn't exist before it.
|
||||
func (p *LocalKMSProvider) getOrCreateKey(keyIdentifier string) (*LocalKey, error) {
|
||||
key, err := p.getKey(keyIdentifier)
|
||||
name := keyName(keyIdentifier)
|
||||
// A key ARN spelling an alias names no key, so it can't create one either.
|
||||
keyARNOfAlias := strings.HasPrefix(keyIdentifier, localARNPrefix+"key/") && strings.HasPrefix(name, "alias/")
|
||||
var kmsErr *kms.KMSError
|
||||
if !errors.As(err, &kmsErr) || kmsErr.Code != kms.ErrCodeNotFoundException ||
|
||||
!p.enableOnDemandCreate || keyARNOfAlias || !p.isReasonableKeyIdentifier(name) {
|
||||
return key, err
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Creating on-demand local KMS key: %s", name)
|
||||
key, err = p.createOnDemandKey(name)
|
||||
if err != nil {
|
||||
return nil, &kms.KMSError{
|
||||
Code: kms.ErrCodeKMSInternalFailure,
|
||||
Message: fmt.Sprintf("Failed to create on-demand key %s: %v", name, err),
|
||||
KeyID: name,
|
||||
}
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// isReasonableKeyIdentifier determines if a key identifier is reasonable for on-demand creation
|
||||
func (p *LocalKMSProvider) isReasonableKeyIdentifier(keyIdentifier string) bool {
|
||||
// Basic validation: reasonable length and character set
|
||||
@@ -768,10 +724,6 @@ func (p *LocalKMSProvider) CreateKey(description string, aliases []string) (*Loc
|
||||
|
||||
// CreateKeyWithID creates a key with a specific keyID, refusing one that's already taken.
|
||||
func (p *LocalKMSProvider) CreateKeyWithID(keyID, description string) (*LocalKey, error) {
|
||||
keyID, err := keyIDName("keyID", keyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyMaterial, err := randomKeyMaterial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -786,38 +738,23 @@ func (p *LocalKMSProvider) addKey(key *LocalKey) (*LocalKey, error) {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// createOnDemandKey creates a key for a name no key has yet. An alias gets a key with a
|
||||
// generated ID, as it would in AWS, rather than one whose ID is the alias.
|
||||
func (p *LocalKMSProvider) createOnDemandKey(name string) (*LocalKey, error) {
|
||||
keyID, aliases := name, []string{}
|
||||
if strings.HasPrefix(name, "alias/") {
|
||||
var err error
|
||||
if keyID, err = generateKeyID(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aliases = []string{name}
|
||||
}
|
||||
// createOnDemandKey returns the key already stored under keyID rather than replacing it, as
|
||||
// two on-demand requests for a new key can race and the first may have wrapped a data key
|
||||
// already.
|
||||
func (p *LocalKMSProvider) createOnDemandKey(keyID string) (*LocalKey, error) {
|
||||
keyMaterial, err := randomKeyMaterial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.storeKey(name, newLocalKey(keyID, fmt.Sprintf("Auto-created local KMS key: %s", name), keyMaterial, kms.KeyOriginLocal, aliases))
|
||||
}
|
||||
key := newLocalKey(keyID, fmt.Sprintf("Auto-created local KMS key: %s", keyID), keyMaterial, kms.KeyOriginLocal, []string{})
|
||||
|
||||
// storeKey returns the key already stored under name rather than replacing it, as two
|
||||
// on-demand requests for a new name can race and the first may have wrapped a data key
|
||||
// already.
|
||||
func (p *LocalKMSProvider) storeKey(name string, key *LocalKey) (*LocalKey, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if existing := p.keys[name]; existing != nil {
|
||||
kms.ClearSensitiveData(key.KeyMaterial)
|
||||
if existing := p.keys[keyID]; existing != nil {
|
||||
kms.ClearSensitiveData(keyMaterial)
|
||||
return existing, nil
|
||||
}
|
||||
for _, n := range append([]string{key.KeyID}, key.Aliases...) {
|
||||
p.keys[n] = key
|
||||
}
|
||||
p.keys[keyID] = key
|
||||
return key, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -165,25 +165,6 @@ key_material = "` + keyA + `"
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupsCreateNoKeys(t *testing.T) {
|
||||
lost := wrap(t, newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`)), "lost-key")
|
||||
p := newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`)).(*LocalKMSProvider)
|
||||
before := len(p.keys)
|
||||
|
||||
ctx := context.Background()
|
||||
_, decryptErr := p.Decrypt(ctx, &kms.DecryptRequest{CiphertextBlob: lost.CiphertextBlob, EncryptionContext: testContext})
|
||||
_, describeErr := p.DescribeKey(ctx, &kms.DescribeKeyRequest{KeyID: "unknown"})
|
||||
_, keyIDErr := p.GetKeyID(ctx, "unknown")
|
||||
for name, err := range map[string]error{"Decrypt": decryptErr, "DescribeKey": describeErr, "GetKeyID": keyIDErr} {
|
||||
if !hasCode(err, kms.ErrCodeNotFoundException) {
|
||||
t.Errorf("%s of an unknown key = %v, want NotFoundException", name, err)
|
||||
}
|
||||
}
|
||||
if n := len(p.keys); n != before {
|
||||
t.Errorf("lookups of unknown keys added %d keys", n-before)
|
||||
}
|
||||
}
|
||||
|
||||
type plainConfig struct{}
|
||||
|
||||
func (plainConfig) GetString(string) string { return "" }
|
||||
@@ -261,44 +242,6 @@ func TestConfiguredAWSS3AliasServesRequestsNamingNoKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyARNsResolve(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "customer-a", "key_material": "KEY_A", "aliases": ["a"]}]}`))
|
||||
desc, err := p.DescribeKey(context.Background(), &kms.DescribeKeyRequest{KeyID: "customer-a"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, keyID := range []string{desc.ARN, "arn:aws:kms:local:000000000000:alias/a"} {
|
||||
if resp := wrap(t, p, keyID); resp.KeyID != "customer-a" {
|
||||
t.Errorf("GenerateDataKey(%q) used key %q, want customer-a", keyID, resp.KeyID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeysConfiguredAsARNs(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "arn:aws:kms:local:000000000000:key/a", "key_material": "KEY_A",
|
||||
"aliases": ["arn:aws:kms:local:000000000000:alias/aws/s3"]}]}`))
|
||||
|
||||
for _, keyID := range []string{"", "a", "alias/aws/s3"} {
|
||||
resp := wrap(t, p, keyID)
|
||||
if resp.KeyID != "a" {
|
||||
t.Fatalf("GenerateDataKey(%q) used key %q, want a", keyID, resp.KeyID)
|
||||
}
|
||||
unwrap(t, p, resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyKeyARNNamesNoKey(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": ["aws/s3"]}]}`))
|
||||
_, err := p.GenerateDataKey(context.Background(), &kms.GenerateDataKeyRequest{
|
||||
KeyID: "arn:aws:kms:local:000000000000:key/",
|
||||
KeySpec: kms.KeySpecAES256,
|
||||
})
|
||||
if !hasCode(err, kms.ErrCodeNotFoundException) {
|
||||
t.Fatalf("GenerateDataKey of an ARN with no key ID = %v, want NotFoundException", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClosedKeyWrapsNothing(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "a", "key_material": "KEY_A"}]}`)).(*LocalKMSProvider)
|
||||
key, err := p.getKey("a")
|
||||
@@ -337,8 +280,6 @@ func TestInvalidKeyConfig(t *testing.T) {
|
||||
"empty keys": `{"keys": []}`,
|
||||
"material as key_id": `{"keys": [{"key_id": "KEY_A"}]}`,
|
||||
"material as key_id, newline": `{"keys": [{"key_id": "KEY_A\n", "key_material": "KEY_B"}]}`,
|
||||
"key_id an empty ARN": `{"keys": [{"key_id": "arn:aws:kms:local:000000000000:key/", "key_material": "KEY_A"}]}`,
|
||||
"alias a key ARN": `{"keys": [{"key_id": "a", "key_material": "KEY_A", "aliases": ["arn:aws:kms:local:000000000000:key/b"]}]}`,
|
||||
"material as key_id, twice": `{"keys": [{"key_id": "KEY_A", "key_material": "KEY_B"}, {"key_id": "KEY_A", "key_material": "KEY_B"}]}`,
|
||||
"material as alias, twice": `{"keys": [{"key_id": "a", "key_material": "KEY_B", "aliases": ["KEY_A", "KEY_A"]}]}`,
|
||||
"material as alias key_id": `{"keys": [{"key_id": "alias/KEY_A", "key_material": "KEY_B"}]}`,
|
||||
@@ -414,25 +355,9 @@ func TestOnDemandKeyIsNotReplaced(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandAliasGetsAGeneratedKeyID(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`))
|
||||
for created, other := range map[string]string{
|
||||
"alias/bucket": "arn:aws:kms:local:000000000000:alias/bucket",
|
||||
"arn:aws:kms:local:000000000000:alias/bucket-arn": "alias/bucket-arn",
|
||||
} {
|
||||
resp := wrap(t, p, created)
|
||||
if strings.Contains(resp.KeyID, "bucket") {
|
||||
t.Fatalf("%s created a key whose ID is taken from the alias: %s", created, resp.KeyID)
|
||||
}
|
||||
if got := wrap(t, p, other).KeyID; got != resp.KeyID {
|
||||
t.Fatalf("%s names %s, want the key %s created, %s", other, got, created, resp.KeyID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateKeyAliases(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{}`)).(*LocalKMSProvider)
|
||||
created, err := p.CreateKey("test", []string{"arn:aws:kms:local:000000000000:alias/x"})
|
||||
created, err := p.CreateKey("test", []string{"x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -445,76 +370,3 @@ func TestCreateKeyAliases(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateKeyWithIDTakesAnARN(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{}`)).(*LocalKMSProvider)
|
||||
arn := "arn:aws:kms:local:000000000000:key/customer-a"
|
||||
if _, err := p.CreateKeyWithID(arn, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, keyID := range []string{arn, "customer-a"} {
|
||||
if got, err := p.GetKeyID(context.Background(), keyID); err != nil || got != "customer-a" {
|
||||
t.Errorf("GetKeyID(%q) = %q, %v, want customer-a", keyID, got, err)
|
||||
}
|
||||
}
|
||||
if _, err := p.CreateKeyWithID(arn[:strings.LastIndex(arn, "/")+1]+arn, "test"); err == nil {
|
||||
t.Error("CreateKeyWithID took an ARN of an ARN, which no request can name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyARNNamesNoAlias(t *testing.T) {
|
||||
for _, cfg := range []string{
|
||||
`{"keys": [{"key_id": "customer-a", "key_material": "KEY_A", "aliases": ["a"]}]}`,
|
||||
`{"enableOnDemandCreate": true}`,
|
||||
} {
|
||||
p := newProvider(t, jsonConfig(t, cfg)).(*LocalKMSProvider)
|
||||
before := len(p.keys)
|
||||
_, err := p.GenerateDataKey(context.Background(), &kms.GenerateDataKeyRequest{
|
||||
KeyID: "arn:aws:kms:local:000000000000:key/alias/a",
|
||||
KeySpec: kms.KeySpecAES256,
|
||||
})
|
||||
if !hasCode(err, kms.ErrCodeNotFoundException) {
|
||||
t.Fatalf("%s: GenerateDataKey of a key ARN spelling an alias = %v, want NotFoundException", cfg, err)
|
||||
}
|
||||
if len(p.keys) != before {
|
||||
t.Fatalf("%s: a key ARN spelling an alias created a key", cfg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnDemandKeyByARN(t *testing.T) {
|
||||
p := newProvider(t, jsonConfig(t, `{"enableOnDemandCreate": true}`))
|
||||
resp := wrap(t, p, "arn:aws:kms:local:000000000000:key/bucket-key")
|
||||
if resp.KeyID != "bucket-key" {
|
||||
t.Fatalf("on-demand key from an ARN has ID %q, want bucket-key", resp.KeyID)
|
||||
}
|
||||
if again := wrap(t, p, "bucket-key"); again.KeyID != "bucket-key" {
|
||||
t.Fatalf("GenerateDataKey(bucket-key) used key %q", again.KeyID)
|
||||
}
|
||||
unwrap(t, p, resp)
|
||||
}
|
||||
|
||||
func TestDecryptKeepsAKeyARNTheCiphertextNames(t *testing.T) {
|
||||
arn := "arn:aws:kms:local:000000000000:key/a"
|
||||
material, err := decodeKeyMaterial(keyA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyKey := newLocalKey(arn, "", material, kms.KeyOriginExternal, nil)
|
||||
legacy := &LocalKMSProvider{keys: map[string]*LocalKey{arn: legacyKey}}
|
||||
legacyBlob, err := legacy.encryptDataKey(make([]byte, 32), legacyKey, testContext)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
p := newProvider(t, jsonConfig(t, `{"keys": [{"key_id": "`+arn+`", "key_material": "KEY_A"}]}`))
|
||||
for want, blob := range map[string][]byte{arn: legacyBlob, "a": wrap(t, p, arn).CiphertextBlob} {
|
||||
resp, err := p.Decrypt(context.Background(), &kms.DecryptRequest{CiphertextBlob: blob, EncryptionContext: testContext})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.KeyID != want {
|
||||
t.Errorf("Decrypt returned key %q, want %q", resp.KeyID, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -417,20 +417,16 @@ func (mc *MetaCache) DiscardDirectoryBuilds(resetFn func()) {
|
||||
// UpdateEntry stores a local write against the entry. versionTsNs is the
|
||||
// filer log position the write restates — a section refresh listed before it
|
||||
// must not roll the content back — or zero when no position describes it,
|
||||
// which marks the content unversioned. When the store refuses the write, the
|
||||
// listing of the entry's directory is dropped (see dropListingOfRefusedUpdate).
|
||||
// which marks the content unversioned.
|
||||
func (mc *MetaCache) UpdateEntry(ctx context.Context, entry *filer.Entry, versionTsNs int64) error {
|
||||
mc.Lock()
|
||||
err := mc.localStore.UpdateEntry(ctx, entry)
|
||||
if err == nil {
|
||||
mc.setEntryVersionLocked(ctx, entry.FullPath, versionTsNs)
|
||||
mc.noteHardLinkVersionLocked(ctx, entry.HardLinkId, versionTsNs)
|
||||
defer mc.Unlock()
|
||||
if err := mc.localStore.UpdateEntry(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
mc.Unlock()
|
||||
if err != nil {
|
||||
mc.dropListingOfRefusedUpdate(entry.FullPath)
|
||||
}
|
||||
return err
|
||||
mc.setEntryVersionLocked(ctx, entry.FullPath, versionTsNs)
|
||||
mc.noteHardLinkVersionLocked(ctx, entry.HardLinkId, versionTsNs)
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateEntryChecked is UpdateEntry gated under the cache lock: when the
|
||||
@@ -439,33 +435,17 @@ func (mc *MetaCache) UpdateEntry(ctx context.Context, entry *filer.Entry, versio
|
||||
// write is skipped instead of restoring old contents or a removed name.
|
||||
func (mc *MetaCache) UpdateEntryChecked(ctx context.Context, entry *filer.Entry, versionTsNs int64) error {
|
||||
mc.Lock()
|
||||
defer mc.Unlock()
|
||||
if mc.entryVersionBlocksLocked(ctx, entry.FullPath, versionTsNs, false) ||
|
||||
mc.hardLinkVersionFloorLocked(ctx, entry.HardLinkId) > versionTsNs {
|
||||
mc.Unlock()
|
||||
return nil
|
||||
}
|
||||
err := mc.localStore.UpdateEntry(ctx, entry)
|
||||
if err == nil {
|
||||
mc.setEntryVersionLocked(ctx, entry.FullPath, versionTsNs)
|
||||
mc.noteHardLinkVersionLocked(ctx, entry.HardLinkId, versionTsNs)
|
||||
}
|
||||
mc.Unlock()
|
||||
if err != nil {
|
||||
mc.dropListingOfRefusedUpdate(entry.FullPath)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// dropListingOfRefusedUpdate answers an update the local store could not
|
||||
// take, as when the cache disk is full: the store still holds the entry as it
|
||||
// was, so the listing of its directory is dropped and read from the filer
|
||||
// again, as dropListingsOf does for an event. It runs after the cache lock is
|
||||
// released, like dropListingsOf.
|
||||
func (mc *MetaCache) dropListingOfRefusedUpdate(path util.FullPath) {
|
||||
if mc.dropListingFn != nil {
|
||||
dir, _ := path.DirAndName()
|
||||
mc.dropListingFn(util.FullPath(dir))
|
||||
if err := mc.localStore.UpdateEntry(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
mc.setEntryVersionLocked(ctx, entry.FullPath, versionTsNs)
|
||||
mc.noteHardLinkVersionLocked(ctx, entry.HardLinkId, versionTsNs)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TouchDirMtimeCtime updates the mtime and ctime of a directory entry
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package meta_cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// An update the local store refuses leaves the entry as it was in the store,
|
||||
// so the listing of its directory is dropped and read from the filer again.
|
||||
// The mount refreshes hard-link siblings this way; one whose refresh a full
|
||||
// cache disk refused went on showing the old link count. An update the store
|
||||
// takes, or one the version gate skips, keeps the listing.
|
||||
func TestRefusedUpdateDropsTheListingOfItsDirectory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for name, update := range map[string]func(mc *MetaCache, entry *filer.Entry, versionTsNs int64) error{
|
||||
"UpdateEntry": func(mc *MetaCache, entry *filer.Entry, versionTsNs int64) error {
|
||||
return mc.UpdateEntry(ctx, entry, versionTsNs)
|
||||
},
|
||||
"UpdateEntryChecked": func(mc *MetaCache, entry *filer.Entry, versionTsNs int64) error {
|
||||
return mc.UpdateEntryChecked(ctx, entry, versionTsNs)
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
mc, store, dropped, _ := newFullDiskMetaCache(t, "/", "/d")
|
||||
defer mc.Shutdown()
|
||||
entry := &filer.Entry{
|
||||
FullPath: "/d/f",
|
||||
Attr: filer.Attr{Mode: 0o644, Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0)},
|
||||
HardLinkCounter: 2,
|
||||
}
|
||||
if err := mc.InsertEntry(ctx, entry, 100); err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
|
||||
entry.HardLinkCounter = 3
|
||||
if err := update(mc, entry, 200); err != nil {
|
||||
t.Fatalf("update with room on the disk: %v", err)
|
||||
}
|
||||
store.full.Store(true)
|
||||
if name == "UpdateEntryChecked" {
|
||||
if err := update(mc, entry, 150); err != nil {
|
||||
t.Fatalf("an update the version gate skips failed: %v", err)
|
||||
}
|
||||
}
|
||||
if got := dropped(); len(got) != 0 {
|
||||
t.Fatalf("updates the store took or skipped dropped the listings of %v", got)
|
||||
}
|
||||
|
||||
entry.HardLinkCounter = 4
|
||||
if err := update(mc, entry, 300); err == nil {
|
||||
t.Fatal("an update on a full disk succeeded")
|
||||
}
|
||||
if got := dropped(); !slices.Equal(got, []util.FullPath{"/d"}) {
|
||||
t.Fatalf("dropped the listings of %v, want [/d]", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -11,27 +11,14 @@ import (
|
||||
|
||||
const wakeupTestChunkSize = 2 * 1024 * 1024
|
||||
|
||||
// parkedUploads returns the goroutine ids of the uploads waiting on
|
||||
// readerCountCond. The wait keeps no state to look at, so the goroutines'
|
||||
// stack frames are the witness.
|
||||
func parkedUploads() map[string]bool {
|
||||
// parkedUploads counts the uploads waiting on readerCountCond. The wait keeps
|
||||
// no state to look at, so the goroutines' stack frames are the witness.
|
||||
func parkedUploads() int {
|
||||
buf := make([]byte, 1<<20)
|
||||
buf = buf[:runtime.Stack(buf, true)]
|
||||
parked := make(map[string]bool)
|
||||
parked := 0
|
||||
for _, stack := range strings.Split(string(buf), "\n\n") {
|
||||
if strings.Contains(stack, "(*UploadPipeline).moveToSealed") && strings.Contains(stack, "sync.(*Cond).Wait") {
|
||||
parked[strings.Fields(stack)[1]] = true
|
||||
}
|
||||
}
|
||||
return parked
|
||||
}
|
||||
|
||||
// parkedSince counts the uploads waiting on readerCountCond that were not
|
||||
// waiting in before.
|
||||
func parkedSince(before map[string]bool) int {
|
||||
parked := 0
|
||||
for id := range parkedUploads() {
|
||||
if !before[id] {
|
||||
parked++
|
||||
}
|
||||
}
|
||||
@@ -40,8 +27,7 @@ func parkedSince(before map[string]bool) int {
|
||||
|
||||
// parkUploads seals a gated chunk at each index while a read holds them, lets
|
||||
// every upload finish, and returns once each of them waits on the read.
|
||||
// Uploads that an earlier test left waiting are counted out, even when they
|
||||
// go on in the meantime.
|
||||
// Uploads that an earlier test left waiting are counted out.
|
||||
func parkUploads(t *testing.T, up *UploadPipeline, indexes ...LogicChunkIndex) []*gatedChunk {
|
||||
t.Helper()
|
||||
before := parkedUploads()
|
||||
@@ -57,7 +43,7 @@ func parkUploads(t *testing.T, up *UploadPipeline, indexes ...LogicChunkIndex) [
|
||||
<-c.saved
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for parkedSince(before) < len(indexes) {
|
||||
for parkedUploads() < before+len(indexes) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("the %d uploads never waited on the read", len(indexes))
|
||||
}
|
||||
|
||||
@@ -41,13 +41,7 @@ func (wfs *WFS) Lseek(cancel <-chan struct{}, in *fuse.LseekIn, out *fuse.LseekO
|
||||
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("Lseek", fh.fh, util.SharedLock)
|
||||
defer fh.wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
|
||||
|
||||
// Upload workers append chunks under the entry lock.
|
||||
entry := fh.GetEntry()
|
||||
entry.RLock()
|
||||
fileSize := int64(filer.FileSize(entry.Entry))
|
||||
// Inline content and an uncached remote file's data are not in the chunk group.
|
||||
dataOutsideChunks := len(entry.Entry.GetContent()) > 0 || entry.Entry.IsInRemoteOnly()
|
||||
entry.RUnlock()
|
||||
fileSize := int64(filer.FileSize(fh.GetEntry().GetEntry()))
|
||||
offset := max(int64(in.Offset), 0)
|
||||
|
||||
glog.V(4).Infof(
|
||||
@@ -62,17 +56,6 @@ func (wfs *WFS) Lseek(cancel <-chan struct{}, in *fuse.LseekIn, out *fuse.LseekO
|
||||
return ENXIO
|
||||
}
|
||||
|
||||
// Pending uploads are not in the chunk group either; report one data
|
||||
// range up to the end of the file, as lseek(2) allows.
|
||||
if dataOutsideChunks || fh.dirtyPages.HasPendingUploads() {
|
||||
if in.Whence == SEEK_DATA {
|
||||
out.Offset = uint64(offset)
|
||||
} else {
|
||||
out.Offset = uint64(fileSize)
|
||||
}
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
// Create a context that will be cancelled when the cancel channel receives a signal
|
||||
ctx, cancelFunc := context.WithCancel(context.Background())
|
||||
defer cancelFunc() // Ensure cleanup
|
||||
|
||||
@@ -32,90 +32,3 @@ func TestLseekReturnsENXIOWhenNoDataFollowsOffset(t *testing.T) {
|
||||
t.Fatalf("Lseek(SEEK_DATA) status = %v, want ENXIO", status)
|
||||
}
|
||||
}
|
||||
|
||||
func lseek(wfs *WFS, fh *FileHandle, offset uint64, whence uint32) (uint64, fuse.Status) {
|
||||
var out fuse.LseekOut
|
||||
status := wfs.Lseek(nil, &fuse.LseekIn{Fh: uint64(fh.fh), Offset: offset, Whence: whence}, &out)
|
||||
return out.Offset, status
|
||||
}
|
||||
|
||||
// Data that is not in the file's chunks yet, or is never there, is still
|
||||
// data: writes not uploaded yet, inline content, and the data of a remote
|
||||
// file that is not cached. SEEK_DATA finds it at the offset, and SEEK_HOLE
|
||||
// finds no hole before the end of the file.
|
||||
func TestLseekFindsDataOutsideTheChunks(t *testing.T) {
|
||||
for name, setup := range map[string]func(t *testing.T, wfs *WFS, fh *FileHandle){
|
||||
"buffered write": func(t *testing.T, wfs *WFS, fh *FileHandle) {
|
||||
t.Cleanup(fh.dirtyPages.Destroy)
|
||||
if _, status := wfs.Write(nil, &fuse.WriteIn{Fh: uint64(fh.fh), Size: 100}, make([]byte, 100)); status != fuse.OK {
|
||||
t.Fatalf("write: %v", status)
|
||||
}
|
||||
},
|
||||
"inline content": func(t *testing.T, wfs *WFS, fh *FileHandle) {
|
||||
fh.SetEntry(&filer_pb.Entry{
|
||||
Name: "file.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 100, Inode: fh.inode},
|
||||
Content: make([]byte, 100),
|
||||
})
|
||||
},
|
||||
"remote data": func(t *testing.T, wfs *WFS, fh *FileHandle) {
|
||||
fh.SetEntry(&filer_pb.Entry{
|
||||
Name: "file.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Mtime: 1, Inode: fh.inode},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 100, RemoteMtime: 2},
|
||||
})
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
wfs, fh := newOpenFileHandle(t, 0)
|
||||
setup(t, wfs, fh)
|
||||
|
||||
if got, status := lseek(wfs, fh, 10, SEEK_DATA); status != fuse.OK || got != 10 {
|
||||
t.Errorf("SEEK_DATA from 10 = %d, %v; want 10, OK", got, status)
|
||||
}
|
||||
if got, status := lseek(wfs, fh, 10, SEEK_HOLE); status != fuse.OK || got != 100 {
|
||||
t.Errorf("SEEK_HOLE from 10 = %d, %v; want 100, OK", got, status)
|
||||
}
|
||||
if _, status := lseek(wfs, fh, 100, SEEK_DATA); status != ENXIO {
|
||||
t.Errorf("SEEK_DATA from the end = %v, want ENXIO", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLseekFindsTheHoleInACachedRemoteFile(t *testing.T) {
|
||||
wfs, fh := newOpenFileHandle(t, 0)
|
||||
fh.SetEntry(&filer_pb.Entry{
|
||||
Name: "file.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 100, Mtime: 2, Inode: fh.inode},
|
||||
Chunks: []*filer_pb.FileChunk{{FileId: "data", Offset: 0, Size: 10}},
|
||||
RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 100, RemoteMtime: 1},
|
||||
})
|
||||
|
||||
if got, status := lseek(wfs, fh, 0, SEEK_HOLE); status != fuse.OK || got != 10 {
|
||||
t.Errorf("SEEK_HOLE from 0 = %d, %v; want 10, OK", got, status)
|
||||
}
|
||||
}
|
||||
|
||||
// Upload workers append chunks to the entry while lseek reads the size.
|
||||
func TestLseekReadsTheSizeUnderTheEntryLock(t *testing.T) {
|
||||
wfs, fh := newOpenFileHandle(t, 0)
|
||||
stop := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for i := int64(0); ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
fh.GetEntry().AppendChunks([]*filer_pb.FileChunk{{FileId: "data", Offset: i * 10, Size: 10}})
|
||||
}
|
||||
}()
|
||||
for i := 0; i < 200; i++ {
|
||||
lseek(wfs, fh, 0, SEEK_HOLE)
|
||||
}
|
||||
close(stop)
|
||||
<-done
|
||||
}
|
||||
@@ -133,12 +133,10 @@ func (wfs *WFS) checkQuotaOnce() {
|
||||
glog.V(4).Infof("read quota usage: %+v", resp)
|
||||
|
||||
// Update the stats cache with latest filer data
|
||||
wfs.stats.Lock()
|
||||
wfs.stats.UsedSize = resp.UsedSize
|
||||
wfs.stats.TotalSize = resp.TotalSize
|
||||
wfs.stats.LogicalUsedSize = resp.LogicalUsedSize
|
||||
wfs.stats.LogicalTotalSize = resp.LogicalTotalSize
|
||||
wfs.stats.Unlock()
|
||||
|
||||
// Reset uncommitted counter since we now have fresh data from filer
|
||||
wfs.ResetUncommittedBytes()
|
||||
|
||||
+34
-75
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
@@ -14,16 +13,9 @@ import (
|
||||
|
||||
const blockSize = 512
|
||||
|
||||
// statsRefreshInterval is how old the stats may be before StatFs asks the
|
||||
// filer for new ones.
|
||||
const statsRefreshInterval = 20 * time.Second
|
||||
|
||||
type statsCache struct {
|
||||
sync.Mutex
|
||||
filer_pb.StatisticsResponse
|
||||
lastChecked int64 // unix time in seconds the last refresh started
|
||||
refreshed bool // a refresh has finished, answered or not
|
||||
refreshing chan struct{} // closed when the refresh in flight finishes; nil if none
|
||||
lastChecked int64 // unix time in seconds
|
||||
}
|
||||
|
||||
// diskSizes reports the sizes df and the quota work from. By default that is
|
||||
@@ -31,8 +23,6 @@ type statsCache struct {
|
||||
// EC shard. Under -df.logical it is the data itself, with the free space
|
||||
// converted to how much more of it the mount's replication setting allows.
|
||||
func (wfs *WFS) diskSizes() (totalSize, usedSize uint64) {
|
||||
wfs.stats.Lock()
|
||||
defer wfs.stats.Unlock()
|
||||
// a filer older than the logical sizes sends zeros, so keep reporting the
|
||||
// raw ones rather than an empty filesystem
|
||||
if wfs.option.LogicalDiskUsage && wfs.stats.LogicalTotalSize > 0 {
|
||||
@@ -41,77 +31,46 @@ func (wfs *WFS) diskSizes() (totalSize, usedSize uint64) {
|
||||
return wfs.stats.TotalSize, wfs.stats.UsedSize
|
||||
}
|
||||
|
||||
// refreshStats starts a refresh of the stats from the filer when they are
|
||||
// older than statsRefreshInterval and no refresh is in flight. It returns a
|
||||
// channel to wait on until the first refresh has finished, and nil after.
|
||||
func (wfs *WFS) refreshStats() <-chan struct{} {
|
||||
wfs.stats.Lock()
|
||||
defer wfs.stats.Unlock()
|
||||
now := time.Now().Unix()
|
||||
if wfs.stats.refreshing == nil && wfs.stats.lastChecked < now-int64(statsRefreshInterval/time.Second) {
|
||||
wfs.stats.lastChecked = now
|
||||
wfs.stats.refreshing = make(chan struct{})
|
||||
go wfs.fetchStats(wfs.stats.refreshing)
|
||||
}
|
||||
if wfs.stats.refreshed {
|
||||
return nil
|
||||
}
|
||||
return wfs.stats.refreshing
|
||||
}
|
||||
|
||||
// fetchStats asks the filer for the stats and closes done when it is through.
|
||||
// When the filer does not answer, the last known stats stay.
|
||||
func (wfs *WFS) fetchStats(done chan struct{}) {
|
||||
request := &filer_pb.StatisticsRequest{
|
||||
Collection: wfs.option.Collection,
|
||||
Replication: wfs.option.Replication,
|
||||
Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
|
||||
DiskType: string(wfs.option.DiskType),
|
||||
}
|
||||
var resp *filer_pb.StatisticsResponse
|
||||
err := wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
|
||||
glog.V(4).Infof("reading filer stats: %+v", request)
|
||||
var err error
|
||||
resp, err = client.Statistics(ctx, request)
|
||||
return err
|
||||
})
|
||||
|
||||
wfs.stats.Lock()
|
||||
if err == nil {
|
||||
glog.V(4).Infof("read filer stats: %+v", resp)
|
||||
wfs.stats.TotalSize = resp.TotalSize
|
||||
wfs.stats.UsedSize = resp.UsedSize
|
||||
wfs.stats.LogicalTotalSize = resp.LogicalTotalSize
|
||||
wfs.stats.LogicalUsedSize = resp.LogicalUsedSize
|
||||
wfs.stats.FileCount = resp.FileCount
|
||||
} else {
|
||||
// the last known sizes beat the empty filesystem a bare return reports
|
||||
glog.V(0).Infof("reading filer stats %v: %v", request, err)
|
||||
}
|
||||
wfs.stats.refreshed = true
|
||||
wfs.stats.refreshing = nil
|
||||
wfs.stats.Unlock()
|
||||
close(done)
|
||||
}
|
||||
|
||||
func (wfs *WFS) StatFs(cancel <-chan struct{}, in *fuse.InHeader, out *fuse.StatfsOut) (code fuse.Status) {
|
||||
|
||||
// Answer from the stats at hand and refresh them in the background, so a
|
||||
// slow filer does not hold statfs: a node agent that probes the mount with
|
||||
// statfs would take the mount for hung. Only the first statfs waits, for
|
||||
// the first refresh.
|
||||
if first := wfs.refreshStats(); first != nil {
|
||||
select {
|
||||
case <-first:
|
||||
case <-cancel:
|
||||
return fuse.EINTR
|
||||
// glog.V(4).Infof("reading fs stats")
|
||||
|
||||
if wfs.stats.lastChecked < time.Now().Unix()-20 {
|
||||
|
||||
err := wfs.withFilerClient(context.Background(), false, wfs.filerRPCWait(), func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
request := &filer_pb.StatisticsRequest{
|
||||
Collection: wfs.option.Collection,
|
||||
Replication: wfs.option.Replication,
|
||||
Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
|
||||
DiskType: string(wfs.option.DiskType),
|
||||
}
|
||||
|
||||
glog.V(4).Infof("reading filer stats: %+v", request)
|
||||
resp, err := client.Statistics(ctx, request)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("reading filer stats %v: %v", request, err)
|
||||
return err
|
||||
}
|
||||
glog.V(4).Infof("read filer stats: %+v", resp)
|
||||
|
||||
wfs.stats.TotalSize = resp.TotalSize
|
||||
wfs.stats.UsedSize = resp.UsedSize
|
||||
wfs.stats.LogicalTotalSize = resp.LogicalTotalSize
|
||||
wfs.stats.LogicalUsedSize = resp.LogicalUsedSize
|
||||
wfs.stats.FileCount = resp.FileCount
|
||||
wfs.stats.lastChecked = time.Now().Unix()
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
// the last known sizes beat the empty filesystem a bare return reports
|
||||
glog.V(0).Infof("filer Statistics: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
totalDiskSize, usedDiskSize := wfs.diskSizes()
|
||||
wfs.stats.Lock()
|
||||
actualFileCount := wfs.stats.FileCount
|
||||
wfs.stats.Unlock()
|
||||
|
||||
if wfs.option.Quota > 0 && totalDiskSize > uint64(wfs.option.Quota) {
|
||||
totalDiskSize = uint64(wfs.option.Quota)
|
||||
|
||||
@@ -1,15 +1,6 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
import "testing"
|
||||
|
||||
func TestDiskSizes(t *testing.T) {
|
||||
wfs := &WFS{option: &Option{}}
|
||||
@@ -38,79 +29,3 @@ func TestDiskSizes(t *testing.T) {
|
||||
t.Errorf("sizes from a filer without logical support: got %d/%d, want 3000/2000", total, used)
|
||||
}
|
||||
}
|
||||
|
||||
// statsFiler answers Statistics with total as the total size, once release is
|
||||
// closed if it is set.
|
||||
type statsFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
calls atomic.Int32
|
||||
total uint64
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (f *statsFiler) Statistics(ctx context.Context, req *filer_pb.StatisticsRequest) (*filer_pb.StatisticsResponse, error) {
|
||||
f.calls.Add(1)
|
||||
if f.release != nil {
|
||||
select {
|
||||
case <-f.release:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return &filer_pb.StatisticsResponse{TotalSize: f.total}, nil
|
||||
}
|
||||
|
||||
func statfsBlocks(t *testing.T, wfs *WFS) uint64 {
|
||||
t.Helper()
|
||||
var out fuse.StatfsOut
|
||||
if status := wfs.StatFs(nil, &fuse.InHeader{}, &out); status != fuse.OK {
|
||||
t.Fatalf("statfs: %v", status)
|
||||
}
|
||||
return out.Blocks
|
||||
}
|
||||
|
||||
// The first statfs waits for the first stats from the filer.
|
||||
func TestStatFsWaitsForTheFirstStats(t *testing.T) {
|
||||
filer := &statsFiler{total: 1 << 30}
|
||||
wfs := newPagingWFS(t, util.FullPath("/"), nil, 0)
|
||||
startFakeFiler(t, wfs, filer)
|
||||
|
||||
if blocks := statfsBlocks(t, wfs); blocks != (1<<30)/blockSize {
|
||||
t.Fatalf("statfs reported %d blocks, want the filer's %d", blocks, (1<<30)/blockSize)
|
||||
}
|
||||
}
|
||||
|
||||
// Once it has stats, statfs answers from them while the filer is slow to give
|
||||
// newer ones, and asks the filer once, not once per statfs.
|
||||
func TestStatFsDoesNotWaitForASlowFiler(t *testing.T) {
|
||||
filer := &statsFiler{total: 1 << 30, release: make(chan struct{})}
|
||||
wfs := newPagingWFS(t, util.FullPath("/"), nil, 0)
|
||||
startFakeFiler(t, wfs, filer)
|
||||
wfs.filerCallTimeout = 3 * time.Second
|
||||
// Stats from an earlier refresh, old enough to be refreshed.
|
||||
wfs.stats.TotalSize = 1 << 20
|
||||
wfs.stats.refreshed = true
|
||||
|
||||
start := time.Now()
|
||||
for i := 0; i < 3; i++ {
|
||||
if blocks := statfsBlocks(t, wfs); blocks != (1<<20)/blockSize {
|
||||
t.Fatalf("statfs %d reported %d blocks, want the last known %d", i, blocks, (1<<20)/blockSize)
|
||||
}
|
||||
}
|
||||
if took := time.Since(start); took > 2*time.Second {
|
||||
t.Fatalf("three statfs took %v: they waited for the filer", took)
|
||||
}
|
||||
waitUntil(t, "the refresh to reach the filer", func() bool { return filer.calls.Load() > 0 })
|
||||
|
||||
close(filer.release)
|
||||
waitUntil(t, "the refreshed stats", func() bool {
|
||||
total, _ := wfs.diskSizes()
|
||||
return total == 1<<30
|
||||
})
|
||||
if blocks := statfsBlocks(t, wfs); blocks != (1<<30)/blockSize {
|
||||
t.Fatalf("statfs after the refresh reported %d blocks, want %d", blocks, (1<<30)/blockSize)
|
||||
}
|
||||
if calls := filer.calls.Load(); calls != 1 {
|
||||
t.Fatalf("%d stats requests reached the filer, want 1", calls)
|
||||
}
|
||||
}
|
||||
@@ -60,12 +60,12 @@ func (wfs *WFS) withFilerClient(ctx context.Context, streamingMode bool, callWai
|
||||
|
||||
if err != nil {
|
||||
// glog.V(0).Infof("WithFilerClient %d %v: %v", x, filerGrpcAddress, err)
|
||||
// A verdict or a missing entry is the filer's answer, and
|
||||
// another filer would give the same one. Stop here, so that a
|
||||
// later filer's transport error cannot replace it and turn it
|
||||
// into a retry. A consumer that stopped following, or asked to
|
||||
// resubscribe, is done with this attempt on every filer.
|
||||
if filer_pb.IsFilerVerdict(err) || errors.Is(err, filer_pb.ErrNotFound) || endsFollowAttempt(err) {
|
||||
// A verdict is the filer's answer, and another filer would give
|
||||
// the same one. Stop here, so that a later filer's transport
|
||||
// error cannot replace it and turn it into a retry. A consumer
|
||||
// that stopped following, or asked to resubscribe, is done with
|
||||
// this attempt on every filer.
|
||||
if filer_pb.IsFilerVerdict(err) || endsFollowAttempt(err) {
|
||||
atomic.StoreInt32(&wfs.option.filerIndex, i)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -126,70 +126,3 @@ func TestIsRetryableFilerCallStopFollowing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// missingEntryFiler answers every lookup the way a filer does for a path it
|
||||
// does not have.
|
||||
type missingEntryFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
lookups atomic.Int32
|
||||
}
|
||||
|
||||
func (f *missingEntryFiler) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
f.lookups.Add(1)
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
// A live filer's "not found" is the answer while the other filers are down,
|
||||
// from whichever filer the walk starts at, and the walk stays on that filer.
|
||||
func TestWithFilerClientKeepsTheLiveFilersNotFound(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = listener.Close() })
|
||||
server := pb.NewGrpcServer()
|
||||
filer := &missingEntryFiler{}
|
||||
filer_pb.RegisterSeaweedFilerServer(server, filer)
|
||||
go server.Serve(listener)
|
||||
t.Cleanup(server.Stop)
|
||||
|
||||
down, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
downPort := down.Addr().(*net.TCPAddr).Port
|
||||
_ = down.Close()
|
||||
|
||||
wfs := &WFS{
|
||||
option: &Option{
|
||||
FilerAddresses: []pb.ServerAddress{
|
||||
pb.NewServerAddressWithGrpcPort("127.0.0.1:1", downPort),
|
||||
pb.NewServerAddressWithGrpcPort("127.0.0.1:2", listener.Addr().(*net.TCPAddr).Port),
|
||||
pb.NewServerAddressWithGrpcPort("127.0.0.1:3", downPort),
|
||||
},
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
},
|
||||
}
|
||||
|
||||
for _, startAt := range []int32{0, 1, 2} {
|
||||
atomic.StoreInt32(&wfs.option.filerIndex, startAt)
|
||||
before := filer.lookups.Load()
|
||||
start := time.Now()
|
||||
err = wfs.withFilerClient(context.Background(), false, time.Second, func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
|
||||
_, lookupErr := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: "/etc/seaweedfs", Name: "filer.conf"})
|
||||
return lookupErr
|
||||
})
|
||||
if err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("start at %d: withFilerClient error = %v, want ErrNotFound", startAt, err)
|
||||
}
|
||||
if n := filer.lookups.Load() - before; n != 1 {
|
||||
t.Fatalf("start at %d: lookups = %d, want 1", startAt, n)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 3*time.Second {
|
||||
t.Fatalf("start at %d: withFilerClient took %v for a missing entry", startAt, elapsed)
|
||||
}
|
||||
if i := atomic.LoadInt32(&wfs.option.filerIndex); i != 1 {
|
||||
t.Fatalf("start at %d: filerIndex = %d, want the live filer 1", startAt, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -464,11 +464,6 @@ func uploadChunkToHolders(ctx context.Context, hosts []string, fid string, prepa
|
||||
// rollback of a failed fan-out.
|
||||
const cleanupJwtLookupTimeout = 10 * time.Second
|
||||
|
||||
// cleanupDeleteTimeout bounds each delete of a cleanup, its answer included.
|
||||
// The holder asked is often the one that just failed the write, and one that
|
||||
// stalls must not hold the upload, or the cleanup of the other holders.
|
||||
var cleanupDeleteTimeout = 10 * time.Second
|
||||
|
||||
// deleteChunkFromHolders best-effort removes a needle from each holder it landed
|
||||
// on, using type=replicate so the volume drops only its local copy. A failed
|
||||
// delete falls back to vacuum reclaiming the orphan.
|
||||
@@ -478,21 +473,16 @@ func deleteChunkFromHolders(hosts []string, fid string, jwt security.EncodedJwt,
|
||||
// Each holder's delete is retried at most once, and a slow holder that
|
||||
// outlives the renewed token can still trigger another renewal.
|
||||
deleteJwt := jwt
|
||||
deleteFrom := func(url string, jwt security.EncodedJwt) ([]byte, int, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cleanupDeleteTimeout)
|
||||
defer cancel()
|
||||
return util_http.DeleteProxied(ctx, url, string(jwt))
|
||||
}
|
||||
for _, host := range hosts {
|
||||
deleteUrl := fmt.Sprintf("http://%s/%s?type=replicate&%s=%s", host, fid, ReplicateSourceParam, ReplicateSourceClient)
|
||||
body, status, err := deleteFrom(deleteUrl, deleteJwt)
|
||||
body, status, err := util_http.DeleteProxied(deleteUrl, string(deleteJwt))
|
||||
if status == http.StatusUnauthorized && opt.LookupJwtFunc != nil {
|
||||
lookupCtx, cancel := context.WithTimeout(context.Background(), cleanupJwtLookupTimeout)
|
||||
token := opt.LookupJwtFunc(lookupCtx, fid)
|
||||
cancel()
|
||||
if token != "" {
|
||||
deleteJwt = token
|
||||
body, status, err = deleteFrom(deleteUrl, deleteJwt)
|
||||
body, status, err = util_http.DeleteProxied(deleteUrl, string(deleteJwt))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -849,50 +849,6 @@ func TestDeleteChunkFromHoldersRenewsPerHolder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A holder that sends the headers of its answer to the cleanup delete and
|
||||
// then stalls the body holds the cleanup for cleanupDeleteTimeout only, and
|
||||
// the holders after it are still asked.
|
||||
func TestDeleteChunkFromHoldersDoesNotWaitOnAStalledHolder(t *testing.T) {
|
||||
defer func(d time.Duration) { cleanupDeleteTimeout = d }(cleanupDeleteTimeout)
|
||||
cleanupDeleteTimeout = 200 * time.Millisecond
|
||||
|
||||
release := make(chan struct{})
|
||||
stalled := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
w.(http.Flusher).Flush()
|
||||
<-release
|
||||
}))
|
||||
defer stalled.Close()
|
||||
defer close(release)
|
||||
var deletes int32
|
||||
healthy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodDelete {
|
||||
atomic.AddInt32(&deletes, 1)
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
defer healthy.Close()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
deleteChunkFromHolders(
|
||||
[]string{strings.TrimPrefix(stalled.URL, "http://"), strings.TrimPrefix(healthy.URL, "http://")},
|
||||
"1,0a0b0c0d",
|
||||
"",
|
||||
&ChunkedUploadOption{},
|
||||
)
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the cleanup still waits on the stalled holder after 5s")
|
||||
}
|
||||
if got := atomic.LoadInt32(&deletes); got != 1 {
|
||||
t.Fatalf("the holder after the stalled one got %d deletes, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUploadChunkToHoldersMarksClientSource verifies that the gateway's own
|
||||
// fan-out writes are tagged as client traffic, so a volume server can tell
|
||||
// them apart from a primary-to-replica forward.
|
||||
|
||||
@@ -844,10 +844,7 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction
|
||||
stopBodyDeadline(bodyTimer)
|
||||
defer util_http.CloseResponse(resp)
|
||||
if post_err != nil {
|
||||
// The three ways a pooled conn the server has closed can fail: which
|
||||
// one depends on when its close reached this side.
|
||||
if strings.Contains(post_err.Error(), "connection reset by peer") ||
|
||||
strings.Contains(post_err.Error(), "broken pipe") ||
|
||||
strings.Contains(post_err.Error(), "use of closed network connection") {
|
||||
glog.V(1).InfofCtx(ctx, "repeat error upload request %s: %v", option.UploadUrl, post_err)
|
||||
stats.FilerHandlerCounter.WithLabelValues(stats.RepeatErrorUploadContent).Inc()
|
||||
|
||||
@@ -762,7 +762,6 @@ func TestUploadWithRetryBoundsAssignVolume(t *testing.T) {
|
||||
func TestUploadRewindsBodyOnConnectionReset(t *testing.T) {
|
||||
for _, transient := range []string{
|
||||
"connection reset by peer",
|
||||
"write: broken pipe",
|
||||
"use of closed network connection",
|
||||
} {
|
||||
t.Run(transient, func(t *testing.T) {
|
||||
@@ -794,29 +793,6 @@ func TestUploadRewindsBodyOnConnectionReset(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A write is forwarded to a replica in one attempt, so nothing after the
|
||||
// resend stands between a conn the replica has closed and a failed write.
|
||||
func TestSingleAttemptUploadResendsOnAStaleConnection(t *testing.T) {
|
||||
client := &bodyCapturingHTTPClient{
|
||||
failFirst: "write tcp 10.0.0.1:36942->10.0.0.2:8080: write: broken pipe",
|
||||
successJSON: `{"name":"test.bin","size":42}`,
|
||||
}
|
||||
uploader := newUploader(client)
|
||||
|
||||
_, err := uploader.UploadData(context.Background(), bytes.Repeat([]byte("payload-"), 256), &UploadOption{
|
||||
UploadUrl: "http://volume/1,abc?type=replicate",
|
||||
Filename: "test.bin",
|
||||
IsReplication: true,
|
||||
MaxAttempts: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("the forward failed on a conn the replica had closed: %v", err)
|
||||
}
|
||||
if len(client.bodies) != 2 || !bytes.Equal(client.bodies[0], client.bodies[1]) {
|
||||
t.Fatalf("%d requests sent, want the same one twice", len(client.bodies))
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplicationUploadPreservesUncompressedNeedle(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
|
||||
@@ -6,7 +6,6 @@ package handlers
|
||||
|
||||
import (
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance" // register volume_balance handler
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/dir_usage" // register dir_usage handler
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/ec_balance" // register ec_balance handler
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding" // register erasure_coding handler
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/filer_ttl" // register filer_ttl handler
|
||||
|
||||
@@ -44,6 +44,8 @@ func InitializeSSEForReplication(filerSource filer_pb.FilerClient) error {
|
||||
loader := kms.NewConfigLoader(util.GetViper())
|
||||
if err := loader.LoadConfigurations(); err != nil {
|
||||
glog.Warningf("KMS initialization from config failed: %v (SSE-KMS decryption will not be available)", err)
|
||||
} else if err := loader.ValidateConfiguration(); err != nil {
|
||||
glog.Warningf("KMS configuration validation failed: %v (SSE-KMS decryption will not be available)", err)
|
||||
} else {
|
||||
glog.V(0).Infof("KMS initialized for replication")
|
||||
}
|
||||
|
||||
+46
-112
@@ -10,7 +10,6 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -142,37 +141,17 @@ type IdentityAccessManagement struct {
|
||||
}
|
||||
|
||||
type Identity struct {
|
||||
Name string
|
||||
Account *Account
|
||||
Credentials []*Credential
|
||||
Actions []Action
|
||||
permissionBoundary []Action
|
||||
serviceAccountParent *Identity
|
||||
PolicyNames []string // Attached IAM policy names
|
||||
PrincipalArn string // ARN for IAM authorization (e.g., "arn:aws:iam::account-id:user/username")
|
||||
Disabled bool // User status: false = enabled (default), true = disabled
|
||||
Claims map[string]interface{} // JWT claims for policy substitution
|
||||
IsStatic bool // Whether identity was loaded from static config (immutable)
|
||||
IdentityClaim string // Authoritative OIDC identity claim for audit logging (preferred_username/email/sub); empty for non-federated sessions
|
||||
Certificates []*iam_pb.CertificateMatch
|
||||
}
|
||||
|
||||
func identityForServiceAccount(parent *Identity, sa *iam_pb.ServiceAccount, credential *Credential) *Identity {
|
||||
if len(sa.Actions) == 0 {
|
||||
return parent
|
||||
}
|
||||
identity := *parent
|
||||
identity.Credentials = []*Credential{credential}
|
||||
identity.serviceAccountParent = parent
|
||||
identity.permissionBoundary = make([]Action, 0, len(sa.Actions))
|
||||
for _, action := range sa.Actions {
|
||||
identity.permissionBoundary = append(identity.permissionBoundary, Action(action))
|
||||
}
|
||||
return &identity
|
||||
}
|
||||
|
||||
func (identity *Identity) belongsTo(parent *Identity) bool {
|
||||
return identity == parent || identity != nil && identity.serviceAccountParent == parent
|
||||
Name string
|
||||
Account *Account
|
||||
Credentials []*Credential
|
||||
Actions []Action
|
||||
PolicyNames []string // Attached IAM policy names
|
||||
PrincipalArn string // ARN for IAM authorization (e.g., "arn:aws:iam::account-id:user/username")
|
||||
Disabled bool // User status: false = enabled (default), true = disabled
|
||||
Claims map[string]interface{} // JWT claims for policy substitution
|
||||
IsStatic bool // Whether identity was loaded from static config (immutable)
|
||||
IdentityClaim string // Authoritative OIDC identity claim for audit logging (preferred_username/email/sub); empty for non-federated sessions
|
||||
Certificates []*iam_pb.CertificateMatch
|
||||
}
|
||||
|
||||
// Account represents a system user, a system user can
|
||||
@@ -707,21 +686,15 @@ func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFile(fileName str
|
||||
glog.Warningf("S3 config %s: ignoring unknown top-level keys %v", fileName, unknown)
|
||||
}
|
||||
|
||||
// The identities are parsed before KMS is loaded, so a file whose identities don't parse
|
||||
// changes neither.
|
||||
config, err := parseS3ApiConfiguration(content, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Initialize KMS if configuration contains KMS settings
|
||||
if err := iam.initializeKMSFromConfig(content); err != nil {
|
||||
glog.Errorf("KMS initialization failed: %v", err)
|
||||
glog.Warningf("KMS initialization failed: %v", err)
|
||||
}
|
||||
|
||||
// fromStaticFile=true: this file is the source of truth for its static
|
||||
// identities, so a reload overwrites them (e.g. a rotated secretKey).
|
||||
if err := iam.loadS3ApiConfigurationWithSource(config, true); err != nil {
|
||||
config, err := iam.loadS3ApiConfigurationFromBytes(content, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Identities listed in a config file are static (immutable). Mark them on
|
||||
@@ -765,17 +738,6 @@ func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromBytes(content []b
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromBytes(content []byte, fromStaticFile bool) (*iam_pb.S3ApiConfiguration, error) {
|
||||
s3ApiConfiguration, err := parseS3ApiConfiguration(content, fromStaticFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := iam.loadS3ApiConfigurationWithSource(s3ApiConfiguration, fromStaticFile); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s3ApiConfiguration, nil
|
||||
}
|
||||
|
||||
func parseS3ApiConfiguration(content []byte, fromStaticFile bool) (*iam_pb.S3ApiConfiguration, error) {
|
||||
s3ApiConfiguration := &iam_pb.S3ApiConfiguration{}
|
||||
if err := filer.ParseS3ConfigurationFromBytes(normalizeAdvancedIAMPolicies(content), s3ApiConfiguration); err != nil {
|
||||
glog.Warningf("unmarshal error: %v", err)
|
||||
@@ -794,6 +756,10 @@ func parseS3ApiConfiguration(content []byte, fromStaticFile bool) (*iam_pb.S3Api
|
||||
if err := filer.CheckDuplicateAccessKey(s3ApiConfiguration); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := iam.loadS3ApiConfigurationWithSource(s3ApiConfiguration, fromStaticFile); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s3ApiConfiguration, nil
|
||||
}
|
||||
|
||||
@@ -993,7 +959,7 @@ func (iam *IdentityAccessManagement) ReplaceS3ApiConfiguration(config *iam_pb.S3
|
||||
Expiration: sa.Expiration, // Populate expiration from service account
|
||||
}
|
||||
parentIdent.Credentials = append(parentIdent.Credentials, cred)
|
||||
accessKeyIdent[sa.Credential.AccessKey] = identityForServiceAccount(parentIdent, sa, cred)
|
||||
accessKeyIdent[sa.Credential.AccessKey] = parentIdent
|
||||
glog.V(3).Infof("Loaded service account %s for parent %s (expiration: %d)", sa.Id, sa.ParentUser, sa.Expiration)
|
||||
}
|
||||
|
||||
@@ -1203,7 +1169,7 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap
|
||||
oldIdentity := identities[existingIdx]
|
||||
for _, oldCred := range oldIdentity.Credentials {
|
||||
// Only remove if it still points to this identity
|
||||
if accessKeyIdent[oldCred.AccessKey].belongsTo(oldIdentity) {
|
||||
if accessKeyIdent[oldCred.AccessKey] == oldIdentity {
|
||||
delete(accessKeyIdent, oldCred.AccessKey)
|
||||
}
|
||||
}
|
||||
@@ -1243,7 +1209,7 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap
|
||||
}
|
||||
delete(nameToIdentity, existing.Name)
|
||||
for _, cred := range existing.Credentials {
|
||||
if accessKeyIdent[cred.AccessKey].belongsTo(existing) {
|
||||
if accessKeyIdent[cred.AccessKey] == existing {
|
||||
delete(accessKeyIdent, cred.AccessKey)
|
||||
}
|
||||
}
|
||||
@@ -1280,18 +1246,18 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap
|
||||
}
|
||||
|
||||
// Check if this access key already exists in parent's credentials to avoid duplicates
|
||||
var existingCredential *Credential
|
||||
alreadyExists := false
|
||||
for _, existingCred := range parentIdent.Credentials {
|
||||
if existingCred.AccessKey == sa.Credential.AccessKey {
|
||||
existingCredential = existingCred
|
||||
alreadyExists = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if existingCredential != nil {
|
||||
if alreadyExists {
|
||||
glog.V(3).Infof("Service account %s credential already exists for parent %s, skipping", sa.Id, sa.ParentUser)
|
||||
// Ensure accessKeyIdent mapping is correct
|
||||
accessKeyIdent[sa.Credential.AccessKey] = identityForServiceAccount(parentIdent, sa, existingCredential)
|
||||
accessKeyIdent[sa.Credential.AccessKey] = parentIdent
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1303,7 +1269,7 @@ func (iam *IdentityAccessManagement) MergeS3ApiConfiguration(config *iam_pb.S3Ap
|
||||
Expiration: sa.Expiration,
|
||||
}
|
||||
parentIdent.Credentials = append(parentIdent.Credentials, cred)
|
||||
accessKeyIdent[sa.Credential.AccessKey] = identityForServiceAccount(parentIdent, sa, cred)
|
||||
accessKeyIdent[sa.Credential.AccessKey] = parentIdent
|
||||
glog.V(3).Infof("Loaded service account %s for dynamic parent %s (expiration: %d)", sa.Id, sa.ParentUser, sa.Expiration)
|
||||
}
|
||||
|
||||
@@ -1415,7 +1381,7 @@ func (iam *IdentityAccessManagement) RemoveIdentity(name string) {
|
||||
// Remove from maps
|
||||
delete(iam.nameToIdentity, name)
|
||||
for _, cred := range identity.Credentials {
|
||||
if iam.accessKeyIdent[cred.AccessKey].belongsTo(identity) {
|
||||
if iam.accessKeyIdent[cred.AccessKey] == identity {
|
||||
delete(iam.accessKeyIdent, cred.AccessKey)
|
||||
}
|
||||
}
|
||||
@@ -2165,9 +2131,6 @@ func (iam *IdentityAccessManagement) authorizeRequest(r *http.Request, identity
|
||||
r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id)
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if !(action == s3_constants.ACTION_LIST && bucket == "") && !identity.allowsPermissionBoundary(r, action, bucket, object) {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
// For ListBuckets, authorization is performed in the handler by iterating
|
||||
// through buckets and checking permissions for each. Skip the global check here.
|
||||
@@ -2278,10 +2241,7 @@ func (identity *Identity) CanDo(action Action, bucket string, objectKey string)
|
||||
if identity == nil {
|
||||
return false
|
||||
}
|
||||
if !identity.allowsPermissionBoundary(nil, action, bucket, objectKey) {
|
||||
return false
|
||||
}
|
||||
if slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN) {
|
||||
if identity.isAdmin() {
|
||||
return true
|
||||
}
|
||||
for _, a := range identity.Actions {
|
||||
@@ -2336,21 +2296,6 @@ func (identity *Identity) CanDo(action Action, bucket string, objectKey string)
|
||||
return false
|
||||
}
|
||||
|
||||
func (identity *Identity) allowsPermissionBoundary(r *http.Request, action Action, bucket string, objectKey string) bool {
|
||||
if identity == nil {
|
||||
return false
|
||||
}
|
||||
if len(identity.permissionBoundary) == 0 {
|
||||
return true
|
||||
}
|
||||
boundary := &Identity{Actions: identity.permissionBoundary}
|
||||
if boundary.CanDo(action, bucket, objectKey) {
|
||||
return true
|
||||
}
|
||||
listing := multipartListingAction(r, action)
|
||||
return listing != "" && boundary.CanDo(listing, bucket, objectKey)
|
||||
}
|
||||
|
||||
// hasListAction reports whether the identity carries any List-scoped legacy
|
||||
// action (e.g. "List", "List:*", "List:prefix-*") or has administrative
|
||||
// privileges. Used to decide whether a ListBuckets request from an anonymous
|
||||
@@ -2378,9 +2323,6 @@ func (identity *Identity) isAdmin() bool {
|
||||
if identity == nil {
|
||||
return false
|
||||
}
|
||||
if len(identity.permissionBoundary) > 0 && !slices.Contains(identity.permissionBoundary, s3_constants.ACTION_ADMIN) {
|
||||
return false
|
||||
}
|
||||
return slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN)
|
||||
}
|
||||
|
||||
@@ -2770,21 +2712,23 @@ func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromCredentialManager
|
||||
return nil
|
||||
}
|
||||
|
||||
// initializeKMSFromConfig loads the optional "kms" block of the JSON identities file. A file
|
||||
// without one drops the providers, so a reload that took the block out turns SSE-KMS off.
|
||||
// initializeKMSFromConfig loads the optional "kms" block of the JSON identities file.
|
||||
// A file that isn't JSON is left for the identities load to report.
|
||||
func (iam *IdentityAccessManagement) initializeKMSFromConfig(configContent []byte) error {
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(configContent, &m); err != nil {
|
||||
// encoding/json's errors quote what they reject, which can be key material. protojson
|
||||
// skips the values of keys it doesn't know without reading their numbers, so after it
|
||||
// accepted the file this is one out of float64 range.
|
||||
var typeErr *json.UnmarshalTypeError
|
||||
if errors.As(err, &typeErr) && typeErr.Type.Kind() == reflect.Float64 {
|
||||
return errors.New("failed to parse S3 config: a number in it is out of float64 range")
|
||||
}
|
||||
return errors.New("failed to parse S3 config")
|
||||
return nil
|
||||
}
|
||||
return kms.LoadKMSFromConfig(m["kms"])
|
||||
kmsVal, ok := m["kms"]
|
||||
if !ok {
|
||||
glog.V(2).Infof("No KMS configuration found in S3 config - SSE-KMS will not be available")
|
||||
return nil
|
||||
}
|
||||
if err := kms.LoadKMSFromConfig(kmsVal); err != nil {
|
||||
return err
|
||||
}
|
||||
glog.V(1).Infof("Successfully loaded KMS configuration from JSON format")
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetIAMIntegration sets the IAM integration for advanced authentication and authorization.
|
||||
@@ -3139,9 +3083,6 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide
|
||||
glog.V(3).Infof("VerifyActionPermission called with nil identity for action %s on %s/%s", action, bucket, object)
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if !identity.allowsPermissionBoundary(r, action, bucket, object) {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
|
||||
switch iam.authorizationRoute(r, identity) {
|
||||
case authorizeViaIAMIntegration:
|
||||
@@ -3160,18 +3101,17 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide
|
||||
// No matching statement: a native bare Admin grant survives
|
||||
// attaching a policy (issue #11226). Scoped actions are not
|
||||
// consulted because inline policies flatten lossily into Actions.
|
||||
if slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN) {
|
||||
if identity.isAdmin() {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
case authorizeViaLegacyActions:
|
||||
grants := &Identity{Name: identity.Name, Actions: identity.Actions}
|
||||
if !grants.CanDo(action, bucket, object) {
|
||||
if !identity.CanDo(action, bucket, object) {
|
||||
// The multipart listing routes are gated on ACTION_READ, but a
|
||||
// grant may name the listing operation itself.
|
||||
listing := multipartListingAction(r, action)
|
||||
if listing == "" || !grants.CanDo(listing, bucket, object) {
|
||||
if listing == "" || !identity.CanDo(listing, bucket, object) {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
}
|
||||
@@ -3192,7 +3132,7 @@ func (iam *IdentityAccessManagement) VerifyActionPermission(r *http.Request, ide
|
||||
func (iam *IdentityAccessManagement) canListBucketsFromOwnerIndex(r *http.Request, identity *Identity) (ok bool, granted []string) {
|
||||
// Fail closed on a nil identity: the scan path filters every bucket out
|
||||
// without dereferencing it, while the index path would need its name.
|
||||
if identity == nil || identity.isAdmin() || len(identity.permissionBoundary) > 0 {
|
||||
if identity == nil || identity.isAdmin() {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -3335,9 +3275,6 @@ func (iam *IdentityAccessManagement) authorizeObjectKeyAction(r *http.Request, i
|
||||
if identity == nil {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if !identity.allowsPermissionBoundary(r, action, bucket, objectKey) {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if identity.isAdmin() {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
@@ -3428,9 +3365,6 @@ func (iam *IdentityAccessManagement) AuthorizeObjectAclWrite(r *http.Request, id
|
||||
|
||||
// authorizeWithIAM authorizes requests using the IAM integration policy engine
|
||||
func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity *Identity, action Action, bucket string, object string) s3err.ErrorCode {
|
||||
if !identity.allowsPermissionBoundary(r, action, bucket, object) {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
ctx := r.Context()
|
||||
|
||||
// The evaluation below consults the bucket-policy:<bucket> mirror, so the
|
||||
@@ -3458,7 +3392,7 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity
|
||||
// an explicit Deny in an attached policy still wins. This runs before the
|
||||
// auth-path switch so an Admin identity without a session principal or
|
||||
// PrincipalArn is still authorized through its native grant.
|
||||
if slices.Contains(identity.Actions, s3_constants.ACTION_ADMIN) {
|
||||
if identity.isAdmin() {
|
||||
s3Action, resourceArn := resolveS3AuthTarget(action, bucket, object, r)
|
||||
principal := buildPrincipalARN(identity, r)
|
||||
if !iam.isActionExplicitlyDeniedByIAM(r, identity, principal, s3Action, resourceArn) {
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/kms"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
|
||||
// resetKMS drops the providers a test loaded.
|
||||
func resetKMS(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
if err := kms.LoadKMSFromConfig(nil); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestKMSSectionRemovedDropsTheProviders(t *testing.T) {
|
||||
resetKMS(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
if err := iam.initializeKMSFromConfig([]byte(`{"kms": {"providers": {"removed-test": {"type": "local"}}}}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := iam.initializeKMSFromConfig([]byte(`{"kms": `)); err == nil {
|
||||
t.Error("a configuration that isn't JSON was reported as loaded")
|
||||
}
|
||||
if kms.GetGlobalKMS() == nil {
|
||||
t.Fatal("a configuration that isn't JSON dropped the KMS providers")
|
||||
}
|
||||
|
||||
if err := iam.initializeKMSFromConfig([]byte(`{"identities": []}`)); err != nil {
|
||||
t.Fatalf("a configuration without KMS: %v", err)
|
||||
}
|
||||
if kms.GetGlobalKMS() != nil {
|
||||
t.Fatal("a reload that took the kms section out kept its providers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentitiesThatDontParseLeaveKMSAlone(t *testing.T) {
|
||||
resetKMS(t)
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
|
||||
identity := func(name string) string {
|
||||
return `{"name": "` + name + `", "credentials": [{"accessKey": "AKIADUPLICATE", "secretKey": "c2VjcmV0"}]}`
|
||||
}
|
||||
|
||||
if kms.GetGlobalKMS() != nil {
|
||||
t.Fatal("a KMS provider is already set")
|
||||
}
|
||||
if err := s3a.iam.loadS3ApiConfigurationFromFile(writeTempIamConfig(t, `{"kms": {"providers": {"identities-test": {"type": "local"}}}, "identities": [`+identity("a")+`]}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded := kms.GetGlobalKMS()
|
||||
if loaded == nil {
|
||||
t.Fatal("the KMS providers didn't load")
|
||||
}
|
||||
|
||||
duplicates := `"identities": [` + identity("a") + `, ` + identity("b") + `]`
|
||||
for name, config := range map[string]string{
|
||||
"other providers": `{"kms": {"providers": {"identities-other": {"type": "local"}}}, ` + duplicates + `}`,
|
||||
"no kms section": `{` + duplicates + `}`,
|
||||
} {
|
||||
if err := s3a.iam.loadS3ApiConfigurationFromFile(writeTempIamConfig(t, config)); err == nil {
|
||||
t.Fatalf("%s: identities sharing an access key were accepted", name)
|
||||
}
|
||||
if kms.GetGlobalKMS() != loaded {
|
||||
t.Fatalf("%s: a file whose identities don't parse changed the KMS providers", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKMSConfigWithANumberOutOfRangeKeepsItOutOfTheError(t *testing.T) {
|
||||
resetKMS(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
const number = "12345678901234567890e400"
|
||||
|
||||
err := iam.initializeKMSFromConfig([]byte(`{"identities": [{"name": "admin"}], "kms": {"providers": {"p": {"type": "local", "note": ` + number + `}}}}`))
|
||||
if want := "failed to parse S3 config: a number in it is out of float64 range"; err == nil || err.Error() != want {
|
||||
t.Fatalf("got %v, want %s", err, want)
|
||||
}
|
||||
}
|
||||
@@ -590,7 +590,7 @@ func TestIdentitiesFileKMSErrorsAreReported(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
for content, wantErr := range map[string]bool{
|
||||
`{"identities":[]}`: false,
|
||||
`not json`: true,
|
||||
`not json`: false,
|
||||
`{"kms":{"default_provider":true}}`: true,
|
||||
`{"kms":{"providers":"vault"}}`: true,
|
||||
`{"kms":{"default_provider":"missing"}}`: true,
|
||||
|
||||
@@ -3,14 +3,12 @@ package s3api
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
@@ -440,134 +438,3 @@ func TestUpsertIdentityKeepsServiceAccountKeys(t *testing.T) {
|
||||
_, _, found = s3a.iam.LookupByAccessKey("AKPACS")
|
||||
assert.True(t, found)
|
||||
}
|
||||
|
||||
func TestServiceAccountActionsLimitParent(t *testing.T) {
|
||||
parent := &iam_pb.Identity{
|
||||
Name: "parent",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "AKPARENT", SecretKey: "parent-secret"}},
|
||||
Actions: []string{"Admin"},
|
||||
}
|
||||
serviceAccount := &iam_pb.ServiceAccount{
|
||||
Id: "sa:parent:restricted",
|
||||
ParentUser: "parent",
|
||||
Actions: []string{"Read"},
|
||||
Credential: &iam_pb.Credential{AccessKey: "AKSERVICE", SecretKey: "service-secret", Status: "Active"},
|
||||
}
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{parent})
|
||||
require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{parent},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount},
|
||||
}))
|
||||
|
||||
writeRequest, err := http.NewRequest(http.MethodPut, "http://s3/bucket/object", nil)
|
||||
require.NoError(t, err)
|
||||
readRequest, err := http.NewRequest(http.MethodGet, "http://s3/bucket/object", nil)
|
||||
require.NoError(t, err)
|
||||
iamRequest, err := http.NewRequest(http.MethodPost, "http://iam/", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
assertPermissions := func() {
|
||||
resolved, _, found := s3a.iam.LookupByAccessKey("AKSERVICE")
|
||||
require.True(t, found)
|
||||
assert.Equal(t, "parent", resolved.Name)
|
||||
assert.Equal(t, s3err.ErrAccessDenied,
|
||||
s3a.iam.VerifyActionPermission(writeRequest, resolved, s3_constants.ACTION_WRITE, "bucket", "object"))
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.iam.VerifyActionPermission(readRequest, resolved, s3_constants.ACTION_READ, "bucket", "object"))
|
||||
assert.Equal(t, s3err.ErrAccessDenied,
|
||||
s3a.iam.AuthorizeIamAction(iamRequest, resolved, "CreateAccessKey", "parent"))
|
||||
}
|
||||
|
||||
assertPermissions()
|
||||
|
||||
withPolicy := &iam_pb.Identity{
|
||||
Name: parent.Name,
|
||||
Credentials: parent.Credentials,
|
||||
Actions: parent.Actions,
|
||||
PolicyNames: []string{"ListBucketsOnly"},
|
||||
}
|
||||
require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{withPolicy},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount},
|
||||
Policies: []*iam_pb.Policy{{
|
||||
Name: "ListBucketsOnly",
|
||||
Content: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}]}`,
|
||||
}},
|
||||
}))
|
||||
assertPermissions()
|
||||
s3a.iam.SetIAMIntegration(NewS3IAMIntegration(newTestIAMManager(t), ""))
|
||||
assertPermissions()
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, s3a.iam.credentialManager.CreateServiceAccount(ctx, serviceAccount))
|
||||
pushed, err := s3a.iam.credentialManager.GetUser(ctx, "parent")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, s3a.iam.UpsertIdentity(pushed))
|
||||
assertPermissions()
|
||||
|
||||
inherited := &iam_pb.ServiceAccount{
|
||||
Id: serviceAccount.Id,
|
||||
ParentUser: serviceAccount.ParentUser,
|
||||
Credential: serviceAccount.Credential,
|
||||
}
|
||||
require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{parent},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{inherited},
|
||||
}))
|
||||
resolved, _, found := s3a.iam.LookupByAccessKey("AKSERVICE")
|
||||
require.True(t, found)
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
s3a.iam.VerifyActionPermission(writeRequest, resolved, s3_constants.ACTION_WRITE, "bucket", "object"))
|
||||
|
||||
require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{parent},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount},
|
||||
}))
|
||||
require.NoError(t, s3a.iam.MergeS3ApiConfiguration(&iam_pb.S3ApiConfiguration{}, false, true))
|
||||
_, _, found = s3a.iam.LookupByAccessKey("AKSERVICE")
|
||||
assert.False(t, found)
|
||||
|
||||
require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{parent},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{serviceAccount},
|
||||
}))
|
||||
s3a.iam.RemoveIdentity("parent")
|
||||
_, _, found = s3a.iam.LookupByAccessKey("AKSERVICE")
|
||||
assert.False(t, found)
|
||||
}
|
||||
|
||||
func TestServiceAccountActionsAllowScopedUploadListing(t *testing.T) {
|
||||
for _, parentAction := range []string{"Admin", "Read"} {
|
||||
t.Run(parentAction, func(t *testing.T) {
|
||||
testServiceAccountScopedUploadListing(t, parentAction)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testServiceAccountScopedUploadListing(t *testing.T, parentAction string) {
|
||||
parent := &iam_pb.Identity{
|
||||
Name: "parent",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "AKPARENT", SecretKey: "parent-secret"}},
|
||||
Actions: []string{parentAction},
|
||||
}
|
||||
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{parent})
|
||||
require.NoError(t, s3a.iam.ReplaceS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{parent},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{{
|
||||
Id: "sa:parent:uploads",
|
||||
ParentUser: "parent",
|
||||
Actions: []string{"ListBucketMultipartUploads:demo"},
|
||||
Credential: &iam_pb.Credential{AccessKey: "AKSERVICE", SecretKey: "service-secret"},
|
||||
}},
|
||||
}))
|
||||
resolved, _, found := s3a.iam.LookupByAccessKey("AKSERVICE")
|
||||
require.True(t, found)
|
||||
|
||||
uploads := mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/demo?uploads", nil), map[string]string{"bucket": "demo"})
|
||||
assert.Equal(t, s3err.ErrNone, s3a.iam.VerifyActionPermission(uploads, resolved, s3_constants.ACTION_READ, "demo", ""))
|
||||
assert.Equal(t, s3err.ErrNone, s3a.iam.authorizeRequest(uploads, resolved, s3_constants.ACTION_READ))
|
||||
|
||||
get := mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/demo/key", nil), map[string]string{"bucket": "demo", "object": "key"})
|
||||
assert.Equal(t, s3err.ErrAccessDenied, s3a.iam.VerifyActionPermission(get, resolved, s3_constants.ACTION_READ, "demo", "key"))
|
||||
assert.Equal(t, s3err.ErrAccessDenied, s3a.iam.authorizeRequest(get, resolved, s3_constants.ACTION_READ))
|
||||
}
|
||||
@@ -976,9 +976,6 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
if errors.Is(err, errObjectPrecondition) {
|
||||
return s3err.ErrPreconditionFailed
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrEntryNameTooLong) {
|
||||
return s3err.ErrKeyTooLongError
|
||||
}
|
||||
// The transaction may have committed the object before failing on
|
||||
// the upload removal; a surviving entry references the manifests.
|
||||
if exists, err := s3a.exists(dirName, entryName, false); err != nil || exists {
|
||||
@@ -1077,9 +1074,6 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
|
||||
if errors.Is(err, errObjectPrecondition) {
|
||||
return s3err.ErrPreconditionFailed
|
||||
}
|
||||
if errors.Is(err, filer_pb.ErrEntryNameTooLong) {
|
||||
return s3err.ErrKeyTooLongError
|
||||
}
|
||||
// The transaction may have committed the object before failing on
|
||||
// the upload removal; a surviving entry references the manifests.
|
||||
if exists, err := s3a.exists(dirName, entryName, false); err != nil || exists {
|
||||
|
||||
@@ -158,9 +158,6 @@ func (s3a *S3ApiServer) bucketVisibleToIdentity(r *http.Request, bucket, owner s
|
||||
if !s3a.iam.isEnabled() {
|
||||
return true
|
||||
}
|
||||
if !identity.allowsPermissionBoundary(r, s3_constants.ACTION_LIST, bucket, "") {
|
||||
return false
|
||||
}
|
||||
if isBucketOwnedByIdentity(owner, identity) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -117,8 +117,8 @@ func (cb *CircuitBreaker) Limit(f func(w http.ResponseWriter, r *http.Request),
|
||||
cb.s3a.inFlightDataLimitCond.L.Lock()
|
||||
defer cb.s3a.inFlightDataLimitCond.L.Unlock()
|
||||
// Decrement counters
|
||||
newUploads := cb.s3a.inFlightUploads.Add(-1)
|
||||
newSize := cb.s3a.inFlightDataSize.Add(-charged)
|
||||
newUploads := atomic.AddInt64(&cb.s3a.inFlightUploads, -1)
|
||||
newSize := atomic.AddInt64(&cb.s3a.inFlightDataSize, -charged)
|
||||
// Update metrics
|
||||
stats.S3InFlightUploadCountGauge.Set(float64(newUploads))
|
||||
stats.S3InFlightUploadBytesGauge.Set(float64(newSize))
|
||||
@@ -195,12 +195,12 @@ func (cb *CircuitBreaker) waitForUploadSlot(w http.ResponseWriter, r *http.Reque
|
||||
s3a := cb.s3a
|
||||
s3a.inFlightDataLimitCond.L.Lock()
|
||||
err := util.WaitUntil(r.Context(), s3a.inFlightDataLimitCond, s3a.option.InflightUploadDataTimeout, func() bool {
|
||||
inFlightDataSize := s3a.inFlightDataSize.Load()
|
||||
inFlightDataSize := atomic.LoadInt64(&s3a.inFlightDataSize)
|
||||
if !util.UploadAdmits(inFlightDataSize, charged, s3a.option.ConcurrentUploadLimit) {
|
||||
glog.V(4).Infof("wait because inflight data %d + %d > %d", inFlightDataSize, charged, s3a.option.ConcurrentUploadLimit)
|
||||
return false
|
||||
}
|
||||
inFlightUploads := s3a.inFlightUploads.Load()
|
||||
inFlightUploads := atomic.LoadInt64(&s3a.inFlightUploads)
|
||||
if s3a.option.ConcurrentFileUploadLimit != 0 && inFlightUploads >= s3a.option.ConcurrentFileUploadLimit {
|
||||
glog.V(4).Infof("wait because inflight uploads %d >= %d", inFlightUploads, s3a.option.ConcurrentFileUploadLimit)
|
||||
return false
|
||||
@@ -209,8 +209,8 @@ func (cb *CircuitBreaker) waitForUploadSlot(w http.ResponseWriter, r *http.Reque
|
||||
})
|
||||
if err == nil {
|
||||
// Increment counters
|
||||
newUploads := s3a.inFlightUploads.Add(1)
|
||||
newSize := s3a.inFlightDataSize.Add(charged)
|
||||
newUploads := atomic.AddInt64(&s3a.inFlightUploads, 1)
|
||||
newSize := atomic.AddInt64(&s3a.inFlightDataSize, charged)
|
||||
// Update metrics
|
||||
stats.S3InFlightUploadCountGauge.Set(float64(newUploads))
|
||||
stats.S3InFlightUploadBytesGauge.Set(float64(newSize))
|
||||
|
||||
@@ -284,7 +284,7 @@ func TestLimitUploadSlotWait(t *testing.T) {
|
||||
if elapsed := time.Since(start); elapsed < 100*time.Millisecond {
|
||||
t.Fatalf("rejected after %v, before the wait timeout", elapsed)
|
||||
}
|
||||
if n := cb.s3a.inFlightUploads.Load(); n != 1 {
|
||||
if n := atomic.LoadInt64(&cb.s3a.inFlightUploads); n != 1 {
|
||||
t.Fatalf("in-flight uploads %d, want 1", n)
|
||||
}
|
||||
})
|
||||
@@ -320,7 +320,7 @@ func TestLimitUploadSlotWait(t *testing.T) {
|
||||
release := holdUploadSlot(t, cb, 1000)
|
||||
releaseOther := holdUploadSlot(t, cb, 1000)
|
||||
defer releaseOther()
|
||||
if got := cb.s3a.inFlightDataSize.Load(); got != 100 {
|
||||
if got := atomic.LoadInt64(&cb.s3a.inFlightDataSize); got != 100 {
|
||||
t.Fatalf("in-flight %d, want the budget full at 100", got)
|
||||
}
|
||||
|
||||
@@ -398,7 +398,7 @@ func TestLimitUploadSlotRejectsStalledBody(t *testing.T) {
|
||||
func putThroughLimit(cb *CircuitBreaker, req *http.Request) (code int, body string, inFlight int64) {
|
||||
inFlight = -1
|
||||
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
|
||||
inFlight = cb.s3a.inFlightDataSize.Load()
|
||||
inFlight = atomic.LoadInt64(&cb.s3a.inFlightDataSize)
|
||||
}, s3_constants.ACTION_WRITE)
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, req)
|
||||
@@ -407,12 +407,12 @@ func putThroughLimit(cb *CircuitBreaker, req *http.Request) (code int, body stri
|
||||
|
||||
func TestLimitUploadSlotNoOvershoot(t *testing.T) {
|
||||
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 10, InflightUploadDataTimeout: 50 * time.Millisecond})
|
||||
cb.s3a.inFlightDataSize.Store(8)
|
||||
cb.s3a.inFlightDataSize = 8
|
||||
code, body, _ := putThroughLimit(cb, putRequest(context.Background(), 4))
|
||||
if code != http.StatusServiceUnavailable || !strings.Contains(body, "<Code>SlowDown</Code>") {
|
||||
t.Fatalf("got %d %q, want 503 SlowDown", code, body)
|
||||
}
|
||||
if n := cb.s3a.inFlightDataSize.Load(); n != 8 {
|
||||
if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 8 {
|
||||
t.Fatalf("in-flight bytes %d, want 8", n)
|
||||
}
|
||||
}
|
||||
@@ -421,7 +421,7 @@ func TestLimitUploadSlotChargesUnknownLength(t *testing.T) {
|
||||
const limit = 1 << 20
|
||||
newCB := func(inFlight int64) *CircuitBreaker {
|
||||
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: limit, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond})
|
||||
cb.s3a.inFlightDataSize.Store(inFlight)
|
||||
cb.s3a.inFlightDataSize = inFlight
|
||||
return cb
|
||||
}
|
||||
unknown := func() *http.Request {
|
||||
@@ -440,7 +440,7 @@ func TestLimitUploadSlotChargesUnknownLength(t *testing.T) {
|
||||
if code != http.StatusOK || inFlight != limit/2 {
|
||||
t.Fatalf("idle: got %d in-flight %d, want 200 and %d", code, inFlight, limit/2)
|
||||
}
|
||||
if n := cb.s3a.inFlightDataSize.Load(); n != 0 {
|
||||
if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 0 {
|
||||
t.Fatalf("in-flight bytes %d after release, want 0", n)
|
||||
}
|
||||
}
|
||||
@@ -474,7 +474,7 @@ func TestLimitUploadSlotUsesDecodedLengthOnlyWhenUnknown(t *testing.T) {
|
||||
|
||||
func TestLimitUploadSlotAdmitsHugeObjectBesideSmallOnes(t *testing.T) {
|
||||
cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 64 << 20, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond})
|
||||
cb.s3a.inFlightDataSize.Store(32 << 20)
|
||||
cb.s3a.inFlightDataSize = 32 << 20
|
||||
req := putRequest(context.Background(), 1)
|
||||
req.ContentLength = 5 << 30
|
||||
code, _, inFlight := putThroughLimit(cb, req)
|
||||
@@ -506,7 +506,7 @@ func TestLimitBucketBytesCounterSymmetricForUnknownLength(t *testing.T) {
|
||||
var during, budget int64
|
||||
h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) {
|
||||
during = atomic.LoadInt64(cb.counters[key])
|
||||
budget = cb.s3a.inFlightDataSize.Load()
|
||||
budget = atomic.LoadInt64(&cb.s3a.inFlightDataSize)
|
||||
}, s3_constants.ACTION_WRITE)
|
||||
h(httptest.NewRecorder(), req)
|
||||
if during != tc.want {
|
||||
@@ -545,7 +545,7 @@ func TestLimitBucketBytesRejectsDeclaredOversizedPut(t *testing.T) {
|
||||
if n := atomic.LoadInt64(cb.counters[key]); n != 0 {
|
||||
t.Fatalf("bucket counter after rejection %d, want 0", n)
|
||||
}
|
||||
if n := cb.s3a.inFlightDataSize.Load(); n != 0 {
|
||||
if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 0 {
|
||||
t.Fatalf("upload budget after rejection %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2693,6 +2693,12 @@ func (iam *IdentityAccessManagement) AuthorizeIamAction(r *http.Request, identit
|
||||
if identity == nil || identity.Name == s3_constants.AccountAnonymousId {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if !iam.selfServiceRequiresGrant && iamRequiresAdminForOthers(action) && (targetUserName == "" || targetUserName == identity.Name) {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if identity.isAdmin() {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
// Self-target actions authorize against the target identity's ARN. The
|
||||
// account segment stays empty so existing arn:aws:iam:::* wildcard
|
||||
// grants keep matching.
|
||||
@@ -2707,15 +2713,6 @@ func (iam *IdentityAccessManagement) AuthorizeIamAction(r *http.Request, identit
|
||||
}
|
||||
resource = fmt.Sprintf("arn:aws:iam:::user/%s", target)
|
||||
}
|
||||
if !identity.allowsPermissionBoundary(r, Action("iam:"+action), resource, "") {
|
||||
return s3err.ErrAccessDenied
|
||||
}
|
||||
if !iam.selfServiceRequiresGrant && iamRequiresAdminForOthers(action) && (targetUserName == "" || targetUserName == identity.Name) {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if identity.isAdmin() {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
return iam.VerifyActionPermission(r, identity, Action("iam:"+action), resource, "")
|
||||
}
|
||||
|
||||
|
||||
@@ -2499,26 +2499,6 @@ func (s3a *S3ApiServer) addSSEResponseHeadersFromEntry(w http.ResponseWriter, r
|
||||
}
|
||||
}
|
||||
|
||||
// objectContentType is the Content-Type GET and HEAD send for entry, and a
|
||||
// metadata=true listing shows: the stored type, else inode/symlink for a
|
||||
// symlink, else one guessed from the name.
|
||||
func objectContentType(entry *filer_pb.Entry) string {
|
||||
mimeType := entry.GetAttributes().GetMime()
|
||||
if mimeType == "" && os.FileMode(entry.GetAttributes().GetFileMode())&os.ModeSymlink != 0 {
|
||||
// The name says nothing about an empty body; call it what file(1) does.
|
||||
mimeType = s3_constants.SymlinkContentType
|
||||
}
|
||||
if mimeType == "" && entry.GetName() != "" {
|
||||
if ext := filepath.Ext(entry.GetName()); ext != "" {
|
||||
mimeType = mime.TypeByExtension(ext)
|
||||
}
|
||||
}
|
||||
if mimeType == "" {
|
||||
mimeType = "application/octet-stream"
|
||||
}
|
||||
return mimeType
|
||||
}
|
||||
|
||||
// setResponseHeaders sets all standard HTTP response headers from entry metadata
|
||||
func (s3a *S3ApiServer) setResponseHeaders(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, totalSize int64) {
|
||||
// Safety check: entry must be valid
|
||||
@@ -2549,7 +2529,29 @@ func (s3a *S3ApiServer) setResponseHeaders(w http.ResponseWriter, r *http.Reques
|
||||
// object; its type and target below tell it apart from an empty file.
|
||||
isSymlink := os.FileMode(entry.GetAttributes().GetFileMode())&os.ModeSymlink != 0
|
||||
|
||||
w.Header().Set("Content-Type", objectContentType(entry))
|
||||
// Set Content-Type
|
||||
mimeType := ""
|
||||
if entry.Attributes != nil && entry.Attributes.Mime != "" {
|
||||
mimeType = entry.Attributes.Mime
|
||||
}
|
||||
if mimeType == "" && isSymlink {
|
||||
// The name says nothing about an empty body; call it what file(1) does.
|
||||
mimeType = s3_constants.SymlinkContentType
|
||||
}
|
||||
if mimeType == "" {
|
||||
// Try to detect from entry name
|
||||
if entry.Name != "" {
|
||||
ext := filepath.Ext(entry.Name)
|
||||
if ext != "" {
|
||||
mimeType = mime.TypeByExtension(ext)
|
||||
}
|
||||
}
|
||||
}
|
||||
if mimeType != "" {
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
}
|
||||
|
||||
// Set custom headers from entry.Extended (user metadata)
|
||||
// Use direct map assignment to preserve original header casing (matches proxy behavior)
|
||||
|
||||
@@ -267,12 +267,8 @@ func (s3a *S3ApiServer) extractZipObject(w http.ResponseWriter, r *http.Request,
|
||||
// must read there too — a routed read can miss a marker the owner
|
||||
// has not received yet.
|
||||
existing, existErr := s3a.getEntry(dirName, entryName)
|
||||
if errors.Is(existErr, filer_pb.ErrNotFound) {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if existErr != nil {
|
||||
glog.Errorf("extractZipObject: cannot read existing marker %s/%s: %v", bucket, memberKey, existErr)
|
||||
return s3err.ErrInternalError
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if lockErr := s3a.enforceObjectLockOnEntry(existing, bucket, memberKey, "", s3a.evaluateGovernanceBypassRequest(r, bucket, memberKey)); lockErr != nil {
|
||||
return s3err.ErrAccessDenied
|
||||
|
||||
@@ -8,14 +8,11 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func makeZipArchive(t *testing.T, members map[string]string) []byte {
|
||||
@@ -194,61 +191,3 @@ func TestExtractZipPutObjectRejectsExplicitSSE(t *testing.T) {
|
||||
t.Fatalf("entries created despite explicit SSE headers: %v", filerImpl.entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractZipOverLockedMarkerFailsClosedOnLookupError(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
absent bool
|
||||
lookupErr error
|
||||
wantErr []string
|
||||
}{
|
||||
{name: "absent", absent: true},
|
||||
{name: "locked", wantErr: []string{"zipdir: AccessDenied"}},
|
||||
{name: "lookup error", lookupErr: status.Error(codes.Unavailable, "filer unavailable"), wantErr: []string{"zipdir: InternalError"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s3a, filerImpl := newExtractTestServer(t)
|
||||
s3a.bucketConfigCache.Set("b", &BucketConfig{
|
||||
Name: "b",
|
||||
Versioning: s3_constants.VersioningEnabled,
|
||||
ObjectLockConfig: &ObjectLockConfiguration{ObjectLockEnabled: s3_constants.ObjectLockEnabled},
|
||||
})
|
||||
locked := &filer_pb.Entry{
|
||||
Name: "zipdir",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mime: "locked"},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte(s3_constants.LegalHoldOn)},
|
||||
}
|
||||
if !tc.absent {
|
||||
filerImpl.entries["/buckets/b/zipdir"] = locked
|
||||
}
|
||||
filerImpl.lookupErr, filerImpl.lookupFailKey = tc.lookupErr, "/buckets/b/zipdir"
|
||||
|
||||
body := makeZipArchive(t, map[string]string{"zipdir/": ""})
|
||||
r := httptest.NewRequest(http.MethodPut, "/b/upload.zip", bytes.NewReader(body))
|
||||
r.Header.Set(s3_constants.SeaweedFSExtract, "zip")
|
||||
rec := httptest.NewRecorder()
|
||||
s3a.extractZipObject(rec, r, "b", "upload.zip", r.Body)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var result extractZipResult
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(result.Errors, tc.wantErr) {
|
||||
t.Fatalf("errors = %v, want %v", result.Errors, tc.wantErr)
|
||||
}
|
||||
filerImpl.mu.Lock()
|
||||
defer filerImpl.mu.Unlock()
|
||||
entry := filerImpl.entries["/buckets/b/zipdir"]
|
||||
if entry == nil || !entry.IsDirectory {
|
||||
t.Fatalf("marker missing: %+v", entry)
|
||||
}
|
||||
if !tc.absent && (entry.Attributes.Mime != "locked" || string(entry.Extended[s3_constants.ExtLegalHoldKey]) != s3_constants.LegalHoldOn) {
|
||||
t.Fatalf("locked marker replaced: %+v", entry)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -123,7 +123,7 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
|
||||
requestMarker := marker
|
||||
marker = adjustMarkerForDelimiter(marker, originalPrefix, delimiter)
|
||||
|
||||
listRequest := listObjectsRequest{
|
||||
response, err := s3a.listFilerEntries(r.Context(), listObjectsRequest{
|
||||
bucket: bucket,
|
||||
prefix: originalPrefix,
|
||||
marker: marker,
|
||||
@@ -132,11 +132,7 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
|
||||
maxKeys: maxKeys,
|
||||
encodingTypeUrl: encodingTypeUrl,
|
||||
fetchOwner: fetchOwner,
|
||||
}
|
||||
if r.URL.Query().Get(listMetadataQuery) == "true" {
|
||||
listRequest.userMetadata = s3a.listMetadataFor(r, bucket)
|
||||
}
|
||||
response, err := s3a.listFilerEntries(r.Context(), listRequest)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
@@ -378,9 +374,6 @@ type listObjectsRequest struct {
|
||||
maxKeys uint16
|
||||
encodingTypeUrl bool
|
||||
fetchOwner bool
|
||||
// userMetadata, set by ListObjectsV2 metadata=true, gives a listed
|
||||
// object's UserMetadata from its key and entry.
|
||||
userMetadata func(key string, entry *filer_pb.Entry) *ListUserMetadata
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsRequest) (response ListBucketResult, err error) {
|
||||
@@ -399,19 +392,6 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
if requestDir != "" {
|
||||
reqDir = fmt.Sprintf("%s%s", bucketPrefix, requestDir)
|
||||
}
|
||||
// listItem builds the page item for entry in dir, with the object's metadata
|
||||
// when the request asked for it.
|
||||
listItem := func(entry *filer_pb.Entry, dir, dirName, entryName string, isDirectory bool) ListEntry {
|
||||
item := newListEntry(s3a, entry, "", dirName, entryName, bucketPrefix, fetchOwner, isDirectory, false)
|
||||
if req.userMetadata != nil {
|
||||
key := fmt.Sprintf("%s/%s", dir, entry.Name)[len(bucketPrefix):]
|
||||
if isDirectory {
|
||||
key += "/"
|
||||
}
|
||||
item.UserMetadata = req.userMetadata(key, entry)
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
var contents []ListEntry
|
||||
var commonPrefixes []PrefixEntry
|
||||
@@ -420,7 +400,6 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
cursor := &ListingCursor{
|
||||
maxKeys: maxKeys,
|
||||
prefixEndsOnDelimiter: prefixEndsOnDelimiter,
|
||||
readVersionFiles: req.userMetadata != nil,
|
||||
}
|
||||
|
||||
// Special case: when maxKeys = 0, return empty results immediately with IsTruncated=false
|
||||
@@ -457,7 +436,6 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
*cursor = ListingCursor{
|
||||
maxKeys: maxKeys,
|
||||
prefixEndsOnDelimiter: prefixEndsOnDelimiter,
|
||||
readVersionFiles: req.userMetadata != nil,
|
||||
}
|
||||
if delimiter != "/" {
|
||||
cursor.prefetch = newListPrefetcher(ctx, client, maxKeys)
|
||||
@@ -486,7 +464,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
if delimiter == "" && versioningErr == nil && !versioningConfigured {
|
||||
page, ok, listErr := s3a.listRecursiveFromStore(ctx, client, listObjectsRequest{
|
||||
bucket: bucket, prefix: originalPrefix, marker: originalMarker, requestMarker: requestMarker,
|
||||
maxKeys: maxKeys, encodingTypeUrl: encodingTypeUrl, fetchOwner: fetchOwner, userMetadata: req.userMetadata,
|
||||
maxKeys: maxKeys, encodingTypeUrl: encodingTypeUrl, fetchOwner: fetchOwner,
|
||||
})
|
||||
if listErr != nil {
|
||||
return listErr
|
||||
@@ -630,7 +608,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
return fmt.Errorf("settle null object %s/%s: %w", p.dir, p.name, err)
|
||||
}
|
||||
fullObjectPath := strings.TrimPrefix(p.dir+"/"+p.name, bucketPrefix)
|
||||
latest, lerr := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, versionsEntry, !cursor.readVersionFiles)
|
||||
latest, lerr := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, versionsEntry)
|
||||
switch {
|
||||
case lerr == nil:
|
||||
if prefix := prefixForKey(p.dir, p.name); prefix != "" {
|
||||
@@ -641,7 +619,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
}
|
||||
} else {
|
||||
dirName, entryName, _ := entryUrlEncode(p.dir, latest.Name, encodingTypeUrl)
|
||||
appendOrDedup(listItem(latest, p.dir, dirName, entryName, false))
|
||||
appendOrDedup(newListEntry(s3a, latest, "", dirName, entryName, bucketPrefix, fetchOwner, false, false))
|
||||
}
|
||||
case errors.Is(lerr, ErrDeleteMarker), errors.Is(lerr, filer_pb.ErrNotFound):
|
||||
cursor.retractEntry(p.dir, p.name)
|
||||
@@ -737,7 +715,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
}
|
||||
return "", fmt.Errorf("look up %s/%s%s: %w", fullDir, base, s3_constants.VersionsFolder, err)
|
||||
}
|
||||
latest, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, key, versionsEntry, !cursor.readVersionFiles)
|
||||
latest, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, key, versionsEntry)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrDeleteMarker) || errors.Is(err, filer_pb.ErrNotFound) {
|
||||
continue
|
||||
@@ -745,7 +723,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
return "", fmt.Errorf("resolve %s: %w", key, err)
|
||||
}
|
||||
dirName, entryName, _ := entryUrlEncode(fullDir, latest.Name, encodingTypeUrl)
|
||||
newEntry := listItem(latest, fullDir, dirName, entryName, false)
|
||||
newEntry := newListEntry(s3a, latest, "", dirName, entryName, bucketPrefix, fetchOwner, false, false)
|
||||
contents = append(contents, newEntry)
|
||||
added++
|
||||
}
|
||||
@@ -813,7 +791,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
addCommonPrefix(folded)
|
||||
return
|
||||
}
|
||||
appendOrDedup(listItem(entry, dir, dirName, entryName, false))
|
||||
appendOrDedup(newListEntry(s3a, entry, "", dirName, entryName, bucketPrefix, fetchOwner, false, false))
|
||||
lastEntryWasCommonPrefix = false
|
||||
}
|
||||
// The key and the prefix come off one entry, which a marker names as a
|
||||
@@ -863,13 +841,13 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
|
||||
// If no delimiter found in the directory object name, treat it as a regular key
|
||||
if !delimiterFound {
|
||||
newEntry := listItem(entry, dir, dirName, entryName, true)
|
||||
newEntry := newListEntry(s3a, entry, "", dirName, entryName, bucketPrefix, fetchOwner, true, false)
|
||||
appendOrDedup(newEntry)
|
||||
lastEntryWasCommonPrefix = false
|
||||
}
|
||||
} else if entry.IsDirectoryKeyObject() {
|
||||
// No delimiter specified, or delimiter doesn't apply - treat as regular key
|
||||
newEntry := listItem(entry, dir, dirName, entryName, true)
|
||||
newEntry := newListEntry(s3a, entry, "", dirName, entryName, bucketPrefix, fetchOwner, true, false)
|
||||
appendOrDedup(newEntry)
|
||||
lastEntryWasCommonPrefix = false
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
|
||||
@@ -952,7 +930,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
|
||||
}
|
||||
if !delimiterFound {
|
||||
glog.V(4).Infof("Adding file to contents: %s", entryName)
|
||||
newEntry := listItem(entry, dir, dirName, entryName, false)
|
||||
newEntry := newListEntry(s3a, entry, "", dirName, entryName, bucketPrefix, fetchOwner, false, false)
|
||||
appendOrDedup(newEntry)
|
||||
lastEntryWasCommonPrefix = false
|
||||
if versioningConfigured {
|
||||
@@ -1044,10 +1022,6 @@ type ListingCursor struct {
|
||||
// probeTotalBudget overrides hiddenProbeTotalBudget for the request-wide probe
|
||||
// ceiling; 0 means use the package default.
|
||||
probeTotalBudget int
|
||||
// readVersionFiles lists a versioned object from its current version's file,
|
||||
// not the pointer cached on its .versions folder, which keeps no type or user
|
||||
// metadata; a metadata=true listing needs them.
|
||||
readVersionFiles bool
|
||||
// retractEntry undoes the listing of a base-path null object once its .versions
|
||||
// sibling reveals that the current version is a delete marker.
|
||||
retractEntry func(dir, name string)
|
||||
@@ -1559,26 +1533,16 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
fullObjectPath = bucketRelativePath + "/" + baseObjectName
|
||||
}
|
||||
// Use metadata from the already-fetched .versions directory entry
|
||||
if latestVersionEntry, latestErr := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, entry, !cursor.readVersionFiles); latestErr == nil {
|
||||
if latestVersionEntry, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, entry); err == nil {
|
||||
eachEntryFn(dir, latestVersionEntry)
|
||||
} else if errors.Is(latestErr, ErrDeleteMarker) {
|
||||
} else if errors.Is(err, ErrDeleteMarker) {
|
||||
// The current version is a delete marker, so a null object listed
|
||||
// for the base path just before this directory is stale.
|
||||
if cursor.retractEntry != nil {
|
||||
cursor.retractEntry(dir, baseObjectName)
|
||||
}
|
||||
} else if errors.Is(latestErr, filer_pb.ErrNotFound) || status.Code(latestErr) == codes.NotFound {
|
||||
// Nothing current remains, so a null object listed just before
|
||||
// this directory is stale, as settlePendingNull also finds.
|
||||
if cursor.retractEntry != nil {
|
||||
cursor.retractEntry(dir, baseObjectName)
|
||||
}
|
||||
glog.V(2).Infof("Skipping versioned object %s: %v", fullObjectPath, latestErr)
|
||||
} else {
|
||||
// Skipping on any other failure would answer a page that silently
|
||||
// lacks the key; fail the listing so the client retries it.
|
||||
err = fmt.Errorf("resolve %s: %w", fullObjectPath, latestErr)
|
||||
return
|
||||
glog.V(2).Infof("Skipping versioned object %s due to error: %v", fullObjectPath, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -1776,14 +1740,6 @@ func getListObjectsV2Args(values url.Values) (prefix, startAfter, delimiter stri
|
||||
token = OptionalString{set: values.Has("continuation-token"), string: values.Get("continuation-token")}
|
||||
startAfter = values.Get("start-after")
|
||||
delimiter = values.Get("delimiter")
|
||||
if !validListParams(prefix, startAfter) {
|
||||
errCode = s3err.ErrInvalidArgument
|
||||
return
|
||||
}
|
||||
if !validListParams(decodeListContinuationToken(token.string)) {
|
||||
errCode = s3err.ErrInvalidContinuationToken
|
||||
return
|
||||
}
|
||||
if encodingTypeUrl, errCode = parseEncodingType(values); errCode != s3err.ErrNone {
|
||||
return
|
||||
}
|
||||
@@ -1801,10 +1757,6 @@ func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string,
|
||||
prefix = values.Get("prefix")
|
||||
marker = values.Get("marker")
|
||||
delimiter = values.Get("delimiter")
|
||||
if !validListParams(prefix, decodeListContinuationToken(marker)) {
|
||||
errCode = s3err.ErrInvalidArgument
|
||||
return
|
||||
}
|
||||
if encodingTypeUrl, errCode = parseEncodingType(values); errCode != s3err.ErrNone {
|
||||
return
|
||||
}
|
||||
@@ -1817,17 +1769,6 @@ func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string,
|
||||
return
|
||||
}
|
||||
|
||||
// validListParams reports whether every listing parameter is valid UTF-8, the
|
||||
// only form a filer request can carry.
|
||||
func validListParams(params ...string) bool {
|
||||
for _, p := range params {
|
||||
if !utf8.ValidString(p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// parseEncodingType reports whether encoding-type=url was requested. AWS
|
||||
// accepts no other encoding and answers anything else with InvalidArgument.
|
||||
func parseEncodingType(values url.Values) (bool, s3err.ErrorCode) {
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
// listMetadataQuery asks ListObjectsV2 for each object's metadata, MinIO's
|
||||
// extension for reading a page's metadata without a HEAD per key. Every
|
||||
// <Contents> then carries <UserMetadata> with one element per field, which
|
||||
// MinIO's SDKs (minio-go WithMetadata, minio-java includeUserMetadata,
|
||||
// minio-py include_user_meta) and `mc find --metadata` read.
|
||||
const listMetadataQuery = "metadata"
|
||||
|
||||
// ListUserMetadata is the <UserMetadata> of a listed object.
|
||||
type ListUserMetadata struct {
|
||||
Items []ListUserMetadataItem
|
||||
}
|
||||
|
||||
// ListUserMetadataItem is one field of a listed object's metadata.
|
||||
type ListUserMetadataItem struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
// MarshalXML names each element after its field, as MinIO does.
|
||||
func (m ListUserMetadata) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
||||
if len(m.Items) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := e.EncodeToken(start); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range m.Items {
|
||||
if err := e.EncodeElement(item.Value, xml.StartElement{Name: xml.Name{Local: item.Key}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return e.EncodeToken(start.End())
|
||||
}
|
||||
|
||||
// UnmarshalXML reads the elements back as fields, in order.
|
||||
func (m *ListUserMetadata) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error {
|
||||
m.Items = nil
|
||||
for {
|
||||
var field struct {
|
||||
XMLName xml.Name
|
||||
Value string `xml:",chardata"`
|
||||
}
|
||||
err := d.Decode(&field)
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.Items = append(m.Items, ListUserMetadataItem{Key: field.XMLName.Local, Value: field.Value})
|
||||
}
|
||||
}
|
||||
|
||||
// listUserMetadata is what a metadata=true listing shows for entry: the
|
||||
// Content-Type and x-amz-meta-* fields GET and HEAD send for it, keyed as MinIO
|
||||
// keys them ("content-type", "X-Amz-Meta-Name"), so a symlink lists with
|
||||
// inode/symlink and its target. A field whose name cannot be an XML element
|
||||
// name is left out.
|
||||
func listUserMetadata(entry *filer_pb.Entry) *ListUserMetadata {
|
||||
stored := make([]string, 0, len(entry.GetExtended()))
|
||||
for k := range entry.GetExtended() {
|
||||
stored = append(stored, k)
|
||||
}
|
||||
// "X-Amz-Meta-A" and "x-amz-meta-a" name one field: take the same one each time.
|
||||
sort.Strings(stored)
|
||||
fields := map[string]string{}
|
||||
for _, k := range stored {
|
||||
lower := strings.ToLower(k)
|
||||
if strings.HasPrefix(lower, "x-amz-meta-") && isXMLNameTail(lower[len("x-amz-meta-"):]) {
|
||||
fields[http.CanonicalHeaderKey(lower)] = string(entry.Extended[k])
|
||||
}
|
||||
}
|
||||
if os.FileMode(entry.GetAttributes().GetFileMode())&os.ModeSymlink != 0 {
|
||||
fields[http.CanonicalHeaderKey(s3_constants.AmzMetaSymlinkTarget)] = urlPathEscape(entry.GetAttributes().GetSymlinkTarget())
|
||||
}
|
||||
keys := make([]string, 0, len(fields))
|
||||
for k := range fields {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
m := &ListUserMetadata{Items: make([]ListUserMetadataItem, 0, len(keys)+1)}
|
||||
m.Items = append(m.Items, ListUserMetadataItem{Key: "content-type", Value: objectContentType(entry)})
|
||||
for _, k := range keys {
|
||||
m.Items = append(m.Items, ListUserMetadataItem{Key: k, Value: fields[k]})
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// isXMLNameTail reports whether s can follow "X-Amz-Meta-" in an XML element
|
||||
// name; header names allow characters such as '+' that element names do not.
|
||||
func isXMLNameTail(s string) bool {
|
||||
for _, c := range s {
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return s != ""
|
||||
}
|
||||
|
||||
// listMetadataFor returns how a metadata=true listing fills a key's
|
||||
// UserMetadata: only when the caller may read that key, as MinIO checks
|
||||
// GetObject per key, so a List grant shows no more than before. As for GET, the
|
||||
// bucket policy is decided again on the listed entry's tags. An anonymous
|
||||
// caller gets none.
|
||||
func (s3a *S3ApiServer) listMetadataFor(r *http.Request, bucket string) func(key string, entry *filer_pb.Entry) *ListUserMetadata {
|
||||
identity, _ := s3_constants.GetIdentityFromContext(r).(*Identity)
|
||||
return func(key string, entry *filer_pb.Entry) *ListUserMetadata {
|
||||
if s3a.iam != nil && s3a.iam.isEnabled() &&
|
||||
s3a.iam.authorizeObjectKeyAction(r, identity, http.MethodGet, s3_constants.ACTION_READ, bucket, key, "") != s3err.ErrNone {
|
||||
return nil
|
||||
}
|
||||
keyReq := objectKeyPolicyRequest(r, http.MethodGet, bucket, key, "")
|
||||
if code, _ := s3a.checkPolicyWithEntry(keyReq, bucket, key, string(s3_constants.ACTION_READ), "", entry.GetExtended()); code != s3err.ErrNone {
|
||||
return nil
|
||||
}
|
||||
return listUserMetadata(entry)
|
||||
}
|
||||
}
|
||||
@@ -1,535 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// minioStringMap decodes <UserMetadata> the way minio-go's StringMap does:
|
||||
// one key per child element, named after it.
|
||||
type minioStringMap map[string]string
|
||||
|
||||
func (m *minioStringMap) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error {
|
||||
*m = minioStringMap{}
|
||||
for {
|
||||
var e struct {
|
||||
XMLName xml.Name
|
||||
Value string `xml:",chardata"`
|
||||
}
|
||||
err := d.Decode(&e)
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
(*m)[e.XMLName.Local] = e.Value
|
||||
}
|
||||
}
|
||||
|
||||
type listMetadataTestPage struct {
|
||||
XMLName xml.Name `xml:"ListBucketResult"`
|
||||
Contents []struct {
|
||||
Key string `xml:"Key"`
|
||||
Size int64 `xml:"Size"`
|
||||
UserMetadata *minioStringMap `xml:"UserMetadata"`
|
||||
} `xml:"Contents"`
|
||||
}
|
||||
|
||||
func metadataTestTree() map[string][]*filer_pb.Entry {
|
||||
symlink := uint32(os.ModeSymlink | 0o777)
|
||||
dir := &filer_pb.FuseAttributes{FileMode: uint32(os.ModeDir | 0o755)}
|
||||
return map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {
|
||||
{Name: "a", IsDirectory: true, Attributes: dir},
|
||||
{Name: "b", IsDirectory: true, Attributes: dir},
|
||||
},
|
||||
"/buckets/test/a": {
|
||||
// Uploaded with a type and user metadata; the internal and xattr
|
||||
// fields must not show, nor one no XML element can be named after.
|
||||
{Name: "doc.txt", Attributes: &filer_pb.FuseAttributes{FileSize: 5, Mime: "text/plain", FileMode: 0o644},
|
||||
Content: []byte("hello"),
|
||||
Extended: map[string][]byte{
|
||||
"X-Amz-Meta-Owner": []byte("alice"),
|
||||
"x-amz-meta-legacy": []byte("v1"),
|
||||
"X-Seaweedfs-Internal-Note": []byte("secret"),
|
||||
"xattr-user.comment": []byte("hidden"),
|
||||
"X-Amz-Meta-A+b": []byte("no element name"),
|
||||
}},
|
||||
// A symlink made through a mount: no data, no stored type.
|
||||
{Name: "models", Attributes: &filer_pb.FuseAttributes{FileMode: symlink, SymlinkTarget: "/data/models/base"}},
|
||||
},
|
||||
"/buckets/test/b": { // in name order, as the filer lists
|
||||
// No stored type: the name decides, as for HEAD.
|
||||
{Name: "conf.json", Attributes: &filer_pb.FuseAttributes{FileSize: 2, FileMode: 0o644}, Content: []byte("{}")},
|
||||
{Name: "link", Attributes: &filer_pb.FuseAttributes{FileMode: symlink, SymlinkTarget: "../数据/a b"}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func metadataTestServer(t *testing.T, tree map[string][]*filer_pb.Entry) *S3ApiServer {
|
||||
t.Helper()
|
||||
filer := &recursiveFakeFiler{fakeBucketDeleteFiler: &fakeBucketDeleteFiler{entriesByDir: tree}}
|
||||
s3a := newFailoverTestServer(t, startFakeFiler(t, filer))
|
||||
s3a.option.BucketsPath = "/buckets"
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set("test", &BucketConfig{Name: "test"})
|
||||
return s3a
|
||||
}
|
||||
|
||||
// listV2 runs ListObjectsV2Handler as identity; fromStore picks the recursive
|
||||
// store read for a listing without a delimiter, otherwise the directory walk.
|
||||
func listV2(t *testing.T, s3a *S3ApiServer, identity *Identity, fromStore bool, query url.Values) (string, listMetadataTestPage) {
|
||||
t.Helper()
|
||||
if !fromStore {
|
||||
s3a.recursiveListDeclined.Store("test", time.Now().Add(time.Hour))
|
||||
defer s3a.recursiveListDeclined.Delete("test")
|
||||
}
|
||||
query.Set("list-type", "2")
|
||||
r := httptest.NewRequest(http.MethodGet, "/test?"+query.Encode(), nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "test"})
|
||||
if identity != nil {
|
||||
r = r.WithContext(s3_constants.SetIdentityInContext(r.Context(), identity))
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s3a.ListObjectsV2Handler(w, r)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
var page listMetadataTestPage
|
||||
require.NoError(t, xml.Unmarshal(w.Body.Bytes(), &page))
|
||||
return w.Body.String(), page
|
||||
}
|
||||
|
||||
func metadataByKey(page listMetadataTestPage) map[string]minioStringMap {
|
||||
got := map[string]minioStringMap{}
|
||||
for _, c := range page.Contents {
|
||||
got[c.Key] = nil
|
||||
if c.UserMetadata != nil {
|
||||
got[c.Key] = *c.UserMetadata
|
||||
}
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func TestListObjectsV2MetadataLikeMinIO(t *testing.T) {
|
||||
s3a := metadataTestServer(t, metadataTestTree())
|
||||
for _, fromStore := range []bool{true, false} {
|
||||
body, page := listV2(t, s3a, nil, fromStore, url.Values{"metadata": {"true"}})
|
||||
assert.Equal(t, map[string]minioStringMap{
|
||||
"a/doc.txt": {"content-type": "text/plain", "X-Amz-Meta-Owner": "alice", "X-Amz-Meta-Legacy": "v1"},
|
||||
"a/models": {"content-type": "inode/symlink", "X-Amz-Meta-Seaweedfs-Symlink-Target": "/data/models/base"},
|
||||
"b/link": {"content-type": "inode/symlink", "X-Amz-Meta-Seaweedfs-Symlink-Target": "../%E6%95%B0%E6%8D%AE/a%20b"},
|
||||
"b/conf.json": {"content-type": "application/json"},
|
||||
}, metadataByKey(page), "fromStore=%v", fromStore)
|
||||
assert.NotContains(t, body, "secret")
|
||||
assert.NotContains(t, body, "hidden")
|
||||
assert.NotContains(t, body, "no element name")
|
||||
assert.Contains(t, body, "<UserMetadata><content-type>inode/symlink</content-type>"+
|
||||
"<X-Amz-Meta-Seaweedfs-Symlink-Target>/data/models/base</X-Amz-Meta-Seaweedfs-Symlink-Target></UserMetadata>")
|
||||
}
|
||||
}
|
||||
|
||||
// A listed object's metadata is what HEAD sends for it.
|
||||
func TestListObjectsV2MetadataMatchesHead(t *testing.T) {
|
||||
s3a := metadataTestServer(t, metadataTestTree())
|
||||
tree := metadataTestTree()
|
||||
for _, dir := range []string{"/buckets/test/a", "/buckets/test/b"} {
|
||||
for _, entry := range tree[dir] {
|
||||
w := httptest.NewRecorder()
|
||||
s3a.setResponseHeaders(w, httptest.NewRequest(http.MethodHead, "/test/x", nil), entry, 0)
|
||||
head := map[string]string{"content-type": w.Header().Get("Content-Type")}
|
||||
for k, v := range w.Header() {
|
||||
if strings.HasPrefix(strings.ToLower(k), "x-amz-meta-") {
|
||||
head[http.CanonicalHeaderKey(k)] = v[0]
|
||||
}
|
||||
}
|
||||
delete(head, "X-Amz-Meta-A+b") // no XML element can be named so
|
||||
listed := map[string]string{}
|
||||
for _, item := range listUserMetadata(entry).Items {
|
||||
listed[item.Key] = item.Value
|
||||
}
|
||||
assert.Equal(t, head, listed, entry.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListObjectsV2WithoutMetadataIsUnchanged(t *testing.T) {
|
||||
s3a := metadataTestServer(t, metadataTestTree())
|
||||
for _, fromStore := range []bool{true, false} {
|
||||
plain, page := listV2(t, s3a, nil, fromStore, url.Values{})
|
||||
assert.NotContains(t, plain, "UserMetadata")
|
||||
assert.Len(t, page.Contents, 4)
|
||||
other, _ := listV2(t, s3a, nil, fromStore, url.Values{"metadata": {"false"}})
|
||||
assert.Equal(t, plain, other)
|
||||
}
|
||||
}
|
||||
|
||||
// As in MinIO, a key's metadata lists only for a caller that may read the key,
|
||||
// so a List grant alone shows no more than before.
|
||||
func TestListObjectsV2MetadataNeedsReadOnTheKey(t *testing.T) {
|
||||
s3a := metadataTestServer(t, metadataTestTree())
|
||||
lister := &Identity{Name: "lister", Account: &AccountAdmin, Actions: []Action{"List:test"}}
|
||||
readerA := &Identity{Name: "reader-a", Account: &AccountAdmin, Actions: []Action{"List:test", "Read:test/a/*"}}
|
||||
admin := &Identity{Name: "admin", Account: &AccountAdmin, Actions: []Action{s3_constants.ACTION_ADMIN}}
|
||||
s3a.iam = &IdentityAccessManagement{identities: []*Identity{lister, readerA, admin}}
|
||||
s3a.iam.isAuthEnabled = true
|
||||
|
||||
listedWith := func(identity *Identity, fromStore bool, query url.Values) map[string]bool {
|
||||
query.Set("metadata", "true")
|
||||
_, page := listV2(t, s3a, identity, fromStore, query)
|
||||
got := map[string]bool{}
|
||||
for _, c := range page.Contents {
|
||||
got[c.Key] = c.UserMetadata != nil
|
||||
}
|
||||
return got
|
||||
}
|
||||
for _, fromStore := range []bool{true, false} {
|
||||
assert.Equal(t, map[string]bool{"a/doc.txt": true, "a/models": true, "b/conf.json": true, "b/link": true}, listedWith(admin, fromStore, url.Values{}))
|
||||
assert.Equal(t, map[string]bool{"a/doc.txt": false, "a/models": false, "b/conf.json": false, "b/link": false}, listedWith(lister, fromStore, url.Values{}))
|
||||
assert.Equal(t, map[string]bool{"a/doc.txt": false, "a/models": false, "b/conf.json": false, "b/link": false}, listedWith(nil, fromStore, url.Values{}), "anonymous")
|
||||
assert.Equal(t, map[string]bool{"a/doc.txt": true, "a/models": true, "b/conf.json": false, "b/link": false}, listedWith(readerA, fromStore, url.Values{}))
|
||||
}
|
||||
// A delimiter page lists through the walk.
|
||||
assert.Equal(t, map[string]bool{"a/doc.txt": true, "a/models": true}, listedWith(readerA, true, url.Values{"prefix": {"a/"}, "delimiter": {"/"}}))
|
||||
assert.Equal(t, map[string]bool{"b/conf.json": false, "b/link": false}, listedWith(readerA, true, url.Values{"prefix": {"b/"}, "delimiter": {"/"}}))
|
||||
}
|
||||
|
||||
// Under encoding-type=url the page escapes the key, but the read check gets it
|
||||
// as stored.
|
||||
func TestListObjectsV2MetadataEncodingTypeURL(t *testing.T) {
|
||||
s3a := metadataTestServer(t, map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {
|
||||
{Name: "空 link", Attributes: &filer_pb.FuseAttributes{FileMode: uint32(os.ModeSymlink | 0o777), SymlinkTarget: "../t"}},
|
||||
},
|
||||
})
|
||||
reader := &Identity{Name: "r", Account: &AccountAdmin, Actions: []Action{"List:test", "Read:test/空*"}}
|
||||
s3a.iam = &IdentityAccessManagement{identities: []*Identity{reader}}
|
||||
s3a.iam.isAuthEnabled = true
|
||||
for _, fromStore := range []bool{true, false} {
|
||||
_, page := listV2(t, s3a, reader, fromStore, url.Values{"metadata": {"true"}, "encoding-type": {"url"}})
|
||||
require.Len(t, page.Contents, 1)
|
||||
assert.Equal(t, "%E7%A9%BA+link", page.Contents[0].Key)
|
||||
require.NotNil(t, page.Contents[0].UserMetadata)
|
||||
assert.Equal(t, "../t", (*page.Contents[0].UserMetadata)["X-Amz-Meta-Seaweedfs-Symlink-Target"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestListUserMetadataRoundTrips(t *testing.T) {
|
||||
in := ListUserMetadata{Items: []ListUserMetadataItem{{Key: "content-type", Value: "a<b"}, {Key: "X-Amz-Meta-K", Value: "v&w"}}}
|
||||
out, err := xml.Marshal(struct {
|
||||
XMLName xml.Name `xml:"Contents"`
|
||||
M *ListUserMetadata `xml:"UserMetadata"`
|
||||
}{M: &in})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "<Contents><UserMetadata><content-type>a<b</content-type><X-Amz-Meta-K>v&w</X-Amz-Meta-K></UserMetadata></Contents>", string(out))
|
||||
var back struct {
|
||||
M ListUserMetadata `xml:"UserMetadata"`
|
||||
}
|
||||
require.NoError(t, xml.Unmarshal(out, &back))
|
||||
assert.Equal(t, in, back.M)
|
||||
}
|
||||
|
||||
// A bucket policy that denies GetObject on an object's tags hides that
|
||||
// object's metadata from the listing, as it fails the GET.
|
||||
func TestListObjectsV2MetadataHonorsExistingObjectTagDeny(t *testing.T) {
|
||||
tree := metadataTestTree()
|
||||
tree["/buckets/test/a"][0].Extended[s3_constants.AmzObjectTaggingPrefix+"classification"] = []byte("confidential")
|
||||
s3a := metadataTestServer(t, tree)
|
||||
reader := &Identity{Name: "reader", Account: &AccountAdmin, Actions: []Action{"List:test", "Read:test"}}
|
||||
s3a.iam = &IdentityAccessManagement{identities: []*Identity{reader}}
|
||||
s3a.iam.isAuthEnabled = true
|
||||
s3a.policyEngine = NewBucketPolicyEngine()
|
||||
s3a.iam.policyEngine = s3a.policyEngine
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("test", `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Principal": "*", "Action": ["s3:ListBucket", "s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::test", "arn:aws:s3:::test/*"]},
|
||||
{"Effect": "Deny", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::test/*",
|
||||
"Condition": {"StringEquals": {"s3:ExistingObjectTag/classification": "confidential"}}}
|
||||
]
|
||||
}`))
|
||||
for _, fromStore := range []bool{true, false} {
|
||||
body, page := listV2(t, s3a, reader, fromStore, url.Values{"metadata": {"true"}})
|
||||
got := map[string]bool{}
|
||||
for _, c := range page.Contents {
|
||||
got[c.Key] = c.UserMetadata != nil
|
||||
}
|
||||
assert.Equal(t, map[string]bool{"a/doc.txt": false, "a/models": true, "b/conf.json": true, "b/link": true}, got, "fromStore=%v", fromStore)
|
||||
assert.NotContains(t, body, "alice", "fromStore=%v", fromStore)
|
||||
}
|
||||
}
|
||||
|
||||
// On a versioned bucket the pointer cached on a .versions folder keeps no
|
||||
// type, user metadata or tags, so a metadata=true listing reads the current
|
||||
// version's file, as GET and HEAD do: the version's own fields list, and the
|
||||
// tag recheck sees the version's tags.
|
||||
func TestListObjectsV2MetadataOfTheCurrentVersion(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
versions := func(name, versionId string, size int) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Name: name + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: now, FileMode: uint32(os.ModeDir | 0o755)},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte(versionId),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_" + versionId),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte(strconv.Itoa(size)),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(`"5d41402abc4b2a76b9719d911017c592"`),
|
||||
}}
|
||||
}
|
||||
version := func(versionId, mime string, extended map[string]string) *filer_pb.Entry {
|
||||
e := &filer_pb.Entry{Name: "v_" + versionId, Content: []byte("hello"),
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 5, Mtime: now, Mime: mime, FileMode: 0o644},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte(versionId)}}
|
||||
for k, v := range extended {
|
||||
e.Extended[k] = []byte(v)
|
||||
}
|
||||
return e
|
||||
}
|
||||
s3a := metadataTestServer(t, map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {versions("doc.txt", "v1", 5), versions("hid.txt", "v2", 5)},
|
||||
"/buckets/test/doc.txt" + s3_constants.VersionsFolder: {version("v1", "text/csv", map[string]string{"X-Amz-Meta-Owner": "bob"})},
|
||||
"/buckets/test/hid.txt" + s3_constants.VersionsFolder: {version("v2", "text/csv", map[string]string{
|
||||
"X-Amz-Meta-Owner": "carol", s3_constants.AmzObjectTaggingPrefix + "classification": "confidential"})},
|
||||
})
|
||||
s3a.bucketConfigCache.Set("test", &BucketConfig{Name: "test", Versioning: s3_constants.VersioningEnabled})
|
||||
reader := &Identity{Name: "reader", Account: &AccountAdmin, Actions: []Action{"List:test", "Read:test"}}
|
||||
s3a.iam = &IdentityAccessManagement{identities: []*Identity{reader}}
|
||||
s3a.iam.isAuthEnabled = true
|
||||
s3a.policyEngine = NewBucketPolicyEngine()
|
||||
s3a.iam.policyEngine = s3a.policyEngine
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("test", `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Principal": "*", "Action": ["s3:ListBucket", "s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::test", "arn:aws:s3:::test/*"]},
|
||||
{"Effect": "Deny", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::test/*",
|
||||
"Condition": {"StringEquals": {"s3:ExistingObjectTag/classification": "confidential"}}}
|
||||
]
|
||||
}`))
|
||||
|
||||
body, page := listV2(t, s3a, reader, true, url.Values{"metadata": {"true"}})
|
||||
assert.Equal(t, map[string]minioStringMap{"doc.txt": {"content-type": "text/csv", "X-Amz-Meta-Owner": "bob"}, "hid.txt": nil}, metadataByKey(page))
|
||||
assert.NotContains(t, body, "carol")
|
||||
plain, page := listV2(t, s3a, reader, true, url.Values{})
|
||||
assert.NotContains(t, plain, "UserMetadata")
|
||||
assert.Len(t, page.Contents, 2)
|
||||
}
|
||||
|
||||
// A .versions pointer that names the current version's file without the cached
|
||||
// size, mtime and ETag lists the object from that file, found in "<key>.versions".
|
||||
func TestListVersionedObjectFromItsVersionFile(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
s3a := metadataTestServer(t, map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {{Name: "doc.txt" + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: now, FileMode: uint32(os.ModeDir | 0o755)},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v1"),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_v1"),
|
||||
}}},
|
||||
"/buckets/test/doc.txt" + s3_constants.VersionsFolder: {{Name: "v_v1", Content: []byte("hello"),
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 5, Mtime: now, FileMode: 0o644},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte("v1")}}},
|
||||
})
|
||||
s3a.bucketConfigCache.Set("test", &BucketConfig{Name: "test", Versioning: s3_constants.VersioningEnabled})
|
||||
_, page := listV2(t, s3a, nil, true, url.Values{})
|
||||
require.Len(t, page.Contents, 1)
|
||||
assert.Equal(t, "doc.txt", page.Contents[0].Key)
|
||||
assert.Equal(t, int64(5), page.Contents[0].Size)
|
||||
}
|
||||
|
||||
// lookupFailingFiler fails lookups in one directory (of one name, if set),
|
||||
// as a filer that cannot be read for a moment.
|
||||
type lookupFailingFiler struct {
|
||||
*recursiveFakeFiler
|
||||
failDir, failName string
|
||||
}
|
||||
|
||||
func (f *lookupFailingFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
if req.Directory == f.failDir && (f.failName == "" || req.Name == f.failName) {
|
||||
return nil, status.Error(codes.PermissionDenied, "injected lookup failure")
|
||||
}
|
||||
return f.recursiveFakeFiler.LookupDirectoryEntry(ctx, req)
|
||||
}
|
||||
|
||||
// lookupMissingFiler answers one entry as missing to lookups while listings
|
||||
// still return it, as when it is removed during a listing.
|
||||
type lookupMissingFiler struct {
|
||||
*recursiveFakeFiler
|
||||
dir, name string
|
||||
}
|
||||
|
||||
func (f *lookupMissingFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
if req.Directory == f.dir && req.Name == f.name {
|
||||
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
return f.recursiveFakeFiler.LookupDirectoryEntry(ctx, req)
|
||||
}
|
||||
|
||||
// With metadata=true every versioned key reads its version file. A version
|
||||
// file removed since the pointer was written skips the key, as a missing
|
||||
// object would; any other failure fails the listing rather than answering a
|
||||
// page that silently lacks the key.
|
||||
func TestListObjectsV2MetadataVersionFileLookup(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
tree := func() map[string][]*filer_pb.Entry {
|
||||
return map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {
|
||||
{Name: "a.txt", Content: []byte("a"), Attributes: &filer_pb.FuseAttributes{FileSize: 1, Mtime: now, FileMode: 0o644}},
|
||||
{Name: "doc.txt" + s3_constants.VersionsFolder, IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: now, FileMode: uint32(os.ModeDir | 0o755)},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("v1"),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_v1"),
|
||||
s3_constants.ExtLatestVersionSizeKey: []byte("5"),
|
||||
s3_constants.ExtLatestVersionMtimeKey: []byte(strconv.FormatInt(now, 10)),
|
||||
s3_constants.ExtLatestVersionETagKey: []byte(`"5d41402abc4b2a76b9719d911017c592"`),
|
||||
}},
|
||||
},
|
||||
}
|
||||
}
|
||||
server := func(t *testing.T, filer filer_pb.SeaweedFilerServer) *S3ApiServer {
|
||||
s3a := newFailoverTestServer(t, startFakeFiler(t, filer))
|
||||
s3a.option.BucketsPath = "/buckets"
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set("test", &BucketConfig{Name: "test", Versioning: s3_constants.VersioningEnabled})
|
||||
return s3a
|
||||
}
|
||||
list := func(t *testing.T, s3a *S3ApiServer, query url.Values) (int, string) {
|
||||
query.Set("list-type", "2")
|
||||
r := httptest.NewRequest(http.MethodGet, "/test?"+query.Encode(), nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "test"})
|
||||
w := httptest.NewRecorder()
|
||||
s3a.ListObjectsV2Handler(w, r)
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
|
||||
t.Run("version file gone", func(t *testing.T) {
|
||||
s3a := server(t, &recursiveFakeFiler{fakeBucketDeleteFiler: &fakeBucketDeleteFiler{entriesByDir: tree()}})
|
||||
code, body := list(t, s3a, url.Values{"metadata": {"true"}})
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
assert.Contains(t, body, "<Key>a.txt</Key>")
|
||||
assert.NotContains(t, body, "<Key>doc.txt</Key>")
|
||||
// Without metadata the cached pointer still lists it.
|
||||
code, body = list(t, s3a, url.Values{})
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
assert.Contains(t, body, "<Key>doc.txt</Key>")
|
||||
})
|
||||
t.Run("stale pointer lists the version that remains", func(t *testing.T) {
|
||||
// The null object lists before its .versions sibling, whose pointer names
|
||||
// a removed file; the remaining v1 is newer than the null object.
|
||||
stale := tree()
|
||||
stale["/buckets/test"] = []*filer_pb.Entry{
|
||||
{Name: "doc.txt", Content: []byte("old"),
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 3, Mtime: now - 100, FileMode: 0o644},
|
||||
Extended: map[string][]byte{"X-Amz-Meta-Owner": []byte("null-owner")}},
|
||||
stale["/buckets/test"][1],
|
||||
{Name: "z.txt", Content: []byte("z"), Attributes: &filer_pb.FuseAttributes{FileSize: 1, Mtime: now, FileMode: 0o644}},
|
||||
}
|
||||
stale["/buckets/test"][1].Extended[s3_constants.ExtLatestVersionIdKey] = []byte("v2")
|
||||
stale["/buckets/test"][1].Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte("v_v2")
|
||||
stale["/buckets/test/doc.txt"+s3_constants.VersionsFolder] = []*filer_pb.Entry{{Name: "v_v1", Content: []byte("hello"),
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 5, Mtime: now, FileMode: 0o644},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte("v1"), "X-Amz-Meta-Owner": []byte("v1-owner")}}}
|
||||
s3a := server(t, &recursiveFakeFiler{fakeBucketDeleteFiler: &fakeBucketDeleteFiler{entriesByDir: stale}})
|
||||
code, body := list(t, s3a, url.Values{"metadata": {"true"}})
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
var page listMetadataTestPage
|
||||
require.NoError(t, xml.Unmarshal([]byte(body), &page))
|
||||
assert.Equal(t, map[string]minioStringMap{
|
||||
"doc.txt": {"content-type": "text/plain; charset=utf-8", "X-Amz-Meta-Owner": "v1-owner"},
|
||||
"z.txt": {"content-type": "text/plain; charset=utf-8"},
|
||||
}, metadataByKey(page))
|
||||
assert.Len(t, page.Contents, 2)
|
||||
})
|
||||
t.Run("null object removed during the listing", func(t *testing.T) {
|
||||
// The walk saw the null object, but by the time the stale pointer is
|
||||
// rescanned it is gone too and no version remains: the key is retracted.
|
||||
gone := tree()
|
||||
gone["/buckets/test"] = []*filer_pb.Entry{
|
||||
{Name: "doc.txt", Content: []byte("old"), Attributes: &filer_pb.FuseAttributes{FileSize: 3, Mtime: now - 100, FileMode: 0o644}},
|
||||
gone["/buckets/test"][1],
|
||||
{Name: "z.txt", Content: []byte("z"), Attributes: &filer_pb.FuseAttributes{FileSize: 1, Mtime: now, FileMode: 0o644}},
|
||||
}
|
||||
s3a := server(t, &lookupMissingFiler{
|
||||
recursiveFakeFiler: &recursiveFakeFiler{fakeBucketDeleteFiler: &fakeBucketDeleteFiler{entriesByDir: gone}},
|
||||
dir: "/buckets/test", name: "doc.txt",
|
||||
})
|
||||
code, body := list(t, s3a, url.Values{"metadata": {"true"}})
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
assert.NotContains(t, body, "<Key>doc.txt</Key>")
|
||||
assert.Contains(t, body, "<Key>z.txt</Key>")
|
||||
})
|
||||
t.Run("stale pointer beside a directory", func(t *testing.T) {
|
||||
// "doc.txt/" holds a child key and is newer than the remaining v1; it is
|
||||
// not a null object of "doc.txt", so v1 stays the key's current version.
|
||||
withDir := tree()
|
||||
withDir["/buckets/test"] = []*filer_pb.Entry{
|
||||
{Name: "doc.txt", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mtime: now + 100, FileMode: uint32(os.ModeDir | 0o755)}},
|
||||
withDir["/buckets/test"][1],
|
||||
}
|
||||
withDir["/buckets/test"][1].Extended[s3_constants.ExtLatestVersionIdKey] = []byte("v2")
|
||||
withDir["/buckets/test"][1].Extended[s3_constants.ExtLatestVersionFileNameKey] = []byte("v_v2")
|
||||
withDir["/buckets/test/doc.txt"] = []*filer_pb.Entry{{Name: "child", Content: []byte("c"),
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 1, Mtime: now, FileMode: 0o644}}}
|
||||
withDir["/buckets/test/doc.txt"+s3_constants.VersionsFolder] = []*filer_pb.Entry{{Name: "v_v1", Content: []byte("hello"),
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 5, Mtime: now, FileMode: 0o644},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte("v1"), "X-Amz-Meta-Owner": []byte("v1-owner")}}}
|
||||
s3a := server(t, &recursiveFakeFiler{fakeBucketDeleteFiler: &fakeBucketDeleteFiler{entriesByDir: withDir}})
|
||||
code, body := list(t, s3a, url.Values{"metadata": {"true"}})
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
var page listMetadataTestPage
|
||||
require.NoError(t, xml.Unmarshal([]byte(body), &page))
|
||||
assert.Equal(t, map[string]minioStringMap{
|
||||
"doc.txt": {"content-type": "text/plain; charset=utf-8", "X-Amz-Meta-Owner": "v1-owner"},
|
||||
"doc.txt/child": {"content-type": "application/octet-stream"},
|
||||
}, metadataByKey(page))
|
||||
})
|
||||
t.Run("null object unreadable during the listing", func(t *testing.T) {
|
||||
// A failed read of the null object is not its absence: retracting the
|
||||
// key would page past an object that still exists.
|
||||
unreadable := tree()
|
||||
unreadable["/buckets/test"] = []*filer_pb.Entry{
|
||||
{Name: "doc.txt", Content: []byte("old"), Attributes: &filer_pb.FuseAttributes{FileSize: 3, Mtime: now - 100, FileMode: 0o644}},
|
||||
unreadable["/buckets/test"][1],
|
||||
{Name: "z.txt", Content: []byte("z"), Attributes: &filer_pb.FuseAttributes{FileSize: 1, Mtime: now, FileMode: 0o644}},
|
||||
}
|
||||
s3a := server(t, &lookupFailingFiler{
|
||||
recursiveFakeFiler: &recursiveFakeFiler{fakeBucketDeleteFiler: &fakeBucketDeleteFiler{entriesByDir: unreadable}},
|
||||
failDir: "/buckets/test", failName: "doc.txt",
|
||||
})
|
||||
code, body := list(t, s3a, url.Values{"metadata": {"true"}})
|
||||
assert.Equal(t, http.StatusInternalServerError, code, body)
|
||||
})
|
||||
t.Run("version file unreadable", func(t *testing.T) {
|
||||
withFile := tree()
|
||||
withFile["/buckets/test/doc.txt"+s3_constants.VersionsFolder] = []*filer_pb.Entry{{Name: "v_v1", Content: []byte("hello"),
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 5, Mtime: now, FileMode: 0o644},
|
||||
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte("v1")}}}
|
||||
s3a := server(t, &lookupFailingFiler{
|
||||
recursiveFakeFiler: &recursiveFakeFiler{fakeBucketDeleteFiler: &fakeBucketDeleteFiler{entriesByDir: withFile}},
|
||||
failDir: "/buckets/test/doc.txt" + s3_constants.VersionsFolder,
|
||||
})
|
||||
code, body := list(t, s3a, url.Values{"metadata": {"true"}})
|
||||
assert.Equal(t, http.StatusInternalServerError, code, body)
|
||||
code, body = list(t, s3a, url.Values{})
|
||||
require.Equal(t, http.StatusOK, code, body)
|
||||
assert.Contains(t, body, "<Key>doc.txt</Key>")
|
||||
})
|
||||
}
|
||||
@@ -223,11 +223,7 @@ func (p *recursiveListPage) append(key, dir string, entry *filer_pb.Entry, isDir
|
||||
return
|
||||
}
|
||||
dirName, entryName, _ := entryUrlEncode(dir, entry.Name, p.req.encodingTypeUrl)
|
||||
item := newListEntry(p.s3a, entry, "", dirName, entryName, p.bucketPrefix, p.req.fetchOwner, isDirectory, false)
|
||||
if p.req.userMetadata != nil {
|
||||
item.UserMetadata = p.req.userMetadata(key, entry)
|
||||
}
|
||||
p.contents = append(p.contents, item)
|
||||
p.contents = append(p.contents, newListEntry(p.s3a, entry, "", dirName, entryName, p.bucketPrefix, p.req.fetchOwner, isDirectory, false))
|
||||
p.lastKey = key
|
||||
}
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
func listStatus(t *testing.T, s3a *S3ApiServer, handler func(http.ResponseWriter, *http.Request), rawQuery string) (int, string) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(http.MethodGet, "/test?"+rawQuery, nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "test"})
|
||||
w := httptest.NewRecorder()
|
||||
handler(w, r)
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
|
||||
func TestListObjectsRefusesInvalidUTF8Parameters(t *testing.T) {
|
||||
s3a := newListTokenTestServer(t, []string{"a", "\u00e9"})
|
||||
s3a.iam = &IdentityAccessManagement{}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
handler func(http.ResponseWriter, *http.Request)
|
||||
query string
|
||||
want s3err.ErrorCode
|
||||
}{
|
||||
{"v2 prefix", s3a.ListObjectsV2Handler, "list-type=2&prefix=%C3", s3err.ErrInvalidArgument},
|
||||
{"v2 start-after", s3a.ListObjectsV2Handler, "list-type=2&start-after=%C3", s3err.ErrInvalidArgument},
|
||||
{"v2 continuation-token", s3a.ListObjectsV2Handler, "list-type=2&continuation-token=%C3", s3err.ErrInvalidContinuationToken},
|
||||
{"v2 encoded continuation-token", s3a.ListObjectsV2Handler, "list-type=2&continuation-token=base64:_w", s3err.ErrInvalidContinuationToken},
|
||||
{"v1 prefix", s3a.ListObjectsV1Handler, "prefix=%C3", s3err.ErrInvalidArgument},
|
||||
{"v1 marker", s3a.ListObjectsV1Handler, "marker=%C3", s3err.ErrInvalidArgument},
|
||||
{"v1 encoded marker", s3a.ListObjectsV1Handler, "marker=base64:_w", s3err.ErrInvalidArgument},
|
||||
{"versions prefix", s3a.ListObjectVersionsHandler, "versions&prefix=%C3", s3err.ErrInvalidArgument},
|
||||
{"versions key-marker", s3a.ListObjectVersionsHandler, "versions&key-marker=%C3", s3err.ErrInvalidArgument},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
want := s3err.GetAPIError(tc.want)
|
||||
code, body := listStatus(t, s3a, tc.handler, tc.query)
|
||||
if code != want.HTTPStatusCode || !strings.Contains(body, "<Code>"+want.Code+"</Code>") ||
|
||||
!strings.Contains(body, want.Description) {
|
||||
t.Fatalf("got %d, want %d %s: %s", code, want.HTTPStatusCode, want.Description, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for _, query := range []string{"list-type=2&prefix=%C3%A9", "list-type=2&start-after=a", "list-type=2&delimiter=%C3"} {
|
||||
if code, body := listStatus(t, s3a, s3a.ListObjectsV2Handler, query); code != http.StatusOK {
|
||||
t.Fatalf("%s: got %d, want 200: %s", query, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,12 +318,8 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
// must read there too — a routed read can miss a marker the owner
|
||||
// has not received yet.
|
||||
existing, existErr := s3a.getEntry(fullDirPath, entryName)
|
||||
if errors.Is(existErr, filer_pb.ErrNotFound) {
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if existErr != nil {
|
||||
glog.Errorf("PutObjectHandler: cannot read existing marker %s/%s: %v", bucket, object, existErr)
|
||||
return s3err.ErrInternalError
|
||||
return s3err.ErrNone
|
||||
}
|
||||
if lockErr := s3a.enforceObjectLockOnEntry(existing, bucket, object, "", s3a.evaluateGovernanceBypassRequest(r, bucket, object)); lockErr != nil {
|
||||
glog.V(2).Infof("PutObjectHandler: object lock permissions check failed for %s/%s: %v", bucket, object, lockErr)
|
||||
@@ -1268,9 +1264,6 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
|
||||
glog.Warningf("putToFiler: routed PUT to %s failed for %s, falling back to lock: %v", owner, filePath, err)
|
||||
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
|
||||
createCode, routed = s3err.ErrPreconditionFailed, true
|
||||
case resp.ErrorCode == filer_pb.FilerError_ENTRY_NAME_TOO_LONG && resp.FailedMutation != nil && *resp.FailedMutation == 0:
|
||||
// The filer refuses the name before the first mutation stores anything.
|
||||
createCode, routed = s3err.ErrKeyTooLongError, true
|
||||
case resp.Error != "":
|
||||
// A mutation can store the entry before a later step of the
|
||||
// same mutation fails, so even an error from the first mutation
|
||||
|
||||
@@ -222,8 +222,6 @@ type ambiguousPutFiler struct {
|
||||
supersede *filer_pb.Entry
|
||||
txnErr error
|
||||
txnNoApply bool
|
||||
// txnResp, when set, is the transaction's answer and nothing is applied.
|
||||
txnResp *filer_pb.ObjectTransactionResponse
|
||||
// beforeCreate runs inside CreateEntry's lock, before the condition is
|
||||
// evaluated, letting a test land a racing write at the worst moment.
|
||||
// beforeLookup runs inside LookupDirectoryEntry, letting a test delete a
|
||||
@@ -341,9 +339,6 @@ func (f *ambiguousPutFiler) ObjectTransaction(_ context.Context, req *filer_pb.O
|
||||
if f.txnCheck != nil {
|
||||
f.txnCheck(req)
|
||||
}
|
||||
if f.txnResp != nil {
|
||||
return f.txnResp, nil
|
||||
}
|
||||
key := req.LockKey
|
||||
if req.ConditionKey != "" {
|
||||
key = req.ConditionKey
|
||||
@@ -1127,42 +1122,6 @@ func TestPutToFilerRoutedAmbiguousEmptyPutForeignWriteId(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A routed PUT whose name the filer refuses stored nothing, so it answers
|
||||
// KeyTooLongError whatever the body's size, and the uploaded chunks are freed.
|
||||
func TestPutToFilerRoutedNameTooLong(t *testing.T) {
|
||||
for _, body := range []string{"", "hello world"} {
|
||||
t.Run(fmt.Sprintf("%d-byte body", len(body)), func(t *testing.T) {
|
||||
volume := startFakeVolumeServer(t)
|
||||
firstMutation := int32(0)
|
||||
filerImpl := &ambiguousPutFiler{
|
||||
volume: volume,
|
||||
entries: map[string]*filer_pb.Entry{},
|
||||
txnResp: &filer_pb.ObjectTransactionResponse{
|
||||
Error: "mutation 0: entry name too long",
|
||||
ErrorCode: filer_pb.FilerError_ENTRY_NAME_TOO_LONG,
|
||||
FailedMutation: &firstMutation,
|
||||
},
|
||||
}
|
||||
filerAddr := startFakeFiler(t, filerImpl)
|
||||
s3a := newPutTestServer(t, filerAddr)
|
||||
s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, filerAddr)
|
||||
s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{filerAddr}, 1)
|
||||
|
||||
r := httptest.NewRequest(http.MethodPut, "/b/o", nil)
|
||||
_, code, _ := s3a.putToFiler(r, "/buckets/b/o", strings.NewReader(body), "b", "o", 1, 0, nil, false, "")
|
||||
if code != s3err.ErrKeyTooLongError {
|
||||
t.Fatalf("putToFiler returned %v, want KeyTooLongError", code)
|
||||
}
|
||||
if filerImpl.txnCount != 1 || filerImpl.stores != 0 {
|
||||
t.Fatalf("refused PUT was retried: %d transactions, %d creates", filerImpl.txnCount, filerImpl.stores)
|
||||
}
|
||||
if body != "" && len(volume.deleted()) == 0 {
|
||||
t.Fatal("the refused PUT's chunks were not deleted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A volume-encrypted chunk must be decrypted before SSE decryption sees it:
|
||||
// fetchChunkData feeds ciphered chunks through the cipher-aware read path and
|
||||
// slices plaintext space, while plain chunks keep streaming range reads.
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidateRetention(t *testing.T) {
|
||||
@@ -1294,50 +1293,3 @@ func TestRoutedDeleteOfLockedDeleteMarkerSkipsWormGuard(t *testing.T) {
|
||||
t.Fatalf("delete marker removal must not carry WORM guards, got %+v", cond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutDirectoryMarkerOverLockedMarkerFailsClosedOnLookupError(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
absent bool
|
||||
lookupErr error
|
||||
want int
|
||||
}{
|
||||
{name: "absent", absent: true, want: http.StatusOK},
|
||||
{name: "locked", want: http.StatusForbidden},
|
||||
{name: "lookup error", lookupErr: status.Error(codes.Unavailable, "filer unavailable"), want: http.StatusInternalServerError},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s3a, filer, _ := newHeaderTestServer(t, s3_constants.VersioningEnabled)
|
||||
s3a.bucketConfigCache.Set("b", &BucketConfig{
|
||||
Name: "b",
|
||||
Versioning: s3_constants.VersioningEnabled,
|
||||
ObjectLockConfig: &ObjectLockConfiguration{ObjectLockEnabled: s3_constants.ObjectLockEnabled},
|
||||
})
|
||||
if !tc.absent {
|
||||
filer.entries["/buckets/b/dir"] = &filer_pb.Entry{
|
||||
Name: "dir",
|
||||
IsDirectory: true,
|
||||
Content: []byte("locked"),
|
||||
Attributes: &filer_pb.FuseAttributes{},
|
||||
Extended: map[string][]byte{s3_constants.ExtLegalHoldKey: []byte(s3_constants.LegalHoldOn)},
|
||||
}
|
||||
}
|
||||
filer.lookupErr, filer.lookupFailKey = tc.lookupErr, "/buckets/b/dir"
|
||||
|
||||
req, probe := newHeaderTestRequest("/b/dir/", "dir/", "replaced", "Content-Type", "text/plain")
|
||||
s3a.PutObjectHandler(probe, req)
|
||||
|
||||
require.Equal(t, tc.want, probe.Code, probe.Body.String())
|
||||
filer.mu.Lock()
|
||||
defer filer.mu.Unlock()
|
||||
entry := filer.entries["/buckets/b/dir"]
|
||||
require.NotNil(t, entry)
|
||||
if tc.absent {
|
||||
require.Equal(t, "replaced", string(entry.Content))
|
||||
return
|
||||
}
|
||||
require.Equal(t, "locked", string(entry.Content))
|
||||
require.Equal(t, s3_constants.LegalHoldOn, string(entry.Extended[s3_constants.ExtLegalHoldKey]))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -282,9 +282,6 @@ func (s3a *S3ApiServer) routedMkFile(owner pb.ServerAddress, routeKey, parentDir
|
||||
return 0, errUploadRemoved
|
||||
}
|
||||
if resp.Error != "" {
|
||||
if sentinel := filer_pb.FilerErrorToSentinel(resp.ErrorCode); sentinel != nil {
|
||||
return 0, fmt.Errorf("routed mkfile %s/%s: %w", parentDir, name, sentinel)
|
||||
}
|
||||
return 0, fmt.Errorf("routed mkfile %s/%s: %s", parentDir, name, resp.Error)
|
||||
}
|
||||
return resp.LogTsNs, nil
|
||||
|
||||
@@ -2,7 +2,6 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -658,32 +657,6 @@ func TestRoutedMultipartFinalize(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A routed mkfile the filer refuses keeps the refusal's sentinel, so callers
|
||||
// map it as they map the same refusal from CreateEntry.
|
||||
func TestRoutedMkFileKeepsFilerErrorCode(t *testing.T) {
|
||||
firstMutation := int32(0)
|
||||
fake := &fakeTxnFiler{resp: &filer_pb.ObjectTransactionResponse{
|
||||
Error: "mutation 0: entry name too long",
|
||||
ErrorCode: filer_pb.FilerError_ENTRY_NAME_TOO_LONG,
|
||||
FailedMutation: &firstMutation,
|
||||
}}
|
||||
owner := startFakeFiler(t, fake)
|
||||
s3a := &S3ApiServer{
|
||||
option: &S3ApiServerOption{
|
||||
BucketsPath: "/buckets",
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
},
|
||||
}
|
||||
|
||||
_, err := s3a.writeMultipartObject(owner, "s3.object.write:/buckets/b/o", "/buckets/b", "o", nil, nil, nil, nil, "")
|
||||
if !errors.Is(err, filer_pb.ErrEntryNameTooLong) {
|
||||
t.Fatalf("writeMultipartObject returned %v, want ErrEntryNameTooLong", err)
|
||||
}
|
||||
if code := filerErrorToS3Error(err); code != s3err.ErrKeyTooLongError {
|
||||
t.Fatalf("filerErrorToS3Error(%v) = %v, want KeyTooLongError", err, code)
|
||||
}
|
||||
}
|
||||
|
||||
// A non-versioned multipart completion removes .uploads/<id> metadata-only in
|
||||
// the same transaction as the object's PUT.
|
||||
func TestWriteMultipartObjectRemovesUploadDir(t *testing.T) {
|
||||
|
||||
@@ -289,9 +289,6 @@ func (s3a *S3ApiServer) attachPutObjectACL(r, aclRequest *http.Request, metadata
|
||||
// Multipart parts do not carry this PutObject context.
|
||||
func applyPutObjectACL(r *http.Request, entry *filer_pb.Entry) {
|
||||
metadata, _ := r.Context().Value(putObjectACLContextKey{}).(putObjectACLMetadata)
|
||||
if len(metadata.extended) > 0 && entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte, len(metadata.extended))
|
||||
}
|
||||
for key, value := range metadata.extended {
|
||||
entry.Extended[key] = value
|
||||
}
|
||||
|
||||
@@ -2026,10 +2026,6 @@ func (s3a *S3ApiServer) ListObjectVersionsHandler(w http.ResponseWriter, r *http
|
||||
keyMarker := decodeListContinuationToken(query.Get("key-marker"))
|
||||
versionIdMarker := query.Get("version-id-marker")
|
||||
delimiter := query.Get("delimiter")
|
||||
if !validListParams(prefix, keyMarker) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidArgument)
|
||||
return
|
||||
}
|
||||
|
||||
encodingTypeUrl, errCode := parseEncodingType(query)
|
||||
if errCode != s3err.ErrNone {
|
||||
@@ -2591,11 +2587,8 @@ func (s3a *S3ApiServer) conditionalUpdateEntry(directory string, entry, expected
|
||||
// - Before: N×1 to N×12 find operations per list
|
||||
// - After: 0 extra find operations (all metadata cached in .versions directory)
|
||||
//
|
||||
// Without useCached it reads the version file even when the cached metadata is
|
||||
// complete, since that keeps no type or user metadata.
|
||||
//
|
||||
// Returns ErrDeleteMarker if the latest version is a delete marker (expected condition, not an error).
|
||||
func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object string, versionsDirEntry *filer_pb.Entry, useCached bool) (*filer_pb.Entry, error) {
|
||||
func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object string, versionsDirEntry *filer_pb.Entry) (*filer_pb.Entry, error) {
|
||||
// Defensive nil check
|
||||
if versionsDirEntry == nil {
|
||||
return nil, fmt.Errorf("nil .versions directory entry")
|
||||
@@ -2626,7 +2619,7 @@ func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object s
|
||||
mtimeBytes, hasMtime := versionsDirEntry.Extended[s3_constants.ExtLatestVersionMtimeKey]
|
||||
etagBytes, hasEtag := versionsDirEntry.Extended[s3_constants.ExtLatestVersionETagKey]
|
||||
|
||||
if useCached && hasSize && hasMtime && hasEtag {
|
||||
if hasSize && hasMtime && hasEtag {
|
||||
size, sizeErr := strconv.ParseUint(string(sizeBytes), 10, 64)
|
||||
mtime, mtimeErr := strconv.ParseInt(string(mtimeBytes), 10, 64)
|
||||
if sizeErr == nil && mtimeErr == nil {
|
||||
@@ -2684,16 +2677,11 @@ func (s3a *S3ApiServer) getLatestVersionEntryFromDirectoryEntry(bucket, object s
|
||||
glog.V(3).Infof("getLatestVersionEntryFromDirectoryEntry: fetching version file for %s/%s (no cached metadata)", bucket, normalizedObject)
|
||||
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
versionsObjectPath := normalizedObject + s3_constants.VersionsFolder
|
||||
versionsObjectPath := path.Join(normalizedObject, s3_constants.VersionsFolder)
|
||||
latestVersionPath := path.Join(versionsObjectPath, latestVersionFile)
|
||||
latestVersionEntry, err := s3a.getEntry(bucketDir, latestVersionPath)
|
||||
if err != nil {
|
||||
// The pointer names a version file that is gone: find the current
|
||||
// version by rescanning .versions/, as GET does for a stale pointer.
|
||||
if errors.Is(err, filer_pb.ErrNotFound) || status.Code(err) == codes.NotFound {
|
||||
return s3a.recoverLatestListEntryByScan(bucket, normalizedObject, nullVersionIsLatest(versionsDirEntry))
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get latest version file %s: %w", latestVersionPath, err)
|
||||
return nil, fmt.Errorf("failed to get latest version file %s: %v", latestVersionPath, err)
|
||||
}
|
||||
|
||||
// Check if this is a delete marker (should not be shown in regular list)
|
||||
@@ -2755,11 +2743,7 @@ func (s3a *S3ApiServer) recoverLatestListEntryByScan(bucket, normalizedObject st
|
||||
// nullIsLatest signal), or that the pointer has not replicated to this
|
||||
// filer while the version files have.
|
||||
regularEntry, regularErr := s3a.getObjectEntryRoutedByKey(bucket, normalizedObject)
|
||||
if regularErr != nil && !isFilerNotFound(regularErr) {
|
||||
return nil, fmt.Errorf("read %s/%s: %w", bucket, normalizedObject, regularErr)
|
||||
}
|
||||
hasNull := regularErr == nil && isNullVersionObject(regularEntry, normalizedObject)
|
||||
if hasNull && nullIsLatest {
|
||||
if regularErr == nil && nullIsLatest {
|
||||
return regularEntry, nil
|
||||
}
|
||||
|
||||
@@ -2767,7 +2751,7 @@ func (s3a *S3ApiServer) recoverLatestListEntryByScan(bucket, normalizedObject st
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if hasNull && nullObjectWins(regularEntry, latestEntry) {
|
||||
if regularErr == nil && nullObjectWins(regularEntry, latestEntry) {
|
||||
return regularEntry, nil
|
||||
}
|
||||
if latestEntry == nil {
|
||||
|
||||
@@ -134,8 +134,8 @@ type S3ApiServer struct {
|
||||
credentialManager *credential.CredentialManager
|
||||
bucketConfigCache *BucketConfigCache
|
||||
policyEngine *BucketPolicyEngine // Engine for evaluating bucket policies
|
||||
inFlightDataSize atomic.Int64
|
||||
inFlightUploads atomic.Int64
|
||||
inFlightDataSize int64
|
||||
inFlightUploads int64
|
||||
inFlightDataLimitCond *sync.Cond
|
||||
draining atomic.Bool
|
||||
embeddedIam *EmbeddedIamApi // Embedded IAM API server (when enabled)
|
||||
|
||||
@@ -426,8 +426,8 @@ func (h *STSHandlers) handleAssumeRole(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Errorf("user %s is not authorized to assume role %s", identity.Name, roleArn))
|
||||
return
|
||||
}
|
||||
if !identity.allowsPermissionBoundary(r, Action(sts.ActionAssumeRole), "", "") || h.iam.isActionExplicitlyDeniedByIAM(r, identity, callerArn, sts.ActionAssumeRole, roleArn) {
|
||||
glog.V(2).Infof("AssumeRole: identity policy denies %s assuming %s", identity.Name, roleArn)
|
||||
if h.iam.isActionExplicitlyDeniedByIAM(r, identity, callerArn, sts.ActionAssumeRole, roleArn) {
|
||||
glog.V(2).Infof("AssumeRole: identity policy explicitly denies %s assuming %s", identity.Name, roleArn)
|
||||
h.writeSTSErrorResponse(w, r, STSErrAccessDenied,
|
||||
fmt.Errorf("user %s is not authorized to assume role %s", identity.Name, roleArn))
|
||||
return
|
||||
@@ -437,7 +437,7 @@ func (h *STSHandlers) handleAssumeRole(w http.ResponseWriter, r *http.Request) {
|
||||
// session ends up with an empty role name in its assumed-role ARN.
|
||||
roleArn = h.callerPrincipalArn(identity)
|
||||
glog.V(2).Infof("AssumeRole: no RoleArn provided, defaulting to caller identity: %s", roleArn)
|
||||
if len(identity.permissionBoundary) > 0 || h.iam.VerifyActionPermission(r, identity, Action(sts.ActionAssumeRole), "", "") != s3err.ErrNone {
|
||||
if authErr := h.iam.VerifyActionPermission(r, identity, Action(sts.ActionAssumeRole), "", ""); authErr != s3err.ErrNone {
|
||||
glog.Warningf("AssumeRole: caller %s attempted to assume role without RoleArn and lacks global sts:AssumeRole permission", identity.Name)
|
||||
h.writeSTSErrorResponse(w, r, STSErrAccessDenied, fmt.Errorf("access denied"))
|
||||
return
|
||||
@@ -722,7 +722,7 @@ func (h *STSHandlers) handleGetFederationToken(w http.ResponseWriter, r *http.Re
|
||||
glog.V(2).Infof("GetFederationToken: caller identity=%s, name=%s", identity.Name, name)
|
||||
|
||||
// Check if the caller is authorized to call GetFederationToken
|
||||
if len(identity.permissionBoundary) > 0 || h.iam.VerifyActionPermission(r, identity, Action(sts.ActionGetFederationToken), "", "") != s3err.ErrNone {
|
||||
if authErr := h.iam.VerifyActionPermission(r, identity, Action(sts.ActionGetFederationToken), "", ""); authErr != s3err.ErrNone {
|
||||
glog.V(2).Infof("GetFederationToken: caller %s is not authorized to call GetFederationToken", identity.Name)
|
||||
h.writeSTSErrorResponse(w, r, STSErrAccessDenied,
|
||||
fmt.Errorf("user %s is not authorized to call GetFederationToken", identity.Name))
|
||||
|
||||
@@ -58,22 +58,7 @@ func TestAssumeRole_NonAdminCallerAuthorizedByTrustPolicy(t *testing.T) {
|
||||
Actions: []string{"Read", "Write", "List", "Tagging"},
|
||||
PolicyNames: []string{"DenyAssumeRole"},
|
||||
},
|
||||
{
|
||||
Name: "warehouse-admin",
|
||||
Actions: []string{"Admin"},
|
||||
},
|
||||
},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{{
|
||||
Id: "sa:lakekeeper:readonly",
|
||||
ParentUser: "lakekeeper",
|
||||
Actions: []string{"Read"},
|
||||
Credential: &iam_pb.Credential{AccessKey: "lakekeeperreadkey", SecretKey: "lakekeeperreadsecret"},
|
||||
}, {
|
||||
Id: "sa:warehouse-admin:sts",
|
||||
ParentUser: "warehouse-admin",
|
||||
Actions: []string{"Read", "sts:AssumeRole", "sts:GetFederationToken"},
|
||||
Credential: &iam_pb.Credential{AccessKey: "adminstskey", SecretKey: "adminstssecret"},
|
||||
}},
|
||||
}))
|
||||
stsHandlers := NewSTSHandlers(manager.GetSTSService(), iam)
|
||||
|
||||
@@ -188,43 +173,6 @@ func TestAssumeRole_NonAdminCallerAuthorizedByTrustPolicy(t *testing.T) {
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, "explicit identity-side deny must block AssumeRole even when the trust policy admits the caller")
|
||||
})
|
||||
|
||||
t.Run("restricted service account cannot assume its parent's roles", func(t *testing.T) {
|
||||
require.NoError(t, manager.CreateRole(ctx, "", "ParentWarehouse", &integration.RoleDefinition{
|
||||
RoleName: "ParentWarehouse",
|
||||
TrustPolicy: &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Principal: map[string]interface{}{"AWS": "arn:aws:iam::" + defaultAccountID + ":user/lakekeeper"},
|
||||
Action: []string{"sts:AssumeRole"},
|
||||
}},
|
||||
},
|
||||
AttachedPolicies: []string{"WarehouseAccess"},
|
||||
}))
|
||||
rec := assume(t, accessKey, secretKey, "ParentWarehouse")
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
|
||||
rec = assume(t, "lakekeeperreadkey", "lakekeeperreadsecret", "ParentWarehouse")
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
})
|
||||
|
||||
t.Run("restricted service account cannot mint a session for its parent", func(t *testing.T) {
|
||||
for _, action := range []string{"AssumeRole", "GetFederationToken"} {
|
||||
body := url.Values{"Action": {action}, "Version": {"2011-06-15"}, "RoleSessionName": {"self"}, "Name": {"self"}}.Encode()
|
||||
req, err := newTestRequest(http.MethodPost, "http://sts.seaweedfs.test/", int64(len(body)), strings.NewReader(body))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
require.NoError(t, signRequestV4(req, "adminstskey", "adminstssecret"))
|
||||
rec := httptest.NewRecorder()
|
||||
if action == "AssumeRole" {
|
||||
stsHandlers.handleAssumeRole(rec, req)
|
||||
} else {
|
||||
stsHandlers.handleGetFederationToken(rec, req)
|
||||
}
|
||||
assert.Equal(t, http.StatusForbidden, rec.Code, "%s: %s", action, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("session policy explicit deny blocks role chaining", func(t *testing.T) {
|
||||
require.NoError(t, manager.CreateRole(ctx, "", "ChainWarehouse", &integration.RoleDefinition{
|
||||
RoleName: "ChainWarehouse",
|
||||
|
||||
@@ -1149,8 +1149,6 @@ type ListEntry struct {
|
||||
Size int64 `xml:"Size"`
|
||||
Owner *CanonicalUser `xml:"Owner,omitempty"`
|
||||
StorageClass StorageClass `xml:"StorageClass"`
|
||||
// UserMetadata is filled by ListObjectsV2 with metadata=true.
|
||||
UserMetadata *ListUserMetadata `xml:"UserMetadata,omitempty"`
|
||||
}
|
||||
|
||||
func (t *ListEntry) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
||||
|
||||
@@ -148,7 +148,7 @@ func (b *fakeBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchMessageRe
|
||||
hook := b.onFetch
|
||||
b.mu.Unlock()
|
||||
if hook != nil {
|
||||
hook(req)
|
||||
hook()
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
@@ -1235,11 +1235,8 @@ func TestALeadThatLostItsLockDoesNotSend(t *testing.T) {
|
||||
s.broker.appendRecords("a", "b")
|
||||
var once sync.Once
|
||||
s.broker.mu.Lock()
|
||||
s.broker.onFetch = func(req *mq_pb.FetchMessageRequest) {
|
||||
// another partition can fetch first, so lose the lock on the records' one
|
||||
if req.Partition.RangeStart == 0 {
|
||||
once.Do(func() { s.locks.holder(ForwarderLockPrefix + "lost").held.Store(false) })
|
||||
}
|
||||
s.broker.onFetch = func() {
|
||||
once.Do(func() { s.locks.holder(ForwarderLockPrefix + "lost").held.Store(false) })
|
||||
}
|
||||
s.broker.mu.Unlock()
|
||||
s.forwarder(t, "gw1").Sync(s.registry(t, "lost"))
|
||||
|
||||
@@ -507,7 +507,7 @@ type fakeBroker struct {
|
||||
holding bool
|
||||
holdAt int64
|
||||
// onFetch runs as a fetch arrives
|
||||
onFetch func(req *mq_pb.FetchMessageRequest)
|
||||
onFetch func()
|
||||
// fetchErrorCode, when set, answers every fetch with that broker error, as a broker that cannot read the files does
|
||||
fetchErrorCode int32
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package sequence
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sync"
|
||||
)
|
||||
|
||||
@@ -20,8 +19,7 @@ func (m *MemorySequencer) NextFileId(count uint64) uint64 {
|
||||
m.sequenceLock.Lock()
|
||||
defer m.sequenceLock.Unlock()
|
||||
ret := m.counter
|
||||
// stays at the largest id rather than wrapping back to ids handed out
|
||||
m.counter += min(count, math.MaxUint64-m.counter)
|
||||
m.counter += count
|
||||
return ret
|
||||
}
|
||||
|
||||
@@ -29,6 +27,6 @@ func (m *MemorySequencer) SetMax(seenValue uint64) {
|
||||
m.sequenceLock.Lock()
|
||||
defer m.sequenceLock.Unlock()
|
||||
if m.counter <= seenValue {
|
||||
m.counter = min(seenValue, math.MaxUint64-1) + 1
|
||||
m.counter = seenValue + 1
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package sequence
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMemorySequencerStopsAtTheLargestId(t *testing.T) {
|
||||
m := NewMemorySequencer()
|
||||
m.SetMax(math.MaxUint64)
|
||||
if id := m.NextFileId(1); id != math.MaxUint64 {
|
||||
t.Fatalf("after seeing the largest id the next one is %d", id)
|
||||
}
|
||||
|
||||
m = NewMemorySequencer()
|
||||
m.SetMax(math.MaxUint64 - 2)
|
||||
if id := m.NextFileId(5); id != math.MaxUint64-1 {
|
||||
t.Fatalf("drew %d, want %d", id, uint64(math.MaxUint64-1))
|
||||
}
|
||||
if id := m.NextFileId(1); id != math.MaxUint64 {
|
||||
t.Fatalf("the sequence wrapped back to %d", id)
|
||||
}
|
||||
}
|
||||
@@ -23,21 +23,14 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/topology"
|
||||
)
|
||||
|
||||
// leaderRaftServer answers State() and takes the file id ceiling an assignment
|
||||
// records; the embedded nil interface panics if any other method is called.
|
||||
// leaderRaftServer answers only State(); the embedded nil interface panics if any
|
||||
// other method is called.
|
||||
type leaderRaftServer struct {
|
||||
raft.Server
|
||||
}
|
||||
|
||||
func (leaderRaftServer) State() string { return raft.Leader }
|
||||
|
||||
func (leaderRaftServer) Do(command raft.Command) (interface{}, error) {
|
||||
if c, ok := command.(*topology.MaxVolumeIdCommand); !ok || c.FileIdCeiling == 0 {
|
||||
panic("an assignment submitted a raft command other than its file id ceiling")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func newLeaderMaster() *MasterServer {
|
||||
topo := topology.NewTopology("test", sequence.NewMemorySequencer(), 1<<20, 5, false)
|
||||
topo.RaftServer = leaderRaftServer{}
|
||||
|
||||
@@ -66,7 +66,6 @@ func (s StateMachine) Save() ([]byte, error) {
|
||||
*state.GrowthFrozen = true
|
||||
state.GrowthFrozenAt = frozenAt
|
||||
}
|
||||
state.FileIdCeiling = s.topo.FileIdCeiling()
|
||||
glog.V(1).Infof("Save raft state %+v", state)
|
||||
return json.Marshal(state)
|
||||
}
|
||||
@@ -87,7 +86,6 @@ func (s StateMachine) Recovery(data []byte) error {
|
||||
s.topo.SetGrowthFrozen(*state.GrowthFrozen, state.GrowthFrozenAt, state.GrowthUnfreezeFor)
|
||||
}
|
||||
s.topo.SetStartedAt(state.StartedAt)
|
||||
s.topo.RaiseFileIdCeiling(state.FileIdCeiling, "")
|
||||
if err := s.topo.PersistMaxVolumeId(state.MaxVolumeId); err != nil {
|
||||
glog.Warningf("persist max volume id %d: %v", state.MaxVolumeId, err)
|
||||
}
|
||||
@@ -114,7 +112,6 @@ func (s *StateMachine) Apply(l *hashicorpRaft.Log) interface{} {
|
||||
s.topo.SetGrowthFrozen(*state.GrowthFrozen, state.GrowthFrozenAt, state.GrowthUnfreezeFor)
|
||||
}
|
||||
s.topo.SetStartedAt(state.StartedAt)
|
||||
s.topo.RaiseFileIdCeiling(state.FileIdCeiling, state.FileIdCeilingBy)
|
||||
if err := s.topo.PersistMaxVolumeId(state.MaxVolumeId); err != nil {
|
||||
glog.Warningf("persist max volume id %d: %v", state.MaxVolumeId, err)
|
||||
}
|
||||
@@ -132,7 +129,6 @@ func (s *StateMachine) Snapshot() (hashicorpRaft.FSMSnapshot, error) {
|
||||
GrowthFrozenAt: frozenAt,
|
||||
StartedAt: s.topo.GetStartedAt(),
|
||||
}
|
||||
state.FileIdCeiling = s.topo.FileIdCeiling()
|
||||
return state, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
hashicorpRaft "github.com/hashicorp/raft"
|
||||
"github.com/seaweedfs/seaweedfs/weed/sequence"
|
||||
"github.com/seaweedfs/seaweedfs/weed/topology"
|
||||
)
|
||||
|
||||
// The file ids recorded as handed out have to outlive the master that
|
||||
// recorded them: a master that recovers the raft state, from a snapshot or
|
||||
// from the log, starts its sequence past them.
|
||||
func TestRaftStateKeepsTheFileIdCeiling(t *testing.T) {
|
||||
newTopology := func() *topology.Topology {
|
||||
return topology.NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false)
|
||||
}
|
||||
|
||||
recorded := newTopology()
|
||||
recorded.RaiseFileIdCeiling(5000, "")
|
||||
snapshot, err := StateMachine{topo: recorded}.Save()
|
||||
if err != nil {
|
||||
t.Fatalf("save the raft state: %v", err)
|
||||
}
|
||||
|
||||
fromSnapshot := newTopology()
|
||||
if err := (StateMachine{topo: fromSnapshot}).Recovery(snapshot); err != nil {
|
||||
t.Fatalf("recover the raft state: %v", err)
|
||||
}
|
||||
if got := fromSnapshot.FileIdCeiling(); got != 5000 {
|
||||
t.Fatalf("ceiling %d recovered from the snapshot, want 5000", got)
|
||||
}
|
||||
if id := fromSnapshot.Sequence.NextFileId(1); id != 5000 {
|
||||
t.Fatalf("the recovered master hands out file id %d first, want 5000: the ids below may be in use", id)
|
||||
}
|
||||
|
||||
fromLog := newTopology()
|
||||
entry, _ := json.Marshal(&topology.MaxVolumeIdCommand{FileIdCeiling: 7000})
|
||||
if res := (&StateMachine{topo: fromLog}).Apply(&hashicorpRaft.Log{Data: entry}); res != nil {
|
||||
t.Fatalf("apply the log entry: %v", res)
|
||||
}
|
||||
if id := fromLog.Sequence.NextFileId(1); id != 7000 {
|
||||
t.Fatalf("a master that replayed the log hands out file id %d first, want 7000", id)
|
||||
}
|
||||
// an entry written before the ceiling existed changes nothing
|
||||
old, _ := json.Marshal(&topology.MaxVolumeIdCommand{MaxVolumeId: 3})
|
||||
(&StateMachine{topo: fromLog}).Apply(&hashicorpRaft.Log{Data: old})
|
||||
if got := fromLog.FileIdCeiling(); got != 7000 {
|
||||
t.Fatalf("ceiling %d after an entry without one, want 7000", got)
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,7 @@ func TestCopyExistingContentFillsSparseGaps(t *testing.T) {
|
||||
fs := newCopyTestServer(t, volume.Listener.Addr().String(), entries)
|
||||
|
||||
var dst bytes.Buffer
|
||||
if _, err := fs.copyExistingContent("/home/sparse.bin", &dst); err != nil {
|
||||
if err := fs.copyExistingContent("/home/sparse.bin", &dst); err != nil {
|
||||
t.Fatalf("copyExistingContent: %v", err)
|
||||
}
|
||||
want := append(append(append([]byte{}, chunkA...), make([]byte, 80)...), chunkB...)
|
||||
@@ -123,7 +123,7 @@ func TestCopyExistingContentRejectsUnreadableEntry(t *testing.T) {
|
||||
fs := newCopyTestServer(t, "", entries)
|
||||
|
||||
var dst bytes.Buffer
|
||||
if _, err := fs.copyExistingContent("/home/remote.bin", &dst); err == nil {
|
||||
if err := fs.copyExistingContent("/home/remote.bin", &dst); err == nil {
|
||||
t.Fatal("expected refusal when no local bytes exist")
|
||||
}
|
||||
}
|
||||
@@ -152,7 +152,7 @@ func TestCopyExistingContentIgnoresStaleRemoteSize(t *testing.T) {
|
||||
fs := newCopyTestServer(t, volume.Listener.Addr().String(), entries)
|
||||
|
||||
var dst bytes.Buffer
|
||||
if _, err := fs.copyExistingContent("/home/short.bin", &dst); err != nil {
|
||||
if err := fs.copyExistingContent("/home/short.bin", &dst); err != nil {
|
||||
t.Fatalf("copyExistingContent: %v", err)
|
||||
}
|
||||
if !bytes.Equal(dst.Bytes(), chunkA) {
|
||||
@@ -168,7 +168,7 @@ func TestCopyExistingContentAllHoles(t *testing.T) {
|
||||
fs := newCopyTestServer(t, "", entries)
|
||||
|
||||
var dst bytes.Buffer
|
||||
if _, err := fs.copyExistingContent("/home/holes.bin", &dst); err != nil {
|
||||
if err := fs.copyExistingContent("/home/holes.bin", &dst); err != nil {
|
||||
t.Fatalf("all-holes file: %v", err)
|
||||
}
|
||||
if dst.Len() != 10 || !bytes.Equal(dst.Bytes(), make([]byte, 10)) {
|
||||
@@ -183,7 +183,7 @@ func TestCopyExistingContentInlineAndMissing(t *testing.T) {
|
||||
fs := newCopyTestServer(t, "", entries)
|
||||
|
||||
var dst bytes.Buffer
|
||||
if _, err := fs.copyExistingContent("/home/inline.txt", &dst); err != nil {
|
||||
if err := fs.copyExistingContent("/home/inline.txt", &dst); err != nil {
|
||||
t.Fatalf("inline content: %v", err)
|
||||
}
|
||||
if got := dst.String(); got != "hello" {
|
||||
@@ -191,7 +191,7 @@ func TestCopyExistingContentInlineAndMissing(t *testing.T) {
|
||||
}
|
||||
|
||||
dst.Reset()
|
||||
if _, err := fs.copyExistingContent("/home/missing.txt", &dst); err != nil || dst.Len() != 0 {
|
||||
if err := fs.copyExistingContent("/home/missing.txt", &dst); err != nil || dst.Len() != 0 {
|
||||
t.Fatalf("missing file: err=%v written=%d", err, dst.Len())
|
||||
}
|
||||
}
|
||||
@@ -213,7 +213,7 @@ func TestCopyExistingContentTrailingGap(t *testing.T) {
|
||||
fs := newCopyTestServer(t, volume.Listener.Addr().String(), entries)
|
||||
|
||||
var dst bytes.Buffer
|
||||
if _, err := fs.copyExistingContent("/home/trailing.bin", &dst); err != nil {
|
||||
if err := fs.copyExistingContent("/home/trailing.bin", &dst); err != nil {
|
||||
t.Fatalf("copyExistingContent: %v", err)
|
||||
}
|
||||
want := append(append([]byte{}, chunkA...), make([]byte, 40)...)
|
||||
|
||||
+79
-108
@@ -1,128 +1,99 @@
|
||||
package sftpd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"github.com/seaweedfs/seaweedfs/weed/sftpd/utils"
|
||||
)
|
||||
|
||||
// downloads is what all downloads share, as in the FUSE mount: volume
|
||||
// lookups that can be invalidated, and one memory budget (the mount's
|
||||
// default -readerCacheSizeMB) for every open file's read buffers.
|
||||
type downloads struct {
|
||||
filerClient *wdclient.FilerClient
|
||||
budget *filer.ReaderCacheBudget
|
||||
type SeaweedFileReaderAt struct {
|
||||
fs *SftpServer
|
||||
entry *filer_pb.Entry
|
||||
reader io.ReadSeeker
|
||||
mu sync.Mutex
|
||||
bufferSize int
|
||||
cache *utils.LruCache
|
||||
fileSize int64
|
||||
}
|
||||
|
||||
func newDownloads(options *SFTPServiceOptions) *downloads {
|
||||
fc := wdclient.NewFilerClient([]pb.ServerAddress{options.Filer}, options.GrpcDialOption, options.DataCenter, &wdclient.FilerClientOption{
|
||||
FilerTokenSource: security.FilerAdminToken,
|
||||
})
|
||||
return &downloads{fc, filer.NewReaderCacheBudget(256 << 20)}
|
||||
func NewSeaweedFileReaderAt(fs *SftpServer, entry *filer_pb.Entry) *SeaweedFileReaderAt {
|
||||
return &SeaweedFileReaderAt{
|
||||
fs: fs,
|
||||
entry: entry,
|
||||
bufferSize: 5 * 1024 * 1024, // 5MB
|
||||
cache: utils.NewLRUCache(10), // Max 10 chunks = ~50MB
|
||||
fileSize: int64(entry.Attributes.FileSize),
|
||||
}
|
||||
}
|
||||
|
||||
// newFileReaderAt reads FileSize bytes of the file, with zeros where no
|
||||
// chunk or inline content stores data.
|
||||
func (fs *SftpServer) newFileReaderAt(ctx context.Context, absPath string, entry *filer_pb.Entry) (io.ReaderAt, error) {
|
||||
if len(entry.Content) == 0 && entry.IsInRemoteOnly() {
|
||||
var err error
|
||||
if entry, err = fs.downloadRemoteEntry(ctx, absPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
size := int64(entry.GetAttributes().GetFileSize())
|
||||
if len(entry.GetChunks()) == 0 {
|
||||
return inlineReaderAt{entry.Content, size}, nil
|
||||
}
|
||||
if fs.downloads == nil {
|
||||
return nil, fmt.Errorf("read %s: downloads are not set up", absPath)
|
||||
}
|
||||
// Like a mount's file handle: 64 MiB sections keep each read's chunk
|
||||
// lookup short however large the file is.
|
||||
dl := fs.downloads
|
||||
lookup := dl.filerClient.GetLookupFileIdFunction()
|
||||
// Resolve manifests here, under the request context and recursively.
|
||||
chunks, _, err := filer.ResolveChunkManifest(ctx, lookup, entry.GetChunks(), 0, math.MaxInt64, dl.filerClient, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", absPath, err)
|
||||
}
|
||||
group, err := filer.NewChunkGroup(lookup, (*chunk_cache.TieredChunkCache)(nil), chunks, 0, dl.filerClient, nil, dl.budget)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", absPath, err)
|
||||
}
|
||||
return chunkReaderAt{ctx, group, size}, nil
|
||||
}
|
||||
func (ra *SeaweedFileReaderAt) ReadAt(p []byte, off int64) (n int, err error) {
|
||||
ra.mu.Lock()
|
||||
defer ra.mu.Unlock()
|
||||
|
||||
// downloadRemoteEntry has the filer copy content only a remote store holds
|
||||
// into the cluster, as a mount's read does, and returns the cached entry.
|
||||
func (fs *SftpServer) downloadRemoteEntry(ctx context.Context, absPath string) (*filer_pb.Entry, error) {
|
||||
dir, name := util.FullPath(absPath).DirAndName()
|
||||
var entry *filer_pb.Entry
|
||||
err := fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.CacheRemoteObjectToLocalCluster(ctx, &filer_pb.CacheRemoteObjectToLocalClusterRequest{Directory: dir, Name: name})
|
||||
entry = resp.GetEntry()
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download %s from its remote store: %w", absPath, err)
|
||||
}
|
||||
if entry == nil || entry.IsInRemoteOnly() {
|
||||
return nil, fmt.Errorf("content of %s is not readable", absPath)
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
type chunkReaderAt struct {
|
||||
ctx context.Context
|
||||
group *filer.ChunkGroup
|
||||
size int64
|
||||
}
|
||||
|
||||
func (r chunkReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
if off < 0 {
|
||||
return 0, fmt.Errorf("negative offset %d", off)
|
||||
}
|
||||
n, _, err := r.group.ReadDataAt(r.ctx, r.size, p, off)
|
||||
if err == nil && n < len(p) {
|
||||
if off+int64(n) < r.size {
|
||||
return n, io.ErrUnexpectedEOF
|
||||
}
|
||||
err = io.EOF
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r chunkReaderAt) Close() error { return r.group.Close() }
|
||||
|
||||
// inlineReaderAt reads inline content up to size, then zeros.
|
||||
type inlineReaderAt struct {
|
||||
content []byte
|
||||
size int64
|
||||
}
|
||||
|
||||
func (r inlineReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
if off < 0 {
|
||||
return 0, fmt.Errorf("negative offset %d", off)
|
||||
}
|
||||
if off >= r.size {
|
||||
if off >= ra.fileSize {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := int(min(int64(len(p)), r.size-off))
|
||||
clear(p[:n])
|
||||
if off < int64(len(r.content)) {
|
||||
copy(p[:n], r.content[off:])
|
||||
|
||||
remaining := len(p)
|
||||
readOffset := off
|
||||
totalRead := 0
|
||||
|
||||
for remaining > 0 && readOffset < ra.fileSize {
|
||||
bufferKey := (readOffset / int64(ra.bufferSize)) * int64(ra.bufferSize)
|
||||
bufferOffset := int(readOffset - bufferKey)
|
||||
|
||||
buffer, ok := ra.cache.Get(bufferKey)
|
||||
if !ok {
|
||||
readSize := ra.bufferSize
|
||||
if bufferKey+int64(readSize) > ra.fileSize {
|
||||
readSize = int(ra.fileSize - bufferKey)
|
||||
}
|
||||
|
||||
if ra.reader == nil {
|
||||
r := filer.NewFileReader(ra.fs, ra.entry)
|
||||
if rs, ok := r.(io.ReadSeeker); ok {
|
||||
ra.reader = rs
|
||||
} else {
|
||||
return 0, fmt.Errorf("reader is not seekable")
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := ra.reader.Seek(bufferKey, io.SeekStart); err != nil {
|
||||
return 0, fmt.Errorf("seek error: %w", err)
|
||||
}
|
||||
|
||||
buffer = make([]byte, readSize)
|
||||
readBytes, err := io.ReadFull(ra.reader, buffer)
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
return 0, fmt.Errorf("read error: %w", err)
|
||||
}
|
||||
buffer = buffer[:readBytes]
|
||||
ra.cache.Put(bufferKey, buffer)
|
||||
}
|
||||
|
||||
toCopy := len(buffer) - bufferOffset
|
||||
if toCopy > remaining {
|
||||
toCopy = remaining
|
||||
}
|
||||
if toCopy <= 0 {
|
||||
break
|
||||
}
|
||||
|
||||
copy(p[totalRead:], buffer[bufferOffset:bufferOffset+toCopy])
|
||||
totalRead += toCopy
|
||||
readOffset += int64(toCopy)
|
||||
remaining -= toCopy
|
||||
}
|
||||
if n < len(p) {
|
||||
return n, io.EOF
|
||||
|
||||
if totalRead == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return n, nil
|
||||
if totalRead < len(p) {
|
||||
return totalRead, io.EOF
|
||||
}
|
||||
return totalRead, nil
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package sftpd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// A download is FileSize bytes: holes and an unstored tail read as zeros,
|
||||
// and inline content counts only up to the size.
|
||||
func TestDownloadReadsLogicalContent(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
objects := map[string][]byte{"3,01": []byte("AAAAAAAAAA"), "3,02": []byte("BBBBBBBBBB")}
|
||||
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(objects[r.URL.Path[1:]])
|
||||
}))
|
||||
t.Cleanup(volume.Close)
|
||||
rw.fs.downloads = newDownloads(&SFTPServiceOptions{Filer: rw.fs.filerAddr, GrpcDialOption: rw.fs.grpcDialOption})
|
||||
inline := func(content string, size uint64) *filer_pb.Entry {
|
||||
return &filer_pb.Entry{Content: []byte(content), Attributes: &filer_pb.FuseAttributes{FileSize: size}}
|
||||
}
|
||||
z := func(n int) string { return string(make([]byte, n)) }
|
||||
rw.fake.mu.Lock()
|
||||
rw.fake.volume = volume.Listener.Addr().String()
|
||||
files := map[string]*filer_pb.Entry{
|
||||
"gap": chunkedEntry(30, fileChunk("3,01", 0, 10), fileChunk("3,02", 20, 10)),
|
||||
"tail": chunkedEntry(15, fileChunk("3,01", 0, 10)),
|
||||
"cut": inline("abcdef", 4),
|
||||
"padded": inline("abc", 6),
|
||||
}
|
||||
for name, e := range files {
|
||||
rw.fake.entries["/buckets/b/"+name] = e
|
||||
}
|
||||
rw.fake.entries["/buckets/b/remote"] = &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{FileSize: 5}, RemoteEntry: &filer_pb.RemoteEntry{RemoteSize: 5}}
|
||||
rw.fake.mu.Unlock()
|
||||
if f, err := rw.client.Open("/b/remote"); err == nil {
|
||||
f.Close()
|
||||
t.Error("open of content an unreachable remote store holds succeeded")
|
||||
}
|
||||
for name, want := range map[string]string{
|
||||
"gap": "AAAAAAAAAA" + z(10) + "BBBBBBBBBB",
|
||||
"tail": "AAAAAAAAAA" + z(5),
|
||||
"cut": "abcd",
|
||||
"padded": "abc" + z(3),
|
||||
} {
|
||||
f, err := rw.client.Open("/b/" + name)
|
||||
if err != nil {
|
||||
t.Fatalf("open %s: %v", name, err)
|
||||
}
|
||||
// One read of everything, then one-byte reads that start inside
|
||||
// holes and inline content too.
|
||||
for _, r := range []io.Reader{io.NewSectionReader(f, 0, 1<<20), iotest.OneByteReader(io.NewSectionReader(f, 0, 1<<20))} {
|
||||
got, err := io.ReadAll(r)
|
||||
if err != nil || !bytes.Equal(got, []byte(want)) {
|
||||
t.Errorf("%s: read %q (err %v), want %q", name, got, err, want)
|
||||
}
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Errorf("%s: close: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reads at or past the end, up to the largest offset, are EOF.
|
||||
func TestDownloadEOFPastTheEnd(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
rw.fs.downloads = newDownloads(&SFTPServiceOptions{Filer: rw.fs.filerAddr, GrpcDialOption: rw.fs.grpcDialOption})
|
||||
ra, err := rw.fs.newFileReaderAt(context.Background(), "/f", chunkedEntry(30, fileChunk("3,01", 0, 10)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ra.(io.Closer).Close()
|
||||
for _, off := range []int64{30, 31, math.MaxInt64} {
|
||||
if n, err := ra.ReadAt(make([]byte, 1), off); n != 0 || err != io.EOF {
|
||||
t.Errorf("read at %d: n=%d err=%v, want EOF", off, n, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A read across the 64 MiB section boundary, after a section with no
|
||||
// chunks, joins both sides; the tail past the last chunk is zeros.
|
||||
func TestDownloadAcrossSections(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
objects := map[string][]byte{"3,01": []byte("AAAAAAAAAA"), "3,02": []byte("BBBBBBBBBB")}
|
||||
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(objects[r.URL.Path[1:]])
|
||||
}))
|
||||
t.Cleanup(volume.Close)
|
||||
rw.fake.mu.Lock()
|
||||
rw.fake.volume = volume.Listener.Addr().String()
|
||||
rw.fake.mu.Unlock()
|
||||
rw.fs.downloads = newDownloads(&SFTPServiceOptions{Filer: rw.fs.filerAddr, GrpcDialOption: rw.fs.grpcDialOption})
|
||||
const boundary = filer.SectionSize * 2 // the first two sections hold no chunk
|
||||
ra, err := rw.fs.newFileReaderAt(context.Background(), "/f", chunkedEntry(boundary+15, fileChunk("3,01", boundary-10, 10), fileChunk("3,02", boundary, 10)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ra.(io.Closer).Close()
|
||||
got := make([]byte, 30)
|
||||
n, err := ra.ReadAt(got, boundary-10)
|
||||
if want := "AAAAAAAAAABBBBBBBBBB\x00\x00\x00\x00\x00"; string(got[:n]) != want || err != io.EOF {
|
||||
t.Errorf("read across the boundary = %q (err %v), want %q and EOF", got[:n], err, want)
|
||||
}
|
||||
n, err = ra.ReadAt(got[:10], 5)
|
||||
if string(got[:n]) != string(make([]byte, 10)) || err != nil {
|
||||
t.Errorf("read in an empty section = %q (err %v), want zeros", got[:n], err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInlineReaderRefusesNegativeOffset(t *testing.T) {
|
||||
if _, err := (inlineReaderAt{[]byte("abc"), 3}).ReadAt(make([]byte, 1), -1); err == nil {
|
||||
t.Error("read at a negative offset succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func (f *lockTestFiler) CacheRemoteObjectToLocalCluster(_ context.Context, req *filer_pb.CacheRemoteObjectToLocalClusterRequest) (*filer_pb.CacheRemoteObjectToLocalClusterResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
key := req.Directory + "/" + req.Name
|
||||
cached, ok := f.remote[key]
|
||||
if !ok {
|
||||
return nil, status.Error(codes.Unavailable, "remote store unreachable")
|
||||
}
|
||||
f.entries[key] = cached
|
||||
return &filer_pb.CacheRemoteObjectToLocalClusterResponse{Entry: cached}, nil
|
||||
}
|
||||
|
||||
// Content only a remote store holds is cached into the cluster on open, as
|
||||
// a mount's read does, then read from the cached chunks.
|
||||
func TestDownloadCachesRemoteOnlyContent(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("AAAAAAAAAA"))
|
||||
}))
|
||||
t.Cleanup(volume.Close)
|
||||
rw.fs.downloads = newDownloads(&SFTPServiceOptions{Filer: rw.fs.filerAddr, GrpcDialOption: rw.fs.grpcDialOption})
|
||||
remote := &filer_pb.RemoteEntry{RemoteSize: 10}
|
||||
cached := chunkedEntry(10, fileChunk("3,01", 0, 10))
|
||||
cached.RemoteEntry = remote
|
||||
rw.fake.mu.Lock()
|
||||
rw.fake.volume = volume.Listener.Addr().String()
|
||||
rw.fake.entries["/buckets/b/remote"] = &filer_pb.Entry{Name: "remote", Attributes: &filer_pb.FuseAttributes{FileSize: 10, FileMode: 0o644}, RemoteEntry: remote}
|
||||
rw.fake.remote = map[string]*filer_pb.Entry{"/buckets/b/remote": cached}
|
||||
rw.fake.mu.Unlock()
|
||||
f, err := rw.client.Open("/b/remote")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
if got, err := io.ReadAll(f); err != nil || string(got) != "AAAAAAAAAA" {
|
||||
t.Errorf("read %q (err %v), want the cached content", got, err)
|
||||
}
|
||||
}
|
||||
@@ -61,17 +61,6 @@ type SeaweedSftpFileWriter struct {
|
||||
offset int64
|
||||
closed bool
|
||||
setStats []fileStat // attributes set while the upload buffered
|
||||
// changed is set by every write and setstat; with
|
||||
// skipUploadIfUnchanged, Close uploads only when it is set.
|
||||
changed bool
|
||||
skipUploadIfUnchanged bool
|
||||
// readErr, when set, is returned by every read: the user may write the
|
||||
// file but not read it.
|
||||
readErr error
|
||||
// With APPEND, writes below appendFrom are refused. Offsets are kept:
|
||||
// pkg/sftp may run pipelined writes in any order.
|
||||
append bool
|
||||
appendFrom int64
|
||||
}
|
||||
|
||||
type fileStat struct {
|
||||
@@ -99,15 +88,20 @@ func (fs *SftpServer) untrackUpload(w *SeaweedSftpFileWriter) {
|
||||
}
|
||||
}
|
||||
|
||||
// openUpload returns the upload open on absPath. A setstat names only the
|
||||
// path, so with several uploads open there it cannot tell which one it is for.
|
||||
func (fs *SftpServer) openUpload(absPath string) *SeaweedSftpFileWriter {
|
||||
// openUpload returns the upload open on absPath, or nil. A setstat names only
|
||||
// the path, so with several uploads open there it cannot tell which one it is
|
||||
// for and is refused.
|
||||
func (fs *SftpServer) openUpload(absPath string) (*SeaweedSftpFileWriter, error) {
|
||||
fs.uploadsMu.Lock()
|
||||
defer fs.uploadsMu.Unlock()
|
||||
if open := fs.uploads[absPath]; len(open) == 1 {
|
||||
return open[0]
|
||||
switch open := fs.uploads[absPath]; len(open) {
|
||||
case 0:
|
||||
return nil, nil
|
||||
case 1:
|
||||
return open[0], nil
|
||||
default:
|
||||
return nil, fmt.Errorf("%s has %d uploads open: %w", absPath, len(open), sftp.ErrSSHFxFailure)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setStat takes an fsetstat on the handle of a buffering upload, whose entry
|
||||
@@ -123,10 +117,8 @@ func (w *SeaweedSftpFileWriter) setStat(flags sftp.FileAttrFlags, attrs *sftp.Fi
|
||||
if err := w.tmpFile.Truncate(int64(attrs.Size)); err != nil {
|
||||
return true, err
|
||||
}
|
||||
w.appendFrom = min(w.appendFrom, int64(attrs.Size))
|
||||
flags.Size = false
|
||||
}
|
||||
w.changed = true // the upload on close applies it
|
||||
w.setStats = append(w.setStats, fileStat{flags: flags, attrs: attrs})
|
||||
return true, nil
|
||||
}
|
||||
@@ -134,7 +126,6 @@ func (w *SeaweedSftpFileWriter) setStat(flags sftp.FileAttrFlags, attrs *sftp.Fi
|
||||
func (w *SeaweedSftpFileWriter) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.changed = true
|
||||
n, err := w.tmpFile.WriteAt(p, w.offset)
|
||||
w.offset += int64(n)
|
||||
return n, err
|
||||
@@ -143,24 +134,9 @@ func (w *SeaweedSftpFileWriter) Write(p []byte) (int, error) {
|
||||
func (w *SeaweedSftpFileWriter) WriteAt(p []byte, off int64) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.append && off < w.appendFrom {
|
||||
return 0, fmt.Errorf("append to %s: write at offset %d is below the end of the file", w.req.Filepath, off)
|
||||
}
|
||||
w.changed = true
|
||||
return w.tmpFile.WriteAt(p, off)
|
||||
}
|
||||
|
||||
// ReadAt reads the file as written so far. Unless the open truncated it, that
|
||||
// starts as the file's existing content.
|
||||
func (w *SeaweedSftpFileWriter) ReadAt(p []byte, off int64) (int, error) {
|
||||
if w.readErr != nil {
|
||||
return 0, w.readErr
|
||||
}
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.tmpFile.ReadAt(p, off)
|
||||
}
|
||||
|
||||
func (w *SeaweedSftpFileWriter) Close() error {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
@@ -170,10 +146,6 @@ func (w *SeaweedSftpFileWriter) Close() error {
|
||||
defer os.Remove(w.tmpFile.Name()) // Clean up temp file
|
||||
defer w.tmpFile.Close()
|
||||
|
||||
if w.skipUploadIfUnchanged && !w.changed {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := w.tmpFile.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+28
-90
@@ -108,12 +108,6 @@ func (fs *SftpServer) withTimeoutContext(fn func(ctx context.Context) error) err
|
||||
// ==================== Command Dispatcher ====================
|
||||
|
||||
func (fs *SftpServer) dispatchCmd(r *sftp.Request) error {
|
||||
if r.Method == "Symlink" || r.Method == "Link" {
|
||||
// Answer before resolving paths: for Symlink, Filepath is the raw link
|
||||
// target. OP_UNSUPPORTED lets clients fall back.
|
||||
glog.V(1).Infof("Dispatch: unsupported %s %s -> %s", r.Method, r.Filepath, r.Target)
|
||||
return fmt.Errorf("%s: %w", r.Method, sftp.ErrSSHFxOpUnsupported)
|
||||
}
|
||||
absPath, err := fs.toAbsolutePath(r.Filepath)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -133,14 +127,18 @@ func (fs *SftpServer) dispatchCmd(r *sftp.Request) error {
|
||||
case "Rmdir":
|
||||
return fs.removeDir(absPath)
|
||||
case "Setstat":
|
||||
if w := fs.openUpload(absPath); w != nil {
|
||||
w, err := fs.openUpload(absPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if w != nil {
|
||||
if handled, err := w.setStat(r.AttrFlags(), r.Attributes()); handled {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return fs.setFileStat(absPath, r.AttrFlags(), r.Attributes())
|
||||
default:
|
||||
return fmt.Errorf("%s: %w", r.Method, sftp.ErrSSHFxOpUnsupported)
|
||||
return fmt.Errorf("unsupported: %s", r.Method)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,15 +156,7 @@ func (fs *SftpServer) readFile(r *sftp.Request) (io.ReaderAt, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A folder has no content to read; without this a download of one would
|
||||
// silently produce an empty file.
|
||||
if entry.IsDirectory {
|
||||
return nil, fmt.Errorf("%s is a directory", r.Filepath)
|
||||
}
|
||||
if entry.Attributes.GetSymlinkTarget() != "" {
|
||||
return nil, fmt.Errorf("%s is a symlink: %w", r.Filepath, sftp.ErrSSHFxOpUnsupported)
|
||||
}
|
||||
return fs.newFileReaderAt(r.Context(), absPath, entry)
|
||||
return NewSeaweedFileReaderAt(fs, entry), nil
|
||||
}
|
||||
|
||||
func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) {
|
||||
@@ -181,30 +171,17 @@ func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) {
|
||||
if err := fs.requireParentDir(absPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flags := r.Pflags()
|
||||
exclusive := flags.Creat && flags.Excl
|
||||
if existing, err := fs.checkWritable(absPath); err != nil {
|
||||
if _, err := fs.checkWritable(absPath); err != nil {
|
||||
return nil, err
|
||||
} else if existing == nil && !flags.Creat {
|
||||
return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: os.ErrNotExist}
|
||||
}
|
||||
// Create a temporary file to buffer writes
|
||||
tmpFile, err := os.CreateTemp("", "sftp-upload-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp file: %w", err)
|
||||
}
|
||||
// Take the name at open, so a concurrent exclusive create fails.
|
||||
if exclusive {
|
||||
if err := fs.createEmptyFile(absPath, r.Filepath); err != nil {
|
||||
tmpFile.Close()
|
||||
os.Remove(tmpFile.Name())
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// Without O_TRUNC the client writes into the existing file, so start from its current bytes.
|
||||
var existing *filer_pb.Entry
|
||||
if !flags.Trunc && !exclusive {
|
||||
if existing, err = fs.copyExistingContent(absPath, tmpFile); err != nil {
|
||||
if !r.Pflags().Trunc {
|
||||
if err := fs.copyExistingContent(absPath, tmpFile); err != nil {
|
||||
tmpFile.Close()
|
||||
os.Remove(tmpFile.Name())
|
||||
return nil, err
|
||||
@@ -221,48 +198,10 @@ func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) {
|
||||
gid: fs.user.Gid,
|
||||
offset: 0,
|
||||
}
|
||||
if flags.Append {
|
||||
w.append, w.appendFrom = true, int64(filer.FileSize(existing))
|
||||
}
|
||||
// Copied bytes are uploaded again only once the handle changes them. A
|
||||
// read-write open reads them, so whether it may read is decided on the
|
||||
// entry they came from. Without read permission it still writes.
|
||||
if existing != nil {
|
||||
w.skipUploadIfUnchanged = true
|
||||
if flags.Read {
|
||||
w.readErr = fs.checkEntryPermission(absPath, existing, "read")
|
||||
}
|
||||
}
|
||||
fs.trackUpload(w)
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// createEmptyFile fails with os.ErrExist when the name is taken.
|
||||
func (fs *SftpServer) createEmptyFile(absPath, clientPath string) error {
|
||||
dir, name := util.FullPath(absPath).DirAndName()
|
||||
now := time.Now().Unix()
|
||||
err := fs.callWithClient(false, func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
|
||||
return filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
Crtime: now,
|
||||
FileMode: 0644,
|
||||
Uid: fs.user.Uid,
|
||||
Gid: fs.user.Gid,
|
||||
},
|
||||
},
|
||||
OExcl: true,
|
||||
})
|
||||
})
|
||||
if errors.Is(err, filer_pb.ErrEntryAlreadyExists) {
|
||||
return &os.PathError{Op: "open", Path: clientPath, Err: os.ErrExist}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// checkWritable refuses an upload onto a directory, which the filer would
|
||||
// redirect to a child, or onto a protected entry. It returns the existing
|
||||
// file, or nil when there is none.
|
||||
@@ -280,20 +219,18 @@ func (fs *SftpServer) checkWritable(absPath string) (*filer_pb.Entry, error) {
|
||||
return entry, fs.checkEntryProtected(absPath, entry)
|
||||
}
|
||||
|
||||
// copyExistingContent writes the file's content to dst and returns the entry
|
||||
// it copied, or nil when there is no file.
|
||||
func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) (*filer_pb.Entry, error) {
|
||||
func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) error {
|
||||
entry, err := fs.getEntry(absPath)
|
||||
if err == os.ErrNotExist {
|
||||
return nil, nil
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
if entry.IsDirectory {
|
||||
return nil, nil
|
||||
return nil
|
||||
}
|
||||
return entry, fs.writeContent(context.Background(), absPath, entry, dst)
|
||||
return fs.writeContent(context.Background(), absPath, entry, dst)
|
||||
}
|
||||
|
||||
// writeContent writes the file's whole logical content to dst: inline bytes,
|
||||
@@ -550,11 +487,7 @@ func (fs *SftpServer) setFileStat(absPath string, flags sftp.FileAttrFlags, attr
|
||||
|
||||
func applyFileStat(entry *filer_pb.Entry, flags sftp.FileAttrFlags, attrs *sftp.FileStat) {
|
||||
if flags.Permissions {
|
||||
// chmod sends only permission bits: keep the stored type bits, or a
|
||||
// folder would turn into a file and the filer refuses the update.
|
||||
const changeable = os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky
|
||||
stored := os.FileMode(entry.Attributes.FileMode)
|
||||
entry.Attributes.FileMode = uint32(stored&^changeable | attrs.FileMode()&changeable)
|
||||
entry.Attributes.FileMode = uint32(attrs.FileMode())
|
||||
}
|
||||
if flags.UidGid {
|
||||
entry.Attributes.Uid = uint32(attrs.UID)
|
||||
@@ -576,9 +509,6 @@ func applyFileStat(entry *filer_pb.Entry, flags sftp.FileAttrFlags, attrs *sftp.
|
||||
// ==================== Directory Operations ====================
|
||||
|
||||
func (fs *SftpServer) listDir(r *sftp.Request) (sftp.ListerAt, error) {
|
||||
if r.Method != "List" && r.Method != "Stat" && r.Method != "Lstat" {
|
||||
return nil, fmt.Errorf("%s: %w", r.Method, sftp.ErrSSHFxOpUnsupported)
|
||||
}
|
||||
absPath, err := fs.toAbsolutePath(r.Filepath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -953,11 +883,19 @@ type EnhancedFileInfo struct {
|
||||
gid uint32
|
||||
}
|
||||
|
||||
// Uid and Gid implement sftp.FileInfoUidGid, so stat and listings report the
|
||||
// owner stored in the filer.
|
||||
func (fi *EnhancedFileInfo) Uid() uint32 { return fi.uid }
|
||||
// FileStat represents file statistics in a platform-independent way
|
||||
type FileStat struct {
|
||||
Uid uint32
|
||||
Gid uint32
|
||||
}
|
||||
|
||||
func (fi *EnhancedFileInfo) Gid() uint32 { return fi.gid }
|
||||
func (fi *EnhancedFileInfo) Sys() interface{} {
|
||||
return &FileStat{Uid: fi.uid, Gid: fi.gid}
|
||||
}
|
||||
|
||||
func (fi *EnhancedFileInfo) Owner() (uid, gid int) {
|
||||
return int(fi.uid), int(fi.gid)
|
||||
}
|
||||
|
||||
func (fs *SftpServer) checkFilePermission(filepath string, permissions string) error {
|
||||
return fs.CheckFilePermission(filepath, permissions)
|
||||
|
||||
@@ -376,7 +376,7 @@ func TestSetstatOnBufferingUpload(t *testing.T) {
|
||||
if got.GetMtime() != mtime || got.GetMtimeNs() != 0 || os.FileMode(got.GetFileMode()).Perm() != 0600 {
|
||||
t.Errorf("stored mtime %d.%09d mode %o, want %d.000000000 and 600", got.GetMtime(), got.GetMtimeNs(), got.GetFileMode(), mtime)
|
||||
}
|
||||
if fs.openUpload("/buckets/plain/new") != nil {
|
||||
if w, _ := fs.openUpload("/buckets/plain/new"); w != nil {
|
||||
t.Error("closed upload is still tracked")
|
||||
}
|
||||
|
||||
@@ -398,10 +398,11 @@ func TestSetstatOnBufferingUpload(t *testing.T) {
|
||||
}
|
||||
|
||||
// A setstat names only the path, so it can't pick between two uploads open
|
||||
// on the same one and goes to the stored entry instead.
|
||||
// on the same one, and changing the stored entry instead would be wrong too.
|
||||
func TestSetstatWithTwoUploadsOnOnePath(t *testing.T) {
|
||||
fs, _ := newLockTestServer(t, map[string]*filer_pb.Entry{
|
||||
"/buckets/plain": {Name: "plain", IsDirectory: true},
|
||||
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
|
||||
"/buckets/plain": {Name: "plain", IsDirectory: true},
|
||||
"/buckets/plain/new": {Name: "new", Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 10}},
|
||||
})
|
||||
open := func() io.WriteCloser {
|
||||
req := sftp.NewRequest("Put", "/plain/new")
|
||||
@@ -413,35 +414,18 @@ func TestSetstatWithTwoUploadsOnOnePath(t *testing.T) {
|
||||
return w.(io.WriteCloser)
|
||||
}
|
||||
first, second := open(), open()
|
||||
if fs.openUpload("/buckets/plain/new") != nil {
|
||||
t.Fatal("setstat routed to one of two open uploads")
|
||||
setstat := sftp.NewRequest("Setstat", "/plain/new")
|
||||
setstat.Flags = 0x1 // size
|
||||
setstat.Attrs = binary.BigEndian.AppendUint64(nil, 0)
|
||||
if err := fs.dispatchCmd(setstat); err == nil {
|
||||
t.Error("setstat with two uploads open succeeded")
|
||||
}
|
||||
if fake.lastUpdate != nil {
|
||||
t.Errorf("setstat changed the stored entry: %v", fake.lastUpdate.Entry.Attributes)
|
||||
}
|
||||
_ = second.Close()
|
||||
if got := fs.openUpload("/buckets/plain/new"); got != first {
|
||||
t.Fatalf("open upload = %p, want the remaining one %p", got, first)
|
||||
if got, err := fs.openUpload("/buckets/plain/new"); got != first || err != nil {
|
||||
t.Fatalf("open upload = %p, %v, want the remaining one %p", got, err, first)
|
||||
}
|
||||
_ = first.Close()
|
||||
}
|
||||
|
||||
// Stat and listings must report the uid/gid stored in the filer.
|
||||
func TestStatAndListReportOwner(t *testing.T) {
|
||||
fs := newCopyTestServer(t, "", map[string]*filer_pb.Entry{
|
||||
"//home": {Name: "home", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: 0o755}},
|
||||
"/home/f": {Name: "f", Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, Uid: 1234, Gid: 5678}},
|
||||
})
|
||||
fs.user.Permissions = map[string][]string{"/": {"read", "list"}}
|
||||
for _, req := range []*sftp.Request{sftp.NewRequest("Stat", "/home/f"), sftp.NewRequest("List", "/home")} {
|
||||
lister, err := fs.listDir(req)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", req.Method, err)
|
||||
}
|
||||
infos := make([]os.FileInfo, 1)
|
||||
if n, _ := lister.ListAt(infos, 0); n != 1 {
|
||||
t.Fatalf("%s returned %d entries, want 1", req.Method, n)
|
||||
}
|
||||
owner, ok := infos[0].(sftp.FileInfoUidGid)
|
||||
if !ok || owner.Uid() != 1234 || owner.Gid() != 5678 {
|
||||
t.Errorf("%s: owner not reported as 1234/5678 (%T)", req.Method, infos[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,6 @@ type lockTestFiler struct {
|
||||
renames []*filer_pb.AtomicRenameEntryRequest
|
||||
updates int
|
||||
volume string
|
||||
// remote holds what CacheRemoteObjectToLocalCluster stores for a path
|
||||
remote map[string]*filer_pb.Entry
|
||||
|
||||
lastUpdate *filer_pb.UpdateEntryRequest
|
||||
updateErr error
|
||||
@@ -321,13 +319,10 @@ func TestUploadRechecksTargetAtClose(t *testing.T) {
|
||||
t.Fatalf("upload onto a directory was accepted")
|
||||
}
|
||||
|
||||
w, err := fs.newFileWriter(uploadRequest("/b/f"))
|
||||
w, err := fs.newFileWriter(sftp.NewRequest("Put", "/b/f"))
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
if _, err := w.WriteAt([]byte("x"), 0); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
fake.mu.Lock()
|
||||
fake.entries["/buckets/b/f"] = lockedEntry("f", map[string]string{s3_constants.ExtLegalHoldKey: s3_constants.LegalHoldOn})
|
||||
fake.entries["/buckets/b/f"].Attributes = &filer_pb.FuseAttributes{FileMode: 0644, Uid: 1000}
|
||||
@@ -457,27 +452,3 @@ func TestPutFileAppliesBucketDefaultRetention(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// chmod sends only permission bits: the stored type must stay, or the filer
|
||||
// refuses to turn a folder into a file.
|
||||
func TestChmodKeepsEntryType(t *testing.T) {
|
||||
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
|
||||
"/buckets/d": {Name: "d", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: uint32(os.ModeDir | 0o700)}},
|
||||
"/buckets/f": {Name: "f", Attributes: &filer_pb.FuseAttributes{FileMode: 0o644}},
|
||||
})
|
||||
for _, c := range []struct {
|
||||
path string
|
||||
sent uint32
|
||||
want os.FileMode
|
||||
}{
|
||||
{"/buckets/d", 0o1750, os.ModeDir | os.ModeSticky | 0o750},
|
||||
{"/buckets/f", 0o600, 0o600},
|
||||
} {
|
||||
if err := fs.setFileStat(c.path, sftp.FileAttrFlags{Permissions: true}, &sftp.FileStat{Mode: c.sent}); err != nil {
|
||||
t.Fatalf("chmod %s: %v", c.path, err)
|
||||
}
|
||||
if got := os.FileMode(fake.lastUpdate.GetEntry().GetAttributes().GetFileMode()); got != c.want {
|
||||
t.Errorf("chmod %s stored mode %v, want %v", c.path, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
package sftpd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// uploadRequest opens with WRITE|CREAT, as clients do for an upload.
|
||||
func uploadRequest(p string) *sftp.Request {
|
||||
return &sftp.Request{Method: "Put", Filepath: p, Flags: 0x02 | 0x08}
|
||||
}
|
||||
|
||||
func (f *lockTestFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
p := path.Join(req.Directory, req.Entry.Name)
|
||||
if _, ok := f.entries[p]; ok && req.OExcl {
|
||||
return &filer_pb.CreateEntryResponse{Error: "exists", ErrorCode: filer_pb.FilerError_ENTRY_ALREADY_EXISTS}, nil
|
||||
}
|
||||
f.entries[p] = req.Entry
|
||||
return &filer_pb.CreateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func (rw *rwTest) entry(p string) *filer_pb.Entry {
|
||||
rw.fake.mu.Lock()
|
||||
defer rw.fake.mu.Unlock()
|
||||
return rw.fake.entries[p]
|
||||
}
|
||||
|
||||
func TestOpenMissingFileWithoutCreate(t *testing.T) {
|
||||
for _, flags := range []int{os.O_WRONLY, os.O_RDWR} {
|
||||
rw := newRWTest(t, PermAll)
|
||||
f, err := rw.client.OpenFile("/b/missing.txt", flags)
|
||||
if err == nil {
|
||||
_, _ = f.Write([]byte("x"))
|
||||
_ = f.Close()
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("open missing with flags %#x: err = %v, want not exist", flags, err)
|
||||
}
|
||||
if got := rw.uploads(); len(got) != 0 {
|
||||
t.Errorf("open missing with flags %#x uploaded %q, want nothing", flags, got)
|
||||
}
|
||||
if e := rw.entry("/buckets/b/missing.txt"); e != nil {
|
||||
t.Errorf("open missing with flags %#x created %v", flags, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExclusiveCreateRefusesExistingFile(t *testing.T) {
|
||||
for _, flags := range []int{os.O_WRONLY, os.O_RDWR} {
|
||||
rw := newRWTest(t, PermAll)
|
||||
f, err := rw.client.OpenFile("/b/rw.txt", flags|os.O_CREATE|os.O_EXCL)
|
||||
if err == nil {
|
||||
_, _ = f.WriteAt([]byte("XY"), 0)
|
||||
_ = f.Close()
|
||||
t.Errorf("exclusive create of an existing file with flags %#x succeeded", flags)
|
||||
}
|
||||
if got := rw.uploads(); len(got) != 0 {
|
||||
t.Errorf("exclusive create of an existing file uploaded %q, want nothing", got)
|
||||
}
|
||||
if c := string(rw.entry("/buckets/b/rw.txt").GetContent()); c != "abcdef" {
|
||||
t.Errorf("content after refused exclusive create = %q, want %q", c, "abcdef")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExclusiveCreateTakesNameAtOpen(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
f, err := rw.client.OpenFile("/b/new.txt", os.O_WRONLY|os.O_CREATE|os.O_EXCL)
|
||||
if err != nil {
|
||||
t.Fatalf("exclusive create of a new file: %v", err)
|
||||
}
|
||||
if rw.entry("/buckets/b/new.txt") == nil {
|
||||
t.Errorf("exclusive create left no entry before close")
|
||||
}
|
||||
if g, err := rw.client.OpenFile("/b/new.txt", os.O_WRONLY|os.O_CREATE|os.O_EXCL); err == nil {
|
||||
_ = g.Close()
|
||||
t.Errorf("second exclusive create of the same name succeeded")
|
||||
}
|
||||
if _, err := f.Write([]byte("lock")); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
if got := rw.uploads(); !slices.Equal(got, []string{"lock"}) {
|
||||
t.Errorf("uploaded = %q, want %q", got, []string{"lock"})
|
||||
}
|
||||
}
|
||||
|
||||
// Like SFTPGo, APPEND refuses writes below the size at open.
|
||||
func TestAppendKeepsExistingContent(t *testing.T) {
|
||||
for _, flags := range []int{os.O_WRONLY, os.O_RDWR} {
|
||||
rw := newRWTest(t, PermAll)
|
||||
f, err := rw.client.OpenFile("/b/rw.txt", flags|os.O_APPEND)
|
||||
if err != nil {
|
||||
t.Fatalf("open append with flags %#x: %v", flags, err)
|
||||
}
|
||||
if _, err := f.WriteAt([]byte("12"), 0); err == nil {
|
||||
t.Errorf("append with flags %#x: write at 0 succeeded", flags)
|
||||
}
|
||||
if _, err := f.WriteAt([]byte("34"), 6); err != nil {
|
||||
t.Errorf("append with flags %#x: write at the end: %v", flags, err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
if c := string(rw.entry("/buckets/b/rw.txt").GetContent()); c != "abcdef34" {
|
||||
t.Errorf("content after append with flags %#x = %q, want %q", flags, c, "abcdef34")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendAfterTruncate(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
f, err := rw.client.OpenFile("/b/rw.txt", os.O_WRONLY|os.O_APPEND)
|
||||
if err != nil {
|
||||
t.Fatalf("open append: %v", err)
|
||||
}
|
||||
if err := f.Truncate(2); err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
if _, err := f.WriteAt([]byte("XY"), 2); err != nil {
|
||||
t.Fatalf("write at the new end: %v", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
if got := rw.uploads(); !slices.Equal(got, []string{"abXY"}) {
|
||||
t.Errorf("uploaded = %q, want %q", got, []string{"abXY"})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefusedAppendLeavesFileAlone(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
f, err := rw.client.OpenFile("/b/rw.txt", os.O_WRONLY|os.O_APPEND)
|
||||
if err != nil {
|
||||
t.Fatalf("open append: %v", err)
|
||||
}
|
||||
if _, err := f.WriteAt([]byte("12"), 0); err == nil {
|
||||
t.Errorf("append: write at 0 succeeded")
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
if got := rw.uploads(); len(got) != 0 {
|
||||
t.Errorf("uploaded %q after the only write was refused, want nothing", got)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/sftpd/user"
|
||||
)
|
||||
|
||||
@@ -76,18 +75,8 @@ func (fs *SftpServer) CheckFilePermission(path string, perm string) error {
|
||||
}
|
||||
return fmt.Errorf("failed to get entry for path %s: %w", path, err)
|
||||
}
|
||||
return fs.checkEntryPermission(path, entry, perm)
|
||||
}
|
||||
|
||||
// checkEntryPermission is CheckFilePermission for an entry already looked up
|
||||
// at path, so a caller can decide on the same entry it then acts on.
|
||||
func (fs *SftpServer) checkEntryPermission(path string, entry *filer_pb.Entry, perm string) error {
|
||||
if fs.user == nil {
|
||||
glog.V(0).Infof("permission denied. No user associated with the SftpServer.")
|
||||
return os.ErrPermission
|
||||
}
|
||||
var err error
|
||||
|
||||
// Rest of the function remains the same...
|
||||
// Handle symlinks by resolving them
|
||||
if target := entry.Attributes.GetSymlinkTarget(); target != "" && !entry.IsDirectory {
|
||||
entry, err = fs.getEntry(target)
|
||||
|
||||
@@ -114,7 +114,7 @@ func TestNewFileWriterChecksTargetFile(t *testing.T) {
|
||||
}
|
||||
|
||||
write := func(path string) error {
|
||||
w, err := fs.newFileWriter(uploadRequest(path))
|
||||
w, err := fs.newFileWriter(&sftp.Request{Filepath: path})
|
||||
if writer, ok := w.(*SeaweedSftpFileWriter); ok {
|
||||
_ = os.Remove(writer.tmpFile.Name())
|
||||
_ = writer.tmpFile.Close()
|
||||
@@ -200,7 +200,7 @@ func TestRequireParentDirEnforced(t *testing.T) {
|
||||
t.Error("mkdir under an existing parent did not create the entry")
|
||||
}
|
||||
|
||||
w, err := fs.newFileWriter(uploadRequest("/d/f.txt"))
|
||||
w, err := fs.newFileWriter(&sftp.Request{Filepath: "/d/f.txt"})
|
||||
if err != nil {
|
||||
t.Fatalf("open upload under an existing parent: %v", err)
|
||||
}
|
||||
@@ -797,28 +797,3 @@ func TestCheckFilePermissionFollowsOnlySymlinks(t *testing.T) {
|
||||
t.Error("dangling symlink allowed")
|
||||
}
|
||||
}
|
||||
|
||||
// Reading a folder must fail, not look like an empty file: clients that don't
|
||||
// stat first would otherwise save an empty download.
|
||||
func TestReadFolderFails(t *testing.T) {
|
||||
fs := newCopyTestServer(t, "", map[string]*filer_pb.Entry{
|
||||
"/home/dir": {Name: "dir", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
|
||||
})
|
||||
fs.user.Permissions = map[string][]string{"/": {"*"}}
|
||||
if _, err := fs.readFile(sftp.NewRequest("Get", "/home/dir")); err == nil {
|
||||
t.Fatal("reading a folder succeeded, want an error")
|
||||
}
|
||||
}
|
||||
|
||||
// A symlink stores no content, and the read does not follow it, so it would
|
||||
// download as an empty file too.
|
||||
func TestReadSymlinkFails(t *testing.T) {
|
||||
fs := newCopyTestServer(t, "", map[string]*filer_pb.Entry{
|
||||
"/home/link": {Name: "link", Attributes: &filer_pb.FuseAttributes{FileMode: uint32(os.ModeSymlink | 0777), SymlinkTarget: "/home/file"}},
|
||||
"/home/file": {Name: "file", Content: []byte("data"), Attributes: &filer_pb.FuseAttributes{FileSize: 4}},
|
||||
})
|
||||
fs.user.Permissions = map[string][]string{"/": {"*"}}
|
||||
if _, err := fs.readFile(sftp.NewRequest("Get", "/home/link")); !errors.Is(err, sftp.ErrSSHFxOpUnsupported) {
|
||||
t.Fatalf("reading a symlink: got %v, want OP_UNSUPPORTED", err)
|
||||
}
|
||||
}
|
||||
@@ -1,240 +0,0 @@
|
||||
package sftpd
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
// newTestClient serves fs as one SFTP session over in-memory pipes and
|
||||
// returns a client connected to it.
|
||||
func newTestClient(t *testing.T, fs *SftpServer) *sftp.Client {
|
||||
t.Helper()
|
||||
serverR, clientW := io.Pipe()
|
||||
clientR, serverW := io.Pipe()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
_ = handleSFTP(pipeStream{serverR, serverW}, fs)
|
||||
}()
|
||||
client, err := sftp.NewClientPipe(clientR, clientW)
|
||||
if err != nil {
|
||||
t.Fatalf("sftp client: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = client.Close()
|
||||
<-done
|
||||
})
|
||||
return client
|
||||
}
|
||||
|
||||
// rwTest serves /buckets/b/rw.txt ("abcdef") and the empty
|
||||
// /buckets/b/empty.txt, with a stand-in filer HTTP endpoint that stores
|
||||
// uploads and records their bodies.
|
||||
type rwTest struct {
|
||||
client *sftp.Client
|
||||
fs *SftpServer
|
||||
fake *lockTestFiler
|
||||
mu sync.Mutex
|
||||
bodies []string
|
||||
}
|
||||
|
||||
func newRWTest(t *testing.T, perms ...string) *rwTest {
|
||||
t.Helper()
|
||||
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
|
||||
"/buckets/b": {Name: "b", IsDirectory: true},
|
||||
"/buckets/b/rw.txt": {Name: "rw.txt", Content: []byte("abcdef"), Attributes: &filer_pb.FuseAttributes{FileSize: 6, FileMode: 0o644}},
|
||||
"/buckets/b/empty.txt": {Name: "empty.txt"},
|
||||
})
|
||||
fs.user.Permissions = map[string][]string{"/buckets": perms}
|
||||
rw := &rwTest{fs: fs, fake: fake}
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
rw.mu.Lock()
|
||||
rw.bodies = append(rw.bodies, string(body))
|
||||
rw.mu.Unlock()
|
||||
fake.mu.Lock()
|
||||
fake.entries[r.URL.Path] = &filer_pb.Entry{Name: path.Base(r.URL.Path), Content: body, Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, FileSize: uint64(len(body))}}
|
||||
fake.mu.Unlock()
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}))
|
||||
t.Cleanup(ts.Close)
|
||||
_, grpcPort, _ := net.SplitHostPort(fs.filerAddr.ToGrpcAddress())
|
||||
fs.filerAddr = pb.ServerAddress(strings.TrimPrefix(ts.URL, "http://") + "." + grpcPort)
|
||||
rw.client = newTestClient(t, fs)
|
||||
return rw
|
||||
}
|
||||
|
||||
func (rw *rwTest) uploads() []string {
|
||||
rw.mu.Lock()
|
||||
defer rw.mu.Unlock()
|
||||
return append([]string(nil), rw.bodies...)
|
||||
}
|
||||
|
||||
// A read on a handle opened for reading and writing must return the file's
|
||||
// bytes and leave them alone. pkg/sftp serves reads on a write-only handle as
|
||||
// writes of the read buffer, which put zeros over the start of the file.
|
||||
func TestReadWriteOpenReadsExistingContent(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
|
||||
f, err := rw.client.OpenFile("/b/rw.txt", os.O_RDWR)
|
||||
if err != nil {
|
||||
t.Fatalf("open read-write: %v", err)
|
||||
}
|
||||
head := make([]byte, 3)
|
||||
if n, err := f.ReadAt(head, 0); n != 3 || string(head) != "abc" {
|
||||
t.Fatalf("read 3 at 0 = %q (n=%d, err=%v), want %q", head[:n], n, err, "abc")
|
||||
}
|
||||
if _, err := f.WriteAt([]byte("XY"), 4); err != nil {
|
||||
t.Fatalf("write at 4: %v", err)
|
||||
}
|
||||
all := make([]byte, 6)
|
||||
if n, err := f.ReadAt(all, 0); string(all[:n]) != "abcdXY" {
|
||||
t.Fatalf("content after read and write = %q (err=%v), want %q", all[:n], err, "abcdXY")
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
if got := rw.uploads(); len(got) != 1 || got[0] != "abcdXY" {
|
||||
t.Fatalf("uploaded on close = %q, want one upload of %q", got, "abcdXY")
|
||||
}
|
||||
}
|
||||
|
||||
// Close uploads a read-write handle again only if it changed the file:
|
||||
// reading must not rewrite it (nor restore it once removed), while a
|
||||
// truncating or creating open, or a setstat on the handle, does change it.
|
||||
func TestReadWriteOpenUploadsOnlyChanges(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
path string
|
||||
flags int
|
||||
do func(*sftp.File, *lockTestFiler) error
|
||||
want []string
|
||||
mode os.FileMode // stored afterwards, when set
|
||||
}{
|
||||
{name: "read", path: "/b/rw.txt", flags: os.O_RDWR},
|
||||
{name: "read empty", path: "/b/empty.txt", flags: os.O_RDWR},
|
||||
{name: "read removed", path: "/b/rw.txt", flags: os.O_RDWR | os.O_CREATE, do: func(_ *sftp.File, fake *lockTestFiler) error {
|
||||
fake.mu.Lock()
|
||||
defer fake.mu.Unlock()
|
||||
delete(fake.entries, "/buckets/b/rw.txt")
|
||||
return nil
|
||||
}},
|
||||
{name: "truncate", path: "/b/rw.txt", flags: os.O_RDWR | os.O_TRUNC, want: []string{""}},
|
||||
{name: "create", path: "/b/new.txt", flags: os.O_RDWR | os.O_CREATE, want: []string{""}},
|
||||
{name: "ftruncate", path: "/b/rw.txt", flags: os.O_RDWR, do: func(f *sftp.File, _ *lockTestFiler) error { return f.Truncate(3) }, want: []string{"abc"}},
|
||||
{name: "fchmod", path: "/b/rw.txt", flags: os.O_RDWR, do: func(f *sftp.File, _ *lockTestFiler) error { return f.Chmod(0o600) }, want: []string{"abcdef"}, mode: 0o600},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
|
||||
f, err := rw.client.OpenFile(c.path, c.flags)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
if _, err := f.ReadAt(make([]byte, 6), 0); err != nil && err != io.EOF {
|
||||
t.Fatalf("read: %v", err)
|
||||
}
|
||||
if c.do != nil {
|
||||
if err := c.do(f, rw.fake); err != nil {
|
||||
t.Fatalf("%s: %v", c.name, err)
|
||||
}
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
if got := rw.uploads(); !slices.Equal(got, c.want) {
|
||||
t.Fatalf("uploaded on close = %q, want %q", got, c.want)
|
||||
}
|
||||
if mode := os.FileMode(rw.fake.lastUpdate.GetEntry().GetAttributes().GetFileMode()).Perm(); c.mode != 0 && mode != c.mode {
|
||||
t.Errorf("stored mode %o, want %o", mode, c.mode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without read permission a read-write open still writes, as a write-only
|
||||
// open would, but reads only what the handle itself wrote.
|
||||
func TestReadWriteOpenWithoutReadPermission(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
path string
|
||||
flags int
|
||||
readable bool // the handle starts empty, so reading needs no permission
|
||||
want string
|
||||
}{
|
||||
{"existing", "/b/rw.txt", os.O_RDWR, false, "XYcdef"},
|
||||
{"truncate", "/b/rw.txt", os.O_RDWR | os.O_TRUNC, true, "XY"},
|
||||
{"create", "/b/new.txt", os.O_RDWR | os.O_CREATE, true, "XY"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
rw := newRWTest(t, "write")
|
||||
|
||||
f, err := rw.client.OpenFile(c.path, c.flags)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
if _, err := f.WriteAt([]byte("XY"), 0); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
b := make([]byte, 2)
|
||||
n, err := f.ReadAt(b, 0)
|
||||
if c.readable && string(b[:n]) != "XY" {
|
||||
t.Fatalf("read back own write = %q (err=%v), want %q", b[:n], err, "XY")
|
||||
}
|
||||
if !c.readable && (err == nil || n > 0) {
|
||||
t.Fatalf("read without read permission = %q (err=%v), want refused", b[:n], err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close: %v", err)
|
||||
}
|
||||
if got := rw.uploads(); len(got) != 1 || got[0] != c.want {
|
||||
t.Fatalf("uploaded on close = %q, want one upload of %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Read permission is decided on the entry that was copied. Looked up again
|
||||
// after the file is removed during the copy, the check would fall back to
|
||||
// the folder's rights, which here are wider than the file's.
|
||||
func TestReadWriteOpenFileRemovedDuringCopyNeedsRead(t *testing.T) {
|
||||
rw := newRWTest(t, PermAll)
|
||||
rw.fs.user.Permissions["/buckets/b/x.bin"] = []string{"write"}
|
||||
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
rw.fake.mu.Lock()
|
||||
delete(rw.fake.entries, "/buckets/b/x.bin")
|
||||
rw.fake.mu.Unlock()
|
||||
_, _ = w.Write([]byte("secret"))
|
||||
}))
|
||||
t.Cleanup(volume.Close)
|
||||
rw.fake.mu.Lock()
|
||||
rw.fake.volume = volume.Listener.Addr().String()
|
||||
rw.fake.entries["/buckets/b/x.bin"] = &filer_pb.Entry{
|
||||
Name: "x.bin",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: 6, FileMode: 0o644},
|
||||
Chunks: []*filer_pb.FileChunk{fileChunk("3,01", 0, 6)},
|
||||
}
|
||||
rw.fake.mu.Unlock()
|
||||
|
||||
f, err := rw.client.OpenFile("/b/x.bin", os.O_RDWR)
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
b := make([]byte, 6)
|
||||
if n, err := f.ReadAt(b, 0); err == nil || n > 0 {
|
||||
t.Fatalf("read of a write-only file removed during the copy = %q (err=%v), want refused", b[:n], err)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user