mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6389887ebb | ||
|
|
51d068a98d | ||
|
|
29d00ae794 | ||
|
|
21c4de24e9 | ||
|
|
f54f20e654 | ||
|
|
561307a7ca | ||
|
|
fdd9c1edd3 | ||
|
|
d09c4d951a | ||
|
|
f03806064e | ||
|
|
666f80564f | ||
|
|
2b47004269 | ||
|
|
1ef76dfb12 | ||
|
|
18b71ed0ef | ||
|
|
a7b0aa8926 | ||
|
|
63dfda3412 | ||
|
|
96f310dec8 | ||
|
|
ffa87c25fd | ||
|
|
153ab668c9 | ||
|
|
6dd6ad512c | ||
|
|
515380c349 | ||
|
|
9620e7ebfe | ||
|
|
53834117a6 |
No files matched your search
@@ -44,7 +44,12 @@ jobs:
|
||||
|
||||
- name: Install musl tools (amd64)
|
||||
if: ${{ !matrix.cross }}
|
||||
run: sudo apt-get install -y musl-tools
|
||||
run: |
|
||||
sudo apt-get install -y musl-tools
|
||||
# C deps (aws-lc-sys) must compile against musl headers, not the host
|
||||
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
|
||||
# __isoc23_strtol) don't exist in musl and fail the link.
|
||||
echo "CC_x86_64_unknown_linux_musl=musl-gcc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Install cross-compilation tools (arm64)
|
||||
if: matrix.cross
|
||||
@@ -53,6 +58,31 @@ jobs:
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
|
||||
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
|
||||
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
|
||||
# aws-lc-sys compiles against glibc headers, which redirect
|
||||
# sscanf/strtol to C23 __isoc23_* symbols musl does not provide.
|
||||
# Link a tiny forwarding shim so those references resolve to the
|
||||
# musl implementations. Prototypes are declared manually: including
|
||||
# glibc headers here would re-redirect the calls back to __isoc23_*.
|
||||
cat > /tmp/isoc23-shim.c <<'SHIM'
|
||||
#include <stdarg.h>
|
||||
extern int vsscanf(const char *s, const char *fmt, va_list ap);
|
||||
extern long strtol(const char *nptr, char **endptr, int base);
|
||||
int __isoc23_sscanf(const char *s, const char *fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
int r = vsscanf(s, fmt, ap);
|
||||
va_end(ap);
|
||||
return r;
|
||||
}
|
||||
long __isoc23_strtol(const char *nptr, char **endptr, int base) {
|
||||
return strtol(nptr, endptr, base);
|
||||
}
|
||||
SHIM
|
||||
aarch64-linux-gnu-gcc -O2 -c /tmp/isoc23-shim.c -o /tmp/isoc23-shim.o
|
||||
# link-args land after libc on the link line; rescan musl libc so
|
||||
# the shim's own vsscanf/strtol references resolve, and libgcc for
|
||||
# the fp128 builtins musl's vfscanf/floatscan pull in on aarch64.
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=-Clink-arg=/tmp/isoc23-shim.o -Clink-arg=-lc -Clink-arg=-lgcc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
if: runner.environment == 'github-hosted'
|
||||
|
||||
@@ -88,7 +88,12 @@ jobs:
|
||||
|
||||
- name: Install musl tools (amd64)
|
||||
if: ${{ !matrix.cross }}
|
||||
run: sudo apt-get install -y musl-tools
|
||||
run: |
|
||||
sudo apt-get install -y musl-tools
|
||||
# C deps (aws-lc-sys) must compile against musl headers, not the host
|
||||
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
|
||||
# __isoc23_strtol) don't exist in musl and fail the link.
|
||||
echo "CC_x86_64_unknown_linux_musl=musl-gcc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Install cross-compilation tools (arm64)
|
||||
if: matrix.cross
|
||||
@@ -97,6 +102,31 @@ jobs:
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
|
||||
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
|
||||
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
|
||||
# aws-lc-sys compiles against glibc headers, which redirect
|
||||
# sscanf/strtol to C23 __isoc23_* symbols musl does not provide.
|
||||
# Link a tiny forwarding shim so those references resolve to the
|
||||
# musl implementations. Prototypes are declared manually: including
|
||||
# glibc headers here would re-redirect the calls back to __isoc23_*.
|
||||
cat > /tmp/isoc23-shim.c <<'SHIM'
|
||||
#include <stdarg.h>
|
||||
extern int vsscanf(const char *s, const char *fmt, va_list ap);
|
||||
extern long strtol(const char *nptr, char **endptr, int base);
|
||||
int __isoc23_sscanf(const char *s, const char *fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
int r = vsscanf(s, fmt, ap);
|
||||
va_end(ap);
|
||||
return r;
|
||||
}
|
||||
long __isoc23_strtol(const char *nptr, char **endptr, int base) {
|
||||
return strtol(nptr, endptr, base);
|
||||
}
|
||||
SHIM
|
||||
aarch64-linux-gnu-gcc -O2 -c /tmp/isoc23-shim.c -o /tmp/isoc23-shim.o
|
||||
# link-args land after libc on the link line; rescan musl libc so
|
||||
# the shim's own vsscanf/strtol references resolve, and libgcc for
|
||||
# the fp128 builtins musl's vfscanf/floatscan pull in on aarch64.
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=-Clink-arg=/tmp/isoc23-shim.o -Clink-arg=-lc -Clink-arg=-lgcc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
if: runner.environment == 'github-hosted'
|
||||
|
||||
@@ -67,7 +67,12 @@ jobs:
|
||||
|
||||
- name: Install musl tools (amd64)
|
||||
if: ${{ !matrix.cross }}
|
||||
run: sudo apt-get install -y musl-tools
|
||||
run: |
|
||||
sudo apt-get install -y musl-tools
|
||||
# C deps (aws-lc-sys) must compile against musl headers, not the host
|
||||
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
|
||||
# __isoc23_strtol) don't exist in musl and fail the link.
|
||||
echo "CC_x86_64_unknown_linux_musl=musl-gcc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Install cross-compilation tools (arm64)
|
||||
if: matrix.cross
|
||||
@@ -76,6 +81,31 @@ jobs:
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
|
||||
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
|
||||
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
|
||||
# aws-lc-sys compiles against glibc headers, which redirect
|
||||
# sscanf/strtol to C23 __isoc23_* symbols musl does not provide.
|
||||
# Link a tiny forwarding shim so those references resolve to the
|
||||
# musl implementations. Prototypes are declared manually: including
|
||||
# glibc headers here would re-redirect the calls back to __isoc23_*.
|
||||
cat > /tmp/isoc23-shim.c <<'SHIM'
|
||||
#include <stdarg.h>
|
||||
extern int vsscanf(const char *s, const char *fmt, va_list ap);
|
||||
extern long strtol(const char *nptr, char **endptr, int base);
|
||||
int __isoc23_sscanf(const char *s, const char *fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
int r = vsscanf(s, fmt, ap);
|
||||
va_end(ap);
|
||||
return r;
|
||||
}
|
||||
long __isoc23_strtol(const char *nptr, char **endptr, int base) {
|
||||
return strtol(nptr, endptr, base);
|
||||
}
|
||||
SHIM
|
||||
aarch64-linux-gnu-gcc -O2 -c /tmp/isoc23-shim.c -o /tmp/isoc23-shim.o
|
||||
# link-args land after libc on the link line; rescan musl libc so
|
||||
# the shim's own vsscanf/strtol references resolve, and libgcc for
|
||||
# the fp128 builtins musl's vfscanf/floatscan pull in on aarch64.
|
||||
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=-Clink-arg=/tmp/isoc23-shim.o -Clink-arg=-lc -Clink-arg=-lgcc" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Cache cargo registry and target
|
||||
if: runner.environment == 'github-hosted'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.50"
|
||||
appVersion: "4.51"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.50.0
|
||||
version: 4.51.0
|
||||
+1037
-1034
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 53 KiB |
@@ -166,6 +166,10 @@ message Entry {
|
||||
repeated FileChunk chunks = 3;
|
||||
FuseAttributes attributes = 4;
|
||||
map<string, bytes> extended = 5;
|
||||
// filer-local commit timestamp of the version stored here: the meta log
|
||||
// event's ts_ns for the mutation that produced this entry, or 0 for
|
||||
// entries written before the field existed
|
||||
int64 commit_ts_ns = 6;
|
||||
bytes hard_link_id = 7;
|
||||
int32 hard_link_counter = 8; // only exists in hard link meta data
|
||||
bytes content = 9; // if not empty, the file content
|
||||
@@ -281,6 +285,7 @@ message WriteCondition {
|
||||
IF_EXTENDED_NOT_EQUAL = 7; // fail if present and extended[ext_key] == ext_value
|
||||
IF_EXTENDED_TIME_ELAPSED = 8; // fail if present and extended[ext_key] (unix seconds) is in the future
|
||||
IF_CHUNKS_EQUAL = 9; // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
|
||||
IF_ENTRY_EQUAL = 10; // fail unless the stored entry equals expected_entry
|
||||
}
|
||||
// Clause is one primitive comparison. IF_ETAG_MATCH holds when the current
|
||||
// entry's ETag equals any value in etags; IF_ETAG_NOT_MATCH holds when it
|
||||
@@ -309,6 +314,7 @@ message WriteCondition {
|
||||
string gate_key = 7; // IF_EXTENDED_TIME_ELAPSED: only enforce when extended[gate_key] == gate_value
|
||||
string gate_value = 8; // gate value (e.g. retention mode COMPLIANCE for governance bypass)
|
||||
repeated string fids = 9; // chunk fid strings for IF_CHUNKS_EQUAL
|
||||
Entry expected_entry = 10; // whole-entry comparison for IF_ENTRY_EQUAL
|
||||
}
|
||||
repeated Clause clauses = 1; // all must hold (logical AND)
|
||||
}
|
||||
@@ -323,6 +329,7 @@ enum FilerError {
|
||||
EXISTING_IS_FILE = 4; // cannot overwrite file with directory
|
||||
ENTRY_ALREADY_EXISTS = 5; // O_EXCL and entry already exists
|
||||
PRECONDITION_FAILED = 6; // WriteCondition not satisfied
|
||||
READ_ONLY = 7; // path matches a read-only storage rule (e.g. bucket over quota)
|
||||
}
|
||||
|
||||
// ObjectMutation is one entry-level change applied by ObjectTransaction. All
|
||||
@@ -351,6 +358,7 @@ message ObjectMutation {
|
||||
bytes content = 11; // PATCH_EXTENDED: new Entry.content when set_content
|
||||
bool touch_mtime = 12; // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
|
||||
bool remove_empty_parent = 13; // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
|
||||
bool keep_remote_object = 14; // DELETE: leave the object on the mounted remote storage
|
||||
}
|
||||
|
||||
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
|
||||
@@ -388,6 +396,8 @@ message ObjectTransactionRequest {
|
||||
string condition_key = 6; // if set, evaluate the condition against this entry instead of lock_key (still locking lock_key)
|
||||
string route_key = 7; // ring key identifying the owner filer; a non-owner forwards the whole transaction to it
|
||||
bool is_moved = 8; // set on a forwarded transaction so the receiver applies it locally instead of forwarding again
|
||||
string request_id = 9; // idempotency token: the owner records the outcome and replays it on a retried request instead of re-applying
|
||||
string condition_alt_key = 10; // if the condition's entry is absent, evaluate it against this entry instead (e.g. null slot, else latest version)
|
||||
}
|
||||
|
||||
message ObjectTransactionResponse {
|
||||
@@ -477,6 +487,7 @@ message UpdateEntryRequest {
|
||||
// the write, under the filer's per-path lock. The caller must route the
|
||||
// key's writes to this entry's owner filer for the check to be authoritative.
|
||||
WriteCondition condition = 6;
|
||||
bool is_moved = 7; // set on a forwarded request so the owner applies it locally
|
||||
}
|
||||
message UpdateEntryResponse {
|
||||
SubscribeMetadataResponse metadata_event = 1;
|
||||
@@ -514,6 +525,7 @@ message DeleteEntryRequest {
|
||||
bool is_from_other_cluster = 7;
|
||||
repeated int32 signatures = 8;
|
||||
int64 if_not_modified_after = 9;
|
||||
bool keep_remote_object = 10;
|
||||
}
|
||||
|
||||
message DeleteEntryResponse {
|
||||
@@ -573,6 +585,9 @@ message AssignVolumeResponse {
|
||||
// fsync is the storage rule's fsync decision for the assigned path, so the
|
||||
// client can carry it onto the volume server upload request.
|
||||
bool fsync = 11;
|
||||
// error_code classifies error for callers that must branch on it; error
|
||||
// keeps the human-readable text for clients that predate the field.
|
||||
FilerError error_code = 12;
|
||||
}
|
||||
|
||||
message LookupVolumeRequest {
|
||||
@@ -709,6 +724,10 @@ message TraverseBfsMetadataRequest {
|
||||
message TraverseBfsMetadataResponse {
|
||||
string directory = 1;
|
||||
Entry entry = 2;
|
||||
// The sender's per-path commit timestamp (see meta_path_ts.go): the newest
|
||||
// event time this filer committed for the path, 0 when unrecorded so
|
||||
// subscribers fall back to the entry's mtime.
|
||||
int64 entry_ts_ns = 3;
|
||||
}
|
||||
|
||||
message LogEntry {
|
||||
|
||||
@@ -555,6 +555,7 @@ async fn lookup_volume(
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("lookup request failed: {}", e))?;
|
||||
let status = resp.status();
|
||||
let result: LookupResult = resp
|
||||
.json()
|
||||
.await
|
||||
@@ -562,7 +563,14 @@ async fn lookup_volume(
|
||||
if let Some(err) = result.error
|
||||
&& !err.is_empty()
|
||||
{
|
||||
return Err(err);
|
||||
// Mirror Go: a missing volume arrives as a per-volume error in an
|
||||
// answered lookup (HTTP 404), meaning "no locations" — a real master
|
||||
// failure (e.g. 503 while warming up) stays an error so proxy mode
|
||||
// can tell missing data (404) from a failed lookup (500).
|
||||
if status != StatusCode::NOT_FOUND {
|
||||
return Err(err);
|
||||
}
|
||||
tracing::debug!("volume {} lookup: {}", volume_id, err);
|
||||
}
|
||||
Ok(result.locations.unwrap_or_default())
|
||||
}
|
||||
@@ -812,6 +820,7 @@ async fn do_replicated_request(
|
||||
|
||||
/// Extracted request info needed for proxy/redirect (avoids borrowing Request across await).
|
||||
struct ProxyRequestInfo {
|
||||
method: Method,
|
||||
original_headers: HeaderMap,
|
||||
original_query: String,
|
||||
path: String,
|
||||
@@ -823,12 +832,14 @@ fn build_proxy_request_info(
|
||||
path: &str,
|
||||
headers: &HeaderMap,
|
||||
query_string: &str,
|
||||
method: &Method,
|
||||
) -> Option<ProxyRequestInfo> {
|
||||
// Go redirects to "vid,fid" built from parseURLPath, so the extension must
|
||||
// already be off the fid here (volume_server_handlers_read.go:128-137).
|
||||
let parsed = parse_needle_path(path)?;
|
||||
|
||||
Some(ProxyRequestInfo {
|
||||
method: method.clone(),
|
||||
original_headers: headers.clone(),
|
||||
original_query: query_string.to_string(),
|
||||
path: path.to_string(),
|
||||
@@ -856,7 +867,11 @@ async fn proxy_or_redirect_to_target(
|
||||
Ok(locs) => locs,
|
||||
Err(e) => {
|
||||
tracing::warn!("volume lookup failed for {}: {}", vid.0, e);
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
// Go: master lookup failure is 500 in proxy mode, 404 for redirect
|
||||
return match state.read_mode {
|
||||
ReadMode::Proxy => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
_ => StatusCode::NOT_FOUND.into_response(),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -920,11 +935,43 @@ async fn proxy_request(
|
||||
}
|
||||
};
|
||||
|
||||
// Build the proxy request
|
||||
let mut req_builder = state.http_client.get(&target_url);
|
||||
// Build the proxy request, preserving the inbound method (Go parity:
|
||||
// a client HEAD must not turn into a GET download at the replica).
|
||||
let mut req_builder = state.http_client.request(info.method.clone(), &target_url);
|
||||
|
||||
// Forward all original headers as raw bytes, as Go does.
|
||||
// Forward the original headers, as Go does — minus hop-by-hop fields.
|
||||
// Host must be the replica's, and Content-Length/Transfer-Encoding describe
|
||||
// a body this request does not carry; forwarding them stalls the peer's
|
||||
// read. Connection also nominates per-request fields to drop (RFC 9110
|
||||
// 7.6.1).
|
||||
let mut hop_by_hop: std::collections::HashSet<String> = info
|
||||
.original_headers
|
||||
.get_all(header::CONNECTION)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.flat_map(|v| v.split(','))
|
||||
.map(|token| token.trim().to_ascii_lowercase())
|
||||
.filter(|token| !token.is_empty())
|
||||
.collect();
|
||||
for fixed in [
|
||||
"host",
|
||||
"content-length",
|
||||
"transfer-encoding",
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"te",
|
||||
"trailer",
|
||||
"upgrade",
|
||||
"proxy-connection",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
] {
|
||||
hop_by_hop.insert(fixed.to_string());
|
||||
}
|
||||
for (name, value) in &info.original_headers {
|
||||
if hop_by_hop.contains(name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
req_builder = req_builder.header(name.clone(), value.clone());
|
||||
}
|
||||
|
||||
@@ -1088,14 +1135,30 @@ async fn get_or_head_handler_inner(
|
||||
let has_ec_volume = state.store.read().unwrap().has_ec_volume(vid);
|
||||
|
||||
if !has_volume && !has_ec_volume {
|
||||
return proxy_missing_volume(&state, request.uri(), request.headers(), &path, vid).await;
|
||||
return proxy_missing_volume(
|
||||
&state,
|
||||
request.uri(),
|
||||
request.headers(),
|
||||
&path,
|
||||
vid,
|
||||
&method,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let track_download =
|
||||
match check_download_limit(&state, request.uri(), request.headers(), &path, vid).await {
|
||||
ControlFlow::Continue(track_download) => track_download,
|
||||
ControlFlow::Break(resp) => return resp,
|
||||
};
|
||||
let track_download = match check_download_limit(
|
||||
&state,
|
||||
request.uri(),
|
||||
request.headers(),
|
||||
&path,
|
||||
vid,
|
||||
&method,
|
||||
)
|
||||
.await
|
||||
{
|
||||
ControlFlow::Continue(track_download) => track_download,
|
||||
ControlFlow::Break(resp) => return resp,
|
||||
};
|
||||
|
||||
let read_deleted = query.read_deleted.as_deref() == Some("true");
|
||||
// Go reads Range once and ignores an empty value; a non-UTF-8 byte fails its parse.
|
||||
@@ -1277,6 +1340,7 @@ async fn proxy_missing_volume(
|
||||
request_headers: &HeaderMap,
|
||||
path: &str,
|
||||
vid: VolumeId,
|
||||
method: &Method,
|
||||
) -> Response {
|
||||
let query_string = uri.query().unwrap_or("").to_string();
|
||||
if is_proxied_query(&query_string)
|
||||
@@ -1287,7 +1351,7 @@ async fn proxy_missing_volume(
|
||||
}
|
||||
|
||||
// For redirect, fid must be stripped of extension (Go parity: parseURLPath returns raw fid).
|
||||
let info = match build_proxy_request_info(path, request_headers, &query_string) {
|
||||
let info = match build_proxy_request_info(path, request_headers, &query_string, method) {
|
||||
Some(info) => info,
|
||||
None => return StatusCode::NOT_FOUND.into_response(),
|
||||
};
|
||||
@@ -1308,6 +1372,7 @@ async fn check_download_limit(
|
||||
request_headers: &HeaderMap,
|
||||
path: &str,
|
||||
vid: VolumeId,
|
||||
method: &Method,
|
||||
) -> ControlFlow<Response, bool> {
|
||||
if state.concurrent_download_limit <= 0 {
|
||||
return ControlFlow::Continue(false);
|
||||
@@ -1332,7 +1397,8 @@ async fn check_download_limit(
|
||||
.is_some_and(|(_, vol)| vol.super_block().replica_placement.has_replication())
|
||||
};
|
||||
if should_try_replica
|
||||
&& let Some(info) = build_proxy_request_info(path, request_headers, &query_string)
|
||||
&& let Some(info) =
|
||||
build_proxy_request_info(path, request_headers, &query_string, method)
|
||||
{
|
||||
return ControlFlow::Break(proxy_or_redirect_to_target(state, info, vid, true).await);
|
||||
}
|
||||
@@ -5181,6 +5247,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_redirect_request_uses_outgoing_http_scheme() {
|
||||
let info = ProxyRequestInfo {
|
||||
method: Method::GET,
|
||||
original_headers: HeaderMap::new(),
|
||||
original_query: "collection=photos&readDeleted=true".to_string(),
|
||||
path: "/3,01637037d6".to_string(),
|
||||
@@ -5209,6 +5276,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_redirect_request_strips_grpc_port_from_target_url() {
|
||||
let info = ProxyRequestInfo {
|
||||
method: Method::GET,
|
||||
original_headers: HeaderMap::new(),
|
||||
original_query: String::new(),
|
||||
path: "/3,01637037d6".to_string(),
|
||||
@@ -5240,7 +5308,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_redirect_location_drops_extension_for_slash_form() {
|
||||
let info =
|
||||
build_proxy_request_info("/3/01637037d6.jpg", &HeaderMap::new(), "").expect("parses");
|
||||
build_proxy_request_info("/3/01637037d6.jpg", &HeaderMap::new(), "", &Method::GET)
|
||||
.expect("parses");
|
||||
assert_eq!(info.vid_str, "3");
|
||||
assert_eq!(info.fid_str, "01637037d6");
|
||||
|
||||
@@ -5334,6 +5403,60 @@ mod tests {
|
||||
server.abort();
|
||||
}
|
||||
|
||||
/// The master answers a missing volume with 404 and a per-volume `error`
|
||||
/// in the lookup body. Go's LookupResult.Error never becomes the Go error
|
||||
/// return — the volume server treats it as empty locations and replies
|
||||
/// 404. Surfacing it as Err would make proxy-mode reads answer 500.
|
||||
/// A lookup answered with any other failure status (e.g. 503 while the
|
||||
/// master warms up) stays an error, like Go's transport-level failure.
|
||||
#[tokio::test]
|
||||
async fn test_lookup_volume_missing_volume_returns_empty() {
|
||||
use axum::{Router, routing::get};
|
||||
|
||||
let app = Router::new().route(
|
||||
"/dir/lookup",
|
||||
get(|axum::extract::Query(params): axum::extract::Query<
|
||||
std::collections::HashMap<String, String>,
|
||||
>| async move {
|
||||
let (status, error) = match params.get("volumeId").map(String::as_str) {
|
||||
Some("7") => (StatusCode::NOT_FOUND, "volume id 7 not found"),
|
||||
_ => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"service warming up, please retry",
|
||||
),
|
||||
};
|
||||
(
|
||||
status,
|
||||
axum::Json(serde_json::json!({
|
||||
"volumeOrFileId": params.get("volumeId"),
|
||||
"error": error
|
||||
})),
|
||||
)
|
||||
}),
|
||||
);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
let master_url = format!("127.0.0.1:{}", addr.port());
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let locations = super::lookup_volume(&client, "http", &master_url, 7)
|
||||
.await
|
||||
.expect("missing volume is not a lookup failure");
|
||||
assert!(locations.is_empty());
|
||||
|
||||
let err = super::lookup_volume(&client, "http", &master_url, 8)
|
||||
.await
|
||||
.expect_err("master failure is a lookup failure");
|
||||
assert!(err.contains("warming up"));
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
/// A body streaming `data_size` bytes of `file` from offset 0.
|
||||
fn file_streaming_body(
|
||||
file: &std::fs::File,
|
||||
@@ -5392,6 +5515,7 @@ mod tests {
|
||||
});
|
||||
|
||||
let info = ProxyRequestInfo {
|
||||
method: Method::GET,
|
||||
original_headers: HeaderMap::new(),
|
||||
original_query: String::new(),
|
||||
path: "/3,01637037d6".to_string(),
|
||||
@@ -5424,6 +5548,183 @@ mod tests {
|
||||
server.abort();
|
||||
}
|
||||
|
||||
/// Go now forwards the inbound method (volume_server_handlers_read.go), so
|
||||
/// a client HEAD reaches the replica as HEAD, not GET.
|
||||
#[tokio::test]
|
||||
async fn test_proxy_request_preserves_method() {
|
||||
use axum::{Router, routing::get};
|
||||
use std::sync::Arc as StdArc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
|
||||
|
||||
let head_count = StdArc::new(AtomicUsize::new(0));
|
||||
let get_count = StdArc::new(AtomicUsize::new(0));
|
||||
let app = {
|
||||
let head_count = head_count.clone();
|
||||
let get_count = get_count.clone();
|
||||
Router::new().route(
|
||||
"/{*path}",
|
||||
get(move |request: axum::extract::Request| {
|
||||
let head_count = head_count.clone();
|
||||
let get_count = get_count.clone();
|
||||
async move {
|
||||
if *request.method() == Method::HEAD {
|
||||
head_count.fetch_add(1, AtomicOrdering::SeqCst);
|
||||
} else {
|
||||
get_count.fetch_add(1, AtomicOrdering::SeqCst);
|
||||
}
|
||||
StatusCode::OK
|
||||
}
|
||||
}),
|
||||
)
|
||||
};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
let target = VolumeLocation {
|
||||
url: addr.to_string(),
|
||||
public_url: String::new(),
|
||||
grpc_port: 0,
|
||||
read_only: false,
|
||||
read_only_can_delete: false,
|
||||
};
|
||||
let state = streaming_test_state();
|
||||
for method in [Method::HEAD, Method::GET] {
|
||||
let info = ProxyRequestInfo {
|
||||
method,
|
||||
original_headers: HeaderMap::new(),
|
||||
original_query: String::new(),
|
||||
path: "/3,01637037d6".to_string(),
|
||||
vid_str: "3".to_string(),
|
||||
fid_str: "01637037d6".to_string(),
|
||||
};
|
||||
let response = proxy_request(&state, &info, &target).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
assert_eq!(head_count.load(AtomicOrdering::SeqCst), 1);
|
||||
assert_eq!(get_count.load(AtomicOrdering::SeqCst), 1);
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
/// End-to-end headers like Range reach the replica; hop-by-hop headers do
|
||||
/// not — a forwarded Content-Length or Host describes this hop, not the
|
||||
/// replica's, and a lying Content-Length stalls the peer's body read.
|
||||
#[tokio::test]
|
||||
async fn test_proxy_request_drops_hop_by_hop_headers() {
|
||||
use axum::{Router, routing::get};
|
||||
use std::sync::Arc as StdArc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
let seen = StdArc::new(Mutex::new(Vec::new()));
|
||||
let app = {
|
||||
let seen = seen.clone();
|
||||
Router::new().route(
|
||||
"/{*path}",
|
||||
get(move |request: axum::extract::Request| {
|
||||
let seen = seen.clone();
|
||||
async move {
|
||||
let headers: Vec<(String, String)> = request
|
||||
.headers()
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(k.as_str().to_string(), v.to_str().unwrap_or("").to_string())
|
||||
})
|
||||
.collect();
|
||||
seen.lock().unwrap().push(headers);
|
||||
request
|
||||
.headers()
|
||||
.get(header::RANGE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
}),
|
||||
)
|
||||
};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
let target = VolumeLocation {
|
||||
url: addr.to_string(),
|
||||
public_url: String::new(),
|
||||
grpc_port: 0,
|
||||
read_only: false,
|
||||
read_only_can_delete: false,
|
||||
};
|
||||
let mut original_headers = HeaderMap::new();
|
||||
original_headers.insert(header::RANGE, header::HeaderValue::from_static("bytes=0-3"));
|
||||
original_headers.insert(
|
||||
header::HOST,
|
||||
header::HeaderValue::from_static("client-facing:8080"),
|
||||
);
|
||||
original_headers.insert(
|
||||
header::CONTENT_LENGTH,
|
||||
header::HeaderValue::from_static("999"),
|
||||
);
|
||||
original_headers.insert(
|
||||
header::TRANSFER_ENCODING,
|
||||
header::HeaderValue::from_static("chunked"),
|
||||
);
|
||||
original_headers.insert(
|
||||
header::CONNECTION,
|
||||
header::HeaderValue::from_static("keep-alive, x-hop-marker"),
|
||||
);
|
||||
original_headers.insert(
|
||||
"x-hop-marker",
|
||||
header::HeaderValue::from_static("private"),
|
||||
);
|
||||
original_headers.insert(
|
||||
"proxy-authorization",
|
||||
header::HeaderValue::from_static("Basic cHJveHk6c2VjcmV0"),
|
||||
);
|
||||
let info = ProxyRequestInfo {
|
||||
method: Method::GET,
|
||||
original_headers,
|
||||
original_query: String::new(),
|
||||
path: "/3,01637037d6".to_string(),
|
||||
vid_str: "3".to_string(),
|
||||
fid_str: "01637037d6".to_string(),
|
||||
};
|
||||
let response = proxy_request(&streaming_test_state(), &info, &target).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let seen = seen.lock().unwrap();
|
||||
let headers = seen.first().expect("peer saw a request");
|
||||
assert!(
|
||||
headers
|
||||
.iter()
|
||||
.any(|(n, v)| n == "range" && v == "bytes=0-3"),
|
||||
"Range was not forwarded: {headers:?}"
|
||||
);
|
||||
for dropped in [
|
||||
"content-length",
|
||||
"transfer-encoding",
|
||||
"connection",
|
||||
"x-hop-marker",
|
||||
"proxy-authorization",
|
||||
] {
|
||||
assert!(
|
||||
!headers.iter().any(|(n, _)| n == dropped),
|
||||
"hop-by-hop header {dropped} reached the replica: {headers:?}"
|
||||
);
|
||||
}
|
||||
// The peer must see its own host, not the client's.
|
||||
let host = headers
|
||||
.iter()
|
||||
.find(|(n, _)| n == "host")
|
||||
.map(|(_, v)| v.as_str())
|
||||
.expect("replica request has a host header");
|
||||
assert_eq!(host, addr.to_string());
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
fn streaming_test_state() -> Arc<VolumeServerState> {
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::store::Store;
|
||||
@@ -7182,7 +7483,7 @@ mod tests {
|
||||
header::RANGE,
|
||||
header::HeaderValue::from_bytes(b"bytes=0-1\xff").unwrap(),
|
||||
);
|
||||
let info = build_proxy_request_info(&path, &headers, "").unwrap();
|
||||
let info = build_proxy_request_info(&path, &headers, "", &Method::GET).unwrap();
|
||||
|
||||
let resp = proxy_request(&proxy_state, &info, &target).await;
|
||||
assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
|
||||
+20
-9
@@ -82,6 +82,15 @@ type MasterOptions struct {
|
||||
// is cancelled. Used by integration tests and by weed mini; nil for
|
||||
// standalone weed master.
|
||||
shutdownCtx context.Context
|
||||
// releaseAllocOnFirstReport lifts the post-mint allocation hold as soon as
|
||||
// one full volume-server inventory has been applied. weed mini sets it in
|
||||
// single-master mode, with singleReporterAddr pinning the embedded volume
|
||||
// server as the only admitted reporter: any other volume server is refused,
|
||||
// so the warmup window after a fresh topology id is dead time.
|
||||
// Standalone weed master / weed server can face late-arriving veterans and
|
||||
// must keep the window.
|
||||
releaseAllocOnFirstReport bool
|
||||
singleReporterAddr string
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -488,14 +497,16 @@ func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOp
|
||||
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
|
||||
VacuumDeleteEmptyAfterSeconds: *m.vacuumDeleteEmptyAfterSeconds,
|
||||
// PulseSeconds: *m.pulseSeconds,
|
||||
DefaultReplicaPlacement: *m.defaultReplication,
|
||||
GarbageThreshold: *m.garbageThreshold,
|
||||
WhiteList: whiteList,
|
||||
DisableHttp: *m.disableHttp,
|
||||
MetricsAddress: *m.metricsAddress,
|
||||
MetricsIntervalSec: *m.metricsIntervalSec,
|
||||
TelemetryUrl: *m.telemetryUrl,
|
||||
TelemetryEnabled: *m.telemetryEnabled,
|
||||
SingleMaster: isSingleMasterMode(*m.peers),
|
||||
DefaultReplicaPlacement: *m.defaultReplication,
|
||||
GarbageThreshold: *m.garbageThreshold,
|
||||
WhiteList: whiteList,
|
||||
DisableHttp: *m.disableHttp,
|
||||
MetricsAddress: *m.metricsAddress,
|
||||
MetricsIntervalSec: *m.metricsIntervalSec,
|
||||
TelemetryUrl: *m.telemetryUrl,
|
||||
TelemetryEnabled: *m.telemetryEnabled,
|
||||
SingleMaster: isSingleMasterMode(*m.peers),
|
||||
ReleaseAllocOnFirstReport: m.releaseAllocOnFirstReport,
|
||||
SingleVolumeReporter: m.singleReporterAddr,
|
||||
}
|
||||
}
|
||||
@@ -1564,6 +1564,22 @@ func runMini(cmd *Command, args []string) bool {
|
||||
// tear those services down too. On Ctrl+C they rely on their own
|
||||
// OnInterrupt hooks (see grace's LIFO ordering).
|
||||
miniMasterOptions.shutdownCtx = MiniClusterCtx
|
||||
// In single-master mode mini's embedded volume server is the only reporter
|
||||
// of prior cluster state; its first heartbeat already carries the full
|
||||
// inventory, so the post-mint allocation hold ends there instead of
|
||||
// running the whole warmup window on every fresh start. The master pins
|
||||
// the embedded address and refuses any other volume server, keeping the
|
||||
// single-reporter assumption true. Multi-master minis can field
|
||||
// late-reporting volume servers and keep the regular hold.
|
||||
// Both fields are re-derived on every run: the package-level options
|
||||
// survive in-process reruns, so a multi-master mini after a
|
||||
// single-master one must not inherit the release or the stale pin.
|
||||
singleMaster := isSingleMasterMode(*miniMasterOptions.peers)
|
||||
miniMasterOptions.releaseAllocOnFirstReport = singleMaster
|
||||
miniMasterOptions.singleReporterAddr = ""
|
||||
if singleMaster {
|
||||
miniMasterOptions.singleReporterAddr = util.JoinHostPort(*miniIp, *miniOptions.v.port)
|
||||
}
|
||||
miniOptions.v.shutdownCtx = MiniClusterCtx
|
||||
miniFilerOptions.shutdownCtx = MiniClusterCtx
|
||||
// Mini is a small/dev setup with short-lived RPCs; cap the filer's
|
||||
|
||||
@@ -48,6 +48,9 @@ type Entry struct {
|
||||
Remote *filer_pb.RemoteEntry
|
||||
Quota int64
|
||||
WORMEnforcedAtTsNs int64
|
||||
// CommitTsNs is the meta log event timestamp of the mutation that
|
||||
// produced this version. Zero for pre-field versions; they order by mtime.
|
||||
CommitTsNs int64
|
||||
}
|
||||
|
||||
func (entry *Entry) Size() uint64 {
|
||||
@@ -76,6 +79,8 @@ func (entry *Entry) ShallowClone() *Entry {
|
||||
newEntry.Content = entry.Content
|
||||
newEntry.Remote = entry.Remote
|
||||
newEntry.Quota = entry.Quota
|
||||
newEntry.WORMEnforcedAtTsNs = entry.WORMEnforcedAtTsNs
|
||||
newEntry.CommitTsNs = entry.CommitTsNs
|
||||
|
||||
return newEntry
|
||||
}
|
||||
@@ -109,6 +114,7 @@ func (entry *Entry) ToExistingProtoEntry(message *filer_pb.Entry) {
|
||||
message.RemoteEntry = entry.Remote
|
||||
message.Quota = entry.Quota
|
||||
message.WormEnforcedAtTsNs = entry.WORMEnforcedAtTsNs
|
||||
message.CommitTsNs = entry.CommitTsNs
|
||||
}
|
||||
|
||||
func FromPbEntryToExistingEntry(message *filer_pb.Entry, fsEntry *Entry) {
|
||||
@@ -122,6 +128,7 @@ func FromPbEntryToExistingEntry(message *filer_pb.Entry, fsEntry *Entry) {
|
||||
fsEntry.Quota = message.Quota
|
||||
fsEntry.FileSize = FileSize(message)
|
||||
fsEntry.WORMEnforcedAtTsNs = message.WormEnforcedAtTsNs
|
||||
fsEntry.CommitTsNs = message.CommitTsNs
|
||||
}
|
||||
|
||||
func (entry *Entry) ToProtoFullEntry() *filer_pb.FullEntry {
|
||||
|
||||
+26
-9
@@ -115,12 +115,6 @@ type Filer struct {
|
||||
// overwriting the unread ledger with a partial set.
|
||||
deletionLedgerBlocked atomic.Bool
|
||||
deletionLedgerFlush chan struct{}
|
||||
// metaTsPending holds per-path commit records whose KV write failed,
|
||||
// keyed by path; ordering reads consult it until the retry lands them
|
||||
// (see meta_path_ts.go). metaTsRepairing marks paths with a live
|
||||
// repair goroutine so failures neither strand a record nor pile on.
|
||||
metaTsPending sync.Map
|
||||
metaTsRepairing sync.Map
|
||||
// flushCtx is the context metadata-log flushes append under. It stays
|
||||
// live for the process lifetime and is cancelled once during Shutdown,
|
||||
// bounding every retry - in-flight and queued alike - to one deadline.
|
||||
@@ -483,8 +477,20 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
}
|
||||
*/
|
||||
|
||||
emitted := false
|
||||
stamped := false
|
||||
// On abort, release the stamp this call made — one the entry already
|
||||
// carried is a concurrent mutation's and stays for its own event.
|
||||
defer func() {
|
||||
if !emitted && stamped {
|
||||
f.releaseEntryCommitTsNs(entry.CommitTsNs)
|
||||
}
|
||||
}()
|
||||
|
||||
if oldEntry == nil {
|
||||
f.ensureEntryInode(entry)
|
||||
f.stampEntryCommitTsNs(entry)
|
||||
stamped = true
|
||||
|
||||
glog.V(4).InfofCtx(ctx, "InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
|
||||
if err := f.Store.InsertEntry(ctx, entry); err != nil {
|
||||
@@ -517,6 +523,8 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
return fmt.Errorf("%s: %w", entry.FullPath, filer_pb.ErrEntryAlreadyExists)
|
||||
}
|
||||
glog.V(4).InfofCtx(ctx, "UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
|
||||
f.stampEntryCommitTsNs(entry)
|
||||
stamped = true
|
||||
if err := f.UpdateEntry(ctx, oldEntry, entry, isFromOtherCluster); err != nil {
|
||||
if errors.Is(err, filer_pb.ErrExistingIsDirectory) || errors.Is(err, filer_pb.ErrExistingIsFile) {
|
||||
glog.V(2).InfofCtx(ctx, "update entry %s: %v", entry.FullPath, err)
|
||||
@@ -528,6 +536,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
}
|
||||
|
||||
f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
|
||||
emitted = true
|
||||
|
||||
f.deleteChunksIfNotNew(ctx, oldEntry, entry)
|
||||
|
||||
@@ -592,16 +601,18 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di
|
||||
}
|
||||
|
||||
glog.V(2).InfofCtx(ctx, "create directory: %s %v", dirPath, dirEntry.Mode)
|
||||
f.stampEntryCommitTsNs(dirEntry)
|
||||
mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
|
||||
if mkdirErr != nil {
|
||||
f.releaseEntryCommitTsNs(dirEntry.CommitTsNs)
|
||||
if fEntry, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound || fEntry == nil {
|
||||
glog.V(3).InfofCtx(ctx, "mkdir %s: %v", dirPath, mkdirErr)
|
||||
return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
|
||||
}
|
||||
} else if !strings.HasPrefix("/"+util.Join(dirParts[:]...), SystemLogDir) {
|
||||
f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
|
||||
} else {
|
||||
if !strings.HasPrefix("/"+util.Join(dirParts[:]...), SystemLogDir) {
|
||||
f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
|
||||
}
|
||||
f.releaseEntryCommitTsNs(dirEntry.CommitTsNs)
|
||||
}
|
||||
|
||||
} else if !dirEntry.IsDirectory() {
|
||||
@@ -621,7 +632,9 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di
|
||||
dirEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
dirEntry.Extended[s3_constants.SeaweedFSPrefixObject] = []byte("true")
|
||||
f.stampEntryCommitTsNs(dirEntry)
|
||||
if updateErr := f.Store.UpdateEntry(ctx, dirEntry); updateErr != nil {
|
||||
f.releaseEntryCommitTsNs(dirEntry.CommitTsNs)
|
||||
return fmt.Errorf("promote %s to directory: %v", dirPath, updateErr)
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
|
||||
@@ -673,7 +686,9 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath,
|
||||
narrowed := existing.ShallowClone()
|
||||
narrowed.Mode = existing.Mode&^restorableModeBits | kept
|
||||
glog.V(1).InfofCtx(ctx, "restore directory %s: narrowing %v to %v", dirPath, existing.Mode, narrowed.Mode)
|
||||
f.stampEntryCommitTsNs(narrowed)
|
||||
if err := f.UpdateEntry(ctx, existing, narrowed, false); err != nil {
|
||||
f.releaseEntryCommitTsNs(narrowed.CommitTsNs)
|
||||
return err
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, existing, narrowed, false, false, nil)
|
||||
@@ -698,7 +713,9 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath,
|
||||
UserName: attrs.UserName, GroupNames: attrs.GroupNames,
|
||||
}}
|
||||
f.ensureEntryInode(dirEntry)
|
||||
f.stampEntryCommitTsNs(dirEntry)
|
||||
if err := f.Store.InsertEntry(ctx, dirEntry); err != nil {
|
||||
f.releaseEntryCommitTsNs(dirEntry.CommitTsNs)
|
||||
return fmt.Errorf("restore directory %s: %v", dirPath, err)
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, nil, dirEntry, false, false, nil)
|
||||
|
||||
@@ -136,9 +136,11 @@ func (f *Filer) maybeLazyListFromRemote(ctx context.Context, p util.FullPath) {
|
||||
existingEntry.Attr.FileSize = uint64(remoteEntry.RemoteSize)
|
||||
existingEntry.Extended = MergeRemoteContentEncoding(remoteEntry, existingEntry.Extended)
|
||||
}
|
||||
f.stampEntryCommitTsNs(existingEntry)
|
||||
if saveErr := f.Store.UpdateEntry(persistCtx, existingEntry); saveErr != nil {
|
||||
glog.Warningf("maybeLazyListFromRemote: update %s: %v", childPath, saveErr)
|
||||
}
|
||||
f.releaseEntryCommitTsNs(existingEntry.CommitTsNs)
|
||||
} else {
|
||||
// New entry not yet in local store
|
||||
var entry *Entry
|
||||
@@ -228,7 +230,9 @@ func (f *Filer) updateDirectoryListingSyncedAt(ctx context.Context, p util.FullP
|
||||
dirEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
dirEntry.Extended[xattrRemoteListingSyncedAt] = []byte(fmt.Sprintf("%d", syncTime.Unix()))
|
||||
f.stampEntryCommitTsNs(dirEntry)
|
||||
if saveErr := f.Store.UpdateEntry(ctx, dirEntry); saveErr != nil {
|
||||
glog.Warningf("maybeLazyListFromRemote: update synced_at for %s: %v", p, saveErr)
|
||||
}
|
||||
f.releaseEntryCommitTsNs(dirEntry.CommitTsNs)
|
||||
}
|
||||
@@ -29,6 +29,8 @@ func (f *Filer) NotifyUpdateEvent(ctx context.Context, oldEntry, newEntry *Entry
|
||||
|
||||
func (f *Filer) notifyUpdateEvent(ctx context.Context, oldEntry, newEntry *Entry, deleteChunks, isFromOtherCluster bool, signatures []int32) *filer_pb.SubscribeMetadataResponse {
|
||||
if metadataEventsSuppressed(ctx) {
|
||||
// The entry's stamp stays in flight for the covering event the
|
||||
// caller emits itself (the rename handler does).
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -44,6 +46,10 @@ func (f *Filer) notifyUpdateEvent(ctx context.Context, oldEntry, newEntry *Entry
|
||||
// println("fullpath:", fullpath)
|
||||
|
||||
if strings.HasPrefix(fullpath, SystemLogDir) {
|
||||
// No event covers this write: release its stamp.
|
||||
if newEntry != nil {
|
||||
f.metaLogInflight.release(newEntry.CommitTsNs)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
foundSelf := false
|
||||
@@ -56,7 +62,7 @@ func (f *Filer) notifyUpdateEvent(ctx context.Context, oldEntry, newEntry *Entry
|
||||
signatures = append(signatures, f.Signature)
|
||||
}
|
||||
|
||||
event := f.newMetadataEvent(oldEntry, newEntry, deleteChunks, isFromOtherCluster, signatures)
|
||||
event := f.newMetadataEvent(oldEntry, newEntry, deleteChunks, isFromOtherCluster, signatures, f.stampOf(newEntry))
|
||||
// Clear the stamp after the buffer append below - deliberately also on
|
||||
// append failure (see the metaLogInflight comment).
|
||||
defer f.metaLogInflight.done(event.TsNs)
|
||||
@@ -71,10 +77,6 @@ func (f *Filer) notifyUpdateEvent(ctx context.Context, oldEntry, newEntry *Entry
|
||||
}
|
||||
|
||||
f.logMetaEvent(ctx, event)
|
||||
// Record the commit timestamp so a peer replay ordered by the entry lock
|
||||
// this mutation may still be under sees the local change, including as a
|
||||
// tombstone after the entry itself is gone.
|
||||
f.noteCommittedEvent(event)
|
||||
if sink := metadataEventSinkFromContext(ctx); sink != nil {
|
||||
sink.Record(event)
|
||||
}
|
||||
@@ -134,6 +136,28 @@ func (t *metaLogInflight) done(tsNs int64) {
|
||||
}
|
||||
}
|
||||
|
||||
// inFlight reports whether tsNs is a pre-commit stamp still awaiting its
|
||||
// buffer append — how an event adopts the stamp an entry carries.
|
||||
func (t *metaLogInflight) inFlight(tsNs int64) bool {
|
||||
t.Lock()
|
||||
defer t.Unlock()
|
||||
return t.stamped[tsNs] > 0
|
||||
}
|
||||
|
||||
// release drops a stamp whose event will never be appended.
|
||||
func (t *metaLogInflight) release(tsNs int64) {
|
||||
if tsNs == 0 {
|
||||
return
|
||||
}
|
||||
t.Lock()
|
||||
defer t.Unlock()
|
||||
if t.stamped[tsNs] <= 1 {
|
||||
delete(t.stamped, tsNs)
|
||||
} else {
|
||||
t.stamped[tsNs]--
|
||||
}
|
||||
}
|
||||
|
||||
// minTsNs returns the oldest in-flight stamp, or 0 when nothing is in flight.
|
||||
func (t *metaLogInflight) minTsNs() int64 {
|
||||
t.Lock()
|
||||
@@ -197,7 +221,41 @@ func (f *Filer) DoneMetaLogInflightForTest(tsNs int64) {
|
||||
f.metaLogInflight.done(tsNs)
|
||||
}
|
||||
|
||||
func (f *Filer) newMetadataEvent(oldEntry, newEntry *Entry, deleteChunks, isFromOtherCluster bool, signatures []int32) *filer_pb.SubscribeMetadataResponse {
|
||||
// stampEntryCommitTsNs assigns the mutation's event timestamp to the entry
|
||||
// pre-write so the emitted event and stored version carry the same commit
|
||||
// time. The stamp stays in flight until the event appends; a write no event
|
||||
// covers must release it via releaseEntryCommitTsNs.
|
||||
func (f *Filer) stampEntryCommitTsNs(entry *Entry) int64 {
|
||||
tsNs := f.metaLogInflight.stamp()
|
||||
entry.CommitTsNs = tsNs
|
||||
return tsNs
|
||||
}
|
||||
|
||||
// releaseEntryCommitTsNs drops a stamp no event will adopt.
|
||||
func (f *Filer) releaseEntryCommitTsNs(tsNs int64) {
|
||||
f.metaLogInflight.release(tsNs)
|
||||
}
|
||||
|
||||
// StampEntryCommitTsNs/ReleaseEntryCommitTsNs expose the lifecycle to the
|
||||
// filer server's mutation paths.
|
||||
func (f *Filer) StampEntryCommitTsNs(entry *Entry) int64 {
|
||||
return f.stampEntryCommitTsNs(entry)
|
||||
}
|
||||
|
||||
func (f *Filer) ReleaseEntryCommitTsNs(tsNs int64) {
|
||||
f.metaLogInflight.release(tsNs)
|
||||
}
|
||||
|
||||
// stampOf returns the event's timestamp: the entry's in-flight stamp, or a
|
||||
// fresh one for events with no newly stamped entry (deletes).
|
||||
func (f *Filer) stampOf(newEntry *Entry) int64 {
|
||||
if newEntry != nil && f.metaLogInflight.inFlight(newEntry.CommitTsNs) {
|
||||
return newEntry.CommitTsNs
|
||||
}
|
||||
return f.metaLogInflight.stamp()
|
||||
}
|
||||
|
||||
func (f *Filer) newMetadataEvent(oldEntry, newEntry *Entry, deleteChunks, isFromOtherCluster bool, signatures []int32, tsNs int64) *filer_pb.SubscribeMetadataResponse {
|
||||
if oldEntry == nil && newEntry == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -224,7 +282,7 @@ func (f *Filer) newMetadataEvent(oldEntry, newEntry *Entry, deleteChunks, isFrom
|
||||
Signatures: signatures,
|
||||
},
|
||||
// In flight until appended to the local log buffer (see metaLogInflight).
|
||||
TsNs: f.metaLogInflight.stamp(),
|
||||
TsNs: tsNs,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -754,10 +754,8 @@ func (ma *MetaAggregator) traversePeerMetadata(ctx context.Context, f *Filer, pe
|
||||
continue
|
||||
}
|
||||
entry := FromPbEntry(resp.Directory, resp.Entry)
|
||||
// Order on the sender's per-path commit timestamp, not the
|
||||
// entry's mtime — mtime is client-settable and does not track
|
||||
// when the peer committed the change. Peers that predate the
|
||||
// field send 0 and fall back to mtime.
|
||||
// Order on the sender's commit timestamp, not client-settable
|
||||
// mtime. Peers predating the field send 0: fall back to mtime.
|
||||
peerTsNs := resp.EntryTsNs
|
||||
if peerTsNs == 0 {
|
||||
peerTsNs = entry.Attr.Mtime.UnixNano()
|
||||
@@ -776,10 +774,9 @@ func (ma *MetaAggregator) traversePeerMetadata(ctx context.Context, f *Filer, pe
|
||||
}
|
||||
|
||||
// applyTraversedEntry merges one bootstrap entry under the path's replay
|
||||
// locks, keeping local state when its commit is newer than the sender's —
|
||||
// most importantly a delete, whose tombstone must not let the bootstrap
|
||||
// resurrect the path. An applied entry records the sender's commit time so a
|
||||
// later peer replay orders against it rather than the entry's mtime.
|
||||
// locks, keeping local state when its commit is newer than the sender's.
|
||||
// An applied entry keeps the sender's commit time on its stamp so a later
|
||||
// peer replay orders against it rather than the entry's mtime.
|
||||
func (f *Filer) applyTraversedEntry(ctx context.Context, entry *Entry, peerTsNs int64) error {
|
||||
unlock := f.lockReplayPaths(entry.FullPath, "")
|
||||
defer unlock()
|
||||
@@ -805,6 +802,7 @@ func (f *Filer) applyTraversedEntry(ctx context.Context, entry *Entry, peerTsNs
|
||||
return nil
|
||||
}
|
||||
}
|
||||
entry.CommitTsNs = peerTsNs
|
||||
if insertErr := f.Store.InsertEntry(ctx, entry); insertErr != nil {
|
||||
// Entry already exists (root dir, or partial previous bootstrap);
|
||||
// the lock kept the check above current, so the peer commit is newer.
|
||||
@@ -815,7 +813,6 @@ func (f *Filer) applyTraversedEntry(ctx context.Context, entry *Entry, peerTsNs
|
||||
return fmt.Errorf("update entry %s: %w", entry.FullPath, updateErr)
|
||||
}
|
||||
}
|
||||
f.notePathChange(entry.FullPath, peerTsNs, false)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
)
|
||||
|
||||
// newReplayTestFiler builds the minimum Filer Replay needs over a stub store.
|
||||
|
||||
func newReplayTestFiler(store FilerStore) *Filer {
|
||||
return &Filer{
|
||||
Store: NewFilerStoreWrapper(store),
|
||||
@@ -259,58 +260,6 @@ func TestReplayMoveChecksEachPathSeparately(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A local delete leaves a recorded tombstone, so a replayed create older than
|
||||
// the delete must not resurrect the path even though no entry remains to
|
||||
// compare against.
|
||||
func TestReplaySkipsCreateOlderThanLocalDelete(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
now := time.Now()
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
// The delete removed the entry; its commit record survives.
|
||||
f.notePathChange(path, now.UnixNano(), true)
|
||||
|
||||
createEvent := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{Name: "file", Content: []byte("stale resurrect")},
|
||||
},
|
||||
TsNs: now.Add(-time.Minute).UnixNano(),
|
||||
}
|
||||
if err := f.Replay(createEvent); err != nil {
|
||||
t.Fatalf("Replay: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), path); err == nil {
|
||||
t.Fatal("stale replayed create resurrected a locally deleted entry")
|
||||
}
|
||||
}
|
||||
|
||||
// A deleted directory covers its children: a bulk drop emits no per-child
|
||||
// events, so the tombstone on the ancestor is what a replayed child create
|
||||
// must check.
|
||||
func TestReplaySkipsCreateUnderDeletedAncestor(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
now := time.Now()
|
||||
|
||||
f.notePathChange("/dir", now.UnixNano(), true)
|
||||
|
||||
createEvent := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{Name: "child", Content: []byte("stale")},
|
||||
},
|
||||
TsNs: now.Add(-time.Minute).UnixNano(),
|
||||
}
|
||||
if err := f.Replay(createEvent); err != nil {
|
||||
t.Fatalf("Replay: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), "/dir/child"); err == nil {
|
||||
t.Fatal("stale replayed create resurrected a child of a deleted directory")
|
||||
}
|
||||
}
|
||||
|
||||
// A recorded commit timestamp orders replay, not the entry's mtime: a rename
|
||||
// keeps the source's mtime on the destination, and a mounted client can set
|
||||
// mtime arbitrarily, so an entry whose mtime postdates the event must still
|
||||
@@ -324,9 +273,9 @@ func TestReplayAppliesWhenCommitRecordIsOlderThanFutureMtime(t *testing.T) {
|
||||
FullPath: path,
|
||||
Attr: Attr{Mtime: now.Add(time.Hour)}, // future mtime, e.g. client-set or kept from a rename source
|
||||
Content: []byte("old destination"),
|
||||
// The last committed change predates the event.
|
||||
CommitTsNs: now.Add(-time.Minute).UnixNano(),
|
||||
}
|
||||
// The last committed change predates the event.
|
||||
f.notePathChange(path, now.Add(-time.Minute).UnixNano(), false)
|
||||
|
||||
event := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/a",
|
||||
@@ -372,9 +321,9 @@ func TestReplaySerializesWithEntryLock(t *testing.T) {
|
||||
store.entries[string(path)] = &Entry{FullPath: path, Attr: Attr{Mtime: now}}
|
||||
|
||||
// A local mutation holding the path lock; a replay started behind it
|
||||
// sees the recorded commit and skips.
|
||||
// sees the entry's commit stamp and skips.
|
||||
held := f.EntryLockTable.AcquireLock("test local write", path, util.ExclusiveLock)
|
||||
f.notePathChange(path, now.UnixNano(), false)
|
||||
store.entries[string(path)].CommitTsNs = now.UnixNano()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
@@ -421,18 +370,6 @@ func TestReplicateMetadataChangeAbortsOnStop(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Commit-record keys must stay small: SQL KV stores keep the key suffix in a
|
||||
// VARCHAR(766) column, so a raw path over ~578 bytes silently drops the
|
||||
// record (the insert fails and the fallback update touches no row).
|
||||
func TestMetaPathKeyFixedSizeForLongPaths(t *testing.T) {
|
||||
path := util.NewFullPath("/", string(make([]rune, 600)))
|
||||
for _, p := range []util.FullPath{"/a", path} {
|
||||
if got := len(metaPathKey(metaPathTsPrefix, p)); got != len(metaPathTsPrefix)+16 {
|
||||
t.Fatalf("metaPathKey(%d-byte path) = %d bytes, want %d", len(p), got, len(metaPathTsPrefix)+16)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exact-path locking alone lets a replayed child create slip between a local
|
||||
// ancestor delete's tombstone check and the sweep: replay locks every
|
||||
// ancestor too, so it waits for the delete's lock and then sees the
|
||||
@@ -444,7 +381,6 @@ func TestReplaySerializesWithAncestorLock(t *testing.T) {
|
||||
now := time.Now()
|
||||
child := util.NewFullPath("/dir", "file")
|
||||
held := f.EntryLockTable.AcquireLock("test local delete", "/dir", util.ExclusiveLock)
|
||||
f.notePathChange("/dir", now.UnixNano(), true)
|
||||
|
||||
createEvent := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
@@ -466,32 +402,9 @@ func TestReplaySerializesWithAncestorLock(t *testing.T) {
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("Replay: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), child); err == nil {
|
||||
t.Fatal("stale replayed create resurrected a child of a locally deleted directory")
|
||||
}
|
||||
}
|
||||
|
||||
// Bootstrap ordering uses the sender's commit timestamp: a local commit
|
||||
// newer than the traversed entry keeps its state even when the peer entry's
|
||||
// mtime is far in the future.
|
||||
func TestBootstrapSkipsPeerEntryBehindLocalDelete(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
now := time.Now()
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
f.notePathChange(path, now.UnixNano(), true)
|
||||
|
||||
entry := &Entry{
|
||||
FullPath: path,
|
||||
Attr: Attr{Mtime: now.Add(time.Hour)}, // client-settable, must not win
|
||||
Content: []byte("stale peer entry"),
|
||||
}
|
||||
if err := f.applyTraversedEntry(context.Background(), entry, now.Add(-time.Minute).UnixNano()); err != nil {
|
||||
t.Fatalf("applyTraversedEntry: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), path); err == nil {
|
||||
t.Fatal("bootstrap resurrected a path newer local delete covered")
|
||||
// No tombstone protects the deleted ancestor: the stale create lands.
|
||||
if _, err := store.FindEntry(context.Background(), child); err != nil {
|
||||
t.Fatalf("stale create applies once the lock releases: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,11 +468,11 @@ func TestBootstrapUpdatesExistingByCommitTime(t *testing.T) {
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
store.entries[string(path)] = &Entry{
|
||||
FullPath: path,
|
||||
Attr: Attr{Mtime: now.Add(time.Hour)}, // future mtime, e.g. client-set
|
||||
Content: []byte("old local write"),
|
||||
FullPath: path,
|
||||
Attr: Attr{Mtime: now.Add(time.Hour)}, // future mtime, e.g. client-set
|
||||
Content: []byte("old local write"),
|
||||
CommitTsNs: now.Add(-time.Minute).UnixNano(),
|
||||
}
|
||||
f.notePathChange(path, now.Add(-time.Minute).UnixNano(), false)
|
||||
|
||||
entry := &Entry{
|
||||
FullPath: path,
|
||||
@@ -612,139 +525,23 @@ func TestBootstrapCopiesMissingEntryWithoutCommitTime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A delete whose commit record failed to persist still blocks a stale
|
||||
// replayed create: the pending record stands in until the retry lands it.
|
||||
func TestPendingDeleteRecordBlocksStaleReplay(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
store.setKvPutErr(errors.New("kv store unreachable"))
|
||||
f := newReplayTestFiler(store)
|
||||
f.flushCtx, f.flushCancel = context.WithCancel(context.Background())
|
||||
defer f.flushCancel()
|
||||
now := time.Now()
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
// The delete already committed; only its ordering record failed.
|
||||
f.notePathChange(path, now.UnixNano(), true)
|
||||
|
||||
createEvent := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{Name: "file", Content: []byte("stale resurrect")},
|
||||
},
|
||||
TsNs: now.Add(-time.Minute).UnixNano(),
|
||||
}
|
||||
if err := f.Replay(createEvent); err != nil {
|
||||
t.Fatalf("Replay: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), path); err == nil {
|
||||
t.Fatal("stale create resurrected a path whose delete record is still pending")
|
||||
}
|
||||
}
|
||||
|
||||
// The failed record write retries until it lands, then leaves the pending set.
|
||||
func TestPendingCommitRecordRepairs(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
f.flushCtx, f.flushCancel = context.WithCancel(context.Background())
|
||||
defer f.flushCancel()
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
store.setKvPutErr(errors.New("kv store unreachable"))
|
||||
f.notePathChange(path, 100, true)
|
||||
if _, loaded := f.metaTsPending.Load(string(path)); !loaded {
|
||||
t.Fatal("failed record write must stay pending")
|
||||
}
|
||||
store.setKvPutErr(nil)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, loaded := f.metaTsPending.Load(string(path)); !loaded {
|
||||
ts, found, err := f.kvReadTsNs(context.Background(), metaPathKey(metaPathDelPrefix, path))
|
||||
if err != nil || !found || ts != 100 {
|
||||
t.Fatalf("delete record after repair: ts=%v found=%v err=%v", ts, found, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("pending record was not repaired")
|
||||
}
|
||||
|
||||
// CommitTsNs reports the recorded commit time over the entry mtime, and a
|
||||
// still-pending record over both.
|
||||
func TestCommitTsNsPrefersRecordAndPending(t *testing.T) {
|
||||
// CommitTsNs reports the commit timestamp stamped on the entry, or the
|
||||
// fallback when the entry predates stamping or is gone.
|
||||
func TestCommitTsNsFromEntry(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
if got, err := f.CommitTsNs(context.Background(), path, 7); err != nil || got != 7 {
|
||||
t.Fatalf("no record: CommitTsNs = %d, %v; want fallback 7", got, err)
|
||||
t.Fatalf("no entry: CommitTsNs = %d, %v; want fallback 7", got, err)
|
||||
}
|
||||
f.notePathChange(path, 50, false)
|
||||
store.entries[string(path)] = &Entry{FullPath: path, CommitTsNs: 50}
|
||||
if got, err := f.CommitTsNs(context.Background(), path, 7); err != nil || got != 50 {
|
||||
t.Fatalf("recorded: CommitTsNs = %d, %v; want 50", got, err)
|
||||
t.Fatalf("stamped: CommitTsNs = %d, %v; want 50", got, err)
|
||||
}
|
||||
pending := &metaTsPendingRec{}
|
||||
pending.changeTsNs.Store(80)
|
||||
f.metaTsPending.Store(string(path), pending)
|
||||
if got, err := f.CommitTsNs(context.Background(), path, 7); err != nil || got != 80 {
|
||||
t.Fatalf("pending: CommitTsNs = %d, %v; want 80", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A successful write discharges what the pending record owed before it, so a
|
||||
// repair pass can never put an older timestamp back over it.
|
||||
func TestPendingCommitRecordDischargedByNewerWrite(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
f.flushCtx, f.flushCancel = context.WithCancel(context.Background())
|
||||
defer f.flushCancel()
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
store.setKvPutErr(errors.New("kv store unreachable"))
|
||||
f.notePathChange(path, 100, false)
|
||||
store.setKvPutErr(nil)
|
||||
f.notePathChange(path, 200, false)
|
||||
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, loaded := f.metaTsPending.Load(string(path)); !loaded {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
ts, found, err := f.kvReadTsNs(context.Background(), metaPathKey(metaPathTsPrefix, path))
|
||||
if err != nil || !found || ts != 200 {
|
||||
t.Fatalf("MpTs after repair = %v, %v, %v; want 200", ts, found, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed delete record keeps its own time even when a later failed change
|
||||
// merges into the pending record: the repair must not stamp the delete at
|
||||
// the newer change's time.
|
||||
func TestPendingDeleteRecordKeepsItsTime(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
store.setKvPutErr(errors.New("kv store unreachable"))
|
||||
f := newReplayTestFiler(store)
|
||||
f.flushCtx, f.flushCancel = context.WithCancel(context.Background())
|
||||
defer f.flushCancel()
|
||||
path := util.NewFullPath("/dir", "file")
|
||||
|
||||
f.notePathChange(path, 100, true)
|
||||
f.notePathChange(path, 200, false)
|
||||
store.setKvPutErr(nil)
|
||||
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, loaded := f.metaTsPending.Load(string(path)); !loaded {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if ts, found, err := f.kvReadTsNs(context.Background(), metaPathKey(metaPathTsPrefix, path)); err != nil || !found || ts != 200 {
|
||||
t.Fatalf("MpTs = %v, %v, %v; want 200", ts, found, err)
|
||||
}
|
||||
if ts, found, err := f.kvReadTsNs(context.Background(), metaPathKey(metaPathDelPrefix, path)); err != nil || !found || ts != 100 {
|
||||
t.Fatalf("MpDl = %v, %v, %v; want 100", ts, found, err)
|
||||
store.entries[string(path)].CommitTsNs = 0
|
||||
if got, err := f.CommitTsNs(context.Background(), path, 7); err != nil || got != 7 {
|
||||
t.Fatalf("unstamped: CommitTsNs = %d, %v; want fallback 7", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -906,9 +703,10 @@ func TestReplayDirectoryDeleteKeepsNewerChildren(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A directory kept for newer descendants still records the delete: a stale
|
||||
// create replayed later for another child must be fenced by it.
|
||||
func TestReplayKeptDirectoryDeleteFencesStaleCreates(t *testing.T) {
|
||||
// A directory kept for newer descendants records no delete — tombstones are
|
||||
// gone — so a stale create replayed later for another child resurrects
|
||||
// under it. This documents the accepted tradeoff.
|
||||
func TestReplayKeptDirectoryDeleteAllowsStaleCreates(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
@@ -952,8 +750,8 @@ func TestReplayKeptDirectoryDeleteFencesStaleCreates(t *testing.T) {
|
||||
if err := f.Replay(stale); err != nil {
|
||||
t.Fatalf("replay stale create: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(ctx, "/d/late.txt"); !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
t.Fatal("stale create resurrected a child under a directory the origin deleted")
|
||||
if _, err := store.FindEntry(ctx, "/d/late.txt"); err != nil {
|
||||
t.Fatalf("no tombstone exists, so the stale create lands: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1569,3 +1367,45 @@ func TestReplaySweepKeepsRemoteOnlyOwnerOfPath(t *testing.T) {
|
||||
t.Fatalf("the owned remote object must be kept, got %v", stub.deleteCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// A directory metadata update is not a subtree delete: replaying one must
|
||||
// leave no tombstone, or a child event older than the update is suppressed
|
||||
// even though nobody deleted the children.
|
||||
func TestReplayDirUpdateDoesNotSuppressChildren(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
now := time.Now()
|
||||
|
||||
store.entries["/dir"] = &Entry{
|
||||
FullPath: "/dir",
|
||||
Attr: Attr{Mtime: now.Add(-time.Hour), Mode: os.ModeDir | 0755},
|
||||
}
|
||||
update := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: "dir", IsDirectory: true},
|
||||
NewEntry: &filer_pb.Entry{Name: "dir", IsDirectory: true},
|
||||
},
|
||||
TsNs: now.UnixNano(),
|
||||
}
|
||||
if err := f.Replay(update); err != nil {
|
||||
t.Fatalf("Replay dir update: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), "/dir"); err != nil {
|
||||
t.Fatalf("the updated directory must be back in place: %v", err)
|
||||
}
|
||||
|
||||
create := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{Name: "child", Content: []byte("data")},
|
||||
},
|
||||
TsNs: now.Add(-time.Minute).UnixNano(),
|
||||
}
|
||||
if err := f.Replay(create); err != nil {
|
||||
t.Fatalf("Replay child create: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(context.Background(), "/dir/child"); err != nil {
|
||||
t.Fatalf("a child create older than the dir update must apply: %v", err)
|
||||
}
|
||||
}
|
||||
+23
-291
@@ -2,323 +2,55 @@ package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const (
|
||||
// metaPathTsPrefix keys per-path commit timestamps in the filer store KV:
|
||||
// the newest event timestamp this filer committed or applied for the
|
||||
// path. Written for every emitted mutation event and kept after the entry
|
||||
// is deleted, so a replayed peer event can still be ordered against a
|
||||
// change that left no entry behind.
|
||||
metaPathTsPrefix = "MpTs"
|
||||
// metaPathDelPrefix keys delete-only timestamps. A replayed event checks
|
||||
// the path's ancestors too, so a directory delete also covers children
|
||||
// swept without per-child events (a dropped bucket's whole-store delete,
|
||||
// or a walk aborted partway).
|
||||
metaPathDelPrefix = "MpDl"
|
||||
)
|
||||
|
||||
// metaPathKey hashes the path into a fixed-size key. SQL-backed KV stores
|
||||
// split the key at byte 8 and store the remainder base64-encoded in a
|
||||
// VARCHAR(766) name column: a raw path over ~578 bytes overflows it, the
|
||||
// KvPut insert fails, and the fallback update touches no row yet returns no
|
||||
// error — the commit record would never land and stale replay could restore
|
||||
// the path.
|
||||
func metaPathKey(prefix string, path util.FullPath) []byte {
|
||||
sum := sha256.Sum256([]byte(path))
|
||||
key := make([]byte, len(prefix)+16)
|
||||
copy(key, prefix)
|
||||
copy(key[len(prefix):], sum[:16])
|
||||
return key
|
||||
}
|
||||
|
||||
// kvReadTsNs returns the timestamp recorded for key, or found=false when the
|
||||
// key is absent or malformed. Any other store read failure is an error: a
|
||||
// caller deciding whether a replayed change is stale must not guess.
|
||||
func (f *Filer) kvReadTsNs(ctx context.Context, key []byte) (tsNs int64, found bool, err error) {
|
||||
value, err := f.Store.KvGet(ctx, key)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrKvNotFound) {
|
||||
return 0, false, nil
|
||||
}
|
||||
return 0, false, err
|
||||
}
|
||||
if len(value) < 8 {
|
||||
return 0, false, nil
|
||||
}
|
||||
return int64(util.BytesToUint64(value)), true, nil
|
||||
}
|
||||
|
||||
// notePathChange persists tsNs as path's newest committed change. Local event
|
||||
// timestamps are stamped monotonically (metaLogInflight.stamp), so a plain
|
||||
// put cannot regress an earlier local record; a higher peer record it may
|
||||
// overwrite was already newer under last-writer-wins ordering anyway. A
|
||||
// delete additionally writes a delete record the ancestor lookup consults.
|
||||
//
|
||||
// The write uses a fresh context: callers notify after CommitTransaction,
|
||||
// and SQL stores keep the already-committed *sql.Tx in the request context —
|
||||
// a record written through it would fail and the path would lose ordering.
|
||||
//
|
||||
// A failed write is kept in metaTsPending and retried in the background: the
|
||||
// mutation the record orders has already committed, so dropping it would let
|
||||
// a stale replayed change overwrite or resurrect the path while the store is
|
||||
// unreachable. Ordering reads consult the pending record until the retry
|
||||
// lands it.
|
||||
func (f *Filer) notePathChange(path util.FullPath, tsNs int64, deleted bool) {
|
||||
if f.Store == nil {
|
||||
return
|
||||
}
|
||||
ctx := context.Background()
|
||||
key := string(path)
|
||||
rec := f.pendingRec(key)
|
||||
defer rec.mu.Unlock()
|
||||
|
||||
value := make([]byte, 8)
|
||||
util.Uint64toBytes(value, uint64(tsNs))
|
||||
if err := f.Store.KvPut(ctx, metaPathKey(metaPathTsPrefix, path), value); err != nil {
|
||||
glog.WarningfCtx(ctx, "record meta change time %s: %v", path, err)
|
||||
if tsNs > rec.changeTsNs.Load() {
|
||||
rec.changeTsNs.Store(tsNs)
|
||||
}
|
||||
} else if rec.changeTsNs.Load() <= tsNs {
|
||||
// This write covers every change record owed so far.
|
||||
rec.changeTsNs.Store(0)
|
||||
}
|
||||
if deleted {
|
||||
if err := f.Store.KvPut(ctx, metaPathKey(metaPathDelPrefix, path), value); err != nil {
|
||||
glog.WarningfCtx(ctx, "record meta delete time %s: %v", path, err)
|
||||
if tsNs > rec.deleteTsNs.Load() {
|
||||
rec.deleteTsNs.Store(tsNs)
|
||||
}
|
||||
} else if rec.deleteTsNs.Load() <= tsNs {
|
||||
rec.deleteTsNs.Store(0)
|
||||
}
|
||||
}
|
||||
if rec.changeTsNs.Load() == 0 && rec.deleteTsNs.Load() == 0 {
|
||||
f.metaTsPending.CompareAndDelete(key, rec)
|
||||
return
|
||||
}
|
||||
if _, running := f.metaTsRepairing.LoadOrStore(key, struct{}{}); !running {
|
||||
go f.repairMetaPathTs(path)
|
||||
}
|
||||
}
|
||||
|
||||
// metaTsPendingRec is a commit record still on its way to the store, holding
|
||||
// only work not yet written: changeTsNs is the newest committed change the
|
||||
// MpTs record lacks and deleteTsNs the newest delete the MpDl record lacks —
|
||||
// the two keep their own times so a later update cannot masquerade as the
|
||||
// delete. Store writes and the bookkeeping they discharge share mu, so a
|
||||
// repair pass can never write an older record over a newer one that already
|
||||
// landed; readers take the atomic fields directly.
|
||||
type metaTsPendingRec struct {
|
||||
mu sync.Mutex
|
||||
changeTsNs atomic.Int64
|
||||
deleteTsNs atomic.Int64
|
||||
}
|
||||
|
||||
// pendingRec returns the live pending record for key, locked for mutation,
|
||||
// recreating it when a repair already dropped the previous one.
|
||||
func (f *Filer) pendingRec(key string) *metaTsPendingRec {
|
||||
for {
|
||||
cur, _ := f.metaTsPending.LoadOrStore(key, &metaTsPendingRec{})
|
||||
rec := cur.(*metaTsPendingRec)
|
||||
rec.mu.Lock()
|
||||
if live, ok := f.metaTsPending.Load(key); ok && live == cur {
|
||||
return rec
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// repairMetaPathTs retries a pending commit record until it lands. Each pass
|
||||
// writes only what the record still owes, so a merge by a later failure is
|
||||
// picked up without another goroutine and a landed write is never rewritten.
|
||||
// The retry is unbounded — the mutation is already committed and only the
|
||||
// record preserves its ordering.
|
||||
func (f *Filer) repairMetaPathTs(path util.FullPath) {
|
||||
key := string(path)
|
||||
ctx := f.flushCtx
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
defer func() {
|
||||
f.metaTsRepairing.Delete(key)
|
||||
// A failure landing between the last pass and the flag release
|
||||
// still needs a repair pass — unless the retry context is done.
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if _, ok := f.metaTsPending.Load(key); ok {
|
||||
if _, running := f.metaTsRepairing.LoadOrStore(key, struct{}{}); !running {
|
||||
go f.repairMetaPathTs(path)
|
||||
}
|
||||
}
|
||||
}()
|
||||
for {
|
||||
if _, ok := f.metaTsPending.Load(key); !ok {
|
||||
return
|
||||
}
|
||||
rec := f.pendingRec(key)
|
||||
var tsErr, delErr error
|
||||
if tsNs := rec.changeTsNs.Load(); tsNs > 0 {
|
||||
value := make([]byte, 8)
|
||||
util.Uint64toBytes(value, uint64(tsNs))
|
||||
if tsErr = f.Store.KvPut(ctx, metaPathKey(metaPathTsPrefix, path), value); tsErr == nil {
|
||||
rec.changeTsNs.Store(0)
|
||||
}
|
||||
}
|
||||
if tsNs := rec.deleteTsNs.Load(); tsNs > 0 {
|
||||
value := make([]byte, 8)
|
||||
util.Uint64toBytes(value, uint64(tsNs))
|
||||
if delErr = f.Store.KvPut(ctx, metaPathKey(metaPathDelPrefix, path), value); delErr == nil {
|
||||
rec.deleteTsNs.Store(0)
|
||||
}
|
||||
}
|
||||
done := rec.changeTsNs.Load() == 0 && rec.deleteTsNs.Load() == 0
|
||||
if done {
|
||||
f.metaTsPending.CompareAndDelete(key, rec)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
if !done {
|
||||
glog.V(0).InfofCtx(ctx, "retry record meta change time %s: %v %v", path, tsErr, delErr)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pendingPathTsNs returns the newest pending commit timestamp for path and
|
||||
// the newest pending delete timestamp.
|
||||
func (f *Filer) pendingPathTsNs(path util.FullPath) (changeTsNs, deleteTsNs int64) {
|
||||
cur, ok := f.metaTsPending.Load(string(path))
|
||||
if !ok {
|
||||
return 0, 0
|
||||
}
|
||||
rec := cur.(*metaTsPendingRec)
|
||||
return rec.changeTsNs.Load(), rec.deleteTsNs.Load()
|
||||
}
|
||||
|
||||
// CommitTsNs returns the newest commit timestamp known for path — the
|
||||
// recorded event time, or a still-pending one — and fallbackTsNs when none
|
||||
// exists. Peers stamp traversal entries with it so a bootstrap subscriber
|
||||
// orders each entry on the sender's commit clock rather than the entry's
|
||||
// client-settable mtime. A store read failure is an error, not a fallback:
|
||||
// the mtime it would mint could outdate real commits.
|
||||
// CommitTsNs resolves the commit timestamp at path for traversal: the
|
||||
// entry's stamp, else fallbackTsNs for pre-stamp or missing entries.
|
||||
func (f *Filer) CommitTsNs(ctx context.Context, path util.FullPath, fallbackTsNs int64) (int64, error) {
|
||||
if f.Store == nil {
|
||||
return fallbackTsNs, nil
|
||||
}
|
||||
tsNs := fallbackTsNs
|
||||
recTs, found, err := f.kvReadTsNs(ctx, metaPathKey(metaPathTsPrefix, path))
|
||||
entry, err := f.Store.FindEntry(ctx, path)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fallbackTsNs, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
if found {
|
||||
tsNs = recTs
|
||||
if entry == nil {
|
||||
return fallbackTsNs, nil
|
||||
}
|
||||
if pendTs, _ := f.pendingPathTsNs(path); pendTs > tsNs {
|
||||
tsNs = pendTs
|
||||
}
|
||||
return tsNs, nil
|
||||
return f.EntryCommitTsNs(ctx, entry, fallbackTsNs)
|
||||
}
|
||||
|
||||
// noteCommittedEvent records the event's commit timestamp for every path it
|
||||
// touches: the source of a delete or rename, and the target of a create,
|
||||
// update, or rename. It runs after the local mutation commits while the
|
||||
// caller still holds the path's entry lock (for filer-server mutations), so
|
||||
// a peer replay ordered by the same lock sees either the whole local change
|
||||
// or none of it.
|
||||
func (f *Filer) noteCommittedEvent(event *filer_pb.SubscribeMetadataResponse) {
|
||||
message := event.EventNotification
|
||||
if message == nil {
|
||||
return
|
||||
}
|
||||
var source, target util.FullPath
|
||||
if message.OldEntry != nil {
|
||||
source = util.FullPath(filer_pb.MetadataEventSourceFullPath(event))
|
||||
}
|
||||
if message.NewEntry != nil {
|
||||
target = util.FullPath(filer_pb.MetadataEventTargetFullPath(event))
|
||||
}
|
||||
// A delete or a rename removes the source path; an update reports the
|
||||
// same path on both sides and counts once.
|
||||
if source != "" && source != target {
|
||||
f.notePathChange(source, event.TsNs, true)
|
||||
}
|
||||
if target != "" {
|
||||
f.notePathChange(target, event.TsNs, false)
|
||||
// EntryCommitTsNs returns the stamp on an already-loaded entry, else
|
||||
// fallbackTsNs.
|
||||
func (f *Filer) EntryCommitTsNs(ctx context.Context, entry *Entry, fallbackTsNs int64) (int64, error) {
|
||||
if entry.CommitTsNs != 0 {
|
||||
return entry.CommitTsNs, nil
|
||||
}
|
||||
return fallbackTsNs, nil
|
||||
}
|
||||
|
||||
// deletedAfterTsNs returns the newest recorded delete timestamp among path
|
||||
// and its ancestors.
|
||||
func (f *Filer) deletedAfterTsNs(ctx context.Context, path util.FullPath) (int64, error) {
|
||||
var tsNs int64
|
||||
for p := string(path); p != "" && p != "/"; {
|
||||
ts, found, err := f.kvReadTsNs(ctx, metaPathKey(metaPathDelPrefix, util.FullPath(p)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if found && ts > tsNs {
|
||||
tsNs = ts
|
||||
}
|
||||
if _, pendDel := f.pendingPathTsNs(util.FullPath(p)); pendDel > tsNs {
|
||||
tsNs = pendDel
|
||||
}
|
||||
i := strings.LastIndexByte(p, '/')
|
||||
if i <= 0 {
|
||||
break
|
||||
}
|
||||
p = p[:i]
|
||||
}
|
||||
return tsNs, nil
|
||||
}
|
||||
|
||||
// localCommitTsNs returns the newest timestamp this filer is known to have
|
||||
// committed for path: the recorded event time when one exists — it is not
|
||||
// client-controllable the way an entry's mtime is — else the entry's mtime
|
||||
// for entries written before recording existed, plus any recorded delete of
|
||||
// the path or an ancestor.
|
||||
// localCommitTsNs returns this filer's newest known commit time for path:
|
||||
// the entry's stamp — not client-controllable like mtime — else mtime.
|
||||
func (f *Filer) localCommitTsNs(ctx context.Context, path util.FullPath) (int64, error) {
|
||||
if f.Store == nil {
|
||||
return 0, nil
|
||||
}
|
||||
var tsNs int64
|
||||
recTs, found, err := f.kvReadTsNs(ctx, metaPathKey(metaPathTsPrefix, path))
|
||||
entry, err := f.Store.FindEntry(ctx, path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if found {
|
||||
tsNs = recTs
|
||||
} else if entry, findErr := f.Store.FindEntry(ctx, path); findErr != nil {
|
||||
if !errors.Is(findErr, filer_pb.ErrNotFound) {
|
||||
return 0, findErr
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return 0, nil
|
||||
}
|
||||
} else if entry != nil {
|
||||
tsNs = entry.Mtime.UnixNano()
|
||||
}
|
||||
if pendTs, _ := f.pendingPathTsNs(path); pendTs > tsNs {
|
||||
tsNs = pendTs
|
||||
}
|
||||
delTs, err := f.deletedAfterTsNs(ctx, path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if delTs > tsNs {
|
||||
tsNs = delTs
|
||||
if entry == nil {
|
||||
return 0, nil
|
||||
}
|
||||
return tsNs, nil
|
||||
return f.EntryCommitTsNs(ctx, entry, entry.Mtime.UnixNano())
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
// Committed entries carry their own commit timestamp; deletes write
|
||||
// nothing — no per-path record and no tombstone.
|
||||
func TestPathCommitStampedOnEntry(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
entry := &Entry{FullPath: "/dir/file", Content: []byte("data")}
|
||||
f.StampEntryCommitTsNs(entry)
|
||||
if err := store.InsertEntry(ctx, entry); err != nil {
|
||||
t.Fatalf("InsertEntry: %v", err)
|
||||
}
|
||||
f.releaseEntryCommitTsNs(entry.CommitTsNs)
|
||||
if got, err := f.CommitTsNs(ctx, "/dir/file", 0); err != nil || got != entry.CommitTsNs {
|
||||
t.Fatalf("CommitTsNs = %d,%v; want %d", got, err, entry.CommitTsNs)
|
||||
}
|
||||
if len(store.kv) != 0 {
|
||||
t.Fatalf("kv keys written for a change event: %v", store.kv)
|
||||
}
|
||||
|
||||
if err := store.DeleteEntry(ctx, entry.FullPath); err != nil {
|
||||
t.Fatalf("DeleteEntry: %v", err)
|
||||
}
|
||||
if len(store.kv) != 0 {
|
||||
t.Fatalf("kv keys written for a change or delete: %v", store.kv)
|
||||
}
|
||||
}
|
||||
|
||||
// The emitted event's TsNs is the commit timestamp stamped on the entry
|
||||
// before its store write — identical values so peers and the local store
|
||||
// agree on last-writer-wins.
|
||||
func TestEventTsNsEqualsEntryCommitTs(t *testing.T) {
|
||||
f := &Filer{
|
||||
Signature: 7,
|
||||
LocalMetaLogBuffer: log_buffer.NewLogBuffer(
|
||||
"commit-ts-test", time.Minute,
|
||||
func(*log_buffer.LogBuffer, time.Time, time.Time, []byte, int64, int64) {},
|
||||
nil, nil,
|
||||
),
|
||||
}
|
||||
defer f.LocalMetaLogBuffer.ShutdownLogBuffer()
|
||||
|
||||
ctx, sink := WithMetadataEventSink(context.Background())
|
||||
newEntry := &Entry{FullPath: util.FullPath("/dir/file")}
|
||||
f.StampEntryCommitTsNs(newEntry)
|
||||
f.NotifyUpdateEvent(ctx, nil, newEntry, true, false, nil)
|
||||
|
||||
event := sink.Last()
|
||||
if event == nil {
|
||||
t.Fatal("expected metadata event")
|
||||
}
|
||||
if event.TsNs != newEntry.CommitTsNs {
|
||||
t.Fatalf("event.TsNs = %d, entry.CommitTsNs = %d; must be equal", event.TsNs, newEntry.CommitTsNs)
|
||||
}
|
||||
if got := f.metaLogInflight.minTsNs(); got != 0 {
|
||||
t.Fatalf("stamp still in flight after emit: %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A notify that never saw a pre-stamp still emits at a fresh stamp — the
|
||||
// stamp/release pairing must hold either way.
|
||||
func TestEventWithoutPreStampStillEmits(t *testing.T) {
|
||||
f := &Filer{
|
||||
Signature: 7,
|
||||
LocalMetaLogBuffer: log_buffer.NewLogBuffer(
|
||||
"commit-ts-fresh", time.Minute,
|
||||
func(*log_buffer.LogBuffer, time.Time, time.Time, []byte, int64, int64) {},
|
||||
nil, nil,
|
||||
),
|
||||
}
|
||||
defer f.LocalMetaLogBuffer.ShutdownLogBuffer()
|
||||
|
||||
ctx, sink := WithMetadataEventSink(context.Background())
|
||||
f.NotifyUpdateEvent(ctx, nil, &Entry{FullPath: util.FullPath("/dir/file")}, true, false, nil)
|
||||
if sink.Last() == nil || sink.Last().TsNs == 0 {
|
||||
t.Fatal("expected stamped metadata event")
|
||||
}
|
||||
if got := f.metaLogInflight.minTsNs(); got != 0 {
|
||||
t.Fatalf("stamp leaked: %d", got)
|
||||
}
|
||||
}
|
||||
+59
-13
@@ -57,21 +57,20 @@ func (f *Filer) Replay(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if err != nil || newer {
|
||||
return err
|
||||
}
|
||||
newEntry := FromPbEntry(dir, message.NewEntry)
|
||||
newEntry.CommitTsNs = resp.TsNs
|
||||
if message.OldEntry.IsDirectory {
|
||||
glog.V(4).Infof("updating %v", newPath)
|
||||
return f.updateExistingEntry(ctx, oldPath, newEntry)
|
||||
}
|
||||
glog.V(4).Infof("deleting %v", oldPath)
|
||||
if err := f.Store.DeleteEntry(ctx, oldPath); err != nil {
|
||||
return err
|
||||
}
|
||||
// Record the commit before the insert too: if the insert fails and
|
||||
// the event is retried later, the path sits deleted in between —
|
||||
// without the record a stale peer create could resurrect it in the
|
||||
// gap. The entry still exists afterward, so no delete record.
|
||||
f.notePathChange(oldPath, resp.TsNs, false)
|
||||
glog.V(4).Infof("creating %v", newPath)
|
||||
newEntry := FromPbEntry(dir, message.NewEntry)
|
||||
if err := f.Store.InsertEntry(ctx, newEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
f.notePathChange(oldPath, resp.TsNs, false)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -98,10 +97,6 @@ func (f *Filer) Replay(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// The origin deleted the directory even when a newer descendant
|
||||
// keeps its entry here — recording the delete fences stale child
|
||||
// creates that would otherwise resurrect under it.
|
||||
f.notePathChange(oldPath, resp.TsNs, true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,16 +108,68 @@ func (f *Filer) Replay(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
if !newer {
|
||||
glog.V(4).Infof("creating %v", newPath)
|
||||
newEntry := FromPbEntry(dir, message.NewEntry)
|
||||
newEntry.CommitTsNs = resp.TsNs
|
||||
if err := f.Store.InsertEntry(ctx, newEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
f.notePathChange(newPath, resp.TsNs, false)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateExistingEntry applies a same-path update without deleting the row in
|
||||
// between: the path never sits absent, so a failed retry cannot leave it
|
||||
// unordered — a tombstone would instead read as a subtree delete that
|
||||
// suppresses a directory's children. UpdateEntry goes on a present row and
|
||||
// InsertEntry on an absent one (InsertEntry is not an upsert on stores
|
||||
// configured without upsert support, and UpdateEntry touches no row that is
|
||||
// not there).
|
||||
//
|
||||
// A peer filer sharing the store can still delete the row between the find
|
||||
// and the update — the UPDATE then changes zero rows yet reports success,
|
||||
// silently dropping the replay while its subscription offset advances. The
|
||||
// write is verified by re-reading the entry, and each pass re-checks the
|
||||
// recorded commit order so a newer peer change wins instead of being
|
||||
// resurrected over.
|
||||
func (f *Filer) updateExistingEntry(ctx context.Context, path util.FullPath, newEntry *Entry) error {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 4; attempt++ {
|
||||
if attempt > 0 {
|
||||
newer, err := f.replayBlockedByLocal(ctx, path, newEntry.CommitTsNs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if newer {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if _, findErr := f.Store.FindEntry(ctx, path); findErr == nil {
|
||||
if err := f.Store.UpdateEntry(ctx, newEntry); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.Store.FindEntry(ctx, path); err == nil {
|
||||
return nil
|
||||
} else if !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return err
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
} else if errors.Is(findErr, filer_pb.ErrNotFound) {
|
||||
// An insert colliding with a racing peer create retries as an
|
||||
// update on the next pass.
|
||||
if err := f.Store.InsertEntry(ctx, newEntry); err != nil {
|
||||
lastErr = err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
return findErr
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("update %s: %w", path, lastErr)
|
||||
}
|
||||
|
||||
// deleteReplayedFolderChildren removes local entries under dir, and queues
|
||||
// the chunks of removed files for deletion. Children this filer committed
|
||||
// after the event stay — a newer local write wins over a delayed delete —
|
||||
@@ -263,7 +310,6 @@ func (f *Filer) deleteSweptChild(ctx context.Context, sub *Entry, message *filer
|
||||
if derr := f.Store.DeleteEntry(ctx, sub.FullPath); derr != nil {
|
||||
return false, fmt.Errorf("delete %s: %w", sub.FullPath, derr)
|
||||
}
|
||||
f.notePathChange(sub.FullPath, tsNs, true)
|
||||
// chunks of a hard-linked child belong to the shared inode record; free
|
||||
// them only once that record is gone. A directory entry can still carry
|
||||
// chunks of its own — an S3 child promotes an existing file to a
|
||||
|
||||
@@ -53,12 +53,9 @@ type IAMManager struct {
|
||||
oidcRetryAgain bool
|
||||
// oidcRefreshMu serializes refreshes from reading the store to handing
|
||||
// STS the result, so an older snapshot cannot replace a newer one.
|
||||
oidcRefreshMu sync.Mutex
|
||||
// oidcManagedProviders caches providers refreshOIDCProvidersFrom built,
|
||||
// keyed by record identity, so an unchanged record reuses its provider:
|
||||
// rebuilding would drop the provider's consumed-token (jti) replay cache
|
||||
// and let an already-used token be presented again. Guarded by
|
||||
// oidcRefreshMu.
|
||||
// oidcManagedProviders caches the provider built per stored record so a
|
||||
// refresh reuses unchanged providers and keeps their JWKS cache.
|
||||
oidcRefreshMu sync.Mutex
|
||||
oidcManagedProviders map[string]*oidcManagedProvider
|
||||
oidcAuditSink OIDCProviderAuditSink
|
||||
revocationStore SessionRevocationStore
|
||||
@@ -953,10 +950,6 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
m.oidcManagedProviders = make(map[string]*oidcManagedProvider)
|
||||
}
|
||||
seen := make(map[string]struct{}, len(records))
|
||||
// Records for one issuer with identical validation settings share a single
|
||||
// provider — and with it the consumed-token (jti) replay store — so a token
|
||||
// spent through one account's record stays spent through the other's too.
|
||||
sharedProviders := make(map[string]*oidc.OIDCProvider)
|
||||
for _, rec := range records {
|
||||
if rec == nil || rec.URL == "" {
|
||||
continue
|
||||
@@ -967,25 +960,10 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
fingerprint := oidcProviderFingerprint(rec)
|
||||
configFingerprint := oidcProviderConfigFingerprint(rec)
|
||||
var provider *oidc.OIDCProvider
|
||||
cached := m.oidcManagedProviders[key]
|
||||
if shared, ok := sharedProviders[configFingerprint]; ok {
|
||||
provider = shared
|
||||
if cached != nil && cached.provider != nil && cached.provider != shared {
|
||||
// The record's own provider is superseded; its consumed
|
||||
// tokens move to the shared store so none reopen for replay.
|
||||
shared.MergeReplayStateFrom(cached.provider)
|
||||
}
|
||||
m.oidcManagedProviders[key] = &oidcManagedProvider{fingerprint: fingerprint, provider: provider}
|
||||
if cached != nil && cached.provider != nil && cached.provider != shared && !m.oidcProviderStillReferenced(cached.provider) {
|
||||
if err := cached.provider.Shutdown(ctx); err != nil {
|
||||
glog.Warningf("shutdown superseded OIDC provider %s: %v", rec.ARN, err)
|
||||
}
|
||||
}
|
||||
} else if cached != nil && cached.fingerprint == fingerprint {
|
||||
var provider *oidc.OIDCProvider
|
||||
if cached != nil && cached.fingerprint == fingerprint {
|
||||
provider = cached.provider
|
||||
sharedProviders[configFingerprint] = provider
|
||||
} else {
|
||||
var err error
|
||||
provider, err = buildOIDCProviderFromRecord(rec)
|
||||
@@ -994,20 +972,7 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
glog.Warningf("skip refreshing OIDC provider %s: %v", rec.ARN, err)
|
||||
continue
|
||||
}
|
||||
if cached != nil && cached.provider != nil {
|
||||
// The rebuild must keep rejecting tokens the replaced
|
||||
// provider consumed; carry its replay store over, then stop
|
||||
// its cleanup worker so only the new one sweeps the store —
|
||||
// unless another record still references that provider.
|
||||
provider.AdoptReplayStateFrom(cached.provider)
|
||||
}
|
||||
sharedProviders[configFingerprint] = provider
|
||||
m.oidcManagedProviders[key] = &oidcManagedProvider{fingerprint: fingerprint, provider: provider}
|
||||
if cached != nil && cached.provider != nil && !m.oidcProviderStillReferenced(cached.provider) {
|
||||
if err := cached.provider.Shutdown(ctx); err != nil {
|
||||
glog.Warningf("shutdown replaced OIDC provider %s: %v", rec.ARN, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Multiple records may share an issuer when each is scoped to a
|
||||
// different account; STS picks the right one at validation time
|
||||
@@ -1017,16 +982,9 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
Provider: provider,
|
||||
})
|
||||
}
|
||||
for key, managed := range m.oidcManagedProviders {
|
||||
for key := range m.oidcManagedProviders {
|
||||
if _, ok := seen[key]; !ok {
|
||||
delete(m.oidcManagedProviders, key)
|
||||
// A removed record's provider may be shared by records that are
|
||||
// still present; shut it down only when nothing references it.
|
||||
if managed.provider != nil && !m.oidcProviderStillReferenced(managed.provider) {
|
||||
if err := managed.provider.Shutdown(ctx); err != nil {
|
||||
glog.Warningf("shutdown removed OIDC provider %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m.stsService.SetIAMManagedOIDCProviders(byIssuer)
|
||||
@@ -1040,17 +998,6 @@ type oidcManagedProvider struct {
|
||||
provider *oidc.OIDCProvider
|
||||
}
|
||||
|
||||
// oidcProviderStillReferenced reports whether any managed record still points
|
||||
// at the provider, so a shared provider is not shut down with a removed record.
|
||||
func (m *IAMManager) oidcProviderStillReferenced(provider *oidc.OIDCProvider) bool {
|
||||
for _, managed := range m.oidcManagedProviders {
|
||||
if managed.provider == provider {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// oidcProviderFingerprint identifies the record content a provider was built
|
||||
// from, so a refresh rebuilds the provider only when that content changed.
|
||||
func oidcProviderFingerprint(rec *OIDCProviderRecord) string {
|
||||
@@ -1067,21 +1014,6 @@ func oidcProviderFingerprint(rec *OIDCProviderRecord) string {
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// oidcProviderConfigFingerprint identifies the validation settings a provider
|
||||
// is built from — everything buildOIDCProviderFromRecord consumes except the
|
||||
// record's name — so records that differ only in identity reuse one provider.
|
||||
func oidcProviderConfigFingerprint(rec *OIDCProviderRecord) string {
|
||||
key, _ := json.Marshal(&oidc.OIDCConfig{
|
||||
Issuer: rec.URL,
|
||||
ClientIDs: rec.ClientIDs,
|
||||
Thumbprints: rec.Thumbprints,
|
||||
AllowedPrincipalTagKeys: rec.AllowedPrincipalTagKeys,
|
||||
PolicyClaim: rec.PolicyClaim,
|
||||
})
|
||||
sum := sha256.Sum256(key)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// buildOIDCProviderFromRecord turns a stored record into a runtime
|
||||
// OIDCProvider. The provider name is the ARN so re-registration is
|
||||
// idempotent and never collides with static-config entries.
|
||||
|
||||
@@ -560,92 +560,47 @@ func TestAFailureDuringARetryIsNotDropped(t *testing.T) {
|
||||
assert.GreaterOrEqual(t, store.successes(), 2, "the retry ended on its first success, dropping the refresh that failed while it ran")
|
||||
}
|
||||
|
||||
// A refresh must not rebuild a provider whose record is unchanged: rebuilding
|
||||
// would drop the provider's consumed-token (jti) replay cache and let an
|
||||
// already-used token be presented again.
|
||||
func TestRefreshReusesProviderWhileRecordIsUnchanged(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
// A refresh caused by an unrelated record must not rebuild a provider whose
|
||||
// own record is unchanged: rebuilding drops its JWKS cache, so a briefly
|
||||
// unreachable issuer would fail exchanges its cached keys still allow.
|
||||
func TestAnUnrelatedRefreshKeepsAProvidersRuntimeState(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store)
|
||||
|
||||
arn := arnOf(t, persistTestAPIIssuer)
|
||||
require.NoError(t, store.StoreProvider(ctx, "", &OIDCProviderRecord{
|
||||
ARN: arn, URL: persistTestAPIIssuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
first := mgr.oidcManagedProviders[arn].provider
|
||||
require.NotNil(t, first)
|
||||
createAPIProvider(t, mgr, persistTestAPIIssuer)
|
||||
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.Same(t, first, mgr.oidcManagedProviders[arn].provider,
|
||||
"an unchanged record was rebuilt, dropping its replay cache")
|
||||
mgr.oidcRefreshMu.Lock()
|
||||
before := mgr.oidcManagedProviders[arn]
|
||||
mgr.oidcRefreshMu.Unlock()
|
||||
require.NotNil(t, before)
|
||||
|
||||
// A changed record must rebuild so the new configuration applies.
|
||||
require.NoError(t, store.StoreProvider(ctx, "", &OIDCProviderRecord{
|
||||
ARN: arn, URL: persistTestAPIIssuer, ClientIDs: []string{"aud", "aud2"},
|
||||
}))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
rebuilt := mgr.oidcManagedProviders[arn].provider
|
||||
require.NotNil(t, rebuilt)
|
||||
assert.NotSame(t, first, rebuilt, "a changed record kept the old provider")
|
||||
createAPIProvider(t, mgr, persistTestStaticIssuer) // refreshes over an unrelated record
|
||||
|
||||
// Deleting the record drops the provider from the cache and the STS map.
|
||||
require.NoError(t, store.DeleteProvider(ctx, "", arn))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.NotContains(t, mgr.oidcManagedProviders, arn)
|
||||
assert.False(t, stsKnowsIssuer(t, mgr, persistTestAPIIssuer))
|
||||
mgr.oidcRefreshMu.Lock()
|
||||
after := mgr.oidcManagedProviders[arn]
|
||||
mgr.oidcRefreshMu.Unlock()
|
||||
require.NotNil(t, after)
|
||||
assert.Same(t, before.provider, after.provider, "an unchanged record's provider was rebuilt")
|
||||
}
|
||||
|
||||
// stsKnowsIssuerForAccount is stsKnowsIssuer through the account-scoped
|
||||
// lookup used for providers that have no global record.
|
||||
func stsKnowsIssuerForAccount(t *testing.T, mgr *IAMManager, issuer, accountID string) bool {
|
||||
t.Helper()
|
||||
tok, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"iss": issuer, "sub": "probe", "aud": "aud", "exp": time.Now().Add(time.Hour).Unix(),
|
||||
}).SignedString([]byte("not-the-providers-key"))
|
||||
require.NoError(t, err)
|
||||
_, _, err = mgr.GetSTSService().ValidateWebIdentityTokenForAccount(context.Background(), tok, accountID)
|
||||
require.Error(t, err, "an unsigned-by-provider token for %s was accepted", issuer)
|
||||
return !strings.Contains(err.Error(), "no identity provider registered")
|
||||
}
|
||||
|
||||
// Two records for one issuer with identical validation settings share a
|
||||
// single provider — and with it the consumed-token (jti) replay store — so a
|
||||
// token spent through one account's record stays spent through the other's.
|
||||
// Removing one record of the pair must not shut the shared provider down.
|
||||
func TestSameIssuerRecordsShareOneProvider(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
// A record whose validation settings change must get a new provider: the
|
||||
// cached runtime cannot keep serving settings the store no longer holds.
|
||||
func TestAChangedRecordRebuildsItsProvider(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store)
|
||||
arn := arnOf(t, persistTestAPIIssuer)
|
||||
createAPIProvider(t, mgr, persistTestAPIIssuer)
|
||||
|
||||
arnA := arnOf(t, persistTestAPIIssuer) + "-account-a"
|
||||
arnB := arnOf(t, persistTestAPIIssuer) + "-account-b"
|
||||
for _, rec := range []*OIDCProviderRecord{
|
||||
{ARN: arnA, URL: persistTestAPIIssuer, AccountID: "111111111111", ClientIDs: []string{"aud"}},
|
||||
{ARN: arnB, URL: persistTestAPIIssuer, AccountID: "222222222222", ClientIDs: []string{"aud"}},
|
||||
} {
|
||||
require.NoError(t, store.StoreProvider(ctx, "", rec))
|
||||
}
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
mgr.oidcRefreshMu.Lock()
|
||||
before := mgr.oidcManagedProviders[arn].provider
|
||||
mgr.oidcRefreshMu.Unlock()
|
||||
|
||||
shared := mgr.oidcManagedProviders[arnA].provider
|
||||
require.NotNil(t, shared)
|
||||
assert.Same(t, shared, mgr.oidcManagedProviders[arnB].provider,
|
||||
"identical records for one issuer built separate replay stores")
|
||||
require.NoError(t, mgr.UpdateOIDCProviderThumbprints(context.Background(), arn,
|
||||
[]string{"0123456789abcdef0123456789abcdef01234567"}))
|
||||
|
||||
// Removing one record of the pair keeps the shared provider alive.
|
||||
require.NoError(t, store.DeleteProvider(ctx, "", arnA))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.Same(t, shared, mgr.oidcManagedProviders[arnB].provider,
|
||||
"a removed sibling record shut down the shared provider")
|
||||
assert.True(t, stsKnowsIssuerForAccount(t, mgr, persistTestAPIIssuer, "222222222222"))
|
||||
|
||||
// The remaining record diverging rebuilds its own provider.
|
||||
require.NoError(t, store.StoreProvider(ctx, "", &OIDCProviderRecord{
|
||||
ARN: arnB, URL: persistTestAPIIssuer, AccountID: "222222222222", ClientIDs: []string{"b-aud"},
|
||||
}))
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.NotSame(t, shared, mgr.oidcManagedProviders[arnB].provider,
|
||||
"a changed record kept the shared provider")
|
||||
assert.True(t, stsKnowsIssuerForAccount(t, mgr, persistTestAPIIssuer, "222222222222"))
|
||||
mgr.oidcRefreshMu.Lock()
|
||||
after := mgr.oidcManagedProviders[arn]
|
||||
mgr.oidcRefreshMu.Unlock()
|
||||
require.NotNil(t, after)
|
||||
assert.NotSame(t, before, after.provider, "a changed record kept its provider")
|
||||
}
|
||||
@@ -1,410 +0,0 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/providers"
|
||||
)
|
||||
|
||||
const (
|
||||
// clockSkewTolerance matches the typical JWT library clock skew allowance (RFC 7519)
|
||||
clockSkewTolerance = 5 * time.Minute
|
||||
// defaultJTICacheSize is the default maximum number of JTI entries to cache
|
||||
defaultJTICacheSize = 10000
|
||||
// defaultCleanupInterval is how often to scan for expired JTI entries
|
||||
defaultCleanupInterval = 5 * time.Minute
|
||||
// eagerCleanupMinInterval rate limits opportunistic sweeps near capacity
|
||||
eagerCleanupMinInterval = 5 * time.Second
|
||||
// tokenFingerprintPrefix marks replay-cache keys derived from the token's
|
||||
// own fingerprint, used when the token carries no usable jti claim
|
||||
tokenFingerprintPrefix = "fp:"
|
||||
)
|
||||
|
||||
// jtiEntry represents a cached JTI with metadata
|
||||
type jtiEntry struct {
|
||||
subject string
|
||||
expiresAt time.Time
|
||||
// uncounted marks an entry merged in past the capacity bound: it keeps
|
||||
// rejecting replays but does not charge the count, so merged excess can
|
||||
// neither reject new exchanges nor be double-counted when swept.
|
||||
uncounted bool
|
||||
}
|
||||
|
||||
// jtiReplayCache wraps the consumed-token store that backs JTI replay
|
||||
// protection. Each consumed token identifier is held until the token's exp
|
||||
// plus clock skew, and a second presentation of the same identifier is
|
||||
// rejected with ErrProviderTokenReplayed.
|
||||
//
|
||||
// The cache is bounded by maxSize and uses automatic TTL-based expiration:
|
||||
// a background worker sweeps expired entries, an eager sweep runs when the
|
||||
// cache nears capacity, and the consume path reclaims expired slots before
|
||||
// rejecting a fresh token for capacity.
|
||||
//
|
||||
// Thread Safety:
|
||||
// All methods are safe for concurrent use. The consume path uses atomic
|
||||
// LoadOrStore to prevent TOCTOU races.
|
||||
type jtiReplayCache struct {
|
||||
name string // owning provider name, for log messages
|
||||
|
||||
enabled atomic.Bool
|
||||
maxSize atomic.Int64
|
||||
lastSweep atomic.Int64 // unix nano of the last sweep; rate limits eager cleanups
|
||||
|
||||
// storeMu guards the store/count pair: replay-state handoffs (adoptFrom,
|
||||
// mergeFrom) repoint them under the write lock while the consume path
|
||||
// holds a read lock, so a consume can never land in a store the handoff
|
||||
// already drained and abandoned.
|
||||
// It is always acquired before sweepMu, never while holding it.
|
||||
storeMu sync.RWMutex
|
||||
store *sync.Map // map[string]*jtiEntry - atomic storage for consumed token keys
|
||||
count *atomic.Int64 // entries in store; shared with the store
|
||||
|
||||
// mu guards the lifecycle of the cleanup worker: cleanupCancel and
|
||||
// cleanupDone. The worker itself only touches store/count, so holding
|
||||
// mu while waiting for it is safe.
|
||||
mu sync.Mutex
|
||||
cleanupCancel context.CancelFunc
|
||||
cleanupDone chan struct{} // Closed when cleanup goroutine exits
|
||||
|
||||
// sweepMu serializes cache sweeps so at most one scan runs at a time.
|
||||
sweepMu sync.Mutex
|
||||
}
|
||||
|
||||
func newJTIReplayCache(name string) *jtiReplayCache {
|
||||
return &jtiReplayCache{
|
||||
name: name,
|
||||
store: &sync.Map{},
|
||||
count: &atomic.Int64{},
|
||||
}
|
||||
}
|
||||
|
||||
// configure applies the replay-protection settings: a previous worker is
|
||||
// always stopped, whether the new configuration enables protection or
|
||||
// disables it. The consumed-token store survives re-configuration: resetting
|
||||
// it would let already-seen tokens be replayed against the refreshed provider.
|
||||
func (c *jtiReplayCache) configure(enabled bool, maxSize int64) {
|
||||
c.mu.Lock()
|
||||
c.stopWorkerLocked()
|
||||
if enabled {
|
||||
if maxSize <= 0 {
|
||||
maxSize = defaultJTICacheSize
|
||||
}
|
||||
// the bound must land before the flag: a consume that sees enabled
|
||||
// with a zero bound would reject the first token it registers
|
||||
c.maxSize.Store(maxSize)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
c.cleanupCancel = cancel
|
||||
c.cleanupDone = done
|
||||
c.enabled.Store(true)
|
||||
c.mu.Unlock()
|
||||
|
||||
go c.cleanupLoop(ctx, done, defaultCleanupInterval)
|
||||
glog.V(2).Infof("OIDC provider %q: JTI replay protection enabled (max size: %d)", c.name, maxSize)
|
||||
} else {
|
||||
c.enabled.Store(false)
|
||||
c.mu.Unlock()
|
||||
glog.Warningf("OIDC provider %q: JTI replay protection is DISABLED", c.name)
|
||||
}
|
||||
}
|
||||
|
||||
// stopWorkerLocked cancels the current cleanup goroutine and waits briefly
|
||||
// for it to exit. Caller must hold mu.
|
||||
func (c *jtiReplayCache) stopWorkerLocked() {
|
||||
if c.cleanupCancel == nil {
|
||||
return
|
||||
}
|
||||
c.cleanupCancel()
|
||||
select {
|
||||
case <-c.cleanupDone:
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine exited", c.name)
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("OIDC provider %q: Timeout waiting for JTI cleanup goroutine", c.name)
|
||||
}
|
||||
c.cleanupCancel = nil
|
||||
c.cleanupDone = nil
|
||||
}
|
||||
|
||||
// consume marks a token as used and rejects a second presentation of it.
|
||||
// jti is the token's jti claim (may be empty); tokenExpiresAt is its exp.
|
||||
// A no-op while protection is disabled.
|
||||
func (c *jtiReplayCache) consume(token, jti, subject string, tokenExpiresAt time.Time) error {
|
||||
if !c.enabled.Load() {
|
||||
return nil
|
||||
}
|
||||
|
||||
key := jti
|
||||
if key == "" {
|
||||
// Providers that issue no jti cannot be tracked by claim, so the
|
||||
// signed input keys the entry: a repeated presentation of the same
|
||||
// claims is a replay even when the signature bytes differ (e.g.
|
||||
// ECDSA s/N-s malleability).
|
||||
signingInput := token
|
||||
if i := strings.LastIndexByte(token, '.'); i > 0 {
|
||||
signingInput = token[:i]
|
||||
}
|
||||
sum := sha256.Sum256([]byte(signingInput))
|
||||
key = tokenFingerprintPrefix + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
if tokenExpiresAt.IsZero() {
|
||||
// a cache slot is freed only by expiry, so a token without exp
|
||||
// would hold it forever and eventually exhaust the bound
|
||||
return fmt.Errorf("%w: missing exp claim", providers.ErrProviderMissingClaims)
|
||||
}
|
||||
expiresAt := tokenExpiresAt.Add(clockSkewTolerance)
|
||||
if !time.Now().Before(expiresAt) {
|
||||
return fmt.Errorf("%w: token expired", providers.ErrProviderTokenExpired)
|
||||
}
|
||||
|
||||
entry := &jtiEntry{
|
||||
subject: subject,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
|
||||
// The read lock pins the store/count pair for the whole test-and-set
|
||||
// so a replay-state handoff cannot repoint them mid-check and strand
|
||||
// this consume in an abandoned store.
|
||||
c.storeMu.RLock()
|
||||
store, count := c.store, c.count
|
||||
|
||||
// Atomic test-and-set detects replays before any capacity work runs,
|
||||
// so a replayed token cannot trigger cleanup scans.
|
||||
if _, loaded := store.LoadOrStore(key, entry); loaded {
|
||||
c.storeMu.RUnlock()
|
||||
glog.Warningf("OIDC provider %q: Token replay detected (jti: %s)",
|
||||
c.name, jtiLogKey(key))
|
||||
return fmt.Errorf("%w: jti %s has already been used",
|
||||
providers.ErrProviderTokenReplayed, jtiLogKey(key))
|
||||
}
|
||||
|
||||
// The count is incremented as part of the insert, so concurrent
|
||||
// validations cannot all slip under the limit: whoever pushes the
|
||||
// count over evicts their own entry and is rejected.
|
||||
newCount := count.Add(1)
|
||||
maxSize := c.maxSize.Load()
|
||||
if newCount > maxSize {
|
||||
// Over the bound: expired entries may still occupy slots, so
|
||||
// reclaim them with a synchronized sweep before rejecting.
|
||||
c.sweepStore(store, count)
|
||||
if count.Load() > maxSize {
|
||||
if _, loaded := store.LoadAndDelete(key); loaded {
|
||||
count.Add(-1)
|
||||
}
|
||||
c.storeMu.RUnlock()
|
||||
glog.Errorf("OIDC provider %q: JTI cache FULL (%d entries) - rejecting token. "+
|
||||
"This may indicate a DoS attack or insufficient cache size. Consider increasing JTICacheMaxSize.",
|
||||
c.name, maxSize)
|
||||
return fmt.Errorf("JTI cache capacity exceeded")
|
||||
}
|
||||
} else if newCount >= maxSize*9/10 {
|
||||
glog.Warningf("OIDC provider %q: JTI cache at %d%% capacity (%d/%d), triggering eager cleanup",
|
||||
c.name, (newCount*100)/maxSize, newCount, maxSize)
|
||||
go c.performEagerCleanup()
|
||||
}
|
||||
c.storeMu.RUnlock()
|
||||
|
||||
glog.V(4).Infof("OIDC provider %q: Registered JTI %s (expires at %v, cache size: %d)",
|
||||
c.name, jtiLogKey(key), expiresAt, newCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
// evictExpired removes entries whose expiry has passed and returns how
|
||||
// many it deleted. Caller must hold sweepMu.
|
||||
func (c *jtiReplayCache) evictExpired(now time.Time, store *sync.Map, count *atomic.Int64) int {
|
||||
removed := 0
|
||||
store.Range(func(key, value interface{}) bool {
|
||||
expiresAt := value.(*jtiEntry).expiresAt
|
||||
if !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
// LoadAndDelete reports whether this call actually removed the
|
||||
// entry, so concurrent deletes cannot decrement the count twice.
|
||||
if v, loaded := store.LoadAndDelete(key); loaded {
|
||||
if !v.(*jtiEntry).uncounted {
|
||||
count.Add(-1)
|
||||
}
|
||||
removed++
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return removed
|
||||
}
|
||||
|
||||
// state returns the cache's current store/count pair.
|
||||
func (c *jtiReplayCache) state() (*sync.Map, *atomic.Int64) {
|
||||
c.storeMu.RLock()
|
||||
defer c.storeMu.RUnlock()
|
||||
return c.store, c.count
|
||||
}
|
||||
|
||||
// sweepStore runs one serialized expiry scan over the given store. It only
|
||||
// takes sweepMu, so callers already holding storeMu may use it.
|
||||
func (c *jtiReplayCache) sweepStore(store *sync.Map, count *atomic.Int64) {
|
||||
c.sweepMu.Lock()
|
||||
defer c.sweepMu.Unlock()
|
||||
c.lastSweep.Store(time.Now().UnixNano())
|
||||
if removed := c.evictExpired(time.Now(), store, count); removed > 0 {
|
||||
glog.V(4).Infof("OIDC provider %q: Cleaned up %d expired JTI entries (remaining: %d)",
|
||||
c.name, removed, count.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// sweepExpired runs a scan that is guaranteed to complete before the
|
||||
// caller proceeds; the periodic worker uses it so the scan always covers
|
||||
// the store currently in effect, not one captured earlier.
|
||||
func (c *jtiReplayCache) sweepExpired() {
|
||||
store, count := c.state()
|
||||
c.sweepStore(store, count)
|
||||
}
|
||||
|
||||
// performEagerCleanup performs an opportunistic cleanup of expired JTI
|
||||
// entries when the cache approaches capacity. At most one sweep runs at a
|
||||
// time and no more often than eagerCleanupMinInterval, so a burst of
|
||||
// requests near the limit cannot each turn into a full-cache scan.
|
||||
func (c *jtiReplayCache) performEagerCleanup() {
|
||||
if !c.enabled.Load() {
|
||||
return
|
||||
}
|
||||
if time.Since(time.Unix(0, c.lastSweep.Load())) < eagerCleanupMinInterval {
|
||||
return
|
||||
}
|
||||
store, count := c.state()
|
||||
if !c.sweepMu.TryLock() {
|
||||
return
|
||||
}
|
||||
defer c.sweepMu.Unlock()
|
||||
c.lastSweep.Store(time.Now().UnixNano())
|
||||
|
||||
beforeCount := count.Load()
|
||||
if removed := c.evictExpired(time.Now(), store, count); removed > 0 {
|
||||
glog.Infof("OIDC provider %q: Eager cleanup removed %d expired JTI entries (%d -> %d)",
|
||||
c.name, removed, beforeCount, count.Load())
|
||||
} else {
|
||||
glog.Warningf("OIDC provider %q: Eager cleanup found no expired entries to remove. "+
|
||||
"Cache may be filled with valid long-lived tokens. Consider increasing JTICacheMaxSize.",
|
||||
c.name)
|
||||
}
|
||||
}
|
||||
|
||||
// cleanupLoop periodically removes expired JTI entries from the cache.
|
||||
// This prevents memory growth by removing JTIs after their tokens have
|
||||
// expired. Runs until ctx is cancelled; done is closed on exit.
|
||||
func (c *jtiReplayCache) cleanupLoop(ctx context.Context, done chan struct{}, interval time.Duration) {
|
||||
defer close(done)
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine started (interval: %v)", c.name, interval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.V(3).Infof("OIDC provider %q: JTI cleanup goroutine stopping", c.name)
|
||||
return
|
||||
case <-ticker.C:
|
||||
c.sweepExpired()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stop gracefully stops the cleanup worker.
|
||||
// Should be called when the provider is being shut down to prevent goroutine
|
||||
// leaks.
|
||||
func (c *jtiReplayCache) stop(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
cancel, done := c.cleanupCancel, c.cleanupDone
|
||||
c.mu.Unlock()
|
||||
|
||||
if cancel == nil {
|
||||
return nil
|
||||
}
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
glog.V(2).Infof("OIDC provider %q: Cleanup goroutine shutdown complete", c.name)
|
||||
case <-ctx.Done():
|
||||
glog.Warningf("OIDC provider %q: Shutdown timeout waiting for cleanup goroutine: %v", c.name, ctx.Err())
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
if c.cleanupDone == done {
|
||||
c.cleanupCancel = nil
|
||||
c.cleanupDone = nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// adoptFrom takes over the consumed-token store of another cache, so tokens
|
||||
// it already saw stay rejected across the rebuild. The caller must shut down
|
||||
// the replaced provider; only one cleanup worker may sweep the shared store
|
||||
// at a time. Call before the new provider serves validators; sweepMu
|
||||
// excludes its own cleanup worker during the swap.
|
||||
func (c *jtiReplayCache) adoptFrom(old *jtiReplayCache) {
|
||||
if old == nil || old == c {
|
||||
return
|
||||
}
|
||||
c.storeMu.Lock()
|
||||
c.sweepMu.Lock()
|
||||
c.store, c.count = old.store, old.count
|
||||
c.sweepMu.Unlock()
|
||||
c.storeMu.Unlock()
|
||||
}
|
||||
|
||||
// mergeFrom hands this cache's store to another cache and then folds the
|
||||
// other's consumed-token entries in, so rejections the other recorded keep
|
||||
// holding when its records move to a shared provider. Repointing first means
|
||||
// tokens the other still consumes — in-flight exchanges or ones routed to it
|
||||
// before the provider map updates — land in the shared store instead of a
|
||||
// store this merge already drained. Unlike adoptFrom it swaps nothing of its
|
||||
// own, so it is safe on a cache that is already serving validators.
|
||||
func (c *jtiReplayCache) mergeFrom(other *jtiReplayCache) {
|
||||
if other == nil || other == c {
|
||||
return
|
||||
}
|
||||
c.storeMu.RLock()
|
||||
defer c.storeMu.RUnlock()
|
||||
store, count := c.store, c.count
|
||||
|
||||
other.storeMu.Lock()
|
||||
oldStore := other.store
|
||||
if oldStore == store {
|
||||
other.storeMu.Unlock()
|
||||
return
|
||||
}
|
||||
other.store, other.count = store, count
|
||||
other.storeMu.Unlock()
|
||||
|
||||
c.sweepMu.Lock()
|
||||
defer c.sweepMu.Unlock()
|
||||
now := time.Now()
|
||||
oldStore.Range(func(key, value interface{}) bool {
|
||||
entry := value.(*jtiEntry)
|
||||
if expiresAt := entry.expiresAt; !expiresAt.IsZero() && now.After(expiresAt) {
|
||||
return true
|
||||
}
|
||||
// A consumed token is never dropped to fit the bound: merged entries
|
||||
// stay but do not charge the count, so a store filled past the bound
|
||||
// by the merge cannot reject new exchanges while it drains by expiry.
|
||||
store.LoadOrStore(key, &jtiEntry{subject: entry.subject, expiresAt: entry.expiresAt, uncounted: true})
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// jtiLogKey redacts a token identifier for logs and error strings: a stable
|
||||
// fingerprint that still lets operators correlate repeated presentations.
|
||||
func jtiLogKey(jti string) string {
|
||||
sum := sha256.Sum256([]byte(jti))
|
||||
return hex.EncodeToString(sum[:8])
|
||||
}
|
||||
@@ -75,17 +75,6 @@ func (m *MockOIDCProvider) Authenticate(ctx context.Context, token string) (*pro
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
// AuthenticateSingleUse stays on the mock path: the embedded provider's
|
||||
// method would bypass the mock's test data and demand a real JWKS.
|
||||
func (m *MockOIDCProvider) AuthenticateSingleUse(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
|
||||
return m.Authenticate(ctx, token)
|
||||
}
|
||||
|
||||
// ValidateTokenSingleUse stays on the mock path; see AuthenticateSingleUse.
|
||||
func (m *MockOIDCProvider) ValidateTokenSingleUse(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
return m.ValidateToken(ctx, token)
|
||||
}
|
||||
|
||||
// ValidateToken validates tokens using test data
|
||||
func (m *MockOIDCProvider) ValidateToken(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
if !m.initialized {
|
||||
|
||||
@@ -27,20 +27,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
)
|
||||
|
||||
// OIDCProvider implements OpenID Connect authentication with JTI replay protection.
|
||||
//
|
||||
// Replay Protection:
|
||||
// The provider validates the 'jti' (JWT ID) claim to prevent token replay attacks.
|
||||
// Each JTI is stored in memory until the token expires. If a token with a duplicate
|
||||
// JTI is presented, it is rejected with ErrProviderTokenReplayed.
|
||||
//
|
||||
// The JTI cache is bounded by JTICacheMaxSize and uses automatic TTL-based expiration.
|
||||
// A token without a usable jti claim is tracked by the token's own fingerprint
|
||||
// instead, so a repeated presentation is still detected as a replay.
|
||||
//
|
||||
// Thread Safety:
|
||||
// All methods are safe for concurrent use. The JTI cache uses atomic LoadOrStore
|
||||
// operations to prevent TOCTOU race conditions.
|
||||
// OIDCProvider implements OpenID Connect authentication
|
||||
type OIDCProvider struct {
|
||||
name string
|
||||
config *OIDCConfig
|
||||
@@ -57,25 +44,6 @@ type OIDCProvider struct {
|
||||
jwksFetchedAt time.Time
|
||||
resolvedJWKSUri string
|
||||
discoveryFailed bool
|
||||
|
||||
// jti wraps the consumed-token cache behind the replay protection. It is
|
||||
// allocated by NewOIDCProvider or lazily by replayCache, and survives
|
||||
// re-initialization, so a config refresh cannot reopen already-consumed
|
||||
// tokens for replay. jtiOnce makes a zero-value OIDCProvider safe.
|
||||
jti *jtiReplayCache
|
||||
jtiOnce sync.Once
|
||||
}
|
||||
|
||||
// replayCache returns the consumed-token cache, allocating it for providers
|
||||
// built without NewOIDCProvider so the delegated operations never panic on a
|
||||
// nil cache.
|
||||
func (p *OIDCProvider) replayCache() *jtiReplayCache {
|
||||
p.jtiOnce.Do(func() {
|
||||
if p.jti == nil {
|
||||
p.jti = newJTIReplayCache(p.name)
|
||||
}
|
||||
})
|
||||
return p.jti
|
||||
}
|
||||
|
||||
// OIDCConfig holds OIDC provider configuration
|
||||
@@ -139,13 +107,6 @@ type OIDCConfig struct {
|
||||
// TLSInsecureSkipVerify controls whether to skip TLS verification.
|
||||
// WARNING: Should only be used in development/testing environments. Never use in production.
|
||||
TLSInsecureSkipVerify bool `json:"tlsInsecureSkipVerify,omitempty"`
|
||||
|
||||
// JTIReplayProtectionEnabled enables token replay protection via JTI tracking (default: true)
|
||||
// Use pointer to distinguish between "not set" (nil = default true) and "explicitly false"
|
||||
JTIReplayProtectionEnabled *bool `json:"jtiReplayProtectionEnabled,omitempty"`
|
||||
|
||||
// JTICacheMaxSize sets maximum number of JTI entries to cache (default: 10000)
|
||||
JTICacheMaxSize int `json:"jtiCacheMaxSize,omitempty"`
|
||||
}
|
||||
|
||||
// PrincipalTagsClaim is the AWS-defined namespace claim that carries
|
||||
@@ -358,7 +319,6 @@ func NewOIDCProvider(name string) *OIDCProvider {
|
||||
return &OIDCProvider{
|
||||
name: name,
|
||||
httpClient: &http.Client{Timeout: 30 * time.Second, CheckRedirect: refuseDowngradeRedirect},
|
||||
jti: newJTIReplayCache(name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,6 +422,9 @@ func (p *OIDCProvider) Initialize(config interface{}) error {
|
||||
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: tlsConfig,
|
||||
// A replaced provider drops its transport without a close; bound
|
||||
// idle connections so they cannot linger with their goroutines.
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
p.httpClient = &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
@@ -469,17 +432,6 @@ func (p *OIDCProvider) Initialize(config interface{}) error {
|
||||
CheckRedirect: refuseDowngradeRedirect,
|
||||
}
|
||||
|
||||
// Configure JTI replay protection last, so a config failure above cannot
|
||||
// leave a running worker behind. A previous worker is always stopped,
|
||||
// whether the new configuration enables protection or disables it.
|
||||
// The consumed-token store survives re-initialization: resetting it would
|
||||
// let already-seen tokens be replayed against the refreshed provider.
|
||||
jtiEnabled := true
|
||||
if oidcConfig.JTIReplayProtectionEnabled != nil {
|
||||
jtiEnabled = *oidcConfig.JTIReplayProtectionEnabled
|
||||
}
|
||||
p.replayCache().configure(jtiEnabled, int64(oidcConfig.JTICacheMaxSize))
|
||||
|
||||
// For testing, we'll skip the actual OIDC client initialization
|
||||
return nil
|
||||
}
|
||||
@@ -530,18 +482,6 @@ func (p *OIDCProvider) allowedAudiences() []string {
|
||||
|
||||
// Authenticate authenticates a user with an OIDC token
|
||||
func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
|
||||
return p.authenticate(ctx, token, false)
|
||||
}
|
||||
|
||||
// AuthenticateSingleUse authenticates and consumes the token so a second
|
||||
// presentation is rejected as a replay. The web-identity exchange uses it,
|
||||
// where a token buys a session exactly once; callers that validate the same
|
||||
// token on every request use Authenticate.
|
||||
func (p *OIDCProvider) AuthenticateSingleUse(ctx context.Context, token string) (*providers.ExternalIdentity, error) {
|
||||
return p.authenticate(ctx, token, true)
|
||||
}
|
||||
|
||||
func (p *OIDCProvider) authenticate(ctx context.Context, token string, singleUse bool) (*providers.ExternalIdentity, error) {
|
||||
if !p.initialized {
|
||||
return nil, fmt.Errorf("provider not initialized")
|
||||
}
|
||||
@@ -551,7 +491,7 @@ func (p *OIDCProvider) authenticate(ctx context.Context, token string, singleUse
|
||||
}
|
||||
|
||||
// Validate token and get claims
|
||||
claims, err := p.validateToken(ctx, token, singleUse)
|
||||
claims, err := p.ValidateToken(ctx, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -718,16 +658,6 @@ func (p *OIDCProvider) getUserInfoWithToken(ctx context.Context, userID, accessT
|
||||
|
||||
// ValidateToken validates an OIDC JWT token
|
||||
func (p *OIDCProvider) ValidateToken(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
return p.validateToken(ctx, token, false)
|
||||
}
|
||||
|
||||
// ValidateTokenSingleUse validates and consumes the token: a second
|
||||
// presentation of it is rejected as a replay. See AuthenticateSingleUse.
|
||||
func (p *OIDCProvider) ValidateTokenSingleUse(ctx context.Context, token string) (*providers.TokenClaims, error) {
|
||||
return p.validateToken(ctx, token, true)
|
||||
}
|
||||
|
||||
func (p *OIDCProvider) validateToken(ctx context.Context, token string, singleUse bool) (*providers.TokenClaims, error) {
|
||||
if !p.initialized {
|
||||
return nil, fmt.Errorf("provider not initialized")
|
||||
}
|
||||
@@ -754,7 +684,8 @@ func (p *OIDCProvider) validateToken(ctx context.Context, token string, singleUs
|
||||
return nil, fmt.Errorf("failed to get public key: %v", err)
|
||||
}
|
||||
|
||||
// Parse and validate token with proper signature verification
|
||||
// Parse and validate token with proper signature verification. exp is
|
||||
// required: without it a leaked token could mint STS sessions forever.
|
||||
claims := jwt.MapClaims{}
|
||||
validatedToken, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
// Verify signing method
|
||||
@@ -764,7 +695,7 @@ func (p *OIDCProvider) validateToken(ctx context.Context, token string, singleUs
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported signing method: %v", token.Header["alg"])
|
||||
}
|
||||
})
|
||||
}, jwt.WithExpirationRequired())
|
||||
|
||||
if err != nil {
|
||||
// Use JWT library's typed errors for robust error checking
|
||||
@@ -860,16 +791,6 @@ func (p *OIDCProvider) validateToken(ctx context.Context, token string, singleUs
|
||||
tokenClaims.Claims[key] = value
|
||||
}
|
||||
|
||||
// Consume the token for replay protection. The check runs only for
|
||||
// single-use callers: a bearer token is meant to be presented on every
|
||||
// request, so validating it must not consume it.
|
||||
if singleUse {
|
||||
jti, _ := claims["jti"].(string)
|
||||
if err := p.replayCache().consume(token, jti, subject, tokenClaims.ExpiresAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return tokenClaims, nil
|
||||
}
|
||||
|
||||
@@ -1298,36 +1219,3 @@ func (p *OIDCProvider) mapUserInfoToIdentity(userInfo map[string]interface{}) *p
|
||||
|
||||
return identity
|
||||
}
|
||||
|
||||
// Shutdown gracefully stops the JTI cleanup goroutine.
|
||||
// Should be called when the provider is being shut down to prevent goroutine leaks.
|
||||
func (p *OIDCProvider) Shutdown(ctx context.Context) error {
|
||||
return p.replayCache().stop(ctx)
|
||||
}
|
||||
|
||||
// AdoptReplayStateFrom takes over the consumed-token store of the provider it
|
||||
// replaces, so tokens it already saw stay rejected across the rebuild. The
|
||||
// caller must shut down the replaced provider; only one cleanup worker may
|
||||
// sweep the shared store at a time. Call before the new provider serves
|
||||
// validators.
|
||||
func (p *OIDCProvider) AdoptReplayStateFrom(old *OIDCProvider) {
|
||||
if old == nil || old == p || old.jti == nil {
|
||||
return
|
||||
}
|
||||
p.replayCache().adoptFrom(old.jti)
|
||||
}
|
||||
|
||||
// MergeReplayStateFrom hands this provider's store to another provider and
|
||||
// then folds the other's consumed-token entries in, so rejections the other
|
||||
// recorded keep holding when its records move to a shared provider. Repointing
|
||||
// first means tokens the other still consumes — in-flight exchanges or ones
|
||||
// routed to it before the provider map updates — land in the shared store
|
||||
// instead of a store this merge already drained. Unlike AdoptReplayStateFrom
|
||||
// it swaps nothing of its own, so it is safe on a provider that is already
|
||||
// serving validators.
|
||||
func (p *OIDCProvider) MergeReplayStateFrom(other *OIDCProvider) {
|
||||
if other == nil || other == p {
|
||||
return
|
||||
}
|
||||
p.replayCache().mergeFrom(other.replayCache())
|
||||
}
|
||||
+24
-1080
File diff suppressed because it is too large.
Load diff
@@ -19,7 +19,4 @@ var (
|
||||
|
||||
// ErrProviderMissingClaims indicates that required claims are missing from the token
|
||||
ErrProviderMissingClaims = errors.New("provider: missing required claims")
|
||||
|
||||
// ErrProviderTokenReplayed is returned when a token with duplicate JTI is detected
|
||||
ErrProviderTokenReplayed = errors.New("provider: token has been replayed")
|
||||
)
|
||||
+15
-17
@@ -42,23 +42,21 @@ const (
|
||||
|
||||
// Configuration Field Names
|
||||
const (
|
||||
ConfigFieldFilerAddress = "filerAddress"
|
||||
ConfigFieldBasePath = "basePath"
|
||||
ConfigFieldIssuer = "issuer"
|
||||
ConfigFieldClientID = "clientId"
|
||||
ConfigFieldClientIDs = "clientIds"
|
||||
ConfigFieldThumbprints = "thumbprints"
|
||||
ConfigFieldAllowedPrincipalTagKeys = "allowedPrincipalTagKeys"
|
||||
ConfigFieldPolicyClaim = "policyClaim"
|
||||
ConfigFieldClientSecret = "clientSecret"
|
||||
ConfigFieldJWKSUri = "jwksUri"
|
||||
ConfigFieldScopes = "scopes"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
ConfigFieldTLSCACert = "tlsCaCert"
|
||||
ConfigFieldTLSInsecureSkipVerify = "tlsInsecureSkipVerify"
|
||||
ConfigFieldJTIReplayProtectionEnabled = "jtiReplayProtectionEnabled"
|
||||
ConfigFieldJTICacheMaxSize = "jtiCacheMaxSize"
|
||||
ConfigFieldFilerAddress = "filerAddress"
|
||||
ConfigFieldBasePath = "basePath"
|
||||
ConfigFieldIssuer = "issuer"
|
||||
ConfigFieldClientID = "clientId"
|
||||
ConfigFieldClientIDs = "clientIds"
|
||||
ConfigFieldThumbprints = "thumbprints"
|
||||
ConfigFieldAllowedPrincipalTagKeys = "allowedPrincipalTagKeys"
|
||||
ConfigFieldPolicyClaim = "policyClaim"
|
||||
ConfigFieldClientSecret = "clientSecret"
|
||||
ConfigFieldJWKSUri = "jwksUri"
|
||||
ConfigFieldScopes = "scopes"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
ConfigFieldTLSCACert = "tlsCaCert"
|
||||
ConfigFieldTLSInsecureSkipVerify = "tlsInsecureSkipVerify"
|
||||
)
|
||||
|
||||
// Error Messages
|
||||
|
||||
@@ -103,51 +103,3 @@ func TestLookupOIDCProviderForAccountFallsBackToStatic(t *testing.T) {
|
||||
t.Fatalf("expected static-config provider as last resort, got %v ok=%v", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// shutdownTrackingProvider records Shutdown calls so tests can observe which
|
||||
// replaced providers the swap released.
|
||||
type shutdownTrackingProvider struct {
|
||||
stubIdentityProvider
|
||||
shutdownCalls int32
|
||||
}
|
||||
|
||||
func (s *shutdownTrackingProvider) Shutdown(context.Context) error {
|
||||
s.shutdownCalls++
|
||||
return nil
|
||||
}
|
||||
|
||||
// A provider dropped from the managed map owns a background JTI cleanup
|
||||
// worker; replacing the map must shut it down, while providers that stay in
|
||||
// the map keep running.
|
||||
func TestSetIAMManagedOIDCProvidersShutsDownDroppedProviders(t *testing.T) {
|
||||
dropped := &shutdownTrackingProvider{stubIdentityProvider{name: "dropped"}, 0}
|
||||
kept := &shutdownTrackingProvider{stubIdentityProvider{name: "kept"}, 0}
|
||||
added := &shutdownTrackingProvider{stubIdentityProvider{name: "added"}, 0}
|
||||
|
||||
s := &STSService{issuerToProvider: map[string]providers.IdentityProvider{}}
|
||||
s.SetIAMManagedOIDCProviders(map[string][]ScopedOIDCProvider{
|
||||
"https://a.example.com": {{Provider: dropped}},
|
||||
"https://b.example.com": {{Provider: kept}, {AccountID: "111111111111", Provider: kept}},
|
||||
})
|
||||
|
||||
s.SetIAMManagedOIDCProviders(map[string][]ScopedOIDCProvider{
|
||||
"https://b.example.com": {{Provider: kept}},
|
||||
"https://c.example.com": {{Provider: added}},
|
||||
})
|
||||
|
||||
if dropped.shutdownCalls != 1 {
|
||||
t.Fatalf("dropped provider was shut down %d times, want 1", dropped.shutdownCalls)
|
||||
}
|
||||
if kept.shutdownCalls != 0 {
|
||||
t.Fatalf("kept provider was shut down %d times, want 0", kept.shutdownCalls)
|
||||
}
|
||||
if added.shutdownCalls != 0 {
|
||||
t.Fatalf("newly added provider was shut down %d times, want 0", added.shutdownCalls)
|
||||
}
|
||||
|
||||
// Clearing the map releases the remaining providers.
|
||||
s.SetIAMManagedOIDCProviders(nil)
|
||||
if kept.shutdownCalls != 1 || added.shutdownCalls != 1 {
|
||||
t.Fatalf("clearing the map shut down kept=%d added=%d, want 1 each", kept.shutdownCalls, added.shutdownCalls)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -155,21 +154,6 @@ func (f *ProviderFactory) convertToOIDCConfig(configMap map[string]interface{})
|
||||
config.TLSInsecureSkipVerify = tlsInsecureSkipVerify
|
||||
}
|
||||
|
||||
if enabled, ok := configMap[ConfigFieldJTIReplayProtectionEnabled].(bool); ok {
|
||||
config.JTIReplayProtectionEnabled = &enabled
|
||||
}
|
||||
|
||||
switch maxSize := configMap[ConfigFieldJTICacheMaxSize].(type) {
|
||||
case float64:
|
||||
config.JTICacheMaxSize = int(maxSize)
|
||||
case int:
|
||||
config.JTICacheMaxSize = maxSize
|
||||
case json.Number:
|
||||
if n, err := maxSize.Int64(); err == nil {
|
||||
config.JTICacheMaxSize = int(n)
|
||||
}
|
||||
}
|
||||
|
||||
// Convert claims mapping
|
||||
if claimsMapInterface, ok := configMap["claimsMapping"]; ok {
|
||||
claimsMap, err := f.convertToStringMap(claimsMapInterface)
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConvertToOIDCConfigCarriesJTISettings(t *testing.T) {
|
||||
factory := NewProviderFactory()
|
||||
|
||||
config, err := factory.convertToOIDCConfig(map[string]interface{}{
|
||||
"issuer": "https://issuer.example",
|
||||
"clientId": "client",
|
||||
"jtiReplayProtectionEnabled": false,
|
||||
"jtiCacheMaxSize": float64(42),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, config.JTIReplayProtectionEnabled)
|
||||
assert.False(t, *config.JTIReplayProtectionEnabled)
|
||||
assert.Equal(t, 42, config.JTICacheMaxSize)
|
||||
|
||||
config, err = factory.convertToOIDCConfig(map[string]interface{}{
|
||||
"issuer": "https://issuer.example",
|
||||
"clientId": "client",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, config.JTIReplayProtectionEnabled)
|
||||
assert.Zero(t, config.JTICacheMaxSize)
|
||||
}
|
||||
@@ -522,35 +522,8 @@ func (s *STSService) SetIAMManagedOIDCProviders(byIssuer map[string][]ScopedOIDC
|
||||
}
|
||||
}
|
||||
s.iamManagedOIDCMu.Lock()
|
||||
old := s.iamManagedOIDCByIssuer
|
||||
s.iamManagedOIDCByIssuer = cp
|
||||
s.iamManagedOIDCMu.Unlock()
|
||||
|
||||
// Providers dropped by the swap may own background workers (the JTI
|
||||
// cleanup goroutine); stop them so a replaced provider does not leak.
|
||||
kept := make(map[providers.IdentityProvider]struct{})
|
||||
for _, scoped := range cp {
|
||||
for _, sp := range scoped {
|
||||
kept[sp.Provider] = struct{}{}
|
||||
}
|
||||
}
|
||||
stopped := make(map[providers.IdentityProvider]struct{})
|
||||
for _, scoped := range old {
|
||||
for _, sp := range scoped {
|
||||
if _, ok := kept[sp.Provider]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := stopped[sp.Provider]; ok {
|
||||
continue
|
||||
}
|
||||
stopped[sp.Provider] = struct{}{}
|
||||
if sd, ok := sp.Provider.(interface{ Shutdown(context.Context) error }); ok {
|
||||
if err := sd.Shutdown(context.Background()); err != nil {
|
||||
glog.Warningf("OIDC provider %q shutdown after replacement: %v", sp.Provider.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lookupOIDCProviderForAccount returns the provider that should validate
|
||||
@@ -624,7 +597,7 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
// caller passed a legacy or claim-based ARN, in which case lookup falls
|
||||
// back to a global (account-less) record only.
|
||||
roleAccountID := utils.ParseRoleARN(request.RoleArn).AccountID
|
||||
externalIdentity, provider, err := s.validateWebIdentityToken(ctx, request.WebIdentityToken, roleAccountID, true)
|
||||
externalIdentity, provider, err := s.validateWebIdentityToken(ctx, request.WebIdentityToken, roleAccountID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to validate web identity token: %w", err)
|
||||
}
|
||||
@@ -1029,7 +1002,7 @@ func (s *STSService) validateAssumeRoleWithWebIdentityRequest(request *AssumeRol
|
||||
// validateWebIdentityToken validates the web identity token with strict issuer-to-provider mapping
|
||||
// SECURITY: JWT tokens with a specific issuer claim MUST only be validated by the provider for that issuer
|
||||
// SECURITY: This method only accepts JWT tokens. Non-JWT authentication must use AssumeRoleWithCredentials with explicit ProviderName.
|
||||
func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAccountID string, singleUse bool) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAccountID string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
// Try to extract issuer from JWT token for strict validation
|
||||
issuer, err := s.extractIssuerFromJWT(token)
|
||||
if err != nil {
|
||||
@@ -1052,10 +1025,8 @@ func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAc
|
||||
return nil, nil, fmt.Errorf("no identity provider registered for issuer: %s", issuer)
|
||||
}
|
||||
|
||||
// Authenticate with the correct provider for this issuer. Only the STS
|
||||
// exchange authenticates single-use: a bearer token is presented on every
|
||||
// request, so consuming it here would reject all but the first one.
|
||||
identity, err := authenticateOIDCProvider(ctx, provider, token, singleUse)
|
||||
// Authenticate with the correct provider for this issuer
|
||||
identity, err := provider.Authenticate(ctx, token)
|
||||
if err != nil {
|
||||
// Map provider errors to STS errors using errors.Is() for robust error checking
|
||||
// This eliminates fragile string matching and provides reliable error classification
|
||||
@@ -1087,29 +1058,14 @@ func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAc
|
||||
// only, then static-config); call ValidateWebIdentityTokenForAccount when the assumed-role account
|
||||
// is known.
|
||||
func (s *STSService) ValidateWebIdentityToken(ctx context.Context, token string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
return s.validateWebIdentityToken(ctx, token, "", false)
|
||||
return s.validateWebIdentityToken(ctx, token, "")
|
||||
}
|
||||
|
||||
// ValidateWebIdentityTokenForAccount mirrors ValidateWebIdentityToken but
|
||||
// scopes the IAM-managed provider lookup to roleAccountID. Pass "" for
|
||||
// callers that don't yet know the account (e.g. claim-based mode).
|
||||
func (s *STSService) ValidateWebIdentityTokenForAccount(ctx context.Context, token, roleAccountID string) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
return s.validateWebIdentityToken(ctx, token, roleAccountID, false)
|
||||
}
|
||||
|
||||
// authenticateOIDCProvider authenticates the token, consuming it for replay
|
||||
// protection when the caller is the single-use STS exchange and the provider
|
||||
// supports it. Other providers and non-exchange callers authenticate without
|
||||
// consuming.
|
||||
func authenticateOIDCProvider(ctx context.Context, provider providers.IdentityProvider, token string, singleUse bool) (*providers.ExternalIdentity, error) {
|
||||
if singleUse {
|
||||
if su, ok := provider.(interface {
|
||||
AuthenticateSingleUse(context.Context, string) (*providers.ExternalIdentity, error)
|
||||
}); ok {
|
||||
return su.AuthenticateSingleUse(ctx, token)
|
||||
}
|
||||
}
|
||||
return provider.Authenticate(ctx, token)
|
||||
return s.validateWebIdentityToken(ctx, token, roleAccountID)
|
||||
}
|
||||
|
||||
// extractIssuerFromJWT extracts the issuer (iss) claim from a JWT token without verification
|
||||
|
||||
@@ -79,7 +79,11 @@ func LookupFileId(masterFn GetMasterFn, grpcDialOption grpc.DialOption, fileId s
|
||||
}
|
||||
|
||||
func LookupVolumeId(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vid string) (*LookupResult, error) {
|
||||
results, err := LookupVolumeIds(masterFn, grpcDialOption, []string{vid})
|
||||
return LookupVolumeIdWithContext(context.Background(), masterFn, grpcDialOption, vid)
|
||||
}
|
||||
|
||||
func LookupVolumeIdWithContext(ctx context.Context, masterFn GetMasterFn, grpcDialOption grpc.DialOption, vid string) (*LookupResult, error) {
|
||||
results, err := LookupVolumeIdsWithContext(ctx, masterFn, grpcDialOption, []string{vid})
|
||||
return results[vid], err
|
||||
}
|
||||
|
||||
@@ -90,6 +94,12 @@ func InvalidateVolumeIdLocationCache(vid string) {
|
||||
|
||||
// LookupVolumeIds find volume locations by cache and actual lookup
|
||||
func LookupVolumeIds(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vids []string, useCache ...bool) (map[string]*LookupResult, error) {
|
||||
return LookupVolumeIdsWithContext(context.Background(), masterFn, grpcDialOption, vids, useCache...)
|
||||
}
|
||||
|
||||
// LookupVolumeIdsWithContext is LookupVolumeIds bound to ctx, so a caller's
|
||||
// cancellation (e.g. a dropped inbound request) also stops the master query.
|
||||
func LookupVolumeIdsWithContext(ctx context.Context, masterFn GetMasterFn, grpcDialOption grpc.DialOption, vids []string, useCache ...bool) (map[string]*LookupResult, error) {
|
||||
ret := make(map[string]*LookupResult)
|
||||
var unknown_vids []string
|
||||
cacheLocations := len(useCache) == 0 || useCache[0]
|
||||
@@ -112,12 +122,12 @@ func LookupVolumeIds(masterFn GetMasterFn, grpcDialOption grpc.DialOption, vids
|
||||
|
||||
//only query unknown_vids
|
||||
|
||||
err := WithMasterServerClient(context.Background(), false, masterFn(context.Background()), grpcDialOption, func(masterClient master_pb.SeaweedClient) error {
|
||||
err := WithMasterServerClient(ctx, false, masterFn(ctx), grpcDialOption, func(masterClient master_pb.SeaweedClient) error {
|
||||
|
||||
req := &master_pb.LookupVolumeRequest{
|
||||
VolumeOrFileIds: unknown_vids,
|
||||
}
|
||||
resp, grpcErr := masterClient.LookupVolume(context.Background(), req)
|
||||
resp, grpcErr := masterClient.LookupVolume(ctx, req)
|
||||
if grpcErr != nil {
|
||||
return grpcErr
|
||||
}
|
||||
|
||||
@@ -166,6 +166,10 @@ message Entry {
|
||||
repeated FileChunk chunks = 3;
|
||||
FuseAttributes attributes = 4;
|
||||
map<string, bytes> extended = 5;
|
||||
// filer-local commit timestamp of the version stored here: the meta log
|
||||
// event's ts_ns for the mutation that produced this entry, or 0 for
|
||||
// entries written before the field existed
|
||||
int64 commit_ts_ns = 6;
|
||||
bytes hard_link_id = 7;
|
||||
int32 hard_link_counter = 8; // only exists in hard link meta data
|
||||
bytes content = 9; // if not empty, the file content
|
||||
|
||||
@@ -672,18 +672,22 @@ func (x *RemoteEntry) GetRemoteContentEncoding() string {
|
||||
}
|
||||
|
||||
type Entry struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
IsDirectory bool `protobuf:"varint,2,opt,name=is_directory,json=isDirectory,proto3" json:"is_directory,omitempty"`
|
||||
Chunks []*FileChunk `protobuf:"bytes,3,rep,name=chunks,proto3" json:"chunks,omitempty"`
|
||||
Attributes *FuseAttributes `protobuf:"bytes,4,opt,name=attributes,proto3" json:"attributes,omitempty"`
|
||||
Extended map[string][]byte `protobuf:"bytes,5,rep,name=extended,proto3" json:"extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
HardLinkId []byte `protobuf:"bytes,7,opt,name=hard_link_id,json=hardLinkId,proto3" json:"hard_link_id,omitempty"`
|
||||
HardLinkCounter int32 `protobuf:"varint,8,opt,name=hard_link_counter,json=hardLinkCounter,proto3" json:"hard_link_counter,omitempty"` // only exists in hard link meta data
|
||||
Content []byte `protobuf:"bytes,9,opt,name=content,proto3" json:"content,omitempty"` // if not empty, the file content
|
||||
RemoteEntry *RemoteEntry `protobuf:"bytes,10,opt,name=remote_entry,json=remoteEntry,proto3" json:"remote_entry,omitempty"`
|
||||
Quota int64 `protobuf:"varint,11,opt,name=quota,proto3" json:"quota,omitempty"` // for bucket only. Positive/Negative means enabled/disabled.
|
||||
WormEnforcedAtTsNs int64 `protobuf:"varint,12,opt,name=worm_enforced_at_ts_ns,json=wormEnforcedAtTsNs,proto3" json:"worm_enforced_at_ts_ns,omitempty"`
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
IsDirectory bool `protobuf:"varint,2,opt,name=is_directory,json=isDirectory,proto3" json:"is_directory,omitempty"`
|
||||
Chunks []*FileChunk `protobuf:"bytes,3,rep,name=chunks,proto3" json:"chunks,omitempty"`
|
||||
Attributes *FuseAttributes `protobuf:"bytes,4,opt,name=attributes,proto3" json:"attributes,omitempty"`
|
||||
Extended map[string][]byte `protobuf:"bytes,5,rep,name=extended,proto3" json:"extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
// filer-local commit timestamp of the version stored here: the meta log
|
||||
// event's ts_ns for the mutation that produced this entry, or 0 for
|
||||
// entries written before the field existed
|
||||
CommitTsNs int64 `protobuf:"varint,6,opt,name=commit_ts_ns,json=commitTsNs,proto3" json:"commit_ts_ns,omitempty"`
|
||||
HardLinkId []byte `protobuf:"bytes,7,opt,name=hard_link_id,json=hardLinkId,proto3" json:"hard_link_id,omitempty"`
|
||||
HardLinkCounter int32 `protobuf:"varint,8,opt,name=hard_link_counter,json=hardLinkCounter,proto3" json:"hard_link_counter,omitempty"` // only exists in hard link meta data
|
||||
Content []byte `protobuf:"bytes,9,opt,name=content,proto3" json:"content,omitempty"` // if not empty, the file content
|
||||
RemoteEntry *RemoteEntry `protobuf:"bytes,10,opt,name=remote_entry,json=remoteEntry,proto3" json:"remote_entry,omitempty"`
|
||||
Quota int64 `protobuf:"varint,11,opt,name=quota,proto3" json:"quota,omitempty"` // for bucket only. Positive/Negative means enabled/disabled.
|
||||
WormEnforcedAtTsNs int64 `protobuf:"varint,12,opt,name=worm_enforced_at_ts_ns,json=wormEnforcedAtTsNs,proto3" json:"worm_enforced_at_ts_ns,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -753,6 +757,13 @@ func (x *Entry) GetExtended() map[string][]byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Entry) GetCommitTsNs() int64 {
|
||||
if x != nil {
|
||||
return x.CommitTsNs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Entry) GetHardLinkId() []byte {
|
||||
if x != nil {
|
||||
return x.HardLinkId
|
||||
@@ -7300,7 +7311,7 @@ const file_filer_proto_rawDesc = "" +
|
||||
"\vremote_size\x18\x05 \x01(\x03R\n" +
|
||||
"remoteSize\x12;\n" +
|
||||
"\x17remote_content_encoding\x18\x06 \x01(\tH\x00R\x15remoteContentEncoding\x88\x01\x01B\x1a\n" +
|
||||
"\x18_remote_content_encoding\"\x89\x04\n" +
|
||||
"\x18_remote_content_encoding\"\xab\x04\n" +
|
||||
"\x05Entry\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12!\n" +
|
||||
"\fis_directory\x18\x02 \x01(\bR\visDirectory\x12+\n" +
|
||||
@@ -7309,6 +7320,8 @@ const file_filer_proto_rawDesc = "" +
|
||||
"attributes\x18\x04 \x01(\v2\x18.filer_pb.FuseAttributesR\n" +
|
||||
"attributes\x129\n" +
|
||||
"\bextended\x18\x05 \x03(\v2\x1d.filer_pb.Entry.ExtendedEntryR\bextended\x12 \n" +
|
||||
"\fcommit_ts_ns\x18\x06 \x01(\x03R\n" +
|
||||
"commitTsNs\x12 \n" +
|
||||
"\fhard_link_id\x18\a \x01(\fR\n" +
|
||||
"hardLinkId\x12*\n" +
|
||||
"\x11hard_link_counter\x18\b \x01(\x05R\x0fhardLinkCounter\x12\x18\n" +
|
||||
|
||||
@@ -389,6 +389,11 @@ func (m *Entry) MarshalToSizedBufferVT(dAtA []byte) (int, error) {
|
||||
i--
|
||||
dAtA[i] = 0x3a
|
||||
}
|
||||
if m.CommitTsNs != 0 {
|
||||
i = protohelpers.EncodeVarint(dAtA, i, uint64(m.CommitTsNs))
|
||||
i--
|
||||
dAtA[i] = 0x30
|
||||
}
|
||||
if len(m.Extended) > 0 {
|
||||
for k := range m.Extended {
|
||||
v := m.Extended[k]
|
||||
@@ -6702,6 +6707,9 @@ func (m *Entry) SizeVT() (n int) {
|
||||
n += mapEntrySize + 1 + protohelpers.SizeOfVarint(uint64(mapEntrySize))
|
||||
}
|
||||
}
|
||||
if m.CommitTsNs != 0 {
|
||||
n += 1 + protohelpers.SizeOfVarint(uint64(m.CommitTsNs))
|
||||
}
|
||||
l = len(m.HardLinkId)
|
||||
if l > 0 {
|
||||
n += 1 + l + protohelpers.SizeOfVarint(uint64(l))
|
||||
@@ -10230,6 +10238,25 @@ func (m *Entry) UnmarshalVT(dAtA []byte) error {
|
||||
}
|
||||
m.Extended[mapkey] = mapvalue
|
||||
iNdEx = postIndex
|
||||
case 6:
|
||||
if wireType != 0 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field CommitTsNs", wireType)
|
||||
}
|
||||
m.CommitTsNs = 0
|
||||
for shift := uint(0); ; shift += 7 {
|
||||
if shift >= 64 {
|
||||
return protohelpers.ErrIntOverflow
|
||||
}
|
||||
if iNdEx >= l {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
b := dAtA[iNdEx]
|
||||
iNdEx++
|
||||
m.CommitTsNs |= int64(b&0x7F) << shift
|
||||
if b < 0x80 {
|
||||
break
|
||||
}
|
||||
}
|
||||
case 7:
|
||||
if wireType != 2 {
|
||||
return fmt.Errorf("proto: wrong wireType = %d for field HardLinkId", wireType)
|
||||
|
||||
@@ -7,7 +7,8 @@ import (
|
||||
|
||||
// ConditionalHeaderResult holds the result of conditional header checking
|
||||
type ConditionalHeaderResult struct {
|
||||
ErrorCode s3err.ErrorCode
|
||||
ETag string // ETag of the object (for 304 responses)
|
||||
Entry *filer_pb.Entry // Entry fetched during conditional check (nil if not fetched or object doesn't exist)
|
||||
ErrorCode s3err.ErrorCode
|
||||
ETag string // ETag of the object (for 304 responses)
|
||||
Entry *filer_pb.Entry // Entry fetched during conditional check (nil if not fetched or object doesn't exist)
|
||||
DeleteMarker *filer_pb.Entry // Set when the resolved entry is a delete marker, so a missing-key answer can still carry its headers
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWriteDeleteMarkerResponse(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "v_marker",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 784111777},
|
||||
Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte("true")},
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, requestedVersionId string
|
||||
status int
|
||||
lastModified string
|
||||
allow string
|
||||
}{
|
||||
{"current version", "", http.StatusNotFound, "", ""},
|
||||
{"marker by versionId", "marker", http.StatusMethodNotAllowed, "Sun, 06 Nov 1994 08:49:37 GMT", "DELETE"},
|
||||
} {
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
w := httptest.NewRecorder()
|
||||
s3a.writeDeleteMarkerResponse(w, httptest.NewRequest(method, "/bucket/object", nil), "bucket", "object", "TestHandler", entry, "marker", tc.requestedVersionId)
|
||||
if w.Code != tc.status {
|
||||
t.Errorf("%s %s: status %d, want %d", tc.name, method, w.Code, tc.status)
|
||||
}
|
||||
if got := w.Header().Get(s3_constants.AmzDeleteMarker); got != "true" {
|
||||
t.Errorf("%s %s: %s = %q, want true", tc.name, method, s3_constants.AmzDeleteMarker, got)
|
||||
}
|
||||
if got := w.Header().Get("x-amz-version-id"); got != "marker" {
|
||||
t.Errorf("%s %s: x-amz-version-id = %q, want marker", tc.name, method, got)
|
||||
}
|
||||
if got := w.Header().Get("Last-Modified"); got != tc.lastModified {
|
||||
t.Errorf("%s %s: Last-Modified = %q, want %q", tc.name, method, got, tc.lastModified)
|
||||
}
|
||||
if got := w.Header().Get("Allow"); got != tc.allow {
|
||||
t.Errorf("%s %s: Allow = %q, want %q", tc.name, method, got, tc.allow)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteDeleteMarkerResponseAnonymous(t *testing.T) {
|
||||
s3a, _ := newAnonymousReadTestServer(t)
|
||||
require.NoError(t, s3a.policyEngine.engine.SetBucketPolicy("b", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:ListBucket","Resource":"arn:aws:s3:::b"}]}`))
|
||||
entry := anonymousReadEntry(anonymousReadGrant("READ"))
|
||||
entry.Extended[s3_constants.ExtDeleteMarkerKey] = []byte("true")
|
||||
for _, query := range []string{"", "?versionId=m"} {
|
||||
r := mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/b/o"+query, nil), map[string]string{"bucket": "b", "object": "o"})
|
||||
r, deferred := s3a.deferAnonymousObjectRead(r, s3_constants.ACTION_READ, "b", "o")
|
||||
require.True(t, deferred)
|
||||
w := httptest.NewRecorder()
|
||||
s3a.writeDeleteMarkerResponse(w, r, "b", "o", "TestHandler", entry, "m", r.URL.Query().Get("versionId"))
|
||||
require.Equal(t, http.StatusNotFound, w.Code, query)
|
||||
require.Empty(t, w.Header().Get(s3_constants.AmzDeleteMarker), query)
|
||||
require.Empty(t, w.Header().Get("x-amz-version-id"), query)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteConditionalCheckErrorDeleteMarker(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
marker := &filer_pb.Entry{
|
||||
Name: "v_marker",
|
||||
Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte("true"), s3_constants.ExtVersionIdKey: []byte("marker")},
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
w := httptest.NewRecorder()
|
||||
s3a.writeConditionalCheckError(w, httptest.NewRequest(method, "/bucket/object", nil), "bucket", "object", "TestHandler", ConditionalHeaderResult{ErrorCode: s3err.ErrNoSuchKey, DeleteMarker: marker})
|
||||
require.Equal(t, http.StatusNotFound, w.Code, method)
|
||||
require.Equal(t, "true", w.Header().Get(s3_constants.AmzDeleteMarker), method)
|
||||
require.Equal(t, "marker", w.Header().Get("x-amz-version-id"), method)
|
||||
}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
s3a.writeConditionalCheckError(w, httptest.NewRequest(http.MethodGet, "/bucket/object", nil), "bucket", "object", "TestHandler", ConditionalHeaderResult{ErrorCode: s3err.ErrNoSuchKey})
|
||||
require.Equal(t, http.StatusNotFound, w.Code)
|
||||
require.Empty(t, w.Header().Get(s3_constants.AmzDeleteMarker))
|
||||
}
|
||||
|
||||
func TestWriteConditionalCheckErrorDeleteMarkerVersionFromName(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
marker := &filer_pb.Entry{
|
||||
Name: "v_named",
|
||||
Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte("true")},
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s3a.writeConditionalCheckError(w, httptest.NewRequest(http.MethodGet, "/bucket/object", nil), "bucket", "object", "TestHandler", ConditionalHeaderResult{ErrorCode: s3err.ErrNoSuchKey, DeleteMarker: marker})
|
||||
require.Equal(t, http.StatusNotFound, w.Code)
|
||||
require.Equal(t, "named", w.Header().Get("x-amz-version-id"))
|
||||
}
|
||||
|
||||
func newDeleteMarkerTestServer(t *testing.T) *S3ApiServer {
|
||||
t.Helper()
|
||||
f := &anonymousReadFiler{entries: map[string]*filer_pb.Entry{
|
||||
"/buckets/b/o.versions": {
|
||||
Name: "o.versions",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 784111700},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("marker"),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_marker"),
|
||||
},
|
||||
},
|
||||
"/buckets/b/o.versions/v_marker": {
|
||||
Name: "v_marker",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 784111777},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtDeleteMarkerKey: []byte("true"),
|
||||
s3_constants.ExtVersionIdKey: []byte("marker"),
|
||||
},
|
||||
},
|
||||
}}
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, f))
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b", Versioning: s3_constants.VersioningEnabled})
|
||||
return s3a
|
||||
}
|
||||
|
||||
func TestGetHeadDeleteMarker(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, query string
|
||||
status int
|
||||
lastModified, allow string
|
||||
}{
|
||||
{"current marker", "", http.StatusNotFound, "", ""},
|
||||
{"marker by versionId", "?versionId=marker", http.StatusMethodNotAllowed, "Sun, 06 Nov 1994 08:49:37 GMT", "DELETE"},
|
||||
} {
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
t.Run(tc.name+"/"+method, func(t *testing.T) {
|
||||
s3a := newDeleteMarkerTestServer(t)
|
||||
r := mux.SetURLVars(httptest.NewRequest(method, "/b/o"+tc.query, nil), map[string]string{"bucket": "b", "object": "o"})
|
||||
w := httptest.NewRecorder()
|
||||
handler := s3a.GetObjectHandler
|
||||
if method == http.MethodHead {
|
||||
handler = s3a.HeadObjectHandler
|
||||
}
|
||||
handler(w, r)
|
||||
require.Equal(t, tc.status, w.Code)
|
||||
require.Equal(t, "true", w.Header().Get(s3_constants.AmzDeleteMarker))
|
||||
require.Equal(t, "marker", w.Header().Get("x-amz-version-id"))
|
||||
require.Equal(t, tc.lastModified, w.Header().Get("Last-Modified"))
|
||||
require.Equal(t, tc.allow, w.Header().Get("Allow"))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHeadNullDeleteMarker(t *testing.T) {
|
||||
f := &anonymousReadFiler{entries: map[string]*filer_pb.Entry{
|
||||
"/buckets/b/o.versions": {
|
||||
Name: "o.versions",
|
||||
IsDirectory: true,
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 784111700},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtLatestVersionIdKey: []byte("null"),
|
||||
s3_constants.ExtLatestVersionFileNameKey: []byte("v_null"),
|
||||
},
|
||||
},
|
||||
"/buckets/b/o.versions/v_null": {
|
||||
Name: "v_null",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 784111777},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.ExtDeleteMarkerKey: []byte("true"),
|
||||
s3_constants.ExtVersionIdKey: []byte("null"),
|
||||
},
|
||||
},
|
||||
}}
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
t.Run(method, func(t *testing.T) {
|
||||
s3a := newPutTestServer(t, startFakeFiler(t, f))
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b", Versioning: s3_constants.VersioningSuspended})
|
||||
r := mux.SetURLVars(httptest.NewRequest(method, "/b/o?versionId=null", nil), map[string]string{"bucket": "b", "object": "o"})
|
||||
w := httptest.NewRecorder()
|
||||
handler := s3a.GetObjectHandler
|
||||
if method == http.MethodHead {
|
||||
handler = s3a.HeadObjectHandler
|
||||
}
|
||||
handler(w, r)
|
||||
require.Equal(t, http.StatusMethodNotAllowed, w.Code)
|
||||
require.Equal(t, "true", w.Header().Get(s3_constants.AmzDeleteMarker))
|
||||
require.Equal(t, "null", w.Header().Get("x-amz-version-id"))
|
||||
require.Equal(t, "DELETE", w.Header().Get("Allow"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHeadNullVersionAbsent(t *testing.T) {
|
||||
s3a := newDeleteMarkerTestServer(t)
|
||||
r := mux.SetURLVars(httptest.NewRequest(http.MethodGet, "/b/o?versionId=null", nil), map[string]string{"bucket": "b", "object": "o"})
|
||||
w := httptest.NewRecorder()
|
||||
s3a.GetObjectHandler(w, r)
|
||||
require.Equal(t, http.StatusNotFound, w.Code)
|
||||
require.Empty(t, w.Header().Get(s3_constants.AmzDeleteMarker))
|
||||
}
|
||||
|
||||
func TestGetHeadDeleteMarkerConditionalMiss(t *testing.T) {
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
t.Run(method, func(t *testing.T) {
|
||||
s3a := newDeleteMarkerTestServer(t)
|
||||
r := httptest.NewRequest(method, "/b/o", nil)
|
||||
r.Header.Set("If-Match", `"no-match"`)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "b", "object": "o"})
|
||||
w := httptest.NewRecorder()
|
||||
handler := s3a.GetObjectHandler
|
||||
if method == http.MethodHead {
|
||||
handler = s3a.HeadObjectHandler
|
||||
}
|
||||
handler(w, r)
|
||||
require.Equal(t, http.StatusNotFound, w.Code)
|
||||
require.Equal(t, "true", w.Header().Get(s3_constants.AmzDeleteMarker))
|
||||
require.Equal(t, "marker", w.Header().Get("x-amz-version-id"))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -790,16 +790,63 @@ func (s3a *S3ApiServer) processConditionalHeaders(w http.ResponseWriter, r *http
|
||||
w.Header().Set("ETag", result.ETag)
|
||||
}
|
||||
|
||||
if result.ErrorCode == s3err.ErrNoSuchKey || result.ErrorCode == s3err.ErrNoSuchBucket {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, result.ErrorCode)
|
||||
} else {
|
||||
s3err.WriteErrorResponse(w, r, result.ErrorCode)
|
||||
}
|
||||
s3a.writeConditionalCheckError(w, r, bucket, object, handlerName, result)
|
||||
return result, true // request handled
|
||||
}
|
||||
return result, false // request not handled
|
||||
}
|
||||
|
||||
// writeConditionalCheckError answers a failed conditional-header check. A
|
||||
// missing-key answer still carries the delete marker's headers when the
|
||||
// condition failed against one, so a resuming client can tell a deleted key
|
||||
// from one that never existed.
|
||||
func (s3a *S3ApiServer) writeConditionalCheckError(w http.ResponseWriter, r *http.Request, bucket, object, handlerName string, result ConditionalHeaderResult) {
|
||||
if result.ErrorCode == s3err.ErrNoSuchKey && result.DeleteMarker != nil {
|
||||
s3a.writeDeleteMarkerResponse(w, r, bucket, object, handlerName, result.DeleteMarker, "", "")
|
||||
return
|
||||
}
|
||||
if result.ErrorCode == s3err.ErrNoSuchKey || result.ErrorCode == s3err.ErrNoSuchBucket {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, result.ErrorCode)
|
||||
return
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, result.ErrorCode)
|
||||
}
|
||||
|
||||
// writeDeleteMarkerResponse answers a GET or HEAD that resolved to a delete
|
||||
// marker as S3 does: x-amz-delete-marker and the marker's version id, with
|
||||
// 404 NoSuchKey for the current version and 405 MethodNotAllowed when the
|
||||
// marker itself was requested by versionId. Anonymous reads never get a
|
||||
// delete marker (authorizeAnonymousObjectRead), so they keep the plain miss.
|
||||
func (s3a *S3ApiServer) writeDeleteMarkerResponse(w http.ResponseWriter, r *http.Request, bucket, object, handlerName string, entry *filer_pb.Entry, markerVersionId, requestedVersionId string) {
|
||||
if isAnonymousObjectRead(r) {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, string(s3_constants.ACTION_READ), entry.Extended, handlerName); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
// The entry's own version id wins: markers written outside the normal PUT
|
||||
// path may lack the attribute yet still carry it in the v_<id> file name.
|
||||
if versionId := versionIdFromEntry(entry); versionId != "" {
|
||||
markerVersionId = versionId
|
||||
}
|
||||
if markerVersionId == "" {
|
||||
markerVersionId = "null"
|
||||
}
|
||||
w.Header().Set(s3_constants.AmzDeleteMarker, "true")
|
||||
w.Header().Set("x-amz-version-id", markerVersionId)
|
||||
if requestedVersionId == "" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Allow", "DELETE")
|
||||
if entry.Attributes != nil {
|
||||
w.Header().Set("Last-Modified", time.Unix(entry.Attributes.Mtime, 0).UTC().Format(http.TimeFormat))
|
||||
}
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrMethodNotAllowed)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
@@ -882,6 +929,18 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
glog.V(3).Infof("GetObject: requesting specific version %s for %s/%s", versionId, bucket, object)
|
||||
entry, err = s3a.getSpecificObjectVersion(bucket, object, versionId)
|
||||
if err != nil {
|
||||
if versionId == "null" && errors.Is(err, filer_pb.ErrNotFound) {
|
||||
marker, markerErr := s3a.nullDeleteMarkerEntry(bucket, object)
|
||||
if markerErr != nil {
|
||||
glog.Errorf("GetObject: failed to look up null delete marker for %s/%s: %v", bucket, object, markerErr)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
if marker != nil {
|
||||
s3a.writeDeleteMarkerResponse(w, r, bucket, object, "GetObjectHandler", marker, "null", versionId)
|
||||
return
|
||||
}
|
||||
}
|
||||
glog.Errorf("Failed to get specific version %s: %v", versionId, err)
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchVersion)
|
||||
@@ -954,7 +1013,7 @@ func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request)
|
||||
// Check if this is a delete marker
|
||||
if entry.Extended != nil {
|
||||
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
s3a.writeDeleteMarkerResponse(w, r, bucket, object, "GetObjectHandler", entry, targetVersionId, versionId)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -2565,6 +2624,18 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
glog.V(2).Infof("HeadObject: requesting specific version %s for %s/%s", versionId, bucket, object)
|
||||
entry, err = s3a.getSpecificObjectVersion(bucket, object, versionId)
|
||||
if err != nil {
|
||||
if versionId == "null" && errors.Is(err, filer_pb.ErrNotFound) {
|
||||
marker, markerErr := s3a.nullDeleteMarkerEntry(bucket, object)
|
||||
if markerErr != nil {
|
||||
glog.Errorf("HeadObject: failed to look up null delete marker for %s/%s: %v", bucket, object, markerErr)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
if marker != nil {
|
||||
s3a.writeDeleteMarkerResponse(w, r, bucket, object, "HeadObjectHandler", marker, "null", versionId)
|
||||
return
|
||||
}
|
||||
}
|
||||
glog.Errorf("Failed to get specific version %s for %s/%s: %v", versionId, bucket, object, err)
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchVersion)
|
||||
@@ -2637,7 +2708,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
|
||||
// Check if this is a delete marker
|
||||
if entry.Extended != nil {
|
||||
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
s3a.writeDeleteMarkerResponse(w, r, bucket, object, "HeadObjectHandler", entry, targetVersionId, versionId)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3022,7 +3022,11 @@ func (s3a *S3ApiServer) checkConditionalHeadersForReads(r *http.Request, bucket,
|
||||
if versionId != "" && normalizeConditionalTargetEntry(entry) == nil {
|
||||
return ConditionalHeaderResult{ErrorCode: s3err.ErrNone, Entry: nil}
|
||||
}
|
||||
return s3a.validateConditionalHeadersForReads(r, headers, entry, bucket, object)
|
||||
result := s3a.validateConditionalHeadersForReads(r, headers, entry, bucket, object)
|
||||
if entry != nil && normalizeConditionalTargetEntry(entry) == nil {
|
||||
result.DeleteMarker = entry
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// lookupVolumeJwt mints a fresh volume-server JWT for an existing file id, so a
|
||||
|
||||
@@ -314,6 +314,26 @@ func (s3a *S3ApiServer) createNullDeleteMarker(bucket, object string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// nullDeleteMarkerEntry returns the suspended-versioning "null" delete marker
|
||||
// stored under .versions, or nil when the object has none.
|
||||
// getSpecificObjectVersion only checks the plain path for "null", so callers
|
||||
// that must answer a marker named by versionId consult this on a miss. Lookup
|
||||
// failures other than not found propagate: a masked read error would answer
|
||||
// a live filer hiccup as a deleted version.
|
||||
func (s3a *S3ApiServer) nullDeleteMarkerEntry(bucket, object string) (*filer_pb.Entry, error) {
|
||||
entry, err := s3a.getEntry(s3a.getVersionedObjectDir(bucket, s3_constants.NormalizeObjectKey(object)), s3a.getVersionFileName("null"))
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if entry == nil || string(entry.Extended[s3_constants.ExtDeleteMarkerKey]) != "true" {
|
||||
return nil, nil
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// versionListItem represents an item in the unified version/prefix list
|
||||
type versionListItem struct {
|
||||
key string
|
||||
|
||||
@@ -7,12 +7,10 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -99,7 +97,6 @@ func TestAssumeRoleWithWebIdentityOverHTTP(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{iamIntegration: NewS3IAMIntegration(manager, "")}
|
||||
handlers := NewSTSHandlers(manager.GetSTSService(), iam)
|
||||
|
||||
var jtiCounter atomic.Int64
|
||||
signOIDCToken := func(t *testing.T, subject string) string {
|
||||
t.Helper()
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
|
||||
@@ -108,10 +105,6 @@ func TestAssumeRoleWithWebIdentityOverHTTP(t *testing.T) {
|
||||
"aud": "test-client",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
"iat": time.Now().Unix(),
|
||||
// a unique jti per token: the exchange consumes it, so two
|
||||
// subtests minting the same claims in one second would otherwise
|
||||
// collide on the token fingerprint and read as a replay
|
||||
"jti": fmt.Sprintf("%s-%d", subject, jtiCounter.Add(1)),
|
||||
})
|
||||
token.Header["kid"] = "web-identity-test-key"
|
||||
signed, err := token.SignedString(key)
|
||||
@@ -181,6 +174,25 @@ func TestAssumeRoleWithWebIdentityOverHTTP(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// Kubernetes workload identity re-presents the same projected token until
|
||||
// ~80% of its lifetime, so one token must exchange more than once.
|
||||
t.Run("the same token exchanges twice", func(t *testing.T) {
|
||||
form := url.Values{
|
||||
"Action": {"AssumeRoleWithWebIdentity"},
|
||||
"Version": {"2011-06-15"},
|
||||
"RoleArn": {trustedRoleArn},
|
||||
"RoleSessionName": {"web-session-reuse"},
|
||||
"WebIdentityToken": {signOIDCToken(t, "oidc-user-1")},
|
||||
}
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
req := httptest.NewRequest(http.MethodPost, "http://sts.seaweedfs.test/", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
rec := httptest.NewRecorder()
|
||||
handlers.HandleSTSRequest(rec, req)
|
||||
require.Equal(t, http.StatusOK, rec.Code, "attempt %d: %s", attempt, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("inline session policy is reported in PackedPolicySize", func(t *testing.T) {
|
||||
sessionPolicy := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"]}]}`
|
||||
form := url.Values{
|
||||
|
||||
@@ -668,7 +668,9 @@ func (fs *FilerServer) applyObjectMutation(ctx context.Context, m *filer_pb.Obje
|
||||
if m.TouchMtime {
|
||||
newEntry.Attr.Mtime = time.Now()
|
||||
}
|
||||
fs.filer.StampEntryCommitTsNs(newEntry)
|
||||
if err := fs.filer.UpdateEntry(ctx, oldEntry, newEntry, fromOtherCluster); err != nil {
|
||||
fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs)
|
||||
return err
|
||||
}
|
||||
// Emit the metadata event so the update replicates and subscribers see it,
|
||||
@@ -773,7 +775,9 @@ func (fs *FilerServer) applyRecomputeLatest(ctx context.Context, m *filer_pb.Obj
|
||||
}
|
||||
}
|
||||
|
||||
fs.filer.StampEntryCommitTsNs(pointer)
|
||||
if err := fs.filer.UpdateEntry(ctx, oldPointer, pointer, fromOtherCluster); err != nil {
|
||||
fs.filer.ReleaseEntryCommitTsNs(pointer.CommitTsNs)
|
||||
return err
|
||||
}
|
||||
// Replicate the recomputed pointer to peer filers and subscribers. Without
|
||||
@@ -803,7 +807,9 @@ func (fs *FilerServer) applyRecomputeLatest(ctx context.Context, m *filer_pb.Obj
|
||||
priorEntry.Extended = make(map[string][]byte)
|
||||
}
|
||||
priorEntry.Extended[rc.DemoteKey] = rc.DemoteValue
|
||||
fs.filer.StampEntryCommitTsNs(priorEntry)
|
||||
if err := fs.filer.UpdateEntry(ctx, oldPrior, priorEntry, fromOtherCluster); err != nil {
|
||||
fs.filer.ReleaseEntryCommitTsNs(priorEntry.CommitTsNs)
|
||||
return err
|
||||
}
|
||||
fs.filer.NotifyUpdateEvent(ctx, oldPrior, priorEntry, false, fromOtherCluster, signatures)
|
||||
@@ -899,6 +905,7 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr
|
||||
|
||||
ctx, eventSink := filer.WithMetadataEventSink(ctx)
|
||||
resp := &filer_pb.UpdateEntryResponse{LogTsNs: logTsNs, LogSignature: fs.filer.Signature}
|
||||
fs.filer.StampEntryCommitTsNs(newEntry)
|
||||
if err = fs.filer.UpdateEntry(ctx, entry, newEntry, req.IsFromOtherCluster); err == nil {
|
||||
fs.filer.DeleteChunksNotRecursive(garbage)
|
||||
|
||||
@@ -906,6 +913,7 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr
|
||||
resp.MetadataEvent = eventSink.Last()
|
||||
|
||||
} else {
|
||||
fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs)
|
||||
glog.V(3).InfofCtx(ctx, "UpdateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), err)
|
||||
}
|
||||
|
||||
|
||||
@@ -318,7 +318,9 @@ func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, re
|
||||
|
||||
// this skips meta data log events
|
||||
|
||||
fs.filer.StampEntryCommitTsNs(newEntry)
|
||||
if err := fs.filer.Store.UpdateEntry(context.Background(), newEntry); err != nil {
|
||||
fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs)
|
||||
fs.filer.DeleteUncommittedChunks(ctx, chunks)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -78,10 +78,12 @@ func (fs *FilerServer) AtomicRenameEntry(ctx context.Context, req *filer_pb.Atom
|
||||
var pendingRemoteCopies []*pendingRemoteCopy
|
||||
moveErr := fs.moveEntry(ctx, nil, oldParent, oldEntry, newParent, req.NewName, req.Signatures, false, &metadataEvents, &pendingChunkDeletes, &pendingRemoteCopies)
|
||||
if moveErr != nil {
|
||||
releaseMetadataEventStamps(fs.filer, metadataEvents)
|
||||
fs.filer.RollbackTransaction(ctx)
|
||||
return nil, fmt.Errorf("%s/%s move error: %v", req.OldDirectory, req.OldName, moveErr)
|
||||
} else {
|
||||
if commitError := fs.filer.CommitTransaction(ctx); commitError != nil {
|
||||
releaseMetadataEventStamps(fs.filer, metadataEvents)
|
||||
fs.filer.RollbackTransaction(ctx)
|
||||
return nil, fmt.Errorf("%s/%s move commit error: %v", req.OldDirectory, req.OldName, commitError)
|
||||
}
|
||||
@@ -149,10 +151,12 @@ func (fs *FilerServer) StreamRenameEntry(req *filer_pb.StreamRenameEntryRequest,
|
||||
var pendingRemoteCopies []*pendingRemoteCopy
|
||||
moveErr := fs.moveEntry(ctx, stream, oldParent, oldEntry, newParent, req.NewName, req.Signatures, false, &metadataEvents, &pendingChunkDeletes, &pendingRemoteCopies)
|
||||
if moveErr != nil {
|
||||
releaseMetadataEventStamps(fs.filer, metadataEvents)
|
||||
fs.filer.RollbackTransaction(ctx)
|
||||
return fmt.Errorf("%s/%s move error: %v", req.OldDirectory, req.OldName, moveErr)
|
||||
} else {
|
||||
if commitError := fs.filer.CommitTransaction(ctx); commitError != nil {
|
||||
releaseMetadataEventStamps(fs.filer, metadataEvents)
|
||||
fs.filer.RollbackTransaction(ctx)
|
||||
return fmt.Errorf("%s/%s move commit error: %v", req.OldDirectory, req.OldName, commitError)
|
||||
}
|
||||
@@ -178,6 +182,17 @@ type metadataEvent struct {
|
||||
deleteOldRemote bool
|
||||
}
|
||||
|
||||
// releaseMetadataEventStamps drops the commit stamps queued events would
|
||||
// never adopt when the rename fails — left in flight they pin the delivered
|
||||
// and flushed watermarks below the aborted rename forever.
|
||||
func releaseMetadataEventStamps(f *filer.Filer, events []metadataEvent) {
|
||||
for _, event := range events {
|
||||
if event.newEntry != nil {
|
||||
f.ReleaseEntryCommitTsNs(event.newEntry.CommitTsNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pendingRemoteCopy is a remote-only rename over a remote-only target whose
|
||||
// copy runs after the commit: the store transaction cannot roll a remote
|
||||
// write back, so the new entry keeps the old key's stamp until the copy lands.
|
||||
@@ -320,7 +335,7 @@ func (fs *FilerServer) moveFolderSubEntries(ctx context.Context, stream filer_pb
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.SeaweedFiler_StreamRenameEntryServer, oldParent util.FullPath, entry *filer.Entry, newParent util.FullPath, newName string, moveFolderSubEntries func() error, signatures []int32, skipTargetLookup bool, metadataEvents *[]metadataEvent, pendingChunkDeletes *[]*filer_pb.FileChunk, pendingRemoteCopies *[]*pendingRemoteCopy) error {
|
||||
func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.SeaweedFiler_StreamRenameEntryServer, oldParent util.FullPath, entry *filer.Entry, newParent util.FullPath, newName string, moveFolderSubEntries func() error, signatures []int32, skipTargetLookup bool, metadataEvents *[]metadataEvent, pendingChunkDeletes *[]*filer_pb.FileChunk, pendingRemoteCopies *[]*pendingRemoteCopy) (retErr error) {
|
||||
|
||||
oldPath, newPath := oldParent.Child(entry.Name()), newParent.Child(newName)
|
||||
|
||||
@@ -415,6 +430,13 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee
|
||||
Remote: remoteEntry,
|
||||
Quota: entry.Quota,
|
||||
}
|
||||
defer func() {
|
||||
// On failure no covering event adopts the insert's stamp.
|
||||
if retErr != nil {
|
||||
fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs)
|
||||
}
|
||||
}()
|
||||
|
||||
if deferredCopy {
|
||||
// a pending entry renamed again still reads its original source
|
||||
newEntry.Extended = maps.Clone(newEntry.Extended)
|
||||
@@ -433,7 +455,9 @@ func (fs *FilerServer) moveSelfEntry(ctx context.Context, stream filer_pb.Seawee
|
||||
if newEntry.FullPath.IsLongerFileName(fs.filer.MaxFilenameLength) {
|
||||
return filer_pb.ErrEntryNameTooLong
|
||||
}
|
||||
fs.filer.StampEntryCommitTsNs(newEntry)
|
||||
if createErr := fs.filer.Store.InsertEntryKnownAbsent(filer.WithSuppressedMetadataEvents(ctx), newEntry); createErr != nil {
|
||||
fs.filer.ReleaseEntryCommitTsNs(newEntry.CommitTsNs)
|
||||
return fmt.Errorf("insert entry %s: %v", newEntry.FullPath, createErr)
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -532,3 +532,30 @@ func TestAtomicRenameEntrySkipsDescendantTargetLookups(t *testing.T) {
|
||||
t.Fatalf("event count = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The stamps queued rename events carry are released when the rename fails:
|
||||
// left in flight they would pin the delivered watermark below the aborted
|
||||
// rename forever.
|
||||
func TestAtomicRenameReleasesQueuedStampsOnCommitFailure(t *testing.T) {
|
||||
store := newRenameTestStore()
|
||||
store.entries["/dir"] = newDirectoryEntry("/dir", 100)
|
||||
store.entries["/dir/a.txt"] = newFileEntry("/dir/a.txt", 101)
|
||||
store.entries["/dir/b.txt"] = newFileEntry("/dir/b.txt", 102)
|
||||
store.commitErr = errors.New("commit failed")
|
||||
|
||||
f := newRenameTestFiler(t, store)
|
||||
server := &FilerServer{filer: f, entryLockTable: util.NewLockTable[util.FullPath]()}
|
||||
_, err := server.AtomicRenameEntry(context.Background(), &filer_pb.AtomicRenameEntryRequest{
|
||||
OldDirectory: "/",
|
||||
OldName: "dir",
|
||||
NewDirectory: "/",
|
||||
NewName: "dstdir",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected commit failure")
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
if got := f.LocalDeliveredThroughTsNs(now); got != now {
|
||||
t.Fatalf("LocalDeliveredThroughTsNs = %d, want %d: a leaked stamp still caps the claim", got, now)
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func (fs *FilerServer) TraverseBfsMetadata(req *filer_pb.TraverseBfsMetadataRequ
|
||||
return nil
|
||||
}
|
||||
sendEntry := func(entry *filer.Entry) error {
|
||||
entryTsNs, err := fs.filer.CommitTsNs(ctx, entry.FullPath, entry.Mtime.UnixNano())
|
||||
entryTsNs, err := fs.filer.EntryCommitTsNs(ctx, entry, entry.Mtime.UnixNano())
|
||||
if err != nil {
|
||||
return fmt.Errorf("commit timestamp of %s: %w", entry.FullPath, err)
|
||||
}
|
||||
|
||||
@@ -231,12 +231,30 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
|
||||
continue
|
||||
}
|
||||
|
||||
if (dn == nil && heartbeat.Ip != "") || reportsPriorClusterState(heartbeat, ms.Topo.GetTopologyId(), ms.Topo.GetMaxVolumeId()) {
|
||||
if dn == nil {
|
||||
// An unregistered heartbeat carries no address to admit; under
|
||||
// the pinned single reporter it can never be the embedded one,
|
||||
// so it must not move allocation or topology state either.
|
||||
addr := ""
|
||||
if heartbeat.Ip != "" {
|
||||
addr = util.JoinHostPort(heartbeat.Ip, int(heartbeat.Port))
|
||||
}
|
||||
if !ms.Topo.AdmitVolumeReporter(addr) {
|
||||
err := fmt.Errorf("volume server %s rejected: this master admits a single volume-server reporter", addr)
|
||||
glog.Warningf("SendHeartbeat: %v", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
priorState := reportsPriorClusterState(heartbeat, ms.Topo.GetTopologyId(), ms.Topo.GetMaxVolumeId())
|
||||
if (dn == nil && heartbeat.Ip != "") || priorState {
|
||||
ms.Topo.NoteAllocationEvidence()
|
||||
}
|
||||
ms.Topo.Sequence.SetMax(heartbeat.MaxFileKey)
|
||||
ms.Topo.UpAdjustMaxVolumeId(needle.VolumeId(heartbeat.MaxVolumeIdSeen))
|
||||
if len(heartbeat.Volumes) > 0 {
|
||||
// A HasNoVolumes report still carries the reporter's LastSeenTopologyId;
|
||||
// skipping it would let an EC-only veteran's stale id miss the mismatch
|
||||
// freeze before the hold release below.
|
||||
if len(heartbeat.Volumes) > 0 || heartbeat.HasNoVolumes {
|
||||
ms.Topo.CheckReportedTopologyId(heartbeat.LastSeenTopologyId)
|
||||
}
|
||||
if dn == nil {
|
||||
@@ -356,6 +374,15 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
|
||||
}
|
||||
}
|
||||
|
||||
// A full volume list is the heartbeat section that settles what a
|
||||
// reporter holds; once applied, a post-mint allocation hold kept for
|
||||
// prior cluster state has nothing left to wait for. A report carrying
|
||||
// such state is itself the evidence the hold exists for, so it keeps
|
||||
// the window for other veterans still due.
|
||||
if (len(heartbeat.Volumes) > 0 || heartbeat.HasNoVolumes) && !priorState {
|
||||
ms.Topo.NoteInventoryApplied()
|
||||
}
|
||||
|
||||
if len(heartbeat.NewEcShards) > 0 || len(heartbeat.DeletedEcShards) > 0 {
|
||||
stats.MasterReceivedHeartbeatCounter.WithLabelValues("newEcShards").Inc()
|
||||
// update master internal volume layouts
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/raft"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// admitTestRaftServer answers as leader and swallows Do so a growth freeze
|
||||
// lands its local flag without needing a real raft log.
|
||||
type admitTestRaftServer struct {
|
||||
raft.Server
|
||||
}
|
||||
|
||||
func (admitTestRaftServer) State() string { return raft.Leader }
|
||||
func (admitTestRaftServer) Do(raft.Command) (interface{}, error) { return nil, nil }
|
||||
|
||||
type fakeHeartbeatStream struct {
|
||||
grpc.ServerStream
|
||||
heartbeats []*master_pb.Heartbeat
|
||||
sent []*master_pb.HeartbeatResponse
|
||||
}
|
||||
|
||||
func (s *fakeHeartbeatStream) Recv() (*master_pb.Heartbeat, error) {
|
||||
if len(s.heartbeats) == 0 {
|
||||
return nil, io.EOF
|
||||
}
|
||||
hb := s.heartbeats[0]
|
||||
s.heartbeats = s.heartbeats[1:]
|
||||
return hb, nil
|
||||
}
|
||||
|
||||
func (s *fakeHeartbeatStream) Send(resp *master_pb.HeartbeatResponse) error {
|
||||
s.sent = append(s.sent, resp)
|
||||
return nil
|
||||
}
|
||||
|
||||
// A server the single-reporter admission refuses must not leave any applied
|
||||
// state behind: its stale topology id cannot freeze growth and its seen bound
|
||||
// cannot raise the master's.
|
||||
func TestSendHeartbeatRejectsForeignReporterBeforeApplyingState(t *testing.T) {
|
||||
ms := newLeaderMaster()
|
||||
ms.Topo.RaftServer = admitTestRaftServer{}
|
||||
ms.Topo.SetGrowthFreezeConfig(true, 0)
|
||||
ms.Topo.SetTopologyId("cluster-b")
|
||||
ms.Topo.ReleaseAllocationOnFirstReport("10.0.0.1:8080")
|
||||
|
||||
stream := &fakeHeartbeatStream{heartbeats: []*master_pb.Heartbeat{{
|
||||
Ip: "10.0.0.2",
|
||||
Port: 8080,
|
||||
MaxVolumeIdSeen: 7,
|
||||
LastSeenTopologyId: "cluster-a",
|
||||
Volumes: []*master_pb.VolumeInformationMessage{{Id: 3}},
|
||||
}}}
|
||||
|
||||
err := ms.SendHeartbeat(stream)
|
||||
require.ErrorContains(t, err, "rejected")
|
||||
assert.False(t, ms.Topo.IsGrowthFrozen())
|
||||
assert.Zero(t, uint32(ms.Topo.GetMaxVolumeId()))
|
||||
assert.Empty(t, stream.sent)
|
||||
}
|
||||
|
||||
// The pinned reporter is still subject to the mismatch freeze: admission gates
|
||||
// who may report, not what a legitimate report can do.
|
||||
func TestSendHeartbeatAdmittedReporterStillFreezesOnMismatch(t *testing.T) {
|
||||
ms := newLeaderMaster()
|
||||
ms.Topo.RaftServer = admitTestRaftServer{}
|
||||
ms.Topo.SetGrowthFreezeConfig(true, 0)
|
||||
ms.Topo.SetTopologyId("cluster-b")
|
||||
ms.Topo.ReleaseAllocationOnFirstReport("10.0.0.1:8080")
|
||||
|
||||
stream := &fakeHeartbeatStream{heartbeats: []*master_pb.Heartbeat{{
|
||||
Ip: "10.0.0.1",
|
||||
Port: 8080,
|
||||
MaxVolumeIdSeen: 7,
|
||||
LastSeenTopologyId: "cluster-a",
|
||||
Volumes: []*master_pb.VolumeInformationMessage{{Id: 3}},
|
||||
}}}
|
||||
|
||||
_ = ms.SendHeartbeat(stream)
|
||||
assert.True(t, ms.Topo.IsGrowthFrozen())
|
||||
}
|
||||
|
||||
// An unregistered heartbeat with no address can never be the pinned reporter:
|
||||
// its stale topology id and seen bound must not reach the topology on the way
|
||||
// to the delta-heartbeat skip.
|
||||
func TestSendHeartbeatRejectsAddresslessFirstHeartbeat(t *testing.T) {
|
||||
ms := newLeaderMaster()
|
||||
ms.Topo.RaftServer = admitTestRaftServer{}
|
||||
ms.Topo.SetGrowthFreezeConfig(true, 0)
|
||||
ms.Topo.SetTopologyId("cluster-b")
|
||||
ms.Topo.ReleaseAllocationOnFirstReport("10.0.0.1:8080")
|
||||
|
||||
stream := &fakeHeartbeatStream{heartbeats: []*master_pb.Heartbeat{{
|
||||
MaxVolumeIdSeen: 7,
|
||||
LastSeenTopologyId: "cluster-a",
|
||||
Volumes: []*master_pb.VolumeInformationMessage{{Id: 3}},
|
||||
}}}
|
||||
|
||||
err := ms.SendHeartbeat(stream)
|
||||
require.ErrorContains(t, err, "rejected")
|
||||
assert.False(t, ms.Topo.IsGrowthFrozen())
|
||||
assert.Zero(t, uint32(ms.Topo.GetMaxVolumeId()))
|
||||
assert.Empty(t, stream.sent)
|
||||
}
|
||||
@@ -70,6 +70,13 @@ type MasterOption struct {
|
||||
TelemetryUrl string
|
||||
TelemetryEnabled bool
|
||||
VolumeGrowthDisabled bool
|
||||
// ReleaseAllocOnFirstReport lifts the post-mint allocation hold as soon as
|
||||
// one full volume-server inventory has been applied, for setups whose
|
||||
// embedded volume server is the only possible reporter (weed mini).
|
||||
// SingleVolumeReporter pins that reporter's ip:port; any other volume
|
||||
// server trying to register is rejected.
|
||||
ReleaseAllocOnFirstReport bool
|
||||
SingleVolumeReporter string
|
||||
}
|
||||
|
||||
type MasterServer struct {
|
||||
@@ -182,6 +189,9 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
|
||||
ms.Topo.SetAllocationDeferral(d)
|
||||
}
|
||||
}
|
||||
if option.ReleaseAllocOnFirstReport {
|
||||
ms.Topo.ReleaseAllocationOnFirstReport(option.SingleVolumeReporter)
|
||||
}
|
||||
ms.Topo.QuarantineVolumeFn = func(dn *topology.DataNode, vid needle.VolumeId, readOnly bool) error {
|
||||
err := operation.WithVolumeServerClient(false, dn.ServerAddress(), ms.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
@@ -64,17 +65,28 @@ func (vs *VolumeServer) proxyReqToTargetServer(w http.ResponseWriter, r *http.Re
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
lookupResult, err := operation.LookupVolumeId(vs.GetMaster, vs.grpcDialOption, volumeId.String())
|
||||
if err != nil || len(lookupResult.Locations) <= 0 {
|
||||
lookupResult, err := operation.LookupVolumeIdWithContext(r.Context(), vs.GetMaster, vs.grpcDialOption, volumeId.String())
|
||||
if err != nil && vs.ReadMode == "proxy" {
|
||||
if r.Context().Err() != nil {
|
||||
return
|
||||
}
|
||||
glog.V(0).InfofCtx(r.Context(), "lookup error: %v %s", err, r.URL.Path)
|
||||
InternalError(w, r, nil)
|
||||
return
|
||||
}
|
||||
if err != nil || lookupResult == nil || len(lookupResult.Locations) <= 0 {
|
||||
glog.V(0).Infoln("lookup error:", err, r.URL.Path)
|
||||
stats.VolumeServerFileReadInvalidNeedles.Inc()
|
||||
NotFound(w)
|
||||
return
|
||||
}
|
||||
if len(lookupResult.Locations) >= 2 {
|
||||
rand.Shuffle(len(lookupResult.Locations), func(i, j int) {
|
||||
lookupResult.Locations[i], lookupResult.Locations[j] = lookupResult.Locations[j], lookupResult.Locations[i]
|
||||
// cached locations are shared between lookups, so shuffle a copy
|
||||
locations := slices.Clone(lookupResult.Locations)
|
||||
rand.Shuffle(len(locations), func(i, j int) {
|
||||
locations[i], locations[j] = locations[j], locations[i]
|
||||
})
|
||||
lookupResult.Locations = locations
|
||||
}
|
||||
var targetUrl *url.URL
|
||||
location := fmt.Sprintf("%s:%d", vs.store.Ip, vs.store.Port)
|
||||
@@ -100,13 +112,30 @@ func (vs *VolumeServer) proxyReqToTargetServer(w http.ResponseWriter, r *http.Re
|
||||
query := r.URL.Query()
|
||||
query.Set(reqIsProxied, "true")
|
||||
r.URL.RawQuery = query.Encode()
|
||||
request, err := http.NewRequest(http.MethodGet, r.URL.String(), nil)
|
||||
request, err := http.NewRequestWithContext(r.Context(), r.Method, r.URL.String(), nil)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("failed to instance http request of url %s: %v", redactedURL(r), err)
|
||||
InternalError(w, r, nil)
|
||||
return
|
||||
}
|
||||
// hop-by-hop headers describe this hop, not the replica's; Connection
|
||||
// also nominates per-request fields to drop (RFC 9110 7.6.1)
|
||||
hopByHop := map[string]bool{
|
||||
"Connection": true, "Keep-Alive": true, "Te": true, "Trailer": true,
|
||||
"Upgrade": true, "Host": true, "Content-Length": true, "Transfer-Encoding": true,
|
||||
"Proxy-Connection": true, "Proxy-Authenticate": true, "Proxy-Authorization": true,
|
||||
}
|
||||
for _, v := range r.Header.Values("Connection") {
|
||||
for _, token := range strings.Split(v, ",") {
|
||||
if name := http.CanonicalHeaderKey(strings.TrimSpace(token)); name != "" {
|
||||
hopByHop[name] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, vv := range r.Header {
|
||||
if hopByHop[http.CanonicalHeaderKey(k)] {
|
||||
continue
|
||||
}
|
||||
for _, v := range vv {
|
||||
request.Header.Add(k, v)
|
||||
}
|
||||
@@ -114,6 +143,9 @@ func (vs *VolumeServer) proxyReqToTargetServer(w http.ResponseWriter, r *http.Re
|
||||
|
||||
response, err := util_http.GetGlobalHttpClient().Do(request)
|
||||
if err != nil {
|
||||
if r.Context().Err() != nil {
|
||||
return
|
||||
}
|
||||
stats.VolumeServerHandlerCounter.WithLabelValues(stats.FailedReadProxyReq).Inc()
|
||||
glog.V(0).Infof("request remote url %s: %v", redactedURL(r), err)
|
||||
InternalError(w, r, nil)
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestInternalErrorWritesTheReadError(t *testing.T) {
|
||||
@@ -96,3 +109,296 @@ func TestNotModifiedChecksIfNoneMatchFirst(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type proxyTestMaster struct {
|
||||
master_pb.UnimplementedSeaweedServer
|
||||
lookup func(context.Context, *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error)
|
||||
}
|
||||
|
||||
func (m *proxyTestMaster) LookupVolume(ctx context.Context, req *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
|
||||
return m.lookup(ctx, req)
|
||||
}
|
||||
|
||||
func newProxyTestHTTPServer(t *testing.T, handler http.Handler) *httptest.Server {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &httptest.Server{Listener: listener, Config: &http.Server{Handler: handler}}
|
||||
server.Start()
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
type proxyTestResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
statusWritten chan struct{}
|
||||
}
|
||||
|
||||
func (w proxyTestResponseWriter) WriteHeader(status int) {
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
w.statusWritten <- struct{}{}
|
||||
}
|
||||
|
||||
func newProxyTestVolumeServer(t *testing.T, volumeID string, locations []*master_pb.Location, lookupErr error) *VolumeServer {
|
||||
t.Helper()
|
||||
operation.InvalidateVolumeIdLocationCache(volumeID)
|
||||
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
masterAddress := pb.NewServerAddress("127.0.0.1", 9333, listener.Addr().(*net.TCPAddr).Port)
|
||||
masterServer := grpc.NewServer()
|
||||
master_pb.RegisterSeaweedServer(masterServer, &proxyTestMaster{lookup: func(_ context.Context, req *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
|
||||
if lookupErr != nil {
|
||||
return nil, lookupErr
|
||||
}
|
||||
if len(req.VolumeOrFileIds) == 0 {
|
||||
return nil, errors.New("lookup request contains no volume IDs")
|
||||
}
|
||||
return &master_pb.LookupVolumeResponse{VolumeIdLocations: []*master_pb.LookupVolumeResponse_VolumeIdLocation{{
|
||||
VolumeOrFileId: req.VolumeOrFileIds[0],
|
||||
Locations: locations,
|
||||
}}}, nil
|
||||
}})
|
||||
go func() {
|
||||
_ = masterServer.Serve(listener)
|
||||
}()
|
||||
|
||||
vs := &VolumeServer{
|
||||
store: &storage.Store{Ip: "192.0.2.10", Port: 8080},
|
||||
ReadMode: "proxy",
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
vs.setCurrentMaster(masterAddress)
|
||||
t.Cleanup(func() {
|
||||
operation.InvalidateVolumeIdLocationCache(volumeID)
|
||||
pb.InvalidateGrpcConnection(masterAddress.ToGrpcAddress())
|
||||
masterServer.Stop()
|
||||
})
|
||||
return vs
|
||||
}
|
||||
|
||||
func TestProxyReqToTargetServerPreservesMethodAndResponse(t *testing.T) {
|
||||
const volumeID = "849300101"
|
||||
type observedRequest struct {
|
||||
method string
|
||||
rangeHeader string
|
||||
ifNoneMatch string
|
||||
ifModifiedAt string
|
||||
header http.Header
|
||||
}
|
||||
observed := make(chan observedRequest, 2)
|
||||
peer := newProxyTestHTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
observed <- observedRequest{
|
||||
method: r.Method,
|
||||
rangeHeader: r.Header.Get("Range"),
|
||||
ifNoneMatch: r.Header.Get("If-None-Match"),
|
||||
ifModifiedAt: r.Header.Get("If-Modified-Since"),
|
||||
header: r.Header.Clone(),
|
||||
}
|
||||
w.Header().Set("ETag", `"peer-etag"`)
|
||||
w.Header().Set("Content-Range", "bytes 0-3/10")
|
||||
w.Header().Set("X-Peer-Header", "preserved")
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = io.WriteString(w, "data")
|
||||
}))
|
||||
|
||||
remoteAddress := strings.TrimPrefix(peer.URL, "http://")
|
||||
vs := newProxyTestVolumeServer(t, volumeID, []*master_pb.Location{{Url: remoteAddress}}, nil)
|
||||
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
t.Run(method, func(t *testing.T) {
|
||||
r := httptest.NewRequest(method, "/"+volumeID+",abcdef", nil)
|
||||
r.Header.Set("Range", "bytes=0-3")
|
||||
r.Header.Set("If-None-Match", `"client-etag"`)
|
||||
r.Header.Set("If-Modified-Since", "Wed, 21 Oct 2015 07:28:00 GMT")
|
||||
r.Header.Set("Connection", "keep-alive, X-Hop-Marker")
|
||||
r.Header.Set("Keep-Alive", "timeout=5")
|
||||
r.Header.Set("Upgrade", "h2c")
|
||||
r.Header.Set("Te", "trailers")
|
||||
r.Header.Set("X-Hop-Marker", "private")
|
||||
r.Header.Set("Proxy-Connection", "keep-alive")
|
||||
r.Header.Set("Proxy-Authorization", "Basic cHJveHk6c2VjcmV0")
|
||||
w := httptest.NewRecorder()
|
||||
vs.proxyReqToTargetServer(w, r)
|
||||
|
||||
var got observedRequest
|
||||
select {
|
||||
case got = <-observed:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("peer did not receive the proxied request; proxy status %d", w.Code)
|
||||
}
|
||||
if got.method != method {
|
||||
t.Errorf("peer received method %q, want %q", got.method, method)
|
||||
}
|
||||
if got.rangeHeader != "bytes=0-3" || got.ifNoneMatch != `"client-etag"` || got.ifModifiedAt != "Wed, 21 Oct 2015 07:28:00 GMT" {
|
||||
t.Errorf("peer received conditional/range headers %+v", got)
|
||||
}
|
||||
for _, dropped := range []string{"Connection", "Keep-Alive", "Upgrade", "Te", "X-Hop-Marker", "Proxy-Connection", "Proxy-Authorization"} {
|
||||
if got.header.Get(dropped) != "" {
|
||||
t.Errorf("hop-by-hop header %s reached the replica: %v", dropped, got.header)
|
||||
}
|
||||
}
|
||||
if w.Code != http.StatusPartialContent {
|
||||
t.Errorf("status %d, want %d", w.Code, http.StatusPartialContent)
|
||||
}
|
||||
if w.Header().Get("ETag") != `"peer-etag"` || w.Header().Get("Content-Range") != "bytes 0-3/10" || w.Header().Get("X-Peer-Header") != "preserved" {
|
||||
t.Errorf("peer response headers were not preserved: %v", w.Header())
|
||||
}
|
||||
wantBody := "data"
|
||||
if method == http.MethodHead {
|
||||
wantBody = ""
|
||||
}
|
||||
if gotBody := w.Body.String(); gotBody != wantBody {
|
||||
t.Errorf("response body %q, want %q", gotBody, wantBody)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyReqToTargetServerCancelsUpstreamWithInboundRequest(t *testing.T) {
|
||||
const volumeID = "849300102"
|
||||
peerStarted := make(chan struct{})
|
||||
peerCanceled := make(chan struct{})
|
||||
releasePeer := make(chan struct{})
|
||||
var releasePeerOnce sync.Once
|
||||
peer := newProxyTestHTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
close(peerStarted)
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
close(peerCanceled)
|
||||
case <-releasePeer:
|
||||
}
|
||||
}))
|
||||
defer releasePeerOnce.Do(func() { close(releasePeer) })
|
||||
|
||||
remoteAddress := strings.TrimPrefix(peer.URL, "http://")
|
||||
vs := newProxyTestVolumeServer(t, volumeID, []*master_pb.Location{{Url: remoteAddress}}, nil)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
r := httptest.NewRequest(http.MethodGet, "/"+volumeID+",abcdef", nil).WithContext(ctx)
|
||||
w := httptest.NewRecorder()
|
||||
proxyDone := make(chan struct{})
|
||||
go func() {
|
||||
vs.proxyReqToTargetServer(w, r)
|
||||
close(proxyDone)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-peerStarted:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("peer did not receive the proxied request")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-peerCanceled:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("canceling the inbound request did not cancel the peer request")
|
||||
}
|
||||
releasePeerOnce.Do(func() { close(releasePeer) })
|
||||
select {
|
||||
case <-proxyDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Error("proxy handler did not finish after inbound cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyReqToTargetServerCancelsUpstreamBodyReadWithInboundRequest(t *testing.T) {
|
||||
const volumeID = "849300106"
|
||||
peerCanceled := make(chan struct{})
|
||||
releasePeer := make(chan struct{})
|
||||
var releasePeerOnce sync.Once
|
||||
peer := newProxyTestHTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
close(peerCanceled)
|
||||
case <-releasePeer:
|
||||
}
|
||||
}))
|
||||
defer releasePeerOnce.Do(func() { close(releasePeer) })
|
||||
|
||||
remoteAddress := strings.TrimPrefix(peer.URL, "http://")
|
||||
vs := newProxyTestVolumeServer(t, volumeID, []*master_pb.Location{{Url: remoteAddress}}, nil)
|
||||
r := httptest.NewRequest(http.MethodGet, "/"+volumeID+",abcdef", nil)
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
r = r.WithContext(ctx)
|
||||
recorder := httptest.NewRecorder()
|
||||
statusWritten := make(chan struct{}, 1)
|
||||
w := proxyTestResponseWriter{ResponseWriter: recorder, statusWritten: statusWritten}
|
||||
proxyDone := make(chan struct{})
|
||||
go func() {
|
||||
vs.proxyReqToTargetServer(w, r)
|
||||
close(proxyDone)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-statusWritten:
|
||||
case <-time.After(2 * time.Second):
|
||||
cancel()
|
||||
t.Fatal("proxy did not receive the peer response headers")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-peerCanceled:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("canceling the inbound request did not cancel the peer response body")
|
||||
}
|
||||
releasePeerOnce.Do(func() { close(releasePeer) })
|
||||
select {
|
||||
case <-proxyDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Error("proxy handler did not finish reading after inbound cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyReqToTargetServerDistinguishesLookupFailureFromNoLocation(t *testing.T) {
|
||||
t.Run("cancelled request skips the lookup error response", func(t *testing.T) {
|
||||
const volumeID = "849300107"
|
||||
vs := newProxyTestVolumeServer(t, volumeID, nil, nil)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
w := httptest.NewRecorder()
|
||||
vs.proxyReqToTargetServer(w, httptest.NewRequest(http.MethodGet, "/"+volumeID+",abcdef", nil).WithContext(ctx))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("status %d, want no response written for a cancelled request", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("master lookup failure is internal error", func(t *testing.T) {
|
||||
const volumeID = "849300103"
|
||||
vs := newProxyTestVolumeServer(t, volumeID, nil, status.Error(codes.Unavailable, "master unavailable"))
|
||||
w := httptest.NewRecorder()
|
||||
vs.proxyReqToTargetServer(w, httptest.NewRequest(http.MethodGet, "/"+volumeID+",abcdef", nil))
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("status %d, want %d", w.Code, http.StatusInternalServerError)
|
||||
}
|
||||
})
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
locations []*master_pb.Location
|
||||
}{
|
||||
{name: "lookup returned no replica locations"},
|
||||
{name: "only local replica is not a usable proxy target", locations: []*master_pb.Location{{Url: "192.0.2.10:8080"}}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
volumeID := "84930010"
|
||||
if tc.name == "lookup returned no replica locations" {
|
||||
volumeID += "4"
|
||||
} else {
|
||||
volumeID += "5"
|
||||
}
|
||||
vs := newProxyTestVolumeServer(t, volumeID, tc.locations, nil)
|
||||
w := httptest.NewRecorder()
|
||||
vs.proxyReqToTargetServer(w, httptest.NewRequest(http.MethodGet, "/"+volumeID+",abcdef", nil))
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -191,3 +191,61 @@ func TestAllocationDeferralDuration(t *testing.T) {
|
||||
t.Fatalf("negative deferral should restore the default, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllocationDeferralReleasedByInventory(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
topo.ReleaseAllocationOnFirstReport()
|
||||
|
||||
topo.DeferAllocation(time.Minute)
|
||||
topo.NoteInventoryApplied()
|
||||
if wait := topo.allocationDelay(); wait > 0 {
|
||||
t.Fatalf("applied inventory should lift the deferral, still waiting %v", wait)
|
||||
}
|
||||
|
||||
fresh := NewTopology("topo", nil, 128, 3, false)
|
||||
fresh.ReleaseAllocationOnFirstReport()
|
||||
fresh.NoteInventoryApplied()
|
||||
fresh.DeferAllocation(time.Minute)
|
||||
if wait := fresh.allocationDelay(); wait > 0 {
|
||||
t.Fatalf("a report applied before the mint should keep the hold unarmed, got %v", wait)
|
||||
}
|
||||
|
||||
walled := NewTopology("topo", nil, 128, 3, false)
|
||||
walled.DeferAllocation(time.Minute)
|
||||
walled.NoteInventoryApplied()
|
||||
if wait := walled.allocationDelay(); wait <= 0 {
|
||||
t.Fatal("without opt-in an applied inventory must not lift the deferral")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueuedTopologyReportFreezesBeforeGateOpens(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
topo.SetGrowthFreezeConfig(true, 0)
|
||||
topo.SetTopologyInitPending(true)
|
||||
|
||||
// A report arriving while the id is still being minted is stashed.
|
||||
topo.CheckReportedTopologyId("cluster-a")
|
||||
topo.SetTopologyId("cluster-b")
|
||||
|
||||
topo.SetTopologyInitPending(false)
|
||||
if topo.topologyInitPending.Load() {
|
||||
t.Fatal("init gate should be open after pending=false")
|
||||
}
|
||||
if !topo.IsGrowthFrozen() {
|
||||
t.Fatal("a stashed mismatch must freeze growth before the gate opens")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSingleReporterAdmission(t *testing.T) {
|
||||
topo := NewTopology("topo", nil, 128, 3, false)
|
||||
if !topo.AdmitVolumeReporter("10.0.0.1:8080") {
|
||||
t.Fatal("without opt-in any reporter is admitted")
|
||||
}
|
||||
topo.ReleaseAllocationOnFirstReport("10.0.0.1:8080")
|
||||
if !topo.AdmitVolumeReporter("10.0.0.1:8080") {
|
||||
t.Fatal("the pinned reporter should be admitted")
|
||||
}
|
||||
if topo.AdmitVolumeReporter("10.0.0.2:8080") {
|
||||
t.Fatal("a foreign reporter should be refused")
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,15 @@ type Topology struct {
|
||||
allocationDeferral atomic.Int64
|
||||
topologyInitPending atomic.Bool
|
||||
|
||||
// releaseAllocOnReport lifts a post-mint allocation hold as soon as a full
|
||||
// volume-server inventory has been applied, for single-reporter setups
|
||||
// (weed mini) whose embedded volume server is the only possible source of
|
||||
// prior cluster state. inventoryApplied records that at least one full
|
||||
// volume list has been synced into this topology.
|
||||
releaseAllocOnReport atomic.Bool
|
||||
inventoryApplied atomic.Bool
|
||||
singleReporter atomic.Value // string
|
||||
|
||||
reportedTopologyIdsLock sync.Mutex
|
||||
pendingReportedTopologyIds map[string]struct{}
|
||||
|
||||
@@ -1477,17 +1486,25 @@ func (t *Topology) CheckReportedTopologyId(reported string) {
|
||||
if reported == "" || !t.freezeOnMismatch.Load() {
|
||||
return
|
||||
}
|
||||
t.reportedTopologyIdsLock.Lock()
|
||||
defer t.reportedTopologyIdsLock.Unlock()
|
||||
t.checkReportedTopologyIdLocked(reported)
|
||||
}
|
||||
|
||||
// checkReportedTopologyIdLocked runs the mismatch check inside
|
||||
// reportedTopologyIdsLock, the same critical section the init gate drains
|
||||
// under: a report received before the gate opens is either stashed or frozen
|
||||
// before the gate can release.
|
||||
func (t *Topology) checkReportedTopologyIdLocked(reported string) {
|
||||
own := t.GetTopologyId()
|
||||
if own == "" {
|
||||
// The local topology id is still being minted. Keep the report so a
|
||||
// later heartbeat echo cannot erase the mismatch on the server side
|
||||
// before the freeze check ever ran.
|
||||
t.reportedTopologyIdsLock.Lock()
|
||||
if t.pendingReportedTopologyIds == nil {
|
||||
t.pendingReportedTopologyIds = make(map[string]struct{})
|
||||
}
|
||||
t.pendingReportedTopologyIds[reported] = struct{}{}
|
||||
t.reportedTopologyIdsLock.Unlock()
|
||||
return
|
||||
}
|
||||
if reported == own {
|
||||
@@ -1568,17 +1585,58 @@ func (t *Topology) applyGrowthFreeze(frozen bool) {
|
||||
|
||||
// SetTopologyInitPending gates allocation while a topology id is being
|
||||
// minted, so growth cannot slip in before the warmup window is installed.
|
||||
// Stashed reports are applied while the gate is still closed: clearing it
|
||||
// first would let an allocation through before a queued mismatch freezes
|
||||
// growth.
|
||||
func (t *Topology) SetTopologyInitPending(pending bool) {
|
||||
t.topologyInitPending.Store(pending)
|
||||
if pending {
|
||||
t.topologyInitPending.Store(true)
|
||||
return
|
||||
}
|
||||
// The stash is drained and the gate released inside one critical section:
|
||||
// a mismatching report checked here, or still in flight under the same
|
||||
// lock, lands its freeze before any allocation can observe the open gate.
|
||||
t.reportedTopologyIdsLock.Lock()
|
||||
defer t.reportedTopologyIdsLock.Unlock()
|
||||
reported := t.pendingReportedTopologyIds
|
||||
t.pendingReportedTopologyIds = nil
|
||||
t.reportedTopologyIdsLock.Unlock()
|
||||
for id := range reported {
|
||||
t.CheckReportedTopologyId(id)
|
||||
t.checkReportedTopologyIdLocked(id)
|
||||
}
|
||||
t.topologyInitPending.Store(false)
|
||||
}
|
||||
|
||||
// ReleaseAllocationOnFirstReport opts the topology into lifting the post-mint
|
||||
// allocation hold once one full volume-server inventory has been applied, and
|
||||
// pins the admitted volume-server reporter: the early release is only sound
|
||||
// when a single embedded server (weed mini) can carry prior cluster state, so
|
||||
// every other reporter must be refused rather than silently trusted.
|
||||
func (t *Topology) ReleaseAllocationOnFirstReport(onlyReporter ...string) {
|
||||
if len(onlyReporter) > 0 {
|
||||
t.singleReporter.Store(onlyReporter[0])
|
||||
}
|
||||
t.releaseAllocOnReport.Store(true)
|
||||
}
|
||||
|
||||
// AdmitVolumeReporter enforces the single-reporter restriction the early
|
||||
// release relies on: a late-arriving foreign server would carry cluster state
|
||||
// the dropped hold was meant to wait for.
|
||||
func (t *Topology) AdmitVolumeReporter(addr string) bool {
|
||||
if !t.releaseAllocOnReport.Load() {
|
||||
return true
|
||||
}
|
||||
expected, _ := t.singleReporter.Load().(string)
|
||||
return expected == "" || expected == addr
|
||||
}
|
||||
|
||||
// NoteInventoryApplied marks a heartbeat's full volume list as applied to this
|
||||
// topology. Under ReleaseAllocationOnFirstReport it also lifts the post-mint
|
||||
// allocation hold: the bound raise and topology-id freeze checks run while the
|
||||
// heartbeat is processed, so nothing protected remains pending afterwards.
|
||||
func (t *Topology) NoteInventoryApplied() {
|
||||
t.inventoryApplied.Store(true)
|
||||
if t.releaseAllocOnReport.Load() {
|
||||
t.allocationNotBefore.Store(0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1586,9 +1644,19 @@ func (t *Topology) SetTopologyInitPending(pending bool) {
|
||||
// mints a fresh topology id: on a rebuilt master that window gives veteran
|
||||
// servers a pulse to raise the bound or trip the freeze.
|
||||
func (t *Topology) DeferAllocation(d time.Duration) {
|
||||
// Under release-on-report a hold is pointless once inventory has landed:
|
||||
// the veteran heartbeat that mattered has already been applied.
|
||||
if t.releaseAllocOnReport.Load() && t.inventoryApplied.Load() {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
t.allocationNotBefore.Store(now.Add(d).UnixNano())
|
||||
t.allocationEvidenceSince.Store(now.UnixNano())
|
||||
// Close the race with a report applied between the check above and the
|
||||
// store, which would otherwise leave the full window armed.
|
||||
if t.releaseAllocOnReport.Load() && t.inventoryApplied.Load() {
|
||||
t.allocationNotBefore.Store(0)
|
||||
}
|
||||
}
|
||||
|
||||
// NoteAllocationEvidence records a heartbeat signal that could still carry
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(50)
|
||||
MINOR_VERSION = int32(51)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
Reference in new issue
Block a user