mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 19:17:28 +01:00
Compare commits
55
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2e8af7890 | ||
|
|
2b30b7112b | ||
|
|
f88f59527f | ||
|
|
96fbacae68 | ||
|
|
fa2f554e8c | ||
|
|
b2da504615 | ||
|
|
dc6f80c8c6 | ||
|
|
bf7927f756 | ||
|
|
8c9a331568 | ||
|
|
6eeb764409 | ||
|
|
f94aaf6dc8 | ||
|
|
d058214660 | ||
|
|
f720c0e584 | ||
|
|
7c0e2c39d4 | ||
|
|
49d6091e59 | ||
|
|
be7b803379 | ||
|
|
54a6c0dce1 | ||
|
|
6860a6404e | ||
|
|
c9e84e4463 | ||
|
|
d6dee41f00 | ||
|
|
76aa922d06 | ||
|
|
13d9f3b104 | ||
|
|
82a435c468 | ||
|
|
a2a7a589bb | ||
|
|
19204293c2 | ||
|
|
f9c08ad379 | ||
|
|
3beca7d956 | ||
|
|
746cae3895 | ||
|
|
d63c225d78 | ||
|
|
5c5e282787 | ||
|
|
29c9e9df04 | ||
|
|
e9fa5802e1 | ||
|
|
43556b3a3c | ||
|
|
29eebd7bb2 | ||
|
|
e3e3bacf10 | ||
|
|
24951dbfe7 | ||
|
|
de76148f54 | ||
|
|
265b3aae0f | ||
|
|
9cea13b9fc | ||
|
|
d4910b70cf | ||
|
|
139c1d6d04 | ||
|
|
394e9d247e | ||
|
|
aeca7a9a8a | ||
|
|
5815d13881 | ||
|
|
501cf6b760 | ||
|
|
4830ae5e96 | ||
|
|
54f0c7ca5b | ||
|
|
81b83b155f | ||
|
|
df2fa630c1 | ||
|
|
0d09c87281 | ||
|
|
d807dbfcbc | ||
|
|
480a1baa20 | ||
|
|
ac2efbac01 | ||
|
|
10381075f3 | ||
|
|
51d591e060 |
No files matched your search
@@ -73,6 +73,13 @@ jobs:
|
||||
echo "=== Running S3 Prefix Object Tests ==="
|
||||
go test -v -timeout=180s -run TestS3PrefixObjectKeys ./...
|
||||
|
||||
- name: Run S3 GetPart Tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/normal
|
||||
run: |
|
||||
set -x
|
||||
go test -v -timeout=180s -run TestS3GetPart ./...
|
||||
|
||||
- name: Run IAM Integration Tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/normal
|
||||
|
||||
@@ -37,10 +37,24 @@ if [ "$(id -u)" = "0" ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# A restrictive Docker daemon umask can leave these 0600, and the resolver
|
||||
# then falls back to a nameserver on localhost once privileges are dropped.
|
||||
for f in /etc/resolv.conf /etc/hosts; do
|
||||
if [ -f "$f" ] && ! su-exec seaweed test -r "$f"; then
|
||||
chmod a+r "$f" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# Use su-exec to drop privileges and run as seaweed user
|
||||
exec su-exec seaweed "$0" "$@"
|
||||
fi
|
||||
|
||||
for f in /etc/resolv.conf /etc/hosts; do
|
||||
if [ -f "$f" ] && [ ! -r "$f" ]; then
|
||||
echo "Warning: $f is not readable by uid $(id -u), so host name lookups may fail. Make it world-readable (0644)." >&2
|
||||
fi
|
||||
done
|
||||
|
||||
isArgPassed() {
|
||||
# Match both `-flag` and `--flag` (and their `=value` forms): the Go fla9
|
||||
# library accepts both, and users may pick either form on the CLI.
|
||||
|
||||
@@ -30,10 +30,12 @@ Override `SEAWEEDFS_IMAGE` to test a newer image. With metrics-enabled engines,
|
||||
append `--metrics-port=9329 --metrics-ip=0.0.0.0` to the vector command and scrape
|
||||
`vector:9329/metrics` inside the Compose network.
|
||||
|
||||
A native development setup can use `weed mini -vector -vectorBucket=embeddings`
|
||||
with `weed-vector` beside `weed` or on PATH. `-vector.binary` selects an explicit
|
||||
binary, and `-vector.metricsPort=9329` enables HTTP readiness and metrics on a
|
||||
compatible engine. The child inherits the cluster's configuration directory and
|
||||
stops with mini. Run `weed-worker` separately for ANN maintenance. `weed shell`
|
||||
provides `s3vectors -operation <Operation> -file request.json` for the same API
|
||||
operations using trusted cluster credentials.
|
||||
A native development setup can use `weed mini -vectorBucket=embeddings`. Mini
|
||||
starts `weed-vector` and the `weed-worker` maintenance worker when it finds them
|
||||
beside `weed` or on PATH, and logs and continues without one it cannot find.
|
||||
`-vector.binary` selects an explicit engine binary, and `weed-worker` is also
|
||||
looked up beside it. `-vector=false` leaves both out, and
|
||||
`-vector.metricsPort=9329` enables HTTP readiness and metrics on a compatible
|
||||
engine. The children inherit the cluster's configuration directory and stop with
|
||||
mini. `weed shell` provides `s3vectors -operation <Operation> -file
|
||||
request.json` for the same API operations using trusted cluster credentials.
|
||||
@@ -1,7 +1,7 @@
|
||||
services:
|
||||
seaweedfs:
|
||||
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
|
||||
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE
|
||||
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE -vector=false
|
||||
environment: &environment
|
||||
WEED_JWT_FILER_SIGNING_KEY: vector-demo-cluster-key
|
||||
AWS_ACCESS_KEY_ID: vector-demo
|
||||
|
||||
@@ -12,6 +12,7 @@ require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
github.com/KimMachineGun/automemlimit v1.0.2
|
||||
github.com/Shopify/sarama v1.38.1
|
||||
github.com/ThreeDotsLabs/watermill v1.5.3
|
||||
github.com/a-h/templ v0.3.1100
|
||||
@@ -378,6 +379,7 @@ require (
|
||||
github.com/parquet-go/bitpack v1.1.1 // indirect
|
||||
github.com/parquet-go/jsonlite v1.5.7 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
|
||||
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
|
||||
|
||||
@@ -85,6 +85,8 @@ github.com/IBM/go-sdk-core/v5 v5.23.1 h1:fxLusCG+GlGY1SM7BYAAiiSFhzKUs5zqs0P8knD
|
||||
github.com/IBM/go-sdk-core/v5 v5.23.1/go.mod h1:yO+OQpByKDLTvpEcsFFexgzpeR8eRfCFWAYzxkAu4bk=
|
||||
github.com/Jille/raft-grpc-transport v1.6.1 h1:gN3sjapb+fVbiebS7AfQQgbV2ecTOI7ur7NPPC7Mhoc=
|
||||
github.com/Jille/raft-grpc-transport v1.6.1/go.mod h1:HbOjEdu/yzCJ/mjTF6wEOJNbAUpHfU2UOA2hVD4CNFg=
|
||||
github.com/KimMachineGun/automemlimit v1.0.2 h1:DkORkhuzrwT2/b35xz8zLd7cJ6Hu2ESRGBY8HKUFIYk=
|
||||
github.com/KimMachineGun/automemlimit v1.0.2/go.mod h1:n+BSXxQWDFS1DKh67Rqo0lgTsowsg6x65ak5uyngML0=
|
||||
github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g=
|
||||
github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
|
||||
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd h1:nzE1YQBdx1bq9IlZinHa+HVffy+NmVRoKr+wHN8fpLE=
|
||||
@@ -964,6 +966,8 @@ github.com/parquet-go/parquet-go v0.33.0/go.mod h1:zl2XMxzSXZ5UYGfTLK0kvW0ifgVMP
|
||||
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
|
||||
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
|
||||
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
|
||||
+1056
-1060
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
@@ -289,6 +289,9 @@ message LookupVolumeResponse {
|
||||
repeated Location locations = 2;
|
||||
string error = 3;
|
||||
string auth = 4;
|
||||
// > 0 when the volume was grown degraded: a write needs this many
|
||||
// writable copies instead of its replica placement's copy count.
|
||||
uint32 min_writable_copies = 5;
|
||||
}
|
||||
repeated VolumeIdLocation volume_id_locations = 1;
|
||||
}
|
||||
@@ -438,6 +441,7 @@ message DataNodeInfo {
|
||||
uint32 grpc_port = 3;
|
||||
int64 last_heartbeat_ns = 5;
|
||||
string address = 4; // ip:port for connecting to the volume server
|
||||
bool maintenance = 6; // the volume server refuses new data while set
|
||||
}
|
||||
message RackInfo {
|
||||
string id = 1;
|
||||
|
||||
@@ -188,7 +188,7 @@ pub struct Cli {
|
||||
pub min_free_space_percent: String,
|
||||
|
||||
/// Min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB).
|
||||
/// Low disk space will mark all volumes as ReadOnly.
|
||||
/// Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit.
|
||||
#[arg(long = "minFreeSpace", default_value = "")]
|
||||
pub min_free_space: String,
|
||||
|
||||
@@ -374,6 +374,27 @@ impl MinFreeSpace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Go's util.MinFreeSpaceReleaseMarginPercent.
|
||||
pub const RELEASE_MARGIN_PERCENT: u64 = 1;
|
||||
|
||||
/// Mirrors Go's MinFreeSpace.IsLowFrom: a location that was low stays low
|
||||
/// until free space is RELEASE_MARGIN_PERCENT of the disk above the limit.
|
||||
pub fn is_low_from(&self, was_low: bool, free_bytes: u64, total_bytes: u64) -> bool {
|
||||
let low = self.is_low(free_bytes, total_bytes);
|
||||
if !was_low || low {
|
||||
return low;
|
||||
}
|
||||
match self {
|
||||
MinFreeSpace::Percent(pct) => {
|
||||
free_bytes as f64 / total_bytes as f64 * 100.0
|
||||
< *pct + Self::RELEASE_MARGIN_PERCENT as f64
|
||||
}
|
||||
MinFreeSpace::Bytes(min) => {
|
||||
free_bytes < min.saturating_add(total_bytes / 100 * Self::RELEASE_MARGIN_PERCENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Free bytes above the floor; mirrors Go's MinFreeSpace.AvailableSpace.
|
||||
pub fn available_space(&self, free_bytes: u64, total_bytes: u64) -> u64 {
|
||||
let floor = match self {
|
||||
@@ -1717,6 +1738,46 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_min_free_space_is_low_from_holds_until_margin() {
|
||||
let pct = MinFreeSpace::Percent(7.0);
|
||||
let total = 10_000u64;
|
||||
for (was_low, free, want) in [
|
||||
(false, 699, true),
|
||||
(false, 702, false),
|
||||
(true, 702, true),
|
||||
(true, 799, true),
|
||||
(true, 800, false),
|
||||
(false, 799, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
pct.is_low_from(was_low, free, total),
|
||||
want,
|
||||
"percent was_low={was_low} free={free}"
|
||||
);
|
||||
}
|
||||
|
||||
let gib = 1u64 << 30;
|
||||
let bytes = MinFreeSpace::Bytes(70 * gib);
|
||||
let total = 1000 * gib;
|
||||
for (was_low, free, want) in [
|
||||
(false, 70 * gib - 1, true),
|
||||
(false, 70 * gib, false),
|
||||
(true, 70 * gib + 1, true),
|
||||
(true, 80 * gib - 1, true),
|
||||
(true, 80 * gib, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
bytes.is_low_from(was_low, free, total),
|
||||
want,
|
||||
"bytes was_low={was_low} free={free}"
|
||||
);
|
||||
}
|
||||
|
||||
let near_max = MinFreeSpace::Bytes(u64::MAX - 1);
|
||||
assert!(near_max.is_low_from(true, u64::MAX - 1, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_min_free_spaces_percent() {
|
||||
let result = parse_min_free_spaces("", "1").unwrap();
|
||||
|
||||
@@ -577,12 +577,13 @@ async fn master_lookup_once(
|
||||
|
||||
/// Look up volume locations over the master's gRPC port, like Go's
|
||||
/// operation.LookupVolumeIds: the master's HTTP port need not speak the
|
||||
/// `[https.client]` scheme.
|
||||
/// `[https.client]` scheme. Also returns the master's min_writable_copies
|
||||
/// (0 unless the volume was grown degraded).
|
||||
async fn lookup_volume(
|
||||
tls: Option<&OutgoingGrpcTlsConfig>,
|
||||
master_url: &str,
|
||||
volume_id: u32,
|
||||
) -> Result<Vec<VolumeLocation>, String> {
|
||||
) -> Result<(Vec<VolumeLocation>, u32), String> {
|
||||
let grpc_addr = parse_grpc_address(master_url)?;
|
||||
let cached = MASTER_LOOKUP_CHANNEL
|
||||
.lock()
|
||||
@@ -618,15 +619,17 @@ async fn lookup_volume(
|
||||
}
|
||||
};
|
||||
let mut locations = Vec::new();
|
||||
let mut min_writable_copies = 0;
|
||||
for found in resp.volume_id_locations {
|
||||
// Mirror Go: a per-volume error in an answered lookup (e.g. a missing
|
||||
// volume) means "no locations"; only a failed call is an error.
|
||||
if !found.error.is_empty() {
|
||||
tracing::debug!("volume {} lookup: {}", volume_id, found.error);
|
||||
}
|
||||
min_writable_copies = min_writable_copies.max(found.min_writable_copies);
|
||||
locations.extend(found.locations.into_iter().map(VolumeLocation::from));
|
||||
}
|
||||
Ok(locations)
|
||||
Ok((locations, min_writable_copies))
|
||||
}
|
||||
|
||||
fn grpc_address_for_location(location: &VolumeLocation) -> Result<String, String> {
|
||||
@@ -678,7 +681,7 @@ async fn batch_delete_file_ids(
|
||||
let locations = if let Some(locations) = lookup_cache.get(&volume_id) {
|
||||
locations.clone()
|
||||
} else {
|
||||
let locations = lookup_volume(
|
||||
let (locations, _) = lookup_volume(
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
&state.current_master().await,
|
||||
volume_id,
|
||||
@@ -828,7 +831,7 @@ async fn do_replicated_request(
|
||||
body: Option<bytes::Bytes>,
|
||||
replica_jwt: Option<&ReplicaJwt>,
|
||||
) -> Result<(), String> {
|
||||
let locations = lookup_volume(
|
||||
let (locations, min_writable_copies) = lookup_volume(
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
&state.current_master().await,
|
||||
vid,
|
||||
@@ -839,9 +842,15 @@ async fn do_replicated_request(
|
||||
let copy_count = {
|
||||
let store = state.store.read().unwrap();
|
||||
store.find_volume(VolumeId(vid)).map_or(1, |(_, v)| {
|
||||
v.super_block().replica_placement.get_copy_count()
|
||||
v.super_block().replica_placement.get_copy_count() as u32
|
||||
})
|
||||
};
|
||||
// A degraded volume is writable with fewer copies, like Go's
|
||||
// getRemoteReplications.
|
||||
let copy_count = match min_writable_copies {
|
||||
n if n > 0 && n < copy_count => n,
|
||||
_ => copy_count,
|
||||
};
|
||||
let allow_delete = method == axum::http::Method::DELETE;
|
||||
let eligible_locations: Vec<_> = locations
|
||||
.into_iter()
|
||||
@@ -1009,7 +1018,7 @@ async fn proxy_or_redirect_to_target(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(locs) => locs,
|
||||
Ok((locs, _)) => locs,
|
||||
Err(e) => {
|
||||
tracing::warn!("volume lookup failed for {}: {}", vid.0, e);
|
||||
// Go: master lookup failure is 500 in proxy mode, 404 for redirect
|
||||
@@ -4927,7 +4936,7 @@ async fn read_remote_chunk_needle(
|
||||
fid: &str,
|
||||
how: RemoteRead,
|
||||
) -> Result<ChunkBytes, String> {
|
||||
let locations = lookup_volume(
|
||||
let (locations, _) = lookup_volume(
|
||||
state.outgoing_grpc_tls.as_ref(),
|
||||
&state.current_master().await,
|
||||
vid.0,
|
||||
@@ -5485,6 +5494,67 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A volume grown degraded keeps its placement's copy count in the super
|
||||
/// block; the master's min_writable_copies lets it write with fewer.
|
||||
#[tokio::test]
|
||||
async fn http_replicated_write_uses_the_master_min_writable_copies() {
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
use tower::ServiceExt;
|
||||
|
||||
let app = axum::Router::new().fallback(|| async { StatusCode::CREATED });
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let peer = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
for (min_writable_copies, written) in [(0, false), (2, true), (3, false)] {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let mut state = volume_test_state(&tmp);
|
||||
Arc::get_mut(&mut state).unwrap().self_url = "127.0.0.1:8080".to_string();
|
||||
state
|
||||
.store
|
||||
.read()
|
||||
.unwrap()
|
||||
.find_volume(VolumeId(1))
|
||||
.unwrap()
|
||||
.1
|
||||
.set_replica_placement(ReplicaPlacement::from_string("200").unwrap())
|
||||
.unwrap();
|
||||
*state.current_master_url.write().await = spawn_lookup_master(move |vid| {
|
||||
let location = |url: String| master_pb::Location {
|
||||
url,
|
||||
..Default::default()
|
||||
};
|
||||
let mut answer = lookup_answer(
|
||||
vid,
|
||||
vec![
|
||||
location("127.0.0.1:8080".to_string()),
|
||||
location(peer.to_string()),
|
||||
],
|
||||
"",
|
||||
);
|
||||
answer.volume_id_locations[0].min_writable_copies = min_writable_copies;
|
||||
Ok(answer)
|
||||
})
|
||||
.await;
|
||||
|
||||
let response = super::super::volume_server::build_admin_router(state)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri(format!("/1,{:x}{TEST_COOKIE:08x}", 0x6e7a_0c04u64))
|
||||
.body(Body::from("x"))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.status() == StatusCode::CREATED,
|
||||
written,
|
||||
"{min_writable_copies}: {}",
|
||||
response.status()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A write forward carries a JWT signed for it, not the incoming one, which
|
||||
/// can expire while the body streams in.
|
||||
#[tokio::test]
|
||||
@@ -6420,7 +6490,7 @@ mod tests {
|
||||
.await;
|
||||
|
||||
for _ in 0..2 {
|
||||
let locations = super::lookup_volume(None, &master_url, 31)
|
||||
let (locations, _) = super::lookup_volume(None, &master_url, 31)
|
||||
.await
|
||||
.expect("lookup over the master's gRPC port");
|
||||
assert_eq!(locations.len(), 1);
|
||||
@@ -6471,7 +6541,7 @@ mod tests {
|
||||
})
|
||||
.await;
|
||||
|
||||
let locations = super::lookup_volume(None, &master_url, 7)
|
||||
let (locations, _) = super::lookup_volume(None, &master_url, 7)
|
||||
.await
|
||||
.expect("missing volume is not a lookup failure");
|
||||
assert!(locations.is_empty());
|
||||
|
||||
@@ -905,6 +905,15 @@ impl DiskLocation {
|
||||
unused
|
||||
}
|
||||
|
||||
/// Mirrors Go's DiskLocation.updateDiskSpaceLow for a reading with space
|
||||
/// values.
|
||||
fn update_disk_space_low(&self, free: u64, total: u64) -> bool {
|
||||
let was_low = self.is_disk_space_low.load(Ordering::Relaxed);
|
||||
let is_low = self.min_free_space.is_low_from(was_low, free, total);
|
||||
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
|
||||
is_low
|
||||
}
|
||||
|
||||
/// Check disk space against min_free_space and update is_disk_space_low.
|
||||
pub fn check_disk_space(&self) {
|
||||
let (total, free) = get_disk_stats(&self.directory);
|
||||
@@ -912,8 +921,7 @@ impl DiskLocation {
|
||||
return;
|
||||
}
|
||||
let used = total.saturating_sub(free);
|
||||
let is_low = self.min_free_space.is_low(free, total);
|
||||
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
|
||||
self.update_disk_space_low(free, total);
|
||||
// Go's DiskLocation.AvailableSpace counts only free space above the
|
||||
// -volume.minFreeSpace floor, so space checks stay above it too.
|
||||
self.available_space.store(
|
||||
@@ -1701,6 +1709,40 @@ mod tests {
|
||||
assert_eq!(loc.available_space.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
// Mirrors Go's TestDiskSpaceLowStaysUntilFreeSpaceIsClearlyBack: a
|
||||
// location that went low stays low until free space clears the margin.
|
||||
#[test]
|
||||
fn test_disk_space_low_stays_until_free_space_is_clearly_back() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = DiskLocation::new(
|
||||
dir,
|
||||
dir,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(7.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let total = 10_000u64;
|
||||
for (free, want) in [
|
||||
(699, true),
|
||||
(702, true),
|
||||
(698, true),
|
||||
(760, true),
|
||||
(800, false),
|
||||
(702, false),
|
||||
(699, true),
|
||||
] {
|
||||
assert_eq!(
|
||||
loc.update_disk_space_low(free, total),
|
||||
want,
|
||||
"free {free} of {total}"
|
||||
);
|
||||
assert_eq!(loc.is_disk_space_low.load(Ordering::Relaxed), want);
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrors Go's CheckDiskSpace pending subtraction: an in-flight copy's
|
||||
// charge stays out of the cache across a probe, so another copy cannot
|
||||
// re-spend the headroom the live reading still shows as free.
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// getPart issues GetPart, which the SDK this suite pins predates, as a signed
|
||||
// raw request.
|
||||
func getPart(t *testing.T, cluster *TestCluster, creds *credentials.Credentials, bucket, key, uploadID string, partNumber int, header http.Header) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
query := url.Values{}
|
||||
query.Set("part", "")
|
||||
query.Set("partNumber", fmt.Sprint(partNumber))
|
||||
query.Set("uploadId", uploadID)
|
||||
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s/%s?%s", cluster.s3Endpoint, bucket, key, query.Encode()), nil)
|
||||
require.NoError(t, err)
|
||||
for k, v := range header {
|
||||
req.Header[k] = v
|
||||
}
|
||||
_, err = v4.NewSigner(creds).Sign(req, nil, "s3", testRegion, time.Now())
|
||||
require.NoError(t, err)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return resp, body
|
||||
}
|
||||
|
||||
func errorCode(t *testing.T, body []byte) string {
|
||||
t.Helper()
|
||||
var e struct{ Code string }
|
||||
require.NoError(t, xml.Unmarshal(body, &e), string(body))
|
||||
return e.Code
|
||||
}
|
||||
|
||||
func TestS3GetPart(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
admin := client.Config.Credentials
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-")
|
||||
key := "media/clip.bin"
|
||||
|
||||
part1 := bytes.Repeat([]byte("a"), 5*1024*1024)
|
||||
part1Retry := bytes.Repeat([]byte("c"), 5*1024*1024)
|
||||
part2 := []byte("the last part, short")
|
||||
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
uploadID := aws.StringValue(created.UploadId)
|
||||
upload := func(n int64, data []byte) *s3.UploadPartOutput {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
PartNumber: aws.Int64(n), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return out
|
||||
}
|
||||
upload(1, part1)
|
||||
retried := upload(1, part1Retry)
|
||||
uploaded2 := upload(2, part2)
|
||||
|
||||
t.Run("open upload serves the latest attempt", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "IN_PROGRESS", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(retried.ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, resp.Header.Get("Content-Range"))
|
||||
assert.True(t, bytes.Equal(part1Retry, body), "part 1 body is not the retried attempt")
|
||||
})
|
||||
|
||||
t.Run("open upload range counts within the part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=4-7"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
assert.Equal(t, fmt.Sprintf("bytes 4-7/%d", len(part2)), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[4:8]), string(body))
|
||||
})
|
||||
|
||||
t.Run("missing part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchPart", errorCode(t, body))
|
||||
})
|
||||
|
||||
t.Run("sse request header is rejected", func(t *testing.T) {
|
||||
resp, _ := getPart(t, cluster, admin, bucket, key, uploadID, 1, http.Header{"X-Amz-Server-Side-Encryption": {"AES256"}})
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("open part returns its checksum when asked", func(t *testing.T) {
|
||||
data := []byte("checksummed part")
|
||||
sum := crc32.ChecksumIEEE(data)
|
||||
want := base64.StdEncoding.EncodeToString([]byte{byte(sum >> 24), byte(sum >> 16), byte(sum >> 8), byte(sum)})
|
||||
_, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
PartNumber: aws.Int64(5), Body: bytes.NewReader(data), ChecksumCRC32: aws.String(want),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 5, http.Header{"X-Amz-Checksum-Mode": {"ENABLED"}})
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, want, resp.Header.Get("x-amz-checksum-crc32"))
|
||||
})
|
||||
|
||||
t.Run("ListParts still answers without ?part", func(t *testing.T) {
|
||||
parts, err := client.ListParts(&s3.ListPartsInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID)})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, parts.Parts, 3)
|
||||
})
|
||||
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{
|
||||
{PartNumber: aws.Int64(1), ETag: retried.ETag},
|
||||
{PartNumber: aws.Int64(2), ETag: uploaded2.ETag},
|
||||
}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("completed upload serves the part from the object", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(uploaded2.ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed upload range counts within the part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=-4"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
n := len(part2)
|
||||
assert.Equal(t, fmt.Sprintf("bytes %d-%d/%d", n-4, n-1, n), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[n-4:]), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed upload has no such part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchPart", errorCode(t, body))
|
||||
})
|
||||
|
||||
t.Run("completed upload in a version that is no longer latest", func(t *testing.T) {
|
||||
vbucket := createTestBucket(t, cluster, "test-get-part-versioned-")
|
||||
_, err := client.PutBucketVersioning(&s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(vbucket), VersioningConfiguration: &s3.VersioningConfiguration{Status: aws.String("Enabled")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(vbucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(1), Body: bytes.NewReader(part2),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
done, err := client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: out.ETag}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = client.PutObject(&s3.PutObjectInput{Bucket: aws.String(vbucket), Key: aws.String(key), Body: strings.NewReader("newer")})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, body := getPart(t, cluster, admin, vbucket, key, aws.StringValue(created.UploadId), 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, aws.StringValue(done.VersionId), resp.Header.Get("x-amz-version-id"))
|
||||
assert.Equal(t, string(part2), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed empty part", func(t *testing.T) {
|
||||
emptyKey := "media/empty-tail.bin"
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(emptyKey)})
|
||||
require.NoError(t, err)
|
||||
var parts []*s3.CompletedPart
|
||||
for n, data := range [][]byte{part1, nil} {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(int64(n + 1)), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
parts = append(parts, &s3.CompletedPart{PartNumber: aws.Int64(int64(n + 1)), ETag: out.ETag})
|
||||
}
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: parts},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, body := getPart(t, cluster, admin, bucket, emptyKey, aws.StringValue(created.UploadId), 2, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(parts[1].ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, body)
|
||||
})
|
||||
|
||||
t.Run("aborted upload", func(t *testing.T) {
|
||||
other, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
_, err = client.AbortMultipartUpload(&s3.AbortMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: other.UploadId})
|
||||
require.NoError(t, err)
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, aws.StringValue(other.UploadId), 1, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchUpload", errorCode(t, body))
|
||||
})
|
||||
}
|
||||
|
||||
// TestS3GetPartIncompleteUploadGrant checks that reading a part of an open
|
||||
// upload needs s3:GetIncompleteUpload on top of s3:GetObject, while a
|
||||
// completed upload's part needs only the read grant.
|
||||
func TestS3GetPartIncompleteUploadGrant(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-grant-")
|
||||
openKey, doneKey := "open.bin", "done.bin"
|
||||
|
||||
start := func(key string) (string, *s3.UploadPartOutput) {
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
part, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(1), Body: strings.NewReader("only part"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return aws.StringValue(created.UploadId), part
|
||||
}
|
||||
openID, _ := start(openKey)
|
||||
doneID, donePart := start(doneKey)
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(doneKey), UploadId: aws.String(doneID),
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: donePart.ETag}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
sess, err := session.NewSession(client.Config.Copy())
|
||||
require.NoError(t, err)
|
||||
iamClient := iam.New(sess)
|
||||
userName := "getpart-reader"
|
||||
_, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
key, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
reader := credentials.NewStaticCredentials(aws.StringValue(key.AccessKey.AccessKeyId), aws.StringValue(key.AccessKey.SecretAccessKey), "")
|
||||
|
||||
grant := func(actions ...string) {
|
||||
policy := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["%s"],"Resource":["arn:aws:s3:::%s/*"]}]}`, strings.Join(actions, `","`), bucket)
|
||||
_, err := iamClient.PutUserPolicy(&iam.PutUserPolicyInput{UserName: aws.String(userName), PolicyName: aws.String("reader"), PolicyDocument: aws.String(policy)})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
expectStatus := func(t *testing.T, key, uploadID string, want int) {
|
||||
t.Helper()
|
||||
require.Eventually(t, func() bool {
|
||||
resp, _ := getPart(t, cluster, reader, bucket, key, uploadID, 1, nil)
|
||||
return resp.StatusCode == want
|
||||
}, 10*time.Second, 200*time.Millisecond)
|
||||
}
|
||||
|
||||
grant("s3:GetObject")
|
||||
t.Run("read grant alone reads a completed part", func(t *testing.T) {
|
||||
expectStatus(t, doneKey, doneID, http.StatusOK)
|
||||
})
|
||||
t.Run("read grant alone cannot read an open part", func(t *testing.T) {
|
||||
expectStatus(t, openKey, openID, http.StatusForbidden)
|
||||
})
|
||||
|
||||
grant("s3:GetObject", "s3:GetIncompleteUpload")
|
||||
t.Run("GetIncompleteUpload opens the part", func(t *testing.T) {
|
||||
expectStatus(t, openKey, openID, http.StatusOK)
|
||||
})
|
||||
}
|
||||
|
||||
// TestS3GetPartSSES3 reads SSE-S3 parts back decrypted, before and after the
|
||||
// upload completes.
|
||||
func TestS3GetPartSSES3(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
admin := client.Config.Credentials
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-sse-")
|
||||
key := "secret.bin"
|
||||
part1 := bytes.Repeat([]byte("0123456789"), 600*1024)
|
||||
part2 := []byte("encrypted tail")
|
||||
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), ServerSideEncryption: aws.String("AES256"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var completed []*s3.CompletedPart
|
||||
for i, data := range [][]byte{part1, part2} {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(int64(i + 1)), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
completed = append(completed, &s3.CompletedPart{PartNumber: aws.Int64(int64(i + 1)), ETag: out.ETag})
|
||||
}
|
||||
uploadID := aws.StringValue(created.UploadId)
|
||||
|
||||
check := func(t *testing.T, status string) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, status, resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.True(t, bytes.Equal(part1, body), "part 1 does not decrypt to what was uploaded")
|
||||
|
||||
resp, body = getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=0-8"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
assert.Equal(t, fmt.Sprintf("bytes 0-8/%d", len(part2)), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[:9]), string(body))
|
||||
}
|
||||
t.Run("open", func(t *testing.T) { check(t, "IN_PROGRESS") })
|
||||
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: completed},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
t.Run("completed", func(t *testing.T) { check(t, "COMPLETED") })
|
||||
}
|
||||
@@ -56,6 +56,9 @@ type AdminData struct {
|
||||
// VersionSummary reports whether all cluster nodes run the same binary
|
||||
// version, so the dashboard can warn about partially upgraded clusters.
|
||||
VersionSummary ClusterVersionSummary `json:"version_summary"`
|
||||
|
||||
UnderReplicatedVolumes int `json:"under_replicated_volumes"`
|
||||
MisplacedVolumes int `json:"misplaced_volumes"`
|
||||
}
|
||||
|
||||
// Object Store Users management structures
|
||||
@@ -261,6 +264,9 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
|
||||
Trends: s.GetDashboardTrends(),
|
||||
TierStats: topology.TierStats,
|
||||
VersionSummary: buildClusterVersionSummary(volumeServersData.VolumeServers, filerNodes, s3Nodes, messageBrokers),
|
||||
|
||||
UnderReplicatedVolumes: topology.UnderReplicatedVolumes,
|
||||
MisplacedVolumes: topology.MisplacedVolumes,
|
||||
}
|
||||
|
||||
return adminData, nil
|
||||
|
||||
@@ -251,6 +251,7 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
topology.TotalChunks = totalCollectionFileCount(resp.TopologyInfo)
|
||||
|
||||
topology.TierStats = CollectTierStats(resp.TopologyInfo, volumeSizeLimitMb)
|
||||
topology.UnderReplicatedVolumes, topology.MisplacedVolumes = countReplicaIssues(resp.TopologyInfo)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/topology/balancer"
|
||||
)
|
||||
|
||||
// countReplicaIssues counts the volumes volume.fix.replication would repair:
|
||||
// under-replicated ones, missing a copy or not spread as their placement
|
||||
// asks, and misplaced ones.
|
||||
func countReplicaIssues(topologyInfo *master_pb.TopologyInfo) (underReplicated, misplaced int) {
|
||||
replicas := make(map[uint32][]balancer.Replica)
|
||||
placements := make(map[uint32]uint32)
|
||||
for _, dc := range topologyInfo.GetDataCenterInfos() {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for _, dn := range rack.DataNodeInfos {
|
||||
loc := balancer.Location{
|
||||
DataCenter: dc.Id,
|
||||
Rack: rack.Id,
|
||||
NodeID: dn.Id,
|
||||
Host: pb.NewServerAddressFromDataNode(dn).ToHost(),
|
||||
}
|
||||
for _, disk := range dn.DiskInfos {
|
||||
for _, v := range disk.VolumeInfos {
|
||||
if _, found := placements[v.Id]; !found {
|
||||
placements[v.Id] = v.ReplicaPlacement
|
||||
}
|
||||
replicas[v.Id] = append(replicas[v.Id], balancer.Replica{Location: loc})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for vid, rs := range replicas {
|
||||
rp, _ := super_block.NewReplicaPlacementFromByte(byte(placements[vid]))
|
||||
locs := make([]balancer.Location, len(rs))
|
||||
for i, r := range rs {
|
||||
locs[i] = r.Location
|
||||
}
|
||||
switch {
|
||||
case rp.GetCopyCount() > len(rs) || !balancer.SatisfyReplicaCurrentLocation(rp, locs):
|
||||
underReplicated++
|
||||
case balancer.IsMisplaced(rs, rp):
|
||||
misplaced++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
func TestCountReplicaIssues(t *testing.T) {
|
||||
node := func(id string, volumes ...*master_pb.VolumeInformationMessage) *master_pb.DataNodeInfo {
|
||||
return &master_pb.DataNodeInfo{
|
||||
Id: id,
|
||||
Address: id,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{"": {VolumeInfos: volumes}},
|
||||
}
|
||||
}
|
||||
volume := func(id uint32, placement uint32) *master_pb.VolumeInformationMessage {
|
||||
return &master_pb.VolumeInformationMessage{Id: id, ReplicaPlacement: placement}
|
||||
}
|
||||
dc := func(id string, nodes ...*master_pb.DataNodeInfo) *master_pb.DataCenterInfo {
|
||||
return &master_pb.DataCenterInfo{Id: id, RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: nodes}}}
|
||||
}
|
||||
// placements are stored as their decimal digits: 200, 100, 001 as 1.
|
||||
topo := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{
|
||||
dc("dc1",
|
||||
node("10.0.0.11:8080", volume(1, 200), volume(2, 200), volume(3, 100), volume(4, 1), volume(5, 0)),
|
||||
node("10.0.0.12:8080", volume(4, 1))),
|
||||
dc("dc2", node("10.0.0.21:8080", volume(1, 200), volume(2, 200), volume(3, 100))),
|
||||
dc("dc3", node("10.0.0.31:8080", volume(1, 200))),
|
||||
}}
|
||||
// volume 1 has its 3 copies; volume 2, grown degraded, misses its dc3 copy.
|
||||
under, misplaced := countReplicaIssues(topo)
|
||||
if under != 1 || misplaced != 0 {
|
||||
t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 0", under, misplaced)
|
||||
}
|
||||
|
||||
// volume 6 (010) has its two racks, but in two data centers.
|
||||
dc1 := topo.DataCenterInfos[0].RackInfos[0].DataNodeInfos[0].DiskInfos[""]
|
||||
dc2 := topo.DataCenterInfos[1].RackInfos[0].DataNodeInfos[0].DiskInfos[""]
|
||||
dc1.VolumeInfos = append(dc1.VolumeInfos, volume(6, 10))
|
||||
dc2.VolumeInfos = append(dc2.VolumeInfos, volume(6, 10))
|
||||
under, misplaced = countReplicaIssues(topo)
|
||||
if under != 1 || misplaced != 1 {
|
||||
t.Fatalf("got %d under-replicated and %d misplaced, want 1 and 1", under, misplaced)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,10 @@ type ClusterTopology struct {
|
||||
// TierStats breaks volumes and EC shards down by storage tier: local
|
||||
// disk types plus one entry per remote storage holding tiered volumes.
|
||||
TierStats []TierStats `json:"tier_stats"`
|
||||
// UnderReplicatedVolumes and MisplacedVolumes count the volumes
|
||||
// volume.fix.replication would repair.
|
||||
UnderReplicatedVolumes int `json:"under_replicated_volumes"`
|
||||
MisplacedVolumes int `json:"misplaced_volumes"`
|
||||
}
|
||||
|
||||
type MasterNode struct {
|
||||
|
||||
@@ -78,7 +78,7 @@ func (at *ActiveTopology) GetEffectiveAvailableEcShardSlots(nodeID string, diskI
|
||||
|
||||
diskKey := fmt.Sprintf("%s:%d", nodeID, diskID)
|
||||
disk, exists := at.disks[diskKey]
|
||||
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
if !exists || disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -284,7 +284,7 @@ func (at *ActiveTopology) CanAccommodateTask(nodeID string, diskID uint32, taskT
|
||||
|
||||
// getPlanningCapacityUnsafe considers both pending and active tasks for planning
|
||||
func (at *ActiveTopology) getPlanningCapacityUnsafe(disk *activeDisk) StorageSlotChange {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
|
||||
return StorageSlotChange{}
|
||||
}
|
||||
|
||||
@@ -358,7 +358,7 @@ func (at *ActiveTopology) getEffectiveCapacityUnsafe(disk *activeDisk) StorageSl
|
||||
|
||||
// getEffectiveAvailableCapacityUnsafe returns detailed available capacity as StorageSlotChange
|
||||
func (at *ActiveTopology) getEffectiveAvailableCapacityUnsafe(disk *activeDisk) StorageSlotChange {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil {
|
||||
if disk.DiskInfo == nil || disk.DiskInfo.DiskInfo == nil || at.inMaintenanceUnsafe(disk) {
|
||||
return StorageSlotChange{}
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,13 @@ func (at *ActiveTopology) assignTaskToDisk(task *taskState) {
|
||||
}
|
||||
}
|
||||
|
||||
// inMaintenanceUnsafe reports whether the disk's volume server is in
|
||||
// maintenance mode. Such a server refuses new data, so it is a source only.
|
||||
func (at *ActiveTopology) inMaintenanceUnsafe(disk *activeDisk) bool {
|
||||
node := at.nodes[disk.NodeID]
|
||||
return node != nil && node.nodeInfo.GetMaintenance()
|
||||
}
|
||||
|
||||
// isDiskAvailable checks if a disk can accept new tasks. Per-volume safety is
|
||||
// enforced by HasAnyTask at detection time, so cross-type tasks on the same
|
||||
// disk are intentionally not considered conflicting (see #9147).
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package topology
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
func TestMaintenanceNodeHasNoCapacity(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
topo := singleDiskTopologyInfoForCapacityTest()
|
||||
rack := topo.DataCenterInfos[0].RackInfos[0]
|
||||
rack.DataNodeInfos = append(rack.DataNodeInfos, &master_pb.DataNodeInfo{
|
||||
Id: "node-b",
|
||||
Maintenance: true,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"hdd": {DiskId: 0, Type: "hdd", MaxVolumeCount: 1000},
|
||||
},
|
||||
})
|
||||
|
||||
at := NewActiveTopology(0)
|
||||
if err := at.UpdateTopology(topo); err != nil {
|
||||
t.Fatalf("UpdateTopology: %v", err)
|
||||
}
|
||||
|
||||
if got := at.GetEffectiveAvailableCapacity("node-b", 0); got != 0 {
|
||||
t.Errorf("GetEffectiveAvailableCapacity(node-b) = %d, want 0", got)
|
||||
}
|
||||
if got := at.GetEffectiveAvailableEcShardSlots("node-b", 0, 0); got != 0 {
|
||||
t.Errorf("GetEffectiveAvailableEcShardSlots(node-b) = %d, want 0", got)
|
||||
}
|
||||
if got := at.GetEffectiveAvailableCapacity("node-a", 0); got != 1000 {
|
||||
t.Errorf("GetEffectiveAvailableCapacity(node-a) = %d, want 1000", got)
|
||||
}
|
||||
for _, d := range at.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 1) {
|
||||
if d.NodeID == "node-b" {
|
||||
t.Errorf("GetDisksWithEffectiveCapacity returned maintenance node-b")
|
||||
}
|
||||
}
|
||||
for _, d := range at.GetAvailableDisks(TaskTypeBalance, "") {
|
||||
if d.NodeID == "node-b" {
|
||||
t.Errorf("GetAvailableDisks returned maintenance node-b")
|
||||
}
|
||||
}
|
||||
sources := 0
|
||||
for _, d := range at.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 0) {
|
||||
if d.NodeID == "node-b" {
|
||||
sources++
|
||||
}
|
||||
}
|
||||
if sources != 1 {
|
||||
t.Errorf("maintenance node-b should stay listed with zero capacity, got %d entries", sources)
|
||||
}
|
||||
}
|
||||
@@ -165,8 +165,8 @@ func (at *ActiveTopology) GetAvailableDisks(taskType TaskType, excludeNodeID str
|
||||
var available []*DiskInfo
|
||||
|
||||
for _, disk := range at.disks {
|
||||
if disk.NodeID == excludeNodeID {
|
||||
continue // Skip excluded node
|
||||
if disk.NodeID == excludeNodeID || at.inMaintenanceUnsafe(disk) {
|
||||
continue
|
||||
}
|
||||
|
||||
if at.isDiskAvailable(disk, taskType) {
|
||||
|
||||
@@ -75,7 +75,9 @@ func TestClusterHealthSummary(t *testing.T) {
|
||||
degraded := healthy
|
||||
degraded.MasterNodes = []dash.MasterNode{{Address: "m1:9333"}}
|
||||
degraded.DiskUsage = 95
|
||||
want := "Needs attention: no master leader, disks 95% full. 2 volume servers and 1 filer reporting, 1 master configured."
|
||||
degraded.UnderReplicatedVolumes = 3
|
||||
degraded.MisplacedVolumes = 1
|
||||
want := "Needs attention: no master leader, disks 95% full, 3 volumes under-replicated, 1 volume misplaced. 2 volume servers and 1 filer reporting, 1 master configured."
|
||||
if got := clusterHealthSummary(degraded); got != want {
|
||||
t.Errorf("degraded summary = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,12 @@ func clusterHealthIssues(data dash.AdminData) []string {
|
||||
issues = append(issues, fmt.Sprintf("disks %d%% full", p))
|
||||
}
|
||||
}
|
||||
if data.UnderReplicatedVolumes > 0 {
|
||||
issues = append(issues, countNoun(data.UnderReplicatedVolumes, "volume")+" under-replicated")
|
||||
}
|
||||
if data.MisplacedVolumes > 0 {
|
||||
issues = append(issues, countNoun(data.MisplacedVolumes, "volume")+" misplaced")
|
||||
}
|
||||
if data.VersionSummary.Mixed() {
|
||||
issues = append(issues, "mixed server versions")
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ func buildPolicyActionSuggestions() []string {
|
||||
s3_constants.S3_ACTION_UPLOAD_PART_COPY,
|
||||
s3_constants.S3_ACTION_LIST_PARTS,
|
||||
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS,
|
||||
s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD,
|
||||
s3_constants.S3_ACTION_CREATE_BUCKET,
|
||||
s3_constants.S3_ACTION_DELETE_BUCKET,
|
||||
s3_constants.S3_ACTION_LIST_BUCKET,
|
||||
|
||||
@@ -172,7 +172,7 @@ type LiveLock struct {
|
||||
isLocked int32 // 0 = unlocked, 1 = locked; use atomic operations
|
||||
self string
|
||||
lc *LockClient
|
||||
owner string
|
||||
owner atomic.Pointer[string] // read by other goroutines through LockOwner
|
||||
lockTTL time.Duration
|
||||
consecutiveFailures int // Track connection failures to trigger fallback
|
||||
}
|
||||
@@ -497,7 +497,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
lock.key, lock.hostFiler, lock.self)
|
||||
|
||||
previousHostFiler := lock.hostFiler
|
||||
previousOwner := lock.owner
|
||||
previousOwner := lock.LockOwner()
|
||||
|
||||
err = pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Bound each attempt: a ring member that is reachable from the masters
|
||||
@@ -549,12 +549,12 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
if resp.LockOwner != "" && resp.LockOwner != previousOwner {
|
||||
// Only log if the owner actually changed
|
||||
glog.V(2).Infof("LOCK: Owner changed from %s to %s for key=%s", previousOwner, resp.LockOwner, lock.key)
|
||||
lock.owner = resp.LockOwner
|
||||
lock.owner.Store(&resp.LockOwner)
|
||||
} else if resp.LockOwner != "" {
|
||||
lock.owner = resp.LockOwner
|
||||
lock.owner.Store(&resp.LockOwner)
|
||||
} else if previousOwner != "" {
|
||||
glog.V(2).Infof("LOCK: Owner cleared for key=%s", lock.key)
|
||||
lock.owner = ""
|
||||
lock.owner.Store(nil)
|
||||
}
|
||||
}
|
||||
return err
|
||||
@@ -575,7 +575,10 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
}
|
||||
|
||||
func (lock *LiveLock) LockOwner() string {
|
||||
return lock.owner
|
||||
if owner := lock.owner.Load(); owner != nil {
|
||||
return *owner
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Generation returns the fencing token for this lock.
|
||||
|
||||
@@ -327,7 +327,7 @@ type grantingLockFiler struct {
|
||||
}
|
||||
|
||||
func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
|
||||
return &filer_pb.LockResponse{RenewToken: "tok", LockOwner: req.Owner}, nil
|
||||
}
|
||||
|
||||
type rotatingAuthLockFiler struct {
|
||||
@@ -819,3 +819,29 @@ func TestLiveLockIsLockedOnlyWithinLease(t *testing.T) {
|
||||
t.Fatal("a lock whose lease ran out must not read as locked")
|
||||
}
|
||||
}
|
||||
|
||||
// Other goroutines read the owner while renewals rewrite it.
|
||||
func TestLiveLockOwnerReadDuringRenewal(t *testing.T) {
|
||||
lock := newGrantingLockClient(t).NewShortLivedLock("test-key", "test-owner")
|
||||
if lock == nil {
|
||||
t.Fatal("lock not granted")
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for i := 0; i < 20; i++ {
|
||||
lock.AttemptToLock(5 * time.Second)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
if got := lock.LockOwner(); got != "test-owner" {
|
||||
t.Fatalf("owner = %q, want test-owner", got)
|
||||
}
|
||||
return
|
||||
default:
|
||||
_ = lock.LockOwner()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -418,7 +418,7 @@ var (
|
||||
miniS3AutoCreateBucket = cmdMini.Flag.Bool("s3.autoCreateBucket", true, "create the bucket on upload if it does not exist, for admin identities only")
|
||||
miniBucket = cmdMini.Flag.String("bucket", "", "comma-separated S3 bucket names to create on startup if they do not already exist; leave empty to skip. Falls back to S3_BUCKET env var.")
|
||||
miniTableBucket = cmdMini.Flag.String("tableBucket", "", "comma-separated S3 Tables buckets to create on startup if they do not already exist, each name[:FORMAT] with FORMAT one of ICEBERG (default) or LANCE, e.g. warehouse,vectors:LANCE; leave empty to skip. Falls back to S3_TABLE_BUCKET env var.")
|
||||
miniVector = cmdMini.Flag.Bool("vector", false, "start the weed-vector engine for vector indexes and search")
|
||||
miniVector = cmdMini.Flag.Bool("vector", true, "start the weed-vector engine for vector indexes and search, and the weed-worker that builds its indexes, when they are installed")
|
||||
miniVectorBinary = cmdMini.Flag.String("vector.binary", "weed-vector", "path to the vector engine binary")
|
||||
miniVectorPort = cmdMini.Flag.Int("vector.port", 8090, "vector engine gRPC port")
|
||||
miniVectorMetricsPort = cmdMini.Flag.Int("vector.metricsPort", 0, "optional vector HTTP health and metrics port")
|
||||
@@ -1490,6 +1490,7 @@ func runMini(cmd *Command, args []string) bool {
|
||||
// plaintext-KEK warning and the IAM "no signing key" error don't fire.
|
||||
// Does nothing for keys the operator has already configured.
|
||||
ensureMiniDevSSES3Keys(*miniDataFolders)
|
||||
prepareMiniVector()
|
||||
|
||||
*miniOptions.cpuprofile = util.ResolvePath(*miniOptions.cpuprofile)
|
||||
*miniOptions.memprofile = util.ResolvePath(*miniOptions.memprofile)
|
||||
@@ -1741,9 +1742,9 @@ func runMini(cmd *Command, args []string) bool {
|
||||
}
|
||||
if *miniVector {
|
||||
if err := startMiniVector(); err != nil {
|
||||
glog.Errorf("start vector engine: %v", err)
|
||||
triggerMiniClientsShutdown(5 * time.Second)
|
||||
return false
|
||||
glog.Errorf("vector engine not started, continuing without vector search: %v", err)
|
||||
} else if err := startMiniVectorWorker(); err != nil {
|
||||
glog.Errorf("weed-worker not started, continuing without vector index maintenance: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+121
-13
@@ -2,6 +2,8 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -16,19 +18,128 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func startMiniVector() error {
|
||||
binary := *miniVectorBinary
|
||||
if binary == "weed-vector" {
|
||||
// miniVectorPath and miniVectorWorkerPath are the resolved binaries, empty
|
||||
// for a component mini does not start.
|
||||
var miniVectorPath, miniVectorWorkerPath string
|
||||
|
||||
// lookMiniBinary finds a companion binary named by its default name next to
|
||||
// weed first, then next to each of besides, then on PATH; any other value is
|
||||
// used as given.
|
||||
func lookMiniBinary(binary, defaultName string, besides ...string) (string, error) {
|
||||
if binary == defaultName {
|
||||
if executable, err := os.Executable(); err == nil {
|
||||
candidate := filepath.Join(filepath.Dir(executable), binary)
|
||||
if resolved, err := exec.LookPath(candidate); err == nil {
|
||||
binary = resolved
|
||||
besides = append([]string{executable}, besides...)
|
||||
}
|
||||
for _, path := range besides {
|
||||
directory, err := filepath.Abs(filepath.Dir(path))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if resolved, err := exec.LookPath(filepath.Join(directory, binary)); err == nil {
|
||||
return resolved, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := exec.LookPath(binary); err != nil {
|
||||
return fmt.Errorf("%s is unavailable: install the vector component or set -vector.binary: %w", binary, err)
|
||||
return exec.LookPath(binary)
|
||||
}
|
||||
|
||||
// miniSecurityToml is the security.toml in -config_dir for a child process,
|
||||
// unless its own environment variable already names one.
|
||||
func miniSecurityToml(env string) string {
|
||||
directory := util.ConfigurationFileDirectory.String()
|
||||
if directory == "" {
|
||||
return ""
|
||||
}
|
||||
path := filepath.Join(util.ResolvePath(directory), "security.toml")
|
||||
if _, explicit := os.LookupEnv(env); explicit || !util.FileExists(path) {
|
||||
return ""
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// prepareMiniVector finds weed-vector and weed-worker before ports are
|
||||
// reserved and the S3 gateway starts. A component that is not installed is
|
||||
// logged and left out. The Lance Namespace trusts the worker only by a token
|
||||
// signed with a key derived from jwt.filer_signing.key, so when the cluster
|
||||
// has none, the namespace and the worker share a key made for this run.
|
||||
func prepareMiniVector() {
|
||||
miniVectorPath, miniVectorWorkerPath, miniS3Options.lanceWorkerKey = "", "", nil
|
||||
if !*miniVector {
|
||||
return
|
||||
}
|
||||
binary, err := lookMiniBinary(*miniVectorBinary, "weed-vector")
|
||||
if err != nil {
|
||||
glog.Warningf("%s is unavailable, starting without vector search: install weed-vector or set -vector.binary: %v", *miniVectorBinary, err)
|
||||
*miniVector = false
|
||||
return
|
||||
}
|
||||
miniVectorPath = binary
|
||||
binary, err = lookMiniBinary("weed-worker", "weed-worker", miniVectorPath)
|
||||
if err != nil {
|
||||
glog.Warningf("weed-worker is unavailable, so vector and metadata indexes will not be built: install it beside weed or weed-vector, or on PATH: %v", err)
|
||||
return
|
||||
}
|
||||
miniVectorWorkerPath = binary
|
||||
if util.GetViper().GetString("jwt.filer_signing.key") != "" {
|
||||
return
|
||||
}
|
||||
key := make([]byte, 32)
|
||||
if _, err := rand.Read(key); err != nil {
|
||||
glog.Warningf("weed-worker will not be started: generate its signing key: %v", err)
|
||||
miniVectorWorkerPath = ""
|
||||
return
|
||||
}
|
||||
miniS3Options.lanceWorkerKey = security.SigningKey(hex.EncodeToString(key))
|
||||
}
|
||||
|
||||
// startMiniVectorWorker starts weed-worker against mini's admin, which names
|
||||
// the filers and the Lance Namespace with every job.
|
||||
// miniWorkerTLSArgs passes the [grpc.worker] certificates the Go workers dial
|
||||
// admin with, chosen as security.LoadClientTLS chooses them: weed-worker takes
|
||||
// its admin TLS only as flags, not from security.toml.
|
||||
func miniWorkerTLSArgs(config util.Configuration) []string {
|
||||
cert, key := config.GetString("grpc.worker.client_cert"), config.GetString("grpc.worker.client_key")
|
||||
if cert == "" || key == "" {
|
||||
cert, key = config.GetString("grpc.worker.cert"), config.GetString("grpc.worker.key")
|
||||
}
|
||||
ca := config.GetString("grpc.ca")
|
||||
if cert == "" || key == "" || ca == "" {
|
||||
return nil
|
||||
}
|
||||
return []string{"--tls-ca=" + ca, "--tls-cert=" + cert, "--tls-key=" + key}
|
||||
}
|
||||
|
||||
func startMiniVectorWorker() error {
|
||||
if miniVectorWorkerPath == "" {
|
||||
return nil
|
||||
}
|
||||
admin := pb.NewServerAddress(miniAdminWorkerDialIP(miniAdminOptions.workerGrpcBindIp), *miniAdminOptions.port, *miniAdminOptions.grpcPort)
|
||||
args := []string{"--admin=" + string(admin)}
|
||||
if path := miniSecurityToml("WEED_WORKER_SECURITY_TOML"); path != "" {
|
||||
args = append(args, "--security-toml="+path)
|
||||
}
|
||||
args = append(args, miniWorkerTLSArgs(util.GetViper())...)
|
||||
command := exec.CommandContext(miniClientsCtx(), miniVectorWorkerPath, args...)
|
||||
command.Stdout, command.Stderr = os.Stdout, os.Stderr
|
||||
if key := miniS3Options.lanceWorkerKey; len(key) > 0 {
|
||||
command.Env = append(os.Environ(), "WEED_FILER_SIGNING_KEY="+string(key))
|
||||
}
|
||||
if err := command.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
done := trackMiniClient()
|
||||
go func() {
|
||||
defer done()
|
||||
if err := command.Wait(); err != nil && miniClientsCtx().Err() == nil {
|
||||
glog.Errorf("weed-worker exited: %v", err)
|
||||
}
|
||||
}()
|
||||
glog.V(0).Infof("weed-worker started against admin %s", admin)
|
||||
return nil
|
||||
}
|
||||
|
||||
func startMiniVector() error {
|
||||
binary := miniVectorPath
|
||||
address := util.JoinHostPort(*miniIp, *miniVectorPort)
|
||||
bindIP := *miniBindIp
|
||||
if bindIP == "" {
|
||||
@@ -54,11 +165,8 @@ func startMiniVector() error {
|
||||
if *miniVectorMetricsPort > 0 {
|
||||
args = append(args, fmt.Sprintf("--metrics-port=%d", *miniVectorMetricsPort), "--metrics-ip="+bindIP)
|
||||
}
|
||||
if directory := util.ConfigurationFileDirectory.String(); directory != "" {
|
||||
path := filepath.Join(util.ResolvePath(directory), "security.toml")
|
||||
if _, explicit := os.LookupEnv("WEED_VECTOR_SECURITY_TOML"); !explicit && util.FileExists(path) {
|
||||
args = append(args, "--security-toml="+path)
|
||||
}
|
||||
if path := miniSecurityToml("WEED_VECTOR_SECURITY_TOML"); path != "" {
|
||||
args = append(args, "--security-toml="+path)
|
||||
}
|
||||
command := exec.CommandContext(miniClientsCtx(), binary, args...)
|
||||
command.Stdout, command.Stderr = os.Stdout, os.Stderr
|
||||
|
||||
@@ -1,10 +1,62 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func TestPrepareMiniVector(t *testing.T) {
|
||||
oldVector, oldVectorBinary := *miniVector, *miniVectorBinary
|
||||
oldPaths, oldKey := [2]string{miniVectorPath, miniVectorWorkerPath}, miniS3Options.lanceWorkerKey
|
||||
defer func() {
|
||||
*miniVector, *miniVectorBinary = oldVector, oldVectorBinary
|
||||
miniVectorPath, miniVectorWorkerPath, miniS3Options.lanceWorkerKey = oldPaths[0], oldPaths[1], oldKey
|
||||
}()
|
||||
both, vectorOnly, besideVector, empty := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir()
|
||||
for dir, names := range map[string][]string{both: {"weed-vector", "weed-worker"}, vectorOnly: {"weed-vector"}, besideVector: {"weed-vector", "weed-worker"}} {
|
||||
for _, name := range names {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte("#!/bin/sh\n"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Chdir(besideVector)
|
||||
t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "")
|
||||
defer util.GetViper().Set("jwt.filer_signing.key", "")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
path string
|
||||
vector bool
|
||||
vectorBinary string
|
||||
clusterKey string
|
||||
wantVector bool
|
||||
wantVectorPath, wantWorker string
|
||||
wantKey bool
|
||||
}{
|
||||
{"both installed", both, true, "weed-vector", "", true, filepath.Join(both, "weed-vector"), filepath.Join(both, "weed-worker"), true},
|
||||
{"weed-worker not installed after a run that started it", vectorOnly, true, "weed-vector", "", true, filepath.Join(vectorOnly, "weed-vector"), "", false},
|
||||
{"cluster key configured", both, true, "weed-vector", "cluster-key", true, filepath.Join(both, "weed-vector"), filepath.Join(both, "weed-worker"), false},
|
||||
{"weed-worker beside an explicit -vector.binary", empty, true, filepath.Join(besideVector, "weed-vector"), "", true, filepath.Join(besideVector, "weed-vector"), filepath.Join(besideVector, "weed-worker"), true},
|
||||
{"weed-worker beside a relative -vector.binary", empty, true, "./weed-vector", "", true, "./weed-vector", filepath.Join(besideVector, "weed-worker"), true},
|
||||
{"weed-vector not installed", empty, true, "weed-vector", "", false, "", "", false},
|
||||
{"-vector=false", both, false, "weed-vector", "", false, "", "", false},
|
||||
} {
|
||||
t.Setenv("PATH", tc.path)
|
||||
*miniVector, *miniVectorBinary = tc.vector, tc.vectorBinary
|
||||
util.GetViper().Set("jwt.filer_signing.key", tc.clusterKey)
|
||||
prepareMiniVector()
|
||||
if *miniVector != tc.wantVector || miniVectorPath != tc.wantVectorPath || miniVectorWorkerPath != tc.wantWorker || (len(miniS3Options.lanceWorkerKey) == 64) != tc.wantKey {
|
||||
t.Errorf("%s: vector %v %q, worker %q, key length %d", tc.name, *miniVector, miniVectorPath, miniVectorWorkerPath, len(miniS3Options.lanceWorkerKey))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiniVectorRejectsExplicitListenerConflict(t *testing.T) {
|
||||
oldVector, oldPort, oldMetrics, oldFlags := *miniVector, *miniVectorPort, *miniVectorMetricsPort, explicitFlags
|
||||
defer func() {
|
||||
@@ -19,3 +71,26 @@ func TestMiniVectorRejectsExplicitListenerConflict(t *testing.T) {
|
||||
t.Fatalf("listener conflict not rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiniWorkerTLSArgs(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
settings map[string]string
|
||||
want []string
|
||||
}{
|
||||
{"plaintext", nil, nil},
|
||||
{"worker cert", map[string]string{"grpc.ca": "ca.crt", "grpc.worker.cert": "w.crt", "grpc.worker.key": "w.key"},
|
||||
[]string{"--tls-ca=ca.crt", "--tls-cert=w.crt", "--tls-key=w.key"}},
|
||||
{"client cert preferred", map[string]string{"grpc.ca": "ca.crt", "grpc.worker.cert": "w.crt", "grpc.worker.key": "w.key", "grpc.worker.client_cert": "c.crt", "grpc.worker.client_key": "c.key"},
|
||||
[]string{"--tls-ca=ca.crt", "--tls-cert=c.crt", "--tls-key=c.key"}},
|
||||
{"no CA", map[string]string{"grpc.worker.cert": "w.crt", "grpc.worker.key": "w.key"}, nil},
|
||||
} {
|
||||
v := viper.New()
|
||||
for key, value := range tc.settings {
|
||||
v.Set(key, value)
|
||||
}
|
||||
if got := miniWorkerTLSArgs(util.NewViperProxy(v)); strings.Join(got, " ") != strings.Join(tc.want, " ") {
|
||||
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -119,7 +119,7 @@ func init() {
|
||||
mountOptions.concurrentWriters = cmdMount.Flag.Int("concurrentWriters", 128, "limit concurrent goroutine writers")
|
||||
mountOptions.concurrentReaders = cmdMount.Flag.Int("concurrentReaders", 128, "limit concurrent chunk fetches for read operations")
|
||||
mountOptions.volumeReadAuth = cmdMount.Flag.Bool("volumeReadAuth", false, "read chunks with the exact-fid tokens the filer returns (LookupDirectoryEntries read_auth) instead of signing with jwt.signing.read.key")
|
||||
mountOptions.memoryLimitMB = cmdMount.Flag.Int64("memoryLimitMB", 0, "soft Go runtime memory limit in MiB; 0 preserves GOMEMLIMIT; leave headroom below the container limit")
|
||||
mountOptions.memoryLimitMB = cmdMount.Flag.Int64("memoryLimitMB", 0, "soft Go runtime memory limit in MiB; 0 keeps GOMEMLIMIT or 90% of the cgroup memory limit; leave headroom below the container limit")
|
||||
mountOptions.readerCacheSizeMB = cmdMount.Flag.Int64("readerCacheSizeMB", 256, "memory budget in MiB for downloaded and in-flight reader buffers across all files; must fit the largest pooled chunk buffer")
|
||||
mountOptions.cacheDirForRead = cmdMount.Flag.String("cacheDir", os.TempDir(), "local cache directory for file chunks and meta data")
|
||||
mountOptions.cacheSizeMBForRead = cmdMount.Flag.Int64("cacheCapacityMB", 128, "file chunk read cache capacity in MB")
|
||||
|
||||
@@ -451,6 +451,7 @@ func configureMountMemory(option *MountOptions) error {
|
||||
}
|
||||
if *option.memoryLimitMB > 0 {
|
||||
debug.SetMemoryLimit(*option.memoryLimitMB << 20)
|
||||
glog.V(0).Infof("Go memory limit: %d MiB from -memoryLimitMB", *option.memoryLimitMB)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -111,15 +111,19 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
}
|
||||
|
||||
// Create main gRPC server
|
||||
grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.msg_broker"))
|
||||
tlsCreds, tlsVerify := security.LoadServerTLS(util.GetViper(), "grpc.msg_broker")
|
||||
serverOptions := append([]grpc.ServerOption{tlsCreds, tlsVerify}, broker.GrpcServerOptions()...)
|
||||
grpcS := pb.NewGrpcServer(serverOptions...)
|
||||
mq_pb.RegisterSeaweedMessagingServer(grpcS, qs)
|
||||
reflection.Register(grpcS)
|
||||
grace.OnInterrupt(grpcS.Stop)
|
||||
|
||||
// Start localhost listener if available
|
||||
if localL != nil {
|
||||
localGrpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.msg_broker"))
|
||||
localGrpcS := pb.NewGrpcServer(serverOptions...)
|
||||
mq_pb.RegisterSeaweedMessagingServer(localGrpcS, qs)
|
||||
reflection.Register(localGrpcS)
|
||||
grace.OnInterrupt(localGrpcS.Stop)
|
||||
go func() {
|
||||
glog.V(0).Infof("MQ Broker listening on localhost:%d", *mqBrokerOpt.port)
|
||||
if err := localGrpcS.Serve(localL); err != nil && err != grpc.ErrServerStopped {
|
||||
@@ -127,6 +131,8 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
}
|
||||
}()
|
||||
}
|
||||
// Hooks run last-registered first: flush the partitions, then drop the connections.
|
||||
grace.OnInterrupt(qs.Stop)
|
||||
|
||||
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ipBind, *mqBrokerOpt.port)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
|
||||
+13
-1
@@ -114,6 +114,9 @@ type S3Options struct {
|
||||
icebergBound atomic.Bool
|
||||
lanceBound atomic.Bool
|
||||
lanceServer *lance.Server
|
||||
// lanceWorkerKey is set by mini for the weed-worker it starts when the
|
||||
// cluster has no jwt.filer_signing.key; not a flag.
|
||||
lanceWorkerKey security.SigningKey
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -748,7 +751,16 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer, liste
|
||||
func (s3opt *S3Options) newLanceServer(s3ApiServer *s3api.S3ApiServer) *lance.Server {
|
||||
lanceServer := lance.NewServer(s3ApiServer, s3ApiServer)
|
||||
lanceServer.SetCredentialValidator(s3ApiServer)
|
||||
lanceServer.SetSigningKey(s3ApiServer.FilerSigningKey)
|
||||
signingKey := s3ApiServer.FilerSigningKey
|
||||
if workerKey := s3opt.lanceWorkerKey; len(workerKey) > 0 {
|
||||
signingKey = func() security.SigningKey {
|
||||
if key := s3ApiServer.FilerSigningKey(); len(key) > 0 {
|
||||
return key
|
||||
}
|
||||
return workerKey
|
||||
}
|
||||
}
|
||||
lanceServer.SetSigningKey(signingKey)
|
||||
if s3opt.vendsCredentials() {
|
||||
lanceServer.SetCredentialVendor(lanceCredentialVendor{s3ApiServer})
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ var (
|
||||
volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
|
||||
volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
|
||||
volumeMinFreeSpacePercent = cmdServer.Flag.String("volume.minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
|
||||
volumeMinFreeSpace = cmdServer.Flag.String("volume.minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
|
||||
volumeMinFreeSpace = cmdServer.Flag.String("volume.minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit.")
|
||||
serverMetricsHttpPort = cmdServer.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
|
||||
serverMetricsHttpIp = cmdServer.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
|
||||
serverGrpcLocalSocketDir = cmdServer.Flag.String("grpc.localSocketDir", "/tmp", "directory for the local gRPC Unix sockets; default to /tmp. Point it at a directory a temp cleaner does not sweep, such as /run/seaweedfs")
|
||||
|
||||
@@ -271,7 +271,7 @@ var (
|
||||
maxVolumeCounts = cmdVolume.Flag.String("max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
|
||||
volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
|
||||
minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
|
||||
minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
|
||||
minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly, until free space is 1% of the disk above the limit.")
|
||||
)
|
||||
|
||||
func runVolume(cmd *Command, args []string) bool {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
@@ -14,7 +15,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -383,8 +383,7 @@ func (cm *CredentialManager) LoadS3ConfigFile(path string) error {
|
||||
return fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
config := &iam_pb.S3ApiConfiguration{}
|
||||
opts := protojson.UnmarshalOptions{DiscardUnknown: true, AllowPartial: true}
|
||||
if err := opts.Unmarshal(content, config); err != nil {
|
||||
if err := filer.ParseS3ConfigurationFromBytes(content, config); err != nil {
|
||||
return fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
for _, ident := range config.Identities {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package credential
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadS3ConfigFileKeepsTheContentOutOfParseErrors(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "s3.json")
|
||||
content := `{"identities": [{"name": "a", "credentials": [{"accessKey": "AK", "secretKey": 102030405060708090}]}]}`
|
||||
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := (&CredentialManager{}).LoadS3ConfigFile(path)
|
||||
if err == nil {
|
||||
t.Fatal("expected a parse error")
|
||||
}
|
||||
if strings.Contains(err.Error(), "102030405060708090") {
|
||||
t.Fatalf("parse error quotes the secret key: %v", err)
|
||||
}
|
||||
if want := "invalid configuration at line 1, column 80: invalid value for string field secretKey"; !strings.HasSuffix(err.Error(), want) {
|
||||
t.Fatalf("got %v, want it to end with %s", err, want)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package credential
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
@@ -90,18 +91,11 @@ func TestCredentialManagerCreation(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCredentialInterface(t *testing.T) {
|
||||
// Skip if no stores are registered
|
||||
if len(Stores) == 0 {
|
||||
t.Skip("No credential stores registered - for full testing see test/ package")
|
||||
if !slices.Contains(GetAvailableStores(), StoreTypeMemory) {
|
||||
t.Skip("memory store not registered - for full testing see test/ package")
|
||||
}
|
||||
|
||||
// Test the interface with the first available store
|
||||
availableStores := GetAvailableStores()
|
||||
if len(availableStores) == 0 {
|
||||
t.Skip("No stores available for testing")
|
||||
}
|
||||
|
||||
testCredentialInterfaceWithStore(t, availableStores[0])
|
||||
testCredentialInterfaceWithStore(t, StoreTypeMemory)
|
||||
}
|
||||
|
||||
func testCredentialInterfaceWithStore(t *testing.T, storeName CredentialStoreTypeName) {
|
||||
@@ -173,18 +167,11 @@ func testCredentialInterfaceWithStore(t *testing.T, storeName CredentialStoreTyp
|
||||
}
|
||||
|
||||
func TestCredentialManagerIntegration(t *testing.T) {
|
||||
// Skip if no stores are registered
|
||||
if len(Stores) == 0 {
|
||||
t.Skip("No credential stores registered - for full testing see test/ package")
|
||||
if !slices.Contains(GetAvailableStores(), StoreTypeMemory) {
|
||||
t.Skip("memory store not registered - for full testing see test/ package")
|
||||
}
|
||||
|
||||
// Test with the first available store
|
||||
availableStores := GetAvailableStores()
|
||||
if len(availableStores) == 0 {
|
||||
t.Skip("No stores available for testing")
|
||||
}
|
||||
|
||||
storeName := availableStores[0]
|
||||
storeName := StoreTypeMemory
|
||||
config := util.GetViper()
|
||||
cm, err := NewCredentialManager(storeName, config, "test.")
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/ecbalancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// A volume server in maintenance mode refuses every shard copy, so the shell
|
||||
// planner must not target it even when its slot count says it has room (a
|
||||
// shard it gives up frees a slot during planning).
|
||||
func TestEcBalanceSkipsMaintenanceTarget(t *testing.T) {
|
||||
maintenance := newEcNode("dc1", "rack2", "dn2", 100)
|
||||
maintenance.Info.Maintenance = true
|
||||
ecNodes := []*EcNode{
|
||||
newEcNode("dc1", "rack1", "dn1", 100).addEcVolumeAndShardsForTest(1, "c1", []erasure_coding.ShardId{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}),
|
||||
maintenance,
|
||||
newEcNode("dc1", "rack3", "dn3", 100),
|
||||
newEcNode("dc1", "rack4", "dn4", 100),
|
||||
}
|
||||
topo, _, _ := toBalancerTopology(ecNodes, []string{"c1"}, types.HardDriveType, nil, nil, nil, nil)
|
||||
moves := ecbalancer.Plan(topo, ecbalancer.Options{})
|
||||
if len(moves) == 0 {
|
||||
t.Fatal("expected moves off dn1")
|
||||
}
|
||||
for _, m := range moves {
|
||||
if m.TargetNode == "dn2" {
|
||||
t.Fatalf("shard %d.%d planned onto dn2, which is in maintenance mode", m.VolumeID, m.ShardID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -358,7 +358,7 @@ func CountShards(ecShardInfos []*master_pb.VolumeEcShardInformationMessage) (cou
|
||||
}
|
||||
|
||||
func CountFreeShardSlots(dn *master_pb.DataNodeInfo, diskType types.DiskType) (count int) {
|
||||
if dn.DiskInfos == nil {
|
||||
if dn.DiskInfos == nil || dn.GetMaintenance() {
|
||||
return 0
|
||||
}
|
||||
diskInfo := dn.DiskInfos[string(diskType)]
|
||||
@@ -1174,7 +1174,7 @@ func toBalancerTopology(ecNodes []*EcNode, collections []string, diskType types.
|
||||
for _, en := range ecNodes {
|
||||
rackKey := string(en.DC) + ":" + string(en.Rack)
|
||||
node := topo.AddNode(en.Info.Id, string(en.DC), rackKey, en.FreeEcSlot)
|
||||
if noReceiveTargets[en.Info.Id] {
|
||||
if noReceiveTargets[en.Info.Id] || en.Info.GetMaintenance() {
|
||||
node.SetNoReceive()
|
||||
}
|
||||
// Group by physical machine (host) so shards spread across machines, not just
|
||||
|
||||
@@ -9,6 +9,25 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// A volume server in maintenance mode refuses every shard copy, so it has no
|
||||
// free shard slots whatever its disks report.
|
||||
func TestCountFreeShardSlotsMaintenance(t *testing.T) {
|
||||
dn := &master_pb.DataNodeInfo{
|
||||
Id: "n1",
|
||||
Maintenance: true,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {MaxVolumeCount: 100},
|
||||
},
|
||||
}
|
||||
if got := CountFreeShardSlots(dn, types.HardDriveType); got != 0 {
|
||||
t.Errorf("maintenance node free shard slots = %d, want 0", got)
|
||||
}
|
||||
dn.Maintenance = false
|
||||
if got := CountFreeShardSlots(dn, types.HardDriveType); got <= 0 {
|
||||
t.Errorf("free shard slots after maintenance off = %d, want > 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// countFreeShardSlots must report zero for a physically near-full disk even
|
||||
// though its slot math (MaxVolumeCount - VolumeCount) says it has room, so EC
|
||||
// placement never piles shards onto a full disk. Mirrors the volume #10160 gate.
|
||||
|
||||
@@ -101,7 +101,13 @@ func (group *ChunkGroup) ReadDataAt(ctx context.Context, fileSize int64, buff []
|
||||
return 0, 0, group.resolveErr
|
||||
}
|
||||
|
||||
sectionIndexStart, sectionIndexStop := SectionIndex(offset/SectionSize), SectionIndex((offset+int64(len(buff)))/SectionSize)
|
||||
if len(buff) == 0 {
|
||||
return 0, 0, nil
|
||||
}
|
||||
if int64(len(buff)) > fileSize-offset {
|
||||
buff = buff[:fileSize-offset]
|
||||
}
|
||||
sectionIndexStart, sectionIndexStop := SectionIndex(offset/SectionSize), SectionIndex((offset+int64(len(buff))-1)/SectionSize)
|
||||
numSections := int(sectionIndexStop - sectionIndexStart + 1)
|
||||
|
||||
// For single section or when concurrency is disabled, use sequential reading
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
func TestChunkGroupReadAcrossEOF(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", "1")
|
||||
_, _ = w.Write([]byte{'A'})
|
||||
}))
|
||||
defer server.Close()
|
||||
lookup := func(ctx context.Context, id string) ([]string, error) {
|
||||
return []string{server.URL + "/" + id}, ctx.Err()
|
||||
}
|
||||
const offset = SectionSize - 4
|
||||
const fileSize = SectionSize - 3
|
||||
for _, hasData := range []bool{false, true} {
|
||||
for _, concurrent := range []int{1, 16} {
|
||||
for _, length := range []int{1, 8} {
|
||||
t.Run(fmt.Sprintf("data_%v/readers_%d/bytes_%d", hasData, concurrent, length), func(t *testing.T) {
|
||||
var chunks []*filer_pb.FileChunk
|
||||
expected := byte(0)
|
||||
if hasData {
|
||||
chunks = []*filer_pb.FileChunk{{FileId: "1,0100000001", Offset: offset, Size: 1, ModifiedTsNs: 1}}
|
||||
expected = 'A'
|
||||
}
|
||||
group, err := NewChunkGroup(lookup, newMockChunkCacheForReaderCache(), chunks, concurrent, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer group.Close()
|
||||
dst := bytes.Repeat([]byte{0xcd}, length)
|
||||
n, _, err := group.ReadDataAt(context.Background(), fileSize, dst, offset)
|
||||
t.Logf("offset=%d fileSize=%d requested=%d n=%d err=%v data=%x", offset, fileSize, length, n, err, dst)
|
||||
if n != 1 || (err != nil && err != io.EOF) || dst[0] != expected {
|
||||
t.Fatal("section aggregation returned an invalid count/content for a valid read crossing EOF")
|
||||
}
|
||||
if !bytes.Equal(dst[1:], bytes.Repeat([]byte{0xcd}, length-1)) {
|
||||
t.Fatal("read modified the buffer beyond EOF")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
-13
@@ -351,19 +351,26 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
|
||||
return
|
||||
}
|
||||
|
||||
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
|
||||
// readsRange reports whether chunkView is fetched as a range rather than
|
||||
// through the shared whole-chunk download.
|
||||
//
|
||||
// A view clipped to part of its chunk (e.g. the edge of a ranged GET,
|
||||
// whose views ViewFromVisibleIntervals clips to the request) only ever
|
||||
// needs that part: fetch it as a range no matter the detected pattern.
|
||||
// Fetching the chunk whole would multiply volume-server reads. Ciphered
|
||||
// and compressed chunks are the exception: the volume server reads the
|
||||
// whole blob to serve a range, so they take the shared whole-chunk path
|
||||
// where one download serves every buffer. A chunk that cannot fit the
|
||||
// reader budget is always fetched as a range, as nothing else can serve it.
|
||||
func (c *ChunkReadAt) readsRange(chunkView *ChunkView) bool {
|
||||
if !c.readerCache.budget.canFit(int(chunkView.ChunkSize)) {
|
||||
return true
|
||||
}
|
||||
return chunkView.CanRangeFetch() && (!chunkView.IsFullChunk() || c.readerPattern.IsRandomMode())
|
||||
}
|
||||
|
||||
// A view clipped to part of its chunk (e.g. the edge of a ranged GET,
|
||||
// whose views ViewFromVisibleIntervals clips to the request) only ever
|
||||
// needs that part: fetch it as a range no matter the detected pattern.
|
||||
// Fetching the chunk whole would multiply volume-server reads. Ciphered
|
||||
// and compressed chunks are the exception: the volume server reads the
|
||||
// whole blob to serve a range, so they take the shared whole-chunk path
|
||||
// where one download serves every buffer — unless the whole chunk cannot
|
||||
// even fit the reader budget, in which case a range fetch is the only
|
||||
// way to serve the request.
|
||||
rangeFetch := chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))
|
||||
if rangeFetch && (!chunkView.IsFullChunk() || c.readerPattern.IsRandomMode()) {
|
||||
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
|
||||
if c.readsRange(chunkView) {
|
||||
c.readerCache.releaseStream(&c.stream)
|
||||
n, err := c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
|
||||
if n > 0 {
|
||||
@@ -393,7 +400,7 @@ func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunk
|
||||
// readChunkSliceAtForParallel is a simplified version for parallel chunk fetching
|
||||
// It doesn't update lastChunkFid or trigger prefetch (handled by the caller)
|
||||
func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer []byte, chunkView *ChunkView, offset uint64) (n int, err error) {
|
||||
if (chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
|
||||
if c.readsRange(chunkView) {
|
||||
n, err = c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
|
||||
if n > 0 {
|
||||
return n, err
|
||||
|
||||
@@ -403,6 +403,107 @@ func TestChunkReadAtOversizedCompressedChunkFallsBackToRange(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A whole chunk larger than the reader cache budget is range-fetched in a
|
||||
// sequential read too, as the budget can't hold it whole.
|
||||
func TestChunkReadAtOversizedFullChunkFallsBackToRange(t *testing.T) {
|
||||
const chunkSize = 1 << 20
|
||||
const sliceSize = 16 << 10
|
||||
|
||||
budget := NewReaderCacheBudget(64 << 10)
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil, budget)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 0,
|
||||
StopOffset: chunkSize,
|
||||
Value: &ChunkView{FileId: "chunk0", ViewSize: chunkSize, ChunkSize: chunkSize},
|
||||
})
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
||||
defer reader.ReleaseStream()
|
||||
if n, err := reader.ReadAt(make([]byte, sliceSize), 0); err != nil || n != sliceSize {
|
||||
t.Fatalf("read: n=%d err=%v", n, err)
|
||||
}
|
||||
|
||||
if len(*fetches) != 1 {
|
||||
t.Fatalf("got %d fetches, want 1 range fetch: %+v", len(*fetches), *fetches)
|
||||
}
|
||||
if f := (*fetches)[0]; f.isFullChunk || f.offset != 0 || f.size != sliceSize {
|
||||
t.Fatalf("fetch = %+v, want range fetch offset=0 size=%d", f, sliceSize)
|
||||
}
|
||||
}
|
||||
|
||||
// A read across chunks bigger than the budget range-fetches each of them, as
|
||||
// the parallel path can't download them whole either.
|
||||
func TestChunkReadAtOversizedFullChunksAcrossABoundaryFallBackToRange(t *testing.T) {
|
||||
const chunkSize = 1 << 20
|
||||
const sliceSize = 16 << 10
|
||||
|
||||
budget := NewReaderCacheBudget(64 << 10)
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil, budget)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
for i := int64(0); i < 2; i++ {
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: i * chunkSize,
|
||||
StopOffset: (i + 1) * chunkSize,
|
||||
Value: &ChunkView{FileId: fmt.Sprintf("chunk%d", i), ViewOffset: i * chunkSize, ViewSize: chunkSize, ChunkSize: chunkSize},
|
||||
})
|
||||
}
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, 2*chunkSize, 0)
|
||||
defer reader.ReleaseStream()
|
||||
if n, err := reader.ReadAt(make([]byte, sliceSize), chunkSize-sliceSize/2); err != nil || n != sliceSize {
|
||||
t.Fatalf("read: n=%d err=%v", n, err)
|
||||
}
|
||||
|
||||
if len(*fetches) != 2 {
|
||||
t.Fatalf("got %d fetches, want 2 range fetches: %+v", len(*fetches), *fetches)
|
||||
}
|
||||
for _, f := range *fetches {
|
||||
if f.isFullChunk || f.size != sliceSize/2 {
|
||||
t.Fatalf("fetch = %+v, want a range fetch of size %d", f, sliceSize/2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prefetch skips a chunk that cannot fit the reader budget: only a range
|
||||
// fetch can serve it, so a whole-chunk prefetch would take a download slot
|
||||
// the chunks after it could use, and then fail.
|
||||
func TestReaderCacheMaybeCacheSkipsOversizedChunk(t *testing.T) {
|
||||
const oversized = 1 << 20
|
||||
const small = 4 << 10
|
||||
|
||||
rc := NewReaderCache(1, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil, NewReaderCacheBudget(64<<10))
|
||||
defer rc.destroy()
|
||||
fetchRecorder(rc)
|
||||
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{StartOffset: 0, StopOffset: oversized,
|
||||
Value: &ChunkView{FileId: "chunk0", ViewSize: oversized, ChunkSize: oversized}})
|
||||
views.AppendInterval(&Interval[*ChunkView]{StartOffset: oversized, StopOffset: oversized + small,
|
||||
Value: &ChunkView{FileId: "chunk1", ViewOffset: oversized, ViewSize: small, ChunkSize: small}})
|
||||
|
||||
rc.MaybeCache(views.Front(), 2)
|
||||
|
||||
rc.Lock()
|
||||
_, prefetched := rc.downloaders["chunk1"]
|
||||
rc.Unlock()
|
||||
if !prefetched {
|
||||
t.Fatal("the chunk after one over the budget was not prefetched")
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk a stream is positioned in must outlast downloader-limit eviction:
|
||||
// otherwise a busy cache drops the buffer mid-stream and forces a refetch.
|
||||
func TestChunkReadAtPinnedChunkSurvivesEviction(t *testing.T) {
|
||||
|
||||
@@ -114,12 +114,12 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
|
||||
// abort when slots are filled
|
||||
return
|
||||
}
|
||||
if (chunkView.CanRangeFetch() || !rc.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
|
||||
// the view is clipped to part of the chunk and will be
|
||||
// range-fetched, so prefetching it whole would download bytes
|
||||
// nobody needs; a ciphered or compressed partial view needs
|
||||
// the whole blob anyway and is worth prefetching, but not when
|
||||
// it cannot fit the budget at all
|
||||
if !rc.budget.canFit(int(chunkView.ChunkSize)) || (chunkView.CanRangeFetch() && !chunkView.IsFullChunk()) {
|
||||
// a chunk that cannot fit the budget is only ever range-fetched,
|
||||
// and so is a view clipped to part of the chunk, so prefetching
|
||||
// it whole would download bytes nobody needs; a ciphered or
|
||||
// compressed partial view needs the whole blob anyway and is
|
||||
// worth prefetching
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,72 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
jsonpb "google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
var protojsonError = regexp.MustCompile(`\(line (\d+):(\d+)\): (invalid value for \w+ field \w+)?`)
|
||||
|
||||
func ParseS3ConfigurationFromBytes[T proto.Message](content []byte, config T) error {
|
||||
options := &jsonpb.UnmarshalOptions{
|
||||
DiscardUnknown: true,
|
||||
AllowPartial: true,
|
||||
}
|
||||
if err := options.Unmarshal(content, config); err != nil {
|
||||
return err
|
||||
err := options.Unmarshal(content, config)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
// protojson's errors quote the token they reject, which in these files can be a secret
|
||||
// key or KMS key material, so an error only says where it is and, for a value of the
|
||||
// wrong type, which field it's for. encoding/json finds syntax errors and gives an offset
|
||||
// instead of a quote, so protojson's text is only read for a file that is valid JSON.
|
||||
decoder := json.NewDecoder(bytes.NewReader(content))
|
||||
var syntaxErr *json.SyntaxError
|
||||
switch jsonErr := decoder.Decode(new(json.RawMessage)); {
|
||||
case jsonErr == io.EOF || jsonErr == io.ErrUnexpectedEOF:
|
||||
return errors.New("invalid configuration: unexpected end of input")
|
||||
case errors.As(jsonErr, &syntaxErr):
|
||||
return fmt.Errorf("invalid configuration at %s", position(content, int(syntaxErr.Offset)-1))
|
||||
case jsonErr == nil:
|
||||
if rest := bytes.TrimLeft(content[decoder.InputOffset():], " \t\r\n"); len(rest) > 0 {
|
||||
return fmt.Errorf("invalid configuration at %s", position(content, len(content)-len(rest)))
|
||||
}
|
||||
}
|
||||
if strings.HasSuffix(err.Error(), io.ErrUnexpectedEOF.Error()) {
|
||||
// protojson reads six bytes past a \u escape of a surrogate, so on one near the end of
|
||||
// the file it runs out of input. With room after it, it says where the escape is.
|
||||
if padded := options.Unmarshal(append(bytes.Clone(content), " "...), config.ProtoReflect().New().Interface()); padded != nil {
|
||||
err = padded
|
||||
}
|
||||
}
|
||||
found := protojsonError.FindStringSubmatch(err.Error())
|
||||
switch {
|
||||
case found != nil && found[3] != "":
|
||||
return fmt.Errorf("invalid configuration at line %s, column %s: %s", found[1], found[2], found[3])
|
||||
case found != nil:
|
||||
return fmt.Errorf("invalid configuration at line %s, column %s", found[1], found[2])
|
||||
}
|
||||
return errors.New("invalid configuration")
|
||||
}
|
||||
|
||||
// position gives offset as protojson's errors do, with the column in runes.
|
||||
func position(content []byte, offset int) string {
|
||||
before := content[:offset]
|
||||
line := bytes.Count(before, []byte("\n")) + 1
|
||||
if i := bytes.LastIndexByte(before, '\n'); i >= 0 {
|
||||
before = before[i+1:]
|
||||
}
|
||||
return fmt.Sprintf("line %d, column %d", line, utf8.RuneCount(before)+1)
|
||||
}
|
||||
|
||||
func ProtoToText(writer io.Writer, config proto.Message) error {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
@@ -181,3 +182,32 @@ func TestCheckDuplicateAccessKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseErrorKeepsTheContentOut(t *testing.T) {
|
||||
for content, want := range map[string]string{
|
||||
`{"kms": {"providers": {"local": {"keys": [{"key_material": fa0102030405060708090a0b0c0d0e0f}]}}}}`: "invalid configuration at line 1, column 62",
|
||||
`{"kms": {"providers": {"local": {"keys": [{"key_material": "\ud800fa0102030405"}]}}}}`: "invalid configuration at line 1, column 60",
|
||||
`{"identities": [{"name": "a", "credentials": [{"accessKey": "AK", "secretKey": 102030405060708090}]}]}`: "invalid configuration at line 1, column 80: invalid value for string field secretKey",
|
||||
`{"identities": [{"name": "a", "credentials": [{"secretKey": 102030405060708090`: "invalid configuration: unexpected end of input",
|
||||
`{"identities": [{"name": "a", "credentials": [{"secretKey": "c2VjcmV0`: "invalid configuration: unexpected end of input",
|
||||
`{"identities": "c2VjcmV0"}`: "invalid configuration at line 1, column 16",
|
||||
`"c2VjcmV0"`: "invalid configuration at line 1, column 1",
|
||||
`{"identities": [{"name": "\ud800"}]}`: "invalid configuration at line 1, column 26",
|
||||
`{"identities": [{"name": 5, "actions": [`: "invalid configuration: unexpected end of input",
|
||||
`{"identities": [{"name": "a"}]}"`: "invalid configuration at line 1, column 32",
|
||||
`{"é": nul#`: "invalid configuration at line 1, column 10",
|
||||
"{}\n \"x": "invalid configuration at line 2, column 3",
|
||||
"{\"a\": 1} \t\r\n\"x": "invalid configuration at line 2, column 1",
|
||||
" \n": "invalid configuration: unexpected end of input",
|
||||
} {
|
||||
err := ParseS3ConfigurationFromBytes([]byte(content), &iam_pb.S3ApiConfiguration{})
|
||||
if err == nil || err.Error() != want {
|
||||
t.Errorf("%q: got %v, want %s", content, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
err := ParseS3ConfigurationFromBytes([]byte(`{"global": {"enabled": "yes"}}`), &s3_pb.S3CircuitBreakerConfig{})
|
||||
if want := "invalid configuration at line 1, column 24: invalid value for bool field enabled"; err == nil || err.Error() != want {
|
||||
t.Errorf("circuit breaker: got %v, want %s", err, want)
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,7 @@ var baseS3ActionMap = map[string]string{
|
||||
// resolved request action.
|
||||
"ListBucketMultipartUploads": s3_constants.ACTION_LIST_MULTIPART_UPLOADS,
|
||||
"ListMultipartUploadParts": s3_constants.ACTION_LIST_PARTS,
|
||||
"GetIncompleteUpload": s3_constants.ACTION_GET_INCOMPLETE_UPLOAD,
|
||||
// Retention and legal hold operations
|
||||
"GetObjectRetention": s3_constants.ACTION_GET_OBJECT_RETENTION,
|
||||
"PutObjectRetention": s3_constants.ACTION_PUT_OBJECT_RETENTION,
|
||||
@@ -230,6 +231,8 @@ func MapToIdentitiesAction(action string) string {
|
||||
return "ListBucketMultipartUploads"
|
||||
case s3_constants.ACTION_LIST_PARTS:
|
||||
return "ListMultipartUploadParts"
|
||||
case s3_constants.ACTION_GET_INCOMPLETE_UPLOAD:
|
||||
return "GetIncompleteUpload"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
)
|
||||
|
||||
var (
|
||||
// chunkProofLimit bounds the assignment proofs a mount keeps at once, a few
|
||||
// hundred bytes each. Reaching it means that many uploaded chunks still
|
||||
// wait for their entry to be stored.
|
||||
chunkProofLimit = 1 << 16
|
||||
// chunkProofWait is how long an upload waits for room to keep its proof
|
||||
// before it fails. Tests shorten it.
|
||||
chunkProofWait = time.Minute
|
||||
// chunkProofExpiryGrace keeps a proof past its expiry for as long as a
|
||||
// filer's clock leeway may still accept it.
|
||||
chunkProofExpiryGrace = 5 * time.Minute
|
||||
)
|
||||
|
||||
// chunkProofs keeps the assignment proofs that a filer returns with
|
||||
// AssignVolume to a scoped token. Such a filer stores a chunk it does not
|
||||
// already hold at that path only when the request carries the chunk's proof
|
||||
// in chunk_auth, so every proof is kept from the upload until a filer has
|
||||
// acknowledged an entry that names the chunk. A failed or timed out commit
|
||||
// may or may not have been stored, so it releases nothing: the retry still
|
||||
// carries the proof, and a proof for a chunk the filer already holds is
|
||||
// ignored there.
|
||||
//
|
||||
// The store is bounded. Once it is full an upload waits, before it is
|
||||
// assigned a file id, for commits to make room, and fails after
|
||||
// chunkProofWait instead of evicting a proof a pending commit still needs.
|
||||
// Only proofs past their expiry are dropped to make room: a filer refuses
|
||||
// them anyway.
|
||||
//
|
||||
// A nil *chunkProofs keeps nothing and attaches nothing: a mount without a
|
||||
// filer token is never given proofs, and its requests are left as they are.
|
||||
type chunkProofs struct {
|
||||
mu sync.Mutex
|
||||
held map[string]chunkProof // by the file id a chunk names
|
||||
reserved int // uploads under way that may add a proof
|
||||
limit int
|
||||
room chan struct{} // closed and replaced when room may have been made
|
||||
}
|
||||
|
||||
type chunkProof struct {
|
||||
auth string
|
||||
expires time.Time // zero when the proof does not say
|
||||
}
|
||||
|
||||
func newChunkProofs(limit int) *chunkProofs {
|
||||
return &chunkProofs{held: make(map[string]chunkProof), limit: limit, room: make(chan struct{})}
|
||||
}
|
||||
|
||||
// reserve makes room for the proofs of an upload of n file ids before it is
|
||||
// assigned, waiting up to chunkProofWait for commits to release some.
|
||||
func (p *chunkProofs) reserve(n int) error {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
if n > p.limit {
|
||||
return fmt.Errorf("an upload of %d file ids needs more assignment proofs than the %d a mount keeps", n, p.limit)
|
||||
}
|
||||
deadline := time.Now().Add(chunkProofWait)
|
||||
logged := false
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
for len(p.held)+p.reserved+n > p.limit {
|
||||
if p.dropExpiredLocked() {
|
||||
continue
|
||||
}
|
||||
wait := time.Until(deadline)
|
||||
if wait <= 0 {
|
||||
return fmt.Errorf("%d uploaded chunks still wait for their entries to be stored: no room to keep another assignment proof", len(p.held))
|
||||
}
|
||||
if !logged {
|
||||
logged = true
|
||||
glog.V(0).Infof("%d uploaded chunks still wait for their entries to be stored: the next upload waits for a commit", len(p.held))
|
||||
}
|
||||
room := p.room
|
||||
p.mu.Unlock()
|
||||
timer := time.NewTimer(wait)
|
||||
select {
|
||||
case <-room:
|
||||
case <-timer.C:
|
||||
}
|
||||
timer.Stop()
|
||||
p.mu.Lock()
|
||||
}
|
||||
p.reserved += n
|
||||
return nil
|
||||
}
|
||||
|
||||
// keep ends the reservation of n file ids made for an upload that stored its
|
||||
// data under fileId, and keeps the proof the filer returned for them. An
|
||||
// empty proof keeps nothing: the filer did not ask for one.
|
||||
func (p *chunkProofs) keep(fileId, auth string, n int) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
covered := n
|
||||
var expires time.Time
|
||||
if claims, ok := security.AssignProofClaims(security.EncodedJwt(auth)); ok {
|
||||
if claims.ExpiresAt != nil {
|
||||
expires = claims.ExpiresAt.Time
|
||||
}
|
||||
// A proof covers fileId and fileId_1 up to its count.
|
||||
if int(claims.Count) < covered {
|
||||
covered = int(claims.Count)
|
||||
}
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.reserved -= n
|
||||
if auth != "" {
|
||||
for i := 0; i < covered; i++ {
|
||||
fid := fileId
|
||||
if i > 0 {
|
||||
fid = fmt.Sprintf("%s_%d", fileId, i)
|
||||
}
|
||||
p.held[fid] = chunkProof{auth: auth, expires: expires}
|
||||
}
|
||||
}
|
||||
p.signalLocked()
|
||||
}
|
||||
|
||||
// unreserve ends the reservation of n file ids made for a failed upload.
|
||||
func (p *chunkProofs) unreserve(n int) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.reserved -= n
|
||||
p.signalLocked()
|
||||
}
|
||||
|
||||
// attach adds to *auth the proof of each chunk the store holds one for, and
|
||||
// reports whether there was any. It writes nothing once *auth carries them,
|
||||
// so a request already handed to a send that is still in flight can be
|
||||
// attached to again for its retry: the proofs of the chunks a request names
|
||||
// are kept before the request is built.
|
||||
func (p *chunkProofs) attach(chunks []*filer_pb.FileChunk, auth *map[string]string) (held bool) {
|
||||
if p == nil || len(chunks) == 0 {
|
||||
return false
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if len(p.held) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, chunk := range chunks {
|
||||
fid := chunk.GetFileIdString()
|
||||
proof, ok := p.held[fid]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
held = true
|
||||
if current, ok := (*auth)[fid]; ok && current == proof.auth {
|
||||
continue
|
||||
}
|
||||
if *auth == nil {
|
||||
*auth = make(map[string]string)
|
||||
}
|
||||
(*auth)[fid] = proof.auth
|
||||
}
|
||||
return held
|
||||
}
|
||||
|
||||
// release drops the proofs of chunks once a filer acknowledged an entry that
|
||||
// names them: it holds the chunks now and asks for no proof again.
|
||||
func (p *chunkProofs) release(chunks []*filer_pb.FileChunk) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
released := false
|
||||
for _, chunk := range chunks {
|
||||
fid := chunk.GetFileIdString()
|
||||
if _, ok := p.held[fid]; ok {
|
||||
delete(p.held, fid)
|
||||
released = true
|
||||
}
|
||||
}
|
||||
if released {
|
||||
p.signalLocked()
|
||||
}
|
||||
}
|
||||
|
||||
// count reports how many file ids have a proof kept.
|
||||
func (p *chunkProofs) count() int {
|
||||
if p == nil {
|
||||
return 0
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return len(p.held)
|
||||
}
|
||||
|
||||
func (p *chunkProofs) dropExpiredLocked() (dropped bool) {
|
||||
now := time.Now()
|
||||
for fid, proof := range p.held {
|
||||
if !proof.expires.IsZero() && now.After(proof.expires.Add(chunkProofExpiryGrace)) {
|
||||
delete(p.held, fid)
|
||||
dropped = true
|
||||
}
|
||||
}
|
||||
return dropped
|
||||
}
|
||||
|
||||
func (p *chunkProofs) signalLocked() {
|
||||
close(p.room)
|
||||
p.room = make(chan struct{})
|
||||
}
|
||||
|
||||
// requestChunks returns the chunks a filer request stores and the map their
|
||||
// proofs go in, or nil for a request that stores none.
|
||||
func requestChunks(req any) ([]*filer_pb.FileChunk, *map[string]string) {
|
||||
switch r := req.(type) {
|
||||
case *filer_pb.CreateEntryRequest:
|
||||
return r.GetEntry().GetChunks(), &r.ChunkAuth
|
||||
case *filer_pb.UpdateEntryRequest:
|
||||
return r.GetEntry().GetChunks(), &r.ChunkAuth
|
||||
case *filer_pb.AppendToEntryRequest:
|
||||
return r.GetChunks(), &r.ChunkAuth
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// stored reports whether reply acknowledges that the filer stored the
|
||||
// request's entry. A create reports a refused condition in its reply.
|
||||
func stored(reply any) bool {
|
||||
if r, ok := reply.(*filer_pb.CreateEntryResponse); ok {
|
||||
return r.GetError() == "" && r.GetErrorCode() == filer_pb.FilerError_OK
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// conn attaches the kept proofs to every unary create, update and append the
|
||||
// mount sends through cc, on each attempt, and releases them once the filer
|
||||
// acknowledged the request.
|
||||
func (p *chunkProofs) conn(cc grpc.ClientConnInterface) grpc.ClientConnInterface {
|
||||
if p == nil {
|
||||
return cc
|
||||
}
|
||||
return &chunkProofConn{ClientConnInterface: cc, proofs: p}
|
||||
}
|
||||
|
||||
type chunkProofConn struct {
|
||||
grpc.ClientConnInterface
|
||||
proofs *chunkProofs
|
||||
}
|
||||
|
||||
func (c *chunkProofConn) Invoke(ctx context.Context, method string, args, reply any, opts ...grpc.CallOption) error {
|
||||
chunks, auth := requestChunks(args)
|
||||
held := auth != nil && c.proofs.attach(chunks, auth)
|
||||
err := c.ClientConnInterface.Invoke(ctx, method, args, reply, opts...)
|
||||
if err == nil && held && stored(reply) {
|
||||
c.proofs.release(chunks)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,763 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v5"
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
)
|
||||
|
||||
var proofTestKey = security.SigningKey("chunk-proof-test-signing-key")
|
||||
|
||||
// proofCluster is what the filers of one cluster share: their entries and the
|
||||
// file ids they assign.
|
||||
type proofCluster struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]*filer_pb.Entry
|
||||
received []proofRequest
|
||||
assigned atomic.Uint64
|
||||
}
|
||||
|
||||
type proofRequest struct {
|
||||
via string // "unary" or "stream"
|
||||
chunk []*filer_pb.FileChunk
|
||||
auth map[string]string
|
||||
}
|
||||
|
||||
func newProofCluster() *proofCluster {
|
||||
return &proofCluster{entries: make(map[string]*filer_pb.Entry)}
|
||||
}
|
||||
|
||||
func (c *proofCluster) entry(path string) *filer_pb.Entry {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.entries[path]
|
||||
}
|
||||
|
||||
func (c *proofCluster) put(path string, entry *filer_pb.Entry) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.entries[path] = entry
|
||||
}
|
||||
|
||||
func (c *proofCluster) requests() []proofRequest {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return append([]proofRequest(nil), c.received...)
|
||||
}
|
||||
|
||||
// proofFiler applies a scoped filer's rule for new chunks with the real
|
||||
// assignment proof primitives. AssignVolume to a scoped token returns a proof
|
||||
// bound to the token's id; a create, update or append naming a chunk the
|
||||
// stored entry lacks is refused unless chunk_auth holds a valid proof for it,
|
||||
// and chunks cannot be added to an entry that holds manifests. A token
|
||||
// without path grants gets no proof and is not checked. Filers sharing a
|
||||
// cluster accept each other's proofs, as they share the signing key.
|
||||
type proofFiler struct {
|
||||
fakeFilerServer
|
||||
cluster *proofCluster
|
||||
volume string
|
||||
assigns atomic.Int32
|
||||
failCommits atomic.Int32 // commits answered Unavailable before storing
|
||||
holdCommits atomic.Int32 // commits held until the caller gives up
|
||||
}
|
||||
|
||||
func newProofFiler(t *testing.T, cluster *proofCluster, volume string) (*proofFiler, pb.ServerAddress) {
|
||||
f := &proofFiler{cluster: cluster, volume: volume}
|
||||
return f, listenFiler(t, f)
|
||||
}
|
||||
|
||||
func proofHolder(ctx context.Context) (string, bool) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
token, ok := strings.CutPrefix(joinAuthorization(md), "Bearer ")
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
claims, ok := security.FilerTokenClaims(security.EncodedJwt(token))
|
||||
if !ok || !claims.IsScoped() {
|
||||
return "", false
|
||||
}
|
||||
return claims.ID, true
|
||||
}
|
||||
|
||||
func (f *proofFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
|
||||
f.assigns.Add(1)
|
||||
fid := needle.NewFileId(3, f.cluster.assigned.Add(1), 0x637037d6).String()
|
||||
resp := &filer_pb.AssignVolumeResponse{
|
||||
FileId: fid,
|
||||
Count: req.GetCount(),
|
||||
Location: &filer_pb.Location{Url: f.volume, PublicUrl: f.volume},
|
||||
}
|
||||
if holder, scoped := proofHolder(ctx); scoped {
|
||||
resp.AssignAuth = string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, holder, req.GetCount(), ""))
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// commit checks a request the way a scoped filer does and stores entry at
|
||||
// path. appended chunks are added to the stored entry instead.
|
||||
func (f *proofFiler) commit(ctx context.Context, via, method, path string, entry *filer_pb.Entry, appended []*filer_pb.FileChunk, auth map[string]string) error {
|
||||
requested := entry.GetChunks()
|
||||
if appended != nil {
|
||||
requested = appended
|
||||
}
|
||||
f.cluster.mu.Lock()
|
||||
defer f.cluster.mu.Unlock()
|
||||
f.cluster.received = append(f.cluster.received, proofRequest{via: via, chunk: requested, auth: auth})
|
||||
if f.failCommits.Load() > 0 {
|
||||
f.failCommits.Add(-1)
|
||||
return status.Error(codes.Unavailable, "filer restarting")
|
||||
}
|
||||
if f.holdCommits.Load() > 0 {
|
||||
f.holdCommits.Add(-1)
|
||||
f.cluster.mu.Unlock()
|
||||
<-ctx.Done()
|
||||
f.cluster.mu.Lock()
|
||||
return ctx.Err()
|
||||
}
|
||||
stored := f.cluster.entries[path]
|
||||
if holder, scoped := proofHolder(ctx); scoped {
|
||||
known := make(map[string]bool)
|
||||
for _, chunk := range stored.GetChunks() {
|
||||
if chunk.GetIsChunkManifest() && len(requested) > 0 {
|
||||
return status.Errorf(codes.PermissionDenied, "filer: %s: chunks cannot be written to an entry containing manifests", method)
|
||||
}
|
||||
known[chunk.GetFileIdString()] = true
|
||||
}
|
||||
for _, chunk := range requested {
|
||||
fid := chunk.GetFileIdString()
|
||||
if !known[fid] && !security.VerifyAssignJwt(proofTestKey, nil, security.EncodedJwt(auth[fid]), fid, holder, 0, "") {
|
||||
return status.Errorf(codes.PermissionDenied, "filer: %s: %s %s", method, filer_pb.ChunkProofRefused, fid)
|
||||
}
|
||||
}
|
||||
}
|
||||
if appended != nil {
|
||||
next := proto.Clone(stored).(*filer_pb.Entry)
|
||||
next.Chunks = append(next.Chunks, appended...)
|
||||
entry = next
|
||||
}
|
||||
f.cluster.entries[path] = proto.Clone(entry).(*filer_pb.Entry)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *proofFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
if err := f.commit(ctx, "unary", "CreateEntry", string(util.NewFullPath(req.Directory, req.Entry.Name)), req.Entry, nil, req.ChunkAuth); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.fakeFilerServer.CreateEntry(ctx, req)
|
||||
}
|
||||
|
||||
func (f *proofFiler) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
|
||||
if err := f.commit(ctx, "unary", "UpdateEntry", string(util.NewFullPath(req.Directory, req.Entry.Name)), req.Entry, nil, req.ChunkAuth); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.fakeFilerServer.UpdateEntry(ctx, req)
|
||||
}
|
||||
|
||||
func (f *proofFiler) AppendToEntry(ctx context.Context, req *filer_pb.AppendToEntryRequest) (*filer_pb.AppendToEntryResponse, error) {
|
||||
if err := f.commit(ctx, "unary", "AppendToEntry", string(util.NewFullPath(req.Directory, req.EntryName)), nil, req.Chunks, req.ChunkAuth); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &filer_pb.AppendToEntryResponse{}, nil
|
||||
}
|
||||
|
||||
// StreamMutateEntry answers a refusal in the response, with EACCES, as the
|
||||
// scoped filer's stream check does.
|
||||
func (f *proofFiler) StreamMutateEntry(stream filer_pb.SeaweedFiler_StreamMutateEntryServer) error {
|
||||
for {
|
||||
req, err := stream.Recv()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out := &filer_pb.StreamMutateEntryResponse{RequestId: req.RequestId, IsLast: true}
|
||||
switch r := req.Request.(type) {
|
||||
case *filer_pb.StreamMutateEntryRequest_CreateRequest:
|
||||
c := r.CreateRequest
|
||||
err = f.commit(stream.Context(), "stream", "CreateEntry", string(util.NewFullPath(c.Directory, c.Entry.Name)), c.Entry, nil, c.ChunkAuth)
|
||||
out.Response = &filer_pb.StreamMutateEntryResponse_CreateResponse{CreateResponse: &filer_pb.CreateEntryResponse{}}
|
||||
case *filer_pb.StreamMutateEntryRequest_UpdateRequest:
|
||||
u := r.UpdateRequest
|
||||
err = f.commit(stream.Context(), "stream", "UpdateEntry", string(util.NewFullPath(u.Directory, u.Entry.Name)), u.Entry, nil, u.ChunkAuth)
|
||||
out.Response = &filer_pb.StreamMutateEntryResponse_UpdateResponse{UpdateResponse: &filer_pb.UpdateEntryResponse{}}
|
||||
default:
|
||||
err = fmt.Errorf("unexpected request %T", req.Request)
|
||||
}
|
||||
if err != nil {
|
||||
out.Response = nil
|
||||
out.Error, out.Errno = err.Error(), int32(syscall.EACCES)
|
||||
}
|
||||
if err := stream.Send(out); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newProofMount is a mount writing through filers (in walk order) with token,
|
||||
// which also keeps assignment proofs unless token is empty. Chunks go straight
|
||||
// to the volume stub the filers assign.
|
||||
func newProofMount(t *testing.T, token security.EncodedJwt, filers ...pb.ServerAddress) *WFS {
|
||||
t.Helper()
|
||||
wfs := newInvalidateTestWFS(t)
|
||||
wfs.filerCallTimeout = 5 * time.Second
|
||||
wfs.option.ConcurrentWriters = 4
|
||||
wfs.option.uniqueCacheDirForWrite = t.TempDir()
|
||||
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
|
||||
wfs.option.FilerAddresses = filers
|
||||
atomic.StoreInt32(&wfs.option.filerIndex, 0)
|
||||
wfs.option.VolumeServerAccess = "direct"
|
||||
wfs.filerClient = wdclient.NewFilerClient(filers, wfs.option.GrpcDialOption, "")
|
||||
if token != "" {
|
||||
wfs.option.FilerTokenSource = func(context.Context) (security.EncodedJwt, error) { return token, nil }
|
||||
wfs.chunkProofs = newChunkProofs(chunkProofLimit)
|
||||
}
|
||||
return wfs
|
||||
}
|
||||
|
||||
func scopedMountToken() security.EncodedJwt {
|
||||
return security.GenJwtForFilerScope(proofTestKey, time.Hour, "mount-1", []string{"/dir"}, nil)
|
||||
}
|
||||
|
||||
// openDirtyFile opens /dir/file holding stored, which the cluster stores too,
|
||||
// with data written after it and not uploaded yet.
|
||||
func openDirtyFile(t *testing.T, wfs *WFS, cluster *proofCluster, stored ...*filer_pb.FileChunk) *FileHandle {
|
||||
t.Helper()
|
||||
data := []byte("data written by a scoped mount")
|
||||
offset := int64(filer.TotalSize(stored))
|
||||
entry := &filer_pb.Entry{
|
||||
Name: "file",
|
||||
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(offset) + uint64(len(data)), FileMode: 0100644},
|
||||
Chunks: stored,
|
||||
}
|
||||
if len(stored) > 0 {
|
||||
cluster.put("/dir/file", proto.Clone(entry).(*filer_pb.Entry))
|
||||
}
|
||||
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
|
||||
t.Cleanup(func() { wfs.ReleaseHandle(fh.fh) })
|
||||
if _, err := fh.dirtyPages.AddPage(offset, data, true, time.Now().UnixNano()); err != nil {
|
||||
t.Fatalf("AddPage: %v", err)
|
||||
}
|
||||
fh.dirtyMetadata = true
|
||||
return fh
|
||||
}
|
||||
|
||||
func flushFile(wfs *WFS, fh *FileHandle) fuse.Status {
|
||||
return wfs.Flush(nil, &fuse.FlushIn{InHeader: fuse.InHeader{NodeId: fh.inode}, Fh: uint64(fh.fh)})
|
||||
}
|
||||
|
||||
// newChunks returns the chunks of req the cluster had not stored before it.
|
||||
func newChunks(req proofRequest, before map[string]bool) []string {
|
||||
var fids []string
|
||||
for _, chunk := range req.chunk {
|
||||
if !before[chunk.GetFileIdString()] {
|
||||
fids = append(fids, chunk.GetFileIdString())
|
||||
}
|
||||
}
|
||||
return fids
|
||||
}
|
||||
|
||||
// checkCarriesProofs asserts auth holds a valid proof for every one of fids
|
||||
// and nothing else.
|
||||
func checkCarriesProofs(t *testing.T, auth map[string]string, fids ...string) {
|
||||
t.Helper()
|
||||
if len(auth) != len(fids) {
|
||||
t.Fatalf("chunk_auth names %d chunks, want exactly %v: %v", len(auth), fids, auth)
|
||||
}
|
||||
for _, fid := range fids {
|
||||
if !security.VerifyAssignJwt(proofTestKey, nil, security.EncodedJwt(auth[fid]), fid, "mount-1", 0, "") {
|
||||
t.Fatalf("chunk_auth carries no valid proof for %s", fid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A scoped mount's flush stores its new chunk only with the chunk's proof,
|
||||
// and the proof is dropped once the filer acknowledged it. Without the proofs
|
||||
// (the mount before it kept them) the filer refuses the same flush.
|
||||
func TestScopedMountFlushCommitsNewChunkWithItsProof(t *testing.T) {
|
||||
for _, keep := range []bool{true, false} {
|
||||
t.Run(fmt.Sprintf("keeps proofs %v", keep), func(t *testing.T) {
|
||||
cluster := newProofCluster()
|
||||
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
wfs := newProofMount(t, scopedMountToken(), addr)
|
||||
if !keep {
|
||||
wfs.chunkProofs = nil
|
||||
}
|
||||
fh := openDirtyFile(t, wfs, cluster)
|
||||
|
||||
status := flushFile(wfs, fh)
|
||||
if !keep {
|
||||
if status == fuse.OK || cluster.entry("/dir/file") != nil {
|
||||
t.Fatalf("Flush = %v without proofs, want the filer to refuse it", status)
|
||||
}
|
||||
return
|
||||
}
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("Flush = %v, want OK", status)
|
||||
}
|
||||
stored := cluster.entry("/dir/file")
|
||||
if len(stored.GetChunks()) != 1 {
|
||||
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
|
||||
}
|
||||
requests := cluster.requests()
|
||||
if len(requests) != 1 {
|
||||
t.Fatalf("filer received %d commits, want 1", len(requests))
|
||||
}
|
||||
checkCarriesProofs(t, requests[0].auth, stored.Chunks[0].GetFileIdString())
|
||||
if n := wfs.chunkProofs.count(); n != 0 {
|
||||
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A commit that failed may still have been stored, so it releases nothing:
|
||||
// the retry, on the same filer or another one of the cluster, carries the
|
||||
// proof the first filer issued.
|
||||
func TestScopedMountRetriedCommitCarriesProof(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
filers int
|
||||
failing int32 // commits the first filer fails
|
||||
}{
|
||||
{name: "same filer", filers: 1, failing: 1},
|
||||
{name: "assigned on one filer, stored by another", filers: 2, failing: 1 << 20},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cluster := newProofCluster()
|
||||
volume := newVolumeStub(t)
|
||||
first, addr := newProofFiler(t, cluster, volume)
|
||||
first.failCommits.Store(tc.failing)
|
||||
addrs := []pb.ServerAddress{addr}
|
||||
var second *proofFiler
|
||||
if tc.filers == 2 {
|
||||
var addr2 pb.ServerAddress
|
||||
second, addr2 = newProofFiler(t, cluster, volume)
|
||||
addrs = append(addrs, addr2)
|
||||
}
|
||||
wfs := newProofMount(t, scopedMountToken(), addrs...)
|
||||
fh := openDirtyFile(t, wfs, cluster)
|
||||
|
||||
if status := flushFile(wfs, fh); status != fuse.OK {
|
||||
t.Fatalf("Flush = %v, want OK", status)
|
||||
}
|
||||
stored := cluster.entry("/dir/file")
|
||||
if len(stored.GetChunks()) != 1 {
|
||||
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
|
||||
}
|
||||
fid := stored.Chunks[0].GetFileIdString()
|
||||
requests := cluster.requests()
|
||||
if len(requests) != 2 {
|
||||
t.Fatalf("filers received %d commits, want the failed one and its retry", len(requests))
|
||||
}
|
||||
for _, req := range requests {
|
||||
checkCarriesProofs(t, req.auth, fid)
|
||||
}
|
||||
if first.assigns.Load() != 1 {
|
||||
t.Fatalf("first filer assigned %d file ids, want 1", first.assigns.Load())
|
||||
}
|
||||
if second != nil && second.assigns.Load() != 0 {
|
||||
t.Fatalf("second filer assigned %d file ids, want none: the proof is from the first", second.assigns.Load())
|
||||
}
|
||||
if n := wfs.chunkProofs.count(); n != 0 {
|
||||
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A commit that timed out is not known to have failed: the proof stays, and
|
||||
// the next flush stores the chunk with it.
|
||||
func TestScopedMountKeepsProofAfterTimedOutCommit(t *testing.T) {
|
||||
saved := metadataFlushTimeout
|
||||
metadataFlushTimeout = 300 * time.Millisecond
|
||||
t.Cleanup(func() { metadataFlushTimeout = saved })
|
||||
|
||||
cluster := newProofCluster()
|
||||
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
fake.holdCommits.Store(1)
|
||||
wfs := newProofMount(t, scopedMountToken(), addr)
|
||||
fh := openDirtyFile(t, wfs, cluster)
|
||||
|
||||
if status := flushFile(wfs, fh); status == fuse.OK {
|
||||
t.Fatal("Flush = OK against a filer that never answered the commit")
|
||||
}
|
||||
if n := wfs.chunkProofs.count(); n != 1 {
|
||||
t.Fatalf("%d proofs kept after a timed out commit, want the chunk's", n)
|
||||
}
|
||||
if status := flushFile(wfs, fh); status != fuse.OK {
|
||||
t.Fatalf("second Flush = %v, want OK", status)
|
||||
}
|
||||
stored := cluster.entry("/dir/file")
|
||||
if len(stored.GetChunks()) != 1 {
|
||||
t.Fatalf("stored chunks = %v, want the uploaded chunk", stored.GetChunks())
|
||||
}
|
||||
requests := cluster.requests()
|
||||
checkCarriesProofs(t, requests[len(requests)-1].auth, stored.Chunks[0].GetFileIdString())
|
||||
if n := wfs.chunkProofs.count(); n != 0 {
|
||||
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Creates and updates carry the proofs of the chunks the filer does not hold
|
||||
// yet, over the mutation stream and over unary calls alike.
|
||||
func TestScopedMountCreateAndUpdateCarryProofs(t *testing.T) {
|
||||
for _, via := range []string{"unary", "stream"} {
|
||||
t.Run(via, func(t *testing.T) {
|
||||
cluster := newProofCluster()
|
||||
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
wfs := newProofMount(t, scopedMountToken(), addr)
|
||||
if via == "stream" {
|
||||
wfs.streamMutate = newStreamMutateMux(wfs)
|
||||
t.Cleanup(wfs.streamMutate.Close)
|
||||
}
|
||||
save := wfs.saveDataAsChunk("/dir/f")
|
||||
upload := func(offset int64) *filer_pb.FileChunk {
|
||||
chunk, err := save(strings.NewReader("chunk"), "f", offset, time.Now().UnixNano(), 0)
|
||||
if err != nil {
|
||||
t.Fatalf("upload: %v", err)
|
||||
}
|
||||
return chunk
|
||||
}
|
||||
|
||||
first := upload(0)
|
||||
if _, err := wfs.streamCreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
||||
Directory: "/dir",
|
||||
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{first}},
|
||||
}); err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
second := upload(5)
|
||||
if _, err := wfs.streamUpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: "/dir",
|
||||
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{first, second}},
|
||||
}); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
|
||||
requests := cluster.requests()
|
||||
if len(requests) != 2 {
|
||||
t.Fatalf("filer received %d commits, want 2", len(requests))
|
||||
}
|
||||
for _, req := range requests {
|
||||
if req.via != via {
|
||||
t.Fatalf("commit went %s, want %s", req.via, via)
|
||||
}
|
||||
}
|
||||
checkCarriesProofs(t, requests[0].auth, first.GetFileIdString())
|
||||
// The update only adds the second chunk: the first one is stored.
|
||||
checkCarriesProofs(t, requests[1].auth, second.GetFileIdString())
|
||||
if got := len(cluster.entry("/dir/f").GetChunks()); got != 2 {
|
||||
t.Fatalf("stored chunks = %d, want 2", got)
|
||||
}
|
||||
if n := wfs.chunkProofs.count(); n != 0 {
|
||||
t.Fatalf("%d proofs kept after the commits were acknowledged, want 0", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A refused update releases nothing: the chunk's proof is kept for a later
|
||||
// commit, here an append.
|
||||
func TestScopedMountRefusedCommitKeepsProof(t *testing.T) {
|
||||
cluster := newProofCluster()
|
||||
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
wfs := newProofMount(t, scopedMountToken(), addr)
|
||||
chunk, err := wfs.saveDataAsChunk("/dir/f")(strings.NewReader("chunk"), "f", 0, time.Now().UnixNano(), 0)
|
||||
if err != nil {
|
||||
t.Fatalf("upload: %v", err)
|
||||
}
|
||||
cluster.put("/dir/f", &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{{FileId: "4,01637037d6", IsChunkManifest: true}}})
|
||||
_, err = wfs.streamUpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
|
||||
Directory: "/dir",
|
||||
Entry: &filer_pb.Entry{Name: "f", Chunks: []*filer_pb.FileChunk{chunk}},
|
||||
})
|
||||
if status.Code(err) != codes.PermissionDenied {
|
||||
t.Fatalf("update onto an entry of manifests = %v, want the filer's refusal", err)
|
||||
}
|
||||
if n := wfs.chunkProofs.count(); n != 1 {
|
||||
t.Fatalf("%d proofs kept after a refused commit, want the chunk's", n)
|
||||
}
|
||||
|
||||
cluster.put("/dir/f", &filer_pb.Entry{Name: "f"})
|
||||
if err := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
_, err := client.AppendToEntry(context.Background(), &filer_pb.AppendToEntryRequest{Directory: "/dir", EntryName: "f", Chunks: []*filer_pb.FileChunk{chunk}})
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatalf("append: %v", err)
|
||||
}
|
||||
requests := cluster.requests()
|
||||
checkCarriesProofs(t, requests[len(requests)-1].auth, chunk.GetFileIdString())
|
||||
if n := wfs.chunkProofs.count(); n != 0 {
|
||||
t.Fatalf("%d proofs kept after the append was acknowledged, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A filer serving a scoped token stores no new chunk in an entry that holds
|
||||
// manifests, so a mount with a token keeps the chunk list flat where an
|
||||
// unscoped mount would fold it: the flush that completes a batch of small
|
||||
// chunks commits them as they are, and the file stays writable.
|
||||
func TestScopedMountKeepsChunkListsFlat(t *testing.T) {
|
||||
cluster := newProofCluster()
|
||||
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
wfs := newProofMount(t, scopedMountToken(), addr)
|
||||
// One chunk short of a batch: the chunk this flush uploads completes it.
|
||||
stored := storedSmallChunks(filer.SmallChunkManifestBatch - 1)
|
||||
fh := openDirtyFile(t, wfs, cluster, stored...)
|
||||
|
||||
if status := flushFile(wfs, fh); status != fuse.OK {
|
||||
t.Fatalf("Flush = %v, want OK", status)
|
||||
}
|
||||
if got := fake.assigns.Load(); got != 1 {
|
||||
t.Fatalf("AssignVolume calls = %d, want only the data chunk", got)
|
||||
}
|
||||
committed := cluster.entry("/dir/file").GetChunks()
|
||||
if len(committed) != filer.SmallChunkManifestBatch {
|
||||
t.Fatalf("stored %d chunks, want the %d small chunks unfolded", len(committed), filer.SmallChunkManifestBatch)
|
||||
}
|
||||
for _, chunk := range committed {
|
||||
if chunk.GetIsChunkManifest() {
|
||||
t.Fatalf("stored a manifest %s; a scoped filer refuses later writes to such an entry", chunk.GetFileIdString())
|
||||
}
|
||||
}
|
||||
if n := wfs.chunkProofs.count(); n != 0 {
|
||||
t.Fatalf("%d proofs kept after the commit was acknowledged, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A mount whose token the filer does not scope folds chunk lists as a mount
|
||||
// without a token does.
|
||||
func TestUnscopedTokenMountFoldsChunkLists(t *testing.T) {
|
||||
cluster := newProofCluster()
|
||||
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
wfs := newProofMount(t, security.GenJwtForFilerAdmin(proofTestKey, 3600), addr)
|
||||
stored := storedSmallChunks(filer.SmallChunkManifestBatch - 1)
|
||||
fh := openDirtyFile(t, wfs, cluster, stored...)
|
||||
|
||||
if status := flushFile(wfs, fh); status != fuse.OK {
|
||||
t.Fatalf("Flush = %v, want OK", status)
|
||||
}
|
||||
if got := fake.assigns.Load(); got != 2 {
|
||||
t.Fatalf("AssignVolume calls = %d, want the data chunk and its manifest", got)
|
||||
}
|
||||
manifests := 0
|
||||
for _, chunk := range cluster.entry("/dir/file").GetChunks() {
|
||||
if chunk.GetIsChunkManifest() {
|
||||
manifests++
|
||||
}
|
||||
}
|
||||
if manifests != 1 {
|
||||
t.Fatalf("stored %d manifests, want the %d small chunks folded into one", manifests, filer.SmallChunkManifestBatch)
|
||||
}
|
||||
}
|
||||
|
||||
// Without a scoped token the filer issues no proofs, and a flush sends the
|
||||
// same chunks and no chunk_auth, whether or not the mount has a token.
|
||||
func TestUnscopedMountRequestsCarryNoProofs(t *testing.T) {
|
||||
var lists [][]string
|
||||
// A filer token with no path grants is unscoped: it has full access.
|
||||
unscoped := security.GenJwtForFilerAdmin(proofTestKey, 3600)
|
||||
if unscoped == "" {
|
||||
t.Fatal("no unscoped filer token was signed")
|
||||
}
|
||||
for _, token := range []security.EncodedJwt{"", unscoped} {
|
||||
cluster := newProofCluster()
|
||||
_, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
wfs := newProofMount(t, token, addr)
|
||||
if (token == "") != (wfs.chunkProofs == nil) {
|
||||
t.Fatal("a mount keeps proofs only with a filer token")
|
||||
}
|
||||
fh := openDirtyFile(t, wfs, cluster)
|
||||
if status := flushFile(wfs, fh); status != fuse.OK {
|
||||
t.Fatalf("Flush = %v, want OK", status)
|
||||
}
|
||||
requests := cluster.requests()
|
||||
if len(requests) != 1 || requests[0].auth != nil {
|
||||
t.Fatalf("commits = %+v, want one without chunk_auth", requests)
|
||||
}
|
||||
var list []string
|
||||
for _, chunk := range requests[0].chunk {
|
||||
list = append(list, fmt.Sprintf("%s@%d+%d", chunk.GetFileIdString(), chunk.Offset, chunk.Size))
|
||||
}
|
||||
lists = append(lists, list)
|
||||
if n := wfs.chunkProofs.count(); n != 0 {
|
||||
t.Fatalf("%d proofs kept without a scoped token", n)
|
||||
}
|
||||
}
|
||||
if fmt.Sprint(lists[0]) != fmt.Sprint(lists[1]) {
|
||||
t.Fatalf("chunk lists differ with and without a token: %v vs %v", lists[0], lists[1])
|
||||
}
|
||||
}
|
||||
|
||||
// One proof covers each file id of a multi-count assignment, and each is
|
||||
// released on its own.
|
||||
func TestChunkProofsCoverEveryIdOfAnAssignment(t *testing.T) {
|
||||
const fid = "3,01637037d6"
|
||||
proof := string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 3, ""))
|
||||
p := newChunkProofs(8)
|
||||
if err := p.reserve(3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.keep(fid, proof, 3)
|
||||
chunks := []*filer_pb.FileChunk{{FileId: fid + "_2"}, {FileId: fid}, {FileId: "3,02637037d6"}}
|
||||
var auth map[string]string
|
||||
if !p.attach(chunks, &auth) {
|
||||
t.Fatal("attach found no proofs")
|
||||
}
|
||||
checkCarriesProofs(t, auth, fid, fid+"_2")
|
||||
|
||||
p.release(chunks[1:2])
|
||||
auth = nil
|
||||
p.attach([]*filer_pb.FileChunk{{FileId: fid}, {FileId: fid + "_1"}}, &auth)
|
||||
checkCarriesProofs(t, auth, fid+"_1")
|
||||
if n := p.count(); n != 2 {
|
||||
t.Fatalf("proofs kept = %d, want 2", n)
|
||||
}
|
||||
|
||||
// A proof covers no more ids than its count, whatever the upload asked.
|
||||
q := newChunkProofs(8)
|
||||
if err := q.reserve(2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q.keep(fid, string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 1, "")), 2)
|
||||
if n := q.count(); n != 1 || q.reserved != 0 {
|
||||
t.Fatalf("proofs kept = %d, reserved = %d, want 1 and 0", n, q.reserved)
|
||||
}
|
||||
}
|
||||
|
||||
func expiredProof(t *testing.T, fid string, expired time.Duration) string {
|
||||
t.Helper()
|
||||
collection := ""
|
||||
claims := security.SeaweedAssignClaims{Fid: fid, Count: 1, Collection: &collection, RegisteredClaims: jwt.RegisteredClaims{
|
||||
ID: "mount-1", ExpiresAt: jwt.NewNumericDate(time.Now().Add(-expired)),
|
||||
}}
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(security.AssignSigningKey(proofTestKey)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
|
||||
// A full store holds an upload back until a commit makes room, and fails it
|
||||
// when none does instead of dropping a proof a commit still needs. Only
|
||||
// proofs past their expiry make room by themselves.
|
||||
func TestChunkProofsFullStoreWaitsThenFails(t *testing.T) {
|
||||
saved := chunkProofWait
|
||||
chunkProofWait = 300 * time.Millisecond
|
||||
t.Cleanup(func() { chunkProofWait = saved })
|
||||
|
||||
proof := func(fid string) string {
|
||||
return string(security.GenJwtForAssign(proofTestKey, time.Hour, fid, "mount-1", 1, ""))
|
||||
}
|
||||
held := []*filer_pb.FileChunk{{FileId: "3,01637037d6"}, {FileId: "3,02637037d6"}}
|
||||
|
||||
t.Run("a commit makes room", func(t *testing.T) {
|
||||
p := newChunkProofs(2)
|
||||
for _, chunk := range held {
|
||||
if err := p.reserve(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.keep(chunk.FileId, proof(chunk.FileId), 1)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- p.reserve(1) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("reserve on a full store returned %v before any commit", err)
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
p.release(held[:1])
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("reserve after a commit made room: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nothing makes room", func(t *testing.T) {
|
||||
p := newChunkProofs(2)
|
||||
for _, chunk := range held {
|
||||
if err := p.reserve(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.keep(chunk.FileId, proof(chunk.FileId), 1)
|
||||
}
|
||||
start := time.Now()
|
||||
if err := p.reserve(1); err == nil {
|
||||
t.Fatal("reserve succeeded on a store no commit drained")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < chunkProofWait {
|
||||
t.Fatalf("reserve failed after %v, want it to wait %v", elapsed, chunkProofWait)
|
||||
}
|
||||
var auth map[string]string
|
||||
p.attach(held, &auth)
|
||||
checkCarriesProofs(t, auth, held[0].FileId, held[1].FileId)
|
||||
})
|
||||
|
||||
t.Run("expired proofs make room", func(t *testing.T) {
|
||||
p := newChunkProofs(2)
|
||||
for _, tc := range []struct {
|
||||
fid string
|
||||
expired time.Duration
|
||||
}{{held[0].FileId, chunkProofExpiryGrace + time.Minute}, {held[1].FileId, chunkProofExpiryGrace - time.Minute}} {
|
||||
if err := p.reserve(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.keep(tc.fid, expiredProof(t, tc.fid, tc.expired), 1)
|
||||
}
|
||||
if err := p.reserve(1); err != nil {
|
||||
t.Fatalf("reserve with a proof past its expiry: %v", err)
|
||||
}
|
||||
var auth map[string]string
|
||||
p.attach(held, &auth)
|
||||
if _, ok := auth[held[0].FileId]; ok || len(auth) != 1 {
|
||||
t.Fatalf("kept proofs = %v, want only the one still within its grace", auth)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An upload the store has no room for fails before it is assigned a file id,
|
||||
// so no data is stored that no commit could name.
|
||||
func TestScopedMountUploadFailsWhenProofsAreFull(t *testing.T) {
|
||||
saved := chunkProofWait
|
||||
chunkProofWait = 100 * time.Millisecond
|
||||
t.Cleanup(func() { chunkProofWait = saved })
|
||||
|
||||
cluster := newProofCluster()
|
||||
fake, addr := newProofFiler(t, cluster, newVolumeStub(t))
|
||||
wfs := newProofMount(t, scopedMountToken(), addr)
|
||||
wfs.chunkProofs = newChunkProofs(1)
|
||||
save := wfs.saveDataAsChunk("/dir/f")
|
||||
if _, err := save(strings.NewReader("one"), "f", 0, time.Now().UnixNano(), 0); err != nil {
|
||||
t.Fatalf("first upload: %v", err)
|
||||
}
|
||||
if _, err := save(strings.NewReader("two"), "f", 3, time.Now().UnixNano(), 0); err == nil {
|
||||
t.Fatal("upload succeeded with no room to keep its proof")
|
||||
}
|
||||
if got := fake.assigns.Load(); got != 1 {
|
||||
t.Fatalf("AssignVolume calls = %d, want only the first upload's", got)
|
||||
}
|
||||
if wfs.chunkProofs.reserved != 0 {
|
||||
t.Fatalf("reserved = %d after the uploads ended, want 0", wfs.chunkProofs.reserved)
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ type FileHandle struct {
|
||||
// Nested handle lock order: wfs.fhLockTable[fh.fh] -> entryLock ->
|
||||
// LockedEntry.RWMutex. Paths may use a subset, but must never acquire an
|
||||
// earlier lock while holding a later one. Release in reverse order.
|
||||
// Only CopyFileRange holds the fhLockTable locks of two handles at once; it
|
||||
// takes them in ascending FileHandleId order.
|
||||
entryLock sync.RWMutex
|
||||
entryChunkGroup *filer.ChunkGroup
|
||||
inode uint64
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"math"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
@@ -23,10 +25,19 @@ import (
|
||||
// need to have logic similar to FilerStoreWrapper
|
||||
// e.g. fill fileId field for chunks
|
||||
|
||||
// metaBatchStore takes the batched writes of a directory build: the inserts of
|
||||
// the listing and the wipe before them. It is the leveldb store; tests stand
|
||||
// in for it to fill the cache disk.
|
||||
type metaBatchStore interface {
|
||||
BatchInsertEntries(ctx context.Context, entries []*filer.Entry) error
|
||||
BatchDeleteEntries(ctx context.Context, paths []util.FullPath) error
|
||||
}
|
||||
|
||||
type MetaCache struct {
|
||||
root util.FullPath
|
||||
localStore filer.VirtualFilerStore
|
||||
leveldbStore *leveldb.LevelDBStore // direct reference for batch operations
|
||||
batchStore metaBatchStore
|
||||
sync.RWMutex
|
||||
uidGidMapper *UidGidMapper
|
||||
markCachedFn func(fullpath util.FullPath)
|
||||
@@ -49,6 +60,11 @@ type MetaCache struct {
|
||||
// instead of streaming to the limit again to rediscover them.
|
||||
oversizedDirs map[util.FullPath]struct{}
|
||||
|
||||
// storeRefusedUntil is when, in unix nanoseconds, builds are tried again
|
||||
// after the store refused one: until then directories read through. Zero
|
||||
// when no build was refused.
|
||||
storeRefusedUntil atomic.Int64
|
||||
|
||||
// rebuildWipeInserts holds the children inserted into each directory
|
||||
// while its rebuild wipe runs; the wipe keeps them.
|
||||
rebuildWipeInserts map[util.FullPath]map[string]struct{}
|
||||
@@ -136,6 +152,7 @@ func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPat
|
||||
root: root,
|
||||
localStore: virtualStore,
|
||||
leveldbStore: leveldbStore,
|
||||
batchStore: leveldbStore,
|
||||
markCachedFn: markCachedFn,
|
||||
isCachedFn: isCachedFn,
|
||||
uidGidMapper: uidGidMapper,
|
||||
@@ -204,7 +221,7 @@ func (mc *MetaCache) doInsertEntry(ctx context.Context, entry *filer.Entry, vers
|
||||
// This is more efficient than inserting entries one by one.
|
||||
|
||||
func (mc *MetaCache) doBatchInsertEntries(ctx context.Context, entries []*filer.Entry) error {
|
||||
return mc.leveldbStore.BatchInsertEntries(ctx, entries)
|
||||
return mc.batchStore.BatchInsertEntries(ctx, entries)
|
||||
}
|
||||
|
||||
func (mc *MetaCache) AtomicUpdateEntryFromFiler(ctx context.Context, oldPath util.FullPath, newEntry *filer.Entry) error {
|
||||
@@ -473,7 +490,7 @@ func (mc *MetaCache) FindEntry(ctx context.Context, fp util.FullPath) (entry *fi
|
||||
if unversioned {
|
||||
return entry, 0, nil
|
||||
}
|
||||
return entry, mc.entryVersionFloorLocked(fp, recordTsNs), nil
|
||||
return entry, mc.entryVersionFloorLocked(fp, max(recordTsNs, entry.CommitTsNs)), nil
|
||||
}
|
||||
|
||||
// entryVersionKeyPrefix namespaces per-entry version records apart from entry
|
||||
@@ -647,9 +664,15 @@ func (mc *MetaCache) entryVersionBlocksLocked(ctx context.Context, fp util.FullP
|
||||
// event can correct it.
|
||||
return false
|
||||
}
|
||||
if !tombstone && !mc.entryExistsLocked(ctx, fp) {
|
||||
entry, err := mc.localStore.FindEntry(ctx, fp)
|
||||
live := err == nil && entry != nil && !isTtlExpired(entry)
|
||||
if !tombstone && !live {
|
||||
recordTsNs = 0
|
||||
}
|
||||
// A live entry reflects its own commit, even under an older listing floor.
|
||||
if live && entry.CommitTsNs > recordTsNs {
|
||||
recordTsNs = entry.CommitTsNs
|
||||
}
|
||||
floorTsNs := mc.entryVersionFloorLocked(fp, recordTsNs)
|
||||
if removal && !tombstone {
|
||||
return floorTsNs > tsNs
|
||||
@@ -874,7 +897,7 @@ func (mc *MetaCache) deleteFolderChildrenBatch(ctx context.Context, dirPath util
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := mc.leveldbStore.BatchDeleteEntries(ctx, doomed); err != nil {
|
||||
if err := mc.batchStore.BatchDeleteEntries(ctx, doomed); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if visited < rebuildWipeBatchSize {
|
||||
@@ -906,6 +929,35 @@ func (mc *MetaCache) ListDirectoryEntries(ctx context.Context, dirPath util.Full
|
||||
})
|
||||
}
|
||||
|
||||
// LocalOnlyChildren returns, in name order, the children of dirPath that the
|
||||
// local store holds and a rebuild keeps (see SetPinnedChildFn): files this
|
||||
// mount created that are not on the filer yet. It covers the names after
|
||||
// startFileName and, unless stopFileName is empty, up to it. A listing read
|
||||
// through from the filer leaves them out; whether the directory is cached does
|
||||
// not matter.
|
||||
func (mc *MetaCache) LocalOnlyChildren(ctx context.Context, dirPath util.FullPath, startFileName, stopFileName string) ([]*filer.Entry, error) {
|
||||
if mc.pinnedChildFn == nil {
|
||||
return nil, nil
|
||||
}
|
||||
mc.RLock()
|
||||
defer mc.RUnlock()
|
||||
var children []*filer.Entry
|
||||
_, err := mc.localStore.ListDirectoryEntries(ctx, dirPath, startFileName, false, math.MaxInt64, func(entry *filer.Entry) (bool, error) {
|
||||
if stopFileName != "" && entry.Name() > stopFileName {
|
||||
return false, nil
|
||||
}
|
||||
if entry.TtlSec > 0 && entry.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now()) {
|
||||
return true, nil
|
||||
}
|
||||
if mc.pinnedChildFn(entry) {
|
||||
mc.mapIdFromFilerToLocal(entry)
|
||||
children = append(children, entry)
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
return children, err
|
||||
}
|
||||
|
||||
func (mc *MetaCache) markOversized(dirPath util.FullPath) {
|
||||
mc.Lock()
|
||||
defer mc.Unlock()
|
||||
@@ -1302,13 +1354,17 @@ func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *file
|
||||
mc.Lock()
|
||||
// Last-writer-wins per entry: an event at or below an entry's version is
|
||||
// already reflected in it, and applying it would roll the entry back while
|
||||
// the version keeps the newer claim. Each half is gated independently.
|
||||
// the version keeps the newer claim. Each half is gated independently,
|
||||
// except an in-place update: a reflected one must not remove its entry.
|
||||
if resp.TsNs != 0 {
|
||||
if oldPath != "" && mc.entryVersionBlocksLocked(ctx, oldPath, resp.TsNs, true) {
|
||||
oldPath = ""
|
||||
}
|
||||
if newEntry != nil {
|
||||
if mc.entryVersionBlocksLocked(ctx, newEntry.FullPath, resp.TsNs, false) {
|
||||
if oldPath == newEntry.FullPath {
|
||||
oldPath = ""
|
||||
}
|
||||
newEntry = nil
|
||||
} else if mc.hardLinkVersionFloorLocked(ctx, newEntry.HardLinkId) > resp.TsNs {
|
||||
// The group's shared content is newer than this event — the
|
||||
|
||||
@@ -957,3 +957,70 @@ func TestUnversionedWriteDoesNotInheritDirectoryFloor(t *testing.T) {
|
||||
}
|
||||
mc.WaitForEntryInvalidations()
|
||||
}
|
||||
|
||||
// A listing snapshot can trail the listed entries: a peer's held watermark
|
||||
// caps it below writes already in the store. A delayed older event must not
|
||||
// roll a listed entry back to the state it replaced.
|
||||
func TestBuildKeepsListedEntryNewerThanSnapshot(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
if err := mc.BeginDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
|
||||
t.Fatalf("begin build: %v", err)
|
||||
}
|
||||
if err := mc.doBatchInsertEntries(context.Background(), []*filer.Entry{{
|
||||
FullPath: "/dir/file",
|
||||
Attr: filer.Attr{
|
||||
Crtime: time.Unix(1, 0),
|
||||
Mtime: time.Unix(1, 0),
|
||||
Mode: 0100644,
|
||||
FileSize: 300,
|
||||
},
|
||||
CommitTsNs: 3000,
|
||||
}}); err != nil {
|
||||
t.Fatalf("batch insert: %v", err)
|
||||
}
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000, nil); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
// open handles compare invalidations against this version
|
||||
if _, versionTsNs, err := mc.FindEntry(context.Background(), util.FullPath("/dir/file")); err != nil || versionTsNs != 3000 {
|
||||
t.Fatalf("listed entry version = %d, %v; want its commit 3000", versionTsNs, err)
|
||||
}
|
||||
|
||||
apply := func(tsNs int64, oldEntry, newEntry *filer_pb.Entry) {
|
||||
t.Helper()
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
TsNs: tsNs,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: oldEntry,
|
||||
NewEntry: newEntry,
|
||||
NewParentPath: "/dir",
|
||||
},
|
||||
}
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply event at %d: %v", tsNs, err)
|
||||
}
|
||||
}
|
||||
wantSize := func(want uint64, why string) {
|
||||
t.Helper()
|
||||
entry, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/file"))
|
||||
if err != nil || entry.FileSize != want {
|
||||
t.Fatalf("entry = %+v, %v; want size %d (%s)", entry, err, want, why)
|
||||
}
|
||||
}
|
||||
|
||||
apply(2500, nil, &filer_pb.Entry{Name: "file", CommitTsNs: 2500, Attributes: &filer_pb.FuseAttributes{FileMode: 0100644}})
|
||||
wantSize(300, "the create below the listed commit is already reflected")
|
||||
apply(2500, &filer_pb.Entry{Name: "file"}, nil)
|
||||
wantSize(300, "a removal below the listed commit is already reflected")
|
||||
apply(3000, &filer_pb.Entry{Name: "file"}, &filer_pb.Entry{Name: "file", CommitTsNs: 3000, Attributes: &filer_pb.FuseAttributes{FileSize: 300, FileMode: 0100644}})
|
||||
wantSize(300, "the update that made the listed commit is already reflected")
|
||||
apply(3500, &filer_pb.Entry{Name: "file"}, &filer_pb.Entry{Name: "file", CommitTsNs: 3500, Attributes: &filer_pb.FuseAttributes{FileSize: 500, FileMode: 0100644}})
|
||||
wantSize(500, "a change past the listed commit applies")
|
||||
mc.WaitForEntryInvalidations()
|
||||
}
|
||||
@@ -24,6 +24,48 @@ func (e *DirectoryTooLargeError) Error() string {
|
||||
return fmt.Sprintf("directory %s is too large to cache locally", e.Path)
|
||||
}
|
||||
|
||||
// LocalStoreError reports a directory build the local store refused: a write
|
||||
// to the cache disk failed, typically because the disk is full. The directory
|
||||
// reads through to the filer, the way an oversized one does, until the store
|
||||
// takes writes again.
|
||||
type LocalStoreError struct {
|
||||
Path util.FullPath
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *LocalStoreError) Error() string {
|
||||
return fmt.Sprintf("local store cannot cache directory %s: %v", e.Path, e.Err)
|
||||
}
|
||||
|
||||
func (e *LocalStoreError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// storeRefusalBackoff is how long directories read through after the store
|
||||
// refused a build before a build is tried again. A build on a full disk lists
|
||||
// the directory from the filer only to fail at its first write.
|
||||
var storeRefusalBackoff = 10 * time.Second
|
||||
|
||||
var errStoreRefusing = errors.New("it refused a write moments ago")
|
||||
|
||||
// noteStoreRefusal starts the backoff after a build the store refused. It logs
|
||||
// once per backoff, not once per listing.
|
||||
func (mc *MetaCache) noteStoreRefusal(path util.FullPath, err error) {
|
||||
now := time.Now()
|
||||
if previous := mc.storeRefusedUntil.Swap(now.Add(storeRefusalBackoff).UnixNano()); previous <= now.UnixNano() {
|
||||
glog.Warningf("local store cannot cache %s, listing directories from the filer for %v: %v", path, storeRefusalBackoff, err)
|
||||
}
|
||||
}
|
||||
|
||||
// storeRefusal is errStoreRefusing while the backoff after a refused build
|
||||
// lasts, nil otherwise.
|
||||
func (mc *MetaCache) storeRefusal() error {
|
||||
if time.Now().UnixNano() < mc.storeRefusedUntil.Load() {
|
||||
return errStoreRefusing
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// maxCacheableEntries is the directory size above which a build gives up, or 0
|
||||
// to cache everything.
|
||||
func EnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClient, dirPath util.FullPath, maxCacheableEntries int) error {
|
||||
@@ -59,6 +101,11 @@ func EnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClie
|
||||
return nil
|
||||
}
|
||||
|
||||
// A build the store refused moments ago would be refused again.
|
||||
if err := mc.storeRefusal(); err != nil {
|
||||
return &LocalStoreError{Path: dirPath, Err: err}
|
||||
}
|
||||
|
||||
// Fetch all uncached directories in parallel with context for cancellation
|
||||
// If one fetch fails, cancel the others to avoid unnecessary work
|
||||
g, ctx := errgroup.WithContext(ctx)
|
||||
@@ -161,7 +208,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
sections = sectionBoundsCollector{}
|
||||
var batch []*filer.Entry // reset on retry, allow GC of previous entries
|
||||
if err := mc.deleteFolderChildrenForRebuild(buildCtx, path); err != nil {
|
||||
return fmt.Errorf("clear existing entries for %s: %w", path, err)
|
||||
return &LocalStoreError{Path: path, Err: fmt.Errorf("clear existing entries: %w", err)}
|
||||
}
|
||||
var listErr error
|
||||
snapshotTsNs, listErr = filer_pb.ReadDirAllEntriesWithSnapshot(buildCtx, client, path, "", func(pbEntry *filer_pb.Entry, isLast bool) error {
|
||||
@@ -180,7 +227,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
// flush by size, not isLast: hidden entries can return early
|
||||
if len(batch) >= batchInsertSize {
|
||||
if err := mc.doBatchInsertEntries(buildCtx, batch); err != nil {
|
||||
return fmt.Errorf("batch insert for %s: %w", path, err)
|
||||
return &LocalStoreError{Path: path, Err: fmt.Errorf("batch insert: %w", err)}
|
||||
}
|
||||
batch = make([]*filer.Entry, 0, batchInsertSize)
|
||||
}
|
||||
@@ -191,7 +238,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
}
|
||||
if len(batch) > 0 {
|
||||
if err := mc.doBatchInsertEntries(buildCtx, batch); err != nil {
|
||||
return fmt.Errorf("batch insert remaining for %s: %w", path, err)
|
||||
return &LocalStoreError{Path: path, Err: fmt.Errorf("batch insert remaining: %w", err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -199,8 +246,18 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
return entryCount, snapshotTsNs, sections, err
|
||||
}
|
||||
|
||||
// noteIfRefused starts the store backoff when a build failed on the
|
||||
// store rather than on the filer.
|
||||
noteIfRefused := func(err error) {
|
||||
var refused *LocalStoreError
|
||||
if errors.As(err, &refused) {
|
||||
mc.noteStoreRefusal(path, refused.Err)
|
||||
}
|
||||
}
|
||||
|
||||
entryCount, snapshotTsNs, sections, fetchErr := reloadFromFiler()
|
||||
if fetchErr != nil {
|
||||
noteIfRefused(fetchErr)
|
||||
var tooLarge *DirectoryTooLargeError
|
||||
if errors.As(fetchErr, &tooLarge) {
|
||||
// Remember the refusal so the next visit fails fast instead of
|
||||
@@ -230,6 +287,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
}
|
||||
}
|
||||
if entryCount, snapshotTsNs, sections, fetchErr = reloadFromFiler(); fetchErr != nil {
|
||||
noteIfRefused(fetchErr)
|
||||
cleanupBuild("failed")
|
||||
return nil, fmt.Errorf("confirm empty list %s: %w", path, fetchErr)
|
||||
}
|
||||
@@ -240,6 +298,12 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), path, snapshotTsNs, sections.bounds); err != nil {
|
||||
cleanupBuild("unreplayed")
|
||||
if !errors.Is(err, ErrClosed) && !errors.Is(err, ErrDirectoryBuildDiscarded) {
|
||||
// Otherwise completing fails only on writing the events
|
||||
// buffered during the listing to the store.
|
||||
err = &LocalStoreError{Path: path, Err: fmt.Errorf("replay buffered events: %w", err)}
|
||||
noteIfRefused(err)
|
||||
}
|
||||
return nil, fmt.Errorf("complete build for %s: %w", path, err)
|
||||
}
|
||||
cleanupDone = true // Prevent deferred cleanup after successful publish
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
package meta_cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// fullDiskBatchStore fails a build's batched writes while full is set, the
|
||||
// way the leveldb store does once the cache disk has no space left. Like the
|
||||
// store, it writes nothing, and so cannot fail, for an empty batch.
|
||||
type fullDiskBatchStore struct {
|
||||
metaBatchStore
|
||||
full atomic.Bool
|
||||
}
|
||||
|
||||
func (s *fullDiskBatchStore) BatchInsertEntries(ctx context.Context, entries []*filer.Entry) error {
|
||||
if s.full.Load() && len(entries) > 0 {
|
||||
return errCacheDiskFull
|
||||
}
|
||||
return s.metaBatchStore.BatchInsertEntries(ctx, entries)
|
||||
}
|
||||
|
||||
func (s *fullDiskBatchStore) BatchDeleteEntries(ctx context.Context, paths []util.FullPath) error {
|
||||
if s.full.Load() && len(paths) > 0 {
|
||||
return errCacheDiskFull
|
||||
}
|
||||
return s.metaBatchStore.BatchDeleteEntries(ctx, paths)
|
||||
}
|
||||
|
||||
// countingListClient counts the listings a build asks the filer for.
|
||||
type countingListClient struct {
|
||||
buildListClient
|
||||
lists atomic.Int32
|
||||
}
|
||||
|
||||
func (c *countingListClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
|
||||
c.lists.Add(1)
|
||||
return c.buildListClient.ListEntries(ctx, in, opts...)
|
||||
}
|
||||
|
||||
func shortStoreRefusalBackoff(t *testing.T, d time.Duration) {
|
||||
t.Helper()
|
||||
saved := storeRefusalBackoff
|
||||
storeRefusalBackoff = d
|
||||
t.Cleanup(func() { storeRefusalBackoff = saved })
|
||||
}
|
||||
|
||||
func countChildren(t *testing.T, mc *MetaCache, dir util.FullPath) int {
|
||||
t.Helper()
|
||||
count := 0
|
||||
if _, err := mc.ListDirectoryEntries(context.Background(), dir, "", false, 1000, func(*filer.Entry) (bool, error) {
|
||||
count++
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
t.Fatalf("list %s: %v", dir, err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// A build on a full cache disk used to fail the listing with EIO. It now
|
||||
// reports a LocalStoreError, which ReadDir answers from the filer; the next
|
||||
// builds wait out a backoff instead of re-listing the directory only to fail
|
||||
// at the first insert again; and once the disk has room the directory caches.
|
||||
func TestEnsureVisitedOnAFullDiskReportsLocalStoreErrorAndBacksOff(t *testing.T) {
|
||||
shortStoreRefusalBackoff(t, 200*time.Millisecond)
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
|
||||
defer mc.Shutdown()
|
||||
store := &fullDiskBatchStore{metaBatchStore: mc.batchStore}
|
||||
mc.batchStore = store
|
||||
store.full.Store(true)
|
||||
|
||||
client := &countingListClient{buildListClient: buildListClient{responses: listResponses(3)}}
|
||||
accessor := &buildFilerAccessor{client: client}
|
||||
|
||||
err := EnsureVisited(context.Background(), mc, accessor, "/d", 0)
|
||||
var refused *LocalStoreError
|
||||
if !errors.As(err, &refused) {
|
||||
t.Fatalf("EnsureVisited on a full disk = %v, want a LocalStoreError", err)
|
||||
}
|
||||
if refused.Path != "/d" || !errors.Is(err, errCacheDiskFull) {
|
||||
t.Errorf("refusal = %v, want /d refused with the store's error", err)
|
||||
}
|
||||
if mc.IsDirectoryCached("/d") {
|
||||
t.Error("a directory the store refused is reported cached")
|
||||
}
|
||||
lists := client.lists.Load()
|
||||
|
||||
// Within the backoff no build is tried: not for this directory, not for
|
||||
// another one, and the filer is not asked to list either.
|
||||
for _, dir := range []util.FullPath{"/d", "/e"} {
|
||||
if err := EnsureVisited(context.Background(), mc, accessor, dir, 0); !errors.As(err, &refused) || refused.Path != dir {
|
||||
t.Fatalf("EnsureVisited(%s) within the backoff = %v, want a LocalStoreError for it", dir, err)
|
||||
}
|
||||
}
|
||||
if got := client.lists.Load(); got != lists {
|
||||
t.Errorf("the filer was asked for %d more listings within the backoff, want none", got-lists)
|
||||
}
|
||||
|
||||
// The disk has room again: after the backoff the directory caches.
|
||||
store.full.Store(false)
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
if err := EnsureVisited(context.Background(), mc, accessor, "/d", 0); err != nil {
|
||||
t.Fatalf("EnsureVisited after the backoff = %v", err)
|
||||
}
|
||||
if !mc.IsDirectoryCached("/d") {
|
||||
t.Fatal("directory not cached once the store took writes again")
|
||||
}
|
||||
if n := countChildren(t, mc, "/d"); n != 3 {
|
||||
t.Errorf("cached %d children, want 3", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A rebuild that cannot wipe the children it is replacing fails on the store
|
||||
// too, not on the filer.
|
||||
func TestEnsureVisitedRebuildThatCannotWipeReportsLocalStoreError(t *testing.T) {
|
||||
shortStoreRefusalBackoff(t, time.Minute)
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
|
||||
defer mc.Shutdown()
|
||||
ctx := context.Background()
|
||||
for _, name := range []string{"old1", "old2"} {
|
||||
if err := mc.InsertEntry(ctx, &filer.Entry{FullPath: util.FullPath("/d").Child(name), Attr: filer.Attr{Mode: 0o644}}, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
store := &fullDiskBatchStore{metaBatchStore: mc.batchStore}
|
||||
mc.batchStore = store
|
||||
store.full.Store(true)
|
||||
|
||||
accessor := &buildFilerAccessor{client: &buildListClient{responses: listResponses(3)}}
|
||||
err := EnsureVisited(ctx, mc, accessor, "/d", 0)
|
||||
var refused *LocalStoreError
|
||||
if !errors.As(err, &refused) {
|
||||
t.Fatalf("EnsureVisited = %v, want a LocalStoreError", err)
|
||||
}
|
||||
if mc.IsDirectoryCached("/d") {
|
||||
t.Error("a directory the store refused is reported cached")
|
||||
}
|
||||
}
|
||||
|
||||
// The listing fits, but the store refuses the event buffered during it when
|
||||
// the build completes. That is the store too.
|
||||
func TestEnsureVisitedRefusedReplayReportsLocalStoreError(t *testing.T) {
|
||||
shortStoreRefusalBackoff(t, time.Minute)
|
||||
mc, store, _, _ := newFullDiskMetaCache(t, "/")
|
||||
defer mc.Shutdown()
|
||||
|
||||
var applyErr error
|
||||
accessor := &buildFilerAccessor{client: &buildListClient{
|
||||
responses: listResponses(2),
|
||||
onFirstRecv: func() {
|
||||
// A peer creates a file while the listing streams: the event is
|
||||
// buffered for the build, and the disk fills before it completes.
|
||||
store.full.Store(true)
|
||||
applyErr = mc.ApplyMetadataResponse(context.Background(), &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/d",
|
||||
TsNs: time.Now().Add(time.Hour).UnixNano(),
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: fileEntry("late.txt", 2),
|
||||
NewParentPath: "/d",
|
||||
},
|
||||
}, SubscriberMetadataResponseApplyOptions)
|
||||
},
|
||||
}}
|
||||
|
||||
err := EnsureVisited(context.Background(), mc, accessor, "/d", 0)
|
||||
if applyErr != nil {
|
||||
t.Fatalf("buffering the event: %v", applyErr)
|
||||
}
|
||||
var refused *LocalStoreError
|
||||
if !errors.As(err, &refused) {
|
||||
t.Fatalf("EnsureVisited = %v, want a LocalStoreError", err)
|
||||
}
|
||||
if mc.IsDirectoryCached("/d") {
|
||||
t.Error("a directory whose replay the store refused is reported cached")
|
||||
}
|
||||
if mc.storeRefusal() == nil {
|
||||
t.Error("a refused replay did not start the backoff")
|
||||
}
|
||||
}
|
||||
|
||||
// A listing the filer fails is not the store's doing: no backoff.
|
||||
func TestEnsureVisitedFilerFailureStartsNoStoreBackoff(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
|
||||
defer mc.Shutdown()
|
||||
|
||||
accessor := &buildFilerAccessor{client: failingListClient{err: errors.New("filer exploded")}}
|
||||
err := EnsureVisited(context.Background(), mc, accessor, "/d", 0)
|
||||
if err == nil {
|
||||
t.Fatal("EnsureVisited with a failing filer = nil")
|
||||
}
|
||||
var refused *LocalStoreError
|
||||
if errors.As(err, &refused) {
|
||||
t.Fatalf("a filer failure was reported as the store's: %v", err)
|
||||
}
|
||||
if mc.storeRefusal() != nil {
|
||||
t.Error("a filer failure started the store backoff")
|
||||
}
|
||||
}
|
||||
|
||||
type failingListClient struct {
|
||||
filer_pb.SeaweedFilerClient
|
||||
err error
|
||||
}
|
||||
|
||||
func (c failingListClient) ListEntries(context.Context, *filer_pb.ListEntriesRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
|
||||
return nil, c.err
|
||||
}
|
||||
|
||||
// A build discarded by a distrust is listed again. That is not the store's
|
||||
// doing: it starts no backoff.
|
||||
func TestEnsureVisitedDiscardedBuildStartsNoStoreBackoff(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
|
||||
defer mc.Shutdown()
|
||||
|
||||
var discardOnce sync.Once
|
||||
accessor := &buildFilerAccessor{client: &buildListClient{
|
||||
responses: listResponses(2),
|
||||
onFirstRecv: func() {
|
||||
discardOnce.Do(func() { mc.DiscardDirectoryBuilds(func() {}) })
|
||||
},
|
||||
}}
|
||||
if err := EnsureVisited(context.Background(), mc, accessor, "/d", 0); err != nil {
|
||||
t.Fatalf("EnsureVisited = %v", err)
|
||||
}
|
||||
if !mc.IsDirectoryCached("/d") {
|
||||
t.Error("directory not cached once its discarded build was listed again")
|
||||
}
|
||||
if mc.storeRefusal() != nil {
|
||||
t.Error("a discarded build started the store backoff")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package page_writer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
@@ -211,13 +212,35 @@ func (sc *SwapFileChunk) SaveContent(saveFn SaveToStorageFunc) {
|
||||
}
|
||||
|
||||
data := mem.Allocate(int(stopOffset - startOffset))
|
||||
n, _ := sc.swapfile.file.ReadAt(data, startOffset+int64(sc.actualChunkIndex)*sc.swapfile.chunkSize)
|
||||
if n > 0 {
|
||||
reader := util.NewBytesReader(data[:n])
|
||||
saveFn(reader, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(n), tsNs, func() {
|
||||
n, err := sc.swapfile.file.ReadAt(data, startOffset+int64(sc.actualChunkIndex)*sc.swapfile.chunkSize)
|
||||
if n < len(data) {
|
||||
// The bytes were acknowledged to the writer, so uploading less than
|
||||
// the interval or skipping it would publish a hole. Hand the upload a
|
||||
// reader that fails, which records the failure on the handle like a
|
||||
// failed chunk upload, and stop: the handle cannot flush cleanly.
|
||||
if err == nil || err == io.EOF {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
err = fmt.Errorf("read swap file in %s [%d,%d) of chunk %d: %w", sc.swapfile.dir, startOffset, stopOffset, sc.logicChunkIndex, err)
|
||||
glog.Errorf("%v", err)
|
||||
saveFn(&failedReader{err: err}, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(len(data)), tsNs, func() {
|
||||
})
|
||||
mem.Free(data)
|
||||
return
|
||||
}
|
||||
reader := util.NewBytesReader(data)
|
||||
saveFn(reader, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(len(data)), tsNs, func() {
|
||||
})
|
||||
mem.Free(data)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// failedReader fails every read with err.
|
||||
type failedReader struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *failedReader) Read([]byte) (int, error) {
|
||||
return 0, r.err
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
package page_writer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// When the swap file cannot be created, SaveDataAt must fail the write
|
||||
@@ -54,3 +60,114 @@ func TestSaveDataAtReportsFailedSwapWrite(t *testing.T) {
|
||||
t.Fatalf("write through a closed swap file = %d, %v; want 0 and an error", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
// swapReadBackProbe collects what the pipeline hands to its uploader and the
|
||||
// errors the uploader meets reading it, the way a chunk upload does.
|
||||
type swapReadBackProbe struct {
|
||||
mu sync.Mutex
|
||||
uploaded map[int64][]byte
|
||||
errs []error
|
||||
}
|
||||
|
||||
func (p *swapReadBackProbe) save(reader io.Reader, offset int64, size int64, modifiedTsNs int64, cleanupFn func()) {
|
||||
defer cleanupFn()
|
||||
body, err := io.ReadAll(reader)
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if err != nil {
|
||||
p.errs = append(p.errs, err)
|
||||
return
|
||||
}
|
||||
if p.uploaded == nil {
|
||||
p.uploaded = make(map[int64][]byte)
|
||||
}
|
||||
p.uploaded[offset] = body
|
||||
}
|
||||
|
||||
// Dirty pages in the swap file were acknowledged to the writer. When they
|
||||
// cannot be read back at upload time the interval must fail the upload, not
|
||||
// go out short or be skipped, and the chunk must still release its budget.
|
||||
func TestSwapChunkReadBackFailureFailsTheUpload(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
breakF func(t *testing.T, f *os.File)
|
||||
}{
|
||||
{"closed swap file", func(t *testing.T, f *os.File) {
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{"truncated swap file", func(t *testing.T, f *os.File) {
|
||||
if err := f.Truncate(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
probe := &swapReadBackProbe{}
|
||||
accountant := NewWriteBufferAccountant(1 << 20)
|
||||
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, probe.save, 16, t.TempDir(), accountant)
|
||||
defer up.Shutdown()
|
||||
// Not sequential: the chunk goes to the swap file.
|
||||
if n, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil || n != 4 {
|
||||
t.Fatalf("write = %d, %v", n, err)
|
||||
}
|
||||
tc.breakF(t, up.swapFile.file)
|
||||
up.FlushAll()
|
||||
|
||||
probe.mu.Lock()
|
||||
defer probe.mu.Unlock()
|
||||
if len(probe.uploaded) != 0 {
|
||||
t.Errorf("uploaded %v from a swap file that cannot be read", probe.uploaded)
|
||||
}
|
||||
if len(probe.errs) != 1 {
|
||||
t.Fatalf("upload read errors = %v, want exactly one", probe.errs)
|
||||
}
|
||||
t.Logf("upload error: %v", probe.errs[0])
|
||||
waitForBudgetRelease(t, accountant)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A swap file cut short fails only the intervals it no longer holds, and the
|
||||
// upload of the first failed interval ends the chunk's save: the handle cannot
|
||||
// flush cleanly anyway.
|
||||
func TestSwapChunkReadBackFailureKeepsReadableIntervals(t *testing.T) {
|
||||
probe := &swapReadBackProbe{}
|
||||
accountant := NewWriteBufferAccountant(1 << 20)
|
||||
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, probe.save, 16, t.TempDir(), accountant)
|
||||
defer up.Shutdown()
|
||||
if _, err := up.SaveDataAt([]byte("head"), 0, false, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := up.SaveDataAt([]byte("tail"), 600, false, 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The chunk is slot 1 of the swap file: [1024, 2048). Cut it inside the
|
||||
// second interval.
|
||||
if err := up.swapFile.file.Truncate(1024 + 602); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
up.FlushAll()
|
||||
|
||||
probe.mu.Lock()
|
||||
defer probe.mu.Unlock()
|
||||
if string(probe.uploaded[0]) != "head" || len(probe.uploaded) != 1 {
|
||||
t.Errorf("uploaded %v, want only the first interval", probe.uploaded)
|
||||
}
|
||||
if len(probe.errs) != 1 || !errors.Is(probe.errs[0], io.ErrUnexpectedEOF) {
|
||||
t.Errorf("upload read errors = %v, want one unexpected EOF", probe.errs)
|
||||
}
|
||||
waitForBudgetRelease(t, accountant)
|
||||
}
|
||||
|
||||
func waitForBudgetRelease(t *testing.T, accountant *WriteBufferAccountant) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for accountant.Used() != 0 {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("write budget still holds %d bytes after the failed upload", accountant.Used())
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"golang.org/x/sync/semaphore"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
@@ -164,6 +165,9 @@ type Option struct {
|
||||
|
||||
type WFS struct {
|
||||
readAuth *ReadAuth
|
||||
// chunkProofs keeps the assignment proofs of uploaded chunks until their
|
||||
// entries are stored; nil without a filer token, which gets none.
|
||||
chunkProofs *chunkProofs
|
||||
// Metadata-only refusal token, detached at final Forget; no live resources retained.
|
||||
writebackContentErrors sync.Map
|
||||
// https://dl.acm.org/doi/fullHtml/10.1145/3310148
|
||||
@@ -266,6 +270,11 @@ type WFS struct {
|
||||
// lockClient is the DLM client for cross-mount write coordination.
|
||||
// Non-nil only when EnableDistributedLock is true.
|
||||
lockClient *cluster.LockClient
|
||||
|
||||
// storeRefusedListings bounds the listings read through while the local
|
||||
// store refuses writes; see readDirectoryDirectStoreRefused.
|
||||
storeRefusedListings *semaphore.Weighted
|
||||
storeRefusedListingsOnce sync.Once
|
||||
}
|
||||
|
||||
const defaultDirIdleEvict = 10 * time.Minute
|
||||
@@ -324,6 +333,10 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
dirIdleEvict: dirIdleEvict,
|
||||
}
|
||||
|
||||
if option.FilerTokenSource != nil {
|
||||
wfs.chunkProofs = newChunkProofs(chunkProofLimit)
|
||||
}
|
||||
|
||||
// With writeback caching, this mount is the single writer. Increase kernel
|
||||
// FUSE cache TTLs so the kernel doesn't re-issue Lookup/GetAttr for every
|
||||
// path component and stat — the local meta cache is authoritative.
|
||||
|
||||
+113
-17
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"golang.org/x/sync/semaphore"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
@@ -305,6 +306,10 @@ func (wfs *WFS) doReadDirectory(ctx context.Context, input *fuse.ReadIn, out Dir
|
||||
if errors.As(err, &tooLarge) {
|
||||
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
var refused *meta_cache.LocalStoreError
|
||||
if errors.As(err, &refused) {
|
||||
return wfs.readDirectoryDirectStoreRefused(ctx, input, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
return dirReadStatus(ctx, err, "dir ReadDirAll %s: %v", dirPath, err)
|
||||
}
|
||||
|
||||
@@ -354,13 +359,22 @@ func (wfs *WFS) doReadDirectory(ctx context.Context, input *fuse.ReadIn, out Dir
|
||||
}
|
||||
}
|
||||
|
||||
// A hand-over to the direct path below keeps the pagination state on
|
||||
// dh, so it carries on from wherever the cached walk reached -- within
|
||||
// this request too: the entries the walk just put in the reply are not
|
||||
// to be sent again.
|
||||
resumed := *input
|
||||
resumed.Offset = dh.entryStreamOffset + uint64(entryCurrentIndex)
|
||||
|
||||
// Cache exhausted, load next batch
|
||||
if err := wfs.ensureDirectoryVisited(ctx, dirPath); err != nil {
|
||||
var tooLarge *meta_cache.DirectoryTooLargeError
|
||||
if errors.As(err, &tooLarge) {
|
||||
// The direct path keeps the same pagination state on dh, so it
|
||||
// carries on from wherever the cached walk reached.
|
||||
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
|
||||
return wfs.readDirectoryDirect(ctx, &resumed, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
var refused *meta_cache.LocalStoreError
|
||||
if errors.As(err, &refused) {
|
||||
return wfs.readDirectoryDirectStoreRefused(ctx, &resumed, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
return dirReadStatus(ctx, err, "dir ReadDirAll %s: %v", dirPath, err)
|
||||
}
|
||||
@@ -378,7 +392,7 @@ func (wfs *WFS) doReadDirectory(ctx context.Context, input *fuse.ReadIn, out Dir
|
||||
if errors.Is(err, meta_cache.ErrRefreshRangeTooLarge) {
|
||||
// re-tile with a full rebuild; serve this request direct
|
||||
wfs.purgeDirectoryCache(dirPath)
|
||||
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
|
||||
return wfs.readDirectoryDirect(ctx, &resumed, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
glog.V(1).Infof("refresh %s sections: %v", dirPath, err)
|
||||
}
|
||||
@@ -430,7 +444,9 @@ func dirReadStatus(ctx context.Context, err error, format string, args ...any) f
|
||||
|
||||
// ensureDirectoryVisited pulls the directory into the local cache, unless it is
|
||||
// too large to cache: then the directory is marked read-through, so later
|
||||
// listings go straight to the filer without re-asking.
|
||||
// listings go straight to the filer without re-asking. A directory the local
|
||||
// store refused (cache disk full) is not marked: the store's own backoff
|
||||
// decides when a listing tries to cache again.
|
||||
func (wfs *WFS) ensureDirectoryVisited(ctx context.Context, dirPath util.FullPath) error {
|
||||
err := meta_cache.EnsureVisited(ctx, wfs.metaCache, wfs, dirPath, wfs.option.CacheDirMaxEntries)
|
||||
var tooLarge *meta_cache.DirectoryTooLargeError
|
||||
@@ -440,6 +456,31 @@ func (wfs *WFS) ensureDirectoryVisited(ctx context.Context, dirPath util.FullPat
|
||||
return err
|
||||
}
|
||||
|
||||
// storeRefusedListingLimit caps the directory listings one mount reads through
|
||||
// at once while its local store refuses writes. Every listing of the mount
|
||||
// then goes to the filer instead of the cache; the cap spreads a burst out
|
||||
// rather than sending it all at once.
|
||||
const storeRefusedListingLimit = 4
|
||||
|
||||
// readDirectoryDirectStoreRefused serves a listing from the filer because the
|
||||
// local store could not cache the directory, at most storeRefusedListingLimit
|
||||
// of them at a time per mount.
|
||||
func (wfs *WFS) readDirectoryDirectStoreRefused(ctx context.Context, input *fuse.ReadIn, out DirEntrySink, dh *DirectoryHandle, dirPath util.FullPath, processEachEntryFn func(entry *filer.Entry, index int64) bool) fuse.Status {
|
||||
slots := wfs.storeRefusedListingSlots()
|
||||
if err := slots.Acquire(ctx, 1); err != nil {
|
||||
return fuse.EINTR
|
||||
}
|
||||
defer slots.Release(1)
|
||||
return wfs.readDirectoryDirect(ctx, input, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
|
||||
func (wfs *WFS) storeRefusedListingSlots() *semaphore.Weighted {
|
||||
wfs.storeRefusedListingsOnce.Do(func() {
|
||||
wfs.storeRefusedListings = semaphore.NewWeighted(storeRefusedListingLimit)
|
||||
})
|
||||
return wfs.storeRefusedListings
|
||||
}
|
||||
|
||||
func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out DirEntrySink, dh *DirectoryHandle, dirPath util.FullPath, processEachEntryFn func(entry *filer.Entry, index int64) bool) fuse.Status {
|
||||
listingCtx := filer_pb.WithChunksOmitted(ctx)
|
||||
var lastEntryName string
|
||||
@@ -447,11 +488,11 @@ func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out
|
||||
if input.Offset >= dh.entryStreamOffset {
|
||||
if len(dh.entryStream) == 0 && input.Offset > dh.entryStreamOffset {
|
||||
skipCount := uint32(input.Offset-dh.entryStreamOffset) + batchSize
|
||||
entries, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
|
||||
entries, listed, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, "", false, skipCount, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
|
||||
if err != nil {
|
||||
return dirReadStatus(ctx, err, "list filer directory: %v", err)
|
||||
}
|
||||
dh.entryStream = append(dh.entryStream, entries...)
|
||||
dh.entryStream = append(dh.entryStream, wfs.withLocalOnly(listingCtx, dirPath, entries, "", listed < int(skipCount))...)
|
||||
if dh.snapshotTsNs == 0 {
|
||||
dh.snapshotTsNs = snapshotTs
|
||||
}
|
||||
@@ -480,24 +521,31 @@ func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out
|
||||
}
|
||||
}
|
||||
|
||||
entries, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
|
||||
entries, listed, snapshotTs, err := loadDirectoryEntriesDirect(listingCtx, wfs, wfs.option.UidGidMapper, dirPath, lastEntryName, false, batchSize, dh.snapshotTsNs, wfs.option.IncludeSystemEntries)
|
||||
if err != nil {
|
||||
return dirReadStatus(ctx, err, "list filer directory: %v", err)
|
||||
}
|
||||
if dh.snapshotTsNs == 0 {
|
||||
dh.snapshotTsNs = snapshotTs
|
||||
}
|
||||
// Only a short page from the filer ends the directory: the hidden
|
||||
// system entries the loader leaves out shorten a full one.
|
||||
lastPage := listed < int(batchSize)
|
||||
entries = wfs.withLocalOnly(listingCtx, dirPath, entries, lastEntryName, lastPage)
|
||||
|
||||
// The whole page goes on the handle, and the next requests take what
|
||||
// this reply has no room for from there, as from the cache, rather
|
||||
// than listing the filer again and merging the unflushed creates again
|
||||
// for every reply.
|
||||
bufferFull := false
|
||||
for _, entry := range entries {
|
||||
currentIndex := int64(len(dh.entryStream))
|
||||
dh.entryStream = append(dh.entryStream, entry)
|
||||
if !processEachEntryFn(entry, currentIndex) {
|
||||
if !bufferFull && !processEachEntryFn(entry, currentIndex) {
|
||||
bufferFull = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !bufferFull && len(entries) < int(batchSize) {
|
||||
if !bufferFull && lastPage {
|
||||
dh.isFinished = true
|
||||
// After a full successful read-through listing, exit direct mode
|
||||
// so subsequent reads can use the cache instead of hitting the filer.
|
||||
@@ -508,7 +556,53 @@ func (wfs *WFS) readDirectoryDirect(ctx context.Context, input *fuse.ReadIn, out
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient, uidGidMapper *meta_cache.UidGidMapper, dirPath util.FullPath, startFileName string, includeStart bool, limit uint32, snapshotTsNs int64, includeSystemEntries bool) ([]*filer.Entry, int64, error) {
|
||||
// withLocalOnly merges into a page listed from the filer the children this
|
||||
// mount holds that are not on the filer yet (MetaCache.LocalOnlyChildren),
|
||||
// such as a file created and not flushed, so a listing read through shows them
|
||||
// as a cached one does. It takes those named after `after` and up to the
|
||||
// page's last name, or every one past `after` on the directory's last page;
|
||||
// later ones come with later pages. The page stays in name order, and a name
|
||||
// the filer has by now is listed once, as the filer has it.
|
||||
func (wfs *WFS) withLocalOnly(ctx context.Context, dirPath util.FullPath, page []*filer.Entry, after string, lastPage bool) []*filer.Entry {
|
||||
upTo := ""
|
||||
if !lastPage {
|
||||
if len(page) == 0 {
|
||||
return page
|
||||
}
|
||||
upTo = page[len(page)-1].Name()
|
||||
}
|
||||
local, err := wfs.metaCache.LocalOnlyChildren(ctx, dirPath, after, upTo)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("list unflushed children of %s: %v", dirPath, err)
|
||||
return page
|
||||
}
|
||||
if len(local) == 0 {
|
||||
return page
|
||||
}
|
||||
merged := make([]*filer.Entry, 0, len(page)+len(local))
|
||||
i, j := 0, 0
|
||||
for i < len(page) && j < len(local) {
|
||||
switch a, b := page[i].Name(), local[j].Name(); {
|
||||
case a < b:
|
||||
merged = append(merged, page[i])
|
||||
i++
|
||||
case b < a:
|
||||
merged = append(merged, local[j])
|
||||
j++
|
||||
default:
|
||||
merged = append(merged, page[i])
|
||||
i++
|
||||
j++
|
||||
}
|
||||
}
|
||||
merged = append(merged, page[i:]...)
|
||||
return append(merged, local[j:]...)
|
||||
}
|
||||
|
||||
// loadDirectoryEntriesDirect lists up to limit entries from the filer. listed
|
||||
// counts every entry the filer sent, the hidden system entries left out of
|
||||
// entries included, so a caller can tell a full page from the last one.
|
||||
func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient, uidGidMapper *meta_cache.UidGidMapper, dirPath util.FullPath, startFileName string, includeStart bool, limit uint32, snapshotTsNs int64, includeSystemEntries bool) (entries []*filer.Entry, listed int, actualSnapshotTsNs int64, err error) {
|
||||
// limit can be a client-supplied resume offset rather than a batch size, so
|
||||
// preallocating for it would size the slice from where the caller happened to
|
||||
// seek. Reserve a batch and let append find the rest.
|
||||
@@ -516,11 +610,13 @@ func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient
|
||||
if prealloc > batchSize {
|
||||
prealloc = batchSize
|
||||
}
|
||||
entries := make([]*filer.Entry, 0, prealloc)
|
||||
var actualSnapshotTsNs int64
|
||||
err := client.WithFilerClient(false, func(sc filer_pb.SeaweedFilerClient) error {
|
||||
entries = make([]*filer.Entry, 0, prealloc)
|
||||
err = client.WithFilerClient(false, func(sc filer_pb.SeaweedFilerClient) error {
|
||||
// reset in case a failover retry re-runs a partly streamed page
|
||||
entries, listed = entries[:0], 0
|
||||
var innerErr error
|
||||
actualSnapshotTsNs, innerErr = filer_pb.DoSeaweedListWithSnapshot(ctx, sc, dirPath, "", func(entry *filer_pb.Entry, isLast bool) error {
|
||||
listed++
|
||||
if !includeSystemEntries && meta_cache.IsHiddenSystemEntry(string(dirPath), entry.Name) {
|
||||
return nil
|
||||
}
|
||||
@@ -533,7 +629,7 @@ func loadDirectoryEntriesDirect(ctx context.Context, client filer_pb.FilerClient
|
||||
return innerErr
|
||||
})
|
||||
if err != nil {
|
||||
return nil, actualSnapshotTsNs, err
|
||||
return nil, 0, actualSnapshotTsNs, err
|
||||
}
|
||||
return entries, actualSnapshotTsNs, nil
|
||||
return entries, listed, actualSnapshotTsNs, nil
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -357,3 +360,304 @@ func TestReadDirPlusSanitizedName(t *testing.T) {
|
||||
t.Errorf("%s keyed on the unsanitized name", dir.Child(rawName))
|
||||
}
|
||||
}
|
||||
|
||||
// A listing that began from the cache hands over to the filer when the
|
||||
// directory stops being cacheable partway: here its cached listing is dropped
|
||||
// and the rebuild finds it too large. The hand-over resumed the direct walk at
|
||||
// the request's offset, so the entries the cached walk had just put in the same
|
||||
// reply were sent again and the client saw names twice. A full cache disk
|
||||
// takes the same hand-over on every request.
|
||||
func TestReadDirHandOverToTheFilerMidWalkSendsEachNameOnce(t *testing.T) {
|
||||
dir := util.FullPath("/d")
|
||||
const total = 2500
|
||||
var names []string
|
||||
for i := 0; i < total; i++ {
|
||||
names = append(names, fmt.Sprintf("f%05d", i))
|
||||
}
|
||||
// The cache holds the first 1500 names, the filer all of them: a walk
|
||||
// that lists every name finished from the filer.
|
||||
wfs := newPagingWFS(t, dir, names[:1500], 0)
|
||||
wfs.option.CacheDirMaxEntries = 100
|
||||
startFakeFiler(t, wfs, &listingFilerServer{names: names})
|
||||
dirInode, _ := wfs.inodeToPath.GetInode(dir)
|
||||
|
||||
dhid, _ := wfs.AcquireDirectoryHandle()
|
||||
defer wfs.ReleaseDirectoryHandle(dhid)
|
||||
|
||||
sink := &pagingSink{limit: 64}
|
||||
var offset uint64
|
||||
dropped := false
|
||||
for round := 0; round < 1000; round++ {
|
||||
sink.round = 0
|
||||
before := len(sink.names)
|
||||
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
|
||||
InHeader: fuse.InHeader{NodeId: dirInode},
|
||||
Fh: uint64(dhid),
|
||||
Offset: offset,
|
||||
Size: 1 << 20,
|
||||
}, sink, false)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("readdir: %v", status)
|
||||
}
|
||||
if !dropped {
|
||||
// The cached listing goes away after the first reply.
|
||||
wfs.inodeToPath.InvalidateChildrenCache(dir)
|
||||
dropped = true
|
||||
}
|
||||
if len(sink.names) == before || sink.lastOff <= offset {
|
||||
break
|
||||
}
|
||||
offset = sink.lastOff
|
||||
}
|
||||
|
||||
seen := map[string]int{}
|
||||
var listed []string
|
||||
for _, n := range sink.names {
|
||||
if n == "." || n == ".." {
|
||||
continue
|
||||
}
|
||||
seen[n]++
|
||||
listed = append(listed, n)
|
||||
}
|
||||
for n, count := range seen {
|
||||
if count > 1 {
|
||||
t.Errorf("%s listed %d times", n, count)
|
||||
}
|
||||
}
|
||||
if len(seen) != total {
|
||||
t.Fatalf("listed %d distinct names (%d in all), want %d", len(seen), len(listed), total)
|
||||
}
|
||||
}
|
||||
|
||||
// listWholeDirectory lists dir through one handle in replies of at most
|
||||
// sinkLimit entries, calling afterReply after each, and returns the names in
|
||||
// listing order without "." and "..".
|
||||
func listWholeDirectory(t *testing.T, wfs *WFS, dir util.FullPath, sinkLimit int, afterReply func(reply int)) []string {
|
||||
t.Helper()
|
||||
dirInode, found := wfs.inodeToPath.GetInode(dir)
|
||||
if !found {
|
||||
t.Fatalf("no inode for %s", dir)
|
||||
}
|
||||
dhid, _ := wfs.AcquireDirectoryHandle()
|
||||
defer wfs.ReleaseDirectoryHandle(dhid)
|
||||
|
||||
sink := &pagingSink{limit: sinkLimit}
|
||||
var offset uint64
|
||||
for reply := 0; reply < 100000; reply++ {
|
||||
sink.round = 0
|
||||
before := len(sink.names)
|
||||
status := wfs.doReadDirectory(context.Background(), &fuse.ReadIn{
|
||||
InHeader: fuse.InHeader{NodeId: dirInode},
|
||||
Fh: uint64(dhid),
|
||||
Offset: offset,
|
||||
Size: 1 << 20,
|
||||
}, sink, false)
|
||||
if status != fuse.OK {
|
||||
t.Fatalf("readdir: %v", status)
|
||||
}
|
||||
if afterReply != nil {
|
||||
afterReply(reply)
|
||||
}
|
||||
if len(sink.names) == before || sink.lastOff <= offset {
|
||||
break
|
||||
}
|
||||
offset = sink.lastOff
|
||||
}
|
||||
var names []string
|
||||
for _, name := range sink.names {
|
||||
if name != "." && name != ".." {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// requireListing fails unless got is want: every name once, in order.
|
||||
func requireListing(t *testing.T, got, want []string) {
|
||||
t.Helper()
|
||||
if slices.Equal(got, want) {
|
||||
return
|
||||
}
|
||||
seen := map[string]int{}
|
||||
for _, name := range got {
|
||||
seen[name]++
|
||||
}
|
||||
var twice, missing []string
|
||||
for name, count := range seen {
|
||||
if count > 1 {
|
||||
twice = append(twice, name)
|
||||
}
|
||||
}
|
||||
for _, name := range want {
|
||||
if seen[name] == 0 {
|
||||
missing = append(missing, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(twice)
|
||||
first := func(names []string) []string {
|
||||
if len(names) > 5 {
|
||||
return names[:5]
|
||||
}
|
||||
return names
|
||||
}
|
||||
t.Fatalf("listed %d names, want %d; listed more than once: %d %v; missing: %d %v", len(got), len(want), len(twice), first(twice), len(missing), first(missing))
|
||||
}
|
||||
|
||||
// createUnflushed leaves dir/name as Create leaves a file before its first
|
||||
// flush: a placeholder in the local store, and an open handle with dirty
|
||||
// metadata.
|
||||
func createUnflushed(t *testing.T, wfs *WFS, dir util.FullPath, name string) {
|
||||
t.Helper()
|
||||
path := dir.Child(name)
|
||||
now := time.Now()
|
||||
inode := wfs.inodeToPath.Lookup(path, now.Unix(), false, false, 0, true)
|
||||
entry := &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, Mtime: now.Unix(), Crtime: now.Unix(), Inode: inode},
|
||||
}
|
||||
if err := wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(string(dir), entry), 0); err != nil {
|
||||
t.Fatalf("insert placeholder %s: %v", path, err)
|
||||
}
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, entry, 0, 0)
|
||||
fh.dirtyMetadata = true
|
||||
t.Cleanup(fh.dirtyPages.Destroy)
|
||||
}
|
||||
|
||||
// A directory read through from the filer lists the files this mount created
|
||||
// and has not flushed, as a cached listing does, though the filer has none of
|
||||
// them yet: each once and in name order, wherever it falls among the filer's
|
||||
// pages. One the filer has by now is listed once.
|
||||
func TestReadDirReadThroughListsUnflushedCreates(t *testing.T) {
|
||||
dir := util.FullPath("/d")
|
||||
var filerNames []string
|
||||
for i := 0; i < 2500; i++ {
|
||||
filerNames = append(filerNames, fmt.Sprintf("f%05d", i))
|
||||
}
|
||||
// Before the first page, right after a page's last name, inside a page, a
|
||||
// name the filer has by now, and past the last page.
|
||||
unflushed := []string{"a-new", "f00999x", "f01500x", "f02000", "z-new"}
|
||||
want := append(append([]string{}, filerNames...), "a-new", "f00999x", "f01500x", "z-new")
|
||||
sort.Strings(want)
|
||||
|
||||
for _, sinkLimit := range []int{64, 5000} {
|
||||
t.Run(fmt.Sprintf("replies of %d", sinkLimit), func(t *testing.T) {
|
||||
wfs := newPagingWFS(t, dir, nil, 0)
|
||||
wfs.metaCache.SetPinnedChildFn(wfs.isLocalOnlyEntry)
|
||||
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
|
||||
for _, name := range unflushed {
|
||||
createUnflushed(t, wfs, dir, name)
|
||||
}
|
||||
// Too large to cache: listings read it through.
|
||||
wfs.inodeToPath.MarkDirectoryReadThrough(dir, time.Now())
|
||||
requireListing(t, listWholeDirectory(t, wfs, dir, sinkLimit, nil), want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The mount's root read through from the filer. The loader leaves out the
|
||||
// hidden system entries, etc and topics, so a full page from the filer that
|
||||
// held one came back short and was taken for the end of the directory.
|
||||
func TestReadDirReadThroughRootPastHiddenEntries(t *testing.T) {
|
||||
root := util.FullPath("/")
|
||||
var visible []string
|
||||
for _, prefix := range []string{"d", "s", "u"} {
|
||||
for i := 0; i < 500; i++ {
|
||||
visible = append(visible, fmt.Sprintf("%s%04d", prefix, i))
|
||||
}
|
||||
}
|
||||
// etc falls inside the first page of 1000, topics inside the second.
|
||||
filerNames := append([]string{"etc", "topics"}, visible...)
|
||||
sort.Strings(filerNames)
|
||||
|
||||
wfs := newPagingWFS(t, "/x", nil, 0)
|
||||
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
|
||||
wfs.inodeToPath.MarkDirectoryReadThrough(root, time.Now())
|
||||
requireListing(t, listWholeDirectory(t, wfs, root, 5000, nil), visible)
|
||||
}
|
||||
|
||||
// A listing walking the cache hands over to the filer when a section of the
|
||||
// directory changed so much that refreshing it would list more than a
|
||||
// refresh may (ErrRefreshRangeTooLarge). That hand-over, too, resumed at the
|
||||
// request's offset and sent again the entries the cached walk had just put in
|
||||
// the reply.
|
||||
func TestReadDirHandOverOnOvergrownSectionSendsEachNameOnce(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := util.FullPath("/d")
|
||||
var cached, filerNames, burst []string
|
||||
for i := 0; i < 2000; i++ {
|
||||
cached = append(cached, fmt.Sprintf("f%05d", i))
|
||||
}
|
||||
// Far more than one refresh may list.
|
||||
for i := 0; i < 6000; i++ {
|
||||
filerNames = append(filerNames, fmt.Sprintf("f%05d", i))
|
||||
}
|
||||
// Enough changes in one go to make a section stale.
|
||||
for i := 0; i < 64; i++ {
|
||||
burst = append(burst, fmt.Sprintf("g-%03d", i))
|
||||
}
|
||||
filerNames = append(filerNames, burst...)
|
||||
|
||||
wfs := newPagingWFS(t, dir, cached, 0)
|
||||
startFakeFiler(t, wfs, &listingFilerServer{names: filerNames})
|
||||
// One section over the directory, as a build of it leaves.
|
||||
if err := wfs.metaCache.BeginDirectoryBuild(ctx, dir); err != nil {
|
||||
t.Fatalf("begin build: %v", err)
|
||||
}
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(ctx, dir, 1000, nil); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
got := listWholeDirectory(t, wfs, dir, 64, func(reply int) {
|
||||
if reply != 0 {
|
||||
return
|
||||
}
|
||||
// After the first reply other clients create a burst of files: the
|
||||
// section goes stale, and refreshing it would list too much.
|
||||
for i, name := range burst {
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: string(dir),
|
||||
EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0o100644, FileSize: 1},
|
||||
}},
|
||||
TsNs: 2000 + int64(i),
|
||||
}
|
||||
if err := wfs.metaCache.ApplyMetadataResponse(ctx, resp, meta_cache.SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
requireListing(t, got, filerNames)
|
||||
}
|
||||
|
||||
// countingListingFilerServer counts the listings it serves.
|
||||
type countingListingFilerServer struct {
|
||||
listingFilerServer
|
||||
listings atomic.Int32
|
||||
}
|
||||
|
||||
func (s *countingListingFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
|
||||
s.listings.Add(1)
|
||||
return s.listingFilerServer.ListEntries(req, stream)
|
||||
}
|
||||
|
||||
// A page listed from the filer stays on the handle until the client has read
|
||||
// it. A listing in small replies then lists each filer page once, and merges
|
||||
// the unflushed creates once per page, rather than again for every reply.
|
||||
func TestReadDirReadThroughListsEachFilerPageOnce(t *testing.T) {
|
||||
dir := util.FullPath("/d")
|
||||
var names []string
|
||||
for i := 0; i < 2500; i++ {
|
||||
names = append(names, fmt.Sprintf("f%05d", i))
|
||||
}
|
||||
wfs := newPagingWFS(t, dir, nil, 0)
|
||||
server := &countingListingFilerServer{listingFilerServer: listingFilerServer{names: names}}
|
||||
startFakeFiler(t, wfs, server)
|
||||
wfs.inodeToPath.MarkDirectoryReadThrough(dir, time.Now())
|
||||
|
||||
requireListing(t, listWholeDirectory(t, wfs, dir, 64, nil), names)
|
||||
// Three pages, and the empty one that finds the end.
|
||||
if n := server.listings.Load(); n > 4 {
|
||||
t.Errorf("the filer was asked for %d listings, want one per page of %d", n, batchSize)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// heldListingFilerServer lists names, holding every listing until release is
|
||||
// closed, and records how many it held at once.
|
||||
type heldListingFilerServer struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
names []string
|
||||
release chan struct{}
|
||||
inFlight atomic.Int32
|
||||
peak atomic.Int32
|
||||
}
|
||||
|
||||
func (s *heldListingFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
|
||||
n := s.inFlight.Add(1)
|
||||
defer s.inFlight.Add(-1)
|
||||
for {
|
||||
peak := s.peak.Load()
|
||||
if n <= peak || s.peak.CompareAndSwap(peak, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-s.release:
|
||||
case <-stream.Context().Done():
|
||||
return stream.Context().Err()
|
||||
}
|
||||
for _, name := range s.names {
|
||||
if name <= req.StartFromFileName {
|
||||
continue
|
||||
}
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, FileSize: 1},
|
||||
}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitUntil(t *testing.T, what string, cond func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !cond() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("timed out waiting for %s", what)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// While the local store refuses writes every listing of the mount reads
|
||||
// through to the filer. Each still lists the whole directory, but no more than
|
||||
// storeRefusedListingLimit go to the filer at once; a listing waiting for a
|
||||
// slot gives up with EINTR when its request is interrupted.
|
||||
func TestReadDirStoreRefusedListsFromTheFilerAFewAtATime(t *testing.T) {
|
||||
dir := util.FullPath("/d")
|
||||
names := []string{"a", "b", "c"}
|
||||
wfs := newPagingWFS(t, dir, nil, 0)
|
||||
server := &heldListingFilerServer{names: names, release: make(chan struct{})}
|
||||
startFakeFiler(t, wfs, server)
|
||||
|
||||
const listings = 3 * storeRefusedListingLimit
|
||||
results := make([][]string, listings)
|
||||
statuses := make([]fuse.Status, listings)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < listings; i++ {
|
||||
dhid, dh := wfs.AcquireDirectoryHandle()
|
||||
defer wfs.ReleaseDirectoryHandle(dhid)
|
||||
wg.Add(1)
|
||||
go func(i int, dh *DirectoryHandle) {
|
||||
defer wg.Done()
|
||||
statuses[i] = wfs.readDirectoryDirectStoreRefused(context.Background(), &fuse.ReadIn{Offset: directoryStreamBaseOffset}, &pagingSink{limit: 100}, dh, dir, func(entry *filer.Entry, index int64) bool {
|
||||
results[i] = append(results[i], entry.Name())
|
||||
return true
|
||||
})
|
||||
}(i, dh)
|
||||
}
|
||||
|
||||
waitUntil(t, "the first listings to reach the filer", func() bool { return server.inFlight.Load() == storeRefusedListingLimit })
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if n := server.inFlight.Load(); n != storeRefusedListingLimit {
|
||||
t.Errorf("%d listings at the filer at once, want %d", n, storeRefusedListingLimit)
|
||||
}
|
||||
|
||||
// Every slot is taken: an interrupted request stops waiting.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
dhid, dh := wfs.AcquireDirectoryHandle()
|
||||
defer wfs.ReleaseDirectoryHandle(dhid)
|
||||
if status := wfs.readDirectoryDirectStoreRefused(ctx, &fuse.ReadIn{Offset: directoryStreamBaseOffset}, &pagingSink{limit: 100}, dh, dir, func(*filer.Entry, int64) bool { return true }); status != fuse.EINTR {
|
||||
t.Errorf("an interrupted listing waiting for a slot = %v, want EINTR", status)
|
||||
}
|
||||
|
||||
close(server.release)
|
||||
wg.Wait()
|
||||
if peak := server.peak.Load(); peak > storeRefusedListingLimit {
|
||||
t.Errorf("up to %d listings at the filer at once, want at most %d", peak, storeRefusedListingLimit)
|
||||
}
|
||||
for i := 0; i < listings; i++ {
|
||||
if statuses[i] != fuse.OK {
|
||||
t.Errorf("listing %d = %v", i, statuses[i])
|
||||
}
|
||||
if got := fmt.Sprint(results[i]); got != fmt.Sprint(names) {
|
||||
t.Errorf("listing %d = %s, want %s", i, got, fmt.Sprint(names))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func TestLoadDirectoryEntriesDirectFiltersHiddenEntriesAndMapsIds(t *testing.T)
|
||||
},
|
||||
}
|
||||
|
||||
entries, _, err := loadDirectoryEntriesDirect(context.Background(), client, mapper, util.FullPath("/"), "", false, 10, 0, false)
|
||||
entries, _, _, err := loadDirectoryEntriesDirect(context.Background(), client, mapper, util.FullPath("/"), "", false, 10, 0, false)
|
||||
if err != nil {
|
||||
t.Fatalf("loadDirectoryEntriesDirect: %v", err)
|
||||
}
|
||||
@@ -115,7 +115,7 @@ func TestLoadDirectoryEntriesDirectShowsSystemEntriesWhenEnabled(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
entries, _, err := loadDirectoryEntriesDirect(context.Background(), client, nil, util.FullPath("/"), "", false, 10, 0, true)
|
||||
entries, _, _, err := loadDirectoryEntriesDirect(context.Background(), client, nil, util.FullPath("/"), "", false, 10, 0, true)
|
||||
if err != nil {
|
||||
t.Fatalf("loadDirectoryEntriesDirect: %v", err)
|
||||
}
|
||||
|
||||
@@ -93,18 +93,13 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
|
||||
}
|
||||
|
||||
// lock source and target file handles
|
||||
fhOutActiveLock := fhOut.wfs.fhLockTable.AcquireLock("CopyFileRange", fhOut.fh, util.ExclusiveLock)
|
||||
defer fhOut.wfs.fhLockTable.ReleaseLock(fhOut.fh, fhOutActiveLock)
|
||||
unlockHandles := lockCopyFileRangeHandles(fhIn, fhOut)
|
||||
defer unlockHandles()
|
||||
|
||||
if fhOut.entry == nil {
|
||||
return 0, fuse.ENOENT
|
||||
}
|
||||
|
||||
if fhIn.fh != fhOut.fh {
|
||||
fhInActiveLock := fhIn.wfs.fhLockTable.AcquireLock("CopyFileRange", fhIn.fh, util.SharedLock)
|
||||
defer fhIn.wfs.fhLockTable.ReleaseLock(fhIn.fh, fhInActiveLock)
|
||||
}
|
||||
|
||||
// directories are not supported
|
||||
if fhIn.entry.IsDirectory || fhOut.entry.IsDirectory {
|
||||
return 0, fuse.EISDIR
|
||||
@@ -224,6 +219,29 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn)
|
||||
return written, fuse.OK
|
||||
}
|
||||
|
||||
// lockCopyFileRangeHandles takes the destination handle's lock exclusively and
|
||||
// the source handle's lock shared, in ascending FileHandleId order whichever of
|
||||
// the two is the destination. Two copies in opposite directions between the
|
||||
// same pair of files would otherwise each hold their destination and wait for
|
||||
// their source. It returns the function that releases both.
|
||||
func lockCopyFileRangeHandles(fhIn, fhOut *FileHandle) (unlock func()) {
|
||||
lockTable := fhOut.wfs.fhLockTable
|
||||
if fhIn.fh == fhOut.fh {
|
||||
lock := lockTable.AcquireLock("CopyFileRange", fhOut.fh, util.ExclusiveLock)
|
||||
return func() { lockTable.ReleaseLock(fhOut.fh, lock) }
|
||||
}
|
||||
first, firstType, second, secondType := fhOut, util.ExclusiveLock, fhIn, util.SharedLock
|
||||
if fhIn.fh < fhOut.fh {
|
||||
first, firstType, second, secondType = fhIn, util.SharedLock, fhOut, util.ExclusiveLock
|
||||
}
|
||||
firstLock := lockTable.AcquireLock("CopyFileRange", first.fh, firstType)
|
||||
secondLock := lockTable.AcquireLock("CopyFileRange", second.fh, secondType)
|
||||
return func() {
|
||||
lockTable.ReleaseLock(second.fh, secondLock)
|
||||
lockTable.ReleaseLock(first.fh, firstLock)
|
||||
}
|
||||
}
|
||||
|
||||
func (wfs *WFS) tryServerSideWholeFileCopy(cancel <-chan struct{}, in *fuse.CopyFileRangeIn, fhIn, fhOut *FileHandle) (written uint32, handled bool, code fuse.Status) {
|
||||
if !wfs.canSignFilerCopy() {
|
||||
glog.V(4).Infof("server-side copy: skipped (filer token file without a filer signing key)")
|
||||
|
||||
@@ -6,7 +6,10 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mount/meta_cache"
|
||||
@@ -539,3 +542,87 @@ func TestServerSideCopyNeedsASigningKeyWithAFilerTokenFile(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Two copies in opposite directions between the same pair of files must not
|
||||
// wait on each other's handle locks. The test holds the lower handle's lock so
|
||||
// that the first copy queues for it and the second copy has to take its
|
||||
// handle locks while the first one is still waiting for its own: with the
|
||||
// destination locked before the source, each copy then holds its destination
|
||||
// and waits for its source.
|
||||
func TestCopyFileRangeInOppositeDirectionsDoesNotDeadlock(t *testing.T) {
|
||||
wfs := newCopyRangeTestWFS()
|
||||
var handles [2]*FileHandle
|
||||
for i, name := range []string{"a.txt", "b.txt"} {
|
||||
path := util.FullPath("/" + name)
|
||||
inode := wfs.inodeToPath.Lookup(path, 1, false, false, 0, true)
|
||||
handle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 5, Inode: inode},
|
||||
Content: []byte("hello"),
|
||||
}, 0, 0)
|
||||
handle.RememberPath(path)
|
||||
t.Cleanup(handle.dirtyPages.Destroy)
|
||||
handles[i] = handle
|
||||
}
|
||||
low, high := handles[0], handles[1]
|
||||
if high.fh < low.fh {
|
||||
low, high = high, low
|
||||
}
|
||||
|
||||
copyFromTo := func(src, dst *FileHandle) <-chan fuse.Status {
|
||||
done := make(chan fuse.Status, 1)
|
||||
go func() {
|
||||
_, status := wfs.CopyFileRange(make(chan struct{}), &fuse.CopyFileRangeIn{
|
||||
FhIn: uint64(src.fh),
|
||||
FhOut: uint64(dst.fh),
|
||||
Len: 5,
|
||||
})
|
||||
done <- status
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
held := wfs.fhLockTable.AcquireLock("test", low.fh, util.ExclusiveLock)
|
||||
intoLow := copyFromTo(high, low)
|
||||
waitForBlockedCopyFileRange(t, 1)
|
||||
intoHigh := copyFromTo(low, high)
|
||||
waitForBlockedCopyFileRange(t, 2)
|
||||
wfs.fhLockTable.ReleaseLock(low.fh, held)
|
||||
|
||||
for name, done := range map[string]<-chan fuse.Status{"into low": intoLow, "into high": intoHigh} {
|
||||
select {
|
||||
case status := <-done:
|
||||
if status != fuse.OK {
|
||||
t.Errorf("CopyFileRange (%s) status = %v, want OK", name, status)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("CopyFileRange (%s) did not finish: the two copies hold each other's handle locks", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// waitForBlockedCopyFileRange waits until n CopyFileRange calls are parked in
|
||||
// a handle lock queue, which the lock table does not otherwise expose.
|
||||
func waitForBlockedCopyFileRange(t *testing.T, n int) {
|
||||
t.Helper()
|
||||
buf := make([]byte, 1<<20)
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
size := runtime.Stack(buf, true)
|
||||
if size == len(buf) { // the dump was cut short: look at all of it
|
||||
buf = make([]byte, 2*len(buf))
|
||||
continue
|
||||
}
|
||||
blocked := 0
|
||||
for _, stack := range strings.Split(string(buf[:size]), "\n\n") {
|
||||
if strings.Contains(stack, "mount.(*WFS).CopyFileRange(") && strings.Contains(stack, "sync.(*Cond).Wait") {
|
||||
blocked++
|
||||
}
|
||||
}
|
||||
if blocked >= n {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatalf("%d CopyFileRange calls never blocked on a handle lock", n)
|
||||
}
|
||||
@@ -377,7 +377,7 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
|
||||
|
||||
// no chunk deleter here: a failed fold reports the blobs it saved
|
||||
unfolded := chunks
|
||||
chunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), nil, chunks)
|
||||
chunks, manifestErr := wfs.maybeManifestize(fileFullPath, chunks)
|
||||
if manifestErr != nil {
|
||||
// not good, but should be ok
|
||||
glog.V(0).Infof("MaybeManifestize: %v", manifestErr)
|
||||
|
||||
@@ -17,27 +17,18 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// A write the swap file cannot buffer fails, and must not grow the file: the
|
||||
// next flush would publish that size with a hole where its data should be. A
|
||||
// write that buffers only its first chunk is a short write of those bytes, or
|
||||
// an error for kernel writeback, which would drop the rest silently.
|
||||
func TestFailedWriteDoesNotGrowFile(t *testing.T) {
|
||||
t.Run("short write", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, 0) })
|
||||
t.Run("kernel writeback", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, fuse.WRITE_CACHE) })
|
||||
}
|
||||
|
||||
func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
|
||||
// openSwapWriteHandle opens /dir/file for writing on a WFS with one writable
|
||||
// chunk slot, so a second chunk is buffered in the swap file under swapDir.
|
||||
// The file holds 256 'O' bytes on the fake filer.
|
||||
func openSwapWriteHandle(t *testing.T, swapDir string) (*WFS, *FileHandle, *g6ConditionalPeer, *fuse.OpenOut) {
|
||||
t.Helper()
|
||||
base := attributeAppendEntry(1)
|
||||
base.CommitTsNs = 100
|
||||
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
|
||||
peer.blobs = map[string][]byte{base.Chunks[0].GetFileIdString(): bytes.Repeat([]byte{'O'}, 256)}
|
||||
|
||||
w := newInvalidateTestWFS(t)
|
||||
notADir := filepath.Join(t.TempDir(), "file")
|
||||
if err := os.WriteFile(notADir, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.option.uniqueCacheDirForWrite = filepath.Join(notADir, "swap")
|
||||
w.option.uniqueCacheDirForWrite = swapDir
|
||||
w.option.DefaultPermissions = true
|
||||
w.posixLocks = NewPosixLockTable()
|
||||
w.option.ConcurrentWriters = 1
|
||||
@@ -56,6 +47,25 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
|
||||
fh := w.GetHandle(FileHandleId(out.Fh))
|
||||
g6AppendUploader(t, fh, 100, peer)
|
||||
|
||||
return w, fh, peer, out
|
||||
}
|
||||
|
||||
// A write the swap file cannot buffer fails, and must not grow the file: the
|
||||
// next flush would publish that size with a hole where its data should be. A
|
||||
// write that buffers only its first chunk is a short write of those bytes, or
|
||||
// an error for kernel writeback, which would drop the rest silently.
|
||||
func TestFailedWriteDoesNotGrowFile(t *testing.T) {
|
||||
t.Run("short write", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, 0) })
|
||||
t.Run("kernel writeback", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, fuse.WRITE_CACHE) })
|
||||
}
|
||||
|
||||
func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
|
||||
notADir := filepath.Join(t.TempDir(), "file")
|
||||
if err := os.WriteFile(notADir, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w, fh, peer, out := openSwapWriteHandle(t, filepath.Join(notADir, "swap"))
|
||||
|
||||
write := func(offset uint64, size int, value byte) (uint32, fuse.Status) {
|
||||
return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: uint32(size), WriteFlags: writeFlags}, bytes.Repeat([]byte{value}, size))
|
||||
}
|
||||
@@ -93,3 +103,52 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
|
||||
t.Fatalf("stored size %d, want 1024 with the original and buffered bytes", peer.entry.Attributes.FileSize)
|
||||
}
|
||||
}
|
||||
|
||||
// Writes buffered in the swap file were acknowledged to the application. If the
|
||||
// swap file cannot be read back when they upload, fsync must fail like a failed
|
||||
// chunk upload and the filer must not get an entry that claims those bytes.
|
||||
func TestFsyncFailsWhenSwapFileCannotBeReadBack(t *testing.T) {
|
||||
swapDir := t.TempDir()
|
||||
w, _, peer, out := openSwapWriteHandle(t, swapDir)
|
||||
peer.mu.Lock()
|
||||
before := proto.Clone(peer.entry).(*filer_pb.Entry)
|
||||
peer.mu.Unlock()
|
||||
write := func(offset uint64, value byte) (uint32, fuse.Status) {
|
||||
return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: 256}, bytes.Repeat([]byte{value}, 256))
|
||||
}
|
||||
if n, code := write(256, 'A'); n != 256 || code != fuse.OK {
|
||||
t.Fatalf("buffered write = %d, %v", n, code)
|
||||
}
|
||||
// The only writable chunk slot is taken, so this write goes to the swap file.
|
||||
if n, code := write(4096, 'B'); n != 256 || code != fuse.OK {
|
||||
t.Fatalf("swap file write = %d, %v", n, code)
|
||||
}
|
||||
swapFiles, err := os.ReadDir(swapDir)
|
||||
if err != nil || len(swapFiles) != 1 {
|
||||
t.Fatalf("swap dir = %v, %v; want one swap file", swapFiles, err)
|
||||
}
|
||||
// An outside cleanup cuts the swap file after the write was acknowledged.
|
||||
if err := os.Truncate(filepath.Join(swapDir, swapFiles[0].Name()), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh})
|
||||
if code == fuse.OK {
|
||||
t.Fatal("fsync succeeded although acknowledged bytes could not be uploaded")
|
||||
}
|
||||
t.Logf("fsync = %v", code)
|
||||
if _, code := write(8192, 'C'); code == fuse.OK {
|
||||
t.Error("write after the failed upload succeeded; the handle can no longer flush cleanly")
|
||||
}
|
||||
|
||||
peer.mu.Lock()
|
||||
defer peer.mu.Unlock()
|
||||
// The failed fsync publishes nothing: the filer keeps the entry and the 256
|
||||
// bytes it had before the writes.
|
||||
if !proto.Equal(peer.entry, before) {
|
||||
t.Fatalf("a failed fsync changed the filer entry:\n got %v\nwant %v", peer.entry, before)
|
||||
}
|
||||
if stored := g6StoredBytes(t, peer); !bytes.Equal(stored, bytes.Repeat([]byte{'O'}, 256)) {
|
||||
t.Fatalf("filer content = %q, want the original 256 bytes", stored)
|
||||
}
|
||||
}
|
||||
@@ -76,3 +76,15 @@ func filerTokenExpiry(token security.EncodedJwt) time.Time {
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
// filerTokenScoped reports whether the filer scopes the mount's current
|
||||
// token, as it does one with path grants or a method list. A token that
|
||||
// cannot be read or decoded counts as scoped.
|
||||
func (wfs *WFS) filerTokenScoped() bool {
|
||||
token, err := wfs.option.FilerTokenSource(context.Background())
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
claims, ok := security.FilerTokenClaims(token)
|
||||
return !ok || claims.IsScoped() || len(claims.AllowedMethods) > 0
|
||||
}
|
||||
@@ -156,7 +156,7 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
|
||||
// Try to create manifest chunks for large files
|
||||
// no chunk deleter here: a failed fold reports the blobs it saved
|
||||
unfolded := compactedChunks
|
||||
compactedChunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), nil, compactedChunks)
|
||||
compactedChunks, manifestErr := wfs.maybeManifestize(fileFullPath, compactedChunks)
|
||||
if manifestErr != nil {
|
||||
glog.V(0).Infof("flushFileMetadata MaybeManifestize: %v", manifestErr)
|
||||
}
|
||||
|
||||
@@ -102,14 +102,22 @@ func newStreamMutateMux(wfs *WFS) *streamMutateMux {
|
||||
}
|
||||
|
||||
// CreateEntry sends a CreateEntryRequest over the stream and waits for the response.
|
||||
// The request carries the assignment proofs of the new chunks it stores,
|
||||
// released once the filer acknowledged it.
|
||||
func (m *streamMutateMux) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
proofs := m.wfs.chunkProofs
|
||||
held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth)
|
||||
resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{
|
||||
Request: &filer_pb.StreamMutateEntryRequest_CreateRequest{CreateRequest: req},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return createEntryFromResponse(resp, req)
|
||||
cr, err := createEntryFromResponse(resp, req)
|
||||
if err == nil && held {
|
||||
proofs.release(req.GetEntry().GetChunks())
|
||||
}
|
||||
return cr, err
|
||||
}
|
||||
|
||||
// createEntryFromResponse unwraps a create's nested response, mapping its
|
||||
@@ -146,7 +154,10 @@ func createEntryFromResponse(resp *filer_pb.StreamMutateEntryResponse, req *file
|
||||
}
|
||||
|
||||
// UpdateEntry sends an UpdateEntryRequest over the stream and waits for the response.
|
||||
// Proofs are attached and released as for CreateEntry.
|
||||
func (m *streamMutateMux) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
|
||||
proofs := m.wfs.chunkProofs
|
||||
held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth)
|
||||
resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{
|
||||
Request: &filer_pb.StreamMutateEntryRequest_UpdateRequest{UpdateRequest: req},
|
||||
})
|
||||
@@ -154,6 +165,9 @@ func (m *streamMutateMux) UpdateEntry(ctx context.Context, req *filer_pb.UpdateE
|
||||
return nil, err
|
||||
}
|
||||
if r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_UpdateResponse); ok {
|
||||
if held {
|
||||
proofs.release(req.GetEntry().GetChunks())
|
||||
}
|
||||
return r.UpdateResponse, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected response type %T", resp.Response)
|
||||
|
||||
@@ -25,6 +25,18 @@ func (wfs *WFS) shouldCacheUploadedChunk(offset int64) bool {
|
||||
return wfs.chunkCache != nil && (offset == 0 || wfs.peerAnnouncer != nil || wfs.readAuth != nil)
|
||||
}
|
||||
|
||||
// maybeManifestize folds a file's chunks into manifests as
|
||||
// filer.MaybeManifestize does, except on a mount with a scoped filer token: a
|
||||
// filer serving a scoped token stores no new chunk in an entry that holds
|
||||
// manifests, so every later write to a folded file would be refused. Such a
|
||||
// mount keeps chunk lists flat.
|
||||
func (wfs *WFS) maybeManifestize(fullPath util.FullPath, chunks []*filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) {
|
||||
if wfs.chunkProofs != nil && wfs.filerTokenScoped() {
|
||||
return chunks, nil
|
||||
}
|
||||
return filer.MaybeManifestize(wfs.saveDataAsChunk(fullPath), nil, chunks)
|
||||
}
|
||||
|
||||
func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFunctionType {
|
||||
|
||||
// Backstop: FUSE entry points sanitize names before they reach
|
||||
@@ -56,6 +68,12 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
|
||||
}
|
||||
}
|
||||
|
||||
// A filer serving a scoped token stores the chunk only with the
|
||||
// assignment proof it returns, so make room to keep it first.
|
||||
if err = wfs.chunkProofs.reserve(1); err != nil {
|
||||
glog.V(0).Infof("upload data %v: %v", filename, err)
|
||||
return nil, fmt.Errorf("upload data: %w", err)
|
||||
}
|
||||
fileId, uploadResult, err, data := uploader.UploadWithRetry(
|
||||
wfs,
|
||||
&filer_pb.AssignVolumeRequest{
|
||||
@@ -71,13 +89,16 @@ func (wfs *WFS) saveDataAsChunk(fullPath util.FullPath) filer.SaveDataAsChunkFun
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
wfs.chunkProofs.unreserve(1)
|
||||
glog.V(0).Infof("upload data %v: %v", filename, err)
|
||||
return nil, fmt.Errorf("upload data: %w", err)
|
||||
}
|
||||
if uploadResult.Error != "" {
|
||||
wfs.chunkProofs.unreserve(1)
|
||||
glog.V(0).Infof("upload failure %v: %v", filename, err)
|
||||
return nil, fmt.Errorf("upload result: %v", uploadResult.Error)
|
||||
}
|
||||
wfs.chunkProofs.keep(fileId, uploadResult.AssignAuth, 1)
|
||||
|
||||
// shouldCacheUploadedChunk explains when and why every uploaded
|
||||
// chunk is cached (peer sharing, and read-auth read-after-write).
|
||||
|
||||
+39
-11
@@ -42,13 +42,17 @@ func (wfs *WFS) GetXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr str
|
||||
|
||||
ctx, cancelFunc := ctxFromCancel(cancel)
|
||||
defer cancelFunc()
|
||||
_, _, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
|
||||
_, fh, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
|
||||
if status != fuse.OK {
|
||||
return 0, status
|
||||
}
|
||||
if entry == nil {
|
||||
return 0, fuse.ENOENT
|
||||
}
|
||||
// An open handle's Extended map is shared with the writers of its
|
||||
// entry, so the value is copied out while the entry lock is held.
|
||||
unlock, entry := lockExtendedForRead(fh, entry)
|
||||
defer unlock()
|
||||
if entry.Extended == nil {
|
||||
return 0, fuse.ENOATTR
|
||||
}
|
||||
@@ -64,6 +68,20 @@ func (wfs *WFS) GetXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr str
|
||||
return uint32(len(data)), fuse.OK
|
||||
}
|
||||
|
||||
// lockExtendedForRead returns the entry whose Extended map the caller may
|
||||
// read until it calls unlock. An open handle's entry is changed in place by
|
||||
// setxattr, removexattr, truncate to zero and the metadata merges, all under
|
||||
// the LockedEntry lock, and SetEntry can swap the entry since maybeReadEntry
|
||||
// returned it, so the read takes that lock and the handle's current entry.
|
||||
// Any other entry is a private copy.
|
||||
func lockExtendedForRead(fh *FileHandle, entry *filer_pb.Entry) (unlock func(), current *filer_pb.Entry) {
|
||||
if fh == nil {
|
||||
return func() {}, entry
|
||||
}
|
||||
fh.entry.RLock()
|
||||
return fh.entry.RUnlock, fh.entry.Entry
|
||||
}
|
||||
|
||||
// SetXAttr writes an extended attribute.
|
||||
// https://man7.org/linux/man-pages/man2/setxattr.2.html
|
||||
//
|
||||
@@ -144,6 +162,11 @@ func (wfs *WFS) SetXAttr(cancel <-chan struct{}, input *fuse.SetXAttrIn, attr st
|
||||
defer wfs.fhLockTable.ReleaseLock(fh.fh, active)
|
||||
fh.entryLock.Lock()
|
||||
defer fh.entryLock.Unlock()
|
||||
// Readers take only the LockedEntry lock. Re-read the entry under
|
||||
// it in case SetEntry swapped the pointer since maybeReadEntry.
|
||||
fh.entry.Lock()
|
||||
defer fh.entry.Unlock()
|
||||
entry = fh.entry.Entry
|
||||
}
|
||||
|
||||
if code := applyXAttr(entry, input.Flags, attr, data); code != fuse.OK {
|
||||
@@ -175,24 +198,24 @@ func (wfs *WFS) ListXAttr(cancel <-chan struct{}, header *fuse.InHeader, dest []
|
||||
|
||||
ctx, cancelFunc := ctxFromCancel(cancel)
|
||||
defer cancelFunc()
|
||||
_, _, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
|
||||
_, fh, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
|
||||
if status != fuse.OK {
|
||||
return 0, status
|
||||
}
|
||||
if entry == nil {
|
||||
return 0, fuse.ENOENT
|
||||
}
|
||||
if entry.Extended == nil {
|
||||
return 0, fuse.OK
|
||||
}
|
||||
|
||||
var data []byte
|
||||
for k := range entry.Extended {
|
||||
if strings.HasPrefix(k, XATTR_PREFIX) {
|
||||
data = append(data, k[len(XATTR_PREFIX):]...)
|
||||
data = append(data, 0)
|
||||
func() {
|
||||
unlock, live := lockExtendedForRead(fh, entry)
|
||||
defer unlock()
|
||||
for k := range live.Extended {
|
||||
if strings.HasPrefix(k, XATTR_PREFIX) {
|
||||
data = append(data, k[len(XATTR_PREFIX):]...)
|
||||
data = append(data, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
if len(dest) < len(data) {
|
||||
return uint32(len(data)), fuse.ERANGE
|
||||
}
|
||||
@@ -244,6 +267,11 @@ func (wfs *WFS) RemoveXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr
|
||||
defer wfs.fhLockTable.ReleaseLock(fh.fh, active)
|
||||
fh.entryLock.Lock()
|
||||
defer fh.entryLock.Unlock()
|
||||
// Readers take only the LockedEntry lock. Re-read the entry under
|
||||
// it in case SetEntry swapped the pointer since maybeReadEntry.
|
||||
fh.entry.Lock()
|
||||
defer fh.entry.Unlock()
|
||||
entry = fh.entry.Entry
|
||||
}
|
||||
|
||||
if code := removeXAttr(entry, attr); code != fuse.OK {
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//go:build !freebsd
|
||||
|
||||
package mount
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
)
|
||||
|
||||
// raceDuration is how long a reader and a writer run against each other. The
|
||||
// unguarded map access this covers fails within milliseconds: Go aborts the
|
||||
// whole process on a concurrent map read and write, and -race reports it.
|
||||
const raceDuration = 300 * time.Millisecond
|
||||
|
||||
// openXAttrRaceHandle opens a file with some extended attributes and no name,
|
||||
// as an unlinked file that is still open: every operation on it works on the
|
||||
// handle's own entry and none goes to the filer.
|
||||
func openXAttrRaceHandle(t *testing.T, content []byte) (*WFS, *FileHandle) {
|
||||
t.Helper()
|
||||
wfs := newCopyRangeTestWFS()
|
||||
const inode = 42
|
||||
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
|
||||
Name: "x.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: uint64(len(content)), Inode: inode},
|
||||
Content: content,
|
||||
Extended: map[string][]byte{
|
||||
XATTR_PREFIX + "user.a": []byte("1"),
|
||||
XATTR_PREFIX + "user.b": []byte("2"),
|
||||
},
|
||||
}, 0, 0)
|
||||
t.Cleanup(fh.dirtyPages.Destroy)
|
||||
fh.dirtyMetadata = true
|
||||
return wfs, fh
|
||||
}
|
||||
|
||||
// runXAttrRace runs one writer and several readers until the time is up.
|
||||
func runXAttrRace(writer func(i int), readers ...func(i int)) {
|
||||
stop := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for _, fn := range append([]func(int){writer}, readers...) {
|
||||
wg.Add(1)
|
||||
go func(fn func(int)) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
fn(i)
|
||||
}
|
||||
}(fn)
|
||||
}
|
||||
time.Sleep(raceDuration)
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func getXAttrReader(t *testing.T, wfs *WFS, inode uint64, name string) func(int) {
|
||||
dest := make([]byte, 64)
|
||||
return func(int) {
|
||||
n, code := wfs.GetXAttr(nil, &fuse.InHeader{NodeId: inode}, name, dest)
|
||||
if code == fuse.OK && n == 0 {
|
||||
t.Errorf("GetXAttr(%q) = OK with no bytes", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func listXAttrReader(wfs *WFS, inode uint64) func(int) {
|
||||
dest := make([]byte, 4096)
|
||||
return func(int) { wfs.ListXAttr(nil, &fuse.InHeader{NodeId: inode}, dest) }
|
||||
}
|
||||
|
||||
// SetXAttr and RemoveXAttr on an open file change its entry's Extended map in
|
||||
// place while GetXAttr and ListXAttr read it.
|
||||
func TestXAttrReadsAgainstSetAndRemoveOnOpenFile(t *testing.T) {
|
||||
wfs, fh := openXAttrRaceHandle(t, nil)
|
||||
inode := fh.inode
|
||||
runXAttrRace(func(i int) {
|
||||
// each name is set and then removed, so every removal deletes a key
|
||||
name := fmt.Sprintf("user.k%d", (i/2)%64)
|
||||
if i%2 == 0 {
|
||||
if code := wfs.SetXAttr(nil, &fuse.SetXAttrIn{InHeader: fuse.InHeader{NodeId: inode}}, name, []byte("v")); code != fuse.OK {
|
||||
t.Errorf("SetXAttr(%q) = %v", name, code)
|
||||
}
|
||||
} else if code := wfs.RemoveXAttr(nil, &fuse.InHeader{NodeId: inode}, name); code != fuse.OK {
|
||||
t.Errorf("RemoveXAttr(%q) = %v", name, code)
|
||||
}
|
||||
}, getXAttrReader(t, wfs, inode, "user.a"), getXAttrReader(t, wfs, inode, "security.capability"), listXAttrReader(wfs, inode))
|
||||
}
|
||||
|
||||
// Truncating an open file to zero removes its S3 encryption attributes from
|
||||
// the same map.
|
||||
func TestXAttrReadsAgainstTruncateToZeroOnOpenFile(t *testing.T) {
|
||||
wfs, fh := openXAttrRaceHandle(t, []byte("payload"))
|
||||
inode := fh.inode
|
||||
runXAttrRace(func(int) {
|
||||
// put the keys back so that every truncate deletes something
|
||||
fh.UpdateEntry(func(e *filer_pb.Entry) {
|
||||
e.Extended[s3_constants.AmzServerSideEncryption] = []byte("AES256")
|
||||
e.Extended[s3_constants.SeaweedFSSSEIV] = []byte("iv")
|
||||
})
|
||||
in := &fuse.SetAttrIn{}
|
||||
in.NodeId, in.Valid, in.Size = inode, fuse.FATTR_SIZE, 0
|
||||
if code := wfs.SetAttr(nil, in, &fuse.AttrOut{}); code != fuse.OK {
|
||||
t.Errorf("truncate = %v", code)
|
||||
}
|
||||
}, getXAttrReader(t, wfs, inode, "user.a"), listXAttrReader(wfs, inode))
|
||||
}
|
||||
|
||||
// A flush that merged a peer's change gives the handle the merged entry's
|
||||
// attributes, Extended among them.
|
||||
func TestXAttrReadsAgainstFlushMergeOnOpenFile(t *testing.T) {
|
||||
wfs, fh := openXAttrRaceHandle(t, nil)
|
||||
inode := fh.inode
|
||||
runXAttrRace(func(i int) {
|
||||
merged := &filer_pb.Entry{
|
||||
Name: "x.txt",
|
||||
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: inode},
|
||||
Extended: map[string][]byte{
|
||||
XATTR_PREFIX + "user.a": []byte("1"),
|
||||
XATTR_PREFIX + fmt.Sprintf("user.m%d", i%8): []byte("m"),
|
||||
},
|
||||
}
|
||||
fh.rebaseEntry(merged, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
|
||||
}, getXAttrReader(t, wfs, inode, "user.a"), listXAttrReader(wfs, inode))
|
||||
}
|
||||
|
||||
// The reply carries the value as it was when it was read, in the caller's
|
||||
// buffer.
|
||||
func TestGetXAttrReturnsCopyOfOpenFileValue(t *testing.T) {
|
||||
wfs, fh := openXAttrRaceHandle(t, nil)
|
||||
dest := make([]byte, 8)
|
||||
n, code := wfs.GetXAttr(nil, &fuse.InHeader{NodeId: fh.inode}, "user.a", dest)
|
||||
if code != fuse.OK || string(dest[:n]) != "1" {
|
||||
t.Fatalf("GetXAttr = %q, %v; want \"1\", OK", dest[:n], code)
|
||||
}
|
||||
dest[0] = 'x'
|
||||
if got := fh.entry.Entry.Extended[XATTR_PREFIX+"user.a"]; string(got) != "1" {
|
||||
t.Fatalf("the handle's value changed through the caller's buffer: %q", got)
|
||||
}
|
||||
if code := wfs.SetXAttr(nil, &fuse.SetXAttrIn{InHeader: fuse.InHeader{NodeId: fh.inode}}, "user.a", []byte("22")); code != fuse.OK {
|
||||
t.Fatalf("SetXAttr = %v", code)
|
||||
}
|
||||
if n, code = wfs.GetXAttr(nil, &fuse.InHeader{NodeId: fh.inode}, "user.a", dest); code != fuse.OK || string(dest[:n]) != "22" {
|
||||
t.Fatalf("GetXAttr after SetXAttr = %q, %v; want \"22\", OK", dest[:n], code)
|
||||
}
|
||||
}
|
||||
@@ -155,9 +155,10 @@ func (wfs *WFS) callFiler(ctx context.Context, streamingMode bool, callWait time
|
||||
|
||||
// newFilerClient authorizes each call through the client with the mount's
|
||||
// filer token source, resolved per attempt so a retry carries a replaced
|
||||
// token. The cached channel itself carries no identity.
|
||||
// token. The cached channel itself carries no identity. Creates and updates
|
||||
// carry the assignment proofs of the new chunks they store.
|
||||
func (wfs *WFS) newFilerClient(conn *grpc.ClientConn) filer_pb.SeaweedFilerClient {
|
||||
return filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, wfs.option.FilerTokenSource))
|
||||
return filer_pb.NewSeaweedFilerClient(wfs.chunkProofs.conn(security.WithFilerClientAuth(conn, wfs.option.FilerTokenSource)))
|
||||
}
|
||||
|
||||
func (wfs *WFS) AdjustedUrl(location *filer_pb.Location) string {
|
||||
|
||||
+8
-5
@@ -53,12 +53,15 @@ The client will write the messages for this segment to the selected brokers.
|
||||
|
||||
The broker leader does not contain any state. If it fails, the masters will select a different broker.
|
||||
|
||||
For a segment, if any one of the selected brokers is down, the remaining brokers should try to write received messages
|
||||
to the filer, and close the segment to the clients.
|
||||
A partition's files are written only by the broker holding the partition's fence, so a broker that lost its
|
||||
leadership cannot add to them. When that broker fails, the partition is assigned to another broker, which takes the
|
||||
fence at a new epoch and continues from the files.
|
||||
|
||||
Then the clients should start a new segment. The masters should assign other healthy brokers to handle the new segment.
|
||||
|
||||
So any brokers can go down without losing data.
|
||||
Each partition has a leader and a follower on two brokers. The leader acknowledges a message once the follower holds
|
||||
it, and the follower keeps what the leader has not flushed yet in memory. If either is lost, the survivor writes what
|
||||
it holds, seals the fence and reports the generation ended; the balancer then assigns a new pair at the next epoch,
|
||||
and publishers resend what was not acknowledged. A partition placed while only one broker is live has no follower,
|
||||
and messages it acknowledged but had not flushed yet are lost when that broker fails.
|
||||
|
||||
## Auto Split or Merge
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math/rand/v2"
|
||||
|
||||
@@ -20,6 +21,7 @@ func (a *MessageQueueAgent) StartPublishSession(ctx context.Context, req *mq_age
|
||||
Brokers: a.brokersList(),
|
||||
PublisherName: req.PublisherName,
|
||||
RecordType: req.RecordType,
|
||||
GrpcDialOption: a.grpcDialOption,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -37,18 +39,33 @@ func (a *MessageQueueAgent) StartPublishSession(ctx context.Context, req *mq_age
|
||||
}
|
||||
|
||||
func (a *MessageQueueAgent) ClosePublishSession(ctx context.Context, req *mq_agent_pb.ClosePublishSessionRequest) (*mq_agent_pb.ClosePublishSessionResponse, error) {
|
||||
var finishErr string
|
||||
sessionID := SessionId(req.SessionId)
|
||||
a.publishersLock.RLock()
|
||||
entry := a.publishers[sessionID]
|
||||
a.publishersLock.RUnlock()
|
||||
if entry == nil {
|
||||
return &mq_agent_pb.ClosePublishSessionResponse{Error: fmt.Sprintf("publish session id %d not found", sessionID)}, nil
|
||||
}
|
||||
if err := a.finishPublisher(sessionID, entry); err != nil {
|
||||
return &mq_agent_pb.ClosePublishSessionResponse{Error: err.Error()}, nil
|
||||
}
|
||||
return &mq_agent_pb.ClosePublishSessionResponse{}, nil
|
||||
}
|
||||
|
||||
// Concurrent closers of the same publisher wait on the same scheduler and observe
|
||||
// the same acknowledgment count. Keep the session reachable during the flush.
|
||||
func (a *MessageQueueAgent) finishPublisher(id SessionId, entry *SessionEntry[*pub_client.TopicPublisher]) error {
|
||||
err := entry.entry.FinishPublish()
|
||||
if err == nil {
|
||||
err = entry.entry.Shutdown()
|
||||
}
|
||||
a.publishersLock.Lock()
|
||||
publisherEntry, found := a.publishers[SessionId(req.SessionId)]
|
||||
if found {
|
||||
if err := publisherEntry.entry.FinishPublish(); err != nil {
|
||||
finishErr = err.Error()
|
||||
if a.publishers[id] == entry {
|
||||
delete(a.publishers, id)
|
||||
if err != nil {
|
||||
slog.Warn("failed to finish publish", "error", err)
|
||||
}
|
||||
delete(a.publishers, SessionId(req.SessionId))
|
||||
}
|
||||
a.publishersLock.Unlock()
|
||||
return &mq_agent_pb.ClosePublishSessionResponse{
|
||||
Error: finishErr,
|
||||
}, nil
|
||||
return err
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
|
||||
)
|
||||
|
||||
func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAgent_PublishRecordServer) error {
|
||||
func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAgent_PublishRecordServer) (streamErr error) {
|
||||
m, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -18,10 +21,11 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
|
||||
if !found {
|
||||
return fmt.Errorf("publish session id %d not found", sessionId)
|
||||
}
|
||||
// A disconnected stream may already be blocked enqueueing to a full partition.
|
||||
stopOnDisconnect := context.AfterFunc(stream.Context(), func() { publisherEntry.entry.FinishPublish() })
|
||||
defer func() {
|
||||
a.publishersLock.Lock()
|
||||
delete(a.publishers, sessionId)
|
||||
a.publishersLock.Unlock()
|
||||
stopOnDisconnect()
|
||||
streamErr = errors.Join(streamErr, a.finishPublisher(sessionId, publisherEntry))
|
||||
}()
|
||||
|
||||
if m.Value != nil {
|
||||
@@ -32,6 +36,9 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
|
||||
|
||||
for {
|
||||
m, err = stream.Recv()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/client/agent_client"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
type gatedAckBroker struct {
|
||||
mq_pb.UnimplementedSeaweedMessagingServer
|
||||
addr string
|
||||
closeMarker chan struct{}
|
||||
allowAck chan struct{}
|
||||
}
|
||||
|
||||
func (b *gatedAckBroker) ConfigureTopic(context.Context, *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
|
||||
return &mq_pb.ConfigureTopicResponse{}, nil
|
||||
}
|
||||
|
||||
func (b *gatedAckBroker) LookupTopicBrokers(context.Context, *mq_pb.LookupTopicBrokersRequest) (*mq_pb.LookupTopicBrokersResponse, error) {
|
||||
return &mq_pb.LookupTopicBrokersResponse{BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
|
||||
Partition: &schema_pb.Partition{RangeStop: pub_balancer.MaxPartitionCount},
|
||||
LeaderBroker: b.addr,
|
||||
}}}, nil
|
||||
}
|
||||
|
||||
func (b *gatedAckBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
|
||||
if _, err := stream.Recv(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.Send(&mq_pb.PublishMessageResponse{}); err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
req, err := stream.Recv()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
data := req.GetData()
|
||||
if data.GetCtrl().GetIsClose() {
|
||||
close(b.closeMarker)
|
||||
select {
|
||||
case <-b.allowAck:
|
||||
case <-stream.Context().Done():
|
||||
return stream.Context().Err()
|
||||
}
|
||||
// The marker acknowledges the entire stream, including the earlier record.
|
||||
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishStreamCloseWaitsForAcknowledgment(t *testing.T) {
|
||||
listen := func() net.Listener {
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
brokerListener := listen()
|
||||
broker := &gatedAckBroker{addr: brokerListener.Addr().String(), closeMarker: make(chan struct{}), allowAck: make(chan struct{})}
|
||||
brokerServer := grpc.NewServer()
|
||||
mq_pb.RegisterSeaweedMessagingServer(brokerServer, broker)
|
||||
go brokerServer.Serve(brokerListener)
|
||||
t.Cleanup(brokerServer.Stop)
|
||||
|
||||
agent := NewMessageQueueAgent(&MessageQueueAgentOptions{SeedBrokers: []pb.ServerAddress{pb.ServerAddress(broker.addr)}}, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
agentListener := listen()
|
||||
agentServer := grpc.NewServer()
|
||||
mq_agent_pb.RegisterSeaweedMessagingAgentServer(agentServer, agent)
|
||||
go agentServer.Serve(agentListener)
|
||||
t.Cleanup(agentServer.Stop)
|
||||
|
||||
client, err := agent_client.NewPublishSession(agentListener.Addr().String(), &schema.Schema{Namespace: "test", Name: "events"}, 1, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
agent.publishersLock.RLock()
|
||||
var id SessionId
|
||||
for id = range agent.publishers {
|
||||
break
|
||||
}
|
||||
agent.publishersLock.RUnlock()
|
||||
|
||||
if err := client.PublishMessageRecord([]byte("key"), &schema_pb.RecordValue{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
closed := make(chan error, 1)
|
||||
go func() { closed <- client.CloseSession() }()
|
||||
select {
|
||||
case <-broker.closeMarker:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("closing the stream did not finish the publisher")
|
||||
}
|
||||
duplicate := make(chan *mq_agent_pb.ClosePublishSessionResponse, 1)
|
||||
go func() {
|
||||
resp, _ := agent.ClosePublishSession(t.Context(), &mq_agent_pb.ClosePublishSessionRequest{SessionId: int64(id)})
|
||||
duplicate <- resp
|
||||
}()
|
||||
waitForFinishers(t, 2)
|
||||
select {
|
||||
case <-closed:
|
||||
t.Fatal("stream close returned before acknowledgment")
|
||||
case <-duplicate:
|
||||
t.Fatal("duplicate close returned before acknowledgment")
|
||||
default:
|
||||
}
|
||||
close(broker.allowAck)
|
||||
select {
|
||||
case err := <-closed:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("stream close did not finish")
|
||||
}
|
||||
select {
|
||||
case resp := <-duplicate:
|
||||
if resp == nil || resp.Error != "" {
|
||||
t.Fatalf("duplicate close returned %v", resp)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("duplicate close did not finish")
|
||||
}
|
||||
}
|
||||
|
||||
// waitForFinishers waits until n goroutines are flushing a publisher in finishPublisher.
|
||||
func waitForFinishers(t *testing.T, n int) {
|
||||
t.Helper()
|
||||
buf := make([]byte, 1<<20)
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
stacks := string(buf[:runtime.Stack(buf, true)])
|
||||
if strings.Count(stacks, "(*MessageQueueAgent).finishPublisher(") >= n {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("fewer than %d goroutines reached finishPublisher", n)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// balancerSettleTime outlasts a broker's lock retry (5 x LiveLockTTL/2) plus its
|
||||
// reconnect, so a new balancer does not take a broker still reconnecting for dead.
|
||||
const balancerSettleTime = 30 * time.Second
|
||||
|
||||
func (b *MessageQueueBroker) balancerSettled() bool {
|
||||
return time.Now().After(b.balancerSettleDeadline())
|
||||
}
|
||||
|
||||
// balancerSettleDeadline counts from the first sight of the current lease. A
|
||||
// regained lease has a new generation; a renewal keeps it.
|
||||
func (b *MessageQueueBroker) balancerSettleDeadline() time.Time {
|
||||
var generation int64
|
||||
if lock := b.lockAsBalancer.Load(); lock != nil {
|
||||
generation = lock.Generation()
|
||||
}
|
||||
return b.settleDeadline(generation, time.Now())
|
||||
}
|
||||
|
||||
// balancerSettle is the balancer lease the settle window counts from.
|
||||
type balancerSettle struct {
|
||||
sync.Mutex
|
||||
generation int64
|
||||
since time.Time
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) settleDeadline(generation int64, now time.Time) time.Time {
|
||||
s := &b.balancerSettle
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.since.IsZero() || generation != s.generation {
|
||||
s.generation, s.since = generation, now
|
||||
}
|
||||
return s.since.Add(balancerSettleTime)
|
||||
}
|
||||
|
||||
// topicConfExpiry ends a config validated at validatedAt by a settling balancer
|
||||
// at the settle deadline, so the repair it skipped runs as soon as it may, even
|
||||
// when the deadline passed before the config was cached.
|
||||
func (b *MessageQueueBroker) topicConfExpiry(validatedAt time.Time) time.Time {
|
||||
if b.isLockOwner() {
|
||||
return cacheExpiry(validatedAt, b.topicCacheTTL, b.balancerSettleDeadline())
|
||||
}
|
||||
return validatedAt.Add(b.topicCacheTTL)
|
||||
}
|
||||
|
||||
func cacheExpiry(now time.Time, ttl time.Duration, settleDeadline time.Time) time.Time {
|
||||
if expiry := now.Add(ttl); !now.Before(settleDeadline) || expiry.Before(settleDeadline) {
|
||||
return expiry
|
||||
}
|
||||
return settleDeadline
|
||||
}
|
||||
|
||||
// isLockOwner reports whether this broker holds an unexpired balancer lease.
|
||||
func (b *MessageQueueBroker) isLockOwner() bool {
|
||||
lock := b.lockAsBalancer.Load()
|
||||
return lock != nil && lock.IsLocked()
|
||||
}
|
||||
|
||||
// balancer is the broker that balancer-only requests are proxied to.
|
||||
func (b *MessageQueueBroker) balancer() (pb.ServerAddress, error) {
|
||||
if lock := b.lockAsBalancer.Load(); lock != nil {
|
||||
owner := pb.ServerAddress(lock.LockOwner())
|
||||
// A lapsed lease still names this broker; proxying to itself would loop.
|
||||
if owner != "" && !owner.Equals(b.option.BrokerAddress()) {
|
||||
return owner, nil
|
||||
}
|
||||
}
|
||||
return "", status.Error(codes.Unavailable, "no broker balancer elected yet")
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) withBalancerClient(fn func(client mq_pb.SeaweedMessagingClient) error) error {
|
||||
balancer, err := b.balancer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return b.withBrokerClient(false, balancer, fn)
|
||||
}
|
||||
|
||||
// lockRing holds the master's filer lock ring until the balancer lock client
|
||||
// exists, since the master sends the whole ring only when the broker connects.
|
||||
type lockRing struct {
|
||||
sync.Mutex
|
||||
client *cluster.LockClient
|
||||
servers []pb.ServerAddress
|
||||
version int64
|
||||
}
|
||||
|
||||
func (r *lockRing) set(servers []pb.ServerAddress, version int64) {
|
||||
r.Lock()
|
||||
defer r.Unlock()
|
||||
if r.client != nil {
|
||||
r.client.SetRing(servers, version)
|
||||
return
|
||||
}
|
||||
r.servers, r.version = servers, version
|
||||
}
|
||||
|
||||
// reset drops the version gate: ring versions count per master.
|
||||
func (r *lockRing) reset() {
|
||||
r.Lock()
|
||||
defer r.Unlock()
|
||||
if r.client != nil {
|
||||
r.client.ResetRing()
|
||||
return
|
||||
}
|
||||
r.version = 0
|
||||
}
|
||||
|
||||
func (r *lockRing) attach(client *cluster.LockClient) {
|
||||
r.Lock()
|
||||
defer r.Unlock()
|
||||
r.client = client
|
||||
if r.servers != nil {
|
||||
client.SetRing(r.servers, r.version)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func newUnelectedBroker() *MessageQueueBroker {
|
||||
return &MessageQueueBroker{
|
||||
option: &MessageQueueBrokerOption{Ip: "127.0.0.1", Port: 17777},
|
||||
PubBalancer: pub_balancer.NewPubBalancer(),
|
||||
}
|
||||
}
|
||||
|
||||
// Requests that reach a broker before it has found a filer used to dereference
|
||||
// the not yet created balancer lock.
|
||||
func TestBalancerRequestsBeforeElection(t *testing.T) {
|
||||
b := newUnelectedBroker()
|
||||
assert.False(t, b.isLockOwner())
|
||||
|
||||
_, err := b.LookupTopicBrokers(context.Background(), &mq_pb.LookupTopicBrokersRequest{
|
||||
Topic: &schema_pb.Topic{Namespace: "test", Name: "t"},
|
||||
})
|
||||
assert.Equal(t, codes.Unavailable, status.Code(err))
|
||||
|
||||
_, err = b.ConfigureTopic(context.Background(), &mq_pb.ConfigureTopicRequest{
|
||||
Topic: &schema_pb.Topic{Namespace: "test", Name: "t"},
|
||||
})
|
||||
assert.Equal(t, codes.Unavailable, status.Code(err))
|
||||
}
|
||||
|
||||
func TestLockRingAppliedWhenClientAttaches(t *testing.T) {
|
||||
var ring lockRing
|
||||
ring.set([]pb.ServerAddress{"filer1:8888"}, 3)
|
||||
|
||||
client := cluster.NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "filer0:8888")
|
||||
assert.Equal(t, pb.ServerAddress(""), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
|
||||
ring.attach(client)
|
||||
assert.Equal(t, pb.ServerAddress("filer1:8888"), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
|
||||
|
||||
ring.set([]pb.ServerAddress{"filer2:8888"}, 4)
|
||||
assert.Equal(t, pb.ServerAddress("filer2:8888"), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
|
||||
}
|
||||
|
||||
// Only the balancer tracks live brokers; any other broker sees an empty set and
|
||||
// used to blank every leader of the topic it read.
|
||||
func TestNonBalancerKeepsStoredAssignments(t *testing.T) {
|
||||
b := newUnelectedBroker()
|
||||
conf := &mq_pb.ConfigureTopicResponse{
|
||||
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{
|
||||
{LeaderBroker: "10.0.0.1:17777", FollowerBroker: "10.0.0.2:17777", Partition: &schema_pb.Partition{RingSize: 2520, RangeStop: 2520}},
|
||||
},
|
||||
}
|
||||
assert.False(t, b.ensureTopicActiveAssignmentsUnsafe(topic.NewTopic("test", "t"), conf))
|
||||
assert.Equal(t, "10.0.0.1:17777", conf.BrokerPartitionAssignments[0].LeaderBroker)
|
||||
assert.Equal(t, "10.0.0.2:17777", conf.BrokerPartitionAssignments[0].FollowerBroker)
|
||||
}
|
||||
|
||||
// A new master's ring versions start over, even before the client attaches.
|
||||
func TestLockRingResetBeforeClientAttaches(t *testing.T) {
|
||||
var ring lockRing
|
||||
ring.set([]pb.ServerAddress{"filer1:8888"}, 100)
|
||||
ring.reset()
|
||||
client := cluster.NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "filer0:8888")
|
||||
ring.attach(client)
|
||||
|
||||
ring.set([]pb.ServerAddress{"filer2:8888"}, 1)
|
||||
assert.Equal(t, pb.ServerAddress("filer2:8888"), client.PrimaryForKey(pub_balancer.LockBrokerBalancer))
|
||||
}
|
||||
|
||||
func TestSettleWindowRestartsWithANewLease(t *testing.T) {
|
||||
b := newUnelectedBroker()
|
||||
start := time.Now()
|
||||
want := start.Add(balancerSettleTime).UnixNano()
|
||||
assert.Equal(t, want, b.settleDeadline(1, start).UnixNano())
|
||||
assert.Equal(t, want, b.settleDeadline(1, start.Add(time.Minute)).UnixNano(), "a renewal keeps the window")
|
||||
|
||||
regained := start.Add(2 * time.Minute)
|
||||
assert.Equal(t, regained.Add(balancerSettleTime).UnixNano(), b.settleDeadline(2, regained).UnixNano())
|
||||
}
|
||||
|
||||
func TestTopicConfCachedNoLongerThanTheSettleWindow(t *testing.T) {
|
||||
now := time.Now()
|
||||
ttl := 30 * time.Second
|
||||
assert.Equal(t, now.Add(10*time.Second), cacheExpiry(now, ttl, now.Add(10*time.Second)), "settling: until the deadline")
|
||||
assert.Equal(t, now.Add(ttl), cacheExpiry(now, ttl, now.Add(time.Minute)), "deadline past the TTL")
|
||||
assert.Equal(t, now.Add(ttl), cacheExpiry(now, ttl, now.Add(-time.Second)), "settled")
|
||||
}
|
||||
|
||||
// The balancer records an assignment the broker acknowledged, so a stopping
|
||||
// broker must refuse it rather than drop the partition and report success.
|
||||
// That holds for a partition it already hosts, which Shutdown leaves registered.
|
||||
func TestStoppingBrokerRefusesAssignment(t *testing.T) {
|
||||
for _, hosted := range []bool{false, true} {
|
||||
b := newUnelectedBroker()
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
if hosted {
|
||||
b.localTopicManager.AddLocalPartition(topic.NewTopic("test", "t"),
|
||||
topic.NewLocalPartition(topic.Partition{RingSize: 2520, RangeStop: 2520}, 3600, nil, nil))
|
||||
}
|
||||
b.localTopicManager.Shutdown()
|
||||
|
||||
_, err := b.AssignTopicPartitions(context.Background(), &mq_pb.AssignTopicPartitionsRequest{
|
||||
Topic: &schema_pb.Topic{Namespace: "test", Name: "t"},
|
||||
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{
|
||||
{Partition: &schema_pb.Partition{RingSize: 2520, RangeStop: 2520}},
|
||||
},
|
||||
})
|
||||
assert.Equal(t, codes.Unavailable, status.Code(err), "hosted=%v", hosted)
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,11 @@ func (b *MessageQueueBroker) KeepConnectedToBrokerBalancer(newBrokerBalancerCh c
|
||||
var stopPrevRunChan chan struct{}
|
||||
for {
|
||||
select {
|
||||
case <-b.ctx.Done():
|
||||
if stopPrevRunChan != nil {
|
||||
close(stopPrevRunChan)
|
||||
}
|
||||
return
|
||||
case newBrokerBalancer := <-newBrokerBalancerCh:
|
||||
if stopPrevRunChan != nil {
|
||||
close(stopPrevRunChan)
|
||||
@@ -82,17 +87,14 @@ func (b *MessageQueueBroker) KeepConnectedToBrokerBalancer(newBrokerBalancerCh c
|
||||
go func() {
|
||||
for {
|
||||
err := b.BrokerConnectToBalancer(newBrokerBalancer, thisRunStopChan)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("connect to balancer %s: %v", newBrokerBalancer, err)
|
||||
time.Sleep(time.Second)
|
||||
} else {
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
glog.V(0).Infof("connect to balancer %s: %v", newBrokerBalancer, err)
|
||||
select {
|
||||
case <-thisRunStopChan:
|
||||
return
|
||||
default:
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -20,11 +20,16 @@ const (
|
||||
BrokerErrorTopicAlreadyExists int32 = 36
|
||||
BrokerErrorInvalidPartitions int32 = 37
|
||||
BrokerErrorInvalidConfig int32 = 40
|
||||
BrokerErrorStorageError int32 = 56
|
||||
// Kafka's code 1, which here is BrokerErrorUnknownServerError
|
||||
BrokerErrorOffsetOutOfRange int32 = 104
|
||||
|
||||
// Publisher/connection errors
|
||||
BrokerErrorPublisherNotFound int32 = 100
|
||||
BrokerErrorConnectionFailed int32 = 101
|
||||
BrokerErrorFollowerConnectionFailed int32 = 102
|
||||
// the partition's leader/follower pair broke; publishers look it up again and resend
|
||||
BrokerErrorGenerationEnded int32 = 103
|
||||
)
|
||||
|
||||
// BrokerErrorInfo contains metadata about a broker error
|
||||
@@ -43,7 +48,7 @@ var BrokerErrors = map[int32]BrokerErrorInfo{
|
||||
},
|
||||
BrokerErrorUnknownServerError: {
|
||||
Code: BrokerErrorUnknownServerError, Name: "UNKNOWN_SERVER_ERROR",
|
||||
Description: "Unknown server error", KafkaCode: 1,
|
||||
Description: "Unknown server error", KafkaCode: -1,
|
||||
},
|
||||
BrokerErrorTopicNotFound: {
|
||||
Code: BrokerErrorTopicNotFound, Name: "TOPIC_NOT_FOUND",
|
||||
@@ -93,14 +98,26 @@ var BrokerErrors = map[int32]BrokerErrorInfo{
|
||||
Code: BrokerErrorInvalidConfig, Name: "INVALID_CONFIG",
|
||||
Description: "Invalid configuration", KafkaCode: 40,
|
||||
},
|
||||
BrokerErrorStorageError: {
|
||||
Code: BrokerErrorStorageError, Name: "KAFKA_STORAGE_ERROR",
|
||||
Description: "Stored messages could not be read", KafkaCode: 56,
|
||||
},
|
||||
BrokerErrorOffsetOutOfRange: {
|
||||
Code: BrokerErrorOffsetOutOfRange, Name: "OFFSET_OUT_OF_RANGE",
|
||||
Description: "Offset is below the earliest retained offset", KafkaCode: 1,
|
||||
},
|
||||
BrokerErrorPublisherNotFound: {
|
||||
Code: BrokerErrorPublisherNotFound, Name: "PUBLISHER_NOT_FOUND",
|
||||
Description: "Publisher not found", KafkaCode: 1, // UNKNOWN_SERVER_ERROR
|
||||
Description: "Publisher not found", KafkaCode: -1, // UNKNOWN_SERVER_ERROR
|
||||
},
|
||||
BrokerErrorConnectionFailed: {
|
||||
Code: BrokerErrorConnectionFailed, Name: "CONNECTION_FAILED",
|
||||
Description: "Connection failed", KafkaCode: 13, // NETWORK_EXCEPTION
|
||||
},
|
||||
BrokerErrorGenerationEnded: {
|
||||
Code: BrokerErrorGenerationEnded, Name: "GENERATION_ENDED",
|
||||
Description: "Partition generation ended; look up its new leader", KafkaCode: 6,
|
||||
},
|
||||
BrokerErrorFollowerConnectionFailed: {
|
||||
Code: BrokerErrorFollowerConnectionFailed, Name: "FOLLOWER_CONNECTION_FAILED",
|
||||
Description: "Failed to connect to follower brokers", KafkaCode: 13, // NETWORK_EXCEPTION
|
||||
@@ -113,7 +130,7 @@ func GetBrokerErrorInfo(code int32) BrokerErrorInfo {
|
||||
return info
|
||||
}
|
||||
return BrokerErrorInfo{
|
||||
Code: code, Name: "UNKNOWN", Description: "Unknown broker error code", KafkaCode: 1,
|
||||
Code: code, Name: "UNKNOWN", Description: "Unknown broker error code", KafkaCode: -1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,12 +6,13 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/logstore"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// AssignTopicPartitions Runs on the assigned broker, to execute the topic partition assignment
|
||||
@@ -23,39 +24,47 @@ func (b *MessageQueueBroker) AssignTopicPartitions(c context.Context, request *m
|
||||
t := topic.FromPbTopic(request.Topic)
|
||||
partition := topic.FromPbPartition(assignment.Partition)
|
||||
b.accessLock.Lock()
|
||||
localPartition := b.localTopicManager.GetLocalPartition(t, partition)
|
||||
for !request.IsDraining && localPartition == nil && b.localTopicManager.RetiringPartition(t, partition) != nil {
|
||||
// its flush takes accessLock, so wait without it
|
||||
b.accessLock.Unlock()
|
||||
if err := b.localTopicManager.WaitRetired(c, t, partition); err != nil {
|
||||
return nil, status.FromContextError(err).Err()
|
||||
}
|
||||
b.accessLock.Lock()
|
||||
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
|
||||
}
|
||||
if request.IsDraining {
|
||||
// TODO drain existing topic partition subscriptions
|
||||
b.localTopicManager.RemoveLocalPartition(t, partition)
|
||||
b.localTopicManager.RemoveLocalPartition(t, localPartition)
|
||||
} else {
|
||||
var localPartition *topic.LocalPartition
|
||||
if localPartition = b.localTopicManager.GetLocalPartition(t, partition); localPartition == nil {
|
||||
localPartition = topic.NewLocalPartition(partition, b.option.LogFlushInterval, b.genLogFlushFunc(t, partition), logstore.GenMergedReadFunc(b, t, partition))
|
||||
|
||||
// Initialize offset from existing data to ensure continuity on restart
|
||||
b.initializePartitionOffsetFromExistingData(localPartition, t, partition)
|
||||
|
||||
b.localTopicManager.AddLocalPartition(t, localPartition)
|
||||
} else {
|
||||
for b.retireStaleLeader(t, localPartition, assignment.Epoch) {
|
||||
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
|
||||
}
|
||||
// checked after the reload, which can wait out a Shutdown that starts meanwhile
|
||||
if b.localTopicManager.IsStopping() {
|
||||
b.accessLock.Unlock()
|
||||
return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress())
|
||||
}
|
||||
// a follower learns of its partition from the leader's follow stream
|
||||
isLeader := assignment.LeaderBroker == "" || pb.ServerAddress(assignment.LeaderBroker).Equals(b.option.BrokerAddress())
|
||||
if isLeader && localPartition == nil {
|
||||
localPartition, genErr := b.newLeaderPartition(t, partition, assignment)
|
||||
if genErr != nil {
|
||||
b.accessLock.Unlock()
|
||||
return nil, status.Errorf(codes.Unavailable, "%v", genErr)
|
||||
}
|
||||
if !b.localTopicManager.AddLocalPartition(t, localPartition) {
|
||||
localPartition.Shutdown()
|
||||
b.accessLock.Unlock()
|
||||
return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress())
|
||||
}
|
||||
go b.watchReplica(t, partition, localPartition, assignment.Epoch)
|
||||
}
|
||||
}
|
||||
b.accessLock.Unlock()
|
||||
}
|
||||
|
||||
// if is leader, notify the followers to drain existing topic partition subscriptions
|
||||
if request.IsLeader {
|
||||
for _, brokerPartition := range request.BrokerPartitionAssignments {
|
||||
if follower := brokerPartition.FollowerBroker; follower != "" {
|
||||
err := pb.WithBrokerGrpcClient(false, follower, b.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error {
|
||||
_, err := client.AssignTopicPartitions(context.Background(), request)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return ret, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
@@ -70,14 +79,10 @@ func (b *MessageQueueBroker) assignTopicPartitionsToBrokers(ctx context.Context,
|
||||
defer wg.Done()
|
||||
if doCreateErr := b.withBrokerClient(false, pb.ServerAddress(bpa.LeaderBroker), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
_, doCreateErr := client.AssignTopicPartitions(ctx, &mq_pb.AssignTopicPartitionsRequest{
|
||||
Topic: t,
|
||||
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{
|
||||
{
|
||||
Partition: bpa.Partition,
|
||||
},
|
||||
},
|
||||
IsLeader: true,
|
||||
IsDraining: !isAdd,
|
||||
Topic: t,
|
||||
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{bpa},
|
||||
IsLeader: true,
|
||||
IsDraining: !isAdd,
|
||||
})
|
||||
if doCreateErr != nil {
|
||||
if !isAdd {
|
||||
|
||||
@@ -3,13 +3,12 @@ package broker
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
)
|
||||
|
||||
func (b *MessageQueueBroker) BalanceTopics(ctx context.Context, request *mq_pb.BalanceTopicsRequest) (resp *mq_pb.BalanceTopicsResponse, err error) {
|
||||
if !b.isLockOwner() {
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.BalanceTopics(ctx, request)
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -20,7 +19,7 @@ import (
|
||||
// and then assign the partitions to the brokers.
|
||||
func (b *MessageQueueBroker) ConfigureTopic(ctx context.Context, request *mq_pb.ConfigureTopicRequest) (resp *mq_pb.ConfigureTopicResponse, err error) {
|
||||
if !b.isLockOwner() {
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.ConfigureTopic(ctx, request)
|
||||
return nil
|
||||
})
|
||||
@@ -37,6 +36,8 @@ func (b *MessageQueueBroker) ConfigureTopic(ctx context.Context, request *mq_pb.
|
||||
}
|
||||
}
|
||||
|
||||
b.topicConfLock.Lock()
|
||||
defer b.topicConfLock.Unlock()
|
||||
t := topic.FromPbTopic(request.Topic)
|
||||
var readErr, assignErr error
|
||||
resp, readErr = b.fca.ReadTopicConfFromFiler(t)
|
||||
|
||||
@@ -2,11 +2,13 @@ package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
// FetchMessage implements Kafka-style stateless message fetching
|
||||
@@ -47,14 +49,16 @@ func (b *MessageQueueBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchM
|
||||
if err != nil {
|
||||
glog.Errorf("[FetchMessage] Failed to get partition: %v", err)
|
||||
return &mq_pb.FetchMessageResponse{
|
||||
Error: fmt.Sprintf("partition not found: %v", err),
|
||||
ErrorCode: 1,
|
||||
Error: fmt.Sprintf("partition not found: %v", err),
|
||||
ErrorCode: 1,
|
||||
NextOffset: req.StartOffset,
|
||||
}, nil
|
||||
}
|
||||
if localPartition == nil {
|
||||
return &mq_pb.FetchMessageResponse{
|
||||
Error: "partition not found",
|
||||
ErrorCode: 1,
|
||||
Error: "partition not found",
|
||||
ErrorCode: 1,
|
||||
NextOffset: req.StartOffset,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -119,25 +123,25 @@ func (b *MessageQueueBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchM
|
||||
nextOffset, endOfPartition, localPartition.LogBuffer.GetLogStartOffset())
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// Check if this is an "offset out of range" error
|
||||
errMsg := err.Error()
|
||||
if len(errMsg) > 0 && (len(errMsg) < 20 || errMsg[:20] != "offset") {
|
||||
glog.Errorf("[FetchMessage] Read error: %v", err)
|
||||
} else {
|
||||
// Offset out of range - this is expected when consumer requests old data
|
||||
glog.V(3).Infof("[FetchMessage] Offset out of range: %v", err)
|
||||
}
|
||||
|
||||
// Return empty response with metadata - let client adjust offset
|
||||
if errors.Is(err, log_buffer.ErrOffsetOutOfRange) {
|
||||
glog.V(1).Infof("[FetchMessage] %s/%s partition=%v: %v", t.Namespace, t.Name, partition, err)
|
||||
return &mq_pb.FetchMessageResponse{
|
||||
Messages: []*mq_pb.DataMessage{},
|
||||
HighWaterMark: highWaterMark,
|
||||
LogStartOffset: localPartition.LogBuffer.GetLogStartOffset(),
|
||||
EndOfPartition: false,
|
||||
NextOffset: localPartition.LogBuffer.GetLogStartOffset(), // Suggest starting from earliest available
|
||||
Error: errMsg,
|
||||
ErrorCode: 2,
|
||||
NextOffset: requestedOffset,
|
||||
Error: err.Error(),
|
||||
ErrorCode: BrokerErrorOffsetOutOfRange,
|
||||
}, nil
|
||||
}
|
||||
if err != nil {
|
||||
// Any other failed read is retried at the same offset.
|
||||
glog.Errorf("[FetchMessage] %s/%s partition=%v read at offset %d: %v", t.Namespace, t.Name, partition, requestedOffset, err)
|
||||
return &mq_pb.FetchMessageResponse{
|
||||
HighWaterMark: highWaterMark,
|
||||
LogStartOffset: localPartition.LogBuffer.GetLogStartOffset(),
|
||||
NextOffset: requestedOffset,
|
||||
Error: err.Error(),
|
||||
ErrorCode: BrokerErrorStorageError,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
// A failed disk read must leave the client at the offset it asked for.
|
||||
func TestFetchMessageReadErrorKeepsRequestedOffset(t *testing.T) {
|
||||
b := newUnelectedBroker()
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
tp := topic.NewTopic("test", "t")
|
||||
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
|
||||
b.topicCache = map[string]*topicCacheEntry{tp.String(): {conf: &mq_pb.ConfigureTopicResponse{}, expiresAt: time.Now().Add(time.Hour)}}
|
||||
|
||||
failingDiskRead := func(log_buffer.MessagePosition, int64, log_buffer.EachLogEntryFuncType) (log_buffer.MessagePosition, bool, error) {
|
||||
return log_buffer.MessagePosition{}, false, errors.New("volume unreachable")
|
||||
}
|
||||
lp := topic.NewLocalPartition(partition, 3600, nil, failingDiskRead)
|
||||
defer lp.Shutdown()
|
||||
// offsets 0..41 are on disk, the buffer continues at 42
|
||||
if err := lp.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) { return 41, nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.localTopicManager.AddLocalPartition(tp, lp)
|
||||
|
||||
resp, err := b.FetchMessage(context.Background(), &mq_pb.FetchMessageRequest{
|
||||
Topic: &schema_pb.Topic{Namespace: tp.Namespace, Name: tp.Name},
|
||||
Partition: &schema_pb.Partition{RingSize: partition.RingSize, RangeStart: partition.RangeStart, RangeStop: partition.RangeStop, UnixTimeNs: partition.UnixTimeNs},
|
||||
StartOffset: 10,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Error == "" || resp.ErrorCode != BrokerErrorStorageError {
|
||||
t.Errorf("error %q code %d, want a storage error", resp.Error, resp.ErrorCode)
|
||||
}
|
||||
if resp.NextOffset != 10 {
|
||||
t.Errorf("next offset %d after a failed read at 10", resp.NextOffset)
|
||||
}
|
||||
if len(resp.Messages) != 0 {
|
||||
t.Errorf("got %d messages from a failed read", len(resp.Messages))
|
||||
}
|
||||
}
|
||||
|
||||
// A fetch for a partition this broker cannot load must not point the client at offset 0.
|
||||
func TestFetchMessageMissingPartitionKeepsRequestedOffset(t *testing.T) {
|
||||
b := newUnelectedBroker()
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
tp := topic.NewTopic("test", "t")
|
||||
b.topicCache = map[string]*topicCacheEntry{tp.String(): {expiresAt: time.Now().Add(time.Hour)}}
|
||||
|
||||
resp, err := b.FetchMessage(context.Background(), &mq_pb.FetchMessageRequest{
|
||||
Topic: &schema_pb.Topic{Namespace: tp.Namespace, Name: tp.Name},
|
||||
Partition: &schema_pb.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520},
|
||||
StartOffset: 10,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Error == "" {
|
||||
t.Fatal("fetch from a missing topic succeeded")
|
||||
}
|
||||
if resp.NextOffset != 10 {
|
||||
t.Errorf("next offset %d after a failed fetch at 10", resp.NextOffset)
|
||||
}
|
||||
}
|
||||
|
||||
// A fetch below the earliest retained offset is out of range, not a storage
|
||||
// error to retry, and the range info reports where the retained log starts.
|
||||
func TestFetchBelowRetentionIsOutOfRange(t *testing.T) {
|
||||
b := newUnelectedBroker()
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
tp := topic.NewTopic("test", "t")
|
||||
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
|
||||
b.topicCache = map[string]*topicCacheEntry{tp.String(): {conf: &mq_pb.ConfigureTopicResponse{}, expiresAt: time.Now().Add(time.Hour)}}
|
||||
|
||||
lp := topic.NewLocalPartition(partition, 3600, nil, nil)
|
||||
defer lp.Shutdown()
|
||||
if err := lp.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) { return 41, nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a purge left offsets 30..41 on disk
|
||||
lp.LogBuffer.SetLogStartOffset(30)
|
||||
b.localTopicManager.AddLocalPartition(tp, lp)
|
||||
pbTopic := &schema_pb.Topic{Namespace: tp.Namespace, Name: tp.Name}
|
||||
pbPartition := &schema_pb.Partition{RingSize: partition.RingSize, RangeStart: partition.RangeStart, RangeStop: partition.RangeStop, UnixTimeNs: partition.UnixTimeNs}
|
||||
|
||||
resp, err := b.FetchMessage(context.Background(), &mq_pb.FetchMessageRequest{Topic: pbTopic, Partition: pbPartition, StartOffset: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.ErrorCode != BrokerErrorOffsetOutOfRange || resp.LogStartOffset != 30 || resp.NextOffset != 10 || len(resp.Messages) != 0 {
|
||||
t.Errorf("fetch at 10: code %d (%q), log start %d, next %d, %d messages; want out of range, log start 30, next 10",
|
||||
resp.ErrorCode, resp.Error, resp.LogStartOffset, resp.NextOffset, len(resp.Messages))
|
||||
}
|
||||
|
||||
info, err := b.GetPartitionRangeInfo(context.Background(), &mq_pb.GetPartitionRangeInfoRequest{Topic: pbTopic, Partition: pbPartition})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Error != "" || info.OffsetRange.GetEarliestOffset() != 30 || info.OffsetRange.GetHighWaterMark() != 42 {
|
||||
t.Errorf("range info %v, want earliest 30, high water mark 42", info)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// EndPartitionGeneration gives a partition whose leader/follower pair broke a new
|
||||
// pair. A report for an epoch that already moved on is ignored, so both halves of
|
||||
// a broken pair can report it.
|
||||
func (b *MessageQueueBroker) EndPartitionGeneration(ctx context.Context, req *mq_pb.EndPartitionGenerationRequest) (resp *mq_pb.EndPartitionGenerationResponse, err error) {
|
||||
if !b.isLockOwner() {
|
||||
err = b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.EndPartitionGeneration(ctx, req)
|
||||
return err
|
||||
})
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if !b.balancerSettled() {
|
||||
// a new pair is picked from the brokers it has heard from, so wait until all have reconnected
|
||||
return nil, status.Error(codes.Unavailable, "broker balancer is still settling")
|
||||
}
|
||||
b.topicConfLock.Lock()
|
||||
defer b.topicConfLock.Unlock()
|
||||
t := topic.FromPbTopic(req.Topic)
|
||||
conf, err := b.fca.ReadTopicConfFromFiler(t)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read topic %s: %w", t, err)
|
||||
}
|
||||
for _, assignment := range conf.BrokerPartitionAssignments {
|
||||
if !b.partitionsMatch(assignment.Partition, req.Partition) {
|
||||
continue
|
||||
}
|
||||
if assignment.Epoch != req.Epoch {
|
||||
return &mq_pb.EndPartitionGenerationResponse{}, nil
|
||||
}
|
||||
previousLeader, previousFollower := assignment.LeaderBroker, assignment.FollowerBroker
|
||||
pub_balancer.ReassignPartition(b.PubBalancer.Brokers, assignment)
|
||||
if err := b.fca.SaveTopicConfToFiler(t, conf); err != nil {
|
||||
return nil, fmt.Errorf("save topic %s: %w", t, err)
|
||||
}
|
||||
b.invalidateTopicCache(t)
|
||||
glog.V(0).Infof("topic %s partition %v epoch %d ended (reported by %s): %s/%s -> %s/%s at epoch %d", t, topic.FromPbPartition(req.Partition), req.Epoch, req.Broker,
|
||||
previousLeader, previousFollower, assignment.LeaderBroker, assignment.FollowerBroker, assignment.Epoch)
|
||||
return &mq_pb.EndPartitionGenerationResponse{}, nil
|
||||
}
|
||||
return nil, status.Errorf(codes.NotFound, "topic %s has no partition %v", t, topic.FromPbPartition(req.Partition))
|
||||
}
|
||||
|
||||
// watchReplica ends this leader's generation when its follower is lost. It starts
|
||||
// once lp is registered, so the generation never ends under an unlisted partition.
|
||||
func (b *MessageQueueBroker) watchReplica(t topic.Topic, p topic.Partition, lp *topic.LocalPartition, epoch int64) {
|
||||
if lp.Replica == nil {
|
||||
return
|
||||
}
|
||||
<-lp.Replica.Broken()
|
||||
if err := lp.Replica.Err(); errors.Is(err, topic.ErrReplicaClosed) || errors.Is(err, topic.ErrReplicaAbandoned) {
|
||||
return
|
||||
}
|
||||
glog.Warningf("topic %s partition %v epoch %d lost follower %s: %v", t, p, epoch, lp.Follower, lp.Replica.Err())
|
||||
b.endLeaderGeneration(t, lp, epoch)
|
||||
}
|
||||
|
||||
// endLeaderGeneration stores what this leader holds, seals its fence and reports
|
||||
// the generation ended. The fence is kept renewed meanwhile, so a new leader waits.
|
||||
func (b *MessageQueueBroker) endLeaderGeneration(t topic.Topic, lp *topic.LocalPartition, epoch int64) {
|
||||
ctx := context.Background()
|
||||
p, fence := lp.Partition, lp.Fence
|
||||
stopRenewing := b.keepFenceRenewed(fence)
|
||||
b.localTopicManager.RemoveLocalPartition(t, lp)
|
||||
b.localTopicManager.WaitRetired(ctx, t, p)
|
||||
stopRenewing()
|
||||
b.sealAndReportGeneration(ctx, t, p, fence, epoch)
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) sealAndReportGeneration(ctx context.Context, t topic.Topic, p topic.Partition, fence *topic.PartitionFence, epoch int64) {
|
||||
if fence != nil && !fence.IsLost() {
|
||||
if err := b.renewPartitionFence(ctx, fence, true); err != nil {
|
||||
glog.Warningf("seal topic %s partition %v epoch %d: %v", t, p, epoch, err)
|
||||
}
|
||||
}
|
||||
go b.reportGenerationEnded(t, p, epoch)
|
||||
}
|
||||
|
||||
const generationReportTimeout = 30 * time.Second
|
||||
|
||||
// reportGenerationEnded retries until a balancer takes the report: the lost broker
|
||||
// may have been the balancer, and the partition stays unserved until one does.
|
||||
func (b *MessageQueueBroker) reportGenerationEnded(t topic.Topic, p topic.Partition, epoch int64) {
|
||||
req := &mq_pb.EndPartitionGenerationRequest{
|
||||
Topic: t.ToPbTopic(),
|
||||
Partition: p.ToPbPartition(),
|
||||
Epoch: epoch,
|
||||
Broker: string(b.option.BrokerAddress()),
|
||||
}
|
||||
parent := context.Background()
|
||||
if b.ctx != nil {
|
||||
parent = b.ctx
|
||||
}
|
||||
for wait := time.Second; ; wait = min(2*wait, 10*time.Second) {
|
||||
// a balancer that stops answering must not hold the retries; a repeat after a
|
||||
// save that landed finds the epoch moved on and returns without writing
|
||||
ctx, cancel := context.WithTimeout(parent, generationReportTimeout)
|
||||
_, err := b.EndPartitionGeneration(ctx, req)
|
||||
cancel()
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
glog.Warningf("report topic %s partition %v epoch %d ended: %v", t, p, epoch, err)
|
||||
select {
|
||||
case <-parent.Done():
|
||||
return
|
||||
case <-time.After(wait):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// LookupTopicBrokers returns the brokers that are serving the topic
|
||||
func (b *MessageQueueBroker) LookupTopicBrokers(ctx context.Context, request *mq_pb.LookupTopicBrokersRequest) (resp *mq_pb.LookupTopicBrokersResponse, err error) {
|
||||
if !b.isLockOwner() {
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.LookupTopicBrokers(ctx, request)
|
||||
return nil
|
||||
})
|
||||
@@ -52,8 +52,7 @@ func (b *MessageQueueBroker) ListTopics(ctx context.Context, request *mq_pb.List
|
||||
glog.V(4).Infof("📋 ListTopics called, isLockOwner=%v", b.isLockOwner())
|
||||
|
||||
if !b.isLockOwner() {
|
||||
glog.V(4).Infof("📋 ListTopics proxying to lock owner: %s", b.lockAsBalancer.LockOwner())
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.ListTopics(ctx, request)
|
||||
return nil
|
||||
})
|
||||
@@ -190,7 +189,7 @@ func (b *MessageQueueBroker) TopicExists(ctx context.Context, request *mq_pb.Top
|
||||
if !b.isLockOwner() {
|
||||
var resp *mq_pb.TopicExistsResponse
|
||||
var err error
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.TopicExists(ctx, request)
|
||||
return nil
|
||||
})
|
||||
@@ -276,7 +275,7 @@ func (b *MessageQueueBroker) TopicExists(ctx context.Context, request *mq_pb.Top
|
||||
// GetTopicConfiguration returns the complete configuration of a topic including schema and partition assignments
|
||||
func (b *MessageQueueBroker) GetTopicConfiguration(ctx context.Context, request *mq_pb.GetTopicConfigurationRequest) (resp *mq_pb.GetTopicConfigurationResponse, err error) {
|
||||
if !b.isLockOwner() {
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.GetTopicConfiguration(ctx, request)
|
||||
return nil
|
||||
})
|
||||
@@ -290,6 +289,8 @@ func (b *MessageQueueBroker) GetTopicConfiguration(ctx context.Context, request
|
||||
var conf *mq_pb.ConfigureTopicResponse
|
||||
var createdAtNs, modifiedAtNs int64
|
||||
|
||||
b.topicConfLock.Lock()
|
||||
defer b.topicConfLock.Unlock()
|
||||
if conf, createdAtNs, modifiedAtNs, err = b.fca.ReadTopicConfFromFilerWithMetadata(t); err != nil {
|
||||
glog.V(0).Infof("get topic configuration %s: %v", request.Topic, err)
|
||||
return nil, fmt.Errorf("failed to read topic configuration: %w", err)
|
||||
@@ -320,7 +321,7 @@ func (b *MessageQueueBroker) GetTopicConfiguration(ctx context.Context, request
|
||||
// GetTopicPublishers returns the active publishers for a topic
|
||||
func (b *MessageQueueBroker) GetTopicPublishers(ctx context.Context, request *mq_pb.GetTopicPublishersRequest) (resp *mq_pb.GetTopicPublishersResponse, err error) {
|
||||
if !b.isLockOwner() {
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.GetTopicPublishers(ctx, request)
|
||||
return nil
|
||||
})
|
||||
@@ -374,7 +375,7 @@ func (b *MessageQueueBroker) GetTopicPublishers(ctx context.Context, request *mq
|
||||
// GetTopicSubscribers returns the active subscribers for a topic
|
||||
func (b *MessageQueueBroker) GetTopicSubscribers(ctx context.Context, request *mq_pb.GetTopicSubscribersRequest) (resp *mq_pb.GetTopicSubscribersResponse, err error) {
|
||||
if !b.isLockOwner() {
|
||||
proxyErr := b.withBrokerClient(false, pb.ServerAddress(b.lockAsBalancer.LockOwner()), func(client mq_pb.SeaweedMessagingClient) error {
|
||||
proxyErr := b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
resp, err = client.GetTopicSubscribers(ctx, request)
|
||||
return nil
|
||||
})
|
||||
@@ -435,7 +436,3 @@ func (b *MessageQueueBroker) GetTopicSubscribers(ctx context.Context, request *m
|
||||
Subscribers: subscribers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) isLockOwner() bool {
|
||||
return pb.ServerAddress(b.lockAsBalancer.LockOwner()).Equals(b.option.BrokerAddress())
|
||||
}
|
||||
@@ -2,15 +2,15 @@ package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"google.golang.org/grpc/peer"
|
||||
@@ -61,8 +61,7 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
|
||||
return stream.Send(response)
|
||||
}
|
||||
|
||||
currentBrokerAddress := fmt.Sprintf("%s:%d", b.option.Ip, b.option.Port)
|
||||
if leaderBroker != currentBrokerAddress {
|
||||
if !pb.ServerAddress(leaderBroker).Equals(b.option.BrokerAddress()) {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("not the leader for this partition, leader is: %s", leaderBroker))
|
||||
glog.V(1).Infof("rejecting publish request: not the leader for partition, leader is: %s", leaderBroker)
|
||||
return stream.Send(response)
|
||||
@@ -71,16 +70,35 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
|
||||
// get or generate a local partition
|
||||
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
|
||||
localTopicPartition, getOrGenErr := b.GetOrGenerateLocalPartition(t, p)
|
||||
if localTopicPartition == nil && (getOrGenErr == nil || errors.Is(getOrGenErr, errFenceLost)) {
|
||||
// the balancer named this broker from a newer topic.conf than the cached one
|
||||
b.invalidateTopicCache(t)
|
||||
localTopicPartition, getOrGenErr = b.GetOrGenerateLocalPartition(t, p)
|
||||
}
|
||||
if errors.Is(getOrGenErr, errFenceLost) {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, getOrGenErr.Error())
|
||||
return stream.Send(response)
|
||||
}
|
||||
if errors.Is(getOrGenErr, errGenerationEnded) {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, getOrGenErr.Error())
|
||||
return stream.Send(response)
|
||||
}
|
||||
if getOrGenErr != nil {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorTopicNotFound, fmt.Sprintf("topic %v not found: %v", t, getOrGenErr))
|
||||
glog.Errorf("topic %v not found: %v", t, getOrGenErr)
|
||||
return stream.Send(response)
|
||||
}
|
||||
|
||||
// connect to follower brokers
|
||||
if followerErr := localTopicPartition.MaybeConnectToFollowers(initMessage, b.grpcDialOption); followerErr != nil {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorFollowerConnectionFailed, followerErr.Error())
|
||||
glog.Errorf("MaybeConnectToFollowers: %v", followerErr)
|
||||
if localTopicPartition == nil {
|
||||
// topic.conf does not name this broker, though the balancer just did
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is not assigned to this broker", t, p))
|
||||
return stream.Send(response)
|
||||
}
|
||||
if localTopicPartition.IsFenced() {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is fenced by another broker", t, p))
|
||||
return stream.Send(response)
|
||||
}
|
||||
if replica := localTopicPartition.Replica; replica != nil && replica.Err() != nil {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, fmt.Sprintf("topic %v partition %v: %v", t, p, replica.Err()))
|
||||
return stream.Send(response)
|
||||
}
|
||||
|
||||
@@ -89,49 +107,12 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
|
||||
publisher := topic.NewLocalPublisher()
|
||||
localTopicPartition.Publishers.AddPublisher(clientName, publisher)
|
||||
|
||||
// DISABLED: Periodic ack goroutine not needed with immediate per-message acks
|
||||
// Immediate acks provide correct offset information for Kafka Gateway
|
||||
var receivedSequence, acknowledgedSequence int64
|
||||
var isClosed bool
|
||||
|
||||
if false {
|
||||
ackInterval := int64(1)
|
||||
if initMessage.AckInterval > 0 {
|
||||
ackInterval = int64(initMessage.AckInterval)
|
||||
}
|
||||
go func() {
|
||||
defer func() {
|
||||
// println("stop sending ack to publisher", initMessage.PublisherName)
|
||||
}()
|
||||
|
||||
lastAckTime := time.Now()
|
||||
for !isClosed {
|
||||
receivedSequence = atomic.LoadInt64(&localTopicPartition.AckTsNs)
|
||||
if acknowledgedSequence < receivedSequence && (receivedSequence-acknowledgedSequence >= ackInterval || time.Since(lastAckTime) > 100*time.Millisecond) {
|
||||
acknowledgedSequence = receivedSequence
|
||||
response := &mq_pb.PublishMessageResponse{
|
||||
AckTsNs: acknowledgedSequence,
|
||||
}
|
||||
if err := stream.Send(response); err != nil {
|
||||
glog.Errorf("Error sending response %v: %v", response, err)
|
||||
}
|
||||
// Update acknowledged offset for this publisher
|
||||
publisher.UpdateAckedOffset(acknowledgedSequence)
|
||||
// println("sent ack", acknowledgedSequence, "=>", initMessage.PublisherName)
|
||||
lastAckTime = time.Now()
|
||||
} else {
|
||||
time.Sleep(10 * time.Millisecond) // Reduced from 1s to 10ms for faster acknowledgments
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
defer func() {
|
||||
// remove the publisher
|
||||
localTopicPartition.Publishers.RemovePublisher(clientName)
|
||||
// Use topic-aware shutdown logic to prevent aggressive removal of system topics
|
||||
if localTopicPartition.MaybeShutdownLocalPartitionForTopic(t.Name) {
|
||||
b.localTopicManager.RemoveLocalPartition(t, p)
|
||||
b.localTopicManager.RemoveLocalPartition(t, localTopicPartition)
|
||||
glog.V(0).Infof("Removed local topic %v partition %v", initMessage.Topic, initMessage.Partition)
|
||||
}
|
||||
}()
|
||||
@@ -139,10 +120,6 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
|
||||
// send a hello message
|
||||
stream.Send(&mq_pb.PublishMessageResponse{})
|
||||
|
||||
defer func() {
|
||||
isClosed = true
|
||||
}()
|
||||
|
||||
// process each published messages
|
||||
for {
|
||||
// receive a message
|
||||
@@ -179,16 +156,22 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
|
||||
// The control message should still be sent to the follower
|
||||
// to avoid timing issue when ack messages.
|
||||
|
||||
// Send to the local partition with offset assignment
|
||||
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
|
||||
|
||||
// Create offset assignment function for this partition
|
||||
assignOffsetFn := func() (int64, error) {
|
||||
return b.offsetManager.AssignOffset(t, p)
|
||||
if localTopicPartition.IsFenced() {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is fenced by another broker", t, p))
|
||||
return stream.Send(response)
|
||||
}
|
||||
|
||||
// Use offset-aware publishing
|
||||
assignedOffset, err := localTopicPartition.PublishWithOffset(dataMessage, assignOffsetFn)
|
||||
assignedOffset, err := localTopicPartition.PublishWithOffset(dataMessage)
|
||||
if replica := localTopicPartition.Replica; replica != nil {
|
||||
// acked only once the follower holds it too
|
||||
if err == nil {
|
||||
err = replica.WaitAcked(assignedOffset)
|
||||
}
|
||||
if replicaErr := replica.Err(); replicaErr != nil {
|
||||
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, fmt.Sprintf("topic %v partition %v: %v", t, p, replicaErr))
|
||||
return stream.Send(response)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("topic %v partition %v publish error: %w", initMessage.Topic, initMessage.Partition, err)
|
||||
}
|
||||
@@ -267,6 +250,19 @@ func (b *MessageQueueBroker) GetPartitionRangeInfo(ctx context.Context, req *mq_
|
||||
t := topic.FromPbTopic(req.Topic)
|
||||
p := topic.FromPbPartition(req.Partition)
|
||||
|
||||
// A broker that no longer leads the partition would answer with its stale range.
|
||||
localPartition, err := b.GetOrGenerateLocalPartition(t, p)
|
||||
if err != nil {
|
||||
return &mq_pb.GetPartitionRangeInfoResponse{
|
||||
Error: fmt.Sprintf("partition not found: %v", err),
|
||||
}, nil
|
||||
}
|
||||
if localPartition == nil {
|
||||
return &mq_pb.GetPartitionRangeInfoResponse{
|
||||
Error: "partition not found",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Get offset information from the broker's internal method
|
||||
info, err := b.GetPartitionOffsetInfoInternal(t, p)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,152 +1,122 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/buffered_queue"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
type memBuffer struct {
|
||||
buf []byte
|
||||
startTime time.Time
|
||||
stopTime time.Time
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) (err error) {
|
||||
var req *mq_pb.PublishFollowMeRequest
|
||||
req, err = stream.Recv()
|
||||
// PublishFollowMe holds a leader's entries that are not stored yet, acking each,
|
||||
// until the leader closes the stream after storing everything.
|
||||
func (b *MessageQueueBroker) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) error {
|
||||
req, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
initMessage := req.GetInit()
|
||||
if initMessage == nil {
|
||||
init := req.GetInit()
|
||||
if init == nil {
|
||||
return fmt.Errorf("missing init message")
|
||||
}
|
||||
t, p := topic.FromPbTopic(init.Topic), topic.FromPbPartition(init.Partition)
|
||||
|
||||
// create an in-memory queue of buffered messages
|
||||
inMemoryBuffers := buffered_queue.NewBufferedQueue[memBuffer](4)
|
||||
logBuffer := b.buildFollowerLogBuffer(inMemoryBuffers)
|
||||
|
||||
lastFlushTsNs := time.Now().UnixNano()
|
||||
|
||||
// follow each published messages
|
||||
var held []*filer_pb.LogEntry
|
||||
acked := int64(-1)
|
||||
for {
|
||||
// receive a message
|
||||
req, err = stream.Recv()
|
||||
req, err := stream.Recv()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
break
|
||||
}
|
||||
glog.V(0).Infof("topic %v partition %v publish stream error: %v", initMessage.Topic, initMessage.Partition, err)
|
||||
break
|
||||
// the leader went without closing the stream, so it may not have stored these
|
||||
glog.Warningf("follow stream of %v %v from %s at epoch %d broke with %d unstored entries: %v", t, p, init.Leader, init.Epoch, len(held), err)
|
||||
b.takeOverPartition(t, p, init, held)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Process the received message
|
||||
if dataMessage := req.GetData(); dataMessage != nil {
|
||||
|
||||
// TODO: change this to DataMessage
|
||||
// log the message
|
||||
if addErr := logBuffer.AddToBuffer(dataMessage); addErr != nil {
|
||||
err = fmt.Errorf("failed to add message to log buffer: %w", addErr)
|
||||
glog.Errorf("Failed to add message to log buffer: %v", addErr)
|
||||
break
|
||||
}
|
||||
|
||||
// send back the ack
|
||||
if err := stream.Send(&mq_pb.PublishFollowMeResponse{
|
||||
AckTsNs: dataMessage.TsNs,
|
||||
}); err != nil {
|
||||
glog.Errorf("Error sending response %v: %v", dataMessage, err)
|
||||
}
|
||||
// println("ack", string(dataMessage.Key), dataMessage.TsNs)
|
||||
} else if closeMessage := req.GetClose(); closeMessage != nil {
|
||||
glog.V(0).Infof("topic %v partition %v publish stream closed: %v", initMessage.Topic, initMessage.Partition, closeMessage)
|
||||
break
|
||||
} else if flushMessage := req.GetFlush(); flushMessage != nil {
|
||||
glog.V(0).Infof("topic %v partition %v publish stream flushed: %v", initMessage.Topic, initMessage.Partition, flushMessage)
|
||||
|
||||
lastFlushTsNs = flushMessage.TsNs
|
||||
|
||||
// drop already flushed messages
|
||||
for mem, found := inMemoryBuffers.PeekHead(); found; mem, found = inMemoryBuffers.PeekHead() {
|
||||
if mem.stopTime.UnixNano() <= flushMessage.TsNs {
|
||||
inMemoryBuffers.Dequeue()
|
||||
// println("dropping flushed messages: ", mem.startTime.UnixNano(), mem.stopTime.UnixNano(), len(mem.buf))
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
glog.Errorf("unknown message: %v", req)
|
||||
}
|
||||
}
|
||||
|
||||
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
|
||||
|
||||
logBuffer.ShutdownLogBuffer()
|
||||
// wait until all messages are sent to inMemoryBuffers
|
||||
for !logBuffer.IsAllFlushed() {
|
||||
time.Sleep(113 * time.Millisecond)
|
||||
}
|
||||
|
||||
partitionDir := topic.PartitionDir(t, p)
|
||||
|
||||
// flush the remaining messages
|
||||
inMemoryBuffers.CloseInput()
|
||||
for mem, found := inMemoryBuffers.Dequeue(); found; mem, found = inMemoryBuffers.Dequeue() {
|
||||
if len(mem.buf) == 0 {
|
||||
switch m := req.Message.(type) {
|
||||
case *mq_pb.PublishFollowMeRequest_Entry:
|
||||
held = append(held, m.Entry)
|
||||
acked = m.Entry.Offset
|
||||
case *mq_pb.PublishFollowMeRequest_Heartbeat:
|
||||
case *mq_pb.PublishFollowMeRequest_Flush:
|
||||
held = dropStored(held, m.Flush.Offset)
|
||||
continue
|
||||
case *mq_pb.PublishFollowMeRequest_Close:
|
||||
return nil
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
startTime, stopTime := mem.startTime.UTC(), mem.stopTime.UTC()
|
||||
|
||||
if stopTime.UnixNano() <= lastFlushTsNs {
|
||||
glog.V(0).Infof("dropping remaining data at %v %v", t, p)
|
||||
continue
|
||||
if err := stream.Send(&mq_pb.PublishFollowMeResponse{AckOffset: acked}); err != nil {
|
||||
glog.Warningf("follow stream of %v %v from %s at epoch %d failed to ack with %d unstored entries: %v", t, p, init.Leader, init.Epoch, len(held), err)
|
||||
b.takeOverPartition(t, p, init, held)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO trim data earlier than lastFlushTsNs
|
||||
|
||||
targetFile := fmt.Sprintf("%s/%s", partitionDir, startTime.Format(topic.TIME_FORMAT))
|
||||
|
||||
for {
|
||||
if err := b.appendToFile(targetFile, mem.buf); err != nil {
|
||||
glog.V(0).Infof("metadata log write failed %s: %v", targetFile, err)
|
||||
time.Sleep(737 * time.Millisecond)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
glog.V(0).Infof("flushed remaining data at %v to %s size %d", mem.stopTime.UnixNano(), targetFile, len(mem.buf))
|
||||
}
|
||||
|
||||
glog.V(0).Infof("shut down follower for %v %v", t, p)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) buildFollowerLogBuffer(inMemoryBuffers *buffered_queue.BufferedQueue[memBuffer]) *log_buffer.LogBuffer {
|
||||
lb := log_buffer.NewLogBuffer("follower",
|
||||
5*time.Second, func(logBuffer *log_buffer.LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
|
||||
if len(buf) == 0 {
|
||||
// dropStored keeps the entries above offset; held is in offset order.
|
||||
func dropStored(held []*filer_pb.LogEntry, offset int64) []*filer_pb.LogEntry {
|
||||
i := sort.Search(len(held), func(i int) bool { return held[i].Offset > offset })
|
||||
return append([]*filer_pb.LogEntry(nil), held[i:]...)
|
||||
}
|
||||
|
||||
// takeOverPartition moves the fence from a lost leader to this follower, stores the
|
||||
// entries the leader had not, and ends the generation. Every acked entry is here,
|
||||
// since the leader acks only what this follower holds.
|
||||
func (b *MessageQueueBroker) takeOverPartition(t topic.Topic, p topic.Partition, init *mq_pb.PublishFollowMeRequest_InitMessage, held []*filer_pb.LogEntry) {
|
||||
ctx := context.Background()
|
||||
if b.ctx != nil {
|
||||
ctx = b.ctx
|
||||
}
|
||||
// these entries may be the only copy left, so a filer error is retried until the fence moves on
|
||||
var fence *topic.PartitionFence
|
||||
if err := retryLogWrite(ctx, topic.PartitionFencePath(t, p), func() (err error) {
|
||||
fence, err = b.takeOverPartitionFence(ctx, t, p, init.Epoch, init.Leader)
|
||||
return err
|
||||
}); err != nil {
|
||||
glog.V(0).Infof("not taking over %v %v epoch %d: %v", t, p, init.Epoch, err)
|
||||
return
|
||||
}
|
||||
stopRenewing := b.keepFenceRenewed(fence)
|
||||
defer stopRenewing()
|
||||
// with the fence moved, nothing else adds to what is stored
|
||||
var stored mq.OffsetRange
|
||||
if err := retryLogWrite(ctx, topic.PartitionDir(t, p), func() (err error) {
|
||||
stored, err = b.getOffsetRangeFromChunkMetadata(t, p)
|
||||
return err
|
||||
}); err != nil {
|
||||
glog.Errorf("take over %v %v epoch %d: %v", t, p, init.Epoch, err)
|
||||
return
|
||||
}
|
||||
fence.NoteLogFileTime(stored.NewestLogFileTime())
|
||||
_, highWaterMark := stored.Bounds()
|
||||
held = dropStored(held, highWaterMark-1)
|
||||
if len(held) > 0 {
|
||||
var data []byte
|
||||
minTsNs, maxTsNs := held[0].TsNs, held[0].TsNs
|
||||
for _, entry := range held {
|
||||
encoded, err := entry.MarshalVT()
|
||||
if err != nil {
|
||||
glog.Errorf("take over %v %v epoch %d: %v", t, p, init.Epoch, err)
|
||||
return
|
||||
}
|
||||
inMemoryBuffers.Enqueue(memBuffer{
|
||||
buf: buf,
|
||||
startTime: startTime,
|
||||
stopTime: stopTime,
|
||||
})
|
||||
glog.V(0).Infof("queue up %d~%d size %d", startTime.UnixNano(), stopTime.UnixNano(), len(buf))
|
||||
}, nil, func() {
|
||||
})
|
||||
return lb
|
||||
data = binary.BigEndian.AppendUint32(data, uint32(len(encoded)))
|
||||
data = append(data, encoded...)
|
||||
minTsNs, maxTsNs = min(minTsNs, entry.TsNs), max(maxTsNs, entry.TsNs)
|
||||
}
|
||||
first, last := held[0], held[len(held)-1]
|
||||
startTime, stopTime := time.Unix(0, minTsNs).UTC(), time.Unix(0, maxTsNs).UTC()
|
||||
targetFile := topic.PartitionDir(t, p) + "/" + topic.LogFileName(fence.LogFileTime(startTime), first.Offset)
|
||||
if err := b.writeLogFile(ctx, fence, targetFile, startTime, stopTime, data, first.Offset, last.Offset); err != nil {
|
||||
glog.Errorf("take over %v %v epoch %d: store offsets %d-%d: %v", t, p, init.Epoch, first.Offset, last.Offset, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
glog.V(0).Infof("took over %v %v epoch %d from %s, stored %d entries", t, p, init.Epoch, init.Leader, len(held))
|
||||
stopRenewing()
|
||||
b.sealAndReportGeneration(ctx, t, p, fence, init.Epoch)
|
||||
}
|
||||
@@ -280,8 +280,7 @@ func (b *MessageQueueBroker) findBrokerForTopicPartition(topic *schema_pb.Topic,
|
||||
|
||||
if !b.isLockOwner() {
|
||||
// Redirect to balancer to get topic broker assignments
|
||||
balancerAddress := pb.ServerAddress(b.lockAsBalancer.LockOwner())
|
||||
err = b.withBrokerClient(false, balancerAddress, func(client mq_pb.SeaweedMessagingClient) error {
|
||||
err = b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
|
||||
lookupResp, err = client.LookupTopicBrokers(ctx, lookupReq)
|
||||
return err
|
||||
})
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// GrpcServerOptions turns a panic in one broker RPC into an error for that
|
||||
// call, so it cannot take down the process the broker runs in.
|
||||
func GrpcServerOptions() []grpc.ServerOption {
|
||||
return []grpc.ServerOption{
|
||||
grpc.ChainUnaryInterceptor(recoverUnary),
|
||||
grpc.ChainStreamInterceptor(recoverStream),
|
||||
}
|
||||
}
|
||||
|
||||
func recoverUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
|
||||
defer recoverRpc(info.FullMethod, &err)
|
||||
return handler(ctx, req)
|
||||
}
|
||||
|
||||
func recoverStream(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
|
||||
defer recoverRpc(info.FullMethod, &err)
|
||||
return handler(srv, ss)
|
||||
}
|
||||
|
||||
func recoverRpc(method string, err *error) {
|
||||
if r := recover(); r != nil {
|
||||
glog.Errorf("broker %s panic: %v\n%s", method, r, debug.Stack())
|
||||
*err = status.Errorf(codes.Internal, "broker %s: internal error", method)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestBrokerRpcPanicBecomesError(t *testing.T) {
|
||||
_, err := recoverUnary(context.Background(), nil, &grpc.UnaryServerInfo{FullMethod: "/test/Unary"},
|
||||
func(ctx context.Context, req any) (any, error) {
|
||||
var p *mq_pb.BrokerPartitionAssignment
|
||||
return p.LeaderBroker, nil
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, codes.Internal, status.Code(err))
|
||||
|
||||
err = recoverStream(nil, nil, &grpc.StreamServerInfo{FullMethod: "/test/Stream"},
|
||||
func(srv any, stream grpc.ServerStream) error {
|
||||
panic("boom")
|
||||
})
|
||||
assert.Equal(t, codes.Internal, status.Code(err))
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/sub_coordinator"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
@@ -68,45 +67,10 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
|
||||
glog.V(0).Infof("Subscriber %s on %v %v disconnected, sent %d", clientName, t, partition, counter)
|
||||
// Use topic-aware shutdown logic to prevent aggressive removal of system topics
|
||||
if localTopicPartition.MaybeShutdownLocalPartitionForTopic(t.Name) {
|
||||
b.localTopicManager.RemoveLocalPartition(t, partition)
|
||||
b.localTopicManager.RemoveLocalPartition(t, localTopicPartition)
|
||||
}
|
||||
}()
|
||||
|
||||
// connect to the follower
|
||||
var subscribeFollowMeStream mq_pb.SeaweedMessaging_SubscribeFollowMeClient
|
||||
glog.V(0).Infof("follower broker: %v", req.GetInit().FollowerBroker)
|
||||
if req.GetInit().FollowerBroker != "" {
|
||||
follower := req.GetInit().FollowerBroker
|
||||
if followerGrpcConnection, err := pb.GrpcDial(ctx, follower, true, b.grpcDialOption); err != nil {
|
||||
return fmt.Errorf("fail to dial %s: %v", follower, err)
|
||||
} else {
|
||||
defer func() {
|
||||
println("closing SubscribeFollowMe connection", follower)
|
||||
if subscribeFollowMeStream != nil {
|
||||
subscribeFollowMeStream.CloseSend()
|
||||
}
|
||||
// followerGrpcConnection.Close()
|
||||
}()
|
||||
followerClient := mq_pb.NewSeaweedMessagingClient(followerGrpcConnection)
|
||||
if subscribeFollowMeStream, err = followerClient.SubscribeFollowMe(ctx); err != nil {
|
||||
return fmt.Errorf("fail to subscribe to %s: %v", follower, err)
|
||||
} else {
|
||||
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
|
||||
Message: &mq_pb.SubscribeFollowMeRequest_Init{
|
||||
Init: &mq_pb.SubscribeFollowMeRequest_InitMessage{
|
||||
Topic: req.GetInit().Topic,
|
||||
Partition: req.GetInit().GetPartitionOffset().Partition,
|
||||
ConsumerGroup: req.GetInit().ConsumerGroup,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
return fmt.Errorf("fail to send init to %s: %v", follower, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
glog.V(0).Infof("follower %s connected", follower)
|
||||
}
|
||||
|
||||
// Channel to handle seek requests - signals Subscribe loop to restart from new offset
|
||||
seekChan := make(chan *mq_pb.SubscribeMessageRequest_SeekMessage, 1)
|
||||
|
||||
@@ -162,19 +126,8 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
|
||||
// Update acknowledged offset and last seen time for this subscriber when it sends an ack
|
||||
subscriber.UpdateAckedOffset(currentLastOffset)
|
||||
// fmt.Printf("%+v recv (%s,%d), oldest %d\n", partition, string(ack.GetAck().Key), ack.GetAck().TsNs, currentLastOffset)
|
||||
if subscribeFollowMeStream != nil && currentLastOffset > lastOffset {
|
||||
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
|
||||
Message: &mq_pb.SubscribeFollowMeRequest_Ack{
|
||||
Ack: &mq_pb.SubscribeFollowMeRequest_AckMessage{
|
||||
TsNs: currentLastOffset,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
glog.Errorf("Error sending ack to follower: %v", err)
|
||||
break
|
||||
}
|
||||
if currentLastOffset > lastOffset {
|
||||
lastOffset = currentLastOffset
|
||||
// fmt.Printf("%+v forwarding ack %d\n", partition, lastOffset)
|
||||
}
|
||||
}
|
||||
if lastOffset > 0 {
|
||||
@@ -183,17 +136,6 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
|
||||
glog.Errorf("saveConsumerGroupOffset partition %v lastOffset %d: %v", partition, lastOffset, err)
|
||||
}
|
||||
}
|
||||
if subscribeFollowMeStream != nil {
|
||||
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
|
||||
Message: &mq_pb.SubscribeFollowMeRequest_Close{
|
||||
Close: &mq_pb.SubscribeFollowMeRequest_CloseMessage{},
|
||||
},
|
||||
}); err != nil {
|
||||
if err != io.EOF {
|
||||
glog.Errorf("Error sending close to follower: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Create a goroutine to handle context cancellation and wake up the condition variable
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
// SubscribeWithOffset handles subscription requests with offset-based positioning
|
||||
// TODO: This extends the broker with offset-aware subscription support
|
||||
// ASSUMPTION: This will eventually be integrated into the main SubscribeMessage method
|
||||
func (b *MessageQueueBroker) SubscribeWithOffset(
|
||||
ctx context.Context,
|
||||
req *mq_pb.SubscribeMessageRequest,
|
||||
stream mq_pb.SeaweedMessaging_SubscribeMessageServer,
|
||||
offsetType schema_pb.OffsetType,
|
||||
startOffset int64,
|
||||
) error {
|
||||
|
||||
initMessage := req.GetInit()
|
||||
if initMessage == nil {
|
||||
return fmt.Errorf("missing init message")
|
||||
}
|
||||
|
||||
// Extract partition information from the request
|
||||
t := topic.FromPbTopic(initMessage.Topic)
|
||||
|
||||
// Get partition from the request's partition_offset field
|
||||
if initMessage.PartitionOffset == nil || initMessage.PartitionOffset.Partition == nil {
|
||||
return fmt.Errorf("missing partition information in request")
|
||||
}
|
||||
|
||||
// Use the partition information from the request
|
||||
p := topic.Partition{
|
||||
RingSize: initMessage.PartitionOffset.Partition.RingSize,
|
||||
RangeStart: initMessage.PartitionOffset.Partition.RangeStart,
|
||||
RangeStop: initMessage.PartitionOffset.Partition.RangeStop,
|
||||
UnixTimeNs: initMessage.PartitionOffset.Partition.UnixTimeNs,
|
||||
}
|
||||
|
||||
// Create offset-based subscription
|
||||
subscriptionID := fmt.Sprintf("%s-%s-%d", initMessage.ConsumerGroup, initMessage.ConsumerId, startOffset)
|
||||
subscription, err := b.offsetManager.CreateSubscription(subscriptionID, t, p, offsetType, startOffset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create offset subscription: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := b.offsetManager.CloseSubscription(subscriptionID); closeErr != nil {
|
||||
glog.V(0).Infof("Failed to close subscription %s: %v", subscriptionID, closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
// Get local partition for reading
|
||||
localTopicPartition, err := b.GetOrGenerateLocalPartition(t, p)
|
||||
if err != nil {
|
||||
return fmt.Errorf("topic %v partition %v not found: %v", t, p, err)
|
||||
}
|
||||
|
||||
// Subscribe to messages using offset-based positioning
|
||||
return b.subscribeWithOffsetSubscription(ctx, localTopicPartition, subscription, stream, initMessage)
|
||||
}
|
||||
|
||||
// subscribeWithOffsetSubscription handles the actual message consumption with offset tracking
|
||||
func (b *MessageQueueBroker) subscribeWithOffsetSubscription(
|
||||
ctx context.Context,
|
||||
localPartition *topic.LocalPartition,
|
||||
subscription *offset.OffsetSubscription,
|
||||
stream mq_pb.SeaweedMessaging_SubscribeMessageServer,
|
||||
initMessage *mq_pb.SubscribeMessageRequest_InitMessage,
|
||||
) error {
|
||||
|
||||
clientName := fmt.Sprintf("%s-%s", initMessage.ConsumerGroup, initMessage.ConsumerId)
|
||||
|
||||
// TODO: Implement offset-based message reading
|
||||
// ASSUMPTION: For now, we'll use the existing subscription mechanism and track offsets separately
|
||||
// This should be replaced with proper offset-based reading from storage
|
||||
|
||||
// Convert the subscription's current offset to a proper MessagePosition
|
||||
startPosition, err := b.convertOffsetToMessagePosition(subscription)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert offset to message position: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("[%s] Starting Subscribe for topic %s partition %d-%d at offset %d",
|
||||
clientName, subscription.TopicName, subscription.Partition.RangeStart, subscription.Partition.RangeStop, subscription.CurrentOffset)
|
||||
|
||||
return localPartition.Subscribe(clientName,
|
||||
startPosition,
|
||||
func() bool {
|
||||
// Check if context is cancelled (client disconnected)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.V(0).Infof("[%s] Context cancelled, stopping", clientName)
|
||||
return false
|
||||
default:
|
||||
}
|
||||
|
||||
// Check if subscription is still active and not at end
|
||||
if !subscription.IsActive {
|
||||
glog.V(0).Infof("[%s] Subscription not active, stopping", clientName)
|
||||
return false
|
||||
}
|
||||
|
||||
atEnd, err := subscription.IsAtEnd()
|
||||
if err != nil {
|
||||
glog.V(0).Infof("[%s] Error checking if subscription at end: %v", clientName, err)
|
||||
return false
|
||||
}
|
||||
|
||||
if atEnd {
|
||||
glog.V(4).Infof("[%s] At end of subscription, stopping", clientName)
|
||||
return false
|
||||
}
|
||||
|
||||
// Add a small sleep to avoid CPU busy-wait when checking for new data
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
return true
|
||||
},
|
||||
func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
// Check if this message matches our offset requirements
|
||||
currentOffset := subscription.GetNextOffset()
|
||||
|
||||
if logEntry.Offset < currentOffset {
|
||||
// Skip messages before our current offset
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Send message to client
|
||||
if err := stream.Send(&mq_pb.SubscribeMessageResponse{
|
||||
Message: &mq_pb.SubscribeMessageResponse_Data{
|
||||
Data: &mq_pb.DataMessage{
|
||||
Key: logEntry.Key,
|
||||
Value: logEntry.Data,
|
||||
TsNs: logEntry.TsNs,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
glog.Errorf("Error sending data to %s: %v", clientName, err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Advance subscription offset
|
||||
subscription.AdvanceOffset()
|
||||
|
||||
// Check context for cancellation
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return true, ctx.Err()
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// GetSubscriptionInfo returns information about an active subscription
|
||||
func (b *MessageQueueBroker) GetSubscriptionInfo(subscriptionID string) (map[string]interface{}, error) {
|
||||
subscription, err := b.offsetManager.GetSubscription(subscriptionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lag, err := subscription.GetLag()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
atEnd, err := subscription.IsAtEnd()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"subscription_id": subscription.ID,
|
||||
"start_offset": subscription.StartOffset,
|
||||
"current_offset": subscription.CurrentOffset,
|
||||
"offset_type": subscription.OffsetType.String(),
|
||||
"is_active": subscription.IsActive,
|
||||
"lag": lag,
|
||||
"at_end": atEnd,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListActiveSubscriptions returns information about all active subscriptions
|
||||
func (b *MessageQueueBroker) ListActiveSubscriptions() ([]map[string]interface{}, error) {
|
||||
subscriptions, err := b.offsetManager.ListActiveSubscriptions()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := make([]map[string]interface{}, len(subscriptions))
|
||||
for i, subscription := range subscriptions {
|
||||
lag, _ := subscription.GetLag()
|
||||
atEnd, _ := subscription.IsAtEnd()
|
||||
|
||||
result[i] = map[string]interface{}{
|
||||
"subscription_id": subscription.ID,
|
||||
"start_offset": subscription.StartOffset,
|
||||
"current_offset": subscription.CurrentOffset,
|
||||
"offset_type": subscription.OffsetType.String(),
|
||||
"is_active": subscription.IsActive,
|
||||
"lag": lag,
|
||||
"at_end": atEnd,
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SeekSubscription seeks an existing subscription to a specific offset
|
||||
func (b *MessageQueueBroker) SeekSubscription(subscriptionID string, offset int64) error {
|
||||
subscription, err := b.offsetManager.GetSubscription(subscriptionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return subscription.SeekToOffset(offset)
|
||||
}
|
||||
|
||||
// convertOffsetToMessagePosition converts a subscription's current offset to a MessagePosition for log_buffer
|
||||
func (b *MessageQueueBroker) convertOffsetToMessagePosition(subscription *offset.OffsetSubscription) (log_buffer.MessagePosition, error) {
|
||||
currentOffset := subscription.GetNextOffset()
|
||||
|
||||
// Handle special offset cases
|
||||
switch subscription.OffsetType {
|
||||
case schema_pb.OffsetType_RESET_TO_EARLIEST:
|
||||
return log_buffer.NewMessagePosition(1, -3), nil
|
||||
|
||||
case schema_pb.OffsetType_RESET_TO_LATEST:
|
||||
return log_buffer.NewMessagePosition(time.Now().UnixNano(), -4), nil
|
||||
|
||||
case schema_pb.OffsetType_EXACT_OFFSET:
|
||||
// Use proper offset-based positioning that provides consistent results
|
||||
// This uses the same approach as the main subscription handler in broker_grpc_sub.go
|
||||
return log_buffer.NewMessagePositionFromOffset(currentOffset), nil
|
||||
|
||||
case schema_pb.OffsetType_EXACT_TS_NS:
|
||||
// For exact timestamps, use the timestamp directly
|
||||
return log_buffer.NewMessagePosition(currentOffset, -2), nil
|
||||
|
||||
default:
|
||||
// Default to starting from current time for unknown offset types
|
||||
return log_buffer.NewMessagePosition(time.Now().UnixNano(), -2), nil
|
||||
}
|
||||
}
|
||||
@@ -1,707 +0,0 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
func TestConvertOffsetToMessagePosition(t *testing.T) {
|
||||
broker := &MessageQueueBroker{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
offsetType schema_pb.OffsetType
|
||||
currentOffset int64
|
||||
expectedBatch int64
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
name: "reset to earliest",
|
||||
offsetType: schema_pb.OffsetType_RESET_TO_EARLIEST,
|
||||
currentOffset: 0,
|
||||
expectedBatch: -3,
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "reset to latest",
|
||||
offsetType: schema_pb.OffsetType_RESET_TO_LATEST,
|
||||
currentOffset: 0,
|
||||
expectedBatch: -4,
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "exact offset zero",
|
||||
offsetType: schema_pb.OffsetType_EXACT_OFFSET,
|
||||
currentOffset: 0,
|
||||
expectedBatch: 0, // NewMessagePositionFromOffset stores offset directly in Offset field
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "exact offset non-zero",
|
||||
offsetType: schema_pb.OffsetType_EXACT_OFFSET,
|
||||
currentOffset: 100,
|
||||
expectedBatch: 100, // NewMessagePositionFromOffset stores offset directly in Offset field
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "exact timestamp",
|
||||
offsetType: schema_pb.OffsetType_EXACT_TS_NS,
|
||||
currentOffset: 50,
|
||||
expectedBatch: -2,
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create a mock subscription
|
||||
subscription := &offset.OffsetSubscription{
|
||||
ID: "test-subscription",
|
||||
CurrentOffset: tt.currentOffset,
|
||||
OffsetType: tt.offsetType,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
position, err := broker.convertOffsetToMessagePosition(subscription)
|
||||
|
||||
if tt.expectError && err == nil {
|
||||
t.Error("Expected error but got none")
|
||||
return
|
||||
}
|
||||
|
||||
if !tt.expectError && err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if position.Offset != tt.expectedBatch {
|
||||
t.Errorf("Expected batch index %d, got %d", tt.expectedBatch, position.Offset)
|
||||
}
|
||||
|
||||
// Verify that the timestamp is reasonable (not zero for most cases)
|
||||
// Note: EXACT_OFFSET uses epoch time (zero) with NewMessagePositionFromOffset
|
||||
if tt.offsetType != schema_pb.OffsetType_RESET_TO_EARLIEST &&
|
||||
tt.offsetType != schema_pb.OffsetType_EXACT_OFFSET &&
|
||||
position.Time.IsZero() {
|
||||
t.Error("Expected non-zero timestamp")
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertOffsetToMessagePosition_OffsetEncoding(t *testing.T) {
|
||||
broker := &MessageQueueBroker{}
|
||||
|
||||
// Test that offset-based positions encode the offset correctly in Offset field
|
||||
testCases := []struct {
|
||||
offset int64
|
||||
expectedBatch int64
|
||||
expectedIsSentinel bool // Should timestamp be the offset sentinel value?
|
||||
}{
|
||||
{10, 10, true},
|
||||
{100, 100, true},
|
||||
{0, 0, true},
|
||||
{42, 42, true},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(fmt.Sprintf("offset_%d", tc.offset), func(t *testing.T) {
|
||||
subscription := &offset.OffsetSubscription{
|
||||
ID: fmt.Sprintf("test-%d", tc.offset),
|
||||
CurrentOffset: tc.offset,
|
||||
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
pos, err := broker.convertOffsetToMessagePosition(subscription)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// Check Offset encoding
|
||||
if pos.Offset != tc.expectedBatch {
|
||||
t.Errorf("Expected batch index %d, got %d", tc.expectedBatch, pos.Offset)
|
||||
}
|
||||
|
||||
// Verify the offset can be extracted correctly using IsOffsetBased/GetOffset
|
||||
if !pos.IsOffsetBased {
|
||||
t.Error("Position should be detected as offset-based")
|
||||
}
|
||||
|
||||
// Check that IsOffsetBased flag is set correctly
|
||||
if tc.expectedIsSentinel && !pos.IsOffsetBased {
|
||||
t.Error("Expected offset-based position but IsOffsetBased=false")
|
||||
}
|
||||
|
||||
if extractedOffset := pos.GetOffset(); extractedOffset != tc.offset {
|
||||
t.Errorf("Expected extracted offset %d, got %d", tc.offset, extractedOffset)
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertOffsetToMessagePosition_ConsistentResults(t *testing.T) {
|
||||
broker := &MessageQueueBroker{}
|
||||
|
||||
subscription := &offset.OffsetSubscription{
|
||||
ID: "consistent-test",
|
||||
CurrentOffset: 42,
|
||||
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
// Call multiple times within a short period
|
||||
positions := make([]log_buffer.MessagePosition, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
pos, err := broker.convertOffsetToMessagePosition(subscription)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on iteration %d: %v", i, err)
|
||||
}
|
||||
positions[i] = pos
|
||||
time.Sleep(1 * time.Millisecond) // Small delay
|
||||
}
|
||||
|
||||
// All positions should have the same Offset
|
||||
for i := 1; i < len(positions); i++ {
|
||||
if positions[i].Offset != positions[0].Offset {
|
||||
t.Errorf("Inconsistent Offset: %d vs %d", positions[0].Offset, positions[i].Offset)
|
||||
}
|
||||
}
|
||||
|
||||
// With NewMessagePositionFromOffset, timestamps should be identical (zero time for offset-based)
|
||||
expectedTime := time.Time{}
|
||||
for i := 0; i < len(positions); i++ {
|
||||
if !positions[i].Time.Equal(expectedTime) {
|
||||
t.Errorf("Expected all timestamps to be sentinel time (%v), got %v at index %d",
|
||||
expectedTime, positions[i].Time, i)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestConvertOffsetToMessagePosition_FixVerification(t *testing.T) {
|
||||
// This test specifically verifies that the fix addresses the issue mentioned:
|
||||
// "The calculated timestamp for a given offset will change every time the function is called"
|
||||
|
||||
broker := &MessageQueueBroker{}
|
||||
|
||||
subscription := &offset.OffsetSubscription{
|
||||
ID: "fix-verification",
|
||||
CurrentOffset: 123,
|
||||
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
// Call the function multiple times with delays to simulate real-world usage
|
||||
var positions []log_buffer.MessagePosition
|
||||
var timestamps []int64
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
pos, err := broker.convertOffsetToMessagePosition(subscription)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on iteration %d: %v", i, err)
|
||||
}
|
||||
positions = append(positions, pos)
|
||||
timestamps = append(timestamps, pos.Time.UnixNano())
|
||||
time.Sleep(2 * time.Millisecond) // Small delay to ensure time progression
|
||||
}
|
||||
|
||||
// Verify ALL timestamps are identical (no time-based variance)
|
||||
expectedTimestamp := timestamps[0]
|
||||
for i, ts := range timestamps {
|
||||
if ts != expectedTimestamp {
|
||||
t.Errorf("Timestamp variance detected at call %d: expected %d, got %d", i, expectedTimestamp, ts)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify ALL Offset values are identical
|
||||
expectedBatch := positions[0].Offset
|
||||
for i, pos := range positions {
|
||||
if pos.Offset != expectedBatch {
|
||||
t.Errorf("Offset variance detected at call %d: expected %d, got %d", i, expectedBatch, pos.Offset)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the offset can be consistently extracted
|
||||
expectedOffset := subscription.CurrentOffset
|
||||
for i, pos := range positions {
|
||||
if extractedOffset := pos.GetOffset(); extractedOffset != expectedOffset {
|
||||
t.Errorf("Extracted offset variance at call %d: expected %d, got %d", i, expectedOffset, extractedOffset)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPartitionIdentityConsistency(t *testing.T) {
|
||||
// Test that partition identity is preserved from request to avoid breaking offset manager keys
|
||||
|
||||
// Create a mock init message with specific partition info
|
||||
partition := &schema_pb.Partition{
|
||||
RingSize: 32,
|
||||
RangeStart: 0,
|
||||
RangeStop: 31,
|
||||
UnixTimeNs: 1234567890123456789, // Fixed timestamp
|
||||
}
|
||||
|
||||
initMessage := &mq_pb.SubscribeMessageRequest_InitMessage{
|
||||
ConsumerGroup: "test-group",
|
||||
ConsumerId: "test-consumer",
|
||||
PartitionOffset: &schema_pb.PartitionOffset{
|
||||
Partition: partition,
|
||||
},
|
||||
}
|
||||
|
||||
// Simulate the partition creation logic from SubscribeWithOffset
|
||||
p := topic.Partition{
|
||||
RingSize: initMessage.PartitionOffset.Partition.RingSize,
|
||||
RangeStart: initMessage.PartitionOffset.Partition.RangeStart,
|
||||
RangeStop: initMessage.PartitionOffset.Partition.RangeStop,
|
||||
UnixTimeNs: initMessage.PartitionOffset.Partition.UnixTimeNs,
|
||||
}
|
||||
|
||||
// Verify that the partition preserves the original UnixTimeNs
|
||||
if p.UnixTimeNs != partition.UnixTimeNs {
|
||||
t.Errorf("Partition UnixTimeNs not preserved: expected %d, got %d",
|
||||
partition.UnixTimeNs, p.UnixTimeNs)
|
||||
}
|
||||
|
||||
// Verify partition key consistency
|
||||
expectedKey := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
|
||||
partition.RingSize, partition.RangeStart, partition.RangeStop, partition.UnixTimeNs)
|
||||
|
||||
actualKey := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
|
||||
p.RingSize, p.RangeStart, p.RangeStop, p.UnixTimeNs)
|
||||
|
||||
if actualKey != expectedKey {
|
||||
t.Errorf("Partition key mismatch: expected %s, got %s", expectedKey, actualKey)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBrokerOffsetManager_GetSubscription_Fixed(t *testing.T) {
|
||||
// Test that GetSubscription now works correctly after the fix
|
||||
|
||||
storage := NewInMemoryOffsetStorageForTesting()
|
||||
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
|
||||
|
||||
// Create test topic and partition
|
||||
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
|
||||
testPartition := topic.Partition{
|
||||
RingSize: 32,
|
||||
RangeStart: 0,
|
||||
RangeStop: 31,
|
||||
UnixTimeNs: time.Now().UnixNano(),
|
||||
}
|
||||
|
||||
// Test getting non-existent subscription
|
||||
_, err := offsetManager.GetSubscription("non-existent")
|
||||
if err == nil {
|
||||
t.Error("Expected error for non-existent subscription")
|
||||
}
|
||||
|
||||
// Create a subscription
|
||||
subscriptionID := "test-subscription-fixed"
|
||||
subscription, err := offsetManager.CreateSubscription(
|
||||
subscriptionID,
|
||||
testTopic,
|
||||
testPartition,
|
||||
schema_pb.OffsetType_RESET_TO_EARLIEST,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create subscription: %v", err)
|
||||
}
|
||||
|
||||
// Test getting existing subscription (this should now work)
|
||||
retrievedSub, err := offsetManager.GetSubscription(subscriptionID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetSubscription failed after fix: %v", err)
|
||||
}
|
||||
|
||||
if retrievedSub.ID != subscription.ID {
|
||||
t.Errorf("Expected subscription ID %s, got %s", subscription.ID, retrievedSub.ID)
|
||||
}
|
||||
|
||||
if retrievedSub.OffsetType != subscription.OffsetType {
|
||||
t.Errorf("Expected offset type %v, got %v", subscription.OffsetType, retrievedSub.OffsetType)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBrokerOffsetManager_ListActiveSubscriptions_Fixed(t *testing.T) {
|
||||
// Test that ListActiveSubscriptions now works correctly after the fix
|
||||
|
||||
storage := NewInMemoryOffsetStorageForTesting()
|
||||
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
|
||||
|
||||
// Create test topic and partition
|
||||
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
|
||||
testPartition := topic.Partition{
|
||||
RingSize: 32,
|
||||
RangeStart: 0,
|
||||
RangeStop: 31,
|
||||
UnixTimeNs: time.Now().UnixNano(),
|
||||
}
|
||||
|
||||
// Initially should have no subscriptions
|
||||
subscriptions, err := offsetManager.ListActiveSubscriptions()
|
||||
if err != nil {
|
||||
t.Fatalf("ListActiveSubscriptions failed after fix: %v", err)
|
||||
}
|
||||
if len(subscriptions) != 0 {
|
||||
t.Errorf("Expected 0 subscriptions, got %d", len(subscriptions))
|
||||
}
|
||||
|
||||
// Create multiple subscriptions (use RESET types to avoid HWM validation issues)
|
||||
subscriptionIDs := []string{"sub-fixed-1", "sub-fixed-2", "sub-fixed-3"}
|
||||
offsetTypes := []schema_pb.OffsetType{
|
||||
schema_pb.OffsetType_RESET_TO_EARLIEST,
|
||||
schema_pb.OffsetType_RESET_TO_LATEST,
|
||||
schema_pb.OffsetType_RESET_TO_EARLIEST, // Changed from EXACT_OFFSET
|
||||
}
|
||||
|
||||
for i, subID := range subscriptionIDs {
|
||||
_, err := offsetManager.CreateSubscription(
|
||||
subID,
|
||||
testTopic,
|
||||
testPartition,
|
||||
offsetTypes[i],
|
||||
0, // Use 0 for all to avoid validation issues
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create subscription %s: %v", subID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// List all subscriptions (this should now work)
|
||||
subscriptions, err = offsetManager.ListActiveSubscriptions()
|
||||
if err != nil {
|
||||
t.Fatalf("ListActiveSubscriptions failed after fix: %v", err)
|
||||
}
|
||||
|
||||
if len(subscriptions) != len(subscriptionIDs) {
|
||||
t.Errorf("Expected %d subscriptions, got %d", len(subscriptionIDs), len(subscriptions))
|
||||
}
|
||||
|
||||
// Verify all subscriptions are active
|
||||
for _, sub := range subscriptions {
|
||||
if !sub.IsActive {
|
||||
t.Errorf("Subscription %s should be active", sub.ID)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestMessageQueueBroker_ListActiveSubscriptions_Fixed(t *testing.T) {
|
||||
// Test that the broker-level ListActiveSubscriptions now works correctly
|
||||
|
||||
storage := NewInMemoryOffsetStorageForTesting()
|
||||
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
|
||||
|
||||
broker := &MessageQueueBroker{
|
||||
offsetManager: offsetManager,
|
||||
}
|
||||
|
||||
// Create test topic and partition
|
||||
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
|
||||
testPartition := topic.Partition{
|
||||
RingSize: 32,
|
||||
RangeStart: 0,
|
||||
RangeStop: 31,
|
||||
UnixTimeNs: time.Now().UnixNano(),
|
||||
}
|
||||
|
||||
// Initially should have no subscriptions
|
||||
subscriptionInfos, err := broker.ListActiveSubscriptions()
|
||||
if err != nil {
|
||||
t.Fatalf("Broker ListActiveSubscriptions failed after fix: %v", err)
|
||||
}
|
||||
if len(subscriptionInfos) != 0 {
|
||||
t.Errorf("Expected 0 subscription infos, got %d", len(subscriptionInfos))
|
||||
}
|
||||
|
||||
// Create subscriptions with different offset types (use RESET types to avoid HWM validation issues)
|
||||
testCases := []struct {
|
||||
id string
|
||||
offsetType schema_pb.OffsetType
|
||||
startOffset int64
|
||||
}{
|
||||
{"broker-earliest-sub", schema_pb.OffsetType_RESET_TO_EARLIEST, 0},
|
||||
{"broker-latest-sub", schema_pb.OffsetType_RESET_TO_LATEST, 0},
|
||||
{"broker-reset-sub", schema_pb.OffsetType_RESET_TO_EARLIEST, 0}, // Changed from EXACT_OFFSET
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
_, err := broker.offsetManager.CreateSubscription(
|
||||
tc.id,
|
||||
testTopic,
|
||||
testPartition,
|
||||
tc.offsetType,
|
||||
tc.startOffset,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create subscription %s: %v", tc.id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// List subscription infos (this should now work)
|
||||
subscriptionInfos, err = broker.ListActiveSubscriptions()
|
||||
if err != nil {
|
||||
t.Fatalf("Broker ListActiveSubscriptions failed after fix: %v", err)
|
||||
}
|
||||
|
||||
if len(subscriptionInfos) != len(testCases) {
|
||||
t.Errorf("Expected %d subscription infos, got %d", len(testCases), len(subscriptionInfos))
|
||||
}
|
||||
|
||||
// Verify subscription info structure
|
||||
for _, info := range subscriptionInfos {
|
||||
// Check required fields
|
||||
requiredFields := []string{
|
||||
"subscription_id", "start_offset", "current_offset",
|
||||
"offset_type", "is_active", "lag", "at_end",
|
||||
}
|
||||
|
||||
for _, field := range requiredFields {
|
||||
if _, ok := info[field]; !ok {
|
||||
t.Errorf("Missing field %s in subscription info", field)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify is_active is true
|
||||
if isActive, ok := info["is_active"].(bool); !ok || !isActive {
|
||||
t.Errorf("Expected is_active to be true, got %v", info["is_active"])
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestSingleWriterPerPartitionCorrectness(t *testing.T) {
|
||||
// Test that demonstrates correctness under single-writer-per-partition model
|
||||
|
||||
// Simulate two brokers with separate offset managers but same partition
|
||||
storage1 := NewInMemoryOffsetStorageForTesting()
|
||||
storage2 := NewInMemoryOffsetStorageForTesting()
|
||||
|
||||
offsetManager1 := NewBrokerOffsetManagerWithStorage(storage1)
|
||||
offsetManager2 := NewBrokerOffsetManagerWithStorage(storage2)
|
||||
|
||||
broker1 := &MessageQueueBroker{offsetManager: offsetManager1}
|
||||
broker2 := &MessageQueueBroker{offsetManager: offsetManager2}
|
||||
|
||||
// Same partition identity (this is key for correctness)
|
||||
fixedTimestamp := time.Now().UnixNano()
|
||||
testTopic := topic.Topic{Namespace: "test", Name: "shared-topic"}
|
||||
testPartition := topic.Partition{
|
||||
RingSize: 32,
|
||||
RangeStart: 0,
|
||||
RangeStop: 31,
|
||||
UnixTimeNs: fixedTimestamp, // Same timestamp = same partition identity
|
||||
}
|
||||
|
||||
// Broker 1 is the leader for this partition - assigns offsets
|
||||
baseOffset, lastOffset, err := broker1.offsetManager.AssignBatchOffsets(testTopic, testPartition, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to assign offsets on broker1: %v", err)
|
||||
}
|
||||
|
||||
if baseOffset != 0 || lastOffset != 9 {
|
||||
t.Errorf("Expected offsets 0-9, got %d-%d", baseOffset, lastOffset)
|
||||
}
|
||||
|
||||
// Get HWM from leader
|
||||
hwm1, err := broker1.offsetManager.GetHighWaterMark(testTopic, testPartition)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get HWM from broker1: %v", err)
|
||||
}
|
||||
|
||||
if hwm1 != 10 {
|
||||
t.Errorf("Expected HWM 10 on leader, got %d", hwm1)
|
||||
}
|
||||
|
||||
// Broker 2 is a follower - should have HWM 0 (no local assignments)
|
||||
hwm2, err := broker2.offsetManager.GetHighWaterMark(testTopic, testPartition)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get HWM from broker2: %v", err)
|
||||
}
|
||||
|
||||
if hwm2 != 0 {
|
||||
t.Errorf("Expected HWM 0 on follower, got %d", hwm2)
|
||||
}
|
||||
|
||||
// Create subscription on leader (where offsets were assigned)
|
||||
subscription1, err := broker1.offsetManager.CreateSubscription(
|
||||
"leader-subscription",
|
||||
testTopic,
|
||||
testPartition,
|
||||
schema_pb.OffsetType_RESET_TO_EARLIEST,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create subscription on leader: %v", err)
|
||||
}
|
||||
|
||||
// Verify subscription can see the correct HWM
|
||||
lag1, err := subscription1.GetLag()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get lag on leader subscription: %v", err)
|
||||
}
|
||||
|
||||
if lag1 != 10 {
|
||||
t.Errorf("Expected lag 10 on leader subscription, got %d", lag1)
|
||||
}
|
||||
|
||||
// Create subscription on follower (should have different lag due to local HWM)
|
||||
subscription2, err := broker2.offsetManager.CreateSubscription(
|
||||
"follower-subscription",
|
||||
testTopic,
|
||||
testPartition,
|
||||
schema_pb.OffsetType_RESET_TO_EARLIEST,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create subscription on follower: %v", err)
|
||||
}
|
||||
|
||||
lag2, err := subscription2.GetLag()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get lag on follower subscription: %v", err)
|
||||
}
|
||||
|
||||
if lag2 != 0 {
|
||||
t.Errorf("Expected lag 0 on follower subscription (no local data), got %d", lag2)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestEndToEndWorkflowAfterFixes(t *testing.T) {
|
||||
// Test the complete workflow with all fixes applied
|
||||
|
||||
storage := NewInMemoryOffsetStorageForTesting()
|
||||
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
|
||||
|
||||
broker := &MessageQueueBroker{
|
||||
offsetManager: offsetManager,
|
||||
}
|
||||
|
||||
// Create test topic and partition with fixed timestamp
|
||||
fixedTimestamp := time.Now().UnixNano()
|
||||
testTopic := topic.Topic{Namespace: "test", Name: "e2e-topic"}
|
||||
testPartition := topic.Partition{
|
||||
RingSize: 32,
|
||||
RangeStart: 0,
|
||||
RangeStop: 31,
|
||||
UnixTimeNs: fixedTimestamp,
|
||||
}
|
||||
|
||||
subscriptionID := "e2e-test-sub"
|
||||
|
||||
// 1. Create subscription (use RESET_TO_EARLIEST to avoid HWM validation issues)
|
||||
subscription, err := broker.offsetManager.CreateSubscription(
|
||||
subscriptionID,
|
||||
testTopic,
|
||||
testPartition,
|
||||
schema_pb.OffsetType_RESET_TO_EARLIEST,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create subscription: %v", err)
|
||||
}
|
||||
|
||||
// 2. Verify GetSubscription works
|
||||
retrievedSub, err := broker.offsetManager.GetSubscription(subscriptionID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetSubscription failed: %v", err)
|
||||
}
|
||||
|
||||
if retrievedSub.ID != subscription.ID {
|
||||
t.Errorf("GetSubscription returned wrong subscription: expected %s, got %s",
|
||||
subscription.ID, retrievedSub.ID)
|
||||
}
|
||||
|
||||
// 3. Verify it appears in active list
|
||||
activeList, err := broker.ListActiveSubscriptions()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list active subscriptions: %v", err)
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, info := range activeList {
|
||||
if info["subscription_id"] == subscriptionID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("New subscription not found in active list")
|
||||
}
|
||||
|
||||
// 4. Get subscription info
|
||||
info, err := broker.GetSubscriptionInfo(subscriptionID)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get subscription info: %v", err)
|
||||
}
|
||||
|
||||
if info["subscription_id"] != subscriptionID {
|
||||
t.Errorf("Wrong subscription ID in info: expected %s, got %v", subscriptionID, info["subscription_id"])
|
||||
}
|
||||
|
||||
// 5. Assign some offsets to create data for seeking
|
||||
_, _, err = broker.offsetManager.AssignBatchOffsets(testTopic, testPartition, 50)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to assign offsets: %v", err)
|
||||
}
|
||||
|
||||
// 6. Seek subscription
|
||||
newOffset := int64(42)
|
||||
err = broker.SeekSubscription(subscriptionID, newOffset)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to seek subscription: %v", err)
|
||||
}
|
||||
|
||||
// 7. Verify seek worked
|
||||
updatedInfo, err := broker.GetSubscriptionInfo(subscriptionID)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get updated subscription info: %v", err)
|
||||
}
|
||||
|
||||
if updatedInfo["current_offset"] != newOffset {
|
||||
t.Errorf("Seek didn't work: expected offset %d, got %v", newOffset, updatedInfo["current_offset"])
|
||||
}
|
||||
|
||||
// 8. Test offset to timestamp conversion with fixed partition identity
|
||||
updatedSub, err := broker.offsetManager.GetSubscription(subscriptionID)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get updated subscription: %v", err)
|
||||
}
|
||||
|
||||
position, err := broker.convertOffsetToMessagePosition(updatedSub)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to convert offset to position: %v", err)
|
||||
}
|
||||
|
||||
if position.Time.IsZero() {
|
||||
t.Error("Expected non-zero timestamp from conversion")
|
||||
}
|
||||
|
||||
// 9. Verify partition identity consistency throughout
|
||||
partitionKey1 := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
|
||||
testPartition.RingSize, testPartition.RangeStart, testPartition.RangeStop, testPartition.UnixTimeNs)
|
||||
|
||||
partitionKey2 := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
|
||||
testPartition.RingSize, testPartition.RangeStart, testPartition.RangeStop, fixedTimestamp)
|
||||
|
||||
if partitionKey1 != partitionKey2 {
|
||||
t.Errorf("Partition key inconsistency: %s != %s", partitionKey1, partitionKey2)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,107 +1,33 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
// OffsetAssignmentFunc is a function type for assigning offsets to messages
|
||||
type OffsetAssignmentFunc func() (int64, error)
|
||||
|
||||
// AddToBufferWithOffset adds a message to the log buffer with offset assignment
|
||||
// TODO: This is a temporary solution until LogBuffer can be modified to accept offset assignment
|
||||
// ASSUMPTION: This function will be integrated into LogBuffer.AddToBuffer in the future
|
||||
func (b *MessageQueueBroker) AddToBufferWithOffset(
|
||||
logBuffer *log_buffer.LogBuffer,
|
||||
message *mq_pb.DataMessage,
|
||||
t topic.Topic,
|
||||
p topic.Partition,
|
||||
) error {
|
||||
// Assign offset for this message
|
||||
offset, err := b.offsetManager.AssignOffset(t, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// PERFORMANCE OPTIMIZATION: Pre-process expensive operations OUTSIDE the lock
|
||||
processingTsNs := message.TsNs
|
||||
if processingTsNs == 0 {
|
||||
processingTsNs = time.Now().UnixNano()
|
||||
}
|
||||
|
||||
// Create LogEntry with assigned offset
|
||||
logEntry := &filer_pb.LogEntry{
|
||||
TsNs: processingTsNs,
|
||||
PartitionKeyHash: util.HashToInt32(message.Key),
|
||||
Data: message.Value,
|
||||
Key: message.Key,
|
||||
Offset: offset, // Add the assigned offset
|
||||
}
|
||||
|
||||
// Use the existing LogBuffer infrastructure for the rest
|
||||
// TODO: This is a workaround - ideally LogBuffer should handle offset assignment
|
||||
// For now, we'll add the message with the pre-assigned offset
|
||||
return b.addLogEntryToBuffer(logBuffer, logEntry)
|
||||
}
|
||||
|
||||
// addLogEntryToBuffer adds a pre-constructed LogEntry to the buffer
|
||||
// This is a helper function that directly uses LogBuffer.AddLogEntryToBuffer
|
||||
func (b *MessageQueueBroker) addLogEntryToBuffer(
|
||||
logBuffer *log_buffer.LogBuffer,
|
||||
logEntry *filer_pb.LogEntry,
|
||||
) error {
|
||||
// Use the AddLogEntryToBuffer method to preserve offset information
|
||||
// This ensures the offset is maintained throughout the entire data flow
|
||||
return logBuffer.AddLogEntryToBuffer(logEntry)
|
||||
}
|
||||
|
||||
// GetPartitionOffsetInfoInternal returns offset information for a partition (internal method)
|
||||
// GetPartitionOffsetInfoInternal reports offsets from the loaded partition's buffer, which
|
||||
// assigns them and tracks the earliest one retained, or from the ranges stored on disk
|
||||
// when this broker has not loaded it.
|
||||
func (b *MessageQueueBroker) GetPartitionOffsetInfoInternal(t topic.Topic, p topic.Partition) (*PartitionOffsetInfo, error) {
|
||||
info, err := b.offsetManager.GetPartitionOffsetInfo(t, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// CRITICAL FIX: Also check LogBuffer for in-memory messages
|
||||
// The offset manager only tracks assigned offsets from persistent storage
|
||||
// But the LogBuffer contains recently written messages that haven't been flushed yet
|
||||
localPartition := b.localTopicManager.GetLocalPartition(t, p)
|
||||
logBufferHWM := int64(-1)
|
||||
if localPartition != nil && localPartition.LogBuffer != nil {
|
||||
logBufferHWM = localPartition.LogBuffer.GetOffset()
|
||||
var earliestOffset, highWaterMark, activeSubscriptions int64
|
||||
if localPartition := b.localTopicManager.GetLocalPartition(t, p); localPartition != nil {
|
||||
earliestOffset = localPartition.LogBuffer.GetLogStartOffset()
|
||||
highWaterMark = localPartition.LogBuffer.GetOffset()
|
||||
activeSubscriptions = int64(localPartition.Subscribers.Size())
|
||||
} else {
|
||||
r, err := b.getOffsetRangeFromChunkMetadata(t, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
earliestOffset, highWaterMark = r.Bounds()
|
||||
}
|
||||
|
||||
// Use the MAX of offset manager HWM and LogBuffer HWM
|
||||
// This ensures we report the correct HWM even if data hasn't been flushed to disk yet
|
||||
// IMPORTANT: Use >= not > because when they're equal, we still want the correct value
|
||||
highWaterMark := info.HighWaterMark
|
||||
if logBufferHWM >= 0 && logBufferHWM > highWaterMark {
|
||||
highWaterMark = logBufferHWM
|
||||
} else if logBufferHWM >= 0 && logBufferHWM == highWaterMark && highWaterMark > 0 {
|
||||
} else if logBufferHWM >= 0 {
|
||||
}
|
||||
|
||||
// Latest offset is HWM - 1 (last assigned offset)
|
||||
latestOffset := highWaterMark - 1
|
||||
if highWaterMark == 0 {
|
||||
latestOffset = -1 // No records
|
||||
}
|
||||
|
||||
// Convert to broker-specific format
|
||||
return &PartitionOffsetInfo{
|
||||
Topic: t,
|
||||
Partition: p,
|
||||
EarliestOffset: info.EarliestOffset,
|
||||
LatestOffset: latestOffset,
|
||||
EarliestOffset: earliestOffset,
|
||||
LatestOffset: highWaterMark - 1,
|
||||
HighWaterMark: highWaterMark,
|
||||
RecordCount: highWaterMark, // HWM equals record count (offsets 0 to HWM-1)
|
||||
ActiveSubscriptions: info.ActiveSubscriptions,
|
||||
RecordCount: highWaterMark - earliestOffset,
|
||||
ActiveSubscriptions: activeSubscriptions,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -115,38 +41,3 @@ type PartitionOffsetInfo struct {
|
||||
RecordCount int64
|
||||
ActiveSubscriptions int64
|
||||
}
|
||||
|
||||
// CreateOffsetSubscription creates an offset-based subscription through the broker
|
||||
func (b *MessageQueueBroker) CreateOffsetSubscription(
|
||||
subscriptionID string,
|
||||
t topic.Topic,
|
||||
p topic.Partition,
|
||||
offsetType string, // Will be converted to schema_pb.OffsetType
|
||||
startOffset int64,
|
||||
) error {
|
||||
// TODO: Convert string offsetType to schema_pb.OffsetType
|
||||
// ASSUMPTION: For now using RESET_TO_EARLIEST as default
|
||||
// This should be properly mapped based on the offsetType parameter
|
||||
|
||||
_, err := b.offsetManager.CreateSubscription(
|
||||
subscriptionID,
|
||||
t,
|
||||
p,
|
||||
0, // schema_pb.OffsetType_RESET_TO_EARLIEST
|
||||
startOffset,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetOffsetMetrics returns offset metrics for monitoring
|
||||
func (b *MessageQueueBroker) GetOffsetMetrics() map[string]interface{} {
|
||||
metrics := b.offsetManager.GetOffsetMetrics()
|
||||
|
||||
return map[string]interface{}{
|
||||
"partition_count": metrics.PartitionCount,
|
||||
"total_offsets": metrics.TotalOffsets,
|
||||
"active_subscriptions": metrics.ActiveSubscriptions,
|
||||
"average_latency": metrics.AverageLatency,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
|
||||
)
|
||||
|
||||
// A loaded partition starts its log at the earliest offset still stored, so a
|
||||
// read below it is out of range rather than answered from a later file.
|
||||
func TestLoadedPartitionStartsAtTheEarliestStoredOffset(t *testing.T) {
|
||||
f, b := newFencingFiler(t)
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
|
||||
f.putLogFile(start, 100, 199, start)
|
||||
f.putLogFile(start.Add(time.Minute), 200, 299, start.Add(time.Minute))
|
||||
|
||||
lp, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lp.LogBuffer.ShutdownLogBuffer()
|
||||
b.localTopicManager.AddLocalPartition(fenceTestTopic, lp)
|
||||
|
||||
info, err := b.GetPartitionOffsetInfoInternal(fenceTestTopic, fenceTestPartition)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.EarliestOffset != 100 || info.HighWaterMark != 300 || info.RecordCount != 200 {
|
||||
t.Fatalf("info = %+v, want earliest 100, hwm 300, count 200", info)
|
||||
}
|
||||
if _, _, _, _, err := lp.LogBuffer.ReadMessagesAtOffset(50, 10, 1<<20); !errors.Is(err, log_buffer.ErrOffsetOutOfRange) {
|
||||
t.Fatalf("read below the earliest stored offset: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A leader whose clock is behind the stored messages stamps new ones after them, so
|
||||
// a timestamp resume from the last stored message still reads what it publishes. An
|
||||
// older file recording no message times is bounded by when it was written.
|
||||
func TestLoadedPartitionStampsAfterTheNewestStoredMessage(t *testing.T) {
|
||||
for _, recordsTimes := range []bool{true, false} {
|
||||
f, b := newFencingFiler(t)
|
||||
// the flush on shutdown notifies the partition through the topic manager
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
stored := time.Now().Add(time.Hour)
|
||||
name := f.putLogFile(stored.Truncate(time.Second), 0, 9, stored)
|
||||
if recordsTimes {
|
||||
entry := f.entry(topic.PartitionDir(fenceTestTopic, fenceTestPartition) + "/" + name)
|
||||
f.mu.Lock()
|
||||
entry.Extended[mq.ExtendedAttrTimestampMin] = binary.BigEndian.AppendUint64(nil, uint64(stored.Truncate(time.Second).UnixNano()))
|
||||
entry.Extended[mq.ExtendedAttrTimestampMax] = binary.BigEndian.AppendUint64(nil, uint64(stored.UnixNano()))
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
lp, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("new"), TsNs: time.Now().UnixNano()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var got []string
|
||||
if _, _, err := lp.LogBuffer.LoopProcessLogData("test", log_buffer.NewMessagePosition(stored.UnixNano(), -2), 0, func() bool { return false }, func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
got = append(got, string(logEntry.Data))
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lp.Shutdown()
|
||||
if len(got) != 1 || got[0] != "new" {
|
||||
t.Errorf("file records message times %v: resumed after the stored messages, read %q, want the new message", recordsTimes, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A loaded partition's buffer assigns offsets, so it is the high water mark.
|
||||
func TestPartitionOffsetInfoFromLoadedBuffer(t *testing.T) {
|
||||
b := newUnelectedBroker()
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
tp := topic.NewTopic("test", "t")
|
||||
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
|
||||
lp := topic.NewLocalPartition(partition, 3600, nil, nil)
|
||||
defer lp.Shutdown()
|
||||
b.localTopicManager.AddLocalPartition(tp, lp)
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
info, err := b.GetPartitionOffsetInfoInternal(tp, partition)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.HighWaterMark != 3 || info.LatestOffset != 2 || info.RecordCount != 3 {
|
||||
t.Fatalf("info = %+v, want hwm 3, latest 2, count 3", info)
|
||||
}
|
||||
}
|
||||
|
||||
// A subscriber or fetch naming a stale generation of an assigned range loads
|
||||
// the assigned generation and continues its stored offsets.
|
||||
func TestStaleGenerationRequestLoadsTheAssignedPartition(t *testing.T) {
|
||||
tp := topic.NewTopic("test", "t")
|
||||
assigned := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
|
||||
f, b := newFencingFiler(t)
|
||||
offsetMax := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(offsetMax, 41)
|
||||
f.entries[topic.PartitionDir(tp, assigned)+"/segment"] = &filer_pb.Entry{Name: "segment", Extended: map[string][]byte{mq.ExtendedAttrOffsetMax: offsetMax}}
|
||||
b.localTopicManager = topic.NewLocalTopicManager()
|
||||
conf := &mq_pb.ConfigureTopicResponse{BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
|
||||
LeaderBroker: string(b.option.BrokerAddress()),
|
||||
Partition: &schema_pb.Partition{RingSize: assigned.RingSize, RangeStart: assigned.RangeStart, RangeStop: assigned.RangeStop, UnixTimeNs: assigned.UnixTimeNs},
|
||||
}}}
|
||||
|
||||
stale := assigned
|
||||
stale.UnixTimeNs = 0
|
||||
lp, generated, err := b.doGetOrGenLocalPartition(tp, stale, conf)
|
||||
if err != nil || !generated {
|
||||
t.Fatalf("generated=%v err=%v", generated, err)
|
||||
}
|
||||
defer lp.Shutdown()
|
||||
if lp.Partition.UnixTimeNs != assigned.UnixTimeNs {
|
||||
t.Errorf("loaded generation %d, assigned %d", lp.Partition.UnixTimeNs, assigned.UnixTimeNs)
|
||||
}
|
||||
if next := lp.LogBuffer.GetOffset(); next != 42 {
|
||||
t.Errorf("next offset %d, want 42 after the stored offsets", next)
|
||||
}
|
||||
}
|
||||
@@ -2,173 +2,24 @@ package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer_client"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
||||
)
|
||||
|
||||
// BrokerOffsetManager manages offset assignment for all partitions in a broker
|
||||
// BrokerOffsetManager keeps consumer-group positions. Publish offsets are
|
||||
// assigned by each partition's log buffer.
|
||||
type BrokerOffsetManager struct {
|
||||
mu sync.RWMutex
|
||||
offsetIntegration *offset.SMQOffsetIntegration
|
||||
storage offset.OffsetStorage
|
||||
consumerGroupStorage offset.ConsumerGroupOffsetStorage
|
||||
}
|
||||
|
||||
// NewBrokerOffsetManagerWithFilerAccessor creates a new broker offset manager using existing filer client accessor
|
||||
func NewBrokerOffsetManagerWithFilerAccessor(filerAccessor *filer_client.FilerClientAccessor) *BrokerOffsetManager {
|
||||
// Create filer storage using the accessor directly - no duplicate connection management
|
||||
filerStorage := offset.NewFilerOffsetStorageWithAccessor(filerAccessor)
|
||||
|
||||
// Create consumer group storage using the accessor directly
|
||||
consumerGroupStorage := offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filerAccessor)
|
||||
|
||||
return &BrokerOffsetManager{
|
||||
offsetIntegration: offset.NewSMQOffsetIntegration(filerStorage),
|
||||
storage: filerStorage,
|
||||
consumerGroupStorage: consumerGroupStorage,
|
||||
consumerGroupStorage: offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filerAccessor),
|
||||
}
|
||||
}
|
||||
|
||||
// AssignOffset assigns the next offset for a partition
|
||||
func (bom *BrokerOffsetManager) AssignOffset(t topic.Topic, p topic.Partition) (int64, error) {
|
||||
partition := topicPartitionToSchemaPartition(t, p)
|
||||
|
||||
// Use the integration layer's offset assigner to ensure consistency with subscriptions
|
||||
result := bom.offsetIntegration.AssignSingleOffset(t.Namespace, t.Name, partition)
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
}
|
||||
|
||||
return result.Assignment.Offset, nil
|
||||
}
|
||||
|
||||
// AssignBatchOffsets assigns a batch of offsets for a partition
|
||||
func (bom *BrokerOffsetManager) AssignBatchOffsets(t topic.Topic, p topic.Partition, count int64) (baseOffset, lastOffset int64, err error) {
|
||||
partition := topicPartitionToSchemaPartition(t, p)
|
||||
|
||||
// Use the integration layer's offset assigner to ensure consistency with subscriptions
|
||||
result := bom.offsetIntegration.AssignBatchOffsets(t.Namespace, t.Name, partition, count)
|
||||
if result.Error != nil {
|
||||
return 0, 0, result.Error
|
||||
}
|
||||
|
||||
return result.Batch.BaseOffset, result.Batch.LastOffset, nil
|
||||
}
|
||||
|
||||
// GetHighWaterMark returns the high water mark for a partition
|
||||
func (bom *BrokerOffsetManager) GetHighWaterMark(t topic.Topic, p topic.Partition) (int64, error) {
|
||||
partition := topicPartitionToSchemaPartition(t, p)
|
||||
|
||||
// Use the integration layer's offset assigner to ensure consistency with subscriptions
|
||||
return bom.offsetIntegration.GetHighWaterMark(t.Namespace, t.Name, partition)
|
||||
}
|
||||
|
||||
// CreateSubscription creates an offset-based subscription
|
||||
func (bom *BrokerOffsetManager) CreateSubscription(
|
||||
subscriptionID string,
|
||||
t topic.Topic,
|
||||
p topic.Partition,
|
||||
offsetType schema_pb.OffsetType,
|
||||
startOffset int64,
|
||||
) (*offset.OffsetSubscription, error) {
|
||||
partition := topicPartitionToSchemaPartition(t, p)
|
||||
return bom.offsetIntegration.CreateSubscription(subscriptionID, t.Namespace, t.Name, partition, offsetType, startOffset)
|
||||
}
|
||||
|
||||
// GetSubscription retrieves an existing subscription
|
||||
func (bom *BrokerOffsetManager) GetSubscription(subscriptionID string) (*offset.OffsetSubscription, error) {
|
||||
return bom.offsetIntegration.GetSubscription(subscriptionID)
|
||||
}
|
||||
|
||||
// CloseSubscription closes a subscription
|
||||
func (bom *BrokerOffsetManager) CloseSubscription(subscriptionID string) error {
|
||||
return bom.offsetIntegration.CloseSubscription(subscriptionID)
|
||||
}
|
||||
|
||||
// ListActiveSubscriptions returns all active subscriptions
|
||||
func (bom *BrokerOffsetManager) ListActiveSubscriptions() ([]*offset.OffsetSubscription, error) {
|
||||
return bom.offsetIntegration.ListActiveSubscriptions()
|
||||
}
|
||||
|
||||
// GetPartitionOffsetInfo returns comprehensive offset information for a partition
|
||||
func (bom *BrokerOffsetManager) GetPartitionOffsetInfo(t topic.Topic, p topic.Partition) (*offset.PartitionOffsetInfo, error) {
|
||||
partition := topicPartitionToSchemaPartition(t, p)
|
||||
|
||||
// Use the integration layer to ensure consistency with subscriptions
|
||||
return bom.offsetIntegration.GetPartitionOffsetInfo(t.Namespace, t.Name, partition)
|
||||
}
|
||||
|
||||
// topicPartitionToSchemaPartition converts topic.Topic and topic.Partition to schema_pb.Partition
|
||||
func topicPartitionToSchemaPartition(t topic.Topic, p topic.Partition) *schema_pb.Partition {
|
||||
return &schema_pb.Partition{
|
||||
RingSize: int32(p.RingSize),
|
||||
RangeStart: int32(p.RangeStart),
|
||||
RangeStop: int32(p.RangeStop),
|
||||
UnixTimeNs: p.UnixTimeNs,
|
||||
}
|
||||
}
|
||||
|
||||
// OffsetAssignmentResult contains the result of offset assignment for logging/metrics
|
||||
type OffsetAssignmentResult struct {
|
||||
Topic topic.Topic
|
||||
Partition topic.Partition
|
||||
BaseOffset int64
|
||||
LastOffset int64
|
||||
Count int64
|
||||
Timestamp int64
|
||||
Error error
|
||||
}
|
||||
|
||||
// AssignOffsetsWithResult assigns offsets and returns detailed result for logging/metrics
|
||||
func (bom *BrokerOffsetManager) AssignOffsetsWithResult(t topic.Topic, p topic.Partition, count int64) *OffsetAssignmentResult {
|
||||
baseOffset, lastOffset, err := bom.AssignBatchOffsets(t, p, count)
|
||||
|
||||
result := &OffsetAssignmentResult{
|
||||
Topic: t,
|
||||
Partition: p,
|
||||
Count: count,
|
||||
Error: err,
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
result.BaseOffset = baseOffset
|
||||
result.LastOffset = lastOffset
|
||||
result.Timestamp = time.Now().UnixNano()
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetOffsetMetrics returns metrics about offset usage across all partitions
|
||||
func (bom *BrokerOffsetManager) GetOffsetMetrics() *offset.OffsetMetrics {
|
||||
// Use the integration layer to ensure consistency with subscriptions
|
||||
return bom.offsetIntegration.GetOffsetMetrics()
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the offset manager
|
||||
func (bom *BrokerOffsetManager) Shutdown() {
|
||||
bom.mu.Lock()
|
||||
defer bom.mu.Unlock()
|
||||
|
||||
// Reset the underlying storage to ensure clean restart behavior
|
||||
// This is important for testing where we want offsets to start from 0 after shutdown
|
||||
if bom.storage != nil {
|
||||
if resettable, ok := bom.storage.(interface{ Reset() error }); ok {
|
||||
resettable.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
// Reset the integration layer to ensure clean restart behavior
|
||||
bom.offsetIntegration.Reset()
|
||||
}
|
||||
|
||||
// Consumer Group Offset Management
|
||||
|
||||
// SaveConsumerGroupOffset saves the committed offset for a consumer group
|
||||
func (bom *BrokerOffsetManager) SaveConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string, offset int64) error {
|
||||
if bom.consumerGroupStorage == nil {
|
||||
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user