mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-26 22:27:05 +01:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65685ee915 | ||
|
|
60c23ae5e0 | ||
|
|
acc1075fd5 | ||
|
|
cbbc9e6efe | ||
|
|
70bbd27638 | ||
|
|
630dc8aee1 | ||
|
|
ca4e1c76d8 | ||
|
|
d9236a9c7f | ||
|
|
9cc1f0dc36 | ||
|
|
9ded580993 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.51"
|
||||
appVersion: "4.50"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.51.0
|
||||
version: 4.50.0
|
||||
@@ -166,10 +166,6 @@ 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
|
||||
@@ -285,7 +281,6 @@ 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
|
||||
@@ -314,7 +309,6 @@ 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)
|
||||
}
|
||||
@@ -329,7 +323,6 @@ 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
|
||||
@@ -358,7 +351,6 @@ 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
|
||||
@@ -396,8 +388,6 @@ 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 {
|
||||
@@ -487,7 +477,6 @@ 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;
|
||||
@@ -525,7 +514,6 @@ 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 {
|
||||
@@ -585,9 +573,6 @@ 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 {
|
||||
@@ -724,10 +709,6 @@ 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 {
|
||||
|
||||
Generated
-1
@@ -4601,7 +4601,6 @@ dependencies = [
|
||||
"futures",
|
||||
"hex",
|
||||
"http-body 1.0.1",
|
||||
"httpdate",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"image",
|
||||
|
||||
@@ -51,7 +51,6 @@ prost-types = "0.14"
|
||||
# HTTP server
|
||||
axum = { version = "0.8", features = ["multipart"] }
|
||||
http-body = "1"
|
||||
httpdate = "1"
|
||||
hyper = { version = "1", features = ["full"] }
|
||||
hyper-util = { version = "0.1", features = ["tokio", "service", "server-auto", "http1", "http2"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
||||
@@ -1120,10 +1120,6 @@ async fn get_or_head_handler_inner(
|
||||
};
|
||||
|
||||
let (etag, last_modified_str) = etag_and_last_modified(&n);
|
||||
// A Range whose If-Range no longer matches is ignored and the whole
|
||||
// content is sent, so a resumed download restarts instead of mixing
|
||||
// two versions.
|
||||
let range = range.filter(|_| if_range_matches(&headers, &etag, &last_modified_str));
|
||||
if let Some(resp) = not_modified_response(&n, &headers, &etag, &last_modified_str) {
|
||||
// A request that ends here was answered by the meta read alone.
|
||||
if let Some(io_errors) = strategy.io_errors() {
|
||||
@@ -1171,20 +1167,14 @@ async fn get_or_head_handler_inner(
|
||||
return head_from_meta_response(&info, response_headers);
|
||||
}
|
||||
ReadStrategy::RangeFromSource(info) => {
|
||||
return match range.as_deref() {
|
||||
Some(range) => {
|
||||
range_from_source_response(
|
||||
&state,
|
||||
range,
|
||||
info,
|
||||
response_headers,
|
||||
track_download,
|
||||
)
|
||||
.await
|
||||
}
|
||||
// If-Range dropped the range; serve the whole content.
|
||||
None => stream_response(&state, info, response_headers, track_download),
|
||||
};
|
||||
return range_from_source_response(
|
||||
&state,
|
||||
range.as_deref().unwrap_or_default(),
|
||||
info,
|
||||
response_headers,
|
||||
track_download,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
ReadStrategy::Buffered => {}
|
||||
}
|
||||
@@ -1567,31 +1557,6 @@ fn not_modified_response(
|
||||
None
|
||||
}
|
||||
|
||||
/// If-Range (RFC 9110 13.1.5): an entity-tag by strong comparison, or a date
|
||||
/// equal to Last-Modified. The response etag here is always a strong tag.
|
||||
fn if_range_matches(headers: &HeaderMap, etag: &str, last_modified_str: &Option<String>) -> bool {
|
||||
let Some(raw) = headers.get(header::IF_RANGE) else {
|
||||
return true;
|
||||
};
|
||||
let Ok(if_range) = raw.to_str() else {
|
||||
return false;
|
||||
};
|
||||
let if_range = if_range.trim();
|
||||
if if_range.is_empty() {
|
||||
return true;
|
||||
}
|
||||
if if_range.starts_with('"') || if_range.starts_with("W/") {
|
||||
return if_range == etag;
|
||||
}
|
||||
let Ok(date) = httpdate::parse_http_date(if_range) else {
|
||||
return false;
|
||||
};
|
||||
last_modified_str
|
||||
.as_deref()
|
||||
.and_then(|lm| httpdate::parse_http_date(lm).ok())
|
||||
.is_some_and(|lm| date == lm)
|
||||
}
|
||||
|
||||
/// Weak comparison against "*" or a comma-separated entity-tag list (RFC 9110 13.1.2).
|
||||
fn etag_list_matches(header: &str, etag: &str) -> bool {
|
||||
if header.trim() == "*" {
|
||||
@@ -5802,53 +5767,6 @@ mod tests {
|
||||
assert!(resp.headers().contains_key(header::LAST_MODIFIED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_if_range_matches() {
|
||||
let etag = "\"v2\"".to_string();
|
||||
let last_modified_str = Some("Sat, 24 Oct 2026 22:01:04 GMT".to_string());
|
||||
let cases: Vec<(Option<&str>, bool)> = vec![
|
||||
(None, true),
|
||||
(Some("\"v2\""), true),
|
||||
(Some("Sat, 24 Oct 2026 22:01:04 GMT"), true),
|
||||
(Some("Saturday, 24-Oct-26 22:01:04 GMT"), true),
|
||||
(Some("Sat Oct 24 22:01:04 2026"), true),
|
||||
(Some("\"v1\""), false),
|
||||
(Some("W/\"v2\""), false),
|
||||
(Some("Sat, 24 Oct 2026 22:01:03 GMT"), false),
|
||||
(Some("not a date"), false),
|
||||
];
|
||||
for (if_range, want) in cases {
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Some(v) = if_range {
|
||||
headers.insert(header::IF_RANGE, v.parse().unwrap());
|
||||
}
|
||||
assert_eq!(
|
||||
if_range_matches(&headers, &etag, &last_modified_str),
|
||||
want,
|
||||
"{if_range:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// A present value that is not valid UTF-8 fails the condition.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::IF_RANGE,
|
||||
header::HeaderValue::from_bytes(b"\"\xff\xfev2\"").unwrap(),
|
||||
);
|
||||
assert!(!if_range_matches(&headers, &etag, &last_modified_str));
|
||||
|
||||
// No Last-Modified on the representation: a date validator fails,
|
||||
// an entity-tag still applies.
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(header::IF_RANGE, "\"v2\"".parse().unwrap());
|
||||
assert!(if_range_matches(&headers, &etag, &None));
|
||||
headers.insert(
|
||||
header::IF_RANGE,
|
||||
"Sat, 24 Oct 2026 22:01:04 GMT".parse().unwrap(),
|
||||
);
|
||||
assert!(!if_range_matches(&headers, &etag, &None));
|
||||
}
|
||||
|
||||
/// A GET whose needle read is parked must not hold the store lock: a
|
||||
/// writer, here a real append to the same volume, must get through.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
@@ -34,7 +34,6 @@ struct ListTablesResponse {
|
||||
pub struct NamespaceClient {
|
||||
base_url: String,
|
||||
http: reqwest::Client,
|
||||
api_key: Option<String>,
|
||||
}
|
||||
|
||||
/// A namespace call that has not answered by now is not going to. Without this
|
||||
@@ -42,23 +41,12 @@ pub struct NamespaceClient {
|
||||
/// slot open forever, and the sweep never finishes.
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_REDIRECT_HOPS: usize = 10;
|
||||
|
||||
impl NamespaceClient {
|
||||
pub fn new(base_url: impl Into<String>) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
// reqwest forwards custom headers on a follow, so only a same-origin
|
||||
// hop is allowed: anywhere else would carry x-api-key to a listener
|
||||
// the credential was never meant for.
|
||||
.redirect(reqwest::redirect::Policy::custom(|attempt| {
|
||||
if may_follow(attempt.previous(), attempt.url()) {
|
||||
attempt.follow()
|
||||
} else {
|
||||
attempt.stop()
|
||||
}
|
||||
}))
|
||||
.build()
|
||||
// The builder only fails on a bad TLS backend, which would break
|
||||
// every call anyway; a client with no timeouts is worse than a panic
|
||||
@@ -70,32 +58,6 @@ impl NamespaceClient {
|
||||
Self {
|
||||
base_url: base_url.into().trim_end_matches('/').to_string(),
|
||||
http,
|
||||
api_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The catalog accepts an S3 credential as `x-api-key`; where the worker
|
||||
/// already holds one for storage it authenticates the namespace calls too.
|
||||
pub fn with_fallback(mut self, fallback: &crate::dataset::FallbackOptions) -> Self {
|
||||
if let (Some(access), Some(secret)) = (
|
||||
fallback.get("aws_access_key_id"),
|
||||
fallback.get("aws_secret_access_key"),
|
||||
) {
|
||||
if !protected_transport(&self.base_url) {
|
||||
tracing::warn!(
|
||||
"catalog url {} exposes the x-api-key credential in cleartext",
|
||||
self.base_url
|
||||
);
|
||||
}
|
||||
self.api_key = Some(format!("{access}:{secret}"));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn authed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
||||
match &self.api_key {
|
||||
Some(key) => request.header("x-api-key", key),
|
||||
None => request,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +65,8 @@ impl NamespaceClient {
|
||||
pub async fn list_all_tables(&self) -> Result<Vec<String>> {
|
||||
let url = format!("{}/v1/table", self.base_url);
|
||||
let response: ListTablesResponse = self
|
||||
.authed(self.http.get(&url))
|
||||
.http
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.context("list tables")?
|
||||
@@ -117,7 +80,8 @@ impl NamespaceClient {
|
||||
pub async fn list_namespaces(&self, id: &[String]) -> Result<Vec<String>> {
|
||||
let url = format!("{}/v1/namespace/{}/list", self.base_url, encode_id(id));
|
||||
let response: ListNamespacesResponse = self
|
||||
.authed(self.http.get(&url))
|
||||
.http
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.context("list namespaces")?
|
||||
@@ -134,7 +98,8 @@ impl NamespaceClient {
|
||||
let url = format!("{}/v1/table/{}/describe", self.base_url, encode_id(id));
|
||||
let body = serde_json::json!({ "id": id, "vend_credentials": true });
|
||||
let description: TableDescription = self
|
||||
.authed(self.http.post(&url))
|
||||
.http
|
||||
.post(&url)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
@@ -146,41 +111,6 @@ impl NamespaceClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Without a hop bound a catalog that redirects to itself keeps the request
|
||||
/// alive until the call timeout, so the custom policy keeps the limit the
|
||||
/// default one had.
|
||||
fn may_follow(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
|
||||
previous.len() < MAX_REDIRECT_HOPS
|
||||
&& previous.last().is_some_and(|prev| same_origin(prev, next))
|
||||
}
|
||||
|
||||
/// A redirect stays within an origin when scheme, host, and port all match, so
|
||||
/// a catalog cannot bounce the api key onto a downgraded or foreign listener.
|
||||
fn same_origin(from: &reqwest::Url, to: &reqwest::Url) -> bool {
|
||||
from.scheme() == to.scheme()
|
||||
&& from.host_str() == to.host_str()
|
||||
&& from.port_or_known_default() == to.port_or_known_default()
|
||||
}
|
||||
|
||||
/// A catalog url protects the api key when the hop is TLS or never leaves the
|
||||
/// host; anything else sends it where the network can read it.
|
||||
fn protected_transport(base_url: &str) -> bool {
|
||||
let Ok(url) = reqwest::Url::parse(base_url) else {
|
||||
return false;
|
||||
};
|
||||
if url.scheme() == "https" {
|
||||
return true;
|
||||
}
|
||||
match url.host_str() {
|
||||
Some("localhost") => true,
|
||||
Some(host) => host
|
||||
.trim_matches(['[', ']'])
|
||||
.parse::<std::net::IpAddr>()
|
||||
.is_ok_and(|ip| ip.is_loopback()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_id(id: &[String]) -> String {
|
||||
if id.is_empty() {
|
||||
DELIMITER.to_string()
|
||||
@@ -197,56 +127,3 @@ pub fn parse_id(encoded: &str) -> Vec<String> {
|
||||
.map(|part| part.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{MAX_REDIRECT_HOPS, may_follow, protected_transport, same_origin};
|
||||
|
||||
#[test]
|
||||
fn may_follow_bounds_hops_within_the_origin() {
|
||||
let url = |u: &str| reqwest::Url::parse(u).unwrap();
|
||||
let first = [url("https://c.local/ns")];
|
||||
let next = url("https://c.local/other");
|
||||
assert!(may_follow(&first, &next));
|
||||
assert!(!may_follow(&[], &next));
|
||||
assert!(!may_follow(&first, &url("http://c.local/other")));
|
||||
let full: Vec<_> = (0..MAX_REDIRECT_HOPS)
|
||||
.map(|i| url(&format!("https://c.local/{i}")))
|
||||
.collect();
|
||||
assert!(!may_follow(&full, &next));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_origin_rejects_scheme_and_port_hops() {
|
||||
for (from, to, expected) in [
|
||||
("https://c.local/ns", "https://c.local/other", true),
|
||||
("http://c.local", "http://c.local:80/next", true),
|
||||
("https://c.local", "http://c.local/next", false),
|
||||
("https://c.local:8443", "https://c.local/next", false),
|
||||
("https://c.local", "https://other.local/next", false),
|
||||
] {
|
||||
let from = reqwest::Url::parse(from).unwrap();
|
||||
let to = reqwest::Url::parse(to).unwrap();
|
||||
assert_eq!(same_origin(&from, &to), expected, "{from} -> {to}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protected_transport_covers_tls_and_loopback() {
|
||||
for url in [
|
||||
"https://catalog.internal:8443",
|
||||
"http://127.0.0.1:8080",
|
||||
"http://localhost",
|
||||
"http://[::1]:8080",
|
||||
] {
|
||||
assert!(protected_transport(url), "{url} should be protected");
|
||||
}
|
||||
for url in [
|
||||
"http://catalog.internal",
|
||||
"http://127.0.0.1.evil.test",
|
||||
"not a url",
|
||||
] {
|
||||
assert!(!protected_transport(url), "{url} should warn");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,7 @@ impl CleanupVersionsHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ impl CompactHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ impl OptimizeIndicesHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ impl SortHandler {
|
||||
}
|
||||
|
||||
fn client(&self) -> NamespaceClient {
|
||||
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
|
||||
NamespaceClient::new(self.namespace_url.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ impl PreviewProvider for LancePreview {
|
||||
}
|
||||
|
||||
async fn preview(&self, object_id: &[String], row_limit: usize) -> Result<Preview> {
|
||||
let client = NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback);
|
||||
let client = NamespaceClient::new(self.namespace_url.clone());
|
||||
let table = dataset::open(&client, object_id, &self.fallback).await?;
|
||||
|
||||
let total_rows = table.dataset.count_rows(None).await.unwrap_or(0) as i64;
|
||||
|
||||
@@ -244,13 +244,7 @@ func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
|
||||
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatalf("build the namespace exists request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", env.accessKey+":"+env.secretKey)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
|
||||
}
|
||||
|
||||
@@ -53,13 +53,7 @@ def main():
|
||||
"aws_region": "us-east-1",
|
||||
}
|
||||
|
||||
ns = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
)
|
||||
ns = ln.connect("rest", {"uri": args.namespace_url})
|
||||
ns.create_namespace(ln.CreateNamespaceRequest(id=[args.bucket], mode="EXIST_OK"))
|
||||
ns.create_namespace(
|
||||
ln.CreateNamespaceRequest(id=[args.bucket, args.namespace], mode="EXIST_OK")
|
||||
|
||||
@@ -45,15 +45,7 @@ def seed_table(namespace_url, storage, bucket, namespace, table, rows):
|
||||
LanceDB reads through the catalog; the writing half is pylance, because the
|
||||
namespace records where a table lives and does not carry its data.
|
||||
"""
|
||||
ns = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": namespace_url,
|
||||
"header.x-api-key": (
|
||||
f"{storage['aws_access_key_id']}:{storage['aws_secret_access_key']}"
|
||||
),
|
||||
},
|
||||
)
|
||||
ns = ln.connect("rest", {"uri": namespace_url})
|
||||
ns.create_namespace(
|
||||
ln.CreateNamespaceRequest(id=[bucket], mode="EXIST_OK")
|
||||
)
|
||||
@@ -106,12 +98,7 @@ def main():
|
||||
|
||||
print(f"lancedb {lancedb.__version__} connecting to {args.namespace_url}")
|
||||
db = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
storage_options=storage,
|
||||
"rest", {"uri": args.namespace_url}, storage_options=storage
|
||||
)
|
||||
|
||||
# 1. The catalog is browsable: the bucket is a namespace, and the table is
|
||||
@@ -203,10 +190,7 @@ def main():
|
||||
# declare-and-write - rather than a hang, a 404, or a half-made table.
|
||||
pushdown = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
{"uri": args.namespace_url},
|
||||
storage_options=storage,
|
||||
namespace_client_pushdown_operations=["CreateTable"],
|
||||
)
|
||||
|
||||
@@ -41,7 +41,6 @@ deployment uses whatever address the gateway answers on:
|
||||
spark.sql.catalog.lance org.lance.spark.LanceNamespaceSparkCatalog
|
||||
spark.sql.catalog.lance.impl rest
|
||||
spark.sql.catalog.lance.uri http://seaweed:9101
|
||||
spark.sql.catalog.lance.headers.x-api-key <access-key>:<secret-key>
|
||||
spark.sql.catalog.lance.storage.aws_endpoint http://seaweed:8333
|
||||
spark.sql.catalog.lance.storage.allow_http true
|
||||
spark.sql.catalog.lance.storage.aws_access_key_id …
|
||||
|
||||
@@ -46,10 +46,6 @@ def main():
|
||||
.config("spark.sql.catalog.lance", "org.lance.spark.LanceNamespaceSparkCatalog")
|
||||
.config("spark.sql.catalog.lance.impl", "rest")
|
||||
.config("spark.sql.catalog.lance.uri", args.namespace_url)
|
||||
.config(
|
||||
"spark.sql.catalog.lance.headers.x-api-key",
|
||||
f"{args.access_key}:{args.secret_key}",
|
||||
)
|
||||
.config("spark.sql.catalog.lance.storage.aws_endpoint", args.s3_endpoint)
|
||||
.config("spark.sql.catalog.lance.storage.allow_http", "true")
|
||||
.config("spark.sql.catalog.lance.storage.aws_access_key_id", args.access_key)
|
||||
|
||||
@@ -239,13 +239,7 @@ func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
|
||||
t.Helper()
|
||||
|
||||
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
|
||||
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatalf("build the namespace exists request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", env.accessKey+":"+env.secretKey)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
|
||||
}
|
||||
|
||||
@@ -99,8 +99,7 @@ def connect(args):
|
||||
"uri": args.catalog_url,
|
||||
"warehouse": f"s3://{args.bucket}/",
|
||||
"prefix": args.bucket,
|
||||
"oauth2-server-uri": f"{args.catalog_url}/v1/oauth/tokens",
|
||||
"credential": f"{args.access_key}:{args.secret_key}",
|
||||
"auth": {"type": "noop"},
|
||||
"s3.endpoint": args.s3_endpoint,
|
||||
"s3.access-key-id": args.access_key,
|
||||
"s3.secret-access-key": args.secret_key,
|
||||
|
||||
@@ -83,13 +83,7 @@ def tally(dataset):
|
||||
|
||||
def resolve(args):
|
||||
"""Ask the namespace where the table lives, the way the worker does."""
|
||||
namespace = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
)
|
||||
namespace = ln.connect("rest", {"uri": args.namespace_url})
|
||||
table_id = [args.bucket, args.namespace, args.table]
|
||||
described = namespace.describe_table(ln.DescribeTableRequest(id=table_id))
|
||||
return namespace, table_id, described.location, storage_options(args, described)
|
||||
@@ -121,13 +115,7 @@ def main():
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.phase == "write":
|
||||
namespace = ln.connect(
|
||||
"rest",
|
||||
{
|
||||
"uri": args.namespace_url,
|
||||
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
|
||||
},
|
||||
)
|
||||
namespace = ln.connect("rest", {"uri": args.namespace_url})
|
||||
for parent in ([args.bucket], [args.bucket, args.namespace]):
|
||||
namespace.create_namespace(ln.CreateNamespaceRequest(id=parent, mode="EXIST_OK"))
|
||||
table_id = [args.bucket, args.namespace, args.table]
|
||||
|
||||
@@ -111,16 +111,6 @@ func (cp *ConfigPersistence) ApplyMaintenanceConfigFromToml(v TomlConfig) error
|
||||
}
|
||||
ecChanged = true
|
||||
}
|
||||
if k := "maintenance.erasure_coding.max_shard_transfers"; v.IsSet(k) {
|
||||
n := v.GetInt(k)
|
||||
if n < 0 {
|
||||
n = 0
|
||||
} else if n > math.MaxInt32 {
|
||||
n = math.MaxInt32
|
||||
}
|
||||
ecConf.MaxShardTransfers = &n
|
||||
ecChanged = true
|
||||
}
|
||||
|
||||
if !maintenanceChanged && !vacuumChanged && !balanceChanged && !ecChanged {
|
||||
return nil
|
||||
@@ -249,7 +239,6 @@ var pluginConfigSections = []pluginConfigSection{
|
||||
"replica_placement": stringValue,
|
||||
"strict_placement": boolValue,
|
||||
"free_slots_deadband": int64Value,
|
||||
"max_shard_transfers": int64Value,
|
||||
},
|
||||
// workers read collection_filter from the admin values, not the worker values
|
||||
adminKeys: map[string]func(v TomlConfig, key string) *plugin_pb.ConfigValue{
|
||||
|
||||
@@ -307,97 +307,3 @@ preferred_tags = ["fast,SSD"]
|
||||
t.Errorf("preferred_tags = %v, want [fast ssd]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMaintenanceConfigFromTomlMaxShardTransfers(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cp := NewConfigPersistence(dir)
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
fullness_ratio = 0.9
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply fullness: %v", err)
|
||||
}
|
||||
ec := erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers != nil {
|
||||
t.Fatalf("absent key persisted as %d, want unset", *ec.MaxShardTransfers)
|
||||
}
|
||||
if ec.FullnessRatio != 0.9 {
|
||||
t.Fatalf("fullness_ratio = %v, want 0.9", ec.FullnessRatio)
|
||||
}
|
||||
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = 0
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply 0: %v", err)
|
||||
}
|
||||
ec = erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 0 {
|
||||
t.Fatalf("0: got %v, want sequential 0", ec.MaxShardTransfers)
|
||||
}
|
||||
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = 4
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply 4: %v", err)
|
||||
}
|
||||
ec = erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 4 {
|
||||
t.Fatalf("4: got %v, want 4", ec.MaxShardTransfers)
|
||||
}
|
||||
|
||||
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = -3
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply negative: %v", err)
|
||||
}
|
||||
ec = erasure_coding.LoadConfigFromPersistence(cp)
|
||||
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 0 {
|
||||
t.Fatalf("negative: got %v, want sequential 0", ec.MaxShardTransfers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyPluginConfigFromTomlMaxShardTransfers(t *testing.T) {
|
||||
s := newPluginServer(t)
|
||||
seed := &plugin_pb.PersistedJobTypeConfig{
|
||||
JobType: "erasure_coding",
|
||||
AdminRuntime: &plugin_pb.AdminRuntimeConfig{Enabled: true},
|
||||
}
|
||||
if err := s.GetPlugin().SaveJobTypeConfig(seed); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
|
||||
if err := s.ApplyPluginConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
replica_placement = "020"
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply placement: %v", err)
|
||||
}
|
||||
cfg, err := s.GetPlugin().LoadJobTypeConfig("erasure_coding")
|
||||
if err != nil || cfg == nil {
|
||||
t.Fatalf("load: %v %v", cfg, err)
|
||||
}
|
||||
if _, ok := cfg.WorkerConfigValues["max_shard_transfers"]; ok {
|
||||
t.Fatal("absent max_shard_transfers was written into worker config")
|
||||
}
|
||||
|
||||
if err := s.ApplyPluginConfigFromToml(tomlConfig(t, `
|
||||
[maintenance.erasure_coding]
|
||||
max_shard_transfers = 0
|
||||
`)); err != nil {
|
||||
t.Fatalf("apply 0: %v", err)
|
||||
}
|
||||
cfg, err = s.GetPlugin().LoadJobTypeConfig("erasure_coding")
|
||||
if err != nil || cfg == nil {
|
||||
t.Fatalf("load 0: %v %v", cfg, err)
|
||||
}
|
||||
got, ok := cfg.WorkerConfigValues["max_shard_transfers"]
|
||||
if !ok {
|
||||
t.Fatal("max_shard_transfers = 0 missing from worker config")
|
||||
}
|
||||
if got.GetInt64Value() != 0 {
|
||||
t.Fatalf("max_shard_transfers = %d, want 0", got.GetInt64Value())
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -51,14 +50,9 @@ func NewFileBrowserHandlers(adminServer *dash.AdminServer) *FileBrowserHandlers
|
||||
// ShowFileBrowser renders the file browser page
|
||||
func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Request) {
|
||||
// Get path from query parameter, default to root
|
||||
dirPath := path.Clean(util.CleanWindowsPath(defaultQuery(r.URL.Query().Get("path"), "/")))
|
||||
if !strings.HasPrefix(dirPath, "/") {
|
||||
dirPath = "/" + dirPath
|
||||
}
|
||||
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) && restrictedBrowserPath(dirPath) {
|
||||
http.Redirect(w, r, dash.P(r.Context(), "/admin?error=Insufficient permissions"), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
path := defaultQuery(r.URL.Query().Get("path"), "/")
|
||||
// Normalize Windows-style paths for consistency
|
||||
path = util.CleanWindowsPath(path)
|
||||
|
||||
// Get pagination parameters
|
||||
lastFileName := r.URL.Query().Get("lastFileName")
|
||||
@@ -72,7 +66,7 @@ func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
// Get file browser data with cursor-based pagination
|
||||
browserData, err := h.adminServer.GetFileBrowser(dirPath, "", lastFileName, pageSize)
|
||||
browserData, err := h.adminServer.GetFileBrowser(path, "", lastFileName, pageSize)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to get file browser data: "+err.Error())
|
||||
return
|
||||
@@ -362,46 +356,14 @@ func (h *FileBrowserHandlers) validateAndCleanFilePath(filePath string) (string,
|
||||
cleanPath = "/" + cleanPath
|
||||
}
|
||||
|
||||
// Reject parent-directory components; names merely containing ".." are valid
|
||||
if slices.Contains(strings.Split(cleanPath, "/"), "..") {
|
||||
// Prevent path traversal attacks
|
||||
if strings.Contains(cleanPath, "..") {
|
||||
return "", fmt.Errorf("path traversal not allowed")
|
||||
}
|
||||
|
||||
return cleanPath, nil
|
||||
}
|
||||
|
||||
// restrictedBrowserPath reports whether a cleaned path lies inside the filer's
|
||||
// /etc tree, which holds the credential store and cluster configuration.
|
||||
func restrictedBrowserPath(cleanPath string) bool {
|
||||
return cleanPath == strings.TrimSuffix(filer.DirectoryEtcRoot, "/") ||
|
||||
strings.HasPrefix(cleanPath, filer.DirectoryEtcRoot)
|
||||
}
|
||||
|
||||
// cleanReadPath validates the request's path parameter; read-only sessions are
|
||||
// denied the /etc tree so the file browser cannot serve stored credentials.
|
||||
func (h *FileBrowserHandlers) cleanReadPath(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
cleanPath, err := h.validateAndCleanFilePath(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return "", false
|
||||
}
|
||||
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) && restrictedBrowserPath(cleanPath) {
|
||||
writeJSONError(w, http.StatusForbidden, "Access to this path requires admin access")
|
||||
return "", false
|
||||
}
|
||||
return cleanPath, true
|
||||
}
|
||||
|
||||
// exportExcludedPrefixes lists the subtrees a metadata export skips; read-only
|
||||
// sessions also lose /etc so stored credentials stay out of the dump.
|
||||
func exportExcludedPrefixes(r *http.Request) []string {
|
||||
prefixes := []string{filer.SystemLogDir}
|
||||
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) {
|
||||
prefixes = append(prefixes, strings.TrimSuffix(filer.DirectoryEtcRoot, "/"))
|
||||
}
|
||||
return prefixes
|
||||
}
|
||||
|
||||
// fetchFileContent fetches file content via the filer gRPC service. It is
|
||||
// used for the "view as text" path, so the maxBytes cap matches the 1 MB
|
||||
// limit the caller already applies before invoking us.
|
||||
@@ -415,8 +377,9 @@ func (h *FileBrowserHandlers) fetchFileContent(filePath string, timeout time.Dur
|
||||
// gRPC service, so the admin file browser keeps working even when the filer
|
||||
// is started with -disableHttp=true.
|
||||
func (h *FileBrowserHandlers) DownloadFile(w http.ResponseWriter, r *http.Request) {
|
||||
filePath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
return
|
||||
}
|
||||
inline := r.URL.Query().Get("inline") == "true"
|
||||
@@ -456,8 +419,9 @@ func (t *responseWriteTracker) Write(p []byte) (int, error) {
|
||||
|
||||
// ViewFile handles file viewing requests (for text files, images, etc.)
|
||||
func (h *FileBrowserHandlers) ViewFile(w http.ResponseWriter, r *http.Request) {
|
||||
filePath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -560,8 +524,9 @@ func (h *FileBrowserHandlers) ViewFile(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// GetFileProperties handles file properties requests
|
||||
func (h *FileBrowserHandlers) GetFileProperties(w http.ResponseWriter, r *http.Request) {
|
||||
filePath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -665,18 +630,23 @@ func (h *FileBrowserHandlers) GetFileProperties(w http.ResponseWriter, r *http.R
|
||||
// FullEntry stream — the format weed shell fs.meta.load reads. Directories are
|
||||
// walked recursively via the filer BFS metadata stream.
|
||||
func (h *FileBrowserHandlers) ExportMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
cleanPath, ok := h.cleanReadPath(w, r)
|
||||
if !ok {
|
||||
filePath := r.URL.Query().Get("path")
|
||||
if filePath == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "File path is required")
|
||||
return
|
||||
}
|
||||
cleanPath, err := h.validateAndCleanFilePath(filePath)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
excludedPrefixes := exportExcludedPrefixes(r)
|
||||
|
||||
tracker := &responseWriteTracker{ResponseWriter: w}
|
||||
|
||||
err := h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
err = h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
|
||||
stream, err := client.TraverseBfsMetadata(r.Context(), &filer_pb.TraverseBfsMetadataRequest{
|
||||
Directory: cleanPath,
|
||||
ExcludedPrefixes: excludedPrefixes,
|
||||
ExcludedPrefixes: []string{filer.SystemLogDir},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -3,12 +3,9 @@ package handlers
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/dash"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
)
|
||||
|
||||
func TestValidateAndCleanFilePath_AllowsControlChars(t *testing.T) {
|
||||
@@ -29,9 +26,6 @@ func TestValidateAndCleanFilePath_AllowsControlChars(t *testing.T) {
|
||||
{"relative/path.txt", "/relative/path.txt"},
|
||||
// Duplicate slashes should be collapsed by path.Clean.
|
||||
{"/a//b", "/a/b"},
|
||||
// ".." inside a file or directory name is not a parent component.
|
||||
{"/buckets/reports/report..csv", "/buckets/reports/report..csv"},
|
||||
{"/a../b", "/a../b"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := h.validateAndCleanFilePath(tc.in)
|
||||
@@ -52,81 +46,6 @@ func TestValidateAndCleanFilePath_RejectsEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAndCleanFilePath_RejectsParentComponents(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
for _, p := range []string{"../etc", "../../etc/iam", "..", "a/../../b"} {
|
||||
if _, err := h.validateAndCleanFilePath(p); err == nil {
|
||||
t.Errorf("validateAndCleanFilePath(%q): expected traversal rejection", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanReadPath_DeniesEtcForReadOnly(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
|
||||
denied := []string{"/etc", "/etc/iam", "/etc/iam/identities/root.json",
|
||||
"/etc/s3/kek.json", "/etc/../etc/iam/identity.json", "/a/../../etc/x"}
|
||||
for _, p := range denied {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/download?path="+p, nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "ro", dash.RoleReadOnly, "csrf"))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
if _, ok := h.cleanReadPath(w, req); ok {
|
||||
t.Errorf("path %q: expected denial for read-only session", p)
|
||||
continue
|
||||
}
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("path %q: expected 403, got %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanReadPath_AllowsEtcForAdminAndNorRole(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
|
||||
for _, role := range []string{"admin", ""} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/download?path=/etc/iam/identities/root.json", nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "u", role, "csrf"))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
if _, ok := h.cleanReadPath(w, req); !ok {
|
||||
t.Errorf("role %q: expected /etc path to be allowed, got %d", role, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanReadPath_AllowsReadOnlyOutsideEtc(t *testing.T) {
|
||||
h := &FileBrowserHandlers{}
|
||||
|
||||
for _, p := range []string{"/buckets/foo/bar.txt", "/etcx/file", "/etcetera", "/"} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/download?path="+p, nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "ro", dash.RoleReadOnly, "csrf"))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
if _, ok := h.cleanReadPath(w, req); !ok {
|
||||
t.Errorf("path %q: expected allowed for read-only session, got %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportExcludedPrefixes_ReadOnlyDropsEtc(t *testing.T) {
|
||||
etcPrefix := strings.TrimSuffix(filer.DirectoryEtcRoot, "/")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/metadata/export?path=/", nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "ro", dash.RoleReadOnly, "csrf"))
|
||||
if got := exportExcludedPrefixes(req); !slices.Contains(got, etcPrefix) {
|
||||
t.Errorf("read-only export should exclude %q, got %v", etcPrefix, got)
|
||||
}
|
||||
|
||||
for _, role := range []string{"admin", ""} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/files/metadata/export?path=/", nil)
|
||||
req = req.WithContext(dash.WithAuthContext(req.Context(), "u", role, "csrf"))
|
||||
if got := exportExcludedPrefixes(req); slices.Contains(got, etcPrefix) {
|
||||
t.Errorf("role %q: export should keep %q, got %v", role, etcPrefix, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListFolders_RejectsPathOutsideBuckets(t *testing.T) {
|
||||
h := &FileBrowserHandlers{adminServer: &dash.AdminServer{}}
|
||||
|
||||
@@ -143,3 +62,4 @@ func TestListFolders_RejectsPathOutsideBuckets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2272,105 +2272,6 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
return input;
|
||||
}
|
||||
|
||||
function shardTransferParallelOn(nativeValue) {
|
||||
if (nativeValue === null || nativeValue === undefined || nativeValue === '') {
|
||||
return true;
|
||||
}
|
||||
var n = parseInt(nativeValue, 10);
|
||||
if (Number.isNaN(n)) {
|
||||
return true;
|
||||
}
|
||||
return n !== 0;
|
||||
}
|
||||
|
||||
function shardTransferMaxText(nativeValue) {
|
||||
if (nativeValue === null || nativeValue === undefined || nativeValue === '') {
|
||||
return '';
|
||||
}
|
||||
var n = parseInt(nativeValue, 10);
|
||||
if (Number.isNaN(n) || n <= 0) {
|
||||
return '';
|
||||
}
|
||||
return String(n);
|
||||
}
|
||||
|
||||
// Presentation of the single persisted max_shard_transfers value.
|
||||
// Unchecked stores 0. Checked with an empty max omits the key.
|
||||
function renderShardTransferControls(scope, field, nativeValue) {
|
||||
var parallelOn = shardTransferParallelOn(nativeValue);
|
||||
var wrapper = document.createElement('div');
|
||||
wrapper.className = 'mb-3 plugin-field';
|
||||
wrapper.dataset.scope = scope;
|
||||
wrapper.dataset.fieldName = field.name;
|
||||
wrapper.dataset.fieldType = normalizeEnum(field.field_type);
|
||||
wrapper.dataset.widget = 'SHARD_TRANSFERS';
|
||||
|
||||
var checkWrap = document.createElement('div');
|
||||
checkWrap.className = 'form-check form-switch mb-2';
|
||||
var box = document.createElement('input');
|
||||
box.type = 'checkbox';
|
||||
box.className = 'form-check-input';
|
||||
box.id = toInputID(scope, field.name) + '-parallel';
|
||||
box.checked = parallelOn;
|
||||
var boxLabel = document.createElement('label');
|
||||
boxLabel.className = 'form-check-label';
|
||||
boxLabel.setAttribute('for', box.id);
|
||||
boxLabel.textContent = 'Parallel shard distribution';
|
||||
checkWrap.appendChild(box);
|
||||
checkWrap.appendChild(boxLabel);
|
||||
wrapper.appendChild(checkWrap);
|
||||
|
||||
var numberLabel = document.createElement('label');
|
||||
numberLabel.className = 'form-label';
|
||||
numberLabel.setAttribute('for', toInputID(scope, field.name));
|
||||
numberLabel.textContent = 'Max transfers';
|
||||
wrapper.appendChild(numberLabel);
|
||||
|
||||
var input = document.createElement('input');
|
||||
input.type = 'number';
|
||||
input.min = '1';
|
||||
input.step = '1';
|
||||
input.className = 'form-control';
|
||||
input.id = toInputID(scope, field.name);
|
||||
input.placeholder = 'no global cap';
|
||||
input.value = shardTransferMaxText(nativeValue);
|
||||
input.disabled = !parallelOn;
|
||||
wrapper.appendChild(input);
|
||||
|
||||
box.addEventListener('change', function() {
|
||||
input.disabled = !box.checked;
|
||||
});
|
||||
|
||||
var help = document.createElement('div');
|
||||
help.className = 'form-text';
|
||||
help.textContent = field.description || 'Unchecked sends shards sequentially. Checked with an empty max uses one in-flight copy per destination disk. A number is a global cap, still one copy per disk.';
|
||||
wrapper.appendChild(help);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function collectShardTransferValue(scope) {
|
||||
var box = document.getElementById(toInputID(scope, 'max_shard_transfers') + '-parallel');
|
||||
var input = document.getElementById(toInputID(scope, 'max_shard_transfers'));
|
||||
if (!box || !input) {
|
||||
return null;
|
||||
}
|
||||
if (!box.checked) {
|
||||
return { int64_value: '0' };
|
||||
}
|
||||
var raw = String(input.value || '').trim();
|
||||
if (raw === '') {
|
||||
return null;
|
||||
}
|
||||
if (!/^\d+$/.test(raw)) {
|
||||
throw new Error('Invalid int64 value for field Max transfers');
|
||||
}
|
||||
var n = parseInt(raw, 10);
|
||||
if (n <= 0) {
|
||||
return { int64_value: '0' };
|
||||
}
|
||||
return { int64_value: String(n) };
|
||||
}
|
||||
|
||||
function renderConfigForm(scope, rootID, form) {
|
||||
var root = document.getElementById(rootID);
|
||||
if (!root) {
|
||||
@@ -2420,11 +2321,6 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
var configValue = resolveFieldConfigValue(scope, field);
|
||||
var nativeValue = configValueToNative(configValue);
|
||||
|
||||
if (field.name === 'max_shard_transfers') {
|
||||
sectionBody.appendChild(renderShardTransferControls(scope, field, nativeValue));
|
||||
continue;
|
||||
}
|
||||
|
||||
var wrapper = document.createElement('div');
|
||||
wrapper.className = 'mb-3 plugin-field';
|
||||
wrapper.dataset.scope = scope;
|
||||
@@ -2544,14 +2440,6 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field.name === 'max_shard_transfers') {
|
||||
var shardCap = collectShardTransferValue(scope);
|
||||
if (shardCap !== null) {
|
||||
out[field.name] = shardCap;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
var wrapper = document.querySelector('.plugin-field[data-scope="' + scope + '"][data-field-name="' + field.name + '"]');
|
||||
if (wrapper && wrapper.classList.contains('plugin-field-hidden')) {
|
||||
continue;
|
||||
|
||||
@@ -104,7 +104,7 @@ func Plugin(page string, initialJob string, lane string) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"bi bi-arrow-repeat me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"bi bi-graph-up-arrow me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"bi bi-sliders me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"bi bi-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"bi bi-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"bi bi-list-check me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</p></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-outline-secondary\" id=\"plugin-refresh-all-btn\"><i class=\"bi bi-arrow-repeat me-1\"></i>Refresh</button></div></div></div></div><div class=\"row mb-3\"><div class=\"col-12\"><ul class=\"nav nav-tabs\" id=\"plugin-top-tabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-top-tab=\"overview\"><i class=\"bi bi-graph-up-arrow me-1\"></i>Overview</button></li></ul></div></div><div class=\"row mb-3 d-none\" id=\"plugin-subtab-row\"><div class=\"col-12\"><ul class=\"nav nav-pills gap-2\" id=\"plugin-subtabs\"><li class=\"nav-item\"><button type=\"button\" class=\"nav-link active\" data-plugin-subtab=\"configuration\"><i class=\"bi bi-sliders me-1\"></i>Configuration</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"detection\"><i class=\"bi bi-search me-1\"></i>Job Detection</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"queue\"><i class=\"bi bi-list me-1\"></i>Job Queue</button></li><li class=\"nav-item\"><button type=\"button\" class=\"nav-link\" data-plugin-subtab=\"execution\"><i class=\"bi bi-list-check me-1\"></i>Job Execution</button></li></ul></div></div><div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next Run</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
+3
-18
@@ -64,7 +64,6 @@ type FilerOptions struct {
|
||||
mastersString *string
|
||||
ip *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
portGrpc *int
|
||||
publicPort *int
|
||||
@@ -283,17 +282,12 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
}
|
||||
go stats_collect.StartMetricsServer(*f.metricsHttpIp, *f.metricsHttpPort)
|
||||
|
||||
// Embedded services keep their loopback companion listener only while
|
||||
// -ip.bind is unset and the bind address falls back to -ip. This must be
|
||||
// captured before startFiler fills *f.bindIp in place.
|
||||
filerBindIpUnset := *f.bindIp == ""
|
||||
filerAddress := pb.NewServerAddress(*f.ip, *f.port, *f.portGrpc).String()
|
||||
startDelay := time.Duration(2)
|
||||
if *filerStartS3 {
|
||||
filerS3Options.filer = &filerAddress
|
||||
filerS3Options.ip = f.ip
|
||||
if *filerS3Options.bindIp == "" {
|
||||
filerS3Options.listenOnLocalhost = &filerBindIpUnset
|
||||
filerS3Options.bindIp = f.bindIp
|
||||
}
|
||||
filerS3Options.localFilerSocket = f.localSocket
|
||||
@@ -326,7 +320,6 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
if *filerStartIam {
|
||||
filerIamOptions.filer = &filerAddress
|
||||
filerIamOptions.masters = f.mastersString
|
||||
filerIamOptions.listenOnLocalhost = &filerBindIpUnset
|
||||
go func(delay time.Duration) {
|
||||
time.Sleep(delay * time.Second)
|
||||
filerIamOptions.startIamServer()
|
||||
@@ -337,7 +330,6 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
if *filerStartSftp {
|
||||
filerSftpOptions.filer = &filerAddress
|
||||
if *filerSftpOptions.bindIp == "" {
|
||||
filerSftpOptions.listenOnLocalhost = &filerBindIpUnset
|
||||
filerSftpOptions.bindIp = f.bindIp
|
||||
}
|
||||
go func(delay time.Duration) {
|
||||
@@ -364,13 +356,6 @@ func (fo *FilerOptions) startFiler() {
|
||||
if *fo.portGrpc == 0 {
|
||||
*fo.portGrpc = 10000 + *fo.port
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset
|
||||
// and the bind address falls back to -ip. An explicit -ip.bind pins each
|
||||
// port to exactly that address.
|
||||
listenOnLocalhost := *fo.bindIp == ""
|
||||
if fo.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *fo.listenOnLocalhost
|
||||
}
|
||||
if *fo.bindIp == "" {
|
||||
*fo.bindIp = *fo.ip
|
||||
}
|
||||
@@ -448,7 +433,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
if *fo.publicPort != 0 {
|
||||
publicListeningAddress := util.JoinHostPort(*fo.bindIp, *fo.publicPort)
|
||||
glog.V(0).Infoln("Start Seaweed filer server", version.Version(), "public at", publicListeningAddress)
|
||||
publicListener, localPublicListener, e := util.NewIpAndLocalListeners(*fo.bindIp, *fo.publicPort, 0, listenOnLocalhost)
|
||||
publicListener, localPublicListener, e := util.NewIpAndLocalListeners(*fo.bindIp, *fo.publicPort, 0)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer server public listener error on port %d:%v", *fo.publicPort, e)
|
||||
}
|
||||
@@ -474,7 +459,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
glog.V(0).Infof("Start Seaweed Filer %s at %s:%d", version.Version(), *fo.ip, *fo.port)
|
||||
filerListener, filerLocalListener, e := util.NewIpAndLocalListeners(
|
||||
*fo.bindIp, *fo.port,
|
||||
time.Duration(10)*time.Second, listenOnLocalhost,
|
||||
time.Duration(10)*time.Second,
|
||||
)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer listener error: %v", e)
|
||||
@@ -482,7 +467,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
|
||||
// starting grpc server
|
||||
grpcPort := *fo.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*fo.bindIp, grpcPort, 0, listenOnLocalhost)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*fo.bindIp, grpcPort, 0)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
|
||||
+1
-16
@@ -31,8 +31,6 @@ type IamOptions struct {
|
||||
filer *string
|
||||
masters *string
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
selfServiceRequiresGrant *bool
|
||||
}
|
||||
@@ -42,7 +40,6 @@ func init() {
|
||||
iamStandaloneOptions.filer = cmdIam.Flag.String("filer", "localhost:8888", "comma-separated filer server addresses for high availability")
|
||||
iamStandaloneOptions.masters = cmdIam.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
iamStandaloneOptions.ip = cmdIam.Flag.String("ip", util.DetectedHostAddress(), "iam server http listen ip address")
|
||||
iamStandaloneOptions.ipBind = cmdIam.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
iamStandaloneOptions.port = cmdIam.Flag.Int("port", 8111, "iam server http listen port")
|
||||
iamStandaloneOptions.selfServiceRequiresGrant = cmdIam.Flag.Bool("selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage)
|
||||
}
|
||||
@@ -122,20 +119,8 @@ func (iamopt *IamOptions) startIamServer() bool {
|
||||
iamApiServer.Shutdown()
|
||||
})
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset and
|
||||
// the bind address falls back to -ip. An explicit -ip.bind pins the port to
|
||||
// exactly that address.
|
||||
bindIp := *iamopt.ip
|
||||
listenOnLocalhost := iamopt.ipBind == nil || *iamopt.ipBind == ""
|
||||
if iamopt.ipBind != nil && *iamopt.ipBind != "" {
|
||||
bindIp = *iamopt.ipBind
|
||||
}
|
||||
if iamopt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *iamopt.listenOnLocalhost
|
||||
}
|
||||
|
||||
listenAddress := fmt.Sprintf(":%d", *iamopt.port)
|
||||
iamApiListener, iamApiLocalListener, err := util.NewIpAndLocalListeners(bindIp, *iamopt.port, time.Duration(10)*time.Second, listenOnLocalhost)
|
||||
iamApiListener, iamApiLocalListener, err := util.NewIpAndLocalListeners(*iamopt.ip, *iamopt.port, time.Duration(10)*time.Second)
|
||||
if err != nil {
|
||||
glog.Fatalf("IAM API Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
+6
-18
@@ -50,7 +50,6 @@ type MasterOptions struct {
|
||||
portGrpc *int
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
metaFolder *string
|
||||
peers *string
|
||||
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
|
||||
@@ -83,14 +82,11 @@ type MasterOptions struct {
|
||||
// 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.
|
||||
// one full volume-server inventory has been applied. weed mini sets it:
|
||||
// the embedded volume server is the only possible reporter, 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() {
|
||||
@@ -201,13 +197,6 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
if *masterOption.portGrpc == 0 {
|
||||
*masterOption.portGrpc = 10000 + *masterOption.port
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset
|
||||
// and the bind address falls back to -ip. An explicit -ip.bind pins each
|
||||
// port to exactly that address.
|
||||
listenOnLocalhost := *masterOption.ipBind == ""
|
||||
if masterOption.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *masterOption.listenOnLocalhost
|
||||
}
|
||||
if *masterOption.ipBind == "" {
|
||||
*masterOption.ipBind = *masterOption.ip
|
||||
}
|
||||
@@ -224,7 +213,7 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
ms := weed_server.NewMasterServer(r, masterOption.toMasterOption(masterWhiteList), masterPeers)
|
||||
listeningAddress := util.JoinHostPort(*masterOption.ipBind, *masterOption.port)
|
||||
glog.V(0).Infof("Start Seaweed Master %s at %s", version.Version(), listeningAddress)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOption.ipBind, *masterOption.port, 0, listenOnLocalhost)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOption.ipBind, *masterOption.port, 0)
|
||||
if e != nil {
|
||||
glog.Fatalf("Master startup error: %v", e)
|
||||
}
|
||||
@@ -281,7 +270,7 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
}
|
||||
// starting grpc server
|
||||
grpcPort := *masterOption.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOption.ipBind, grpcPort, 0, listenOnLocalhost)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOption.ipBind, grpcPort, 0)
|
||||
if err != nil {
|
||||
glog.Fatalf("master failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
@@ -507,6 +496,5 @@ func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOp
|
||||
TelemetryEnabled: *m.telemetryEnabled,
|
||||
SingleMaster: isSingleMasterMode(*m.peers),
|
||||
ReleaseAllocOnFirstReport: m.releaseAllocOnFirstReport,
|
||||
SingleVolumeReporter: m.singleReporterAddr,
|
||||
}
|
||||
}
|
||||
@@ -129,10 +129,6 @@ func startMasterFollower(masterOptions MasterOptions) {
|
||||
option := masterOptions.toMasterOption(nil)
|
||||
option.IsFollower = true
|
||||
|
||||
listenOnLocalhost := *masterOptions.ipBind == ""
|
||||
if masterOptions.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *masterOptions.listenOnLocalhost
|
||||
}
|
||||
if *masterOptions.ipBind == "" {
|
||||
*masterOptions.ipBind = *masterOptions.ip
|
||||
}
|
||||
@@ -141,14 +137,14 @@ func startMasterFollower(masterOptions MasterOptions) {
|
||||
ms := weed_server.NewMasterServer(r, option, masters)
|
||||
listeningAddress := util.JoinHostPort(*masterOptions.ipBind, *masterOptions.port)
|
||||
glog.V(0).Infof("Start Seaweed Master %s at %s", version.Version(), listeningAddress)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOptions.ipBind, *masterOptions.port, 0, listenOnLocalhost)
|
||||
masterListener, masterLocalListener, e := util.NewIpAndLocalListeners(*masterOptions.ipBind, *masterOptions.port, 0)
|
||||
if e != nil {
|
||||
glog.Fatalf("Master startup error: %v", e)
|
||||
}
|
||||
|
||||
// starting grpc server
|
||||
grpcPort := *masterOptions.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOptions.ipBind, grpcPort, 0, listenOnLocalhost)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOptions.ipBind, grpcPort, 0)
|
||||
if err != nil {
|
||||
glog.Fatalf("master failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
|
||||
+70
-127
@@ -821,20 +821,10 @@ func isPortAvailable(port int) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// isPortUsableOnIP reports whether port can be bound on ip. While mini also
|
||||
// opens a loopback listener, the port must additionally be free on every
|
||||
// interface so that listener cannot collide with a holder on another address.
|
||||
func isPortUsableOnIP(ip string, port int, listenOnLocalhost bool) bool {
|
||||
if !isPortOpenOnIP(ip, port) {
|
||||
return false
|
||||
}
|
||||
return !listenOnLocalhost || isPortAvailable(port)
|
||||
}
|
||||
|
||||
// findAvailablePortOnIP finds the next available port on a specific IP starting from the given port
|
||||
// It skips any ports that are in the reservedPorts map (for gRPC port collision avoidance)
|
||||
// It returns the first available port found within maxAttempts, or 0 if none found
|
||||
func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPorts map[int]bool, listenOnLocalhost bool) int {
|
||||
func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPorts map[int]bool) int {
|
||||
for i := 0; i < maxAttempts; i++ {
|
||||
port := startPort + i
|
||||
if port > 65535 {
|
||||
@@ -846,7 +836,7 @@ func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPo
|
||||
continue
|
||||
}
|
||||
// Check on both the specific IP and on all interfaces for maximum reliability
|
||||
if isPortUsableOnIP(ip, port, listenOnLocalhost) {
|
||||
if isPortOpenOnIP(ip, port) && isPortAvailable(port) {
|
||||
return port
|
||||
}
|
||||
}
|
||||
@@ -857,7 +847,7 @@ func findAvailablePortOnIP(ip string, startPort int, maxAttempts int, reservedPo
|
||||
// ensurePortAvailableOnIP ensures a port pointer points to an available port on a specific IP
|
||||
// If the port is not available, it finds the next available port and updates the pointer
|
||||
// The reservedPorts map contains ports that should not be allocated (for gRPC collision avoidance)
|
||||
func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reservedPorts map[int]bool, flagName string, listenOnLocalhost bool) error {
|
||||
func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reservedPorts map[int]bool, flagName string) error {
|
||||
// Check if this port was explicitly specified by the user (from CLI or env, before the config file was applied)
|
||||
isExplicitPort := explicitFlags[flagName]
|
||||
|
||||
@@ -873,7 +863,7 @@ func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reserv
|
||||
return fmt.Errorf("port %d for %s (specified by flag %s) is reserved for gRPC calculation and cannot be used", original, serviceName, flagName)
|
||||
}
|
||||
glog.Warningf("Port %d for %s is reserved for gRPC calculation, finding alternative...", original, serviceName)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts, listenOnLocalhost)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts)
|
||||
if newPort == 0 {
|
||||
glog.Errorf("Could not find available port for %s starting from %d, will use original %d and fail on binding", serviceName, original+1, original)
|
||||
} else {
|
||||
@@ -884,14 +874,14 @@ func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reserv
|
||||
}
|
||||
|
||||
// Check on both the specific IP and on all interfaces (0.0.0.0) for maximum reliability
|
||||
if !isPortUsableOnIP(ip, original, listenOnLocalhost) {
|
||||
if !isPortOpenOnIP(ip, original) || !isPortAvailable(original) {
|
||||
// If explicitly specified, fail immediately with the originally requested port
|
||||
if isExplicitPort {
|
||||
return fmt.Errorf("port %d for %s (specified by flag %s) is not available on %s and cannot be used", original, serviceName, flagName, ip)
|
||||
}
|
||||
// For default ports, try to find an alternative
|
||||
glog.Warningf("Port %d for %s is not available on %s, finding alternative port...", original, serviceName, ip)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts, listenOnLocalhost)
|
||||
newPort := findAvailablePortOnIP(ip, original+1, 100, reservedPorts)
|
||||
if newPort == 0 {
|
||||
glog.Errorf("Could not find available port for %s starting from %d, will use original %d and fail on binding", serviceName, original+1, original)
|
||||
} else {
|
||||
@@ -907,61 +897,53 @@ func ensurePortAvailableOnIP(portPtr *int, serviceName string, ip string, reserv
|
||||
// ensureAllPortsAvailableOnIP ensures all mini service ports are available on a specific IP
|
||||
// Returns an error if an explicitly specified port is unavailable.
|
||||
// This should be called before starting any services
|
||||
func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
|
||||
func ensureAllPortsAvailableOnIP(bindIp string) error {
|
||||
portConfigs := []struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{
|
||||
{miniMasterOptions.port, "Master", "master.port", miniMasterOptions.portGrpc, listenOnLocalhost},
|
||||
{miniFilerOptions.port, "Filer", "filer.port", miniFilerOptions.portGrpc, listenOnLocalhost},
|
||||
{miniOptions.v.port, "Volume", "volume.port", miniOptions.v.portGrpc, listenOnLocalhost},
|
||||
{miniMasterOptions.port, "Master", "master.port", miniMasterOptions.portGrpc},
|
||||
{miniFilerOptions.port, "Filer", "filer.port", miniFilerOptions.portGrpc},
|
||||
{miniOptions.v.port, "Volume", "volume.port", miniOptions.v.portGrpc},
|
||||
}
|
||||
if *miniEnableS3 {
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniS3Options.port, "S3", "s3.port", miniS3Options.portGrpc, listenOnLocalhost})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniS3Options.port, "S3", "s3.port", miniS3Options.portGrpc})
|
||||
if miniS3Options.portIceberg != nil && *miniS3Options.portIceberg > 0 {
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniS3Options.portIceberg, "Iceberg", "s3.port.iceberg", nil, listenOnLocalhost})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniS3Options.portIceberg, "Iceberg", "s3.port.iceberg", nil})
|
||||
}
|
||||
if miniS3Options.portLance != nil && *miniS3Options.portLance > 0 {
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniS3Options.portLance, "Lance", "s3.port.lance", nil, listenOnLocalhost})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniS3Options.portLance, "Lance", "s3.port.lance", nil})
|
||||
}
|
||||
}
|
||||
// WebDAV and the Admin UI bind only -ip.bind; they never open a loopback
|
||||
// companion listener, so ports held elsewhere cannot collide with them.
|
||||
portConfigs = append(portConfigs, struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniWebDavOptions.port, "WebDAV", "webdav.port", nil, false},
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniWebDavOptions.port, "WebDAV", "webdav.port", nil},
|
||||
struct {
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
localhost bool
|
||||
}{miniAdminOptions.port, "Admin", "admin.port", miniAdminOptions.grpcPort, false})
|
||||
port *int
|
||||
name string
|
||||
flagName string
|
||||
grpcPtr *int
|
||||
}{miniAdminOptions.port, "Admin", "admin.port", miniAdminOptions.grpcPort})
|
||||
|
||||
// First, reserve all gRPC ports that will be calculated to prevent HTTP port allocation from using them
|
||||
// This prevents collisions like: HTTP port moves to X, then gRPC port is calculated as Y where Y == X
|
||||
@@ -974,20 +956,13 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
|
||||
}
|
||||
}
|
||||
|
||||
applyMiniAdminCredentialFallback(&miniAdminOptions)
|
||||
adminBindIP := miniAdminEffectiveBindIP(bindIp)
|
||||
|
||||
// Check all HTTP ports sequentially to avoid race conditions
|
||||
// Each port check and allocation must complete before the next one starts
|
||||
// to prevent multiple goroutines from claiming the same available port
|
||||
// Also avoid allocating ports that are reserved for gRPC calculation
|
||||
for _, config := range portConfigs {
|
||||
checkIP := bindIp
|
||||
if config.name == "Admin" {
|
||||
checkIP = adminBindIP
|
||||
}
|
||||
original := *config.port
|
||||
if err := ensurePortAvailableOnIP(config.port, config.name, checkIP, reservedPorts, config.flagName, config.localhost); err != nil {
|
||||
if err := ensurePortAvailableOnIP(config.port, config.name, bindIp, reservedPorts, config.flagName); err != nil {
|
||||
return err
|
||||
}
|
||||
// If port was changed, update the reserved gRPC ports mapping
|
||||
@@ -1000,7 +975,7 @@ func ensureAllPortsAvailableOnIP(bindIp string, listenOnLocalhost bool) error {
|
||||
// Initialize all gRPC ports before services start
|
||||
// This ensures they won't be recalculated and cause conflicts
|
||||
// All gRPC port handling (calculation, validation, and assignment) is performed exclusively in initializeGrpcPortsOnIP
|
||||
allocatedPorts := initializeGrpcPortsOnIP(bindIp, listenOnLocalhost)
|
||||
allocatedPorts := initializeGrpcPortsOnIP(bindIp)
|
||||
|
||||
// Every other service binds within a moment of this check, but the admin
|
||||
// waits for all of them first. The admin gRPC port sits inside the Linux
|
||||
@@ -1079,7 +1054,7 @@ func listenMiniAdminWorker(bindIP string, port int) (net.Listener, error) {
|
||||
// This must be called after HTTP ports are finalized and before services start
|
||||
// Returns the set of ports allocated to mini services, for callers that must
|
||||
// keep optional listeners from stealing them.
|
||||
func initializeGrpcPortsOnIP(bindIp string, listenOnLocalhost bool) map[int]bool {
|
||||
func initializeGrpcPortsOnIP(bindIp string) map[int]bool {
|
||||
// Track all ports allocated (both HTTP and gRPC) to prevent collisions.
|
||||
// We must reserve HTTP ports so that gRPC fallback allocation never picks
|
||||
// a port already assigned to an HTTP service (which hasn't bound yet).
|
||||
@@ -1102,34 +1077,26 @@ func initializeGrpcPortsOnIP(bindIp string, listenOnLocalhost bool) map[int]bool
|
||||
}
|
||||
|
||||
grpcConfigs := []struct {
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
ip string
|
||||
localhost bool
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
}{
|
||||
{miniMasterOptions.port, miniMasterOptions.portGrpc, "Master", bindIp, listenOnLocalhost},
|
||||
{miniFilerOptions.port, miniFilerOptions.portGrpc, "Filer", bindIp, listenOnLocalhost},
|
||||
{miniOptions.v.port, miniOptions.v.portGrpc, "Volume", bindIp, listenOnLocalhost},
|
||||
{miniMasterOptions.port, miniMasterOptions.portGrpc, "Master"},
|
||||
{miniFilerOptions.port, miniFilerOptions.portGrpc, "Filer"},
|
||||
{miniOptions.v.port, miniOptions.v.portGrpc, "Volume"},
|
||||
}
|
||||
if *miniEnableS3 {
|
||||
grpcConfigs = append(grpcConfigs, struct {
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
ip string
|
||||
localhost bool
|
||||
}{miniS3Options.port, miniS3Options.portGrpc, "S3", bindIp, listenOnLocalhost})
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
}{miniS3Options.port, miniS3Options.portGrpc, "S3"})
|
||||
}
|
||||
// The Admin worker gRPC binds workerGrpcBindIp (loopback by default), not
|
||||
// -ip.bind, and never opens a companion listener.
|
||||
grpcConfigs = append(grpcConfigs, struct {
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
ip string
|
||||
localhost bool
|
||||
}{miniAdminOptions.port, miniAdminOptions.grpcPort, "Admin", miniAdminOptions.workerGrpcBindIp, false})
|
||||
httpPort *int
|
||||
grpcPort *int
|
||||
name string
|
||||
}{miniAdminOptions.port, miniAdminOptions.grpcPort, "Admin"})
|
||||
|
||||
for _, config := range grpcConfigs {
|
||||
if config.grpcPort == nil {
|
||||
@@ -1143,10 +1110,10 @@ func initializeGrpcPortsOnIP(bindIp string, listenOnLocalhost bool) map[int]bool
|
||||
|
||||
// Verify the gRPC port is available (whether calculated or explicitly set)
|
||||
// Check on both specific IP and all interfaces, and check against already allocated ports
|
||||
if !isPortUsableOnIP(config.ip, *config.grpcPort, config.localhost) || allocatedPorts[*config.grpcPort] {
|
||||
if !isPortOpenOnIP(bindIp, *config.grpcPort) || !isPortAvailable(*config.grpcPort) || allocatedPorts[*config.grpcPort] {
|
||||
glog.Warningf("gRPC port %d for %s is not available, finding alternative...", *config.grpcPort, config.name)
|
||||
originalPort := *config.grpcPort
|
||||
newPort := findAvailablePortOnIP(config.ip, originalPort+1, 100, allocatedPorts, config.localhost)
|
||||
newPort := findAvailablePortOnIP(bindIp, originalPort+1, 100, allocatedPorts)
|
||||
if newPort == 0 {
|
||||
glog.Errorf("Could not find available gRPC port for %s starting from %d, will use %d and fail on binding", config.name, originalPort+1, originalPort)
|
||||
} else {
|
||||
@@ -1437,14 +1404,8 @@ func runMini(cmd *Command, args []string) bool {
|
||||
miniAdminOptions.workerGrpcBindIp = "127.0.0.1"
|
||||
}
|
||||
|
||||
// Services keep the loopback companion listener only while -ip.bind is
|
||||
// unset and the bind address falls back to -ip. While it is on, each
|
||||
// service port must be free on every interface, not just bindIp. This
|
||||
// must be captured before *miniBindIp is filled in below.
|
||||
listenOnLocalhost := *miniBindIp == "" && !util.IsLoopbackOrWildcardAddress(bindIp)
|
||||
|
||||
// Ensure all ports are available, find alternatives if needed
|
||||
if err := ensureAllPortsAvailableOnIP(bindIp, listenOnLocalhost); err != nil {
|
||||
if err := ensureAllPortsAvailableOnIP(bindIp); err != nil {
|
||||
glog.Errorf("Port allocation failed: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -1469,18 +1430,14 @@ func runMini(cmd *Command, args []string) bool {
|
||||
// ip address
|
||||
miniMasterOptions.ip = miniIp
|
||||
miniMasterOptions.ipBind = miniBindIp
|
||||
miniMasterOptions.listenOnLocalhost = &listenOnLocalhost
|
||||
miniFilerOptions.masters = pb.ServerAddresses(actualPeersForComponents).ToServiceDiscovery()
|
||||
miniFilerOptions.ip = miniIp
|
||||
miniFilerOptions.bindIp = miniBindIp
|
||||
miniFilerOptions.listenOnLocalhost = &listenOnLocalhost
|
||||
miniS3Options.ip = miniIp
|
||||
miniS3Options.bindIp = miniBindIp
|
||||
miniS3Options.listenOnLocalhost = &listenOnLocalhost
|
||||
miniWebDavOptions.ipBind = miniBindIp
|
||||
miniOptions.v.ip = miniIp
|
||||
miniOptions.v.bindIp = miniBindIp
|
||||
miniOptions.v.listenOnLocalhost = &listenOnLocalhost
|
||||
miniOptions.v.masters = pb.ServerAddresses(actualPeersForComponents).ToAddresses()
|
||||
miniOptions.v.idleConnectionTimeout = miniTimeout
|
||||
// Admin server binds to the same address as the other mini services.
|
||||
@@ -1564,22 +1521,11 @@ 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)
|
||||
}
|
||||
// Mini's embedded volume server is the only possible 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.
|
||||
miniMasterOptions.releaseAllocOnFirstReport = true
|
||||
miniOptions.v.shutdownCtx = MiniClusterCtx
|
||||
miniFilerOptions.shutdownCtx = MiniClusterCtx
|
||||
// Mini is a small/dev setup with short-lived RPCs; cap the filer's
|
||||
@@ -1835,14 +1781,6 @@ func miniAdminBindIP(requestedIP string, passwordConfigured, mtlsConfigured, all
|
||||
return "127.0.0.1"
|
||||
}
|
||||
|
||||
func miniAdminEffectiveBindIP(requestedIP string) string {
|
||||
hasMTLS := util.GetViper().GetString("https.admin.key") != "" &&
|
||||
util.GetViper().GetString("https.admin.ca") != ""
|
||||
allowInsecure := miniAdminOptions.allowInsecureBind != nil &&
|
||||
*miniAdminOptions.allowInsecureBind
|
||||
return miniAdminBindIP(requestedIP, *miniAdminOptions.adminPassword != "", hasMTLS, allowInsecure)
|
||||
}
|
||||
|
||||
// miniAdminWorkerAddress encodes the finalized HTTP and gRPC ports in the
|
||||
// server-address format understood by pb.ServerToGrpcAddress.
|
||||
func miniAdminWorkerAddress(bindIP string, httpPort, grpcPort int) string {
|
||||
@@ -1900,11 +1838,16 @@ func startMiniAdminWithWorker(allServicesReady chan struct{}) {
|
||||
applyMiniAdminCredentialFallback(&miniAdminOptions)
|
||||
|
||||
requestedBindIP := getBindIp()
|
||||
bindIP := miniAdminEffectiveBindIP(requestedBindIP)
|
||||
hasMTLS := util.GetViper().GetString("https.admin.key") != "" &&
|
||||
util.GetViper().GetString("https.admin.ca") != ""
|
||||
allowInsecure := miniAdminOptions.allowInsecureBind != nil &&
|
||||
*miniAdminOptions.allowInsecureBind
|
||||
bindIP := miniAdminBindIP(
|
||||
requestedBindIP,
|
||||
*miniAdminOptions.adminPassword != "",
|
||||
hasMTLS,
|
||||
allowInsecure,
|
||||
)
|
||||
miniAdminOptions.ip = &bindIP
|
||||
if bindIP != requestedBindIP {
|
||||
glog.Warningf(
|
||||
|
||||
@@ -17,20 +17,17 @@ var (
|
||||
)
|
||||
|
||||
type MessageQueueAgentOptions struct {
|
||||
brokers []pb.ServerAddress
|
||||
brokersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
brokers []pb.ServerAddress
|
||||
brokersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
port *int
|
||||
}
|
||||
|
||||
func init() {
|
||||
cmdMqAgent.Run = runMqAgent // break init cycle
|
||||
mqAgentOptions.brokersString = cmdMqAgent.Flag.String("broker", "localhost:17777", "comma-separated message queue brokers")
|
||||
mqAgentOptions.ip = cmdMqAgent.Flag.String("ip", "", "message queue agent host address")
|
||||
mqAgentOptions.ipBind = cmdMqAgent.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
mqAgentOptions.port = cmdMqAgent.Flag.Int("port", 16777, "message queue agent gRPC server port")
|
||||
}
|
||||
|
||||
@@ -63,20 +60,8 @@ func (mqAgentOpt *MessageQueueAgentOptions) startQueueAgent() bool {
|
||||
SeedBrokers: mqAgentOpt.brokers,
|
||||
}, grpcDialOption)
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset and
|
||||
// the bind address falls back to -ip. An explicit -ip.bind pins the port to
|
||||
// exactly that address.
|
||||
bindIp := *mqAgentOpt.ip
|
||||
listenOnLocalhost := mqAgentOpt.ipBind == nil || *mqAgentOpt.ipBind == ""
|
||||
if mqAgentOpt.ipBind != nil && *mqAgentOpt.ipBind != "" {
|
||||
bindIp = *mqAgentOpt.ipBind
|
||||
}
|
||||
if mqAgentOpt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *mqAgentOpt.listenOnLocalhost
|
||||
}
|
||||
|
||||
// start grpc listener
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners(bindIp, *mqAgentOpt.port, 0, listenOnLocalhost)
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners(*mqAgentOpt.ip, *mqAgentOpt.port, 0)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", *mqAgentOpt.port, err)
|
||||
}
|
||||
@@ -99,7 +84,7 @@ func (mqAgentOpt *MessageQueueAgentOptions) startQueueAgent() bool {
|
||||
}()
|
||||
}
|
||||
|
||||
glog.Infof("Start Seaweed Message Queue Agent on %s:%d", bindIp, *mqAgentOpt.port)
|
||||
glog.Infof("Start Seaweed Message Queue Agent on %s:%d", *mqAgentOpt.ip, *mqAgentOpt.port)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("MQ Agent failed to start: %v", err)
|
||||
}
|
||||
|
||||
+14
-24
@@ -18,20 +18,18 @@ var (
|
||||
)
|
||||
|
||||
type MessageQueueBrokerOptions struct {
|
||||
masters map[string]pb.ServerAddress
|
||||
mastersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
ipBind *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
dataCenter *string
|
||||
rack *string
|
||||
cpuprofile *string
|
||||
memprofile *string
|
||||
logFlushInterval *int
|
||||
debug *bool
|
||||
debugPort *int
|
||||
masters map[string]pb.ServerAddress
|
||||
mastersString *string
|
||||
filerGroup *string
|
||||
ip *string
|
||||
port *int
|
||||
dataCenter *string
|
||||
rack *string
|
||||
cpuprofile *string
|
||||
memprofile *string
|
||||
logFlushInterval *int
|
||||
debug *bool
|
||||
debugPort *int
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -39,7 +37,6 @@ func init() {
|
||||
mqBrokerStandaloneOptions.mastersString = cmdMqBroker.Flag.String("master", "localhost:9333", "comma-separated master servers")
|
||||
mqBrokerStandaloneOptions.filerGroup = cmdMqBroker.Flag.String("filerGroup", "", "share metadata with other filers in the same filerGroup")
|
||||
mqBrokerStandaloneOptions.ip = cmdMqBroker.Flag.String("ip", util.DetectedHostAddress(), "broker host address")
|
||||
mqBrokerStandaloneOptions.ipBind = cmdMqBroker.Flag.String("ip.bind", "", "ip address to bind to. If empty, listen on all interfaces.")
|
||||
mqBrokerStandaloneOptions.port = cmdMqBroker.Flag.Int("port", 17777, "broker gRPC listen port")
|
||||
mqBrokerStandaloneOptions.dataCenter = cmdMqBroker.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
|
||||
mqBrokerStandaloneOptions.rack = cmdMqBroker.Flag.String("rack", "", "prefer to write to volumes in this rack")
|
||||
@@ -97,15 +94,8 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
glog.Fatalf("failed to create new message broker for queue server: %v", err)
|
||||
}
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset.
|
||||
// An explicit -ip.bind pins the port to exactly that address.
|
||||
listenOnLocalhost := *mqBrokerOpt.ipBind == ""
|
||||
if mqBrokerOpt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *mqBrokerOpt.listenOnLocalhost
|
||||
}
|
||||
|
||||
// start grpc listener
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners(*mqBrokerOpt.ipBind, *mqBrokerOpt.port, 0, listenOnLocalhost)
|
||||
grpcL, localL, err := util.NewIpAndLocalListeners("", *mqBrokerOpt.port, 0)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", *mqBrokerOpt.port, err)
|
||||
}
|
||||
@@ -128,7 +118,7 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
}()
|
||||
}
|
||||
|
||||
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ipBind, *mqBrokerOpt.port)
|
||||
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ip, *mqBrokerOpt.port)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("Failed to serve MQ Broker: %v", err)
|
||||
}
|
||||
|
||||
+9
-16
@@ -46,7 +46,6 @@ type S3Options struct {
|
||||
filer *string
|
||||
ip *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
portHttps *int
|
||||
portGrpc *int
|
||||
@@ -360,12 +359,6 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
if *s3opt.portGrpc == 0 {
|
||||
*s3opt.portGrpc = 10000 + *s3opt.port
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset.
|
||||
// An explicit -ip.bind pins each port to exactly that address.
|
||||
listenOnLocalhost := *s3opt.bindIp == ""
|
||||
if s3opt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *s3opt.listenOnLocalhost
|
||||
}
|
||||
if *s3opt.bindIp == "" {
|
||||
*s3opt.bindIp = "0.0.0.0"
|
||||
}
|
||||
@@ -421,14 +414,14 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
// Start Iceberg REST Catalog server if enabled
|
||||
if *s3opt.portIceberg > 0 {
|
||||
if httpS := s3opt.startIcebergServer(s3ApiServer, listenOnLocalhost); httpS != nil {
|
||||
if httpS := s3opt.startIcebergServer(s3ApiServer); httpS != nil {
|
||||
httpServers = append(httpServers, httpS)
|
||||
}
|
||||
}
|
||||
|
||||
// Start Lance Namespace server if enabled
|
||||
if s3opt.portLance != nil && *s3opt.portLance > 0 {
|
||||
if httpS := s3opt.startLanceServer(s3ApiServer, listenOnLocalhost); httpS != nil {
|
||||
if httpS := s3opt.startLanceServer(s3ApiServer); httpS != nil {
|
||||
httpServers = append(httpServers, httpS)
|
||||
}
|
||||
}
|
||||
@@ -452,7 +445,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.port)
|
||||
s3ApiListener, s3ApiLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.port, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.port, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API Server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
@@ -466,7 +459,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
|
||||
// starting grpc server
|
||||
grpcPort := *s3opt.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*s3opt.bindIp, grpcPort, 0, listenOnLocalhost)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*s3opt.bindIp, grpcPort, 0)
|
||||
if err != nil {
|
||||
glog.Fatalf("s3 failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
@@ -539,7 +532,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
} else {
|
||||
glog.V(0).Infof("Start Seaweed S3 API Server %s at https port %d", version.Version(), *s3opt.portHttps)
|
||||
s3ApiListenerHttps, s3ApiLocalListenerHttps, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portHttps, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.portHttps, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API HTTPS listener on %s:%d error: %v", *s3opt.bindIp, *s3opt.portHttps, err)
|
||||
}
|
||||
@@ -599,7 +592,7 @@ func (s3opt *S3Options) newShutdown(stopGrpc func(), s3ApiServer *s3api.S3ApiSer
|
||||
}
|
||||
|
||||
// startIcebergServer starts the Iceberg REST Catalog server on a separate port.
|
||||
func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer, listenOnLocalhost bool) *http.Server {
|
||||
func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) *http.Server {
|
||||
icebergRouter := mux.NewRouter().SkipClean(true)
|
||||
// warehouse/parent query values may legally contain ';', which Go's
|
||||
// url.ParseQuery would otherwise drop
|
||||
@@ -621,7 +614,7 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer, liste
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portIceberg)
|
||||
icebergListener, icebergLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portIceberg, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.portIceberg, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
if err != nil {
|
||||
// The catalog is auxiliary to the S3 gateway; a port conflict must not
|
||||
// take the whole server down.
|
||||
@@ -652,7 +645,7 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer, liste
|
||||
// startLanceServer starts the Lance Namespace server on a separate port. It
|
||||
// shares the Iceberg catalog's credential role: one deployment vends table
|
||||
// credentials one way, whichever catalog the client speaks to.
|
||||
func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer, listenOnLocalhost bool) *http.Server {
|
||||
func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer) *http.Server {
|
||||
lanceRouter := mux.NewRouter().SkipClean(true)
|
||||
lanceRouter.Use(util_http.EscapeSemicolonsInQuery)
|
||||
|
||||
@@ -667,7 +660,7 @@ func (s3opt *S3Options) startLanceServer(s3ApiServer *s3api.S3ApiServer, listenO
|
||||
|
||||
listenAddress := fmt.Sprintf("%s:%d", *s3opt.bindIp, *s3opt.portLance)
|
||||
lanceListener, lanceLocalListener, err := util.NewIpAndLocalListeners(
|
||||
*s3opt.bindIp, *s3opt.portLance, time.Duration(*s3opt.idleTimeout)*time.Second, listenOnLocalhost)
|
||||
*s3opt.bindIp, *s3opt.portLance, time.Duration(*s3opt.idleTimeout)*time.Second)
|
||||
if err != nil {
|
||||
glog.Errorf("Lance Namespace listener on %s error: %v", listenAddress, err)
|
||||
return nil
|
||||
|
||||
@@ -42,14 +42,14 @@ func TestAuxListenerBindFailureIsNonFatal(t *testing.T) {
|
||||
}
|
||||
s3a := &s3api.S3ApiServer{}
|
||||
|
||||
if s := s3opt.startIcebergServer(s3a, false); s != nil {
|
||||
if s := s3opt.startIcebergServer(s3a); s != nil {
|
||||
s.Close()
|
||||
t.Error("startIcebergServer on an occupied port should return nil")
|
||||
}
|
||||
if s3opt.icebergBound.Load() {
|
||||
t.Error("icebergBound must stay false when the listener failed to bind")
|
||||
}
|
||||
if s := s3opt.startLanceServer(s3a, false); s != nil {
|
||||
if s := s3opt.startLanceServer(s3a); s != nil {
|
||||
s.Close()
|
||||
t.Error("startLanceServer on an occupied port should return nil")
|
||||
}
|
||||
|
||||
@@ -69,9 +69,6 @@
|
||||
# volume-slot deadband for shard placement: nodes whose free volume slots differ by at
|
||||
# most this much tie and fewer live shards wins; applied times data shards (0 = strict)
|
||||
# free_slots_deadband = 0
|
||||
# shard copy concurrency. Leave unset for one in-flight copy per destination disk.
|
||||
# 0 sends shards sequentially. A positive N is a global cap, still one per disk.
|
||||
# max_shard_transfers = 4
|
||||
# max retry attempts for a failed erasure coding job
|
||||
# retry_limit = 1
|
||||
# seconds to wait between retry attempts
|
||||
|
||||
+1
-38
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/grace"
|
||||
)
|
||||
|
||||
@@ -241,17 +240,6 @@ func init() {
|
||||
|
||||
}
|
||||
|
||||
// isServerFlagPassed checks if a specific flag was passed on the command line
|
||||
func isServerFlagPassed(name string) bool {
|
||||
found := false
|
||||
cmdServer.Flag.Visit(func(f *flag.Flag) {
|
||||
if f.Name == name {
|
||||
found = true
|
||||
}
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func runServer(cmd *Command, args []string) bool {
|
||||
|
||||
if *serverOptions.debug {
|
||||
@@ -305,11 +293,6 @@ func runServer(cmd *Command, args []string) bool {
|
||||
actualPeersForComponents = *masterOptions.peers
|
||||
}
|
||||
|
||||
// The loopback companion listener is only kept while -ip.bind is unset and
|
||||
// the bind address falls back to -ip. Capture that here: serverBindIp is
|
||||
// repointed at serverIp below, after which the flag state is no longer
|
||||
// distinguishable.
|
||||
ipBindUnspecified := *serverBindIp == ""
|
||||
if *serverBindIp == "" {
|
||||
serverBindIp = serverIp
|
||||
}
|
||||
@@ -324,51 +307,31 @@ func runServer(cmd *Command, args []string) bool {
|
||||
// ip address
|
||||
masterOptions.ip = serverIp
|
||||
masterOptions.ipBind = serverBindIp
|
||||
masterOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
// Use actualPeersForComponents for volume/filer, not masterOptions.peers which might be "none"
|
||||
filerOptions.masters = pb.ServerAddresses(actualPeersForComponents).ToServiceDiscovery()
|
||||
filerOptions.ip = serverIp
|
||||
filerOptions.bindIp = serverBindIp
|
||||
filerOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
s3Options.ip = serverIp
|
||||
if *s3Options.bindIp == "" {
|
||||
s3Options.listenOnLocalhost = &ipBindUnspecified
|
||||
s3Options.bindIp = serverBindIp
|
||||
}
|
||||
if sftpOptions.bindIp == nil || *sftpOptions.bindIp == "" {
|
||||
sftpOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
sftpOptions.bindIp = serverBindIp
|
||||
}
|
||||
iamOptions.ip = serverBindIp
|
||||
iamOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
iamOptions.masters = &actualPeersForComponents
|
||||
webdavOptions.ipBind = serverBindIp
|
||||
serverOptions.v.ip = serverIp
|
||||
serverOptions.v.bindIp = serverBindIp
|
||||
serverOptions.v.listenOnLocalhost = &ipBindUnspecified
|
||||
serverOptions.v.masters = pb.ServerAddresses(actualPeersForComponents).ToAddresses()
|
||||
serverOptions.v.idleConnectionTimeout = serverTimeout
|
||||
serverOptions.v.dataCenter = serverDataCenter
|
||||
serverOptions.v.rack = serverRack
|
||||
mqBrokerOptions.ip = serverIp
|
||||
mqBrokerOptions.ipBind = serverBindIp
|
||||
mqBrokerOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
mqBrokerOptions.masters = filerOptions.masters.GetInstancesAsMap()
|
||||
mqBrokerOptions.filerGroup = filerOptions.filerGroup
|
||||
mqAgentServerOptions.ip = serverIp
|
||||
mqAgentServerOptions.ipBind = serverBindIp
|
||||
mqAgentServerOptions.listenOnLocalhost = &ipBindUnspecified
|
||||
if isServerFlagPassed("mq.agent.brokers") {
|
||||
mqAgentServerOptions.brokers = pb.ServerAddresses(*mqAgentServerOptions.brokersString).ToAddresses()
|
||||
} else {
|
||||
// Default to the embedded broker's bind address: with an explicit
|
||||
// -ip.bind the broker does not listen on localhost.
|
||||
brokerHost := *serverBindIp
|
||||
if brokerHost == "0.0.0.0" || brokerHost == "::" || brokerHost == "[::]" {
|
||||
brokerHost = "localhost"
|
||||
}
|
||||
mqAgentServerOptions.brokers = []pb.ServerAddress{pb.NewServerAddress(brokerHost, *mqBrokerOptions.port, 0)}
|
||||
}
|
||||
mqAgentServerOptions.brokers = pb.ServerAddresses(*mqAgentServerOptions.brokersString).ToAddresses()
|
||||
|
||||
// serverOptions.v.pulseSeconds = pulseSeconds
|
||||
// masterOptions.pulseSeconds = pulseSeconds
|
||||
|
||||
@@ -25,7 +25,6 @@ var (
|
||||
type SftpOptions struct {
|
||||
filer *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
port *int
|
||||
sshPrivateKey *string
|
||||
hostKeysFolder *string
|
||||
@@ -106,12 +105,6 @@ func (sftpOpt *SftpOptions) resolvePaths() {
|
||||
}
|
||||
|
||||
func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
// The loopback companion listener is only kept while -ip.bind is unset.
|
||||
// An explicit -ip.bind pins the port to exactly that address.
|
||||
listenOnLocalhost := *sftpOpt.bindIp == ""
|
||||
if sftpOpt.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *sftpOpt.listenOnLocalhost
|
||||
}
|
||||
if *sftpOpt.bindIp == "" {
|
||||
*sftpOpt.bindIp = "0.0.0.0"
|
||||
}
|
||||
@@ -201,7 +194,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
|
||||
// Start the SFTP service on TCP
|
||||
listenAddress := fmt.Sprintf("%s:%d", *sftpOpt.bindIp, *sftpOpt.port)
|
||||
sftpListener, sftpLocalListener, err := util.NewIpAndLocalListeners(*sftpOpt.bindIp, *sftpOpt.port, time.Duration(10)*time.Second, listenOnLocalhost)
|
||||
sftpListener, sftpLocalListener, err := util.NewIpAndLocalListeners(*sftpOpt.bindIp, *sftpOpt.port, time.Duration(10)*time.Second)
|
||||
if err != nil {
|
||||
glog.Fatalf("SFTP server listener on %s error: %v", listenAddress, err)
|
||||
}
|
||||
|
||||
+9
-17
@@ -45,7 +45,6 @@ type VolumeServerOptions struct {
|
||||
id *string
|
||||
publicUrl *string
|
||||
bindIp *string
|
||||
listenOnLocalhost *bool
|
||||
mastersString *string
|
||||
mserverString *string // deprecated, for backward compatibility
|
||||
masters []pb.ServerAddress
|
||||
@@ -398,13 +397,6 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
*v.ip = util.DetectedHostAddress()
|
||||
glog.V(0).Infof("detected volume server ip address: %v", *v.ip)
|
||||
}
|
||||
// The loopback companion listener is only kept while -ip.bind is unset
|
||||
// and the bind address falls back to -ip. An explicit -ip.bind pins each
|
||||
// port to exactly that address.
|
||||
listenOnLocalhost := *v.bindIp == ""
|
||||
if v.listenOnLocalhost != nil {
|
||||
listenOnLocalhost = *v.listenOnLocalhost
|
||||
}
|
||||
if *v.bindIp == "" {
|
||||
*v.bindIp = *v.ip
|
||||
}
|
||||
@@ -493,19 +485,19 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
v.syncBatchOption(),
|
||||
)
|
||||
// starting grpc server
|
||||
grpcS := v.startGrpcService(volumeServer, listenOnLocalhost)
|
||||
grpcS := v.startGrpcService(volumeServer)
|
||||
|
||||
// starting public http server
|
||||
var publicHttpDown httpdown.Server
|
||||
if v.isSeparatedPublicPort() {
|
||||
publicHttpDown = v.startPublicHttpService(publicVolumeMux, listenOnLocalhost)
|
||||
publicHttpDown = v.startPublicHttpService(publicVolumeMux)
|
||||
if nil == publicHttpDown {
|
||||
glog.Fatalf("start public http service failed")
|
||||
}
|
||||
}
|
||||
|
||||
// starting the cluster http server
|
||||
clusterHttpServer, closeCert := v.startClusterHttpService(volumeMux, listenOnLocalhost)
|
||||
clusterHttpServer, closeCert := v.startClusterHttpService(volumeMux)
|
||||
|
||||
grace.OnReload(volumeServer.LoadNewVolumes)
|
||||
grace.OnReload(volumeServer.Reload)
|
||||
@@ -640,9 +632,9 @@ func (m multiHttpdownServer) Stop() error {
|
||||
return firstErr
|
||||
}
|
||||
|
||||
func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer, listenOnLocalhost bool) *grpc.Server {
|
||||
func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerServer) *grpc.Server {
|
||||
grpcPort := *v.portGrpc
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*v.bindIp, grpcPort, 0, listenOnLocalhost)
|
||||
grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*v.bindIp, grpcPort, 0)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
@@ -661,10 +653,10 @@ func (v VolumeServerOptions) startGrpcService(vs volume_server_pb.VolumeServerSe
|
||||
return grpcS
|
||||
}
|
||||
|
||||
func (v VolumeServerOptions) startPublicHttpService(handler http.Handler, listenOnLocalhost bool) httpdown.Server {
|
||||
func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdown.Server {
|
||||
publicListeningAddress := util.JoinHostPort(*v.bindIp, *v.publicPort)
|
||||
glog.V(0).Infoln("Start Seaweed volume server", version.Version(), "public at", publicListeningAddress)
|
||||
publicListener, publicLocalListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.publicPort, time.Duration(*v.idleConnectionTimeout)*time.Second, listenOnLocalhost)
|
||||
publicListener, publicLocalListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.publicPort, time.Duration(*v.idleConnectionTimeout)*time.Second)
|
||||
if e != nil {
|
||||
glog.Fatalf("Volume server listener error:%v", e)
|
||||
}
|
||||
@@ -689,7 +681,7 @@ func (v VolumeServerOptions) startPublicHttpService(handler http.Handler, listen
|
||||
// for invoking the close func on every shutdown path — both the
|
||||
// SIGTERM/grace.OnInterrupt path and the shutdownCtx path used by
|
||||
// mini/integration tests.
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler, listenOnLocalhost bool) (httpdown.Server, func()) {
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) (httpdown.Server, func()) {
|
||||
var (
|
||||
certFile, keyFile string
|
||||
)
|
||||
@@ -700,7 +692,7 @@ func (v VolumeServerOptions) startClusterHttpService(handler http.Handler, liste
|
||||
|
||||
listeningAddress := util.JoinHostPort(*v.bindIp, *v.port)
|
||||
glog.V(0).Infof("Start Seaweed volume server %s at %s", version.Version(), listeningAddress)
|
||||
listener, localListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.port, time.Duration(*v.idleConnectionTimeout)*time.Second, listenOnLocalhost)
|
||||
listener, localListener, e := util.NewIpAndLocalListeners(*v.bindIp, *v.port, time.Duration(*v.idleConnectionTimeout)*time.Second)
|
||||
if e != nil {
|
||||
glog.Fatalf("Volume server listener error:%v", e)
|
||||
}
|
||||
|
||||
@@ -48,9 +48,6 @@ 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 {
|
||||
@@ -79,8 +76,6 @@ 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
|
||||
}
|
||||
@@ -114,7 +109,6 @@ 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) {
|
||||
@@ -128,7 +122,6 @@ 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 {
|
||||
|
||||
+9
-26
@@ -115,6 +115,12 @@ 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.
|
||||
@@ -477,20 +483,8 @@ 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 {
|
||||
@@ -523,8 +517,6 @@ 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)
|
||||
@@ -536,7 +528,6 @@ 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)
|
||||
|
||||
@@ -601,18 +592,16 @@ 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 {
|
||||
f.releaseEntryCommitTsNs(dirEntry.CommitTsNs)
|
||||
if !strings.HasPrefix("/"+util.Join(dirParts[:]...), SystemLogDir) {
|
||||
f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
|
||||
}
|
||||
}
|
||||
|
||||
} else if !dirEntry.IsDirectory() {
|
||||
@@ -632,9 +621,7 @@ 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)
|
||||
@@ -686,9 +673,7 @@ 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)
|
||||
@@ -713,9 +698,7 @@ 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,11 +136,9 @@ 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
|
||||
@@ -230,9 +228,7 @@ 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,8 +29,6 @@ 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
|
||||
}
|
||||
|
||||
@@ -46,10 +44,6 @@ 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
|
||||
@@ -62,7 +56,7 @@ func (f *Filer) notifyUpdateEvent(ctx context.Context, oldEntry, newEntry *Entry
|
||||
signatures = append(signatures, f.Signature)
|
||||
}
|
||||
|
||||
event := f.newMetadataEvent(oldEntry, newEntry, deleteChunks, isFromOtherCluster, signatures, f.stampOf(newEntry))
|
||||
event := f.newMetadataEvent(oldEntry, newEntry, deleteChunks, isFromOtherCluster, signatures)
|
||||
// Clear the stamp after the buffer append below - deliberately also on
|
||||
// append failure (see the metaLogInflight comment).
|
||||
defer f.metaLogInflight.done(event.TsNs)
|
||||
@@ -77,6 +71,10 @@ 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)
|
||||
}
|
||||
@@ -136,28 +134,6 @@ 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()
|
||||
@@ -221,41 +197,7 @@ func (f *Filer) DoneMetaLogInflightForTest(tsNs int64) {
|
||||
f.metaLogInflight.done(tsNs)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
func (f *Filer) newMetadataEvent(oldEntry, newEntry *Entry, deleteChunks, isFromOtherCluster bool, signatures []int32) *filer_pb.SubscribeMetadataResponse {
|
||||
if oldEntry == nil && newEntry == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -282,7 +224,7 @@ func (f *Filer) newMetadataEvent(oldEntry, newEntry *Entry, deleteChunks, isFrom
|
||||
Signatures: signatures,
|
||||
},
|
||||
// In flight until appended to the local log buffer (see metaLogInflight).
|
||||
TsNs: tsNs,
|
||||
TsNs: f.metaLogInflight.stamp(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -754,8 +754,10 @@ func (ma *MetaAggregator) traversePeerMetadata(ctx context.Context, f *Filer, pe
|
||||
continue
|
||||
}
|
||||
entry := FromPbEntry(resp.Directory, resp.Entry)
|
||||
// Order on the sender's commit timestamp, not client-settable
|
||||
// mtime. Peers predating the field send 0: fall back to mtime.
|
||||
// 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.
|
||||
peerTsNs := resp.EntryTsNs
|
||||
if peerTsNs == 0 {
|
||||
peerTsNs = entry.Attr.Mtime.UnixNano()
|
||||
@@ -774,9 +776,10 @@ 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.
|
||||
// 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.
|
||||
// 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.
|
||||
func (f *Filer) applyTraversedEntry(ctx context.Context, entry *Entry, peerTsNs int64) error {
|
||||
unlock := f.lockReplayPaths(entry.FullPath, "")
|
||||
defer unlock()
|
||||
@@ -802,7 +805,6 @@ 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.
|
||||
@@ -813,6 +815,7 @@ 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,7 +18,6 @@ import (
|
||||
)
|
||||
|
||||
// newReplayTestFiler builds the minimum Filer Replay needs over a stub store.
|
||||
|
||||
func newReplayTestFiler(store FilerStore) *Filer {
|
||||
return &Filer{
|
||||
Store: NewFilerStoreWrapper(store),
|
||||
@@ -260,6 +259,58 @@ 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
|
||||
@@ -273,9 +324,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",
|
||||
@@ -321,9 +372,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 entry's commit stamp and skips.
|
||||
// sees the recorded commit and skips.
|
||||
held := f.EntryLockTable.AcquireLock("test local write", path, util.ExclusiveLock)
|
||||
store.entries[string(path)].CommitTsNs = now.UnixNano()
|
||||
f.notePathChange(path, now.UnixNano(), false)
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
@@ -370,6 +421,18 @@ 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
|
||||
@@ -381,6 +444,7 @@ 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",
|
||||
@@ -402,9 +466,32 @@ func TestReplaySerializesWithAncestorLock(t *testing.T) {
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("Replay: %v", err)
|
||||
}
|
||||
// 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)
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,11 +555,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"),
|
||||
CommitTsNs: now.Add(-time.Minute).UnixNano(),
|
||||
FullPath: path,
|
||||
Attr: Attr{Mtime: now.Add(time.Hour)}, // future mtime, e.g. client-set
|
||||
Content: []byte("old local write"),
|
||||
}
|
||||
f.notePathChange(path, now.Add(-time.Minute).UnixNano(), false)
|
||||
|
||||
entry := &Entry{
|
||||
FullPath: path,
|
||||
@@ -525,23 +612,139 @@ func TestBootstrapCopiesMissingEntryWithoutCommitTime(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) {
|
||||
// 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) {
|
||||
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 entry: CommitTsNs = %d, %v; want fallback 7", got, err)
|
||||
t.Fatalf("no record: CommitTsNs = %d, %v; want fallback 7", got, err)
|
||||
}
|
||||
store.entries[string(path)] = &Entry{FullPath: path, CommitTsNs: 50}
|
||||
f.notePathChange(path, 50, false)
|
||||
if got, err := f.CommitTsNs(context.Background(), path, 7); err != nil || got != 50 {
|
||||
t.Fatalf("stamped: CommitTsNs = %d, %v; want 50", got, err)
|
||||
t.Fatalf("recorded: CommitTsNs = %d, %v; want 50", got, 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -703,10 +906,9 @@ func TestReplayDirectoryDeleteKeepsNewerChildren(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) {
|
||||
// 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) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
@@ -750,8 +952,8 @@ func TestReplayKeptDirectoryDeleteAllowsStaleCreates(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"); err != nil {
|
||||
t.Fatalf("no tombstone exists, so the stale create lands: %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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1367,45 +1569,3 @@ 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)
|
||||
}
|
||||
}
|
||||
+234
-73
@@ -5,28 +5,35 @@ import (
|
||||
"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 the per-path commit timestamps older builds
|
||||
// wrote into the store KV for every mutation and kept after the entry
|
||||
// was deleted. They are no longer written — ordering lives on the
|
||||
// entry's CommitTsNs — but records left behind by an upgrade still
|
||||
// fence replayed events older than the change they recorded.
|
||||
// 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 the delete timestamps those builds kept. The
|
||||
// replay check consults the path's ancestors too, so a directory's
|
||||
// retained delete record covers children deleted without per-child
|
||||
// events.
|
||||
// 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 the fixed-size key the writing builds
|
||||
// used: SQL stores split the key at byte 8 and base64 the rest into a
|
||||
// bounded name column, which a raw path can overflow.
|
||||
// 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)
|
||||
@@ -52,65 +59,212 @@ func (f *Filer) kvReadTsNs(ctx context.Context, key []byte) (tsNs int64, found b
|
||||
return int64(util.BytesToUint64(value)), true, nil
|
||||
}
|
||||
|
||||
// CommitTsNs resolves the commit timestamp at path for traversal: the
|
||||
// entry's stamp, else fallbackTsNs for pre-stamp or missing entries.
|
||||
// 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.
|
||||
func (f *Filer) CommitTsNs(ctx context.Context, path util.FullPath, fallbackTsNs int64) (int64, error) {
|
||||
if f.Store == nil {
|
||||
return fallbackTsNs, nil
|
||||
}
|
||||
entry, err := f.Store.FindEntry(ctx, path)
|
||||
if err != nil {
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return f.retainedCommitTsNs(ctx, path, fallbackTsNs)
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
if entry == nil {
|
||||
return f.retainedCommitTsNs(ctx, path, fallbackTsNs)
|
||||
}
|
||||
return f.EntryCommitTsNs(ctx, entry, fallbackTsNs)
|
||||
}
|
||||
|
||||
// EntryCommitTsNs returns the newest commit time known for an already-loaded
|
||||
// entry: its stamp, a retained per-path record left by an older build —
|
||||
// which can outdate a replayed peer stamp — else fallbackTsNs.
|
||||
func (f *Filer) EntryCommitTsNs(ctx context.Context, entry *Entry, fallbackTsNs int64) (int64, error) {
|
||||
tsNs := entry.CommitTsNs
|
||||
if f.Store == nil {
|
||||
if tsNs == 0 {
|
||||
return fallbackTsNs, nil
|
||||
}
|
||||
return tsNs, nil
|
||||
}
|
||||
recTs, found, err := f.kvReadTsNs(ctx, metaPathKey(metaPathTsPrefix, entry.FullPath))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if found && recTs > tsNs {
|
||||
tsNs = recTs
|
||||
}
|
||||
if tsNs == 0 {
|
||||
return fallbackTsNs, nil
|
||||
}
|
||||
return tsNs, nil
|
||||
}
|
||||
|
||||
// retainedCommitTsNs reads the per-path record an older build may have left
|
||||
// for a path that has no entry now — a delete under the recording builds
|
||||
// kept its change record past the entry's removal.
|
||||
func (f *Filer) retainedCommitTsNs(ctx context.Context, path util.FullPath, fallbackTsNs int64) (int64, error) {
|
||||
tsNs := fallbackTsNs
|
||||
recTs, found, err := f.kvReadTsNs(ctx, metaPathKey(metaPathTsPrefix, path))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if found {
|
||||
return recTs, nil
|
||||
tsNs = recTs
|
||||
}
|
||||
return fallbackTsNs, nil
|
||||
if pendTs, _ := f.pendingPathTsNs(path); pendTs > tsNs {
|
||||
tsNs = pendTs
|
||||
}
|
||||
return tsNs, nil
|
||||
}
|
||||
|
||||
// deletedAfterTsNs returns the newest retained delete record among path and
|
||||
// its ancestors.
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 != "/"; {
|
||||
@@ -121,6 +275,9 @@ func (f *Filer) deletedAfterTsNs(ctx context.Context, path util.FullPath) (int64
|
||||
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
|
||||
@@ -130,28 +287,32 @@ func (f *Filer) deletedAfterTsNs(ctx context.Context, path util.FullPath) (int64
|
||||
return tsNs, nil
|
||||
}
|
||||
|
||||
// localCommitTsNs returns this filer's newest known commit time for path:
|
||||
// the entry's stamp — not client-controllable like mtime — else mtime, plus
|
||||
// any retained change or delete record an older build left for the path or
|
||||
// its ancestors.
|
||||
// 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.
|
||||
func (f *Filer) localCommitTsNs(ctx context.Context, path util.FullPath) (int64, error) {
|
||||
if f.Store == nil {
|
||||
return 0, nil
|
||||
}
|
||||
var tsNs int64
|
||||
entry, err := f.Store.FindEntry(ctx, path)
|
||||
recTs, found, err := f.kvReadTsNs(ctx, metaPathKey(metaPathTsPrefix, path))
|
||||
if err != nil {
|
||||
if !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if entry == nil {
|
||||
if tsNs, err = f.retainedCommitTsNs(ctx, path, 0); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
} else if tsNs, err = f.EntryCommitTsNs(ctx, entry, entry.Mtime.UnixNano()); 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
|
||||
}
|
||||
} 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
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"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)
|
||||
}
|
||||
}
|
||||
|
||||
// putRecord seeds the per-path key an older build would have left.
|
||||
func putRecord(t *testing.T, store *stubFilerStore, prefix string, path util.FullPath, tsNs int64) {
|
||||
t.Helper()
|
||||
value := make([]byte, 8)
|
||||
util.Uint64toBytes(value, uint64(tsNs))
|
||||
if err := store.KvPut(context.Background(), metaPathKey(prefix, path), value); err != nil {
|
||||
t.Fatalf("seed record %s%s: %v", prefix, path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A retained change record still orders a path whose entry is gone: a
|
||||
// replayed create older than the record must not resurrect it.
|
||||
func TestRetainedChangeRecordFencesMissingEntry(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
putRecord(t, store, metaPathTsPrefix, "/dir/file", 300)
|
||||
|
||||
if newer, err := f.replayBlockedByLocal(ctx, "/dir/file", 200); err != nil || !newer {
|
||||
t.Fatalf("event at 200 should lose to retained record at 300: newer=%v err=%v", newer, err)
|
||||
}
|
||||
if newer, err := f.replayBlockedByLocal(ctx, "/dir/file", 400); err != nil || newer {
|
||||
t.Fatalf("event at 400 should win over retained record at 300: newer=%v err=%v", newer, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A directory's retained delete record covers children removed without
|
||||
// per-child records — the replay check walks the ancestors.
|
||||
func TestRetainedAncestorDeleteRecordFencesChild(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
putRecord(t, store, metaPathDelPrefix, "/dir", 300)
|
||||
|
||||
if newer, err := f.replayBlockedByLocal(ctx, "/dir/sub/file", 200); err != nil || !newer {
|
||||
t.Fatalf("child event at 200 should lose to ancestor delete at 300: newer=%v err=%v", newer, err)
|
||||
}
|
||||
if newer, err := f.replayBlockedByLocal(ctx, "/dir/sub/file", 400); err != nil || newer {
|
||||
t.Fatalf("child event at 400 should win over ancestor delete at 300: newer=%v err=%v", newer, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The retained record orders the entry, not its client-settable mtime: a
|
||||
// mounted client can push mtime into the future, and the record must not
|
||||
// let that silence newer replayed events.
|
||||
func TestRetainedRecordOrdersUnstampedEntry(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
path := util.FullPath("/dir/file")
|
||||
putRecord(t, store, metaPathTsPrefix, path, 300)
|
||||
store.entries[string(path)] = &Entry{
|
||||
FullPath: path,
|
||||
Attr: Attr{Mtime: time.Unix(0, 999)},
|
||||
}
|
||||
|
||||
if tsNs, err := f.localCommitTsNs(ctx, path); err != nil || tsNs != 300 {
|
||||
t.Fatalf("localCommitTsNs = %d,%v; want the record's 300, not the entry's mtime", tsNs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// An entry stamped under the current build outranks any record an older
|
||||
// build left: the stamp is the newest commit.
|
||||
func TestEntryStampBeatsRetainedRecord(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
path := util.FullPath("/dir/file")
|
||||
putRecord(t, store, metaPathTsPrefix, path, 300)
|
||||
store.entries[string(path)] = &Entry{FullPath: path, CommitTsNs: 400}
|
||||
|
||||
if tsNs, err := f.localCommitTsNs(ctx, path); err != nil || tsNs != 400 {
|
||||
t.Fatalf("localCommitTsNs = %d,%v; want the entry stamp's 400", tsNs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// End to end: a replayed create older than a retained delete record leaves
|
||||
// the path absent.
|
||||
func TestReplayCreateBlockedByRetainedDelete(t *testing.T) {
|
||||
store := newStubFilerStore()
|
||||
f := newReplayTestFiler(store)
|
||||
ctx := context.Background()
|
||||
putRecord(t, store, metaPathDelPrefix, "/dir/file", 300)
|
||||
|
||||
event := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{Name: "file", Content: []byte("resurrected")},
|
||||
},
|
||||
TsNs: 200,
|
||||
}
|
||||
if err := f.Replay(event); err != nil {
|
||||
t.Fatalf("Replay: %v", err)
|
||||
}
|
||||
if _, err := store.FindEntry(ctx, "/dir/file"); err == nil {
|
||||
t.Fatal("replayed create at 200 must not resurrect a path deleted at 300")
|
||||
}
|
||||
}
|
||||
+28
-76
@@ -23,14 +23,12 @@ import (
|
||||
// only when no newer local change is recorded, so a late event cannot revert
|
||||
// or resurrect entries.
|
||||
//
|
||||
// Ordering uses the commit timestamp stamped on the entry by its mutation
|
||||
// event (meta_path_ts.go), which is not client-controllable the way entry
|
||||
// mtime is — a mounted client can set mtime into the future, and a rename
|
||||
// keeps the source file's mtime on the destination entry. Entries written
|
||||
// before stamping existed fall back to their mtime, except where a
|
||||
// per-path record left by an older build remains: a retained change or
|
||||
// delete record outlives the entry it ordered, so a stale replayed event
|
||||
// cannot resurrect a path whose removal the record still covers.
|
||||
// Ordering uses the per-path commit timestamp recorded for every emitted
|
||||
// mutation (meta_path_ts.go), which survives deletes as a tombstone and is
|
||||
// not client-controllable the way entry mtime is — a mounted client can set
|
||||
// mtime into the future, and a rename keeps the source file's mtime on the
|
||||
// destination entry. Entries written before recording existed fall back to
|
||||
// their mtime.
|
||||
//
|
||||
// The check and the mutation run under the same per-path entry lock the
|
||||
// filer server's local writes hold, so they cannot be split by a concurrent
|
||||
@@ -59,20 +57,21 @@ 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
|
||||
}
|
||||
|
||||
@@ -99,6 +98,10 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,68 +113,16 @@ 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 —
|
||||
@@ -312,6 +263,7 @@ 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
|
||||
@@ -342,19 +294,19 @@ func (f *Filer) replayBlockedByLocal(ctx context.Context, path util.FullPath, ts
|
||||
return localTsNs > tsNs, nil
|
||||
}
|
||||
|
||||
// lockReplayPaths holds the shared entry locks for every path the event
|
||||
// touches, in the same sorted order the rename handler takes them.
|
||||
// lockReplayPaths takes the per-path entry locks for the event's paths and
|
||||
// every ancestor of them, in lexicographic order — parents sort before
|
||||
// children, the same ordering the local rename handler's two-path lock uses,
|
||||
// so lock acquisition is deadlock-free across operations. Ancestors are
|
||||
// included because the replay check consults ancestor state — a retained
|
||||
// delete record an older build left, or the ancestor entry itself: a local
|
||||
// recursive delete or directory rename holds only the ancestor's lock, and
|
||||
// without contending on it a replay could reinsert a stale child into a
|
||||
// subtree being deleted after its check. Ancestors are locked shared —
|
||||
// they only need to exclude an exclusive holder, not each other, or every
|
||||
// replay under a busy parent would serialize — while a path the event
|
||||
// actually changes stays exclusive even when it is also the other path's
|
||||
// ancestor. The root is never locked:
|
||||
// included because the replay check consults ancestor delete records: a
|
||||
// local recursive delete or directory rename holds only the ancestor's lock,
|
||||
// and without contending on it a replay could reinsert a stale child after
|
||||
// its check. Ancestors are locked shared — they only need to exclude an
|
||||
// exclusive holder, not each other, or every replay under a busy parent
|
||||
// would serialize — while a path the event actually changes stays exclusive
|
||||
// even when it is also the other path's ancestor. The root is never locked:
|
||||
// it cannot be deleted, and a shared root lock would still be excluded by
|
||||
// every top-level delete.
|
||||
func (f *Filer) lockReplayPaths(oldPath, newPath util.FullPath) func() {
|
||||
|
||||
@@ -53,9 +53,12 @@ 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.
|
||||
// oidcManagedProviders caches the provider built per stored record so a
|
||||
// refresh reuses unchanged providers and keeps their JWKS cache.
|
||||
oidcRefreshMu sync.Mutex
|
||||
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 map[string]*oidcManagedProvider
|
||||
oidcAuditSink OIDCProviderAuditSink
|
||||
revocationStore SessionRevocationStore
|
||||
@@ -950,6 +953,10 @@ 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
|
||||
@@ -960,10 +967,25 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
fingerprint := oidcProviderFingerprint(rec)
|
||||
cached := m.oidcManagedProviders[key]
|
||||
configFingerprint := oidcProviderConfigFingerprint(rec)
|
||||
var provider *oidc.OIDCProvider
|
||||
if cached != nil && cached.fingerprint == fingerprint {
|
||||
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 {
|
||||
provider = cached.provider
|
||||
sharedProviders[configFingerprint] = provider
|
||||
} else {
|
||||
var err error
|
||||
provider, err = buildOIDCProviderFromRecord(rec)
|
||||
@@ -972,7 +994,20 @@ 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
|
||||
@@ -982,9 +1017,16 @@ func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCPro
|
||||
Provider: provider,
|
||||
})
|
||||
}
|
||||
for key := range m.oidcManagedProviders {
|
||||
for key, managed := 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)
|
||||
@@ -998,6 +1040,17 @@ 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 {
|
||||
@@ -1014,6 +1067,21 @@ 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,47 +560,92 @@ 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 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()}
|
||||
// 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()
|
||||
mgr := startServer(t, store)
|
||||
|
||||
arn := arnOf(t, persistTestAPIIssuer)
|
||||
createAPIProvider(t, mgr, 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)
|
||||
|
||||
mgr.oidcRefreshMu.Lock()
|
||||
before := mgr.oidcManagedProviders[arn]
|
||||
mgr.oidcRefreshMu.Unlock()
|
||||
require.NotNil(t, before)
|
||||
require.NoError(t, mgr.refreshOIDCProvidersFrom(ctx, store))
|
||||
assert.Same(t, first, mgr.oidcManagedProviders[arn].provider,
|
||||
"an unchanged record was rebuilt, dropping its replay cache")
|
||||
|
||||
createAPIProvider(t, mgr, persistTestStaticIssuer) // refreshes over an unrelated record
|
||||
// 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")
|
||||
|
||||
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")
|
||||
// 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))
|
||||
}
|
||||
|
||||
// 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()}
|
||||
// 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()
|
||||
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"))
|
||||
|
||||
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")
|
||||
// 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"))
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
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,6 +75,17 @@ 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,7 +27,20 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
)
|
||||
|
||||
// OIDCProvider implements OpenID Connect authentication
|
||||
// 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.
|
||||
type OIDCProvider struct {
|
||||
name string
|
||||
config *OIDCConfig
|
||||
@@ -44,6 +57,25 @@ 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
|
||||
@@ -107,6 +139,13 @@ 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
|
||||
@@ -319,6 +358,7 @@ func NewOIDCProvider(name string) *OIDCProvider {
|
||||
return &OIDCProvider{
|
||||
name: name,
|
||||
httpClient: &http.Client{Timeout: 30 * time.Second, CheckRedirect: refuseDowngradeRedirect},
|
||||
jti: newJTIReplayCache(name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,9 +462,6 @@ 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,
|
||||
@@ -432,6 +469,17 @@ 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
|
||||
}
|
||||
@@ -482,6 +530,18 @@ 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")
|
||||
}
|
||||
@@ -491,7 +551,7 @@ func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*provide
|
||||
}
|
||||
|
||||
// Validate token and get claims
|
||||
claims, err := p.ValidateToken(ctx, token)
|
||||
claims, err := p.validateToken(ctx, token, singleUse)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -658,6 +718,16 @@ 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")
|
||||
}
|
||||
@@ -684,8 +754,7 @@ func (p *OIDCProvider) ValidateToken(ctx context.Context, token string) (*provid
|
||||
return nil, fmt.Errorf("failed to get public key: %v", err)
|
||||
}
|
||||
|
||||
// Parse and validate token with proper signature verification. exp is
|
||||
// required: without it a leaked token could mint STS sessions forever.
|
||||
// Parse and validate token with proper signature verification
|
||||
claims := jwt.MapClaims{}
|
||||
validatedToken, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
// Verify signing method
|
||||
@@ -695,7 +764,7 @@ func (p *OIDCProvider) ValidateToken(ctx context.Context, token string) (*provid
|
||||
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
|
||||
@@ -791,6 +860,16 @@ func (p *OIDCProvider) ValidateToken(ctx context.Context, token string) (*provid
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1219,3 +1298,36 @@ 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())
|
||||
}
|
||||
+1080
-24
File diff suppressed because it is too large.
Load diff
@@ -19,4 +19,7 @@ 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")
|
||||
)
|
||||
+17
-15
@@ -42,21 +42,23 @@ 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"
|
||||
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"
|
||||
)
|
||||
|
||||
// Error Messages
|
||||
|
||||
@@ -103,3 +103,51 @@ 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,6 +1,7 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -154,6 +155,21 @@ 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)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
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,8 +522,35 @@ 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
|
||||
@@ -597,7 +624,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)
|
||||
externalIdentity, provider, err := s.validateWebIdentityToken(ctx, request.WebIdentityToken, roleAccountID, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to validate web identity token: %w", err)
|
||||
}
|
||||
@@ -1002,7 +1029,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) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
func (s *STSService) validateWebIdentityToken(ctx context.Context, token, roleAccountID string, singleUse bool) (*providers.ExternalIdentity, providers.IdentityProvider, error) {
|
||||
// Try to extract issuer from JWT token for strict validation
|
||||
issuer, err := s.extractIssuerFromJWT(token)
|
||||
if err != nil {
|
||||
@@ -1025,8 +1052,10 @@ 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
|
||||
identity, err := provider.Authenticate(ctx, token)
|
||||
// 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)
|
||||
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
|
||||
@@ -1058,14 +1087,29 @@ 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, "")
|
||||
return s.validateWebIdentityToken(ctx, token, "", false)
|
||||
}
|
||||
|
||||
// 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)
|
||||
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)
|
||||
}
|
||||
|
||||
// extractIssuerFromJWT extracts the issuer (iss) claim from a JWT token without verification
|
||||
|
||||
@@ -166,10 +166,6 @@ 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,22 +672,18 @@ 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"`
|
||||
// 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"`
|
||||
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"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -757,13 +753,6 @@ 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
|
||||
@@ -7311,7 +7300,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\"\xab\x04\n" +
|
||||
"\x18_remote_content_encoding\"\x89\x04\n" +
|
||||
"\x05Entry\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12!\n" +
|
||||
"\fis_directory\x18\x02 \x01(\bR\visDirectory\x12+\n" +
|
||||
@@ -7320,8 +7309,6 @@ 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,11 +389,6 @@ 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]
|
||||
@@ -6707,9 +6702,6 @@ 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))
|
||||
@@ -10238,25 +10230,6 @@ 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)
|
||||
|
||||
@@ -382,7 +382,6 @@ message ErasureCodingTaskConfig {
|
||||
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
bool strict_placement = 7; // fail planning instead of relaxing placement constraints
|
||||
int32 free_slots_deadband = 8; // Place free-volume-slot deadband; |ΔfreeSlots| ≤ M×dataShards ranks by liveShards; 0 = strict
|
||||
optional int32 max_shard_transfers = 9; // unset = no global cap (one in-flight per dest disk); 0 = sequential; N>0 = global cap
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
|
||||
@@ -2974,15 +2974,14 @@ func (x *VacuumTaskConfig) GetMinIntervalSeconds() int32 {
|
||||
// ErasureCodingTaskConfig contains EC-specific configuration
|
||||
type ErasureCodingTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
FullnessRatio float64 `protobuf:"fixed64,1,opt,name=fullness_ratio,json=fullnessRatio,proto3" json:"fullness_ratio,omitempty"` // Minimum fullness ratio to trigger EC (0.0-1.0)
|
||||
QuietForSeconds int32 `protobuf:"varint,2,opt,name=quiet_for_seconds,json=quietForSeconds,proto3" json:"quiet_for_seconds,omitempty"` // Minimum quiet time before EC
|
||||
MinVolumeSizeMb int32 `protobuf:"varint,3,opt,name=min_volume_size_mb,json=minVolumeSizeMb,proto3" json:"min_volume_size_mb,omitempty"` // Minimum volume size for EC
|
||||
CollectionFilter string `protobuf:"bytes,4,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Only process volumes from specific collections
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Disk tags to prioritize for EC shard placement
|
||||
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
StrictPlacement bool `protobuf:"varint,7,opt,name=strict_placement,json=strictPlacement,proto3" json:"strict_placement,omitempty"` // fail planning instead of relaxing placement constraints
|
||||
FreeSlotsDeadband int32 `protobuf:"varint,8,opt,name=free_slots_deadband,json=freeSlotsDeadband,proto3" json:"free_slots_deadband,omitempty"` // Place free-volume-slot deadband; |ΔfreeSlots| ≤ M×dataShards ranks by liveShards; 0 = strict
|
||||
MaxShardTransfers *int32 `protobuf:"varint,9,opt,name=max_shard_transfers,json=maxShardTransfers,proto3,oneof" json:"max_shard_transfers,omitempty"` // unset = no global cap (one in-flight per dest disk); 0 = sequential; N>0 = global cap
|
||||
FullnessRatio float64 `protobuf:"fixed64,1,opt,name=fullness_ratio,json=fullnessRatio,proto3" json:"fullness_ratio,omitempty"` // Minimum fullness ratio to trigger EC (0.0-1.0)
|
||||
QuietForSeconds int32 `protobuf:"varint,2,opt,name=quiet_for_seconds,json=quietForSeconds,proto3" json:"quiet_for_seconds,omitempty"` // Minimum quiet time before EC
|
||||
MinVolumeSizeMb int32 `protobuf:"varint,3,opt,name=min_volume_size_mb,json=minVolumeSizeMb,proto3" json:"min_volume_size_mb,omitempty"` // Minimum volume size for EC
|
||||
CollectionFilter string `protobuf:"bytes,4,opt,name=collection_filter,json=collectionFilter,proto3" json:"collection_filter,omitempty"` // Only process volumes from specific collections
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Disk tags to prioritize for EC shard placement
|
||||
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
StrictPlacement bool `protobuf:"varint,7,opt,name=strict_placement,json=strictPlacement,proto3" json:"strict_placement,omitempty"` // fail planning instead of relaxing placement constraints
|
||||
FreeSlotsDeadband int32 `protobuf:"varint,8,opt,name=free_slots_deadband,json=freeSlotsDeadband,proto3" json:"free_slots_deadband,omitempty"` // Place free-volume-slot deadband; |ΔfreeSlots| ≤ M×dataShards ranks by liveShards; 0 = strict
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3073,13 +3072,6 @@ func (x *ErasureCodingTaskConfig) GetFreeSlotsDeadband() int32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *ErasureCodingTaskConfig) GetMaxShardTransfers() int32 {
|
||||
if x != nil && x.MaxShardTransfers != nil {
|
||||
return *x.MaxShardTransfers
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// BalanceTaskConfig contains balance-specific configuration
|
||||
type BalanceTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -4309,7 +4301,7 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x10VacuumTaskConfig\x12+\n" +
|
||||
"\x11garbage_threshold\x18\x01 \x01(\x01R\x10garbageThreshold\x12/\n" +
|
||||
"\x14min_volume_age_hours\x18\x02 \x01(\x05R\x11minVolumeAgeHours\x120\n" +
|
||||
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\xc2\x03\n" +
|
||||
"\x14min_interval_seconds\x18\x03 \x01(\x05R\x12minIntervalSeconds\"\xf5\x02\n" +
|
||||
"\x17ErasureCodingTaskConfig\x12%\n" +
|
||||
"\x0efullness_ratio\x18\x01 \x01(\x01R\rfullnessRatio\x12*\n" +
|
||||
"\x11quiet_for_seconds\x18\x02 \x01(\x05R\x0fquietForSeconds\x12+\n" +
|
||||
@@ -4318,9 +4310,7 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\x12)\n" +
|
||||
"\x10strict_placement\x18\a \x01(\bR\x0fstrictPlacement\x12.\n" +
|
||||
"\x13free_slots_deadband\x18\b \x01(\x05R\x11freeSlotsDeadband\x123\n" +
|
||||
"\x13max_shard_transfers\x18\t \x01(\x05H\x00R\x11maxShardTransfers\x88\x01\x01B\x16\n" +
|
||||
"\x14_max_shard_transfers\"\x9b\x01\n" +
|
||||
"\x13free_slots_deadband\x18\b \x01(\x05R\x11freeSlotsDeadband\"\x9b\x01\n" +
|
||||
"\x11BalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\x12+\n" +
|
||||
@@ -4595,7 +4585,6 @@ func file_worker_proto_init() {
|
||||
(*TaskPolicy_ReplicationConfig)(nil),
|
||||
(*TaskPolicy_EcBalanceConfig)(nil),
|
||||
}
|
||||
file_worker_proto_msgTypes[31].OneofWrappers = []any{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
|
||||
@@ -7,8 +7,7 @@ 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)
|
||||
DeleteMarker *filer_pb.Entry // Set when the resolved entry is a delete marker, so a missing-key answer can still carry its headers
|
||||
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)
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
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,63 +790,16 @@ func (s3a *S3ApiServer) processConditionalHeaders(w http.ResponseWriter, r *http
|
||||
w.Header().Set("ETag", result.ETag)
|
||||
}
|
||||
|
||||
s3a.writeConditionalCheckError(w, r, bucket, object, handlerName, result)
|
||||
if result.ErrorCode == s3err.ErrNoSuchKey || result.ErrorCode == s3err.ErrNoSuchBucket {
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, result.ErrorCode)
|
||||
} else {
|
||||
s3err.WriteErrorResponse(w, r, result.ErrorCode)
|
||||
}
|
||||
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)
|
||||
@@ -929,18 +882,6 @@ 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)
|
||||
@@ -1013,7 +954,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.writeDeleteMarkerResponse(w, r, bucket, object, "GetObjectHandler", entry, targetVersionId, versionId)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -2460,29 +2401,23 @@ func (s3a *S3ApiServer) setResponseHeaders(w http.ResponseWriter, r *http.Reques
|
||||
// Set custom headers from entry.Extended (user metadata)
|
||||
// Use direct map assignment to preserve original header casing (matches proxy behavior)
|
||||
if entry.Extended != nil {
|
||||
extAmzPrefixLower := strings.ToLower(s3_constants.ExtAmzPrefix)
|
||||
taggingPrefixLower := strings.ToLower(s3_constants.AmzObjectTaggingPrefix)
|
||||
for k, v := range entry.Extended {
|
||||
// Skip internal SeaweedFS headers, and the stored tag/ACL/lock
|
||||
// metadata that belongs behind its own API (GetObjectTagging,
|
||||
// GetObjectAcl, GetObjectRetention) instead of every reader.
|
||||
lowerKey := strings.ToLower(k)
|
||||
if strings.HasPrefix(lowerKey, "xattr-") || strings.HasPrefix(lowerKey, extAmzPrefixLower) || strings.HasPrefix(lowerKey, taggingPrefixLower) || s3_constants.IsSeaweedFSInternalHeader(lowerKey) {
|
||||
continue
|
||||
}
|
||||
// Support backward compatibility: migrate old non-canonical format to canonical format
|
||||
// OLD: "x-amz-meta-foo" → NEW: "X-Amz-Meta-foo" (preserving suffix case)
|
||||
headerKey := k
|
||||
if len(k) >= 11 && strings.EqualFold(k[:11], "x-amz-meta-") {
|
||||
// Normalize to AWS S3 format: "X-Amz-Meta-" prefix with lowercase suffix
|
||||
// AWS S3 returns user metadata with the suffix in lowercase
|
||||
suffix := k[len("x-amz-meta-"):]
|
||||
headerKey = s3_constants.AmzUserMetaPrefix + strings.ToLower(suffix)
|
||||
if glog.V(4) && k != headerKey {
|
||||
glog.Infof("Normalizing user metadata header %q to %q in response", k, headerKey)
|
||||
// Skip internal SeaweedFS headers
|
||||
if !strings.HasPrefix(k, "xattr-") && !s3_constants.IsSeaweedFSInternalHeader(k) {
|
||||
// Support backward compatibility: migrate old non-canonical format to canonical format
|
||||
// OLD: "x-amz-meta-foo" → NEW: "X-Amz-Meta-foo" (preserving suffix case)
|
||||
headerKey := k
|
||||
if len(k) >= 11 && strings.EqualFold(k[:11], "x-amz-meta-") {
|
||||
// Normalize to AWS S3 format: "X-Amz-Meta-" prefix with lowercase suffix
|
||||
// AWS S3 returns user metadata with the suffix in lowercase
|
||||
suffix := k[len("x-amz-meta-"):]
|
||||
headerKey = s3_constants.AmzUserMetaPrefix + strings.ToLower(suffix)
|
||||
if glog.V(4) && k != headerKey {
|
||||
glog.Infof("Normalizing user metadata header %q to %q in response", k, headerKey)
|
||||
}
|
||||
}
|
||||
w.Header()[headerKey] = []string{string(v)}
|
||||
}
|
||||
w.Header()[headerKey] = []string{string(v)}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2624,18 +2559,6 @@ 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)
|
||||
@@ -2708,7 +2631,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.writeDeleteMarkerResponse(w, r, bucket, object, "HeadObjectHandler", entry, targetVersionId, versionId)
|
||||
s3a.writeAnonymousAwareNotFound(w, r, bucket, s3err.ErrNoSuchKey)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3022,11 +3022,7 @@ func (s3a *S3ApiServer) checkConditionalHeadersForReads(r *http.Request, bucket,
|
||||
if versionId != "" && normalizeConditionalTargetEntry(entry) == nil {
|
||||
return ConditionalHeaderResult{ErrorCode: s3err.ErrNone, Entry: nil}
|
||||
}
|
||||
result := s3a.validateConditionalHeadersForReads(r, headers, entry, bucket, object)
|
||||
if entry != nil && normalizeConditionalTargetEntry(entry) == nil {
|
||||
result.DeleteMarker = entry
|
||||
}
|
||||
return result
|
||||
return s3a.validateConditionalHeadersForReads(r, headers, entry, bucket, object)
|
||||
}
|
||||
|
||||
// lookupVolumeJwt mints a fresh volume-server JWT for an existing file id, so a
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// GetObject/HeadObject must expose only response headers AWS defines: user
|
||||
// metadata, standard entity headers and x-amz-tagging-count. Tag values live
|
||||
// behind GetObjectTagging and ACL/owner/lock state behind its own APIs; the
|
||||
// generic Extended echo must not hand them to any caller that can read the
|
||||
// object.
|
||||
func TestSetResponseHeadersFiltersInternalExtendedKeys(t *testing.T) {
|
||||
s3a := &S3ApiServer{}
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "object",
|
||||
Attributes: &filer_pb.FuseAttributes{Mtime: 100},
|
||||
Extended: map[string][]byte{
|
||||
s3_constants.AmzObjectTaggingPrefix + "project": []byte("alpha"),
|
||||
s3_constants.AmzObjectTaggingPrefix + "owner": []byte("y"),
|
||||
"x-amz-tagging-sneaky": []byte("z"),
|
||||
"seaweed-x-amz-acl": []byte("z"),
|
||||
s3_constants.ExtAmzAclKey: []byte(`[{"Permission":"FULL_CONTROL"}]`),
|
||||
s3_constants.ExtAmzOwnerKey: []byte("admin"),
|
||||
s3_constants.ExtVersionIdKey: []byte("version-1"),
|
||||
s3_constants.ExtObjectLockModeKey: []byte("COMPLIANCE"),
|
||||
s3_constants.ExtETagKey: []byte("d41d8cd98f00b204e9800998ecf8427e"),
|
||||
s3_constants.SeaweedFSWriteId: []byte("write-id"),
|
||||
"X-Amz-Meta-Foo": []byte("bar"),
|
||||
"Cache-Control": []byte("no-cache"),
|
||||
"xattr-user.note": []byte("n"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
w := httptest.NewRecorder()
|
||||
s3a.setResponseHeaders(w, httptest.NewRequest(method, "/bucket/object", nil), entry, 8)
|
||||
|
||||
for key := range w.Header() {
|
||||
lowerKey := strings.ToLower(key)
|
||||
if lowerKey == s3_constants.AmzTagCount {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(lowerKey, strings.ToLower(s3_constants.ExtAmzPrefix)) {
|
||||
t.Errorf("%s: internal header %q leaked into response", method, key)
|
||||
}
|
||||
if strings.HasPrefix(lowerKey, strings.ToLower(s3_constants.AmzObjectTaggingPrefix)) {
|
||||
t.Errorf("%s: object tag value %q leaked into response", method, key)
|
||||
}
|
||||
}
|
||||
if got := w.Header().Get(s3_constants.AmzTagCount); got != "2" {
|
||||
t.Errorf("%s: tag count = %q, want 2", method, got)
|
||||
}
|
||||
if got := w.Header()["X-Amz-Meta-foo"]; len(got) != 1 || got[0] != "bar" {
|
||||
t.Errorf("%s: user metadata dropped, X-Amz-Meta-foo = %v", method, got)
|
||||
}
|
||||
if got := w.Header().Get("Cache-Control"); got != "no-cache" {
|
||||
t.Errorf("%s: Cache-Control = %q", method, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -314,26 +314,6 @@ 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,10 +7,12 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -97,6 +99,7 @@ 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{
|
||||
@@ -105,6 +108,10 @@ 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)
|
||||
@@ -174,25 +181,6 @@ 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{
|
||||
|
||||
@@ -140,7 +140,7 @@ func TestGetAccountIDAdminActionKeepsAdminAccount(t *testing.T) {
|
||||
assert.Equal(t, s3_constants.AccountAdminId, h.getAccountID(req), "an admin identity keeps the admin account as principal")
|
||||
}
|
||||
|
||||
func TestDefaultAllowForOnlyAppliesWithoutResolvedIdentity(t *testing.T) {
|
||||
func TestDefaultAllowForOnlyAppliesToUnauthenticatedOrAnonymous(t *testing.T) {
|
||||
h := NewS3TablesHandler()
|
||||
h.SetDefaultAllow(true)
|
||||
|
||||
@@ -149,8 +149,8 @@ func TestDefaultAllowForOnlyAppliesWithoutResolvedIdentity(t *testing.T) {
|
||||
|
||||
anon := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
anon = anon.WithContext(s3_constants.SetIdentityInContext(anon.Context(),
|
||||
&testIdentity{Name: s3_constants.AccountAnonymousId, Actions: []string{"Read:pub", "List:pub"}}))
|
||||
assert.False(t, h.defaultAllowFor(anon), "a resolved anonymous identity is scoped by its grant, not the open default")
|
||||
&testIdentity{Name: s3_constants.AccountAnonymousId}))
|
||||
assert.True(t, h.defaultAllowFor(anon), "anonymous requests keep the open default")
|
||||
|
||||
authed := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
authed = authed.WithContext(s3_constants.SetIdentityInContext(authed.Context(),
|
||||
|
||||
@@ -49,8 +49,7 @@ func (h *S3TablesHandler) shouldUseIAM(r *http.Request, identityActions, identit
|
||||
}
|
||||
|
||||
// defaultAllowFor reports whether the open-by-default fallback applies: only for
|
||||
// trusted tooling or when no principal was resolved at all. A resolved identity
|
||||
// — the configured anonymous identity included — is scoped by its grant and
|
||||
// trusted tooling or unauthenticated/anonymous access. An authenticated principal
|
||||
// must pass an explicit check.
|
||||
func (h *S3TablesHandler) defaultAllowFor(r *http.Request) bool {
|
||||
if h.trusted {
|
||||
@@ -61,7 +60,10 @@ func (h *S3TablesHandler) defaultAllowFor(r *http.Request) bool {
|
||||
}
|
||||
// The Manager path forwards only the identity name, so a name alone (no
|
||||
// identity object) still counts as an authenticated principal.
|
||||
return s3_constants.GetIdentityFromContext(r) == nil && s3_constants.GetIdentityNameFromContext(r) == ""
|
||||
if s3_constants.GetIdentityFromContext(r) == nil && s3_constants.GetIdentityNameFromContext(r) == "" {
|
||||
return true
|
||||
}
|
||||
return isAnonymousIdentity(r)
|
||||
}
|
||||
|
||||
func isAnonymousIdentity(r *http.Request) bool {
|
||||
|
||||
@@ -313,33 +313,8 @@ func (t *responseBodyTracker) Write(p []byte) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
// ifRangeMatches reports whether an If-Range validator still names the
|
||||
// representation described by header (RFC 9110 13.1.5): an entity tag by
|
||||
// strong comparison, or a date equal to Last-Modified.
|
||||
func ifRangeMatches(ifRange string, header http.Header) bool {
|
||||
ifRange = strings.TrimSpace(ifRange)
|
||||
if ifRange == "" {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(ifRange, "\"") || strings.HasPrefix(ifRange, "W/") {
|
||||
etag := header.Get("ETag")
|
||||
return etag != "" && !strings.HasPrefix(etag, "W/") && ifRange == etag
|
||||
}
|
||||
date, err := http.ParseTime(ifRange)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
lastModified, err := http.ParseTime(header.Get("Last-Modified"))
|
||||
return err == nil && date.Equal(lastModified)
|
||||
}
|
||||
|
||||
func ProcessRangeRequest(r *http.Request, w http.ResponseWriter, totalSize int64, mimeType string, prepareWriteFn func(offset int64, size int64) (filer.DoStreamContent, error)) error {
|
||||
rangeReq := r.Header.Get("Range")
|
||||
// A Range whose If-Range no longer matches is ignored and the whole content
|
||||
// is sent, so a resumed download restarts instead of mixing two versions.
|
||||
if rangeReq != "" && !ifRangeMatches(r.Header.Get("If-Range"), w.Header()) {
|
||||
rangeReq = ""
|
||||
}
|
||||
sink := &responseBodyTracker{ResponseWriter: w}
|
||||
bufferedWriter := writePool.Get().(*bufio.Writer)
|
||||
bufferedWriter.Reset(sink)
|
||||
|
||||
@@ -343,48 +343,6 @@ func TestProcessRangeRequestRanges(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessRangeRequestIfRange(t *testing.T) {
|
||||
data := []byte("0123456789")
|
||||
const etag = `"v2"`
|
||||
const lastModified = "Sat, 24 Oct 2026 22:01:04 GMT"
|
||||
tests := []struct {
|
||||
ifRange string
|
||||
wantCode int
|
||||
wantBody string
|
||||
}{
|
||||
{"", http.StatusPartialContent, "01"},
|
||||
{etag, http.StatusPartialContent, "01"},
|
||||
{lastModified, http.StatusPartialContent, "01"},
|
||||
{"Saturday, 24-Oct-26 22:01:04 GMT", http.StatusPartialContent, "01"},
|
||||
{"Sat Oct 24 22:01:04 2026", http.StatusPartialContent, "01"},
|
||||
{`"v1"`, http.StatusOK, "0123456789"},
|
||||
{`W/"v2"`, http.StatusOK, "0123456789"},
|
||||
{"Sat, 24 Oct 2026 22:01:03 GMT", http.StatusOK, "0123456789"},
|
||||
{"not a date", http.StatusOK, "0123456789"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/test.txt", nil)
|
||||
r.Header.Set("Range", "bytes=0-1")
|
||||
if tt.ifRange != "" {
|
||||
r.Header.Set("If-Range", tt.ifRange)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
w.Header().Set("ETag", etag)
|
||||
w.Header().Set("Last-Modified", lastModified)
|
||||
if err := ProcessRangeRequest(r, w, int64(len(data)), "text/plain", func(offset int64, size int64) (filer.DoStreamContent, error) {
|
||||
return func(writer io.Writer) error {
|
||||
_, err := writer.Write(data[offset : offset+size])
|
||||
return err
|
||||
}, nil
|
||||
}); err != nil {
|
||||
t.Errorf("If-Range %q: %v", tt.ifRange, err)
|
||||
}
|
||||
if w.Code != tt.wantCode || w.Body.String() != tt.wantBody {
|
||||
t.Errorf("If-Range %q: got %d %q, want %d %q", tt.ifRange, w.Code, w.Body.String(), tt.wantCode, tt.wantBody)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// /submit must reject at the limit its master was given, not at a hardcoded
|
||||
// 256MB: weed server hands -volume.fileSizeLimitMB down to the master, and an
|
||||
// upload the volume server would store must not be turned away here (#6748).
|
||||
|
||||
@@ -668,9 +668,7 @@ 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,
|
||||
@@ -775,9 +773,7 @@ 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
|
||||
@@ -807,9 +803,7 @@ 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)
|
||||
@@ -905,7 +899,6 @@ 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)
|
||||
|
||||
@@ -913,7 +906,6 @@ 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,9 +318,7 @@ 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,12 +78,10 @@ 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)
|
||||
}
|
||||
@@ -151,12 +149,10 @@ 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)
|
||||
}
|
||||
@@ -182,17 +178,6 @@ 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.
|
||||
@@ -335,7 +320,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) (retErr 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) error {
|
||||
|
||||
oldPath, newPath := oldParent.Child(entry.Name()), newParent.Child(newName)
|
||||
|
||||
@@ -430,13 +415,6 @@ 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)
|
||||
@@ -455,9 +433,7 @@ 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,30 +532,3 @@ 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.EntryCommitTsNs(ctx, entry, entry.Mtime.UnixNano())
|
||||
entryTsNs, err := fs.filer.CommitTsNs(ctx, entry.FullPath, entry.Mtime.UnixNano())
|
||||
if err != nil {
|
||||
return fmt.Errorf("commit timestamp of %s: %w", entry.FullPath, err)
|
||||
}
|
||||
|
||||
@@ -231,30 +231,12 @@ func (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServ
|
||||
continue
|
||||
}
|
||||
|
||||
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 {
|
||||
if (dn == nil && heartbeat.Ip != "") || reportsPriorClusterState(heartbeat, ms.Topo.GetTopologyId(), ms.Topo.GetMaxVolumeId()) {
|
||||
ms.Topo.NoteAllocationEvidence()
|
||||
}
|
||||
ms.Topo.Sequence.SetMax(heartbeat.MaxFileKey)
|
||||
ms.Topo.UpAdjustMaxVolumeId(needle.VolumeId(heartbeat.MaxVolumeIdSeen))
|
||||
// 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 {
|
||||
if len(heartbeat.Volumes) > 0 {
|
||||
ms.Topo.CheckReportedTopologyId(heartbeat.LastSeenTopologyId)
|
||||
}
|
||||
if dn == nil {
|
||||
@@ -376,10 +358,8 @@ 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 {
|
||||
// prior cluster state has nothing left to wait for.
|
||||
if len(heartbeat.Volumes) > 0 || heartbeat.HasNoVolumes {
|
||||
ms.Topo.NoteInventoryApplied()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -73,10 +73,7 @@ type MasterOption struct {
|
||||
// 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 {
|
||||
@@ -190,7 +187,7 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers map[string]pb.Se
|
||||
}
|
||||
}
|
||||
if option.ReleaseAllocOnFirstReport {
|
||||
ms.Topo.ReleaseAllocationOnFirstReport(option.SingleVolumeReporter)
|
||||
ms.Topo.ReleaseAllocationOnFirstReport()
|
||||
}
|
||||
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 {
|
||||
|
||||
@@ -14,66 +14,9 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// ShardDistributionOptions controls DistributeEcShards concurrency.
|
||||
// MaxShardTransfers:
|
||||
// - nil / unset: no global cap; one in-flight per (destNode, disk_id), or
|
||||
// per destNode (host:port, not rack) when any target leaves disk choice
|
||||
// to the receiver (disk_id 0)
|
||||
// - N<=0: historical sequential nested loops
|
||||
// - N>0: global cap of N, still at most one in-flight per key
|
||||
type ShardDistributionOptions struct {
|
||||
MaxShardTransfers *int
|
||||
send shardSender
|
||||
}
|
||||
|
||||
type shardSender func(ctx context.Context, volumeID uint32, collection string, dialOption grpc.DialOption, destServer string, diskID uint32, filePath, shardType string) error
|
||||
|
||||
type shardJob struct {
|
||||
destNode string
|
||||
shardType string
|
||||
filePath string
|
||||
diskID uint32
|
||||
hasDisk bool
|
||||
}
|
||||
|
||||
func shardSenderOrDefault(opts *ShardDistributionOptions) shardSender {
|
||||
if opts != nil && opts.send != nil {
|
||||
return opts.send
|
||||
}
|
||||
return sendShardFileToDestination
|
||||
}
|
||||
|
||||
func shardTransferCap(opts *ShardDistributionOptions) (sequential bool, capN int) {
|
||||
if opts == nil || opts.MaxShardTransfers == nil {
|
||||
return false, 0
|
||||
}
|
||||
n := *opts.MaxShardTransfers
|
||||
if n <= 0 {
|
||||
return true, 0
|
||||
}
|
||||
return false, n
|
||||
}
|
||||
|
||||
func lookupShardDisk(shardDisks map[string]map[string]uint32, destNode, shardType string) (uint32, bool) {
|
||||
if byShard, ok := shardDisks[destNode]; ok {
|
||||
if id, exists := byShard[shardType]; exists {
|
||||
return id, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func shardTransferKey(j shardJob) string {
|
||||
if j.hasDisk {
|
||||
return fmt.Sprintf("%s#%d", j.destNode, j.diskID)
|
||||
}
|
||||
return j.destNode
|
||||
}
|
||||
|
||||
func ensureLogger(logger logger) logger {
|
||||
if logger == nil {
|
||||
return &glogFallbackLogger{}
|
||||
@@ -155,8 +98,7 @@ func (g *glogFallbackLogger) Error(msg string, args ...interface{}) {
|
||||
|
||||
// DistributeEcShards distributes locally generated EC shards to destination servers.
|
||||
// Returns the shard assignment map used for mounting.
|
||||
// opts nil is the default: one in-flight per dest disk/node, no global cap.
|
||||
func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb.TaskTarget, shardFiles map[string]string, dialOption grpc.DialOption, logger logger, opts *ShardDistributionOptions) (map[string][]string, error) {
|
||||
func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb.TaskTarget, shardFiles map[string]string, dialOption grpc.DialOption, logger logger) (map[string][]string, error) {
|
||||
if len(targets) == 0 {
|
||||
return nil, fmt.Errorf("no targets specified for EC shard distribution")
|
||||
}
|
||||
@@ -231,22 +173,6 @@ func DistributeEcShards(volumeID uint32, collection string, targets []*worker_pb
|
||||
return nil, fmt.Errorf("no shard assignments found from planning phase")
|
||||
}
|
||||
|
||||
send := shardSenderOrDefault(opts)
|
||||
sequential, capN := shardTransferCap(opts)
|
||||
if sequential {
|
||||
if err := distributeEcShardsSequential(volumeID, collection, shardAssignment, shardFiles, shardDisks, dialOption, log, send); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if err := distributeEcShardsParallel(volumeID, collection, shardAssignment, shardFiles, shardDisks, dialOption, log, send, capN); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
glog.V(1).Infof("Successfully distributed EC shards to %d destinations", len(shardAssignment))
|
||||
return shardAssignment, nil
|
||||
}
|
||||
|
||||
func distributeEcShardsSequential(volumeID uint32, collection string, shardAssignment map[string][]string, shardFiles map[string]string, shardDisks map[string]map[string]uint32, dialOption grpc.DialOption, log logger, send shardSender) error {
|
||||
ctx := context.Background()
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": destNode,
|
||||
@@ -258,7 +184,7 @@ func distributeEcShardsSequential(volumeID uint32, collection string, shardAssig
|
||||
for _, shardType := range assignedShards {
|
||||
filePath, exists := shardFiles[shardType]
|
||||
if !exists {
|
||||
return fmt.Errorf("shard file %s not found for destination %s", shardType, destNode)
|
||||
return nil, fmt.Errorf("shard file %s not found for destination %s", shardType, destNode)
|
||||
}
|
||||
|
||||
if info, err := os.Stat(filePath); err == nil {
|
||||
@@ -272,9 +198,12 @@ func distributeEcShardsSequential(volumeID uint32, collection string, shardAssig
|
||||
}).Info("Starting shard file transfer")
|
||||
}
|
||||
|
||||
diskID, _ := lookupShardDisk(shardDisks, destNode, shardType)
|
||||
if err := send(ctx, volumeID, collection, dialOption, destNode, diskID, filePath, shardType); err != nil {
|
||||
return fmt.Errorf("failed to send %s to %s: %w", shardType, destNode, err)
|
||||
diskID := uint32(0)
|
||||
if byShard, ok := shardDisks[destNode]; ok {
|
||||
diskID = byShard[shardType]
|
||||
}
|
||||
if err := sendShardFileToDestination(volumeID, collection, dialOption, destNode, diskID, filePath, shardType); err != nil {
|
||||
return nil, fmt.Errorf("failed to send %s to %s: %w", shardType, destNode, err)
|
||||
}
|
||||
|
||||
withFields(log, map[string]interface{}{
|
||||
@@ -290,139 +219,9 @@ func distributeEcShardsSequential(volumeID uint32, collection string, shardAssig
|
||||
"total_mb": float64(transferredBytes) / (1024 * 1024),
|
||||
}).Info("All shards distributed to destination server")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func collectShardJobs(shardAssignment map[string][]string, shardFiles map[string]string, shardDisks map[string]map[string]uint32, log logger) (map[string][]shardJob, error) {
|
||||
// disk_id 0 leaves placement to the receiver's auto-select, which can land
|
||||
// on a disk another queued stream is pinned to — serialize every transfer
|
||||
// to that server under one key.
|
||||
autoPlacement := make(map[string]bool)
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
for _, shardType := range assignedShards {
|
||||
if diskID, ok := lookupShardDisk(shardDisks, destNode, shardType); ok && diskID == 0 {
|
||||
autoPlacement[destNode] = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
byKey := make(map[string][]shardJob)
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": destNode,
|
||||
"assigned_shards": len(assignedShards),
|
||||
"shard_types": assignedShards,
|
||||
}).Info("Starting shard distribution to destination server")
|
||||
|
||||
for _, shardType := range assignedShards {
|
||||
filePath, exists := shardFiles[shardType]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("shard file %s not found for destination %s", shardType, destNode)
|
||||
}
|
||||
diskID, hasDisk := lookupShardDisk(shardDisks, destNode, shardType)
|
||||
job := shardJob{
|
||||
destNode: destNode,
|
||||
shardType: shardType,
|
||||
filePath: filePath,
|
||||
diskID: diskID,
|
||||
hasDisk: hasDisk,
|
||||
}
|
||||
key := shardTransferKey(job)
|
||||
if autoPlacement[destNode] {
|
||||
key = destNode
|
||||
}
|
||||
byKey[key] = append(byKey[key], job)
|
||||
}
|
||||
}
|
||||
return byKey, nil
|
||||
}
|
||||
|
||||
func distributeEcShardsParallel(volumeID uint32, collection string, shardAssignment map[string][]string, shardFiles map[string]string, shardDisks map[string]map[string]uint32, dialOption grpc.DialOption, log logger, send shardSender, capN int) error {
|
||||
byKey, err := collectShardJobs(shardAssignment, shardFiles, shardDisks, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
g, ctx := errgroup.WithContext(context.Background())
|
||||
var sem chan struct{}
|
||||
if capN > 0 {
|
||||
sem = make(chan struct{}, capN)
|
||||
}
|
||||
|
||||
for _, jobs := range byKey {
|
||||
jobs := jobs
|
||||
g.Go(func() error {
|
||||
for _, job := range jobs {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if sem != nil {
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-sem
|
||||
return err
|
||||
}
|
||||
}
|
||||
err := transferOneShard(ctx, volumeID, collection, dialOption, log, send, job)
|
||||
if err != nil {
|
||||
// Hold the slot so another key cannot start a send in the
|
||||
// window before errgroup cancels ctx.
|
||||
return err
|
||||
}
|
||||
if sem != nil {
|
||||
<-sem
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
if err := g.Wait(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for destNode, assignedShards := range shardAssignment {
|
||||
var transferredBytes int64
|
||||
for _, shardType := range assignedShards {
|
||||
if filePath, ok := shardFiles[shardType]; ok {
|
||||
if info, statErr := os.Stat(filePath); statErr == nil {
|
||||
transferredBytes += info.Size()
|
||||
}
|
||||
}
|
||||
}
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": destNode,
|
||||
"shards_transferred": len(assignedShards),
|
||||
"total_bytes": transferredBytes,
|
||||
"total_mb": float64(transferredBytes) / (1024 * 1024),
|
||||
}).Info("All shards distributed to destination server")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func transferOneShard(ctx context.Context, volumeID uint32, collection string, dialOption grpc.DialOption, log logger, send shardSender, job shardJob) error {
|
||||
if info, err := os.Stat(job.filePath); err == nil {
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": job.destNode,
|
||||
"shard_type": job.shardType,
|
||||
"file_path": job.filePath,
|
||||
"size_bytes": info.Size(),
|
||||
"size_kb": float64(info.Size()) / 1024,
|
||||
}).Info("Starting shard file transfer")
|
||||
}
|
||||
if err := send(ctx, volumeID, collection, dialOption, job.destNode, job.diskID, job.filePath, job.shardType); err != nil {
|
||||
return fmt.Errorf("failed to send %s to %s: %w", job.shardType, job.destNode, err)
|
||||
}
|
||||
withFields(log, map[string]interface{}{
|
||||
"destination": job.destNode,
|
||||
"shard_type": job.shardType,
|
||||
}).Info("Shard file transfer completed")
|
||||
return nil
|
||||
glog.V(1).Infof("Successfully distributed EC shards to %d destinations", len(shardAssignment))
|
||||
return shardAssignment, nil
|
||||
}
|
||||
|
||||
// MountEcShards mounts EC shards on destination servers using an assignment map.
|
||||
@@ -501,10 +300,7 @@ func MountEcShards(volumeID uint32, collection string, shardAssignment map[strin
|
||||
}
|
||||
|
||||
// diskID=0 leaves disk placement to the server's auto-select.
|
||||
func sendShardFileToDestination(ctx context.Context, volumeID uint32, collection string, dialOption grpc.DialOption, destServer string, diskID uint32, filePath, shardType string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
func sendShardFileToDestination(volumeID uint32, collection string, dialOption grpc.DialOption, destServer string, diskID uint32, filePath, shardType string) error {
|
||||
return operation.WithVolumeServerClient(false, pb.ServerAddress(destServer), dialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
file, err := os.Open(filePath)
|
||||
@@ -539,7 +335,7 @@ func sendShardFileToDestination(ctx context.Context, volumeID uint32, collection
|
||||
return fmt.Errorf("unknown shard type: %s", shardType)
|
||||
}
|
||||
|
||||
stream, err := client.ReceiveFile(ctx)
|
||||
stream, err := client.ReceiveFile(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create receive stream: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,428 +0,0 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
func intPtr(n int) *int { return &n }
|
||||
|
||||
func writeShardFiles(t *testing.T, names ...string) map[string]string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
files := make(map[string]string, len(names))
|
||||
for _, name := range names {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(name), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files[name] = p
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
func shardTarget(node string, disk uint32, shards ...uint32) *worker_pb.TaskTarget {
|
||||
return &worker_pb.TaskTarget{Node: node, DiskId: disk, ShardIds: shards}
|
||||
}
|
||||
|
||||
type flightRecorder struct {
|
||||
mu sync.Mutex
|
||||
inFlight int
|
||||
maxFlight int
|
||||
keyFlight map[string]int
|
||||
keyMax int
|
||||
attempts []string
|
||||
sent []string
|
||||
failOn string
|
||||
failFirst bool
|
||||
enter chan struct{}
|
||||
goAhead chan struct{}
|
||||
noGate atomic.Bool
|
||||
}
|
||||
|
||||
func newFlightRecorder() *flightRecorder {
|
||||
return &flightRecorder{
|
||||
keyFlight: make(map[string]int),
|
||||
enter: make(chan struct{}, 32),
|
||||
goAhead: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *flightRecorder) release() {
|
||||
r.noGate.Store(true)
|
||||
close(r.goAhead)
|
||||
}
|
||||
|
||||
func (r *flightRecorder) send(ctx context.Context, _ uint32, _ string, _ grpc.DialOption, destServer string, diskID uint32, _ string, shardType string) error {
|
||||
id := destServer + "/" + shardType
|
||||
key := shardTransferKey(shardJob{destNode: destServer, diskID: diskID, hasDisk: true})
|
||||
|
||||
r.mu.Lock()
|
||||
r.inFlight++
|
||||
if r.inFlight > r.maxFlight {
|
||||
r.maxFlight = r.inFlight
|
||||
}
|
||||
r.keyFlight[key]++
|
||||
if r.keyFlight[key] > r.keyMax {
|
||||
r.keyMax = r.keyFlight[key]
|
||||
}
|
||||
r.attempts = append(r.attempts, id)
|
||||
r.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
r.mu.Lock()
|
||||
r.keyFlight[key]--
|
||||
r.inFlight--
|
||||
r.mu.Unlock()
|
||||
}()
|
||||
|
||||
if r.failOn == id || r.failFirst {
|
||||
r.failFirst = false
|
||||
return errors.New("mock send failed")
|
||||
}
|
||||
if !r.noGate.Load() {
|
||||
select {
|
||||
case r.enter <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
select {
|
||||
case <-r.goAhead:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.sent = append(r.sent, id)
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitEnters(t *testing.T, rec *flightRecorder, n int) {
|
||||
t.Helper()
|
||||
deadline := time.After(2 * time.Second)
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case <-rec.enter:
|
||||
case <-deadline:
|
||||
t.Fatalf("timed out waiting for %d in-flight sends (got %d)", n, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertNoExtraEnter(t *testing.T, rec *flightRecorder, wait time.Duration) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-rec.enter:
|
||||
t.Fatal("unexpected extra in-flight send")
|
||||
case <-time.After(wait):
|
||||
}
|
||||
}
|
||||
|
||||
func runDistribute(t *testing.T, targets []*worker_pb.TaskTarget, files map[string]string, rec *flightRecorder, max *int) (map[string][]string, error) {
|
||||
t.Helper()
|
||||
opts := &ShardDistributionOptions{
|
||||
MaxShardTransfers: max,
|
||||
send: rec.send,
|
||||
}
|
||||
return DistributeEcShards(1, "col", targets, files, nil, nil, opts)
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsZeroIsSequential(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02", "ec03")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0),
|
||||
shardTarget("full-01:8080", 1, 1),
|
||||
shardTarget("full-02:8080", 0, 2),
|
||||
shardTarget("full-02:8080", 1, 3),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, intPtr(0))
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 1)
|
||||
assertNoExtraEnter(t, rec, 40*time.Millisecond)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 1 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("max in-flight=%d, want 1 for max_shard_transfers=0", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if rec.maxFlight != 1 {
|
||||
t.Fatalf("max in-flight=%d after release, want 1", rec.maxFlight)
|
||||
}
|
||||
if rec.keyMax != 1 {
|
||||
t.Fatalf("per-key in-flight=%d, want 1", rec.keyMax)
|
||||
}
|
||||
if len(rec.sent) != 4 {
|
||||
t.Fatalf("sent %d shards, want 4: %v", len(rec.sent), rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsNoCapParallelByKey(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02", "ec03")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 1, 0),
|
||||
shardTarget("full-01:8080", 2, 1),
|
||||
shardTarget("full-02:8080", 0, 2),
|
||||
shardTarget("full-02:8081", 0, 3), // same rack host, different destNode
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 4)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 4 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("no cap: max in-flight=%d, want 4 (one per dest disk/node)", rec.maxFlight)
|
||||
}
|
||||
if rec.keyMax != 1 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("per-key in-flight=%d, want 1", rec.keyMax)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if len(rec.sent) != 4 {
|
||||
t.Fatalf("sent %d, want 4: %v", len(rec.sent), rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsSameDiskQueued(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0, 1),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 1)
|
||||
assertNoExtraEnter(t, rec, 40*time.Millisecond)
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if rec.maxFlight != 1 {
|
||||
t.Fatalf("same disk: max in-flight=%d, want 1", rec.maxFlight)
|
||||
}
|
||||
if rec.sent[0] != "full-01:8080/ec00" || rec.sent[1] != "full-01:8080/ec01" {
|
||||
t.Fatalf("same-disk order %v, want ec00 then ec01", rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsAutoDiskSerializesServer(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0), // disk picked by the receiver
|
||||
shardTarget("full-01:8080", 1, 1),
|
||||
shardTarget("full-02:8080", 1, 2),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 2)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 2 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("auto-placement server must serialize: in-flight=%d, want 2 (one per server)", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if len(rec.sent) != 3 {
|
||||
t.Fatalf("sent %d, want 3", len(rec.sent))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsTwoDisksTwoStreams(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 1, 0),
|
||||
shardTarget("full-01:8080", 2, 1),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 2)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 2 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("two disks on one VS: in-flight=%d, want 2", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsCapNeverExceedsN(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02", "ec03")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 1, 0),
|
||||
shardTarget("full-01:8080", 2, 1),
|
||||
shardTarget("full-02:8080", 1, 2),
|
||||
shardTarget("full-02:8080", 2, 3),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runDistribute(t, targets, files, rec, intPtr(2))
|
||||
errCh <- err
|
||||
}()
|
||||
|
||||
waitEnters(t, rec, 2)
|
||||
assertNoExtraEnter(t, rec, 40*time.Millisecond)
|
||||
rec.mu.Lock()
|
||||
if rec.maxFlight != 2 {
|
||||
rec.mu.Unlock()
|
||||
t.Fatalf("cap 2: in-flight=%d, want 2", rec.maxFlight)
|
||||
}
|
||||
rec.mu.Unlock()
|
||||
rec.release()
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if rec.maxFlight > 2 {
|
||||
t.Fatalf("cap 2: max in-flight=%d", rec.maxFlight)
|
||||
}
|
||||
if rec.keyMax != 1 {
|
||||
t.Fatalf("per-key in-flight=%d, want 1 under cap", rec.keyMax)
|
||||
}
|
||||
if len(rec.sent) != 4 {
|
||||
t.Fatalf("sent %d, want 4", len(rec.sent))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsErrorAbortSameKey(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0, 1, 2),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
rec.noGate.Store(true)
|
||||
rec.failOn = "full-01:8080/ec01"
|
||||
|
||||
_, err := runDistribute(t, targets, files, rec, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected send error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "failed to send ec01 to full-01:8080") {
|
||||
t.Fatalf("error wrap: %v", err)
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if got := strings.Join(rec.attempts, ","); got != "full-01:8080/ec00,full-01:8080/ec01" {
|
||||
t.Fatalf("attempts %v, want ec00 then ec01 (ec02 aborted)", rec.attempts)
|
||||
}
|
||||
if len(rec.sent) != 1 || rec.sent[0] != "full-01:8080/ec00" {
|
||||
t.Fatalf("successful sends %v, want only ec00", rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsErrorAbortCancelsOtherKeys(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00", "ec01", "ec02")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 0),
|
||||
shardTarget("full-02:8080", 0, 1),
|
||||
shardTarget("full-03:8080", 0, 2),
|
||||
}
|
||||
rec := newFlightRecorder()
|
||||
rec.noGate.Store(true)
|
||||
rec.failFirst = true
|
||||
|
||||
_, err := runDistribute(t, targets, files, rec, intPtr(1))
|
||||
if err == nil {
|
||||
t.Fatal("expected send error")
|
||||
}
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
if len(rec.attempts) != 1 {
|
||||
t.Fatalf("cap=1 abort: attempts %v, want only the failing send", rec.attempts)
|
||||
}
|
||||
if len(rec.sent) != 0 {
|
||||
t.Fatalf("successful sends %v, want none", rec.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributeEcShardsMissingFile(t *testing.T) {
|
||||
files := writeShardFiles(t, "ec00")
|
||||
targets := []*worker_pb.TaskTarget{
|
||||
shardTarget("full-01:8080", 0, 1),
|
||||
}
|
||||
for _, max := range []*int{intPtr(0), nil} {
|
||||
_, err := DistributeEcShards(1, "col", targets, files, nil, nil, &ShardDistributionOptions{
|
||||
MaxShardTransfers: max,
|
||||
send: func(context.Context, uint32, string, grpc.DialOption, string, uint32, string, string) error {
|
||||
t.Fatal("send should not run for missing file")
|
||||
return nil
|
||||
},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "shard file ec01 not found") {
|
||||
t.Fatalf("missing file error (max=%v): %v", max, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShardTransferKeyUsesDestNodeNotRack(t *testing.T) {
|
||||
a := shardTransferKey(shardJob{destNode: "full-01:8080", diskID: 0, hasDisk: true})
|
||||
b := shardTransferKey(shardJob{destNode: "full-01:8081", diskID: 0, hasDisk: true})
|
||||
if a == b {
|
||||
t.Fatalf("host:port keys collided: %s", a)
|
||||
}
|
||||
noDisk := shardTransferKey(shardJob{destNode: "full-01:8080", hasDisk: false})
|
||||
if noDisk != "full-01:8080" {
|
||||
t.Fatalf("no disk id key=%q, want destNode", noDisk)
|
||||
}
|
||||
if fmt.Sprint(a) == noDisk {
|
||||
t.Fatalf("disk 0 key should differ from destNode-only when hasDisk")
|
||||
}
|
||||
}
|
||||
@@ -217,35 +217,3 @@ func TestAllocationDeferralReleasedByInventory(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
+10
-40
@@ -108,7 +108,6 @@ type Topology struct {
|
||||
// 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{}
|
||||
@@ -1486,25 +1485,17 @@ 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 {
|
||||
@@ -1585,50 +1576,29 @@ 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.checkReportedTopologyIdLocked(id)
|
||||
t.CheckReportedTopologyId(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])
|
||||
}
|
||||
// allocation hold once one full volume-server inventory has been applied. Only
|
||||
// valid where a single volume server can carry prior cluster state (weed
|
||||
// mini's embedded server): its first heartbeat already raises the id bound or
|
||||
// trips the growth freeze, so the quiet-pulse tail is dead time.
|
||||
func (t *Topology) ReleaseAllocationOnFirstReport() {
|
||||
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
|
||||
|
||||
@@ -154,23 +154,7 @@ func NewListener(addr string, timeout time.Duration) (ipListener net.Listener, e
|
||||
return
|
||||
}
|
||||
|
||||
// IsLoopbackOrWildcardAddress reports whether host already covers loopback
|
||||
// traffic — empty (all interfaces), a wildcard address, or a loopback address —
|
||||
// in which case a separate localhost listener is unnecessary.
|
||||
func IsLoopbackOrWildcardAddress(host string) bool {
|
||||
switch host {
|
||||
case "", "localhost", "0.0.0.0", "127.0.0.1", "[::]", "[::1]":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NewIpAndLocalListeners binds host:port and, unless listenOnLocalhost is given
|
||||
// as false, a second listener on localhost:port so that local clients still
|
||||
// reach the service when it binds a specific address. Callers pass false when
|
||||
// the user explicitly chose the bind address (e.g. -ip.bind), honoring exactly
|
||||
// that address.
|
||||
func NewIpAndLocalListeners(host string, port int, timeout time.Duration, listenOnLocalhost ...bool) (ipListener net.Listener, localListener net.Listener, err error) {
|
||||
func NewIpAndLocalListeners(host string, port int, timeout time.Duration) (ipListener net.Listener, localListener net.Listener, err error) {
|
||||
listener, err := net.Listen("tcp", JoinHostPort(host, port))
|
||||
if err != nil {
|
||||
return
|
||||
@@ -181,10 +165,10 @@ func NewIpAndLocalListeners(host string, port int, timeout time.Duration, listen
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
if (len(listenOnLocalhost) == 0 || listenOnLocalhost[0]) && !IsLoopbackOrWildcardAddress(host) {
|
||||
if host != "localhost" && host != "" && host != "0.0.0.0" && host != "127.0.0.1" && host != "[::]" && host != "[::1]" {
|
||||
listener, err = net.Listen("tcp", JoinHostPort("localhost", port))
|
||||
if err != nil {
|
||||
glog.V(0).Infof("skip starting localhost listener on :%d: %v", port, err)
|
||||
glog.V(0).Infof("skip starting on %s:%d: %v", host, port, err)
|
||||
return ipListener, nil, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(51)
|
||||
MINOR_VERSION = int32(50)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
@@ -2,7 +2,6 @@ package erasure_coding
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/config"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -21,9 +20,6 @@ type Config struct {
|
||||
ReplicaPlacement string `json:"replica_placement"` // e.g. "020"; empty falls back to the master default replication
|
||||
StrictPlacement bool `json:"strict_placement"` // fail planning instead of relaxing placement constraints
|
||||
FreeSlotsDeadband int `json:"free_slots_deadband"` // Place volume-slot M; |ΔfreeSlots| ≤ M×dataShards is a tie, then liveShards; 0 = strict
|
||||
// MaxShardTransfers is the global in-flight cap for EC shard copies.
|
||||
// nil = no cap (one in-flight per dest disk); 0 = sequential; N>0 = cap.
|
||||
MaxShardTransfers *int `json:"max_shard_transfers,omitempty"`
|
||||
}
|
||||
|
||||
// NewDefaultConfig creates a new default erasure coding configuration
|
||||
@@ -228,51 +224,11 @@ func (c *Config) ToTaskPolicy() *worker_pb.TaskPolicy {
|
||||
ReplicaPlacement: c.ReplicaPlacement,
|
||||
StrictPlacement: c.StrictPlacement,
|
||||
FreeSlotsDeadband: int32(c.FreeSlotsDeadband),
|
||||
MaxShardTransfers: optionalInt32(c.MaxShardTransfers),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// optionalInt32 keeps unset (nil) distinct from sequential (0) on the proto field.
|
||||
func optionalInt32(n *int) *int32 {
|
||||
n = normalizedMaxShardTransfers(n)
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
v := int32(*n)
|
||||
return &v
|
||||
}
|
||||
|
||||
// normalizedMaxShardTransfers clamps a set cap into the proto int32 range.
|
||||
// nil stays nil so an absent knob is not stored as sequential.
|
||||
func normalizedMaxShardTransfers(n *int) *int {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
v := *n
|
||||
if v < 0 {
|
||||
v = 0
|
||||
}
|
||||
if v > math.MaxInt32 {
|
||||
v = math.MaxInt32
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
func optionalIntFromProto(n *int32) *int {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
v := int(*n)
|
||||
return &v
|
||||
}
|
||||
|
||||
// cloneMaxShardTransfers copies the cap so a task does not alias the live config.
|
||||
func cloneMaxShardTransfers(n *int) *int {
|
||||
return normalizedMaxShardTransfers(n)
|
||||
}
|
||||
|
||||
// FromTaskPolicy loads configuration from a TaskPolicy protobuf message
|
||||
func (c *Config) FromTaskPolicy(policy *worker_pb.TaskPolicy) error {
|
||||
if policy == nil {
|
||||
@@ -294,8 +250,6 @@ func (c *Config) FromTaskPolicy(policy *worker_pb.TaskPolicy) error {
|
||||
c.ReplicaPlacement = ecConfig.ReplicaPlacement
|
||||
c.StrictPlacement = ecConfig.StrictPlacement
|
||||
c.FreeSlotsDeadband = int(ecConfig.FreeSlotsDeadband)
|
||||
// Read the pointer, not GetMaxShardTransfers: the getter maps unset to 0.
|
||||
c.MaxShardTransfers = normalizedMaxShardTransfers(optionalIntFromProto(ecConfig.MaxShardTransfers))
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestMaxShardTransfersPolicyRoundTrip(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in *int
|
||||
}{
|
||||
{name: "unset", in: nil},
|
||||
{name: "sequential", in: intPtr(0)},
|
||||
{name: "cap", in: intPtr(4)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := NewDefaultConfig()
|
||||
cfg.MaxShardTransfers = cloneMaxShardTransfers(tc.in)
|
||||
|
||||
raw, err := proto.Marshal(cfg.ToTaskPolicy())
|
||||
require.NoError(t, err)
|
||||
var decoded worker_pb.TaskPolicy
|
||||
require.NoError(t, proto.Unmarshal(raw, &decoded))
|
||||
|
||||
restored := NewDefaultConfig()
|
||||
require.NoError(t, restored.FromTaskPolicy(&decoded))
|
||||
ec := decoded.GetErasureCodingConfig()
|
||||
require.NotNil(t, ec)
|
||||
if tc.in == nil {
|
||||
require.Nil(t, ec.MaxShardTransfers)
|
||||
require.Nil(t, restored.MaxShardTransfers)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, ec.MaxShardTransfers)
|
||||
require.Equal(t, int32(*tc.in), *ec.MaxShardTransfers)
|
||||
require.NotNil(t, restored.MaxShardTransfers)
|
||||
require.Equal(t, *tc.in, *restored.MaxShardTransfers)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxShardTransfersNegativeClampsToSequential(t *testing.T) {
|
||||
cfg := NewDefaultConfig()
|
||||
cfg.MaxShardTransfers = intPtr(-3)
|
||||
restored := NewDefaultConfig()
|
||||
require.NoError(t, restored.FromTaskPolicy(cfg.ToTaskPolicy()))
|
||||
require.NotNil(t, restored.MaxShardTransfers)
|
||||
require.Equal(t, 0, *restored.MaxShardTransfers)
|
||||
}
|
||||
|
||||
func intPtr(n int) *int { return &n }
|
||||
@@ -64,10 +64,6 @@ type ErasureCodingTask struct {
|
||||
// with, read back off the EC context. Every holder must report serving the
|
||||
// same one before the source volume may be deleted.
|
||||
encodedBlockSize int64
|
||||
|
||||
// maxShardTransfers is the optional global cap for shard fan-out.
|
||||
// nil = no cap (one in-flight per dest disk/node); 0 = sequential; N>0 = cap.
|
||||
maxShardTransfers *int
|
||||
}
|
||||
|
||||
// NewErasureCodingTask creates a new unified EC task instance
|
||||
@@ -801,9 +797,7 @@ func (t *ErasureCodingTask) generateEcShardsLocally(localFiles map[string]string
|
||||
// distributeEcShards distributes locally generated EC shards to destination servers
|
||||
// using pre-assigned shard IDs from planning phase
|
||||
func (t *ErasureCodingTask) distributeEcShards(shardFiles map[string]string) error {
|
||||
assignment, err := erasure_coding.DistributeEcShards(t.volumeID, t.collection, t.targets, shardFiles, t.grpcDialOption, t.GetLogger(), &erasure_coding.ShardDistributionOptions{
|
||||
MaxShardTransfers: t.maxShardTransfers,
|
||||
})
|
||||
assignment, err := erasure_coding.DistributeEcShards(t.volumeID, t.collection, t.targets, shardFiles, t.grpcDialOption, t.GetLogger())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package erasure_coding
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -175,20 +174,6 @@ func (h *ErasureCodingHandler) Descriptor() *plugin_pb.JobTypeDescriptor {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
SectionId: "shard_distribution",
|
||||
Title: "Shard distribution",
|
||||
Description: "How many EC shard copies are in flight. The checkbox is presentation only; the saved value is max_shard_transfers.",
|
||||
Fields: []*plugin_pb.ConfigField{
|
||||
{
|
||||
Name: "max_shard_transfers",
|
||||
Label: "Parallel shard distribution",
|
||||
Description: "Unchecked sends shards sequentially. Checked with an empty max uses one in-flight copy per destination disk. A number is a global cap, still one copy per disk.",
|
||||
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
|
||||
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
DefaultValues: map[string]*plugin_pb.ConfigValue{
|
||||
"quiet_for_seconds": {
|
||||
@@ -560,7 +545,6 @@ func (h *ErasureCodingHandler) Execute(
|
||||
h.grpcDialOption,
|
||||
)
|
||||
task.workerAddress = h.workerAddress
|
||||
task.maxShardTransfers = deriveErasureCodingWorkerConfig(request.GetWorkerConfigValues()).TaskConfig.MaxShardTransfers
|
||||
execCtx, execCancel := context.WithCancel(ctx)
|
||||
defer execCancel()
|
||||
task.SetProgressCallback(func(progress float64, stage string) {
|
||||
@@ -685,33 +669,12 @@ func deriveErasureCodingWorkerConfig(values map[string]*plugin_pb.ConfigValue) *
|
||||
deadband = 100000
|
||||
}
|
||||
taskConfig.FreeSlotsDeadband = deadband
|
||||
taskConfig.MaxShardTransfers = maxShardTransfersFromValues(values)
|
||||
|
||||
return &erasureCodingWorkerConfig{
|
||||
TaskConfig: taskConfig,
|
||||
}
|
||||
}
|
||||
|
||||
// maxShardTransfersFromValues returns nil when the key is absent so shard
|
||||
// distribution keeps the uncapped default. 0 is sequential; N>0 is a global cap.
|
||||
func maxShardTransfersFromValues(values map[string]*plugin_pb.ConfigValue) *int {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
value, ok := values["max_shard_transfers"]
|
||||
if !ok || value == nil {
|
||||
return nil
|
||||
}
|
||||
n := pluginworker.ReadInt64Config(values, "max_shard_transfers", 0)
|
||||
v := 0
|
||||
if n > math.MaxInt32 {
|
||||
v = math.MaxInt32
|
||||
} else if n > 0 {
|
||||
v = int(n)
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
func buildErasureCodingProposal(
|
||||
result *workertypes.TaskDetectionResult,
|
||||
baseWorkingDir string,
|
||||
|
||||
@@ -2,7 +2,6 @@ package erasure_coding
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -140,46 +139,6 @@ func TestDeriveErasureCodingWorkerConfig(t *testing.T) {
|
||||
if cfg.TaskConfig.FreeSlotsDeadband != 12 {
|
||||
t.Fatalf("expected free_slots_deadband 12, got %d", cfg.TaskConfig.FreeSlotsDeadband)
|
||||
}
|
||||
if cfg.TaskConfig.MaxShardTransfers != nil {
|
||||
t.Fatalf("missing max_shard_transfers must stay unset, got %d", *cfg.TaskConfig.MaxShardTransfers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveErasureCodingWorkerConfigMaxShardTransfers(t *testing.T) {
|
||||
if got := deriveErasureCodingWorkerConfig(nil).TaskConfig.MaxShardTransfers; got != nil {
|
||||
t.Fatalf("nil values: got %d, want unset", *got)
|
||||
}
|
||||
if got := deriveErasureCodingWorkerConfig(map[string]*plugin_pb.ConfigValue{}).TaskConfig.MaxShardTransfers; got != nil {
|
||||
t.Fatalf("missing key: got %d, want unset", *got)
|
||||
}
|
||||
|
||||
cfg := deriveErasureCodingWorkerConfig(map[string]*plugin_pb.ConfigValue{
|
||||
"max_shard_transfers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
|
||||
})
|
||||
if cfg.TaskConfig.MaxShardTransfers == nil || *cfg.TaskConfig.MaxShardTransfers != 0 {
|
||||
t.Fatalf("0: got %v, want 0 (sequential)", cfg.TaskConfig.MaxShardTransfers)
|
||||
}
|
||||
|
||||
cfg = deriveErasureCodingWorkerConfig(map[string]*plugin_pb.ConfigValue{
|
||||
"max_shard_transfers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 4}},
|
||||
})
|
||||
if cfg.TaskConfig.MaxShardTransfers == nil || *cfg.TaskConfig.MaxShardTransfers != 4 {
|
||||
t.Fatalf("4: got %v, want 4", cfg.TaskConfig.MaxShardTransfers)
|
||||
}
|
||||
|
||||
cfg = deriveErasureCodingWorkerConfig(map[string]*plugin_pb.ConfigValue{
|
||||
"max_shard_transfers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: -3}},
|
||||
})
|
||||
if cfg.TaskConfig.MaxShardTransfers == nil || *cfg.TaskConfig.MaxShardTransfers != 0 {
|
||||
t.Fatalf("negative: got %v, want 0", cfg.TaskConfig.MaxShardTransfers)
|
||||
}
|
||||
|
||||
cfg = deriveErasureCodingWorkerConfig(map[string]*plugin_pb.ConfigValue{
|
||||
"max_shard_transfers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: math.MaxInt32 + 1}},
|
||||
})
|
||||
if cfg.TaskConfig.MaxShardTransfers == nil || *cfg.TaskConfig.MaxShardTransfers != math.MaxInt32 {
|
||||
t.Fatalf("above int32: got %v, want clamp to %d", cfg.TaskConfig.MaxShardTransfers, int64(math.MaxInt32))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildErasureCodingProposal(t *testing.T) {
|
||||
@@ -332,15 +291,6 @@ func TestErasureCodingDescriptorExposesFreeSlotsDeadband(t *testing.T) {
|
||||
if sectionID != "placement" {
|
||||
t.Fatalf("free_slots_deadband section = %q, want placement", sectionID)
|
||||
}
|
||||
if !workerConfigFormHasField(descriptor.WorkerConfigForm, "max_shard_transfers") {
|
||||
t.Fatal("worker config form omitted max_shard_transfers")
|
||||
}
|
||||
if _, ok := descriptor.WorkerConfigForm.DefaultValues["max_shard_transfers"]; ok {
|
||||
t.Fatal("max_shard_transfers default would collapse unset into 0")
|
||||
}
|
||||
if _, ok := descriptor.WorkerDefaultValues["max_shard_transfers"]; ok {
|
||||
t.Fatal("worker default max_shard_transfers would collapse unset into 0")
|
||||
}
|
||||
if prev != "placement" {
|
||||
t.Fatalf("replica_placement section = %q, want placement next to free_slots_deadband", prev)
|
||||
}
|
||||
|
||||
@@ -51,17 +51,13 @@ func RegisterErasureCodingTask() {
|
||||
if len(params.Sources) == 0 {
|
||||
return nil, fmt.Errorf("at least one source is required for erasure coding task")
|
||||
}
|
||||
task := NewErasureCodingTask(
|
||||
return NewErasureCodingTask(
|
||||
fmt.Sprintf("erasure_coding-%d", params.VolumeId),
|
||||
params.Sources[0].Node, // Use first source node
|
||||
params.VolumeId,
|
||||
params.Collection,
|
||||
dialOpt,
|
||||
)
|
||||
if cfg, ok := globalTaskDef.Config.(*Config); ok {
|
||||
task.maxShardTransfers = cloneMaxShardTransfers(cfg.MaxShardTransfers)
|
||||
}
|
||||
return task, nil
|
||||
), nil
|
||||
},
|
||||
DetectionFunc: func(metrics []*types.VolumeHealthMetrics, clusterInfo *types.ClusterInfo, config base.TaskConfig) ([]*types.TaskDetectionResult, error) {
|
||||
results, _, err := Detection(context.Background(), metrics, clusterInfo, config, 0)
|
||||
|
||||
Reference in new issue
Block a user