mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-25 05:37:12 +01:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96ef97a026 | ||
|
|
dfd247ea63 |
No files matched your search
@@ -43,10 +43,7 @@ jobs:
|
||||
- name: Run EC Integration Tests
|
||||
working-directory: test/erasure_coding
|
||||
run: |
|
||||
# The suite now includes the interruption matrix and runs close to Go's
|
||||
# default 10m binary timeout on slower runners; bound it by the job's
|
||||
# 30m budget instead.
|
||||
go test -v -timeout 25m
|
||||
go test -v
|
||||
|
||||
- name: Collect server logs on failure
|
||||
if: failure()
|
||||
|
||||
@@ -111,16 +111,6 @@ jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
redis:
|
||||
image: redis:8
|
||||
ports:
|
||||
- 6379:6379
|
||||
options: >-
|
||||
--health-cmd "redis-cli ping"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
steps:
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v7
|
||||
@@ -129,8 +119,6 @@ jobs:
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
- name: Test
|
||||
env:
|
||||
RUN_REDIS_TESTS: "1"
|
||||
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
|
||||
|
||||
test-32bit:
|
||||
|
||||
@@ -61,7 +61,7 @@ Table of Contents
|
||||
* [Features](#features)
|
||||
* [Additional Features](#additional-features)
|
||||
* [Filer Features](#filer-features)
|
||||
* [Example: Using Seaweed Blob Store](#example-using-seaweed-blob-store)
|
||||
* [Example: Using Seaweed Object Store](#example-using-seaweed-object-store)
|
||||
* [Architecture](#object-store-architecture)
|
||||
* [Compared to Other File Systems](#compared-to-other-file-systems)
|
||||
* [Compared to HDFS](#compared-to-hdfs)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.42"
|
||||
appVersion: "4.41"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.42.0
|
||||
version: 4.41.0
|
||||
@@ -45,8 +45,6 @@ service VolumeServer {
|
||||
}
|
||||
rpc VolumeUnmount (VolumeUnmountRequest) returns (VolumeUnmountResponse) {
|
||||
}
|
||||
rpc VolumeConsolidateIndex (VolumeConsolidateIndexRequest) returns (VolumeConsolidateIndexResponse) {
|
||||
}
|
||||
rpc VolumeDelete (VolumeDeleteRequest) returns (VolumeDeleteResponse) {
|
||||
}
|
||||
rpc VolumeMarkReadonly (VolumeMarkReadonlyRequest) returns (VolumeMarkReadonlyResponse) {
|
||||
@@ -246,12 +244,6 @@ message VolumeUnmountRequest {
|
||||
message VolumeUnmountResponse {
|
||||
}
|
||||
|
||||
message VolumeConsolidateIndexRequest {
|
||||
uint32 volume_id = 1;
|
||||
}
|
||||
message VolumeConsolidateIndexResponse {
|
||||
}
|
||||
|
||||
message VolumeDeleteRequest {
|
||||
uint32 volume_id = 1;
|
||||
bool only_empty = 2;
|
||||
|
||||
@@ -256,8 +256,6 @@ pub struct VolumeServerConfig {
|
||||
pub https_client_ca_file: String,
|
||||
pub grpc_cert_file: String,
|
||||
pub grpc_key_file: String,
|
||||
pub grpc_client_cert_file: String,
|
||||
pub grpc_client_key_file: String,
|
||||
pub grpc_ca_file: String,
|
||||
pub grpc_allowed_wildcard_domain: String,
|
||||
pub grpc_volume_allowed_common_names: Vec<String>,
|
||||
@@ -807,8 +805,6 @@ fn resolve_config(cli: Cli) -> VolumeServerConfig {
|
||||
https_client_ca_file: sec.https_client_ca_file,
|
||||
grpc_cert_file: sec.grpc_cert_file,
|
||||
grpc_key_file: sec.grpc_key_file,
|
||||
grpc_client_cert_file: sec.grpc_client_cert_file,
|
||||
grpc_client_key_file: sec.grpc_client_key_file,
|
||||
grpc_ca_file: sec.grpc_ca_file,
|
||||
grpc_allowed_wildcard_domain: sec.grpc_allowed_wildcard_domain,
|
||||
grpc_volume_allowed_common_names: sec.grpc_volume_allowed_common_names,
|
||||
@@ -841,8 +837,6 @@ pub struct SecurityConfig {
|
||||
pub https_client_ca_file: String,
|
||||
pub grpc_cert_file: String,
|
||||
pub grpc_key_file: String,
|
||||
pub grpc_client_cert_file: String,
|
||||
pub grpc_client_key_file: String,
|
||||
pub grpc_ca_file: String,
|
||||
pub grpc_allowed_wildcard_domain: String,
|
||||
pub grpc_volume_allowed_common_names: Vec<String>,
|
||||
@@ -888,8 +882,6 @@ const SECURITY_CONFIG_FILE_NAME: &str = "security.toml";
|
||||
/// [grpc.volume]
|
||||
/// cert = "/path/to/cert.pem"
|
||||
/// key = "/path/to/key.pem"
|
||||
/// client_cert = "/path/to/client-cert.pem"
|
||||
/// client_key = "/path/to/client-key.pem"
|
||||
/// allowed_commonNames = "volume-a.internal,volume-b.internal"
|
||||
/// ```
|
||||
pub fn parse_security_config(path: &str) -> SecurityConfig {
|
||||
@@ -1011,8 +1003,6 @@ pub fn parse_security_config(path: &str) -> SecurityConfig {
|
||||
Section::GrpcVolume => match key {
|
||||
"cert" => cfg.grpc_cert_file = value.to_string(),
|
||||
"key" => cfg.grpc_key_file = value.to_string(),
|
||||
"client_cert" => cfg.grpc_client_cert_file = value.to_string(),
|
||||
"client_key" => cfg.grpc_client_key_file = value.to_string(),
|
||||
// Go only reads CA from [grpc], not [grpc.volume]
|
||||
"allowed_commonNames" => {
|
||||
cfg.grpc_volume_allowed_common_names =
|
||||
@@ -1144,12 +1134,6 @@ fn apply_env_overrides(cfg: &mut SecurityConfig) {
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_KEY") {
|
||||
cfg.grpc_key_file = v;
|
||||
}
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_CLIENT_CERT") {
|
||||
cfg.grpc_client_cert_file = v;
|
||||
}
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_CLIENT_KEY") {
|
||||
cfg.grpc_client_key_file = v;
|
||||
}
|
||||
if let Ok(v) = std::env::var("WEED_GRPC_CA") {
|
||||
cfg.grpc_ca_file = v;
|
||||
} else if let Ok(v) = std::env::var("WEED_GRPC_VOLUME_CA") {
|
||||
@@ -1247,8 +1231,6 @@ mod tests {
|
||||
"WEED_HTTPS_CLIENT_CA",
|
||||
"WEED_GRPC_VOLUME_CERT",
|
||||
"WEED_GRPC_VOLUME_KEY",
|
||||
"WEED_GRPC_VOLUME_CLIENT_CERT",
|
||||
"WEED_GRPC_VOLUME_CLIENT_KEY",
|
||||
"WEED_GRPC_CA",
|
||||
"WEED_GRPC_VOLUME_CA",
|
||||
"WEED_GRPC_ALLOWED_WILDCARD_DOMAIN",
|
||||
@@ -1518,35 +1500,6 @@ key = "/etc/seaweedfs/volume-key.pem"
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_security_config_uses_grpc_volume_client_cert() {
|
||||
let _guard = process_state_lock();
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(
|
||||
tmp.path(),
|
||||
r#"
|
||||
[grpc.volume]
|
||||
cert = "/etc/seaweedfs/volume-cert.pem"
|
||||
key = "/etc/seaweedfs/volume-key.pem"
|
||||
client_cert = "/etc/seaweedfs/volume-client-cert.pem"
|
||||
client_key = "/etc/seaweedfs/volume-client-key.pem"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
with_cleared_security_env(|| {
|
||||
let cfg = parse_security_config(tmp.path().to_str().unwrap());
|
||||
assert_eq!(
|
||||
cfg.grpc_client_cert_file,
|
||||
"/etc/seaweedfs/volume-client-cert.pem"
|
||||
);
|
||||
assert_eq!(
|
||||
cfg.grpc_client_key_file,
|
||||
"/etc/seaweedfs/volume-client-key.pem"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_security_config_uses_grpc_peer_name_policy() {
|
||||
let _guard = process_state_lock();
|
||||
|
||||
@@ -112,14 +112,6 @@ fn embedded_transition_ipv4(v6: Ipv6Addr) -> Option<Ipv4Addr> {
|
||||
/// Returns an error if `ip` is not safe to dial from a server that can reach
|
||||
/// cluster-internal hosts. Mirrors Go's `checkBlockedIP`.
|
||||
pub fn check_blocked_ip(endpoint: &str, ip: IpAddr) -> Result<(), String> {
|
||||
check_blocked_ip_policy(endpoint, ip, false)
|
||||
}
|
||||
|
||||
/// Like [`check_blocked_ip`], but `allow_private` keeps RFC 1918 / CGNAT
|
||||
/// reachable for callers whose target legitimately sits on an internal network
|
||||
/// (peer volume servers), while still blocking loopback, link-local (IMDS) and
|
||||
/// unspecified. Mirrors Go's `checkBlockedIPPolicy`.
|
||||
pub fn check_blocked_ip_policy(endpoint: &str, ip: IpAddr, allow_private: bool) -> Result<(), String> {
|
||||
// Normalize IPv4-mapped IPv6 (`::ffff:a.b.c.d`) to its IPv4 form so the
|
||||
// IPv4 deny rules apply. The OS routes these to the embedded IPv4 address,
|
||||
// so without this `::ffff:127.0.0.1` / `::ffff:169.254.169.254` would slip
|
||||
@@ -155,19 +147,17 @@ pub fn check_blocked_ip_policy(endpoint: &str, ip: IpAddr, allow_private: bool)
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if !allow_private {
|
||||
if is_private(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to private address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_cgnat(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to CGNAT address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_private(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to private address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
if is_cgnat(ip) {
|
||||
return Err(format!(
|
||||
"remote endpoint {:?} resolves to CGNAT address {}",
|
||||
endpoint, ip
|
||||
));
|
||||
}
|
||||
// IPv6 transition addresses embed an IPv4 destination that routes to the
|
||||
// same host wherever the matching relay exists (common in IPv6-only cloud).
|
||||
@@ -175,7 +165,7 @@ pub fn check_blocked_ip_policy(endpoint: &str, ip: IpAddr, allow_private: bool)
|
||||
// embedded IPv4 out of the other forms and re-check it against the rules.
|
||||
if let IpAddr::V6(v6) = ip {
|
||||
if let Some(v4) = embedded_transition_ipv4(v6) {
|
||||
return check_blocked_ip_policy(endpoint, IpAddr::V4(v4), allow_private);
|
||||
return check_blocked_ip(endpoint, IpAddr::V4(v4));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -297,59 +287,6 @@ pub async fn validate_remote_endpoint(endpoint: &str) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an error if `target` could redirect a replica upload away from a peer
|
||||
/// volume server. The target must be a bare `host:port` -- a scheme, userinfo,
|
||||
/// path, query or fragment can smuggle a different destination into the
|
||||
/// formatted upload URL -- whose host is not loopback, link-local (IMDS) or
|
||||
/// unspecified. Cluster peers legitimately sit on private networks, so RFC 1918
|
||||
/// / CGNAT are allowed. Mirrors Go's `validateReplicaTarget`.
|
||||
pub async fn validate_replica_target(target: &str) -> Result<(), String> {
|
||||
let trimmed = target.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("replica target is empty".to_string());
|
||||
}
|
||||
if trimmed.contains("://") || trimmed.contains(['/', '?', '#', '@', '\\']) {
|
||||
return Err(format!("replica target {:?} must be a bare host:port", target));
|
||||
}
|
||||
|
||||
// Require an explicit host:port, handling `[IPv6]:port`. A bracketless IPv6
|
||||
// literal (which carries its own colons) is rejected; peers are addressed as
|
||||
// `[ipv6]:port`, matching Go's net.SplitHostPort.
|
||||
let host = if let Some(rest) = trimmed.strip_prefix('[') {
|
||||
match rest.split_once(']') {
|
||||
Some((h, port)) if port.starts_with(':') && port.len() > 1 => h,
|
||||
_ => return Err(format!("replica target {:?} must be a bare host:port", target)),
|
||||
}
|
||||
} else {
|
||||
match trimmed.rsplit_once(':') {
|
||||
Some((h, port)) if !port.is_empty() && !h.contains(':') => h,
|
||||
_ => return Err(format!("replica target {:?} must be a bare host:port", target)),
|
||||
}
|
||||
};
|
||||
|
||||
if host.is_empty() {
|
||||
return Err(format!("replica target {:?} has no host", target));
|
||||
}
|
||||
if is_blocked_imds_host(&host.to_ascii_lowercase()) {
|
||||
return Err(format!(
|
||||
"replica target {:?} targets instance metadata service",
|
||||
target
|
||||
));
|
||||
}
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
return check_blocked_ip_policy(target, ip, true);
|
||||
}
|
||||
|
||||
let addrs = resolve_host(host).await?;
|
||||
if addrs.is_empty() {
|
||||
return Err(format!("resolve replica target host {:?}: no addresses", host));
|
||||
}
|
||||
for ip in addrs {
|
||||
check_blocked_ip_policy(target, ip, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -506,71 +443,4 @@ mod tests {
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_blocked_ip_policy_allows_private_peers() {
|
||||
// The replica leg targets peer volume servers, which may be private.
|
||||
assert!(check_blocked_ip_policy("e", ip("10.0.0.7"), true).is_ok());
|
||||
assert!(check_blocked_ip_policy("e", ip("192.168.1.5"), true).is_ok());
|
||||
assert!(check_blocked_ip_policy("e", ip("100.64.0.42"), true).is_ok());
|
||||
// Loopback / IMDS / unspecified stay blocked even when private is allowed.
|
||||
assert!(check_blocked_ip_policy("e", ip("127.0.0.1"), true)
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(check_blocked_ip_policy("e", ip("169.254.169.254"), true)
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
assert!(check_blocked_ip_policy("e", ip("0.0.0.0"), true)
|
||||
.unwrap_err()
|
||||
.contains("unspecified"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_replica_target_rejects_and_allows() {
|
||||
// A path plus a trailing ?a= would otherwise swallow ?type=replicate.
|
||||
assert!(validate_replica_target("127.0.0.1:7000/status/x/?a=")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("http://10.0.0.7:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("user@10.0.0.7:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("10.0.0.7")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("peer.example.com")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("bare host:port"));
|
||||
assert!(validate_replica_target("127.0.0.1:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(validate_replica_target("[::1]:8080")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("loopback"));
|
||||
assert!(validate_replica_target("169.254.169.254:80")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
assert!(validate_replica_target("metadata:80")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("metadata"));
|
||||
assert!(validate_replica_target("")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("empty"));
|
||||
// Legitimate peer volume servers on private networks pass.
|
||||
assert!(validate_replica_target("10.0.0.7:8080").await.is_ok());
|
||||
assert!(validate_replica_target("192.168.1.5:8080").await.is_ok());
|
||||
assert!(validate_replica_target("[fd00::1]:8080").await.is_ok());
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ pub mod endpoint_guard;
|
||||
pub mod s3;
|
||||
pub mod s3_tier;
|
||||
|
||||
pub use endpoint_guard::{validate_remote_endpoint, validate_replica_target};
|
||||
pub use endpoint_guard::validate_remote_endpoint;
|
||||
|
||||
use crate::pb::remote_pb::{RemoteConf, RemoteStorageLocation};
|
||||
|
||||
@@ -211,19 +211,4 @@ mod tests {
|
||||
};
|
||||
assert_eq!(s3_compatible_endpoint(&gcs), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn azure_endpoint_has_no_ssrf_path() {
|
||||
// The Go volume server guards the caller-supplied azure endpoint against
|
||||
// SSRF. This server has no azure backend, so there is nothing to dial:
|
||||
// azure is not S3-compatible (the endpoint guard does not apply) and
|
||||
// make_remote_storage_client rejects the type before building a client.
|
||||
let azure = RemoteConf {
|
||||
r#type: "azure".to_string(),
|
||||
azure_endpoint: "https://169.254.169.254/".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(s3_compatible_endpoint(&azure), None);
|
||||
assert!(make_remote_storage_client(&azure).is_err());
|
||||
}
|
||||
}
|
||||
@@ -192,13 +192,6 @@ impl Guard {
|
||||
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
|
||||
}
|
||||
|
||||
/// Whether any write-side control is configured: a non-empty whitelist or a
|
||||
/// signing key. Mirrors Go's non-nil `guard` -- when this is false, every
|
||||
/// caller is allowed and admin RPCs need not carry peer info.
|
||||
pub fn is_write_active(&self) -> bool {
|
||||
self.is_write_active
|
||||
}
|
||||
|
||||
/// Check if a remote IP is in the whitelist.
|
||||
/// Returns true if write security is inactive (no whitelist and no signing key),
|
||||
/// if the whitelist is empty, or if the IP matches.
|
||||
|
||||
@@ -33,31 +33,23 @@ impl Error for GrpcClientError {}
|
||||
pub fn load_outgoing_grpc_tls(
|
||||
config: &VolumeServerConfig,
|
||||
) -> Result<Option<OutgoingGrpcTlsConfig>, GrpcClientError> {
|
||||
// prefer a dedicated client certificate: CAs may issue certs with only one of the serverAuth/clientAuth EKUs
|
||||
let (cert_file, key_file) = if !config.grpc_client_cert_file.is_empty()
|
||||
&& !config.grpc_client_key_file.is_empty()
|
||||
if config.grpc_cert_file.is_empty()
|
||||
|| config.grpc_key_file.is_empty()
|
||||
|| config.grpc_ca_file.is_empty()
|
||||
{
|
||||
(&config.grpc_client_cert_file, &config.grpc_client_key_file)
|
||||
} else {
|
||||
if !config.grpc_client_cert_file.is_empty() || !config.grpc_client_key_file.is_empty() {
|
||||
tracing::warn!("grpc.volume.client_cert and grpc.volume.client_key must both be set, falling back to grpc.volume.cert and grpc.volume.key");
|
||||
}
|
||||
(&config.grpc_cert_file, &config.grpc_key_file)
|
||||
};
|
||||
if cert_file.is_empty() || key_file.is_empty() || config.grpc_ca_file.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let cert_pem = std::fs::read_to_string(cert_file).map_err(|e| {
|
||||
let cert_pem = std::fs::read_to_string(&config.grpc_cert_file).map_err(|e| {
|
||||
GrpcClientError(format!(
|
||||
"Failed to read outgoing gRPC cert '{}': {}",
|
||||
cert_file, e
|
||||
config.grpc_cert_file, e
|
||||
))
|
||||
})?;
|
||||
let key_pem = std::fs::read_to_string(key_file).map_err(|e| {
|
||||
let key_pem = std::fs::read_to_string(&config.grpc_key_file).map_err(|e| {
|
||||
GrpcClientError(format!(
|
||||
"Failed to read outgoing gRPC key '{}': {}",
|
||||
key_file, e
|
||||
config.grpc_key_file, e
|
||||
))
|
||||
})?;
|
||||
let ca_pem = std::fs::read_to_string(&config.grpc_ca_file).map_err(|e| {
|
||||
@@ -244,8 +236,6 @@ mod tests {
|
||||
https_client_ca_file: String::new(),
|
||||
grpc_cert_file: String::new(),
|
||||
grpc_key_file: String::new(),
|
||||
grpc_client_cert_file: String::new(),
|
||||
grpc_client_key_file: String::new(),
|
||||
grpc_ca_file: String::new(),
|
||||
grpc_allowed_wildcard_domain: String::new(),
|
||||
grpc_volume_allowed_common_names: vec![],
|
||||
@@ -275,45 +265,6 @@ mod tests {
|
||||
assert!(load_outgoing_grpc_tls(&config).unwrap().is_none());
|
||||
}
|
||||
|
||||
fn write_pem_files(dir: &tempfile::TempDir, config: &mut VolumeServerConfig) {
|
||||
let write = |name: &str, content: &str| {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, content).unwrap();
|
||||
path.to_str().unwrap().to_string()
|
||||
};
|
||||
config.grpc_cert_file = write("server.pem", "server-cert");
|
||||
config.grpc_key_file = write("server.key", "server-key");
|
||||
config.grpc_ca_file = write("ca.pem", "ca");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_outgoing_grpc_tls_prefers_client_cert() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let mut config = sample_config();
|
||||
write_pem_files(&dir, &mut config);
|
||||
let client_cert = dir.path().join("client.pem");
|
||||
let client_key = dir.path().join("client.key");
|
||||
std::fs::write(&client_cert, "client-cert").unwrap();
|
||||
std::fs::write(&client_key, "client-key").unwrap();
|
||||
config.grpc_client_cert_file = client_cert.to_str().unwrap().to_string();
|
||||
config.grpc_client_key_file = client_key.to_str().unwrap().to_string();
|
||||
|
||||
let tls = load_outgoing_grpc_tls(&config).unwrap().unwrap();
|
||||
assert_eq!(tls.cert_pem, "client-cert");
|
||||
assert_eq!(tls.key_pem, "client-key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_outgoing_grpc_tls_falls_back_to_server_cert() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let mut config = sample_config();
|
||||
write_pem_files(&dir, &mut config);
|
||||
|
||||
let tls = load_outgoing_grpc_tls(&config).unwrap().unwrap();
|
||||
assert_eq!(tls.cert_pem, "server-cert");
|
||||
assert_eq!(tls.key_pem, "server-key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_grpc_endpoint_without_tls_uses_http_scheme() {
|
||||
let endpoint = build_grpc_endpoint("127.0.0.1:19333", None).unwrap();
|
||||
|
||||
@@ -155,13 +155,6 @@ impl VolumeGrpcService {
|
||||
/// SocketAddr; if it is somehow None we deny, matching "if we don't
|
||||
/// know who the caller is, refuse."
|
||||
fn check_grpc_admin_auth<T>(&self, request: &Request<T>) -> Result<(), Status> {
|
||||
// Mirror Go's `if vs.guard == nil { return nil }`: with no whitelist and
|
||||
// no signing key, write security is inactive and every caller is allowed.
|
||||
// Real gRPC connections always carry peer info, so requiring it below only
|
||||
// affects in-process callers (tests, upgrades) once a control is enabled.
|
||||
if !self.state.guard.read().unwrap().is_write_active() {
|
||||
return Ok(());
|
||||
}
|
||||
let remote = match request.remote_addr() {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
@@ -300,7 +293,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::BatchDeleteRequest>,
|
||||
) -> Result<Response<volume_server_pb::BatchDeleteResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let mut results = Vec::new();
|
||||
@@ -952,22 +944,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
Ok(Response::new(volume_server_pb::VolumeUnmountResponse {}))
|
||||
}
|
||||
|
||||
async fn volume_consolidate_index(
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeConsolidateIndexRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeConsolidateIndexResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let vid = VolumeId(request.into_inner().volume_id);
|
||||
let mut store = self.state.store.write().unwrap();
|
||||
store
|
||||
.consolidate_volume_index(vid)
|
||||
.map_err(|e| Status::internal(e.to_string()))?;
|
||||
Ok(Response::new(
|
||||
volume_server_pb::VolumeConsolidateIndexResponse {},
|
||||
))
|
||||
}
|
||||
|
||||
async fn volume_delete(
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeDeleteRequest>,
|
||||
@@ -1159,7 +1135,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::SetStateRequest>,
|
||||
) -> Result<Response<volume_server_pb::SetStateResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
if let Some(new_state) = &req.state {
|
||||
@@ -1212,7 +1187,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeCopyRequest>,
|
||||
) -> Result<Response<Self::VolumeCopyStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -2014,7 +1988,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::ReadAllNeedlesRequest>,
|
||||
) -> Result<Response<Self::ReadAllNeedlesStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let state = self.state.clone();
|
||||
|
||||
@@ -2215,7 +2188,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeTailReceiverRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeTailReceiverResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
@@ -2341,7 +2313,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsGenerateRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsGenerateResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -2442,7 +2413,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsRebuildRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsRebuildResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -2643,7 +2613,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsCopyRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsCopyResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3026,7 +2995,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsUnmountRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsUnmountResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
@@ -3190,7 +3158,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeEcShardsToVolumeRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsToVolumeResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3457,7 +3424,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeTierMoveDatToRemoteRequest>,
|
||||
) -> Result<Response<Self::VolumeTierMoveDatToRemoteStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3624,7 +3590,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeTierMoveDatFromRemoteRequest>,
|
||||
) -> Result<Response<Self::VolumeTierMoveDatFromRemoteStream>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
// Note: Go does NOT check maintenance mode for TierMoveDatFromRemote
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3885,7 +3850,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::FetchAndWriteNeedleRequest>,
|
||||
) -> Result<Response<volume_server_pb::FetchAndWriteNeedleResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
@@ -3961,21 +3925,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
.as_secs();
|
||||
n.set_has_last_modified_date();
|
||||
|
||||
// Validate every replica target before writing anything, so a malformed
|
||||
// or internal target fails the request instead of leaving a local write
|
||||
// behind. Mirrors the Go volume server. NOTE: like the Rust S3 endpoint
|
||||
// guard, this validates the up-front DNS answer but does not yet re-check
|
||||
// at connect time, so a rebinding hostname remains a follow-up.
|
||||
if !self.state.allow_untrusted_remote_endpoints {
|
||||
for replica in &req.replicas {
|
||||
crate::remote_storage::validate_replica_target(&replica.url)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Status::invalid_argument(format!("reject replica target: {}", e))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
// Run local write and replica writes concurrently (matches Go's WaitGroup)
|
||||
let mut handles: Vec<tokio::task::JoinHandle<Result<(), String>>> = Vec::new();
|
||||
|
||||
@@ -4156,7 +4105,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::ScrubEcVolumeRequest>,
|
||||
) -> Result<Response<volume_server_pb::ScrubEcVolumeResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
|
||||
// Validate mode
|
||||
@@ -4514,7 +4462,6 @@ impl VolumeServer for VolumeGrpcService {
|
||||
&self,
|
||||
request: Request<volume_server_pb::VolumeNeedleStatusRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeNeedleStatusResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
let vid = VolumeId(req.volume_id);
|
||||
let needle_id = NeedleId(req.needle_id);
|
||||
@@ -5447,29 +5394,6 @@ mod tests {
|
||||
(VolumeGrpcService { state }, tmp)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_volume_consolidate_index_rpc() {
|
||||
let (service, _tmp) = make_local_service_with_volume("consolidate_rpc", None);
|
||||
|
||||
// Carry a peer address so the admin gate sees a caller; the test guard
|
||||
// has an empty whitelist, so any peer is accepted.
|
||||
let mut request = Request::new(volume_server_pb::VolumeConsolidateIndexRequest {
|
||||
volume_id: 1,
|
||||
});
|
||||
request.extensions_mut().insert(tonic::transport::server::TcpConnectInfo {
|
||||
local_addr: None,
|
||||
remote_addr: Some("127.0.0.1:65000".parse().unwrap()),
|
||||
});
|
||||
|
||||
service.volume_consolidate_index(request).await.unwrap();
|
||||
|
||||
// Data and index share a directory here, so there is nothing to move;
|
||||
// the volume stays mounted and keeps its needle.
|
||||
let store = service.state.store.read().unwrap();
|
||||
let (_, v) = store.find_volume(VolumeId(1)).unwrap();
|
||||
assert_eq!(v.file_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_volume_incremental_copy_streams_remote_only_volume_data() {
|
||||
let (service, _tmp, shutdown_tx, dat_bytes, super_block_size, _delete_count) =
|
||||
|
||||
@@ -163,8 +163,6 @@ mod tests {
|
||||
https_client_ca_file: String::new(),
|
||||
grpc_cert_file: String::new(),
|
||||
grpc_key_file: String::new(),
|
||||
grpc_client_cert_file: String::new(),
|
||||
grpc_client_key_file: String::new(),
|
||||
grpc_ca_file: String::new(),
|
||||
grpc_allowed_wildcard_domain: String::new(),
|
||||
grpc_volume_allowed_common_names: vec![],
|
||||
|
||||
@@ -156,26 +156,6 @@ impl Store {
|
||||
self.find_volume(vid).is_some()
|
||||
}
|
||||
|
||||
/// Move a volume's index into the configured `-dir.idx` directory, reloading
|
||||
/// the volume in place. A no-op when the location has no separate index
|
||||
/// directory. Mirrors Go's `Store::ConsolidateVolumeIndex`.
|
||||
pub fn consolidate_volume_index(&mut self, vid: VolumeId) -> Result<(), VolumeError> {
|
||||
for loc in self.locations.iter_mut() {
|
||||
let idx_dir = loc.idx_directory.clone();
|
||||
let data_dir = loc.directory.clone();
|
||||
if let Some(v) = loc.find_volume_mut(vid) {
|
||||
if idx_dir == data_dir {
|
||||
return Ok(());
|
||||
}
|
||||
return v.relocate_index_to(&idx_dir);
|
||||
}
|
||||
}
|
||||
Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("volume {} not found on disk", vid),
|
||||
)))
|
||||
}
|
||||
|
||||
// ---- Volume lifecycle ----
|
||||
|
||||
/// Find the location with fewest volumes (load-balance) of the given disk type.
|
||||
@@ -1408,73 +1388,6 @@ mod tests {
|
||||
assert!(deleted.0 > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_consolidate_volume_index_not_found() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut store = make_test_store(&[dir]);
|
||||
let err = store.consolidate_volume_index(VolumeId(9)).unwrap_err();
|
||||
assert!(matches!(err, VolumeError::Io(ref e)
|
||||
if e.kind() == std::io::ErrorKind::NotFound));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_consolidate_volume_index_noop_with_separate_idx_dir() {
|
||||
let root = TempDir::new().unwrap();
|
||||
let data_dir = root.path().join("data");
|
||||
let idx_dir = root.path().join("idx");
|
||||
std::fs::create_dir_all(&data_dir).unwrap();
|
||||
std::fs::create_dir_all(&idx_dir).unwrap();
|
||||
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
data_dir.to_str().unwrap(),
|
||||
idx_dir.to_str().unwrap(),
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(
|
||||
VolumeId(1),
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
DiskType::HardDrive,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(0xaa),
|
||||
data: b"co-located".to_vec(),
|
||||
data_size: 10,
|
||||
..Needle::default()
|
||||
};
|
||||
store.write_volume_needle(VolumeId(1), &mut n).unwrap();
|
||||
|
||||
// add_volume already placed the index in the -dir.idx directory, so
|
||||
// consolidation has nothing to move and leaves the volume readable.
|
||||
store.consolidate_volume_index(VolumeId(1)).unwrap();
|
||||
let idx_file = format!(
|
||||
"{}.idx",
|
||||
volume_file_name(idx_dir.to_str().unwrap(), "", VolumeId(1))
|
||||
);
|
||||
assert!(std::path::Path::new(&idx_file).exists());
|
||||
|
||||
let mut got = Needle {
|
||||
id: NeedleId(1),
|
||||
..Needle::default()
|
||||
};
|
||||
let count = store.read_volume_needle(VolumeId(1), &mut got).unwrap();
|
||||
assert_eq!(count, 10);
|
||||
assert_eq!(got.data, b"co-located");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_store_multi_location() {
|
||||
let tmp1 = TempDir::new().unwrap();
|
||||
|
||||
@@ -17,7 +17,7 @@ use std::sync::Arc;
|
||||
use std::sync::{Condvar, Mutex};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tracing::{error, info, warn};
|
||||
use tracing::{info, warn};
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::storage::idx;
|
||||
@@ -3512,62 +3512,6 @@ impl Volume {
|
||||
self.nm = None;
|
||||
}
|
||||
|
||||
/// Move this volume's `.idx` (and `.sdx` when present) from its current
|
||||
/// index directory into `new_idx_dir`, then reload in place. Mirrors Go's
|
||||
/// `Volume::RelocateIndexTo`: it is a no-op when the index is already there
|
||||
/// or nothing is co-located to move, and is used to pull an index a decode
|
||||
/// or reconstruct left beside the data back into the configured `-dir.idx`.
|
||||
pub fn relocate_index_to(&mut self, new_idx_dir: &str) -> Result<(), VolumeError> {
|
||||
let _guard = self.data_file_access_control.write_lock();
|
||||
|
||||
if self.dir_idx == new_idx_dir {
|
||||
return Ok(());
|
||||
}
|
||||
let old_base = volume_file_name(&self.dir_idx, &self.collection, self.id);
|
||||
let old_idx = format!("{old_base}.idx");
|
||||
if !Path::new(&old_idx).exists() {
|
||||
return Ok(()); // nothing co-located to move
|
||||
}
|
||||
let new_base = volume_file_name(new_idx_dir, &self.collection, self.id);
|
||||
let new_idx = format!("{new_base}.idx");
|
||||
|
||||
// Close the index and data handles before moving the index file.
|
||||
let version = self.version();
|
||||
self.close();
|
||||
|
||||
if let Err(e) = rename_or_copy(&old_idx, &new_idx) {
|
||||
// Reopen against the old dir so the volume is not left down; surface
|
||||
// a failed reopen since it leaves the volume unusable until reload.
|
||||
if let Err(reopen) = self.load(true, false, 0, version) {
|
||||
error!(
|
||||
"relocate volume {}: reopen after failed .idx move: {}",
|
||||
self.id, reopen
|
||||
);
|
||||
}
|
||||
return Err(VolumeError::Io(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("relocate index for volume {}: move .idx: {e}", self.id),
|
||||
)));
|
||||
}
|
||||
|
||||
// The .sdx is a derived sorted index; move it when present, but a
|
||||
// failure is not fatal — drop the stale copy so a reload rebuilds it.
|
||||
let old_sdx = format!("{old_base}.sdx");
|
||||
if Path::new(&old_sdx).exists() {
|
||||
let new_sdx = format!("{new_base}.sdx");
|
||||
if let Err(e) = rename_or_copy(&old_sdx, &new_sdx) {
|
||||
warn!(
|
||||
"relocate volume {}: move .sdx: {} (will rebuild)",
|
||||
self.id, e
|
||||
);
|
||||
let _ = fs::remove_file(&old_sdx);
|
||||
}
|
||||
}
|
||||
|
||||
self.dir_idx = new_idx_dir.to_string();
|
||||
self.load(true, false, 0, version)
|
||||
}
|
||||
|
||||
/// Remove all volume files from disk.
|
||||
/// Destroy removes everything related to this volume. When keep_remote_data
|
||||
/// is true the cloud-tier object backing the volume is left intact — used
|
||||
@@ -3710,34 +3654,6 @@ pub fn volume_file_name(dir: &str, collection: &str, id: VolumeId) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Move `src` to `dst`, falling back to copy+remove when the two live on
|
||||
/// different filesystems (a real `-dir.idx` split). Mirrors Go's
|
||||
/// `RenameOrCopyFile`: any rename error other than cross-device is fatal, and a
|
||||
/// failed copy or a source that cannot be removed rolls the copy back so a
|
||||
/// failure never leaves two divergent files.
|
||||
fn rename_or_copy(src: &str, dst: &str) -> io::Result<()> {
|
||||
match fs::rename(src, dst) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) if e.raw_os_error() != Some(libc::EXDEV) => return Err(e),
|
||||
Err(_) => {}
|
||||
}
|
||||
fs::copy(src, dst)?;
|
||||
// fsync the destination before dropping the source, matching Go's out.Sync().
|
||||
if let Err(e) = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(dst)
|
||||
.and_then(|f| f.sync_all())
|
||||
{
|
||||
let _ = fs::remove_file(dst);
|
||||
return Err(e);
|
||||
}
|
||||
if let Err(e) = fs::remove_file(src) {
|
||||
let _ = fs::remove_file(dst);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate a monotonically increasing append timestamp.
|
||||
fn get_append_at_ns(last: u64) -> u64 {
|
||||
let now = SystemTime::now()
|
||||
@@ -4619,96 +4535,6 @@ mod tests {
|
||||
assert_eq!(std::str::from_utf8(&n.data).unwrap(), "data 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_relocate_index_to_moves_index_and_serves_reads() {
|
||||
let root = TempDir::new().unwrap();
|
||||
let data_dir = root.path().join("data");
|
||||
let idx_dir = root.path().join("idx");
|
||||
fs::create_dir_all(&data_dir).unwrap();
|
||||
fs::create_dir_all(&idx_dir).unwrap();
|
||||
let data = data_dir.to_str().unwrap();
|
||||
let idx = idx_dir.to_str().unwrap();
|
||||
|
||||
// Create the volume with its index co-located in the data dir (the state
|
||||
// an EC reconstruct leaves), write a needle, and flush.
|
||||
let mut v = Volume::new(
|
||||
data,
|
||||
data,
|
||||
"",
|
||||
VolumeId(7),
|
||||
NeedleMapKind::InMemory,
|
||||
None,
|
||||
None,
|
||||
0,
|
||||
Version::current(),
|
||||
)
|
||||
.unwrap();
|
||||
let payload = b"payload-across-relocate".to_vec();
|
||||
let mut n = Needle {
|
||||
id: NeedleId(42),
|
||||
cookie: Cookie(0x55),
|
||||
data: payload.clone(),
|
||||
data_size: payload.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
let data_idx = format!("{data}/7.idx");
|
||||
let idx_dir_idx = format!("{idx}/7.idx");
|
||||
assert!(
|
||||
Path::new(&data_idx).exists(),
|
||||
"precondition: index co-located with the data"
|
||||
);
|
||||
|
||||
v.relocate_index_to(idx).unwrap();
|
||||
|
||||
assert!(Path::new(&idx_dir_idx).exists(), "index moved to the idx dir");
|
||||
assert!(
|
||||
!Path::new(&data_idx).exists(),
|
||||
"index gone from the data dir"
|
||||
);
|
||||
assert_eq!(v.file_count(), 1);
|
||||
|
||||
// The volume reloaded in place, so the needle still reads back.
|
||||
let mut got = Needle {
|
||||
id: NeedleId(42),
|
||||
..Needle::default()
|
||||
};
|
||||
v.read_needle(&mut got).unwrap();
|
||||
assert_eq!(got.data, payload, "needle content survives the relocate");
|
||||
|
||||
// Relocating again is a no-op: the index is already where asked.
|
||||
v.relocate_index_to(idx).unwrap();
|
||||
assert!(Path::new(&idx_dir_idx).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_relocate_index_to_noop_when_already_in_place() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut v = make_test_volume(dir);
|
||||
let mut n = Needle {
|
||||
id: NeedleId(1),
|
||||
cookie: Cookie(1),
|
||||
data: b"x".to_vec(),
|
||||
data_size: 1,
|
||||
..Needle::default()
|
||||
};
|
||||
v.write_needle(&mut n, true).unwrap();
|
||||
v.sync_to_disk().unwrap();
|
||||
|
||||
// Data and index share a directory, so there is nothing to move.
|
||||
v.relocate_index_to(dir).unwrap();
|
||||
assert!(Path::new(&format!("{dir}/1.idx")).exists());
|
||||
let mut got = Needle {
|
||||
id: NeedleId(1),
|
||||
..Needle::default()
|
||||
};
|
||||
v.read_needle(&mut got).unwrap();
|
||||
assert_eq!(got.data, b"x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_volume_cookie_mismatch() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
//! Parity guard for the gRPC admin-auth gate.
|
||||
//!
|
||||
//! Every `VolumeServer` handler must either call `check_grpc_admin_auth` or be
|
||||
//! listed here as intentionally ungated, with the reason it stays open. Mirrors
|
||||
//! the Go side's `TestVolumeServerAdminAuthCoverage`
|
||||
//! (`weed/server/volume_grpc_admin_auth_coverage_test.go`). The gate had
|
||||
//! silently dropped off 15 handlers on the Rust side; this keeps the two
|
||||
//! implementations from drifting apart again.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Handlers that intentionally run without `check_grpc_admin_auth`, each with
|
||||
/// the reason. Kept in sync with `ungatedVolumeServerRPCs` on the Go side.
|
||||
///
|
||||
/// The split is by caller, not by how destructive the call is: the guard checks
|
||||
/// the peer IP against `-whiteList`, which holds masters, shell hosts and
|
||||
/// workers -- not every peer volume server. Gating a volume-server ->
|
||||
/// volume-server call therefore breaks replication, EC and tiering, so those
|
||||
/// calls stay open and need a cluster-peer identity before they can be closed.
|
||||
fn ungated_handlers() -> HashMap<&'static str, &'static str> {
|
||||
[
|
||||
// Cluster-internal: issued volume server -> volume server.
|
||||
("copy_file", "replica sync and EC task pull whole files from a peer"),
|
||||
("read_needle_blob", "replica sync, vacuum and EC rebuild read needles from a peer"),
|
||||
("read_needle_meta", "replica sync compares needle metadata across peers"),
|
||||
("write_needle_blob", "replica sync repairs a peer's needle"),
|
||||
("receive_file", "EC shard distribution pushes shards to a peer"),
|
||||
("read_volume_file_status", "the copy path queries the source volume server"),
|
||||
("volume_ec_shard_read", "a volume server reads EC shards held by a peer"),
|
||||
("volume_ec_blob_delete", "EC delete is fanned out to the shard holders"),
|
||||
("volume_ec_shards_info", "EC verification polls shard holders"),
|
||||
("volume_ec_shards_mount", "EC shard distribution mounts on the receiving peer"),
|
||||
("volume_incremental_copy", "volume backup pulls increments from a peer"),
|
||||
("volume_sync_status", "sync compares volume state across peers"),
|
||||
("volume_tail_sender", "the tail source streams to the receiving peer"),
|
||||
("volume_status", "replica sync and the master's vacuum loop poll volume status"),
|
||||
// Read-only or liveness: no state change.
|
||||
("ping", "liveness probe"),
|
||||
("get_state", "read-only volume server state"),
|
||||
("query", "read-only data query"),
|
||||
("vacuum_volume_check", "read-only garbage ratio; the vacuum steps that act on it are gated"),
|
||||
("volume_server_status", "read-only status, the gRPC counterpart of the /status page"),
|
||||
]
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a handler body actually invokes the gate. We can't run a real AST
|
||||
/// pass like the Go side without pulling in a parser, so approximate it: drop
|
||||
/// `//` line comments (the realistic way a stray mention would sneak in) and
|
||||
/// look for the call form `check_grpc_admin_auth(`, not the bare identifier, so
|
||||
/// a comment or doc reference can't make an ungated handler pass.
|
||||
fn calls_gate(body: &str) -> bool {
|
||||
body.lines()
|
||||
.map(|line| line.split_once("//").map_or(line, |(code, _)| code))
|
||||
.any(|code| code.contains("check_grpc_admin_auth("))
|
||||
}
|
||||
|
||||
/// Enumerate the `VolumeServer` trait handlers and whether each gates on
|
||||
/// `check_grpc_admin_auth`, by scanning the source of the trait impl block.
|
||||
fn handler_gating(src: &str) -> Vec<(String, bool)> {
|
||||
let impl_start = src
|
||||
.find("impl VolumeServer for VolumeGrpcService {")
|
||||
.expect("locate the VolumeServer trait impl");
|
||||
let after = &src[impl_start..];
|
||||
// rustfmt keeps every method body indented, so the impl's own closing brace
|
||||
// is the first line that begins at column 0.
|
||||
let impl_end = after
|
||||
.match_indices("\n}")
|
||||
.next()
|
||||
.map(|(i, _)| i + 1)
|
||||
.expect("locate the end of the trait impl");
|
||||
let block = &after[..impl_end];
|
||||
|
||||
let marker = "\n async fn ";
|
||||
let starts: Vec<usize> = block.match_indices(marker).map(|(i, _)| i).collect();
|
||||
let mut handlers = Vec::with_capacity(starts.len());
|
||||
for (i, &start) in starts.iter().enumerate() {
|
||||
let name_start = start + marker.len();
|
||||
let name_end = name_start
|
||||
+ block[name_start..]
|
||||
.find('(')
|
||||
.expect("handler signature has an argument list");
|
||||
let name = block[name_start..name_end].to_string();
|
||||
let body_end = starts.get(i + 1).copied().unwrap_or(block.len());
|
||||
let gated = calls_gate(&block[start..body_end]);
|
||||
handlers.push((name, gated));
|
||||
}
|
||||
handlers
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_server_admin_auth_coverage() {
|
||||
let src = std::fs::read_to_string(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/src/server/grpc_server.rs"
|
||||
))
|
||||
.expect("read grpc_server.rs");
|
||||
|
||||
let handlers = handler_gating(&src);
|
||||
assert!(
|
||||
handlers.len() >= 40,
|
||||
"parsed only {} handlers from the trait impl, expected the full service",
|
||||
handlers.len()
|
||||
);
|
||||
|
||||
let ungated = ungated_handlers();
|
||||
let mut problems = Vec::new();
|
||||
for (name, gated) in &handlers {
|
||||
match (gated, ungated.contains_key(name.as_str())) {
|
||||
(true, true) => problems.push(format!(
|
||||
"{name} calls check_grpc_admin_auth but is also listed as intentionally ungated; drop it from ungated_handlers"
|
||||
)),
|
||||
(false, false) => problems.push(format!(
|
||||
"{name} does not call check_grpc_admin_auth and is not listed as intentionally ungated; gate it, or add it with the reason it must stay open"
|
||||
)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the exemption list honest: an entry for a handler that no longer
|
||||
// exists hides the fact that nothing is being exempted.
|
||||
let names: HashSet<&str> = handlers.iter().map(|(n, _)| n.as_str()).collect();
|
||||
for name in ungated.keys() {
|
||||
if !names.contains(name) {
|
||||
problems.push(format!(
|
||||
"ungated_handlers lists \"{name}\", which is not a VolumeServer handler"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
assert!(problems.is_empty(), "admin-auth coverage gaps:\n{}", problems.join("\n"));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -289,11 +289,16 @@ func uploadPayload(data []byte) (needle.VolumeId, string, error) {
|
||||
return fidObj.VolumeId, assignResult.Fid, nil
|
||||
}
|
||||
|
||||
// readClient bounds every read so a restarting or stalled server cannot hang
|
||||
// the request past the Eventually deadline and the test's own context — a
|
||||
// slow location has to fail and be retried, not block.
|
||||
var readClient = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
// readFid locates the volume via the master and fetches the needle bytes from
|
||||
// a currently-registered location — the same route a client read takes, for a
|
||||
// plain volume before encoding and for the EC read path after.
|
||||
func readFid(fid string, volumeId uint32) ([]byte, error) {
|
||||
resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:9334/dir/lookup?volumeId=%d", volumeId))
|
||||
resp, err := readClient.Get(fmt.Sprintf("http://127.0.0.1:9334/dir/lookup?volumeId=%d", volumeId))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -311,7 +316,7 @@ func readFid(fid string, volumeId uint32) ([]byte, error) {
|
||||
}
|
||||
var lastErr error
|
||||
for _, loc := range lookup.Locations {
|
||||
get, err := http.Get(fmt.Sprintf("http://%s/%s", loc.Url, fid))
|
||||
get, err := readClient.Get(fmt.Sprintf("http://%s/%s", loc.Url, fid))
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
|
||||
@@ -1,232 +0,0 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/shell"
|
||||
)
|
||||
|
||||
// TestECInterruptionMatrix is the systematic counterpart of the randomized
|
||||
// chaos harness: instead of killing operations at random times, it enumerates
|
||||
// every phase of every interruptible EC operation and kills a real weed shell
|
||||
// exactly when that phase announces itself on the command's output. Each
|
||||
// (operation, phase) pair is one deterministic scenario: prepare the
|
||||
// precondition, kill at the phase marker, run the prescribed recovery, and
|
||||
// verify that every stored byte still reads back identical.
|
||||
//
|
||||
// The phase markers are the progress lines the pipelines print; each marker
|
||||
// below names the code that prints it. A marker is the START of its phase, so
|
||||
// killing on it lands the interruption inside that phase — deterministically
|
||||
// per phase, byte-exact timing within the phase left to the scheduler. Every
|
||||
// scenario REQUIRES its marker to appear: a marker that never prints means a
|
||||
// pipeline refactor renamed or dropped the progress line, and silently
|
||||
// degenerating into a no-interruption run would let CI pass without
|
||||
// exercising the boundary the scenario names. Update the marker with the
|
||||
// pipeline.
|
||||
//
|
||||
// Complementing this, weed/ec's TestECLifecycleModelExhaustive explores every
|
||||
// schedule of the same pipelines — crashes between every step, rollback
|
||||
// paths, restarts — exhaustively on a model whose steps mirror the code.
|
||||
func TestECInterruptionMatrix(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping EC interruption matrix in short mode")
|
||||
}
|
||||
|
||||
testDir := t.TempDir()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
cluster, err := startChaosCluster(ctx, testDir)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
require.NoError(t, waitForServer(chaosMasterAddr, 30*time.Second))
|
||||
for i := 0; i < chaosServerCount; i++ {
|
||||
require.NoError(t, waitForServer("127.0.0.1:"+chaosVolumePort(i), 30*time.Second))
|
||||
}
|
||||
time.Sleep(8 * time.Second)
|
||||
|
||||
commandEnv := shell.NewCommandEnv(&shell.ShellOptions{
|
||||
Masters: stringPtr(chaosMasterAddr),
|
||||
GrpcDialOption: grpc.WithInsecure(),
|
||||
FilerGroup: stringPtr("default"),
|
||||
})
|
||||
connectToMasterAndSync(ctx, t, commandEnv)
|
||||
|
||||
r := newChaosRun(t, ctx, cluster, commandEnv, testDir, 1)
|
||||
r.relock()
|
||||
defer r.unlockIfHeld()
|
||||
r.seedAndSpread()
|
||||
r.verify("seeding")
|
||||
|
||||
// One scenario per (operation, phase marker). The preparation puts a
|
||||
// dedicated volume into the operation's precondition state, so scenarios
|
||||
// stay independent even though they share the cluster.
|
||||
type scenario struct {
|
||||
op string
|
||||
marker string // printed by ↓
|
||||
printed string // the code that prints it, for the reader
|
||||
}
|
||||
encodeScenarios := []scenario{
|
||||
{"ec.encode", "markVolumeReadonly ", "weed/ec markVolumeReplicaWritable"},
|
||||
{"ec.encode", "generateEcShards ", "weed/ec generateEcShards"},
|
||||
{"ec.encode", "mount ", "weed/ec MountEcShards"},
|
||||
{"ec.encode", "Deleting original volumes", "weed/ec ProcessEcEncodeBatch, the commit boundary"},
|
||||
}
|
||||
decodeScenarios := []scenario{
|
||||
{"ec.decode", " shard locations:", "weed/ec DoEcDecode, before collect"},
|
||||
{"ec.decode", "generateNormalVolume", "weed/ec generateNormalVolume"},
|
||||
{"ec.decode", "unmount ec volume", "weed/ec unmountAndDeleteEcShards, teardown begin"},
|
||||
{"ec.decode", "delete ec volume", "weed/ec unmountAndDeleteEcShards, shard deletion"},
|
||||
}
|
||||
|
||||
for _, sc := range encodeScenarios {
|
||||
sc := sc
|
||||
t.Run(fmt.Sprintf("encode@%s", trimMarker(sc.marker)), func(t *testing.T) {
|
||||
vid := r.ensureRegularVolume()
|
||||
r.unlockIfHeld()
|
||||
out, hit := runShellKillAtMarker(t, r.ctx,
|
||||
fmt.Sprintf("ec.encode -volumeId %d -collection %s -force", vid, chaosCollection), sc.marker)
|
||||
r.t.Logf("killed %s at %q (marker hit: %v); output:\n%s", sc.op, sc.marker, hit, out)
|
||||
r.relock()
|
||||
require.True(t, hit, "marker %q never appeared (printed by %s); update the marker with the pipeline", sc.marker, sc.printed)
|
||||
r.recoverInterruptedEncode(vid)
|
||||
r.verify(fmt.Sprintf("encode killed at %q", sc.marker))
|
||||
})
|
||||
}
|
||||
for _, sc := range decodeScenarios {
|
||||
sc := sc
|
||||
t.Run(fmt.Sprintf("decode@%s", trimMarker(sc.marker)), func(t *testing.T) {
|
||||
vid := r.ensureEncodedVolume()
|
||||
r.unlockIfHeld()
|
||||
out, hit := runShellKillAtMarker(t, r.ctx,
|
||||
fmt.Sprintf("ec.decode -volumeId %d -collection %s -checkMinFreeSpace=false", vid, chaosCollection), sc.marker)
|
||||
r.t.Logf("killed %s at %q (marker hit: %v); output:\n%s", sc.op, sc.marker, hit, out)
|
||||
r.relock()
|
||||
require.True(t, hit, "marker %q never appeared (printed by %s); update the marker with the pipeline", sc.marker, sc.printed)
|
||||
r.recoverInterruptedDecode(vid)
|
||||
r.verify(fmt.Sprintf("decode killed at %q", sc.marker))
|
||||
})
|
||||
}
|
||||
|
||||
// Balance: encode without rebalancing first, so the standalone balance is
|
||||
// guaranteed to plan moves and the marker is guaranteed to print.
|
||||
t.Run("balance@moves", func(t *testing.T) {
|
||||
vid := r.ensureRegularVolume()
|
||||
out, err := r.shellCommand("ec.encode",
|
||||
"-volumeId", fmt.Sprintf("%d", vid), "-collection", chaosCollection, "-force", "-rebalance=false")
|
||||
r.t.Logf("clumped encode v%d output:\n%s", vid, out)
|
||||
require.NoError(t, err, "encode without rebalance")
|
||||
r.volumes[vid].encoded = true
|
||||
|
||||
r.unlockIfHeld()
|
||||
killOut, hit := runShellKillAtMarker(t, r.ctx,
|
||||
fmt.Sprintf("ec.balance -collection %s -apply", chaosCollection), "moves ec shard")
|
||||
r.t.Logf("killed ec.balance at move (marker hit: %v); output:\n%s", hit, killOut)
|
||||
r.relock()
|
||||
require.True(t, hit, "the balance never printed a move; the -rebalance=false setup should have guaranteed one")
|
||||
r.recoverInterruptedBalance()
|
||||
r.verify("balance killed at move")
|
||||
})
|
||||
|
||||
r.verify("final")
|
||||
t.Logf("interruption matrix done: %d payloads live, %d deleted, %d volumes tracked",
|
||||
len(r.payloads), len(r.deleted), len(r.volumes))
|
||||
}
|
||||
|
||||
func trimMarker(m string) string {
|
||||
out := make([]rune, 0, len(m))
|
||||
for _, c := range m {
|
||||
if c == ' ' || c == ':' {
|
||||
continue
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// runShellKillAtMarker feeds "lock" plus the command to a weed shell
|
||||
// subprocess, scans its combined output live, and kills the process the
|
||||
// moment a line containing marker appears. Returns the captured output and
|
||||
// whether the marker was seen before the shell exited on its own.
|
||||
func runShellKillAtMarker(t *testing.T, ctx context.Context, command, marker string) (string, bool) {
|
||||
t.Helper()
|
||||
weedBinary := findWeedBinary()
|
||||
require.NotEmpty(t, weedBinary, "weed binary not found")
|
||||
cmd := exec.CommandContext(ctx, weedBinary, "shell", "-master="+chaosMasterAddr)
|
||||
|
||||
pr, pw, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
cmd.Stdout, cmd.Stderr = pw, pw
|
||||
stdin, err := cmd.StdinPipe()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, cmd.Start())
|
||||
pw.Close() // the child keeps its dup; ours would hold the reader open
|
||||
|
||||
var buf bytes.Buffer
|
||||
var mu sync.Mutex
|
||||
markerSeen := make(chan struct{})
|
||||
scanDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(scanDone)
|
||||
signaled := false
|
||||
scanner := bufio.NewScanner(pr)
|
||||
scanner.Buffer(make([]byte, 0, 256*1024), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
mu.Lock()
|
||||
buf.WriteString(line)
|
||||
buf.WriteByte('\n')
|
||||
mu.Unlock()
|
||||
if !signaled && bytesContains(line, marker) {
|
||||
signaled = true
|
||||
close(markerSeen)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
fmt.Fprintf(stdin, "lock\n%s\n", command)
|
||||
// Stdin stays open: the shell must die by kill, never by graceful EOF —
|
||||
// a graceful exit would release the cluster lock cleanly and dodge the
|
||||
// dead-holder cleanup path this test also exercises.
|
||||
hit := false
|
||||
select {
|
||||
case <-markerSeen:
|
||||
hit = true
|
||||
case <-scanDone: // shell exited before printing the marker
|
||||
case <-time.After(90 * time.Second):
|
||||
}
|
||||
if !hit {
|
||||
// A shell that printed the marker and exited immediately can make both
|
||||
// channels ready at once, and select picks between ready cases at
|
||||
// random; a printed marker must never be reported as missed.
|
||||
select {
|
||||
case <-markerSeen:
|
||||
hit = true
|
||||
default:
|
||||
}
|
||||
}
|
||||
cmd.Process.Kill()
|
||||
cmd.Wait()
|
||||
pr.Close()
|
||||
<-scanDone
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return buf.String(), hit
|
||||
}
|
||||
|
||||
func bytesContains(line, marker string) bool {
|
||||
return len(marker) > 0 && strings.Contains(line, marker)
|
||||
}
|
||||
@@ -32,7 +32,6 @@ type VolumeServer struct {
|
||||
|
||||
mu sync.Mutex
|
||||
receivedFiles map[string]uint64
|
||||
readonlyVolumes map[uint32]bool
|
||||
mountRequests []*volume_server_pb.VolumeEcShardsMountRequest
|
||||
deleteRequests []*volume_server_pb.VolumeDeleteRequest
|
||||
markReadonlyCalls int
|
||||
@@ -68,13 +67,12 @@ func NewVolumeServer(t *testing.T, baseDir string) *VolumeServer {
|
||||
grpcPort := listener.Addr().(*net.TCPAddr).Port
|
||||
server := pb.NewGrpcServer()
|
||||
vs := &VolumeServer{
|
||||
t: t,
|
||||
server: server,
|
||||
listener: listener,
|
||||
address: fmt.Sprintf("127.0.0.1:0.%d", grpcPort),
|
||||
baseDir: baseDir,
|
||||
receivedFiles: make(map[string]uint64),
|
||||
readonlyVolumes: make(map[uint32]bool),
|
||||
t: t,
|
||||
server: server,
|
||||
listener: listener,
|
||||
address: fmt.Sprintf("127.0.0.1:0.%d", grpcPort),
|
||||
baseDir: baseDir,
|
||||
receivedFiles: make(map[string]uint64),
|
||||
}
|
||||
|
||||
volume_server_pb.RegisterVolumeServerServer(server, vs)
|
||||
@@ -388,9 +386,6 @@ func (v *VolumeServer) VolumeDelete(ctx context.Context, req *volume_server_pb.V
|
||||
func (v *VolumeServer) VolumeMarkReadonly(ctx context.Context, req *volume_server_pb.VolumeMarkReadonlyRequest) (*volume_server_pb.VolumeMarkReadonlyResponse, error) {
|
||||
v.mu.Lock()
|
||||
v.markReadonlyCalls++
|
||||
if req != nil {
|
||||
v.readonlyVolumes[req.VolumeId] = true
|
||||
}
|
||||
v.mu.Unlock()
|
||||
return &volume_server_pb.VolumeMarkReadonlyResponse{}, nil
|
||||
}
|
||||
@@ -398,19 +393,10 @@ func (v *VolumeServer) VolumeMarkReadonly(ctx context.Context, req *volume_serve
|
||||
func (v *VolumeServer) VolumeMarkWritable(ctx context.Context, req *volume_server_pb.VolumeMarkWritableRequest) (*volume_server_pb.VolumeMarkWritableResponse, error) {
|
||||
v.mu.Lock()
|
||||
v.markWritableCalls++
|
||||
if req != nil {
|
||||
v.readonlyVolumes[req.VolumeId] = false
|
||||
}
|
||||
v.mu.Unlock()
|
||||
return &volume_server_pb.VolumeMarkWritableResponse{}, nil
|
||||
}
|
||||
|
||||
func (v *VolumeServer) VolumeStatus(ctx context.Context, req *volume_server_pb.VolumeStatusRequest) (*volume_server_pb.VolumeStatusResponse, error) {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
return &volume_server_pb.VolumeStatusResponse{IsReadOnly: v.readonlyVolumes[req.GetVolumeId()]}, nil
|
||||
}
|
||||
|
||||
func (v *VolumeServer) ReadVolumeFileStatus(ctx context.Context, req *volume_server_pb.ReadVolumeFileStatusRequest) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
|
||||
v.mu.Lock()
|
||||
v.readFileStatusCalls++
|
||||
|
||||
@@ -146,14 +146,13 @@ func TestVolumeBalanceBatchExecutionIntegration(t *testing.T) {
|
||||
require.True(t, deletedVols[vid], "volume %d should have been deleted from source", vid)
|
||||
}
|
||||
|
||||
// Each move reads source status once inside the target's fake VolumeCopy
|
||||
// implementation and once for the pre-delete verification, and reads
|
||||
// target status once probing for a pre-existing copy and once for the
|
||||
// verification.
|
||||
// Each move reads source status once before copy and once inside the
|
||||
// target's fake VolumeCopy implementation, then reads target status once
|
||||
// before deleting the source.
|
||||
require.Equal(t, len(volumeIDs)*2, source.ReadFileStatusCount(),
|
||||
"each move should read source volume status during target copy and at verification")
|
||||
require.Equal(t, len(volumeIDs)*2, target.ReadFileStatusCount(),
|
||||
"each move should probe the target and read its status at verification")
|
||||
"each move should read source volume status before copy and during target copy")
|
||||
require.Equal(t, len(volumeIDs), target.ReadFileStatusCount(),
|
||||
"each move should read target volume status before delete")
|
||||
|
||||
// Target should have received copy and tail calls for all 3 volumes.
|
||||
copyCalls, _, tailCalls := target.BalanceStats()
|
||||
|
||||
@@ -600,9 +600,9 @@ func testExpireSnapshots(t *testing.T) {
|
||||
|
||||
handler := icebergHandler.NewHandler(nil)
|
||||
config := icebergHandler.Config{
|
||||
SnapshotRetentionMs: 0, // instant expiry — everything eligible
|
||||
MaxSnapshotsToKeep: 1, // keep only the current snapshot
|
||||
MaxCommitRetries: 3,
|
||||
SnapshotRetentionHours: 0, // instant expiry — everything eligible
|
||||
MaxSnapshotsToKeep: 1, // keep only the current snapshot
|
||||
MaxCommitRetries: 3,
|
||||
}
|
||||
|
||||
result, _, err := handler.ExpireSnapshots(context.Background(), client, bucket, path.Join(ns, tbl), config)
|
||||
@@ -796,7 +796,7 @@ func testCompactDataFiles(t *testing.T) {
|
||||
}
|
||||
|
||||
require.Len(t, addedPaths, 1, "compaction should add exactly one merged parquet file")
|
||||
assert.Contains(t, addedPaths, fmt.Sprintf("s3://%s/%s/data/%s", bucket, tablePath, compacted.Name))
|
||||
assert.Contains(t, addedPaths, path.Join("data", compacted.Name))
|
||||
require.Len(t, deletedPaths, len(files), "compaction should delete every original small input file")
|
||||
for _, file := range files {
|
||||
assert.Contains(t, deletedPaths, path.Join("data", file.name))
|
||||
@@ -932,9 +932,9 @@ func testFullMaintenanceCycle(t *testing.T) {
|
||||
|
||||
// Step 1: Expire snapshots
|
||||
expireConfig := icebergHandler.Config{
|
||||
SnapshotRetentionMs: 0, // instant expiry
|
||||
MaxSnapshotsToKeep: 1,
|
||||
MaxCommitRetries: 3,
|
||||
SnapshotRetentionHours: 0, // instant expiry
|
||||
MaxSnapshotsToKeep: 1,
|
||||
MaxCommitRetries: 3,
|
||||
}
|
||||
result, _, err := handler.ExpireSnapshots(ctx, client, bucket, tablePath, expireConfig)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -44,10 +44,6 @@ type AdminData struct {
|
||||
// Trends holds at-a-glance sparklines built from the admin's own recent
|
||||
// cluster snapshots (no Prometheus required).
|
||||
Trends DashboardTrends `json:"trends"`
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// Object Store Users management structures
|
||||
@@ -217,7 +213,6 @@ func (s *AdminServer) GetAdminData(username string) (AdminData, error) {
|
||||
TotalEcShards: totalEcShards,
|
||||
TotalMountClients: totalMountClients,
|
||||
Trends: s.GetDashboardTrends(),
|
||||
TierStats: topology.TierStats,
|
||||
}
|
||||
|
||||
return adminData, nil
|
||||
|
||||
@@ -125,12 +125,6 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
}
|
||||
|
||||
if resp.TopologyInfo != nil {
|
||||
// Get volume size limit from response, default to 30GB if not set
|
||||
volumeSizeLimitMb := resp.VolumeSizeLimitMb
|
||||
if volumeSizeLimitMb == 0 {
|
||||
volumeSizeLimitMb = 30000
|
||||
}
|
||||
|
||||
// Process gRPC response
|
||||
for _, dc := range resp.TopologyInfo.DataCenterInfos {
|
||||
dataCenter := DataCenter{
|
||||
@@ -149,7 +143,6 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
var totalVolumes int64
|
||||
var totalMaxVolumes int64
|
||||
var totalSize int64
|
||||
var remoteSize int64
|
||||
// Prefer the real physical disk capacity the volume server
|
||||
// reports per disk; the slot-based estimate overstates capacity
|
||||
// when maxVolumeCount is configured higher than the disk holds.
|
||||
@@ -161,18 +154,12 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
if diskInfo.DiskTotalBytes > 0 {
|
||||
diskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
} else {
|
||||
diskCapacity += diskInfo.MaxVolumeCount * int64(volumeSizeLimitMb) * 1024 * 1024
|
||||
diskCapacity += diskInfo.MaxVolumeCount * int64(resp.VolumeSizeLimitMb) * 1024 * 1024
|
||||
}
|
||||
|
||||
// A remote-tiered volume reports its cloud object's
|
||||
// size; keep those bytes out of the local disk usage
|
||||
// that is compared against diskCapacity.
|
||||
// Sum up individual volume information
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
if volInfo.RemoteStorageName != "" {
|
||||
remoteSize += int64(volInfo.Size)
|
||||
} else {
|
||||
totalSize += int64(volInfo.Size)
|
||||
}
|
||||
totalSize += int64(volInfo.Size)
|
||||
}
|
||||
|
||||
// ShardSizes is local to this node, so summing
|
||||
@@ -206,15 +193,12 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
DiskUsage: totalSize,
|
||||
DiskCapacity: diskCapacity,
|
||||
LastHeartbeat: time.Now(),
|
||||
RemoteSize: remoteSize,
|
||||
}
|
||||
|
||||
rackObj.Nodes = append(rackObj.Nodes, vs)
|
||||
topology.VolumeServers = append(topology.VolumeServers, vs)
|
||||
topology.TotalVolumes += vs.Volumes
|
||||
// TotalSize is the logical data size, wherever the
|
||||
// bytes live, so remote-tiered volumes still count.
|
||||
topology.TotalSize += totalSize + remoteSize
|
||||
topology.TotalSize += totalSize
|
||||
}
|
||||
|
||||
dataCenter.Racks = append(dataCenter.Racks, rackObj)
|
||||
@@ -227,8 +211,6 @@ func (s *AdminServer) getTopologyViaGRPC(topology *ClusterTopology) error {
|
||||
// nets out tombstones and counts a chunk once no matter how many
|
||||
// volume replicas or EC shard holders report it.
|
||||
topology.TotalChunks = totalCollectionFileCount(resp.TopologyInfo)
|
||||
|
||||
topology.TierStats = CollectTierStats(resp.TopologyInfo, volumeSizeLimitMb)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -66,7 +66,6 @@ func (s *AdminServer) GetClusterEcShards(page int, pageSize int, sortBy string,
|
||||
|
||||
// Create individual shard entries for each shard this server has
|
||||
shardBits := ecShardInfo.EcIndexBits
|
||||
shardsInfo := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(ecShardInfo)
|
||||
for shardId := 0; shardId < erasure_coding.MaxShardCount; shardId++ {
|
||||
if (shardBits & (1 << uint(shardId))) != 0 {
|
||||
// Mark this shard as present for this volume
|
||||
@@ -76,7 +75,7 @@ func (s *AdminServer) GetClusterEcShards(page int, pageSize int, sortBy string,
|
||||
VolumeID: volumeId,
|
||||
ShardID: uint32(shardId),
|
||||
Collection: ecShardInfo.Collection,
|
||||
Size: uint64(shardsInfo.Size(erasure_coding.ShardId(shardId))),
|
||||
Size: 0, // EC shards don't have individual size in the API response
|
||||
Server: node.Id,
|
||||
DataCenter: dc.Id,
|
||||
Rack: rack.Id,
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// TierStats aggregates the volumes and EC shards that live on one storage
|
||||
// tier: a local disk type ("hdd", "ssd", or a custom tag), or the remote
|
||||
// storage a tiered volume was uploaded to. A remote-tiered volume reports
|
||||
// the size of its cloud object, so its bytes belong to the remote tier,
|
||||
// not to the local disk that holds only its index.
|
||||
type TierStats struct {
|
||||
Name string `json:"name"`
|
||||
IsRemote bool `json:"is_remote"`
|
||||
VolumeCount int `json:"volume_count"`
|
||||
EcShardCount int `json:"ec_shard_count"`
|
||||
DataSize int64 `json:"data_size"`
|
||||
DiskUsed int64 `json:"disk_used"`
|
||||
DiskCapacity int64 `json:"disk_capacity"`
|
||||
MaxVolumes int64 `json:"max_volumes"`
|
||||
}
|
||||
|
||||
// UsagePercent is the tier's local disk usage in percent, clamped to
|
||||
// [0, 100]. Remote tiers have no capacity and return 0.
|
||||
func (t TierStats) UsagePercent() int {
|
||||
if t.IsRemote || t.DiskCapacity <= 0 {
|
||||
return 0
|
||||
}
|
||||
percent := int(float64(t.DiskUsed) / float64(t.DiskCapacity) * 100)
|
||||
if percent < 0 {
|
||||
return 0
|
||||
}
|
||||
if percent > 100 {
|
||||
return 100
|
||||
}
|
||||
return percent
|
||||
}
|
||||
|
||||
// tierDiskType maps the empty disk type to its display name.
|
||||
func tierDiskType(diskType string) string {
|
||||
if diskType == "" {
|
||||
return "hdd"
|
||||
}
|
||||
return diskType
|
||||
}
|
||||
|
||||
// CollectTierStats walks the topology and groups capacity and usage by
|
||||
// tier. DiskUsed/DiskCapacity come from the statfs numbers the volume
|
||||
// servers report per disk type; a disk that predates disk_total_bytes
|
||||
// falls back to the slot-based capacity estimate and to the logical
|
||||
// bytes it holds, so mixed-version tiers don't underreport usage.
|
||||
// Remote tiers have no local disk, so only VolumeCount and DataSize are
|
||||
// meaningful there.
|
||||
func CollectTierStats(topo *master_pb.TopologyInfo, volumeSizeLimitMb uint64) []TierStats {
|
||||
if topo == nil {
|
||||
return nil
|
||||
}
|
||||
tiers := make(map[string]*TierStats)
|
||||
tier := func(name string, isRemote bool) *TierStats {
|
||||
key := name
|
||||
if isRemote {
|
||||
key = "remote\x00" + name
|
||||
}
|
||||
t := tiers[key]
|
||||
if t == nil {
|
||||
t = &TierStats{Name: name, IsRemote: isRemote}
|
||||
tiers[key] = t
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
for _, dc := range topo.DataCenterInfos {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for _, node := range rack.DataNodeInfos {
|
||||
for _, diskInfo := range node.DiskInfos {
|
||||
local := tier(tierDiskType(diskInfo.Type), false)
|
||||
local.MaxVolumes += diskInfo.MaxVolumeCount
|
||||
hasStatfs := diskInfo.DiskTotalBytes > 0
|
||||
if hasStatfs {
|
||||
local.DiskCapacity += int64(diskInfo.DiskTotalBytes)
|
||||
if diskInfo.DiskTotalBytes > diskInfo.DiskFreeBytes {
|
||||
local.DiskUsed += int64(diskInfo.DiskTotalBytes - diskInfo.DiskFreeBytes)
|
||||
}
|
||||
} else {
|
||||
local.DiskCapacity += diskInfo.MaxVolumeCount * int64(volumeSizeLimitMb) * 1024 * 1024
|
||||
}
|
||||
|
||||
var diskLocalBytes int64
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
if volInfo.RemoteStorageName != "" {
|
||||
remote := tier(volInfo.RemoteStorageName, true)
|
||||
remote.VolumeCount++
|
||||
remote.DataSize += int64(volInfo.Size)
|
||||
} else {
|
||||
local.VolumeCount++
|
||||
local.DataSize += int64(volInfo.Size)
|
||||
diskLocalBytes += int64(volInfo.Size)
|
||||
}
|
||||
}
|
||||
|
||||
// ShardSizes is local to this node, so summing across
|
||||
// nodes gives the tier's physical footprint.
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
local.EcShardCount += erasure_coding.GetShardCount(ecShardInfo)
|
||||
ecBytes := erasure_coding.EcShardsTotalSize(ecShardInfo)
|
||||
local.DataSize += ecBytes
|
||||
diskLocalBytes += ecBytes
|
||||
}
|
||||
|
||||
// Without statfs numbers, approximate this disk's
|
||||
// footprint with the logical bytes it holds.
|
||||
if !hasStatfs {
|
||||
local.DiskUsed += diskLocalBytes
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result := make([]TierStats, 0, len(tiers))
|
||||
for _, t := range tiers {
|
||||
result = append(result, *t)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].IsRemote != result[j].IsRemote {
|
||||
return !result[i].IsRemote
|
||||
}
|
||||
return result[i].Name < result[j].Name
|
||||
})
|
||||
return result
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
)
|
||||
|
||||
func TestCollectTierStats(t *testing.T) {
|
||||
topo := &master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{
|
||||
Id: "node1:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {
|
||||
Type: "",
|
||||
MaxVolumeCount: 10,
|
||||
DiskTotalBytes: 1_000_000,
|
||||
DiskFreeBytes: 400_000,
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{
|
||||
{Id: 1, Size: 1000},
|
||||
{Id: 2, Size: 5000, RemoteStorageName: "s3.backup", RemoteStorageKey: "/2.dat"},
|
||||
},
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{
|
||||
{Id: 7, EcIndexBits: 0b111, ShardSizes: []int64{10, 20, 30}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: "node2:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"ssd": {
|
||||
Type: "ssd",
|
||||
MaxVolumeCount: 5,
|
||||
// No statfs numbers: capacity falls back to
|
||||
// slots and usage to logical bytes.
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{
|
||||
{Id: 3, Size: 2000, DiskType: "ssd"},
|
||||
{Id: 4, Size: 7000, DiskType: "ssd", RemoteStorageName: "s3.backup", RemoteStorageKey: "/4.dat"},
|
||||
{Id: 5, Size: 100, DiskType: "ssd", RemoteStorageName: "gcs.archive", RemoteStorageKey: "/5.dat"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
// An old server without statfs numbers sharing the
|
||||
// hdd tier with node1: its logical bytes must still
|
||||
// count toward the tier's DiskUsed.
|
||||
Id: "node3:8080",
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"": {
|
||||
Type: "",
|
||||
MaxVolumeCount: 2,
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{
|
||||
{Id: 6, Size: 800},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}
|
||||
|
||||
got := CollectTierStats(topo, 30)
|
||||
|
||||
want := []TierStats{
|
||||
{Name: "hdd", VolumeCount: 2, EcShardCount: 3, DataSize: 1860, DiskUsed: 600_800, DiskCapacity: 1_000_000 + 2*30*1024*1024, MaxVolumes: 12},
|
||||
{Name: "ssd", VolumeCount: 1, DataSize: 2000, DiskUsed: 2000, DiskCapacity: 5 * 30 * 1024 * 1024, MaxVolumes: 5},
|
||||
{Name: "gcs.archive", IsRemote: true, VolumeCount: 1, DataSize: 100},
|
||||
{Name: "s3.backup", IsRemote: true, VolumeCount: 2, DataSize: 12000},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("CollectTierStats mismatch:\n got: %+v\nwant: %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectTierStatsEmpty(t *testing.T) {
|
||||
if got := CollectTierStats(nil, 30); got != nil {
|
||||
t.Errorf("expected nil for nil topology, got %+v", got)
|
||||
}
|
||||
if got := CollectTierStats(&master_pb.TopologyInfo{}, 30); len(got) != 0 {
|
||||
t.Errorf("expected no tiers for empty topology, got %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,6 @@ type ClusterTopology struct {
|
||||
TotalChunks int64 `json:"total_chunks"`
|
||||
TotalSize int64 `json:"total_size"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// 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"`
|
||||
}
|
||||
|
||||
type MasterNode struct {
|
||||
@@ -55,11 +52,6 @@ type VolumeServer struct {
|
||||
EcVolumes int `json:"ec_volumes"` // Number of EC volumes this server has shards for
|
||||
EcShards int `json:"ec_shards"` // Total number of EC shards on this server
|
||||
EcShardDetails []VolumeServerEcInfo `json:"ec_shard_details"` // Detailed EC shard information
|
||||
|
||||
// RemoteSize is the bytes this server's remote-tiered volumes hold in
|
||||
// cloud storage. Those bytes are excluded from DiskUsage, which only
|
||||
// counts what occupies local disks.
|
||||
RemoteSize int64 `json:"remote_size"`
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) GetDisplayAddress() string {
|
||||
|
||||
@@ -122,11 +122,7 @@ func (s *AdminServer) GetClusterVolumes(page int, pageSize int, sortBy string, s
|
||||
diskTypeMap := make(map[string]bool)
|
||||
collectionMap := make(map[string]bool)
|
||||
versionMap := make(map[string]bool)
|
||||
hasRemoteVolumes := false
|
||||
for _, volume := range volumes {
|
||||
if volume.RemoteStorageName != "" {
|
||||
hasRemoteVolumes = true
|
||||
}
|
||||
if volume.DataCenter != "" {
|
||||
dataCenterMap[volume.DataCenter] = true
|
||||
}
|
||||
@@ -194,9 +190,7 @@ func (s *AdminServer) GetClusterVolumes(page int, pageSize int, sortBy string, s
|
||||
// Determine conditional display flags and extract single values
|
||||
showDataCenterColumn := dataCenterCount > 1
|
||||
showRackColumn := rackCount > 1
|
||||
// Remote-tiered volumes surface in the disk type column, so show it
|
||||
// whenever any volume lives on a remote tier.
|
||||
showDiskTypeColumn := diskTypeCount > 1 || hasRemoteVolumes
|
||||
showDiskTypeColumn := diskTypeCount > 1
|
||||
showCollectionColumn := collectionCount > 1 && collection == "" // Hide column when filtering by collection
|
||||
showVersionColumn := versionCount > 1
|
||||
|
||||
@@ -488,17 +482,10 @@ func (s *AdminServer) GetClusterVolumeServers() (*ClusterVolumeServersData, erro
|
||||
vs.DiskCapacity += int64(diskInfo.MaxVolumeCount) * int64(volumeSizeLimitMB) * 1024 * 1024
|
||||
}
|
||||
|
||||
// Count regular volumes and calculate disk usage.
|
||||
// A remote-tiered volume reports its cloud object's
|
||||
// size; keep those bytes out of the local disk usage
|
||||
// that is compared against DiskCapacity.
|
||||
// Count regular volumes and calculate disk usage
|
||||
for _, volInfo := range diskInfo.VolumeInfos {
|
||||
vs.Volumes++
|
||||
if volInfo.RemoteStorageName != "" {
|
||||
vs.RemoteSize += int64(volInfo.Size)
|
||||
} else {
|
||||
vs.DiskUsage += int64(volInfo.Size)
|
||||
}
|
||||
vs.DiskUsage += int64(volInfo.Size)
|
||||
}
|
||||
|
||||
// Accumulate EC shard information across all disks for this volume server
|
||||
|
||||
@@ -34,8 +34,6 @@ const (
|
||||
defaultWaitingBacklogFloor = 8
|
||||
defaultWaitingBacklogMultiplier = 4
|
||||
maxEstimatedRuntimeCap = 8 * time.Hour
|
||||
// How long started jobs may drain past the run window close.
|
||||
scheduledExecutionDrainGrace = 30 * time.Minute
|
||||
)
|
||||
|
||||
type schedulerPolicy struct {
|
||||
@@ -413,10 +411,15 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
|
||||
if execPolicy.ExecutionTimeout <= 0 {
|
||||
execPolicy.ExecutionTimeout = defaultScheduledExecutionTimeout
|
||||
}
|
||||
if execPolicy.ExecutionTimeout > remaining {
|
||||
execPolicy.ExecutionTimeout = remaining
|
||||
}
|
||||
|
||||
// jobCtx bounds how long this run keeps STARTING jobs; started jobs
|
||||
// drain past the window close (see scheduledAttemptContext), while
|
||||
// still-queued jobs are canceled and re-proposed by a later detection.
|
||||
// jobCtx bounds how long this run keeps STARTING jobs; a started job
|
||||
// runs on its own estimated-runtime deadline (see
|
||||
// executeScheduledJobWithExecutor). Jobs still queued when the window
|
||||
// closes are canceled and re-proposed by a later detection, so one large
|
||||
// backlog cannot monopolise the lane for hours.
|
||||
successCount, errorCount, canceledCount := r.dispatchScheduledProposals(jobCtx, jobType, filtered, clusterContext, execPolicy)
|
||||
|
||||
status := "success"
|
||||
@@ -1198,11 +1201,24 @@ func (r *Plugin) executeScheduledJobWithExecutor(
|
||||
// default execution timeout. This lets handlers like vacuum scale
|
||||
// the timeout based on volume size so large volumes are not killed.
|
||||
timeout := policy.ExecutionTimeout
|
||||
estimated := scheduledEstimatedRuntime(job.Parameters)
|
||||
if estimated > timeout {
|
||||
timeout = estimated
|
||||
if job.Parameters != nil {
|
||||
if est, ok := job.Parameters["estimated_runtime_seconds"]; ok {
|
||||
if v := est.GetInt64Value(); v > 0 {
|
||||
estimated := time.Duration(v) * time.Second
|
||||
if estimated > maxEstimatedRuntimeCap {
|
||||
estimated = maxEstimatedRuntimeCap
|
||||
}
|
||||
if estimated > timeout {
|
||||
timeout = estimated
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
execCtx, cancel := scheduledAttemptContext(ctx, timeout, estimated)
|
||||
// The attempt runs against its own deadline, detached from the
|
||||
// dispatch window (ctx): a job started near the end of the window
|
||||
// may run to completion; the window only stops further jobs from
|
||||
// starting.
|
||||
execCtx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
_, err := r.executeJobWithExecutor(execCtx, executor, job, clusterContext, int32(attempt))
|
||||
cancel()
|
||||
if err == nil {
|
||||
@@ -1237,43 +1253,6 @@ func (r *Plugin) executeScheduledJobWithExecutor(
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// scheduledEstimatedRuntime returns the job's declared estimated runtime,
|
||||
// capped at maxEstimatedRuntimeCap. The seconds are capped before the
|
||||
// Duration conversion so oversized values cannot overflow.
|
||||
func scheduledEstimatedRuntime(parameters map[string]*plugin_pb.ConfigValue) time.Duration {
|
||||
est, ok := parameters["estimated_runtime_seconds"]
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
v := est.GetInt64Value()
|
||||
if v <= 0 {
|
||||
return 0
|
||||
}
|
||||
if v > int64(maxEstimatedRuntimeCap/time.Second) {
|
||||
v = int64(maxEstimatedRuntimeCap / time.Second)
|
||||
}
|
||||
return time.Duration(v) * time.Second
|
||||
}
|
||||
|
||||
// scheduledAttemptContext bounds one execution attempt: its own timeout,
|
||||
// capped at the window deadline plus scheduledExecutionDrainGrace so a
|
||||
// draining job cannot hold the lane indefinitely, but never below the
|
||||
// job's declared estimated runtime.
|
||||
func scheduledAttemptContext(window context.Context, timeout, estimated time.Duration) (context.Context, context.CancelFunc) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
if window != nil {
|
||||
if windowEnd, ok := window.Deadline(); ok {
|
||||
if drainDeadline := windowEnd.Add(scheduledExecutionDrainGrace); deadline.After(drainDeadline) {
|
||||
if floor := time.Now().Add(estimated); floor.After(drainDeadline) {
|
||||
drainDeadline = floor
|
||||
}
|
||||
deadline = drainDeadline
|
||||
}
|
||||
}
|
||||
}
|
||||
return context.WithDeadline(context.Background(), deadline)
|
||||
}
|
||||
|
||||
func (r *Plugin) shouldSkipDetectionForWaitingJobs(jobType string, policy schedulerPolicy) (bool, int, int) {
|
||||
waitingCount := r.countWaitingTrackedJobs(jobType)
|
||||
threshold := waitingBacklogThreshold(policy)
|
||||
|
||||
@@ -3,13 +3,11 @@ package plugin
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func TestLoadSchedulerPolicyUsesAdminConfig(t *testing.T) {
|
||||
@@ -740,144 +738,6 @@ func TestDispatchScheduledProposalsLocksPerJob(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduledAttemptContextDrainGrace(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
assertDeadline := func(t *testing.T, ctx context.Context, want time.Time) {
|
||||
t.Helper()
|
||||
got, ok := ctx.Deadline()
|
||||
if !ok {
|
||||
t.Fatal("expected attempt context to carry a deadline")
|
||||
}
|
||||
if diff := got.Sub(want); diff < -5*time.Second || diff > 5*time.Second {
|
||||
t.Fatalf("unexpected attempt deadline: got=%v want~%v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
windowEnd := time.Now().Add(time.Minute)
|
||||
window, cancelWindow := context.WithDeadline(context.Background(), windowEnd)
|
||||
defer cancelWindow()
|
||||
|
||||
// Fits inside the window: keeps its own deadline.
|
||||
ctx, cancel := scheduledAttemptContext(window, 30*time.Second, 0)
|
||||
assertDeadline(t, ctx, time.Now().Add(30*time.Second))
|
||||
cancel()
|
||||
|
||||
// Longer: capped at window close plus the grace.
|
||||
ctx, cancel = scheduledAttemptContext(window, 3*time.Hour, 0)
|
||||
assertDeadline(t, ctx, windowEnd.Add(scheduledExecutionDrainGrace))
|
||||
cancel()
|
||||
|
||||
// Estimated runtime: keeps its full deadline.
|
||||
ctx, cancel = scheduledAttemptContext(window, 3*time.Hour, 3*time.Hour)
|
||||
assertDeadline(t, ctx, time.Now().Add(3*time.Hour))
|
||||
cancel()
|
||||
|
||||
// An estimate below the timeout floors the drain cap.
|
||||
ctx, cancel = scheduledAttemptContext(window, 3*time.Hour, 45*time.Minute)
|
||||
assertDeadline(t, ctx, time.Now().Add(45*time.Minute))
|
||||
cancel()
|
||||
|
||||
// No window deadline: the timeout stands alone.
|
||||
ctx, cancel = scheduledAttemptContext(context.Background(), 2*time.Hour, 0)
|
||||
assertDeadline(t, ctx, time.Now().Add(2*time.Hour))
|
||||
cancel()
|
||||
}
|
||||
|
||||
func TestScheduledEstimatedRuntime(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
estimate := func(v int64) map[string]*plugin_pb.ConfigValue {
|
||||
return map[string]*plugin_pb.ConfigValue{
|
||||
"estimated_runtime_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: v}},
|
||||
}
|
||||
}
|
||||
|
||||
if got := scheduledEstimatedRuntime(nil); got != 0 {
|
||||
t.Fatalf("nil parameters: got=%v want=0", got)
|
||||
}
|
||||
if got := scheduledEstimatedRuntime(estimate(-5)); got != 0 {
|
||||
t.Fatalf("negative estimate: got=%v want=0", got)
|
||||
}
|
||||
if got := scheduledEstimatedRuntime(estimate(600)); got != 10*time.Minute {
|
||||
t.Fatalf("normal estimate: got=%v want=10m", got)
|
||||
}
|
||||
// Oversized seconds cap before the Duration conversion can overflow.
|
||||
if got := scheduledEstimatedRuntime(estimate(math.MaxInt64)); got != maxEstimatedRuntimeCap {
|
||||
t.Fatalf("oversized estimate: got=%v want=%v", got, maxEstimatedRuntimeCap)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchScheduledProposalsDrainsStartedJobOnWindowClose(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pluginSvc, err := New(Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
const workerID = "worker-drain"
|
||||
const jobType = "s3_lifecycle" // lifecycle lane: no admin lock needed
|
||||
pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{
|
||||
WorkerId: workerID,
|
||||
Capabilities: []*plugin_pb.JobTypeCapability{
|
||||
{JobType: jobType, CanExecute: true, MaxExecutionConcurrency: 1},
|
||||
},
|
||||
})
|
||||
session := &streamSession{workerID: workerID, outgoing: make(chan *plugin_pb.AdminToWorkerMessage, 8), done: make(chan struct{})}
|
||||
pluginSvc.putSession(session)
|
||||
|
||||
windowCtx, closeWindow := context.WithCancel(context.Background())
|
||||
defer closeWindow()
|
||||
|
||||
policy := schedulerPolicy{
|
||||
ExecutionConcurrency: 1,
|
||||
PerWorkerConcurrency: 1,
|
||||
ExecutionTimeout: time.Hour,
|
||||
ExecutorReserveBackoff: time.Millisecond,
|
||||
}
|
||||
proposals := []*plugin_pb.JobProposal{
|
||||
{ProposalId: "p1", JobType: jobType, DedupeKey: "k1"},
|
||||
{ProposalId: "p2", JobType: jobType, DedupeKey: "k2"},
|
||||
}
|
||||
|
||||
resultCh := make(chan [3]int, 1)
|
||||
go func() {
|
||||
success, errCount, canceled := pluginSvc.dispatchScheduledProposals(
|
||||
windowCtx, jobType, proposals, &plugin_pb.ClusterContext{}, policy)
|
||||
resultCh <- [3]int{success, errCount, canceled}
|
||||
}()
|
||||
|
||||
first := <-session.outgoing
|
||||
execReq := first.GetExecuteJobRequest()
|
||||
if execReq == nil {
|
||||
t.Fatalf("expected execute_job_request, got %+v", first)
|
||||
}
|
||||
|
||||
// Close the window mid-job: the job must drain to completion while the
|
||||
// still-queued second proposal is canceled.
|
||||
closeWindow()
|
||||
pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{
|
||||
RequestId: first.RequestId,
|
||||
JobId: execReq.Job.JobId,
|
||||
JobType: jobType,
|
||||
Success: true,
|
||||
CompletedAt: timestamppb.Now(),
|
||||
})
|
||||
|
||||
result := <-resultCh
|
||||
if result[0] != 1 || result[1] != 0 || result[2] != 1 {
|
||||
t.Fatalf("unexpected dispatch counts: success=%d errors=%d canceled=%d", result[0], result[1], result[2])
|
||||
}
|
||||
|
||||
select {
|
||||
case unexpected := <-session.outgoing:
|
||||
t.Fatalf("expected no further worker messages (no cancel for the draining job), got %+v", unexpected)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- lane-scoped prune ----------
|
||||
|
||||
func TestPruneSchedulerState_DefaultLaneKeepsForeignLanesAndPrunesOwnStale(t *testing.T) {
|
||||
|
||||
@@ -194,87 +194,6 @@ templ Admin(data dash.AdminData) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Storage Tiers -->
|
||||
if len(data.TierStats) > 0 {
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
<div class="card shadow mb-4">
|
||||
<div class="card-header py-3">
|
||||
<h6 class="m-0 font-weight-bold text-primary">
|
||||
<i class="fas fa-layer-group me-2"></i>Storage Tiers
|
||||
</h6>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover" width="100%" cellspacing="0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Tier</th>
|
||||
<th>Volumes</th>
|
||||
<th>EC Shards</th>
|
||||
<th>Data Size</th>
|
||||
<th>Disk Used</th>
|
||||
<th>Capacity</th>
|
||||
<th>Usage</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
for _, tier := range data.TierStats {
|
||||
<tr>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<i class="fas fa-cloud me-1 text-info"></i>{tier.Name}
|
||||
<span class="badge bg-info text-white ms-1">remote</span>
|
||||
} else {
|
||||
<i class="fas fa-hdd me-1 text-muted"></i>{tier.Name}
|
||||
}
|
||||
</td>
|
||||
<td>{fmt.Sprintf("%d", tier.VolumeCount)}</td>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
{fmt.Sprintf("%d", tier.EcShardCount)}
|
||||
}
|
||||
</td>
|
||||
<td>{formatBytes(tier.DataSize)}</td>
|
||||
<td>
|
||||
if tier.IsRemote || tier.DiskUsed == 0 {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
{formatBytes(tier.DiskUsed)}
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
{formatBytes(tier.DiskCapacity)}
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
if tier.IsRemote {
|
||||
<span class="text-muted">-</span>
|
||||
} else {
|
||||
<div class="progress" style="height: 20px;">
|
||||
<div class="progress-bar" role="progressbar"
|
||||
style={fmt.Sprintf("width: %d%%", tier.UsagePercent())}>
|
||||
{fmt.Sprintf("%d%%", tier.UsagePercent())}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<!-- Mount Clients -->
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
@@ -429,7 +348,7 @@ templ Admin(data dash.AdminData) {
|
||||
<th>Rack</th>
|
||||
<th>Volumes</th>
|
||||
<th>EC Shards</th>
|
||||
<th>Usage / Capacity</th>
|
||||
<th>Capacity</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -462,13 +381,7 @@ templ Admin(data dash.AdminData) {
|
||||
<span class="text-muted">-</span>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
{formatBytes(vs.DiskUsage)} / {formatBytes(vs.DiskCapacity)}
|
||||
if vs.RemoteSize > 0 {
|
||||
<br/>
|
||||
<small class="text-muted"><i class="fas fa-cloud me-1"></i>{formatBytes(vs.RemoteSize)} remote</small>
|
||||
}
|
||||
</td>
|
||||
<td>{formatBytes(vs.DiskUsage)} / {formatBytes(vs.DiskCapacity)}</td>
|
||||
</tr>
|
||||
}
|
||||
if len(data.VolumeServers) == 0 {
|
||||
|
||||
+328
-535
File diff suppressed because it is too large.
Load diff
@@ -164,17 +164,12 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="progress me-2" style="width: 60px; height: 16px;">
|
||||
<div class="progress-bar" role="progressbar"
|
||||
<div class="progress-bar" role="progressbar"
|
||||
style={fmt.Sprintf("width: %d%%", calculatePercent(int(host.DiskUsage), int(host.DiskCapacity)))}>
|
||||
</div>
|
||||
</div>
|
||||
<small>{formatBytes(host.DiskUsage)}</small>
|
||||
</div>
|
||||
if host.RemoteSize > 0 {
|
||||
<div class="mt-1">
|
||||
<small class="text-muted"><i class="fas fa-cloud me-1"></i>{formatBytes(host.RemoteSize)} remote</small>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
if host.PublicURL != "" {
|
||||
@@ -191,7 +186,6 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
data-max-volumes={fmt.Sprintf("%d", host.MaxVolumes)}
|
||||
data-disk-usage={fmt.Sprintf("%d", host.DiskUsage)}
|
||||
data-disk-capacity={fmt.Sprintf("%d", host.DiskCapacity)}
|
||||
data-remote-size={fmt.Sprintf("%d", host.RemoteSize)}
|
||||
data-ec-volumes={fmt.Sprintf("%d", host.EcVolumes)}
|
||||
data-ec-shards={fmt.Sprintf("%d", host.EcShards)}
|
||||
data-last-heartbeat={host.LastHeartbeat.Format("2006-01-02 15:04:05")}>
|
||||
@@ -211,7 +205,6 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
data-max-volumes={fmt.Sprintf("%d", host.MaxVolumes)}
|
||||
data-disk-usage={fmt.Sprintf("%d", host.DiskUsage)}
|
||||
data-disk-capacity={fmt.Sprintf("%d", host.DiskCapacity)}
|
||||
data-remote-size={fmt.Sprintf("%d", host.RemoteSize)}
|
||||
data-ec-volumes={fmt.Sprintf("%d", host.EcVolumes)}
|
||||
data-ec-shards={fmt.Sprintf("%d", host.EcShards)}
|
||||
data-last-heartbeat={host.LastHeartbeat.Format("2006-01-02 15:04:05")}>
|
||||
@@ -267,7 +260,6 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
maxVolumes: parseInt(button.getAttribute('data-max-volumes')),
|
||||
diskUsage: parseInt(button.getAttribute('data-disk-usage')),
|
||||
diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),
|
||||
remoteSize: parseInt(button.getAttribute('data-remote-size')) || 0,
|
||||
ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),
|
||||
ecShards: parseInt(button.getAttribute('data-ec-shards')),
|
||||
lastHeartbeat: button.getAttribute('data-last-heartbeat')
|
||||
@@ -322,8 +314,6 @@ templ ClusterVolumeServers(data dash.ClusterVolumeServersData) {
|
||||
'</div>' +
|
||||
'</td></tr>' +
|
||||
'<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +
|
||||
(server.remoteSize > 0 ?
|
||||
'<tr><td><strong>Remote Data:</strong></td><td><i class="fas fa-cloud me-1"></i>' + formatBytes(server.remoteSize) + '</td></tr>' : '') +
|
||||
'</table>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1020
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumeServers))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 34, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 34, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 56, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 56, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(data.TotalCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 76, Col: 68}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 76, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -95,7 +95,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var5 templ.SafeURL
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", host.PublicURL)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 117, Col: 121}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 117, Col: 121}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -108,7 +108,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 118, Col: 65}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 118, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -126,7 +126,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var7 templ.SafeURL
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", host.Address)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 122, Col: 119}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 122, Col: 119}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -139,7 +139,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 123, Col: 65}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 123, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -157,7 +157,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 129, Col: 99}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 129, Col: 99}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -170,7 +170,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 132, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 132, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -183,7 +183,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(host.Volumes, host.MaxVolumes)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 138, Col: 139}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 138, Col: 139}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -196,7 +196,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 141, Col: 111}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 141, Col: 111}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -209,7 +209,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 145, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 145, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -227,7 +227,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 151, Col: 129}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 151, Col: 129}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -245,7 +245,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d EC volumes", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 156, Col: 127}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 156, Col: 127}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -269,7 +269,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 163, Col: 75}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 163, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -282,7 +282,7 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %d%%", calculatePercent(int(host.DiskUsage), int(host.DiskCapacity))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 168, Col: 153}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 168, Col: 153}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -295,417 +295,368 @@ func ClusterVolumeServers(data dash.ClusterVolumeServersData) templ.Component {
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 171, Col: 83}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 171, Col: 83}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</small></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</small></div></td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if host.RemoteSize > 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<div class=\"mt-1\"><small class=\"text-muted\"><i class=\"fas fa-cloud me-1\"></i>")
|
||||
if host.PublicURL != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(host.RemoteSize))
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(host.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 175, Col: 140}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 180, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, " remote</small></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</td><td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if host.PublicURL != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\" data-address=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.ID)
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 185, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 181, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var20)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" data-address=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "\" data-public-url=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Address)
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(host.PublicURL)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 186, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 182, Col: 87}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-public-url=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "\" data-datacenter=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.PublicURL)
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 187, Col: 87}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 183, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var22)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" data-datacenter=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\" data-rack=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.DataCenter)
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 188, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 184, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" data-rack=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Rack)
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 189, Col: 76}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 185, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" data-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "\" data-max-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.Volumes))
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 190, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 186, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var25)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-max-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\" data-disk-usage=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 191, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 187, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-disk-usage=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" data-disk-capacity=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskUsage))
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 192, Col: 106}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 188, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" data-disk-capacity=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 193, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 189, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\" data-remote-size=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.RemoteSize))
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 194, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 190, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "\" data-ec-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcVolumes))
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 195, Col: 106}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 191, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 196, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var31)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 197, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "<button type=\"button\" class=\"btn btn-outline-primary btn-sm\" title=\"View Details\" data-action=\"view-details\" data-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(host.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 199, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\" data-address=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 200, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "\" data-public-url=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.ID)
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(host.Address)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 205, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 201, Col: 85}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var33)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "\" data-address=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\" data-datacenter=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Address)
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(host.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 206, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 202, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var34)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "\" data-public-url=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "\" data-rack=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Address)
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(host.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 207, Col: 85}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 203, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var35)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" data-datacenter=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "\" data-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.DataCenter)
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.Volumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 208, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 204, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var36)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "\" data-rack=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "\" data-max-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var37 string
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.Rack)
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 209, Col: 76}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 205, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var37)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "\" data-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "\" data-disk-usage=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.Volumes))
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskUsage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 210, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 206, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var38)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\" data-max-volumes=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "\" data-disk-capacity=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.MaxVolumes))
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 211, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 207, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var39)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "\" data-disk-usage=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var40 string
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskUsage))
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 212, Col: 106}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 208, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var40)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\" data-disk-capacity=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var41 string
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.DiskCapacity))
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 213, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 209, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var41)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\" data-remote-size=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.RemoteSize))
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 214, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 210, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var42)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "\" data-ec-volumes=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 215, Col: 106}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var43)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "\" data-ec-shards=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var44 string
|
||||
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", host.EcShards))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 216, Col: 104}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var44)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "\" data-last-heartbeat=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var45 string
|
||||
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.ResolveAttributeValue(host.LastHeartbeat.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 217, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var45)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "\"><i class=\"fas fa-eye\"></i></button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "</td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "</td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "</tbody></table></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</tbody></table></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "<div class=\"text-center py-5\"><i class=\"fas fa-server fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volume Servers Found</h5><p class=\"text-muted\">No volume servers are currently available in the cluster.</p></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "<div class=\"text-center py-5\"><i class=\"fas fa-server fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volume Servers Found</h5><p class=\"text-muted\">No volume servers are currently available in the cluster.</p></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "</div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "</div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var46 string
|
||||
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volume_servers.templ`, Line: 242, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volume_servers.templ`, Line: 235, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "</small></div></div></div><!-- JavaScript for cluster volume servers functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle volume server action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const serverData = {\n id: button.getAttribute('data-id'),\n address: button.getAttribute('data-address'),\n publicUrl: button.getAttribute('data-public-url'),\n datacenter: button.getAttribute('data-datacenter'),\n rack: button.getAttribute('data-rack'),\n volumes: parseInt(button.getAttribute('data-volumes')),\n maxVolumes: parseInt(button.getAttribute('data-max-volumes')),\n diskUsage: parseInt(button.getAttribute('data-disk-usage')),\n diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),\n remoteSize: parseInt(button.getAttribute('data-remote-size')) || 0,\n ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),\n ecShards: parseInt(button.getAttribute('data-ec-shards')),\n lastHeartbeat: button.getAttribute('data-last-heartbeat')\n };\n showVolumeServerDetails(serverData);\n break;\n }\n });\n });\n \n function showVolumeServerDetails(server) {\n const volumePercent = server.maxVolumes > 0 ? Math.round((server.volumes / server.maxVolumes) * 100) : 0;\n const diskPercent = server.diskCapacity > 0 ? Math.round((server.diskUsage / server.diskCapacity) * 100) : 0;\n \n const modalHtml = '<div class=\"modal fade\" id=\"volumeServerDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-server me-2\"></i>Volume Server Details: ' + server.address + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Server ID:</strong></td><td><code>' + server.id + '</code></td></tr>' +\n '<tr><td><strong>Address:</strong></td><td>' + server.address + '</td></tr>' +\n '<tr><td><strong>Public URL:</strong></td><td>' + server.publicUrl + '</td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.datacenter + '</span></td></tr>' +\n '<tr><td><strong>Rack:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.rack + '</span></td></tr>' +\n '<tr><td><strong>Last Heartbeat:</strong></td><td>' + server.lastHeartbeat + '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Usage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + volumePercent + '%\"></div>' +\n '</div>' +\n '<span>' + server.volumes + '/' + server.maxVolumes + ' (' + volumePercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Disk Usage:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + diskPercent + '%\"></div>' +\n '</div>' +\n '<span>' + formatBytes(server.diskUsage) + '/' + formatBytes(server.diskCapacity) + ' (' + diskPercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +\nLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</small></div></div></div><!-- JavaScript for cluster volume servers functionality --><script>\n document.addEventListener('DOMContentLoaded', function() {\n // Handle volume server action buttons\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n \n switch(action) {\n case 'view-details':\n const serverData = {\n id: button.getAttribute('data-id'),\n address: button.getAttribute('data-address'),\n publicUrl: button.getAttribute('data-public-url'),\n datacenter: button.getAttribute('data-datacenter'),\n rack: button.getAttribute('data-rack'),\n volumes: parseInt(button.getAttribute('data-volumes')),\n maxVolumes: parseInt(button.getAttribute('data-max-volumes')),\n diskUsage: parseInt(button.getAttribute('data-disk-usage')),\n diskCapacity: parseInt(button.getAttribute('data-disk-capacity')),\n ecVolumes: parseInt(button.getAttribute('data-ec-volumes')),\n ecShards: parseInt(button.getAttribute('data-ec-shards')),\n lastHeartbeat: button.getAttribute('data-last-heartbeat')\n };\n showVolumeServerDetails(serverData);\n break;\n }\n });\n });\n \n function showVolumeServerDetails(server) {\n const volumePercent = server.maxVolumes > 0 ? Math.round((server.volumes / server.maxVolumes) * 100) : 0;\n const diskPercent = server.diskCapacity > 0 ? Math.round((server.diskUsage / server.diskCapacity) * 100) : 0;\n \n const modalHtml = '<div class=\"modal fade\" id=\"volumeServerDetailsModal\" tabindex=\"-1\">' +\n '<div class=\"modal-dialog modal-lg\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\"><i class=\"fas fa-server me-2\"></i>Volume Server Details: ' + server.address + '</h5>' +\n '<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<div class=\"row\">' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-info-circle me-1\"></i>Basic Information</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Server ID:</strong></td><td><code>' + server.id + '</code></td></tr>' +\n '<tr><td><strong>Address:</strong></td><td>' + server.address + '</td></tr>' +\n '<tr><td><strong>Public URL:</strong></td><td>' + server.publicUrl + '</td></tr>' +\n '<tr><td><strong>Data Center:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.datacenter + '</span></td></tr>' +\n '<tr><td><strong>Rack:</strong></td><td><span class=\"badge bg-light text-dark\">' + server.rack + '</span></td></tr>' +\n '<tr><td><strong>Last Heartbeat:</strong></td><td>' + server.lastHeartbeat + '</td></tr>' +\n '</table>' +\n '</div>' +\n '<div class=\"col-md-6\">' +\n '<h6 class=\"text-primary\"><i class=\"fas fa-chart-bar me-1\"></i>Usage Statistics</h6>' +\n '<table class=\"table table-sm\">' +\n '<tr><td><strong>Volumes:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + volumePercent + '%\"></div>' +\n '</div>' +\n '<span>' + server.volumes + '/' + server.maxVolumes + ' (' + volumePercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Disk Usage:</strong></td><td>' +\n '<div class=\"d-flex align-items-center\">' +\n '<div class=\"progress me-2\" style=\"width: 100px; height: 20px;\">' +\n '<div class=\"progress-bar\" role=\"progressbar\" style=\"width: ' + diskPercent + '%\"></div>' +\n '</div>' +\n '<span>' + formatBytes(server.diskUsage) + '/' + formatBytes(server.diskCapacity) + ' (' + diskPercent + '%)</span>' +\n '</div>' +\n '</td></tr>' +\n '<tr><td><strong>Available Space:</strong></td><td>' + formatBytes(server.diskCapacity - server.diskUsage) + '</td></tr>' +\n '</table>' +\n '</div>' +\n '</div>' +\n \n Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -400,12 +400,7 @@ templ ClusterVolumes(data dash.ClusterVolumesData) {
|
||||
</td>
|
||||
if data.ShowDiskTypeColumn {
|
||||
<td>
|
||||
<span class="badge bg-primary">{displayDiskType(volume.DiskType)}</span>
|
||||
if volume.RemoteStorageName != "" {
|
||||
<span class="badge bg-info text-white ms-1" title={volume.RemoteStorageKey}>
|
||||
<i class="fas fa-cloud me-1"></i>{volume.RemoteStorageName}
|
||||
</span>
|
||||
}
|
||||
<span class="badge bg-primary">{volume.DiskType}</span>
|
||||
</td>
|
||||
}
|
||||
if data.ShowVersionColumn {
|
||||
@@ -688,18 +683,14 @@ func countUniqueRacks(volumes []dash.VolumeWithTopology) int {
|
||||
return len(rackMap)
|
||||
}
|
||||
|
||||
// displayDiskType maps the empty disk type to its display name.
|
||||
func displayDiskType(diskType string) string {
|
||||
if diskType == "" {
|
||||
return "hdd"
|
||||
}
|
||||
return diskType
|
||||
}
|
||||
|
||||
func countUniqueDiskTypes(volumes []dash.VolumeWithTopology) int {
|
||||
diskTypeMap := make(map[string]bool)
|
||||
for _, volume := range volumes {
|
||||
diskTypeMap[displayDiskType(volume.DiskType)] = true
|
||||
diskType := volume.DiskType
|
||||
if diskType == "" {
|
||||
diskType = "hdd"
|
||||
}
|
||||
diskTypeMap[diskType] = true
|
||||
}
|
||||
return len(diskTypeMap)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1020
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -47,7 +47,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(data.FilterCollection)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 18, Col: 92}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 18, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -60,7 +60,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var3 templ.SafeURL
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/storage/volumes"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 20, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 20, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -118,7 +118,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 56, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 56, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -147,7 +147,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(data.SingleCollection)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 81, Col: 62}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 81, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -157,7 +157,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CollectionCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 83, Col: 80}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 83, Col: 80}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -187,7 +187,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(data.SingleDataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 109, Col: 62}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 109, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -197,7 +197,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.DataCenterCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 111, Col: 80}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 111, Col: 80}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -227,7 +227,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(data.SingleRack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 137, Col: 56}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 137, Col: 56}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -237,7 +237,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.RackCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 139, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 139, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -267,7 +267,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(data.SingleDiskType)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 165, Col: 60}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 165, Col: 60}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -277,7 +277,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(strings.Join(data.AllDiskTypes, ", "))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 167, Col: 78}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 167, Col: 78}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -307,7 +307,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(data.SingleVersion)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 193, Col: 59}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 193, Col: 59}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -317,7 +317,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(strings.Join(data.AllVersions, ", "))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 195, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 195, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -331,7 +331,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(data.TotalSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 216, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 216, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -470,11 +470,11 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", volume.Id))
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.Id))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 320, Col: 94}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 320, Col: 94}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -485,7 +485,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.Id))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 322, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 322, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -498,7 +498,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var18 templ.SafeURL
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(templ.SafeURL(fmt.Sprintf("//%s/ui/index.html", volume.Server)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 326, Col: 116}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 326, Col: 116}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -511,7 +511,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(volume.Server)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 327, Col: 62}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 327, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -529,7 +529,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(volume.DataCenter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 333, Col: 105}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 333, Col: 105}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -548,7 +548,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(volume.Rack)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 338, Col: 99}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 338, Col: 99}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -572,7 +572,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var22 templ.SafeURL
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, "/storage/volumes?collection=default"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 344, Col: 115}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 344, Col: 115}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -590,7 +590,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var23 templ.SafeURL
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/storage/volumes?collection=%s", volume.Collection)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 348, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 348, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -603,7 +603,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(volume.Collection)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 349, Col: 107}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 349, Col: 107}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -626,7 +626,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(int64(volume.Size)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 354, Col: 100}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 354, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -648,7 +648,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return 0
|
||||
}()))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 369, Col: 49}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 369, Col: 49}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -659,11 +659,11 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("Active: %s", formatBytes(int64(volume.Size-volume.DeletedByteCount))))
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Active: %s", formatBytes(int64(volume.Size-volume.DeletedByteCount))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 370, Col: 132}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 370, Col: 132}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -683,7 +683,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return 0
|
||||
}()))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 383, Col: 49}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 383, Col: 49}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -694,11 +694,11 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("Garbage: %s", formatBytes(int64(volume.DeletedByteCount))))
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("Garbage: %s", formatBytes(int64(volume.DeletedByteCount))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 384, Col: 119}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 384, Col: 119}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -714,7 +714,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return "N/A"
|
||||
}())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 393, Col: 39}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 393, Col: 39}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -727,7 +727,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.FileCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 397, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 397, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -740,7 +740,7 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%03d", volume.ReplicaPlacement))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 399, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 399, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -756,335 +756,299 @@ func ClusterVolumes(data dash.ClusterVolumesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(displayDiskType(volume.DiskType))
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(volume.DiskType)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 403, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 403, Col: 95}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "</span> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if volume.RemoteStorageName != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "<span class=\"badge bg-info text-white ms-1\" title=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.ResolveAttributeValue(volume.RemoteStorageKey)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 405, Col: 126}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var34)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "\"><i class=\"fas fa-cloud me-1\"></i>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(volume.RemoteStorageName)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 406, Col: 114}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "</td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 80, "</span></td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
if data.ShowVersionColumn {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "<td><span class=\"badge bg-dark\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "<td><span class=\"badge bg-dark\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("v%d", volume.Version))
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("v%d", volume.Version))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 413, Col: 111}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 408, Col: 111}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "</span></td>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "</span></td>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "<td><div class=\"btn-group btn-group-sm\"><button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" title=\"View Details\" data-volume-id=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "<td><div class=\"btn-group btn-group-sm\"><button type=\"button\" class=\"btn btn-outline-primary btn-sm view-details-btn\" title=\"View Details\" data-volume-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.Id))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 414, Col: 121}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm vacuum-btn\" title=\"Vacuum\" data-volume-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", volume.Id))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 419, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "\" data-server=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var37 string
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", volume.Id))
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(volume.Server)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 419, Col: 121}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 420, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var37)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "\"><i class=\"fas fa-eye\"></i></button> <button type=\"button\" class=\"btn btn-outline-secondary btn-sm vacuum-btn\" title=\"Vacuum\" data-volume-id=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", volume.Id))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 424, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var38)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "\" data-server=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.ResolveAttributeValue(volume.Server)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 425, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var39)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "\"><i class=\"fas fa-compress-alt\"></i></button></div></td></tr>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "\"><i class=\"fas fa-compress-alt\"></i></button></div></td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</tbody></table></div><!-- Volume Summary --> <div class=\"d-flex justify-content-between align-items-center mt-3\"><div><small class=\"text-muted\">Showing ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "</tbody></table></div><!-- Volume Summary --> <div class=\"d-flex justify-content-between align-items-center mt-3\"><div><small class=\"text-muted\">Showing ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 435, Col: 98}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, " to ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalVolumes)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 435, Col: 180}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, " of ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var40 string
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 440, Col: 98}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 435, Col: 222}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, " to ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var41 string
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalVolumes)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 440, Col: 180}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, " of ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalVolumes))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 440, Col: 222}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, " volumes</small></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, " volumes</small></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if data.TotalPages > 1 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "<div><small class=\"text-muted\">Page ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "<div><small class=\"text-muted\">Page ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage))
|
||||
var templ_7745c5c3_Var41 string
|
||||
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 446, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 441, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, " of ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, " of ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var44 string
|
||||
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPages))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 446, Col: 117}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 441, Col: 117}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "</small></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "</small></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "</div><!-- Pagination Controls --> ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "</div><!-- Pagination Controls --> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if data.TotalPages > 1 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "<div class=\"d-flex justify-content-center mt-3\"><nav aria-label=\"Volumes pagination\"><ul class=\"pagination pagination-sm mb-0\"><!-- Previous Button -->")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "<div class=\"d-flex justify-content-center mt-3\"><nav aria-label=\"Volumes pagination\"><ul class=\"pagination pagination-sm mb-0\"><!-- Previous Button -->")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if data.CurrentPage > 1 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 100, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var45 string
|
||||
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.CurrentPage-1))
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 460, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 455, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var45)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 101, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "\"><i class=\"fas fa-chevron-left\"></i></a></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 102, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-left\"></i></span></li>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-left\"></i></span></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 103, "<!-- Page Numbers -->")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "<!-- Page Numbers -->")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for i := maxInt(1, data.CurrentPage-2); i <= minInt(data.TotalPages, data.CurrentPage+2); i++ {
|
||||
if i == data.CurrentPage {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 104, "<li class=\"page-item active\"><span class=\"page-link\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 100, "<li class=\"page-item active\"><span class=\"page-link\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var44 string
|
||||
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 471, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 101, "</span></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 102, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var45 string
|
||||
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 475, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 103, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var46 string
|
||||
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 476, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 475, Col: 148}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 105, "</span></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 106, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var47 string
|
||||
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 480, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var47)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 107, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var48 string
|
||||
templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 480, Col: 148}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var48))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 108, "</a></li>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 104, "</a></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 109, "<!-- Next Button -->")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 105, "<!-- Next Button -->")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if data.CurrentPage < data.TotalPages {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 110, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 106, "<li class=\"page-item\"><a class=\"page-link pagination-link\" href=\"#\" data-page=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var49 string
|
||||
templ_7745c5c3_Var49, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d", data.CurrentPage+1))
|
||||
var templ_7745c5c3_Var47 string
|
||||
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 488, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 483, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var49)
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 111, "\"><i class=\"fas fa-chevron-right\"></i></a></li>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 107, "\"><i class=\"fas fa-chevron-right\"></i></a></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-right\"></i></span></li>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 108, "<li class=\"page-item disabled\"><span class=\"page-link\"><i class=\"fas fa-chevron-right\"></i></span></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 113, "</ul></nav></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 109, "</ul></nav></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 114, "<div class=\"text-center py-5\"><i class=\"fas fa-database fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volumes Found</h5><p class=\"text-muted\">No volumes are currently available in the cluster.</p></div>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 110, "<div class=\"text-center py-5\"><i class=\"fas fa-database fa-3x text-muted mb-3\"></i><h5 class=\"text-muted\">No Volumes Found</h5><p class=\"text-muted\">No volumes are currently available in the cluster.</p></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 115, "</div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 111, "</div></div><!-- Last Updated --><div class=\"row\"><div class=\"col-12\"><small class=\"text-muted\"><i class=\"fas fa-clock me-1\"></i> Last updated: ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var50 string
|
||||
templ_7745c5c3_Var50, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
var templ_7745c5c3_Var48 string
|
||||
templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/cluster_volumes.templ`, Line: 518, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/cluster_volumes.templ`, Line: 513, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var50))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var48))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 116, "</small></div></div></div><!-- JavaScript for pagination and sorting --><script>\n // Initialize pagination links when page loads\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n \n // Add click handlers to view details buttons\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to volume ID links\n document.querySelectorAll('.volume-id-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to vacuum buttons\n document.querySelectorAll('.vacuum-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n const server = this.getAttribute('data-server');\n performVacuum(volumeId, server, this);\n });\n });\n });\n \n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n \n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function viewVolumeDetails(volumeId) {\n // Get the server from the current row - works for both buttons and volume ID links\n const clickedElement = event.target;\n const row = clickedElement.closest('tr');\n const serverCell = row.querySelector('td:nth-child(2) a');\n const server = serverCell ? serverCell.textContent.trim() : 'unknown';\n \n window.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${encodeURIComponent(server)}`;\n }\n\n function performVacuum(volumeId, server, button) {\n // Disable button and show loading state\n const originalHTML = button.innerHTML;\n button.disabled = true;\n button.innerHTML = '<i class=\"fas fa-spinner fa-spin\"></i>';\n\n // Send vacuum request\n fetch((window.__BASE_PATH__ || '') + `/api/volumes/${volumeId}/${encodeURIComponent(server)}/vacuum`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showMessage(data.error, 'error');\n } else {\n showMessage(data.message || 'Volume vacuum started successfully', 'success');\n // Optionally refresh the page after a delay to show updated vacuum status\n setTimeout(() => {\n window.location.reload();\n }, 2000);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 112, "</small></div></div></div><!-- JavaScript for pagination and sorting --><script>\n // Initialize pagination links when page loads\n document.addEventListener('DOMContentLoaded', function() {\n // Add click handlers to pagination links\n document.querySelectorAll('.pagination-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const page = this.getAttribute('data-page');\n goToPage(page);\n });\n });\n \n // Add click handlers to view details buttons\n document.querySelectorAll('.view-details-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to volume ID links\n document.querySelectorAll('.volume-id-link').forEach(link => {\n link.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n viewVolumeDetails(volumeId);\n });\n });\n\n // Add click handlers to vacuum buttons\n document.querySelectorAll('.vacuum-btn').forEach(button => {\n button.addEventListener('click', function(e) {\n e.preventDefault();\n const volumeId = this.getAttribute('data-volume-id');\n const server = this.getAttribute('data-server');\n performVacuum(volumeId, server, this);\n });\n });\n });\n \n function goToPage(page) {\n const url = new URL(window.location);\n url.searchParams.set('page', page);\n window.location.href = url.toString();\n }\n \n function changePageSize() {\n const pageSize = document.getElementById('pageSizeSelect').value;\n const url = new URL(window.location);\n url.searchParams.set('pageSize', pageSize);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function sortTable(column) {\n const url = new URL(window.location);\n const currentSort = url.searchParams.get('sortBy');\n const currentOrder = url.searchParams.get('sortOrder') || 'asc';\n \n let newOrder = 'asc';\n if (currentSort === column && currentOrder === 'asc') {\n newOrder = 'desc';\n }\n \n url.searchParams.set('sortBy', column);\n url.searchParams.set('sortOrder', newOrder);\n url.searchParams.set('page', '1'); // Reset to first page\n window.location.href = url.toString();\n }\n \n function viewVolumeDetails(volumeId) {\n // Get the server from the current row - works for both buttons and volume ID links\n const clickedElement = event.target;\n const row = clickedElement.closest('tr');\n const serverCell = row.querySelector('td:nth-child(2) a');\n const server = serverCell ? serverCell.textContent.trim() : 'unknown';\n \n window.location.href = (window.__BASE_PATH__ || '') + `/storage/volumes/${volumeId}/${encodeURIComponent(server)}`;\n }\n\n function performVacuum(volumeId, server, button) {\n // Disable button and show loading state\n const originalHTML = button.innerHTML;\n button.disabled = true;\n button.innerHTML = '<i class=\"fas fa-spinner fa-spin\"></i>';\n\n // Send vacuum request\n fetch((window.__BASE_PATH__ || '') + `/api/volumes/${volumeId}/${encodeURIComponent(server)}/vacuum`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showMessage(data.error, 'error');\n } else {\n showMessage(data.message || 'Volume vacuum started successfully', 'success');\n // Optionally refresh the page after a delay to show updated vacuum status\n setTimeout(() => {\n window.location.reload();\n }, 2000);\n }\n })\n .catch(error => {\n console.error('Error:', error);\n Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -1115,18 +1079,14 @@ func countUniqueRacks(volumes []dash.VolumeWithTopology) int {
|
||||
return len(rackMap)
|
||||
}
|
||||
|
||||
// displayDiskType maps the empty disk type to its display name.
|
||||
func displayDiskType(diskType string) string {
|
||||
if diskType == "" {
|
||||
return "hdd"
|
||||
}
|
||||
return diskType
|
||||
}
|
||||
|
||||
func countUniqueDiskTypes(volumes []dash.VolumeWithTopology) int {
|
||||
diskTypeMap := make(map[string]bool)
|
||||
for _, volume := range volumes {
|
||||
diskTypeMap[displayDiskType(volume.DiskType)] = true
|
||||
diskType := volume.DiskType
|
||||
if diskType == "" {
|
||||
diskType = "hdd"
|
||||
}
|
||||
diskTypeMap[diskType] = true
|
||||
}
|
||||
return len(diskTypeMap)
|
||||
}
|
||||
@@ -1147,23 +1107,23 @@ func getSortIcon(column, currentSort, currentOrder string) templ.Component {
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Var51 := templ.GetChildren(ctx)
|
||||
if templ_7745c5c3_Var51 == nil {
|
||||
templ_7745c5c3_Var51 = templ.NopComponent
|
||||
templ_7745c5c3_Var49 := templ.GetChildren(ctx)
|
||||
if templ_7745c5c3_Var49 == nil {
|
||||
templ_7745c5c3_Var49 = templ.NopComponent
|
||||
}
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
if column != currentSort {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 117, "<i class=\"fas fa-sort text-muted ms-1\"></i>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 113, "<i class=\"fas fa-sort text-muted ms-1\"></i>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else if currentOrder == "asc" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 118, "<i class=\"fas fa-sort-up text-primary ms-1\"></i>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 114, "<i class=\"fas fa-sort-up text-primary ms-1\"></i>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 119, "<i class=\"fas fa-sort-down text-primary ms-1\"></i>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 115, "<i class=\"fas fa-sort-down text-primary ms-1\"></i>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -145,7 +145,6 @@ func init() {
|
||||
filerS3Options.metricsHttpIp = cmdFiler.Flag.String("s3.metricsIp", "", "metrics listen ip. If empty, default to same as -s3.ip.bind option.")
|
||||
cmdFiler.Flag.Bool("s3.allowEmptyFolder", true, "deprecated, ignored. Empty folder cleanup is now automatic.")
|
||||
filerS3Options.allowDeleteBucketNotEmpty = cmdFiler.Flag.Bool("s3.allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
|
||||
filerS3Options.autoCreateBucket = cmdFiler.Flag.Bool("s3.autoCreateBucket", true, "create the bucket on upload if it does not exist, for admin identities only")
|
||||
filerS3Options.localSocket = cmdFiler.Flag.String("s3.localSocket", "", "default to /tmp/seaweedfs-s3-<port>.sock")
|
||||
filerS3Options.tlsCACertificate = cmdFiler.Flag.String("s3.cacert.file", "", "path to the TLS CA certificate file")
|
||||
filerS3Options.tlsVerifyClientCert = cmdFiler.Flag.Bool("s3.tlsVerifyClientCert", false, "whether to verify the client's certificate")
|
||||
|
||||
@@ -88,7 +88,7 @@ func init() {
|
||||
m.ipBind = cmdMaster.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to same as -ip option.")
|
||||
m.metaFolder = cmdMaster.Flag.String("mdir", os.TempDir(), "data directory to store meta data")
|
||||
m.peers = cmdMaster.Flag.String("peers", "", "all master nodes in comma separated ip:port list, example: 127.0.0.1:9093,127.0.0.1:9094,127.0.0.1:9095; use 'none' for single-master mode")
|
||||
m.volumeSizeLimitMB = cmdMaster.Flag.Uint("volumeSizeLimitMB", util.DefaultVolumeSizeLimitMB, "Master stops directing writes to oversized volumes.")
|
||||
m.volumeSizeLimitMB = cmdMaster.Flag.Uint("volumeSizeLimitMB", 30*1000, "Master stops directing writes to oversized volumes.")
|
||||
m.volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
m.maxParallelVacuumPerServer = cmdMaster.Flag.Int("maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel per volume server")
|
||||
// m.pulseSeconds = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
|
||||
@@ -160,8 +160,8 @@ func runMaster(cmd *Command, args []string) bool {
|
||||
}
|
||||
|
||||
masterWhiteList := util.StringSplit(*m.whiteList, ",")
|
||||
if *m.volumeSizeLimitMB > util.MaxVolumeSizeLimitMB {
|
||||
glog.Fatalf("volumeSizeLimitMB should not exceed %d", util.MaxVolumeSizeLimitMB)
|
||||
if *m.volumeSizeLimitMB > util.VolumeSizeLimitGB*1000 {
|
||||
glog.Fatalf("volumeSizeLimitMB should be smaller than 30000")
|
||||
}
|
||||
|
||||
switch {
|
||||
|
||||
@@ -4,25 +4,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestDefaultVolumeSizeLimitAlignsWithErasureCodingRows(t *testing.T) {
|
||||
if got := *m.volumeSizeLimitMB; got != util.DefaultVolumeSizeLimitMB {
|
||||
t.Fatalf("master volume size default = %d MiB, want %d MiB", got, util.DefaultVolumeSizeLimitMB)
|
||||
}
|
||||
if got := *masterOptions.volumeSizeLimitMB; got != util.DefaultVolumeSizeLimitMB {
|
||||
t.Fatalf("server master volume size default = %d MiB, want %d MiB", got, util.DefaultVolumeSizeLimitMB)
|
||||
}
|
||||
|
||||
defaultSize := int64(util.DefaultVolumeSizeLimitMB) * util.MiByte
|
||||
largeRowSize := int64(erasure_coding.DataShardsCount) * erasure_coding.ErasureCodingLargeBlockSize
|
||||
if remainder := defaultSize % largeRowSize; remainder != 0 {
|
||||
t.Fatalf("default volume size leaves %d bytes outside complete EC large-block rows", remainder)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerIndexIgnoresGrpcPort(t *testing.T) {
|
||||
self := pb.ServerAddress("127.0.0.1:9000.19000")
|
||||
peers := []pb.ServerAddress{
|
||||
|
||||
@@ -389,7 +389,6 @@ var (
|
||||
miniS3Config = cmdMini.Flag.String("s3.config", "", "path to the S3 config file")
|
||||
miniIamConfig = cmdMini.Flag.String("s3.iam.config", "", "path to the advanced IAM config file for S3")
|
||||
miniS3AllowDeleteBucketNotEmpty = cmdMini.Flag.Bool("s3.allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
|
||||
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 bucket names to create on startup if they do not already exist; leave empty to skip. Falls back to S3_TABLE_BUCKET env var.")
|
||||
)
|
||||
@@ -498,8 +497,6 @@ func initMiniS3Flags() {
|
||||
miniS3Options.portHttps = cmdMini.Flag.Int("s3.port.https", 0, "s3 server https listen port")
|
||||
miniS3Options.portGrpc = cmdMini.Flag.Int("s3.port.grpc", 0, "s3 server grpc listen port")
|
||||
miniS3Options.portIceberg = cmdMini.Flag.Int("s3.port.iceberg", 8181, "Iceberg REST Catalog server listen port (0 to disable)")
|
||||
miniS3Options.icebergCredentialRole = cmdMini.Flag.String("s3.iceberg.credentialRole", "", "IAM role ARN the Iceberg catalog assumes to vend table-scoped credentials (empty disables vending)")
|
||||
miniS3Options.icebergCredentialDuration = cmdMini.Flag.Int("s3.iceberg.credentialDurationSeconds", 3600, "lifetime of credentials vended by the Iceberg catalog")
|
||||
miniS3Options.domainName = cmdMini.Flag.String("s3.domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
|
||||
miniS3Options.allowedOrigins = cmdMini.Flag.String("s3.allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
miniS3Options.tlsPrivateKey = cmdMini.Flag.String("s3.key.file", "", "path to the TLS private key file")
|
||||
@@ -521,7 +518,6 @@ func initMiniS3Flags() {
|
||||
miniS3Options.iamConfig = miniIamConfig
|
||||
miniS3Options.auditLogConfig = cmdMini.Flag.String("s3.auditLogConfig", "", "path to the audit log config file")
|
||||
miniS3Options.allowDeleteBucketNotEmpty = miniS3AllowDeleteBucketNotEmpty
|
||||
miniS3Options.autoCreateBucket = miniS3AutoCreateBucket
|
||||
miniS3Options.externalUrl = cmdMini.Flag.String("s3.externalUrl", "", "the external URL clients use to connect (e.g. https://api.example.com:9000). Used for S3 signature verification behind a reverse proxy. Falls back to S3_EXTERNAL_URL env var.")
|
||||
miniS3Options.defaultFileMode = cmdMini.Flag.String("s3.defaultFileMode", "", "default file mode for S3 uploaded objects, e.g. 0660, 0644, 0666")
|
||||
miniS3Options.cacheSizeMB = cmdMini.Flag.Int64("s3.cacheCapacityMB", 0, "in-memory chunk cache capacity in MB for S3 GETs shared across requests (0 disables)")
|
||||
@@ -1267,8 +1263,8 @@ func runMini(cmd *Command, args []string) bool {
|
||||
|
||||
go stats_collect.StartMetricsServer(*miniMetricsHttpIp, *miniMetricsHttpPort)
|
||||
|
||||
if *miniMasterOptions.volumeSizeLimitMB > util.MaxVolumeSizeLimitMB {
|
||||
glog.Fatalf("master.volumeSizeLimitMB should not exceed %d", util.MaxVolumeSizeLimitMB)
|
||||
if *miniMasterOptions.volumeSizeLimitMB > util.VolumeSizeLimitGB*1000 {
|
||||
glog.Fatalf("masterVolumeSizeLimitMB should be less than 30000")
|
||||
}
|
||||
|
||||
if *miniMasterOptions.metaFolder == "" {
|
||||
|
||||
@@ -115,7 +115,7 @@ func init() {
|
||||
mountOptions.cacheDirForWrite = cmdMount.Flag.String("cacheDirWrite", "", "buffer writes mostly for large files")
|
||||
mountOptions.writeBufferSizeMB = cmdMount.Flag.Int64("writeBufferSizeMB", 0, "global cap on the per-mount write buffer (memory + swap) in MB, 0 means unlimited. Bounds /tmp growth when volume uploads stall")
|
||||
mountOptions.cacheMetaTtlSec = cmdMount.Flag.Int("cacheMetaTtlSec", 60, "metadata cache validity seconds")
|
||||
mountOptions.cacheDirMaxEntries = cmdMount.Flag.Int("cacheDirMaxEntries", 100000, "a directory with more children than this is not cached locally but read directly from the filer; 0 caches everything")
|
||||
mountOptions.cacheDirMaxEntries = cmdMount.Flag.Int("cacheDirMaxEntries", 10000, "a directory with more children than this is not cached locally but read directly from the filer; 0 caches everything")
|
||||
mountOptions.dataCenter = cmdMount.Flag.String("dataCenter", "", "prefer to write to the data center")
|
||||
mountOptions.allowOthers = cmdMount.Flag.Bool("allowOthers", true, "allows other users to access the file system")
|
||||
mountOptions.defaultPermissions = cmdMount.Flag.Bool("defaultPermissions", true, "enforce permissions by the operating system")
|
||||
|
||||
@@ -48,8 +48,6 @@ type S3Options struct {
|
||||
portHttps *int
|
||||
portGrpc *int
|
||||
portIceberg *int
|
||||
icebergCredentialRole *string
|
||||
icebergCredentialDuration *int
|
||||
config *string
|
||||
iamConfig *string
|
||||
domainName *string
|
||||
@@ -61,7 +59,6 @@ type S3Options struct {
|
||||
metricsHttpPort *int
|
||||
metricsHttpIp *string
|
||||
allowDeleteBucketNotEmpty *bool
|
||||
autoCreateBucket *bool
|
||||
auditLogConfig *string
|
||||
localFilerSocket *string
|
||||
dataCenter *string
|
||||
@@ -93,8 +90,6 @@ func init() {
|
||||
s3StandaloneOptions.portHttps = cmdS3.Flag.Int("port.https", 0, "s3 server https listen port")
|
||||
s3StandaloneOptions.portGrpc = cmdS3.Flag.Int("port.grpc", 0, "s3 server grpc listen port")
|
||||
s3StandaloneOptions.portIceberg = cmdS3.Flag.Int("port.iceberg", 8181, "Iceberg REST Catalog server listen port (0 to disable)")
|
||||
s3StandaloneOptions.icebergCredentialRole = cmdS3.Flag.String("iceberg.credentialRole", "", "IAM role ARN the Iceberg catalog assumes to vend table-scoped credentials (empty disables vending)")
|
||||
s3StandaloneOptions.icebergCredentialDuration = cmdS3.Flag.Int("iceberg.credentialDurationSeconds", 3600, "lifetime of credentials vended by the Iceberg catalog")
|
||||
s3StandaloneOptions.domainName = cmdS3.Flag.String("domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
|
||||
s3StandaloneOptions.allowedOrigins = cmdS3.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
s3StandaloneOptions.dataCenter = cmdS3.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
|
||||
@@ -109,7 +104,6 @@ func init() {
|
||||
s3StandaloneOptions.metricsHttpIp = cmdS3.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
|
||||
cmdS3.Flag.Bool("allowEmptyFolder", true, "deprecated, ignored. Empty folder cleanup is now automatic.")
|
||||
s3StandaloneOptions.allowDeleteBucketNotEmpty = cmdS3.Flag.Bool("allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
|
||||
s3StandaloneOptions.autoCreateBucket = cmdS3.Flag.Bool("autoCreateBucket", true, "create the bucket on upload if it does not exist, for admin identities only")
|
||||
s3StandaloneOptions.localFilerSocket = cmdS3.Flag.String("localFilerSocket", "", "local filer socket path")
|
||||
s3StandaloneOptions.localSocket = cmdS3.Flag.String("localSocket", "", "default to /tmp/seaweedfs-s3-<port>.sock")
|
||||
s3StandaloneOptions.idleTimeout = cmdS3.Flag.Int("idleTimeout", 120, "connection idle seconds")
|
||||
@@ -357,7 +351,6 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
BucketsPath: filerBucketsPath,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
AllowDeleteBucketNotEmpty: *s3opt.allowDeleteBucketNotEmpty,
|
||||
AutoCreateBucket: *s3opt.autoCreateBucket,
|
||||
LocalFilerSocket: localFilerSocket,
|
||||
DataCenter: *s3opt.dataCenter,
|
||||
FilerGroup: filerGroup,
|
||||
@@ -548,14 +541,6 @@ func (s3opt *S3Options) startIcebergServer(s3ApiServer *s3api.S3ApiServer) {
|
||||
// Create Iceberg server using the S3ApiServer as filer client
|
||||
icebergServer := iceberg.NewServer(s3ApiServer, s3ApiServer)
|
||||
icebergServer.SetCredentialValidator(s3ApiServer)
|
||||
if s3opt.icebergCredentialRole != nil && *s3opt.icebergCredentialRole != "" {
|
||||
duration := int64(0)
|
||||
if s3opt.icebergCredentialDuration != nil {
|
||||
duration = int64(*s3opt.icebergCredentialDuration)
|
||||
}
|
||||
s3ApiServer.SetIcebergCredentialRole(*s3opt.icebergCredentialRole, duration)
|
||||
icebergServer.SetCredentialVendor(icebergCredentialVendor{s3ApiServer})
|
||||
}
|
||||
icebergServer.SetS3Endpoint(s3opt.deriveS3AdvertisedEndpoint())
|
||||
icebergServer.RegisterRoutes(icebergRouter)
|
||||
|
||||
@@ -627,22 +612,3 @@ func (s3opt *S3Options) deriveS3AdvertisedEndpoint() string {
|
||||
}
|
||||
return fmt.Sprintf("%s://%s", scheme, util.JoinHostPort(host, port))
|
||||
}
|
||||
|
||||
// icebergCredentialVendor adapts the S3 gateway's STS-backed vending to the
|
||||
// catalog's interface, keeping the two packages independent of each other.
|
||||
type icebergCredentialVendor struct {
|
||||
server *s3api.S3ApiServer
|
||||
}
|
||||
|
||||
func (v icebergCredentialVendor) VendTableCredentials(ctx context.Context, principal, bucket, prefix string) (*iceberg.VendedCredentials, error) {
|
||||
credentials, err := v.server.VendTableCredentials(ctx, principal, bucket, prefix)
|
||||
if err != nil || credentials == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &iceberg.VendedCredentials{
|
||||
AccessKeyID: credentials.AccessKeyID,
|
||||
SecretAccessKey: credentials.SecretAccessKey,
|
||||
SessionToken: credentials.SessionToken,
|
||||
Expiration: credentials.Expiration,
|
||||
}, nil
|
||||
}
|
||||
@@ -285,7 +285,7 @@ ca_cert_path = ""
|
||||
client_cert_path = ""
|
||||
client_key_path = ""
|
||||
# allows reads from slave servers or the master, but all writes still go to the master
|
||||
useReadOnly = false
|
||||
readOnly = false
|
||||
# automatically use the closest Redis server for reads
|
||||
routeByLatency = false
|
||||
# This changes the data layout. Only add new directories. Removing/Updating will cause data loss.
|
||||
|
||||
@@ -77,12 +77,6 @@ expires_after_seconds = 10 # seconds
|
||||
# All gRPC TLS authentications are mutual (mTLS)
|
||||
# The values for ca, cert, and key are paths to the certificate/key files
|
||||
# The host name is not checked, so the certificate files can be shared
|
||||
# Each [grpc.<component>] section also accepts optional client_cert/client_key,
|
||||
# presented when that component dials other servers. Set them when your CA
|
||||
# issues separate serverAuth-only and clientAuth-only certificates; when unset,
|
||||
# the component reuses cert/key for both directions.
|
||||
# If client and server certificates come from different issuing CAs, put both
|
||||
# CA certificates in the ca PEM file.
|
||||
[grpc]
|
||||
ca = ""
|
||||
# Set wildcard domain for enable TLS authentication by common names
|
||||
@@ -93,8 +87,6 @@ allowed_wildcard_domain = "" # .mycompany.com
|
||||
[grpc.volume]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
# Master server gRPC options (server-side)
|
||||
@@ -102,8 +94,6 @@ allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
[grpc.master]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
# Filer server gRPC options (server-side)
|
||||
@@ -111,8 +101,6 @@ allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
[grpc.filer]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
# S3 server gRPC options (server-side)
|
||||
@@ -120,43 +108,31 @@ allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
[grpc.s3]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
[grpc.msg_broker]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
[grpc.msg_agent]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
[grpc.admin]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
[grpc.worker]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
[grpc.mq]
|
||||
cert = ""
|
||||
key = ""
|
||||
client_cert = ""
|
||||
client_key = ""
|
||||
allowed_commonNames = "" # comma-separated SSL certificate common names
|
||||
|
||||
# gRPC client configuration for outgoing gRPC connections
|
||||
|
||||
@@ -95,7 +95,7 @@ func init() {
|
||||
masterOptions.portGrpc = cmdServer.Flag.Int("master.port.grpc", 0, "master server grpc listen port")
|
||||
masterOptions.metaFolder = cmdServer.Flag.String("master.dir", "", "data directory to store meta data, default to same as -dir specified")
|
||||
masterOptions.peers = cmdServer.Flag.String("master.peers", "", "all master nodes in comma separated ip:masterPort list")
|
||||
masterOptions.volumeSizeLimitMB = cmdServer.Flag.Uint("master.volumeSizeLimitMB", util.DefaultVolumeSizeLimitMB, "Master stops directing writes to oversized volumes.")
|
||||
masterOptions.volumeSizeLimitMB = cmdServer.Flag.Uint("master.volumeSizeLimitMB", 30*1000, "Master stops directing writes to oversized volumes.")
|
||||
masterOptions.volumePreallocate = cmdServer.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
masterOptions.maxParallelVacuumPerServer = cmdServer.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
|
||||
masterOptions.defaultReplication = cmdServer.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
|
||||
@@ -164,8 +164,6 @@ func init() {
|
||||
s3Options.portHttps = cmdServer.Flag.Int("s3.port.https", 0, "s3 server https listen port")
|
||||
s3Options.portGrpc = cmdServer.Flag.Int("s3.port.grpc", 0, "s3 server grpc listen port")
|
||||
s3Options.portIceberg = cmdServer.Flag.Int("s3.port.iceberg", 8181, "Iceberg REST Catalog server listen port (0 to disable)")
|
||||
s3Options.icebergCredentialRole = cmdServer.Flag.String("s3.iceberg.credentialRole", "", "IAM role ARN the Iceberg catalog assumes to vend table-scoped credentials (empty disables vending)")
|
||||
s3Options.icebergCredentialDuration = cmdServer.Flag.Int("s3.iceberg.credentialDurationSeconds", 3600, "lifetime of credentials vended by the Iceberg catalog")
|
||||
s3Options.domainName = cmdServer.Flag.String("s3.domainName", "", "suffix of the host name in comma separated list, {bucket}.{domainName}")
|
||||
s3Options.allowedOrigins = cmdServer.Flag.String("s3.allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
s3Options.tlsPrivateKey = cmdServer.Flag.String("s3.key.file", "", "path to the TLS private key file")
|
||||
@@ -177,7 +175,6 @@ func init() {
|
||||
s3Options.auditLogConfig = cmdServer.Flag.String("s3.auditLogConfig", "", "path to the audit log config file")
|
||||
cmdServer.Flag.Bool("s3.allowEmptyFolder", true, "deprecated, ignored. Empty folder cleanup is now automatic.")
|
||||
s3Options.allowDeleteBucketNotEmpty = cmdServer.Flag.Bool("s3.allowDeleteBucketNotEmpty", true, "allow recursive deleting all entries along with bucket")
|
||||
s3Options.autoCreateBucket = cmdServer.Flag.Bool("s3.autoCreateBucket", true, "create the bucket on upload if it does not exist, for admin identities only")
|
||||
s3Options.localSocket = cmdServer.Flag.String("s3.localSocket", "", "default to /tmp/seaweedfs-s3-<port>.sock")
|
||||
s3Options.bindIp = cmdServer.Flag.String("s3.ip.bind", "", "ip address to bind to. If empty, default to same as -ip.bind option.")
|
||||
s3Options.idleTimeout = cmdServer.Flag.Int("s3.idleTimeout", 120, "connection idle seconds")
|
||||
@@ -342,8 +339,8 @@ func runServer(cmd *Command, args []string) bool {
|
||||
*volumeDataFolders = util.ResolveCommaSeparatedPaths(*volumeDataFolders)
|
||||
folders := strings.Split(*volumeDataFolders, ",")
|
||||
|
||||
if *masterOptions.volumeSizeLimitMB > util.MaxVolumeSizeLimitMB {
|
||||
glog.Fatalf("master.volumeSizeLimitMB should not exceed %d", util.MaxVolumeSizeLimitMB)
|
||||
if *masterOptions.volumeSizeLimitMB > util.VolumeSizeLimitGB*1000 {
|
||||
glog.Fatalf("masterVolumeSizeLimitMB should be less than 30000")
|
||||
}
|
||||
|
||||
if *masterOptions.metaFolder == "" {
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
)
|
||||
|
||||
// TestEcBalanceMigratesCrossDiskTypeShards: a cross-tier encode generates its
|
||||
// shards beside the source .dat — in the SOURCE disk-type bucket — while the
|
||||
// encode's balance targets -diskType. The balance must still see and spread
|
||||
// those shards when the volume is named as migrating; without that, the
|
||||
// planner finds nothing in the target bucket, plans no moves, and the encode's
|
||||
// spread guard aborts a perfectly good encode.
|
||||
func TestEcBalanceMigratesCrossDiskTypeShards(t *testing.T) {
|
||||
allShards := []erasure_coding.ShardId{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
|
||||
|
||||
build := func() []*EcNode {
|
||||
// Volume 1's fresh shards sit in the default (hdd, "") bucket of dn1;
|
||||
// the balance runs with -diskType=ssd.
|
||||
return []*EcNode{
|
||||
newEcNode("dc1", "rack1", "dn1", 100).addEcVolumeAndShardsForTest(1, "c1", allShards),
|
||||
newEcNode("dc1", "rack2", "dn2", 100),
|
||||
newEcNode("dc1", "rack3", "dn3", 100),
|
||||
}
|
||||
}
|
||||
|
||||
// Without the migrating hint the target-bucket filter hides the shards:
|
||||
// nothing moves. This is the standalone ec.balance semantic — shards of
|
||||
// other tiers stay where they are.
|
||||
ecb := &ecBalancer{
|
||||
ecNodes: build(),
|
||||
applyBalancing: false,
|
||||
diskType: types.SsdType,
|
||||
}
|
||||
if err := ecb.balance([]string{"c1"}); err != nil {
|
||||
t.Fatalf("balance without migrating hint: %v", err)
|
||||
}
|
||||
if got := ecb.ecNodes[0].LocalShardIdCount(1); got != len(allShards) {
|
||||
t.Fatalf("without migrating hint, cross-type shards must stay put; dn1 has %d", got)
|
||||
}
|
||||
|
||||
// With the volume named as migrating, the balance ingests the shards from
|
||||
// the source bucket and spreads them.
|
||||
ecb = &ecBalancer{
|
||||
ecNodes: build(),
|
||||
applyBalancing: false,
|
||||
diskType: types.SsdType,
|
||||
migratingVolumeIds: map[uint32]bool{1: true},
|
||||
}
|
||||
if err := ecb.balance([]string{"c1"}); err != nil {
|
||||
t.Fatalf("balance with migrating hint: %v", err)
|
||||
}
|
||||
onDn1 := ecb.ecNodes[0].LocalShardIdCount(1)
|
||||
spread := ecb.ecNodes[1].LocalShardIdCount(1) + ecb.ecNodes[2].LocalShardIdCount(1)
|
||||
if onDn1 == len(allShards) || spread == 0 {
|
||||
t.Fatalf("migrating volume's shards did not spread: dn1=%d others=%d", onDn1, spread)
|
||||
}
|
||||
if onDn1+spread != len(allShards) {
|
||||
t.Fatalf("shards lost or duplicated during dry-run spread: dn1=%d others=%d", onDn1, spread)
|
||||
}
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// CheckEcVolumeReplication reports EC volumes with under- or over-replicated
|
||||
// shards among the given data nodes. volumeIDs, when non-empty, narrows the
|
||||
// check to those volume ids.
|
||||
func CheckEcVolumeReplication(writer io.Writer, dataNodes []*master_pb.DataNodeInfo, volumeIDs map[uint32]bool, showDetails bool) error {
|
||||
runner := &ecCheckReplicationRunner{
|
||||
writer: writer,
|
||||
dataNodes: dataNodes,
|
||||
volumeIDMap: volumeIDs,
|
||||
}
|
||||
return runner.checkEcVolumes(showDetails)
|
||||
}
|
||||
|
||||
type ecCheckReplicationRunner struct {
|
||||
writer io.Writer
|
||||
dataNodes []*master_pb.DataNodeInfo
|
||||
volumeIDMap map[uint32]bool
|
||||
}
|
||||
|
||||
func (r *ecCheckReplicationRunner) write(format string, a ...any) {
|
||||
fmt.Fprintf(r.writer, format, a...)
|
||||
}
|
||||
|
||||
func (r *ecCheckReplicationRunner) isVolumeIDValid(vid uint32) bool {
|
||||
if len(r.volumeIDMap) == 0 {
|
||||
return true
|
||||
}
|
||||
return r.volumeIDMap[vid]
|
||||
}
|
||||
|
||||
// ecVolumeShardReplication aggregates the observed shards for a single EC volume,
|
||||
// together with the data+parity ratio the volume was encoded with. The ratio is
|
||||
// taken per volume (via erasure_coding.EcShardsVolume*Shards) so custom EC
|
||||
// ratios are checked against their own expected shard count.
|
||||
type ecVolumeShardReplication struct {
|
||||
dataShards int
|
||||
parityShards int
|
||||
// shardAddresses maps a shard id to the sorted node addresses hosting it.
|
||||
shardAddresses map[erasure_coding.ShardId][]string
|
||||
}
|
||||
|
||||
func (h *ecVolumeShardReplication) totalShards() int {
|
||||
return h.dataShards + h.parityShards
|
||||
}
|
||||
|
||||
// replicaCount is the total number of shard copies observed, counting each
|
||||
// over-replicated shard once per hosting node.
|
||||
func (h *ecVolumeShardReplication) replicaCount() int {
|
||||
n := 0
|
||||
for _, addrs := range h.shardAddresses {
|
||||
n += len(addrs)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// unexpectedShardIds returns, in ascending order, any observed shard ids that
|
||||
// fall outside the volume's expected data+parity range. These are anomalies
|
||||
// (e.g. a stray shard) and are treated as over-replication.
|
||||
func (h *ecVolumeShardReplication) unexpectedShardIds() []erasure_coding.ShardId {
|
||||
var ids []erasure_coding.ShardId
|
||||
for sid := range h.shardAddresses {
|
||||
if int(sid) >= h.totalShards() {
|
||||
ids = append(ids, sid)
|
||||
}
|
||||
}
|
||||
slices.Sort(ids)
|
||||
return ids
|
||||
}
|
||||
|
||||
// TODO: check shard sizes?
|
||||
func (r *ecCheckReplicationRunner) checkEcVolumes(showDetails bool) error {
|
||||
// collect EC shard placement, keyed by volume id
|
||||
volumes := map[uint32]*ecVolumeShardReplication{}
|
||||
for _, dni := range r.dataNodes {
|
||||
nodeAddress := dni.GetAddress()
|
||||
for _, di := range dni.GetDiskInfos() {
|
||||
for _, eci := range di.GetEcShardInfos() {
|
||||
vid := eci.GetId()
|
||||
if !r.isVolumeIDValid(vid) {
|
||||
continue
|
||||
}
|
||||
|
||||
h, ok := volumes[vid]
|
||||
if !ok {
|
||||
// all shards of a volume share one ratio; take it from the
|
||||
// first shard message seen for the volume.
|
||||
h = &ecVolumeShardReplication{
|
||||
dataShards: erasure_coding.EcShardsVolumeDataShards(eci),
|
||||
parityShards: erasure_coding.EcShardsVolumeParityShards(eci),
|
||||
shardAddresses: map[erasure_coding.ShardId][]string{},
|
||||
}
|
||||
volumes[vid] = h
|
||||
}
|
||||
|
||||
sinfo := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(eci)
|
||||
for _, sid := range sinfo.Ids() {
|
||||
h.shardAddresses[sid] = append(h.shardAddresses[sid], nodeAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(volumes) == 0 {
|
||||
// Asking about specific volume IDs that turn out not to be EC volumes is
|
||||
// an error; an unfiltered run over a cluster with no EC volumes is a
|
||||
// legitimate, healthy state rather than a failure.
|
||||
if len(r.volumeIDMap) > 0 {
|
||||
return fmt.Errorf("no EC volumes found")
|
||||
}
|
||||
r.write("No EC volumes found.\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// keep the shard address lists nicely sorted, for the sake of readability.
|
||||
for _, h := range volumes {
|
||||
for _, addrs := range h.shardAddresses {
|
||||
slices.Sort(addrs)
|
||||
}
|
||||
}
|
||||
|
||||
// classify each volume against its own expected shard count
|
||||
underreplicatedVolumeIDs := []uint32{}
|
||||
overreplicatedVolumeIDs := []uint32{}
|
||||
for vid, h := range volumes {
|
||||
under := false
|
||||
over := false
|
||||
for sid := 0; sid < h.totalShards(); sid++ {
|
||||
switch len(h.shardAddresses[erasure_coding.ShardId(sid)]) {
|
||||
case 0:
|
||||
under = true
|
||||
case 1:
|
||||
default:
|
||||
over = true
|
||||
}
|
||||
}
|
||||
// shard ids beyond the expected data+parity range are unexpected extras,
|
||||
// i.e. redundant data the ratio doesn't call for.
|
||||
if len(h.unexpectedShardIds()) > 0 {
|
||||
over = true
|
||||
}
|
||||
|
||||
// under- and over-replication are independent problems (missing shards risk
|
||||
// data loss, redundant shards waste space), so a volume exhibiting both is
|
||||
// reported in both lists.
|
||||
if under {
|
||||
underreplicatedVolumeIDs = append(underreplicatedVolumeIDs, vid)
|
||||
}
|
||||
if over {
|
||||
overreplicatedVolumeIDs = append(overreplicatedVolumeIDs, vid)
|
||||
}
|
||||
}
|
||||
slices.Sort(underreplicatedVolumeIDs)
|
||||
slices.Sort(overreplicatedVolumeIDs)
|
||||
|
||||
// ...and display results
|
||||
if len(underreplicatedVolumeIDs) == 0 && len(overreplicatedVolumeIDs) == 0 {
|
||||
r.write("EC volumes are healthy.\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(underreplicatedVolumeIDs) != 0 {
|
||||
r.write("Found %d/%d under-replicated EC volumes: %v\n", len(underreplicatedVolumeIDs), len(volumes), underreplicatedVolumeIDs)
|
||||
}
|
||||
if len(overreplicatedVolumeIDs) != 0 {
|
||||
r.write("Found %d/%d over-replicated EC volumes: %v\n", len(overreplicatedVolumeIDs), len(volumes), overreplicatedVolumeIDs)
|
||||
}
|
||||
|
||||
if showDetails {
|
||||
if len(underreplicatedVolumeIDs) != 0 {
|
||||
r.write("\n")
|
||||
r.writeShardMaps("under-replicated", underreplicatedVolumeIDs, volumes)
|
||||
}
|
||||
if len(overreplicatedVolumeIDs) != 0 {
|
||||
r.write("\n")
|
||||
r.writeShardMaps("over-replicated", overreplicatedVolumeIDs, volumes)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ecCheckReplicationRunner) writeShardMaps(kind string, volumeIDs []uint32, volumes map[uint32]*ecVolumeShardReplication) {
|
||||
for _, vid := range volumeIDs {
|
||||
h := volumes[vid]
|
||||
r.write("Shards map for %s EC volume %v (%d/%d shards):\n", kind, vid, h.replicaCount(), h.totalShards())
|
||||
for sid := 0; sid < h.totalShards(); sid++ {
|
||||
shardTypeDesc := ""
|
||||
if sid >= h.dataShards {
|
||||
shardTypeDesc = " (parity)"
|
||||
}
|
||||
if addrs, ok := h.shardAddresses[erasure_coding.ShardId(sid)]; ok {
|
||||
r.write("\t%02d%s => %v\n", sid, shardTypeDesc, addrs)
|
||||
} else {
|
||||
r.write("\t%02d%s is missing\n", sid, shardTypeDesc)
|
||||
}
|
||||
}
|
||||
for _, sid := range h.unexpectedShardIds() {
|
||||
r.write("\t%02d (unexpected) => %v\n", int(sid), h.shardAddresses[sid])
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,463 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func DoEcDecode(env *Env, topoInfo *master_pb.TopologyInfo, collection string, vid needle.VolumeId, diskType types.DiskType, checkMinFreeSpace bool, diskUsageState *DecodeDiskUsageState) (err error) {
|
||||
|
||||
if !env.isLocked() {
|
||||
return fmt.Errorf("lock is lost")
|
||||
}
|
||||
|
||||
// find volume location
|
||||
nodeToEcShardsInfo, dataShards := collectEcNodeShardsInfo(topoInfo, vid)
|
||||
|
||||
fmt.Printf("ec volume %d shard locations: %+v\n", vid, nodeToEcShardsInfo)
|
||||
|
||||
if len(nodeToEcShardsInfo) == 0 {
|
||||
return fmt.Errorf("no EC shards found for volume %d", vid)
|
||||
}
|
||||
|
||||
// A decode interrupted while deleting the shards leaves the regenerated
|
||||
// volume in place with the set half gone, so a re-run finds both and fails
|
||||
// re-collecting the first shard the interrupted run removed.
|
||||
//
|
||||
// Finding a volume beside the shards is not enough to act on: an encode
|
||||
// interrupted before it deleted the original leaves the same shape, as does
|
||||
// a decode killed while generating, whose volume may be half written. Both
|
||||
// of those leave the shard set COMPLETE. Only the deletion phase can remove
|
||||
// a data shard, so require one to be gone -- that is also exactly the state
|
||||
// no decode can recover from, which makes finishing the cleanup the only
|
||||
// move left rather than a choice between two.
|
||||
if _, found := missingDataShard(nodeToEcShardsInfo, dataShards); found {
|
||||
holder, hasVolume := regularVolumeHolder(topoInfo, vid)
|
||||
if !hasVolume {
|
||||
return fmt.Errorf("volume %d cannot be decoded: data shards are missing and no decoded volume exists to finish", vid)
|
||||
}
|
||||
if err := verifyDecodedVolumeBeforeDelete(env.GrpcDialOption, holder, vid); err != nil {
|
||||
return fmt.Errorf("volume %d is already decoded on %s but did not verify, keeping its ec shards: %v", vid, holder, err)
|
||||
}
|
||||
fmt.Printf("volume %d is already decoded on %s; deleting the ec shards the interrupted run left behind\n", vid, holder)
|
||||
return unmountAndDeleteEcShardsWithPrefix("deleteDecodedEcShards", env.GrpcDialOption, collection, nodeToEcShardsInfo, vid)
|
||||
}
|
||||
|
||||
var originalShardCounts map[pb.ServerAddress]int
|
||||
if diskUsageState != nil {
|
||||
originalShardCounts = make(map[pb.ServerAddress]int, len(nodeToEcShardsInfo))
|
||||
for location, si := range nodeToEcShardsInfo {
|
||||
originalShardCounts[location] = si.Count()
|
||||
}
|
||||
}
|
||||
|
||||
var eligibleTargets map[pb.ServerAddress]struct{}
|
||||
if checkMinFreeSpace {
|
||||
if diskUsageState == nil {
|
||||
return fmt.Errorf("min free space checking requires disk usage state")
|
||||
}
|
||||
eligibleTargets = make(map[pb.ServerAddress]struct{})
|
||||
for location := range nodeToEcShardsInfo {
|
||||
if freeCount, found := diskUsageState.freeVolumeCount(location); found && freeCount > 0 {
|
||||
eligibleTargets[location] = struct{}{}
|
||||
}
|
||||
}
|
||||
if len(eligibleTargets) == 0 {
|
||||
return fmt.Errorf("no eligible target datanodes with free volume slots for volume %d (diskType %s); use -checkMinFreeSpace=false to override", vid, diskType.ReadableString())
|
||||
}
|
||||
}
|
||||
|
||||
// collect ec shards to the server with most space
|
||||
targetNodeLocation, err := collectEcShards(env, nodeToEcShardsInfo, collection, vid, eligibleTargets, dataShards)
|
||||
if err != nil {
|
||||
return fmt.Errorf("collectEcShards for volume %d: %v", vid, err)
|
||||
}
|
||||
|
||||
// generate a normal volume
|
||||
err = generateNormalVolume(env.GrpcDialOption, vid, collection, targetNodeLocation)
|
||||
if err != nil {
|
||||
// Special case: if the EC index has no live entries, decoding is a no-op.
|
||||
// Just purge EC shards and return success without generating/mounting an empty volume.
|
||||
if isEcDecodeEmptyVolumeErr(err) {
|
||||
if err := unmountAndDeleteEcShards(env.GrpcDialOption, collection, nodeToEcShardsInfo, vid); err != nil {
|
||||
return err
|
||||
}
|
||||
if diskUsageState != nil {
|
||||
diskUsageState.applyDecode(targetNodeLocation, originalShardCounts, false)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("generate normal volume %d on %s: %v", vid, targetNodeLocation, err)
|
||||
}
|
||||
|
||||
// mount the decoded volume after server-side offline compaction succeeded
|
||||
err = mountDecodedVolume(env.GrpcDialOption, targetNodeLocation, vid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mount decoded volume %d on %s: %v", vid, targetNodeLocation, err)
|
||||
}
|
||||
|
||||
// Confirm the regenerated .dat is present and non-empty before destroying
|
||||
// the shards. Without this gate, a silent failure in generate/mount could
|
||||
// leave the cluster with neither shards nor volume.
|
||||
if err := verifyDecodedVolumeBeforeDelete(env.GrpcDialOption, targetNodeLocation, vid); err != nil {
|
||||
return fmt.Errorf("verify decoded volume %d on %s before deleting shards: %w", vid, targetNodeLocation, err)
|
||||
}
|
||||
|
||||
// delete the previous ec shards
|
||||
err = unmountAndDeleteEcShardsWithPrefix("deleteDecodedEcShards", env.GrpcDialOption, collection, nodeToEcShardsInfo, vid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete ec shards for volume %d: %v", vid, err)
|
||||
}
|
||||
if diskUsageState != nil {
|
||||
diskUsageState.applyDecode(targetNodeLocation, originalShardCounts, true)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isEcDecodeEmptyVolumeErr(err error) bool {
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if st.Code() != codes.FailedPrecondition {
|
||||
return false
|
||||
}
|
||||
// Keep this robust against wording tweaks while still being specific.
|
||||
return strings.Contains(st.Message(), erasure_coding.EcNoLiveEntriesSubstring)
|
||||
}
|
||||
|
||||
func unmountAndDeleteEcShards(grpcDialOption grpc.DialOption, collection string, nodeToShardsInfo map[pb.ServerAddress]*erasure_coding.ShardsInfo, vid needle.VolumeId) error {
|
||||
return unmountAndDeleteEcShardsWithPrefix("unmountAndDeleteEcShards", grpcDialOption, collection, nodeToShardsInfo, vid)
|
||||
}
|
||||
|
||||
func unmountAndDeleteEcShardsWithPrefix(prefix string, grpcDialOption grpc.DialOption, collection string, nodeToShardsInfo map[pb.ServerAddress]*erasure_coding.ShardsInfo, vid needle.VolumeId) error {
|
||||
ewg := util.NewErrorWaitGroup(len(nodeToShardsInfo))
|
||||
|
||||
// unmount and delete ec shards in parallel (one goroutine per location)
|
||||
for location, si := range nodeToShardsInfo {
|
||||
location, si := location, si // capture loop variables for goroutine
|
||||
ewg.Add(func() error {
|
||||
fmt.Printf("unmount ec volume %d on %s has shards: %+v\n", vid, location, si.Ids())
|
||||
if err := UnmountEcShards(grpcDialOption, vid, location, si.Ids()); err != nil {
|
||||
return fmt.Errorf("%s unmount ec volume %d on %s: %w", prefix, vid, location, err)
|
||||
}
|
||||
|
||||
fmt.Printf("delete ec volume %d on %s has shards: %+v\n", vid, location, si.Ids())
|
||||
if err := SourceServerDeleteEcShards(grpcDialOption, collection, vid, location, si.Ids()); err != nil {
|
||||
return fmt.Errorf("%s delete ec volume %d on %s: %w", prefix, vid, location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
return ewg.Wait()
|
||||
}
|
||||
|
||||
// missingDataShard reports the first data shard absent from every holder.
|
||||
// Parity shards are not enough to answer this: the decode rebuilds the volume
|
||||
// from the data shards, so one of those going missing is what makes a re-run
|
||||
// impossible.
|
||||
func missingDataShard(nodeToShardsInfo map[pb.ServerAddress]*erasure_coding.ShardsInfo, dataShards int) (erasure_coding.ShardId, bool) {
|
||||
var present erasure_coding.ShardBits
|
||||
for _, si := range nodeToShardsInfo {
|
||||
for _, id := range si.Ids() {
|
||||
present = present.Set(id)
|
||||
}
|
||||
}
|
||||
for id := 0; id < dataShards; id++ {
|
||||
if !present.Has(erasure_coding.ShardId(id)) {
|
||||
return erasure_coding.ShardId(id), true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// regularVolumeHolder returns a server already serving vid as a regular
|
||||
// volume. A decode only finds one when an earlier run was interrupted between
|
||||
// regenerating the volume and deleting the shards it came from.
|
||||
func regularVolumeHolder(topoInfo *master_pb.TopologyInfo, vid needle.VolumeId) (pb.ServerAddress, bool) {
|
||||
var holder pb.ServerAddress
|
||||
found := false
|
||||
EachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
if found {
|
||||
return
|
||||
}
|
||||
for _, diskInfo := range dn.DiskInfos {
|
||||
for _, vi := range diskInfo.VolumeInfos {
|
||||
if needle.VolumeId(vi.Id) == vid {
|
||||
holder = pb.NewServerAddressFromDataNode(dn)
|
||||
found = true
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return holder, found
|
||||
}
|
||||
|
||||
func verifyDecodedVolumeBeforeDelete(grpcDialOption grpc.DialOption, target pb.ServerAddress, vid needle.VolumeId) error {
|
||||
var resp *volume_server_pb.ReadVolumeFileStatusResponse
|
||||
if err := operation.WithVolumeServerClient(false, target, grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
|
||||
r, e := client.ReadVolumeFileStatus(context.Background(), &volume_server_pb.ReadVolumeFileStatusRequest{
|
||||
VolumeId: uint32(vid),
|
||||
})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
resp = r
|
||||
return nil
|
||||
}); err != nil {
|
||||
return fmt.Errorf("read volume file status: %w", err)
|
||||
}
|
||||
if resp.DatFileSize == 0 {
|
||||
return fmt.Errorf("decoded .dat is 0 bytes")
|
||||
}
|
||||
if resp.IdxFileSize == 0 {
|
||||
return fmt.Errorf("decoded .idx is 0 bytes")
|
||||
}
|
||||
glog.V(0).Infof("ec decode verification ok for volume %d on %s: dat=%d idx=%d", vid, target, resp.DatFileSize, resp.IdxFileSize)
|
||||
return nil
|
||||
}
|
||||
|
||||
func mountDecodedVolume(grpcDialOption grpc.DialOption, targetNodeLocation pb.ServerAddress, vid needle.VolumeId) error {
|
||||
return operation.WithVolumeServerClient(false, targetNodeLocation, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
_, mountErr := volumeServerClient.VolumeMount(context.Background(), &volume_server_pb.VolumeMountRequest{
|
||||
VolumeId: uint32(vid),
|
||||
})
|
||||
return mountErr
|
||||
})
|
||||
}
|
||||
|
||||
func generateNormalVolume(grpcDialOption grpc.DialOption, vid needle.VolumeId, collection string, sourceVolumeServer pb.ServerAddress) error {
|
||||
fmt.Printf("generateNormalVolume from ec volume %d on %s\n", vid, sourceVolumeServer)
|
||||
|
||||
err := operation.WithVolumeServerClient(false, sourceVolumeServer, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
_, genErr := volumeServerClient.VolumeEcShardsToVolume(context.Background(), &volume_server_pb.VolumeEcShardsToVolumeRequest{
|
||||
VolumeId: uint32(vid),
|
||||
Collection: collection,
|
||||
})
|
||||
return genErr
|
||||
})
|
||||
|
||||
return err
|
||||
|
||||
}
|
||||
|
||||
func collectEcShards(env *Env, nodeToShardsInfo map[pb.ServerAddress]*erasure_coding.ShardsInfo, collection string, vid needle.VolumeId, eligibleTargets map[pb.ServerAddress]struct{}, dataShards int) (targetNodeLocation pb.ServerAddress, err error) {
|
||||
|
||||
maxShardCount := -1
|
||||
existingShardsInfo := erasure_coding.NewShardsInfo()
|
||||
for loc, si := range nodeToShardsInfo {
|
||||
if eligibleTargets != nil {
|
||||
if _, ok := eligibleTargets[loc]; !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
toBeCopiedShardCount := si.MinusParityShards(dataShards).Count()
|
||||
if toBeCopiedShardCount > maxShardCount {
|
||||
maxShardCount = toBeCopiedShardCount
|
||||
targetNodeLocation = loc
|
||||
existingShardsInfo = si
|
||||
}
|
||||
}
|
||||
if targetNodeLocation == "" {
|
||||
return "", fmt.Errorf("no eligible target datanodes available to decode volume %d", vid)
|
||||
}
|
||||
|
||||
// Trust only shards the target can actually serve: an interrupted earlier
|
||||
// decode or balance can leave the master believing the target holds a
|
||||
// shard whose file never landed. A phantom entry here would exclude the
|
||||
// shard from the copy set and the decode would then fail with "missing
|
||||
// shard"; probing the target's live inventory makes the re-run re-copy it.
|
||||
if present, probeErr := erasure_coding.CollectShardsOnServer(context.Background(), collection, uint32(vid), string(targetNodeLocation), env.GrpcDialOption); probeErr == nil {
|
||||
confirmed := erasure_coding.NewShardsInfo()
|
||||
for _, sid := range existingShardsInfo.Ids() {
|
||||
if present.Has(sid) {
|
||||
confirmed.Set(erasure_coding.NewShardInfo(sid, 0))
|
||||
}
|
||||
}
|
||||
existingShardsInfo = confirmed
|
||||
} else {
|
||||
fmt.Printf("collectEcShards: probe %s inventory for volume %d: %v (keeping the topology's view)\n", targetNodeLocation, vid, probeErr)
|
||||
}
|
||||
|
||||
fmt.Printf("collectEcShards: ec volume %d collect shards to %s from: %+v\n", vid, targetNodeLocation, nodeToShardsInfo)
|
||||
|
||||
copiedShardsInfo := erasure_coding.NewShardsInfo()
|
||||
for loc, si := range nodeToShardsInfo {
|
||||
if loc == targetNodeLocation {
|
||||
continue
|
||||
}
|
||||
|
||||
needToCopyShardsInfo := si.Minus(existingShardsInfo).MinusParityShards(dataShards)
|
||||
|
||||
err = operation.WithVolumeServerClient(false, targetNodeLocation, env.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
|
||||
// Always collect .ecj from every shard location. Each server's .ecj
|
||||
// only contains deletions for needles whose data resides in shards
|
||||
// held by that server. Without merging all .ecj files, deletions
|
||||
// recorded on other servers would be lost during decode.
|
||||
if needToCopyShardsInfo.Count() > 0 {
|
||||
fmt.Printf("copy %d.%v %s => %s\n", vid, needToCopyShardsInfo.Ids(), loc, targetNodeLocation)
|
||||
} else {
|
||||
fmt.Printf("collect ecj %d %s => %s\n", vid, loc, targetNodeLocation)
|
||||
}
|
||||
|
||||
_, copyErr := volumeServerClient.VolumeEcShardsCopy(context.Background(), &volume_server_pb.VolumeEcShardsCopyRequest{
|
||||
VolumeId: uint32(vid),
|
||||
Collection: collection,
|
||||
ShardIds: needToCopyShardsInfo.IdsUint32(),
|
||||
CopyEcxFile: false,
|
||||
CopyEcjFile: true,
|
||||
CopyVifFile: needToCopyShardsInfo.Count() > 0,
|
||||
SourceDataNode: string(loc),
|
||||
})
|
||||
if copyErr != nil {
|
||||
return fmt.Errorf("copy %d.%v %s => %s: %v", vid, needToCopyShardsInfo.Ids(), loc, targetNodeLocation, copyErr)
|
||||
}
|
||||
|
||||
if needToCopyShardsInfo.Count() > 0 {
|
||||
fmt.Printf("mount %d.%v on %s\n", vid, needToCopyShardsInfo.Ids(), targetNodeLocation)
|
||||
_, mountErr := volumeServerClient.VolumeEcShardsMount(context.Background(), &volume_server_pb.VolumeEcShardsMountRequest{
|
||||
VolumeId: uint32(vid),
|
||||
Collection: collection,
|
||||
ShardIds: needToCopyShardsInfo.IdsUint32(),
|
||||
})
|
||||
if mountErr != nil {
|
||||
return fmt.Errorf("mount %d.%v on %s: %v", vid, needToCopyShardsInfo.Ids(), targetNodeLocation, mountErr)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
copiedShardsInfo.Add(needToCopyShardsInfo)
|
||||
}
|
||||
|
||||
nodeToShardsInfo[targetNodeLocation] = existingShardsInfo.Plus(copiedShardsInfo)
|
||||
|
||||
return targetNodeLocation, err
|
||||
}
|
||||
func CollectEcShardIds(topoInfo *master_pb.TopologyInfo, collectionRegex *regexp.Regexp, diskType types.DiskType) (vids []needle.VolumeId) {
|
||||
vidMap := make(map[uint32]bool)
|
||||
EachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
if diskInfo, found := dn.DiskInfos[string(diskType)]; found {
|
||||
for _, v := range diskInfo.EcShardInfos {
|
||||
if collectionRegex.MatchString(v.Collection) {
|
||||
vidMap[v.Id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for vid := range vidMap {
|
||||
vids = append(vids, needle.VolumeId(vid))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func collectEcNodeShardsInfo(topoInfo *master_pb.TopologyInfo, vid needle.VolumeId) (map[pb.ServerAddress]*erasure_coding.ShardsInfo, int) {
|
||||
res := make(map[pb.ServerAddress]*erasure_coding.ShardsInfo)
|
||||
EachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
// Union across ALL disk-type buckets and, within a node, across its
|
||||
// physical disks. Shards sit wherever encode generation and balance
|
||||
// left them — a cross-tier encode leaves them in the source bucket, a
|
||||
// partial migration straddles buckets — and a decode that only looks
|
||||
// at one bucket reports a decodable volume as having no shards at all.
|
||||
// (Same rationale as the encode's shard verification.)
|
||||
for _, diskInfo := range dn.DiskInfos {
|
||||
if diskInfo == nil {
|
||||
continue
|
||||
}
|
||||
for _, v := range diskInfo.EcShardInfos {
|
||||
if v.Id == uint32(vid) {
|
||||
addr := pb.NewServerAddressFromDataNode(dn)
|
||||
si := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(v)
|
||||
if existing, ok := res[addr]; ok {
|
||||
existing.Add(si)
|
||||
} else {
|
||||
res[addr] = si
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// OSS is always 10+4; the per-volume ratio override lives in the enterprise build.
|
||||
return res, erasure_coding.DataShardsCount
|
||||
}
|
||||
|
||||
type DecodeDiskUsageState struct {
|
||||
byNode map[pb.ServerAddress]*decodeDiskUsageCounts
|
||||
}
|
||||
|
||||
type decodeDiskUsageCounts struct {
|
||||
maxVolumeCount int64
|
||||
volumeCount int64
|
||||
remoteVolumeCount int64
|
||||
ecShardCount int64
|
||||
}
|
||||
|
||||
func NewDecodeDiskUsageState(topoInfo *master_pb.TopologyInfo, diskType types.DiskType) *DecodeDiskUsageState {
|
||||
state := &DecodeDiskUsageState{byNode: make(map[pb.ServerAddress]*decodeDiskUsageCounts)}
|
||||
EachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
if diskInfo, found := dn.DiskInfos[string(diskType)]; found {
|
||||
state.byNode[pb.NewServerAddressFromDataNode(dn)] = &decodeDiskUsageCounts{
|
||||
maxVolumeCount: diskInfo.MaxVolumeCount,
|
||||
volumeCount: diskInfo.VolumeCount,
|
||||
remoteVolumeCount: diskInfo.RemoteVolumeCount,
|
||||
ecShardCount: int64(CountShards(diskInfo.EcShardInfos)),
|
||||
}
|
||||
}
|
||||
})
|
||||
return state
|
||||
}
|
||||
|
||||
func (state *DecodeDiskUsageState) freeVolumeCount(location pb.ServerAddress) (int64, bool) {
|
||||
if state == nil {
|
||||
return 0, false
|
||||
}
|
||||
usage, found := state.byNode[location]
|
||||
if !found {
|
||||
return 0, false
|
||||
}
|
||||
free := usage.maxVolumeCount - (usage.volumeCount - usage.remoteVolumeCount)
|
||||
free -= (usage.ecShardCount + int64(erasure_coding.DataShardsCount) - 1) / int64(erasure_coding.DataShardsCount)
|
||||
return free, true
|
||||
}
|
||||
|
||||
func (state *DecodeDiskUsageState) applyDecode(targetNodeLocation pb.ServerAddress, shardCounts map[pb.ServerAddress]int, createdVolume bool) {
|
||||
if state == nil {
|
||||
return
|
||||
}
|
||||
for location, shardCount := range shardCounts {
|
||||
if usage, found := state.byNode[location]; found {
|
||||
usage.ecShardCount -= int64(shardCount)
|
||||
}
|
||||
}
|
||||
if createdVolume {
|
||||
if usage, found := state.byNode[targetNodeLocation]; found {
|
||||
usage.volumeCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
// shardsOn builds one holder's inventory.
|
||||
func shardsOn(ids ...int) *erasure_coding.ShardsInfo {
|
||||
si := erasure_coding.NewShardsInfo()
|
||||
for _, id := range ids {
|
||||
si.Set(erasure_coding.NewShardInfo(erasure_coding.ShardId(id), 1024))
|
||||
}
|
||||
return si
|
||||
}
|
||||
|
||||
// missingDataShard decides whether a decode may delete the shards of a volume
|
||||
// that already exists elsewhere. Only the deletion phase of a decode removes a
|
||||
// data shard, so the answer separates "an earlier decode was interrupted while
|
||||
// cleaning up" from the two states that look the same from the outside: an
|
||||
// encode interrupted before it deleted the original, and a decode killed while
|
||||
// generating. Both of those leave every shard in place, and the volume beside
|
||||
// them may be the untouched original or a half-written one -- neither is safe
|
||||
// to trade for the shards.
|
||||
func TestMissingDataShard(t *testing.T) {
|
||||
const dataShards = 10
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
holders map[pb.ServerAddress]*erasure_coding.ShardsInfo
|
||||
wantID erasure_coding.ShardId
|
||||
wantMissed bool
|
||||
}{
|
||||
{
|
||||
name: "complete set on one holder decodes, so nothing is finished",
|
||||
holders: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": shardsOn(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "complete set spread across holders is still complete",
|
||||
holders: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": shardsOn(0, 1, 2, 3, 4),
|
||||
"server2:8080": shardsOn(5, 6, 7, 8, 9),
|
||||
"server3:8080": shardsOn(10, 11, 12, 13),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "parity gone is not the deletion phase: the volume still decodes",
|
||||
holders: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": shardsOn(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a data shard gone is a decode that was interrupted mid-cleanup",
|
||||
holders: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": shardsOn(0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13),
|
||||
},
|
||||
wantID: 6,
|
||||
wantMissed: true,
|
||||
},
|
||||
{
|
||||
name: "the first gap is reported, not the last",
|
||||
holders: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": shardsOn(0, 3, 4, 5, 6, 7, 8, 9),
|
||||
},
|
||||
wantID: 1,
|
||||
wantMissed: true,
|
||||
},
|
||||
{
|
||||
name: "no holders at all leaves every data shard missing",
|
||||
holders: map[pb.ServerAddress]*erasure_coding.ShardsInfo{},
|
||||
wantID: 0,
|
||||
wantMissed: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
id, missed := missingDataShard(tt.holders, dataShards)
|
||||
if missed != tt.wantMissed {
|
||||
t.Fatalf("missingDataShard = %v, want %v", missed, tt.wantMissed)
|
||||
}
|
||||
if missed && id != tt.wantID {
|
||||
t.Errorf("missing shard id = %d, want %d", id, tt.wantID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,214 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
// sizedShards builds one holder's inventory as {shard id: size}.
|
||||
func sizedShards(idToSize map[int]int64) *erasure_coding.ShardsInfo {
|
||||
si := erasure_coding.NewShardsInfo()
|
||||
for id, size := range idToSize {
|
||||
si.Set(erasure_coding.NewShardInfo(erasure_coding.ShardId(id), erasure_coding.ShardSize(size)))
|
||||
}
|
||||
return si
|
||||
}
|
||||
|
||||
// An encode deletes the volume the shards were made from, on the strength of
|
||||
// having counted them. Every shard takes one piece of each block row, so they
|
||||
// are written to the same length: one that disagrees was truncated or half
|
||||
// copied, and counting cannot see it.
|
||||
func TestRequireUniformShardSizes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
byNode map[pb.ServerAddress]*erasure_coding.ShardsInfo
|
||||
wantErr bool
|
||||
errContains []string
|
||||
}{
|
||||
{
|
||||
name: "one holder, all shards the same length",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": sizedShards(map[int]int64{0: 1048576, 1: 1048576, 2: 1048576}),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "spread across holders, still one length",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": sizedShards(map[int]int64{0: 1048576, 1: 1048576}),
|
||||
"server2:8080": sizedShards(map[int]int64{2: 1048576, 3: 1048576}),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "a truncated shard is named with its holder",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": sizedShards(map[int]int64{0: 1048576, 1: 1048576}),
|
||||
"server2:8080": sizedShards(map[int]int64{2: 4096}),
|
||||
},
|
||||
wantErr: true,
|
||||
errContains: []string{"disagree on size", "server2:8080.2", "4096"},
|
||||
},
|
||||
{
|
||||
name: "two copies of one shard that disagree are still a disagreement",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": sizedShards(map[int]int64{5: 1048576}),
|
||||
"server2:8080": sizedShards(map[int]int64{5: 1048570}),
|
||||
},
|
||||
wantErr: true,
|
||||
errContains: []string{"disagree on size"},
|
||||
},
|
||||
|
||||
// Sizes the cluster does not report must never block an encode: an
|
||||
// older volume server, or one that has not heartbeated its sizes yet,
|
||||
// reports zero, and refusing to delete on that would strand every
|
||||
// encode against such a cluster in the hybrid state this check exists
|
||||
// to avoid.
|
||||
{
|
||||
name: "unreported sizes are skipped, not read as a disagreement",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": sizedShards(map[int]int64{0: 1048576, 1: 0}),
|
||||
"server2:8080": sizedShards(map[int]int64{2: 0}),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "nothing reported at all verifies vacuously",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": sizedShards(map[int]int64{0: 0, 1: 0}),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no holders is not a size problem",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{},
|
||||
},
|
||||
{
|
||||
name: "a nil inventory is skipped rather than panicking",
|
||||
byNode: map[pb.ServerAddress]*erasure_coding.ShardsInfo{
|
||||
"server1:8080": nil,
|
||||
"server2:8080": sizedShards(map[int]int64{0: 1048576}),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := requireUniformShardSizes(needle.VolumeId(7), tt.byNode)
|
||||
if !tt.wantErr {
|
||||
if err != nil {
|
||||
t.Fatalf("want the encode to proceed, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("want the deletion held back, got no error")
|
||||
}
|
||||
for _, want := range tt.errContains {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("error %q does not mention %q", err, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ecShardReport builds one heartbeat entry: a generation stamp and the shards
|
||||
// that generation put on this node, all of one size.
|
||||
func ecShardReport(vid uint32, encodeTsNs int64, size int64, ids ...int) *master_pb.VolumeEcShardInformationMessage {
|
||||
si := erasure_coding.NewShardsInfo()
|
||||
for _, id := range ids {
|
||||
si.Set(erasure_coding.NewShardInfo(erasure_coding.ShardId(id), erasure_coding.ShardSize(size)))
|
||||
}
|
||||
return &master_pb.VolumeEcShardInformationMessage{
|
||||
Id: vid,
|
||||
Collection: "ectest",
|
||||
EcIndexBits: si.Bitmap(),
|
||||
ShardSizes: si.SizesInt64(),
|
||||
EncodeTsNs: encodeTsNs,
|
||||
}
|
||||
}
|
||||
|
||||
func topologyWith(reports map[string][]*master_pb.VolumeEcShardInformationMessage) *master_pb.TopologyInfo {
|
||||
var nodes []*master_pb.DataNodeInfo
|
||||
for addr, shards := range reports {
|
||||
nodes = append(nodes, &master_pb.DataNodeInfo{
|
||||
Id: addr,
|
||||
DiskInfos: map[string]*master_pb.DiskInfo{
|
||||
"hdd": {EcShardInfos: shards},
|
||||
},
|
||||
})
|
||||
}
|
||||
return &master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: nodes}},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
// A re-encode can change the ratio, so an older generation's shards are a
|
||||
// different length by nature. Recoverability already judges only the newest
|
||||
// generation; if the size check did not, an orphaned older encode -- one the
|
||||
// pre-encode sweep could not reach, but the master still hears about -- would
|
||||
// disagree on size at every retry and strand the volume beside its shards for
|
||||
// good.
|
||||
func TestShardSizeCheckIgnoresOlderEncodeGenerations(t *testing.T) {
|
||||
const vid = 9
|
||||
|
||||
topo := topologyWith(map[string][]*master_pb.VolumeEcShardInformationMessage{
|
||||
// the current encode: one length, spread over two nodes
|
||||
"server1:8080": {ecShardReport(vid, 2000, 1048576, 0, 1, 2)},
|
||||
"server2:8080": {ecShardReport(vid, 2000, 1048576, 3, 4, 5)},
|
||||
// an orphan from an earlier encode, at a different length
|
||||
"server3:8080": {ecShardReport(vid, 1000, 524288, 0, 1)},
|
||||
})
|
||||
|
||||
byNode := collectNewestGenerationShardsInfo(topo, needle.VolumeId(vid))
|
||||
if _, stale := byNode[pb.ServerAddress("server3:8080")]; stale {
|
||||
t.Error("the older generation's holder must not be collected")
|
||||
}
|
||||
if err := requireUniformShardSizes(needle.VolumeId(vid), byNode); err != nil {
|
||||
t.Fatalf("a healthy current generation must not be vetoed by an orphan: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Fencing to the newest generation must not blind the check: a short shard
|
||||
// inside that generation is exactly what it exists to catch.
|
||||
func TestShardSizeCheckStillCatchesShortShardInNewestGeneration(t *testing.T) {
|
||||
const vid = 9
|
||||
|
||||
topo := topologyWith(map[string][]*master_pb.VolumeEcShardInformationMessage{
|
||||
"server1:8080": {ecShardReport(vid, 2000, 1048576, 0, 1)},
|
||||
"server2:8080": {ecShardReport(vid, 2000, 4096, 2)},
|
||||
"server3:8080": {ecShardReport(vid, 1000, 524288, 0)},
|
||||
})
|
||||
|
||||
err := requireUniformShardSizes(needle.VolumeId(vid), collectNewestGenerationShardsInfo(topo, needle.VolumeId(vid)))
|
||||
if err == nil {
|
||||
t.Fatal("a truncated shard in the newest generation must hold the deletion back")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "server2:8080.2") {
|
||||
t.Errorf("error %q does not name the short shard", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Volumes encoded before generation stamping report zero, which is a single
|
||||
// legacy generation rather than an orphan to drop.
|
||||
func TestShardSizeCheckHandlesUnstampedGenerations(t *testing.T) {
|
||||
const vid = 9
|
||||
|
||||
topo := topologyWith(map[string][]*master_pb.VolumeEcShardInformationMessage{
|
||||
"server1:8080": {ecShardReport(vid, 0, 1048576, 0, 1)},
|
||||
"server2:8080": {ecShardReport(vid, 0, 4096, 2)},
|
||||
})
|
||||
|
||||
byNode := collectNewestGenerationShardsInfo(topo, needle.VolumeId(vid))
|
||||
if len(byNode) != 2 {
|
||||
t.Fatalf("unstamped shards form one generation, got %d holder(s)", len(byNode))
|
||||
}
|
||||
if err := requireUniformShardSizes(needle.VolumeId(vid), byNode); err == nil {
|
||||
t.Error("a truncated legacy shard must still hold the deletion back")
|
||||
}
|
||||
}
|
||||
@@ -1,520 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Bounded-exhaustive model check of the EC volume lifecycle.
|
||||
//
|
||||
// The randomized chaos harness samples the state space; this test enumerates
|
||||
// it. The lifecycle of one volume is modeled as a state machine whose
|
||||
// transitions mirror, step by step, the real pipelines in this package, and
|
||||
// the checker explores EVERY schedule within the bound: every operation, a
|
||||
// crash (kill, no cleanup) at every step boundary, an error return (which
|
||||
// runs the rollback, itself crashable at every step) at every step boundary,
|
||||
// a volume-server restart (running the startup reconciliation rules) in every
|
||||
// quiescent state, and every recovery re-run from every crashed state.
|
||||
//
|
||||
// Two safety invariants are asserted in every reachable state, including
|
||||
// mid-operation and post-crash:
|
||||
//
|
||||
// I1 durability: the volume's data is always recoverable — the regular
|
||||
// replica exists, or some single generation holds at least dataShards
|
||||
// shard files.
|
||||
// I2 single serving generation: at most one generation is ever mounted.
|
||||
// I3 single generation on disk: the sweep-before-generate discipline keeps
|
||||
// at most one generation's files on disk through every schedule. (An
|
||||
// externally planted file breaks this by construction; that path is the
|
||||
// chaos harness's, not the orchestration's.)
|
||||
//
|
||||
// And one convergence property: from every quiescent state, the prescribed
|
||||
// recovery — re-running the interrupted operation, per the restart-not-resume
|
||||
// model — terminates in a clean state (a writable regular volume with no EC
|
||||
// leftovers, or exactly one complete mounted generation with no source
|
||||
// replica and no surplus copies).
|
||||
//
|
||||
// The model's fidelity contract: each step below names the code it stands
|
||||
// for. When the pipeline order changes, this file must change with it.
|
||||
//
|
||||
// encode = ProcessEcEncodeBatch/doEcEncode: markReadonly
|
||||
// (markVolumeReplicaWritable false) → sweep
|
||||
// (clearPreexistingEcShards, removes every prior generation) →
|
||||
// generate (VolumeEcShardsGenerate, a new generation's files) →
|
||||
// mount (VolumeEcShardsMount, registers it) → balance
|
||||
// (EcBalance; a crash mid-move leaves a surplus copy, never a
|
||||
// loss, because moves copy before they delete) → verify
|
||||
// (verifyEcShardsBeforeDelete) → deleteSource
|
||||
// (doDeleteVolumesWithLocations, the commit point).
|
||||
// rollback = rollbackFailedEcEncode, run only on an error return before
|
||||
// the commit: rollbackSweep (clearPreexistingEcShards again) →
|
||||
// restoreWritable. A kill runs nothing.
|
||||
// decode = DoEcDecode: collect (collectEcShards) → generateVolume
|
||||
// (VolumeEcShardsToVolume) → mountVolume (VolumeMount) →
|
||||
// verifyDecoded (verifyDecodedVolumeBeforeDelete) → three
|
||||
// per-location shard deletions (unmountAndDeleteEcShards).
|
||||
// Forward-only: no rollback.
|
||||
// reconcile = the volume server startup rules (weed/storage
|
||||
// disk_location_ec.go): with the source .dat present, a
|
||||
// partial generation fails validation and is deleted
|
||||
// (handleFoundEcxFile/validateEcVolume); surviving shard files
|
||||
// with their sidecars re-register (the #9212 adoption).
|
||||
// dedup = the balance's dedup phase removing surplus copies
|
||||
// (ecbalancer "dedup" moves + verifyEcShardOnKeepNode).
|
||||
//
|
||||
// Deliberately outside the model: multi-replica sources (the pipeline syncs
|
||||
// and reduces to one best replica before encoding), per-node shard placement
|
||||
// (I1/I2 do not depend on it), and externally planted files (the chaos
|
||||
// harness covers adoption of foreign shards).
|
||||
|
||||
const (
|
||||
modelDataShards = 10
|
||||
modelTotalShards = 14
|
||||
)
|
||||
|
||||
type modelGen struct {
|
||||
files int // shard files on disk, whether or not registered
|
||||
mounted bool // registered and serving
|
||||
surplus int // duplicate copies left by an interrupted balance move
|
||||
}
|
||||
|
||||
type modelState struct {
|
||||
replica bool
|
||||
replicaReadonly bool
|
||||
gens []modelGen // oldest first; a new encode appends
|
||||
}
|
||||
|
||||
func (s modelState) clone() modelState {
|
||||
c := s
|
||||
c.gens = append([]modelGen(nil), s.gens...)
|
||||
return c
|
||||
}
|
||||
|
||||
func (s modelState) key() string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "r%v,ro%v", s.replica, s.replicaReadonly)
|
||||
for _, g := range s.gens {
|
||||
fmt.Fprintf(&b, "|f%d,m%v,s%d", g.files, g.mounted, g.surplus)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// dropEmptyGens removes generations with no files left.
|
||||
func (s *modelState) dropEmptyGens() {
|
||||
kept := s.gens[:0]
|
||||
for _, g := range s.gens {
|
||||
if g.files > 0 {
|
||||
kept = append(kept, g)
|
||||
}
|
||||
}
|
||||
s.gens = kept
|
||||
}
|
||||
|
||||
// ── invariants ──────────────────────────────────────────────────────────────
|
||||
|
||||
func checkInvariants(s modelState) error {
|
||||
// I1: durability.
|
||||
recoverable := s.replica
|
||||
for _, g := range s.gens {
|
||||
if g.files >= modelDataShards {
|
||||
recoverable = true
|
||||
}
|
||||
}
|
||||
if !recoverable {
|
||||
return fmt.Errorf("I1 violated: no replica and no generation with >= %d shard files", modelDataShards)
|
||||
}
|
||||
// I2: at most one mounted generation.
|
||||
mounted := 0
|
||||
for _, g := range s.gens {
|
||||
if g.mounted {
|
||||
mounted++
|
||||
}
|
||||
}
|
||||
if mounted > 1 {
|
||||
return fmt.Errorf("I2 violated: %d generations mounted", mounted)
|
||||
}
|
||||
// I3: at most one generation's files on disk.
|
||||
withFiles := 0
|
||||
for _, g := range s.gens {
|
||||
if g.files > 0 {
|
||||
withFiles++
|
||||
}
|
||||
}
|
||||
if withFiles > 1 {
|
||||
return fmt.Errorf("I3 violated: %d generations have files on disk", withFiles)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isCleanEc(s modelState) bool {
|
||||
if s.replica || len(s.gens) != 1 {
|
||||
return false
|
||||
}
|
||||
g := s.gens[0]
|
||||
return g.files == modelTotalShards && g.mounted && g.surplus == 0
|
||||
}
|
||||
|
||||
// ── operations as step lists ────────────────────────────────────────────────
|
||||
|
||||
// A step mutates the state; ok=false means the step's precondition failed
|
||||
// (the real command would return an error at this point).
|
||||
type modelStep struct {
|
||||
name string
|
||||
apply func(*modelState) (ok bool)
|
||||
}
|
||||
|
||||
func encodeSteps() []modelStep {
|
||||
return []modelStep{
|
||||
{"markReadonly", func(s *modelState) bool {
|
||||
if !s.replica {
|
||||
return false
|
||||
}
|
||||
s.replicaReadonly = true
|
||||
return true
|
||||
}},
|
||||
// The orphan sweep tears down per (node, volume); a crash can land
|
||||
// between nodes, leaving a partially removed generation.
|
||||
{"sweepLoc0", func(s *modelState) bool { sweepLocation(s, 0); return true }},
|
||||
{"sweepLoc1", func(s *modelState) bool { sweepLocation(s, 1); return true }},
|
||||
{"sweepLoc2", func(s *modelState) bool { sweepLocation(s, 2); return true }},
|
||||
// Generation writes the shard files on the generation host; a crash
|
||||
// mid-write leaves a partial, unregistered set beside the .dat, which
|
||||
// the startup validation removes and the next sweep also covers.
|
||||
{"generateHalf", func(s *modelState) bool {
|
||||
if !s.replica {
|
||||
return false
|
||||
}
|
||||
s.gens = append(s.gens, modelGen{files: modelTotalShards / 2})
|
||||
return true
|
||||
}},
|
||||
{"generateRest", func(s *modelState) bool {
|
||||
s.gens[len(s.gens)-1].files = modelTotalShards
|
||||
return true
|
||||
}},
|
||||
{"mount", func(s *modelState) bool {
|
||||
s.gens[len(s.gens)-1].mounted = true
|
||||
return true
|
||||
}},
|
||||
// balance: a completed run changes placement only. Its crash variant
|
||||
// is modeled by crashing between "balanceCopy" and "balanceDelete":
|
||||
// the copy landed, the source deletion did not.
|
||||
{"balanceCopy", func(s *modelState) bool {
|
||||
s.gens[len(s.gens)-1].surplus++
|
||||
return true
|
||||
}},
|
||||
{"balanceDelete", func(s *modelState) bool {
|
||||
s.gens[len(s.gens)-1].surplus--
|
||||
return true
|
||||
}},
|
||||
{"verify", func(s *modelState) bool {
|
||||
return s.gens[len(s.gens)-1].files >= modelDataShards
|
||||
}},
|
||||
{"deleteSource", func(s *modelState) bool {
|
||||
s.replica = false
|
||||
s.replicaReadonly = false
|
||||
return true
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
// encodeCommitIndex is the index of deleteSource: an error return at or after
|
||||
// it must not roll back (the shards are the only copy once it runs).
|
||||
func encodeCommitIndex() int { return len(encodeSteps()) - 1 }
|
||||
|
||||
// sweepLocation removes one location's share of every generation's files —
|
||||
// the per-(node, volume) teardown of clearPreexistingEcShards. The last
|
||||
// location clears the remainder, sidecars included.
|
||||
func sweepLocation(s *modelState, loc int) {
|
||||
for gi := range s.gens {
|
||||
g := &s.gens[gi]
|
||||
chunk := modelTotalShards / 3
|
||||
if loc == 2 {
|
||||
g.files, g.mounted, g.surplus = 0, false, 0
|
||||
} else if g.files > chunk {
|
||||
g.files -= chunk
|
||||
} else {
|
||||
g.files = 0
|
||||
}
|
||||
}
|
||||
s.dropEmptyGens()
|
||||
}
|
||||
|
||||
func rollbackSteps() []modelStep {
|
||||
return []modelStep{
|
||||
{"rollbackSweep", func(s *modelState) bool {
|
||||
s.gens = nil
|
||||
return true
|
||||
}},
|
||||
{"restoreWritable", func(s *modelState) bool {
|
||||
if s.replica {
|
||||
s.replicaReadonly = false
|
||||
}
|
||||
return true
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func decodeSteps() []modelStep {
|
||||
steps := []modelStep{
|
||||
{"collect", func(s *modelState) bool {
|
||||
for _, g := range s.gens {
|
||||
if g.mounted && g.files >= modelDataShards {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}},
|
||||
{"generateVolume", func(s *modelState) bool {
|
||||
s.replica = true
|
||||
return true
|
||||
}},
|
||||
{"mountVolume", func(s *modelState) bool { return true }},
|
||||
{"verifyDecoded", func(s *modelState) bool { return s.replica }},
|
||||
}
|
||||
// Shard deletion is per holder location; three locations model a spread
|
||||
// volume, so a crash can land between any two of them.
|
||||
for i := 0; i < 3; i++ {
|
||||
i := i
|
||||
steps = append(steps, modelStep{fmt.Sprintf("deleteShardsLoc%d", i), func(s *modelState) bool {
|
||||
for gi := range s.gens {
|
||||
g := &s.gens[gi]
|
||||
if !g.mounted && g.files == 0 {
|
||||
continue
|
||||
}
|
||||
// Each location holds roughly a third of the shards; the last
|
||||
// pass clears the remainder and the generation with it.
|
||||
chunk := modelTotalShards / 3
|
||||
if i == 2 {
|
||||
g.files, g.surplus, g.mounted = 0, 0, false
|
||||
} else if g.files > chunk {
|
||||
g.files -= chunk
|
||||
}
|
||||
}
|
||||
s.dropEmptyGens()
|
||||
return true
|
||||
}})
|
||||
}
|
||||
return steps
|
||||
}
|
||||
|
||||
// reconcile applies the volume-server startup rules after a crash-restart.
|
||||
func reconcile(s *modelState) {
|
||||
for gi := range s.gens {
|
||||
g := &s.gens[gi]
|
||||
if s.replica && g.files < modelTotalShards {
|
||||
// .dat present and the local generation is partial: validation
|
||||
// fails and the files are removed (disk_location_ec.go).
|
||||
g.files, g.mounted, g.surplus = 0, false, 0
|
||||
continue
|
||||
}
|
||||
if g.files > 0 {
|
||||
// Surviving files re-register through their sidecars (#9212).
|
||||
g.mounted = true
|
||||
}
|
||||
}
|
||||
s.dropEmptyGens()
|
||||
}
|
||||
|
||||
// dedupSurplus is the balance dedup phase.
|
||||
func dedupSurplus(s *modelState) {
|
||||
for gi := range s.gens {
|
||||
s.gens[gi].surplus = 0
|
||||
}
|
||||
}
|
||||
|
||||
// ── recovery convergence ────────────────────────────────────────────────────
|
||||
|
||||
// runToCompletion applies steps without interruption; false when a
|
||||
// precondition fails (the real re-run would error out).
|
||||
func runToCompletion(s *modelState, steps []modelStep) bool {
|
||||
for _, st := range steps {
|
||||
if !st.apply(s) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// recover applies the prescribed recovery for a quiescent state and reports
|
||||
// whether it converges to a clean state. Per the restart-not-resume model:
|
||||
// a surviving replica means the encode restarts from scratch; no replica
|
||||
// means the encode had committed and only surplus cleanup can remain; a
|
||||
// mounted generation beside a replica can also be decoded away.
|
||||
func recoverModel(s modelState) (modelState, error) {
|
||||
// A crash-restart happens before any operator action; its reconciliation
|
||||
// must itself keep the invariants.
|
||||
reconcile(&s)
|
||||
if err := checkInvariants(s); err != nil {
|
||||
return s, fmt.Errorf("after reconcile: %w", err)
|
||||
}
|
||||
|
||||
if !s.replica {
|
||||
// The encode committed: shards are the volume. Dedup cleans surplus.
|
||||
dedupSurplus(&s)
|
||||
if !isCleanEc(s) {
|
||||
return s, fmt.Errorf("no replica and not clean EC")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Replica survives: re-run the encode from scratch (sweep + regenerate),
|
||||
// then the volume is EC; this is the restart path every interrupted
|
||||
// encode and every leftover-orphan state takes.
|
||||
if !runToCompletion(&s, encodeSteps()) {
|
||||
return s, fmt.Errorf("recovery encode did not complete")
|
||||
}
|
||||
dedupSurplus(&s)
|
||||
if err := checkInvariants(s); err != nil {
|
||||
return s, fmt.Errorf("after recovery encode: %w", err)
|
||||
}
|
||||
if !isCleanEc(s) {
|
||||
return s, fmt.Errorf("recovery encode did not converge to clean EC")
|
||||
}
|
||||
// And a decode must be able to bring it back to a regular volume.
|
||||
if !runToCompletion(&s, decodeSteps()) {
|
||||
return s, fmt.Errorf("decode after recovery did not complete")
|
||||
}
|
||||
if err := checkInvariants(s); err != nil {
|
||||
return s, fmt.Errorf("after decode: %w", err)
|
||||
}
|
||||
if !s.replica || len(s.gens) != 0 {
|
||||
return s, fmt.Errorf("decode after recovery did not converge to a bare regular volume")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// ── exhaustive exploration ──────────────────────────────────────────────────
|
||||
|
||||
type trace []string
|
||||
|
||||
// explore runs every schedule of one operation from state s: after every
|
||||
// step, the schedule may continue, crash (kill: stop, nothing else runs), or
|
||||
// error out (rollback runs, itself crashable at every step). Every resulting
|
||||
// quiescent state is handed to onQuiescent together with the trace that
|
||||
// produced it.
|
||||
func exploreOp(t *testing.T, s modelState, opName string, steps []modelStep, commitIndex int, withRollback bool, tr trace, onQuiescent func(modelState, trace)) {
|
||||
t.Helper()
|
||||
// Crash before the first step is the same as never starting.
|
||||
for prefix := 1; prefix <= len(steps); prefix++ {
|
||||
run := s.clone()
|
||||
ok := true
|
||||
for i := 0; i < prefix; i++ {
|
||||
if !steps[i].apply(&run) {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
if err := checkInvariants(run); err != nil {
|
||||
t.Fatalf("%s after %s: %v\ntrace: %v", opName, steps[i].name, err, append(tr, opName+"/"+steps[i].name))
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
continue // precondition stopped the op; same as an early error
|
||||
}
|
||||
stepTrace := append(append(trace{}, tr...), fmt.Sprintf("%s..%s", opName, steps[prefix-1].name))
|
||||
|
||||
// Kill here: nothing else runs.
|
||||
onQuiescent(run.clone(), append(append(trace{}, stepTrace...), "KILL"))
|
||||
|
||||
// Error return here: the rollback runs, unless the op has committed;
|
||||
// the rollback itself can be killed at each of its step boundaries.
|
||||
if withRollback && prefix <= commitIndex {
|
||||
rb := rollbackSteps()
|
||||
for rbPrefix := 0; rbPrefix <= len(rb); rbPrefix++ {
|
||||
rbRun := run.clone()
|
||||
for i := 0; i < rbPrefix; i++ {
|
||||
rb[i].apply(&rbRun)
|
||||
if err := checkInvariants(rbRun); err != nil {
|
||||
t.Fatalf("%s rollback after %s: %v\ntrace: %v", opName, rb[i].name, err, stepTrace)
|
||||
}
|
||||
}
|
||||
suffix := "FAIL+rollback-killed"
|
||||
if rbPrefix == len(rb) {
|
||||
suffix = "FAIL+rollback-complete"
|
||||
}
|
||||
onQuiescent(rbRun.clone(), append(append(trace{}, stepTrace...), fmt.Sprintf("%s@%d", suffix, rbPrefix)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestECLifecycleModelExhaustive enumerates every crash and failure schedule
|
||||
// of encode and decode up to two chained interrupted operations, checks the
|
||||
// safety invariants in every intermediate state, and requires the prescribed
|
||||
// recovery to converge from every quiescent state.
|
||||
func TestECLifecycleModelExhaustive(t *testing.T) {
|
||||
start := modelState{replica: true}
|
||||
|
||||
visited := map[string]trace{}
|
||||
quiescent := 0
|
||||
schedules := 0
|
||||
var enqueue func(s modelState, depth int, tr trace)
|
||||
|
||||
checkRecovery := func(s modelState, tr trace) {
|
||||
schedules++
|
||||
if _, seen := visited["Q"+s.key()]; seen {
|
||||
return
|
||||
}
|
||||
visited["Q"+s.key()] = tr
|
||||
quiescent++
|
||||
if _, err := recoverModel(s.clone()); err != nil {
|
||||
t.Fatalf("recovery does not converge: %v\nstate: %s\ntrace: %v", err, s.key(), tr)
|
||||
}
|
||||
}
|
||||
|
||||
enqueue = func(s modelState, depth int, tr trace) {
|
||||
checkRecovery(s, tr)
|
||||
if depth == 0 {
|
||||
return
|
||||
}
|
||||
// A crash-restart may happen in any quiescent state before the next
|
||||
// operation; explore both with and without it.
|
||||
restarted := s.clone()
|
||||
reconcile(&restarted)
|
||||
if err := checkInvariants(restarted); err != nil {
|
||||
t.Fatalf("reconcile violated invariants: %v\nstate: %s\ntrace: %v", err, s.key(), tr)
|
||||
}
|
||||
for _, variant := range []struct {
|
||||
st modelState
|
||||
tag string
|
||||
}{{s, ""}, {restarted, "+restart"}} {
|
||||
st, tag := variant.st, variant.tag
|
||||
if st.replica {
|
||||
exploreOp(t, st, "encode"+tag, encodeSteps(), encodeCommitIndex(), true, tr, func(q modelState, qtr trace) {
|
||||
enqueue(q, depth-1, qtr)
|
||||
})
|
||||
}
|
||||
canDecode := false
|
||||
for _, g := range st.gens {
|
||||
if g.mounted && g.files >= modelDataShards {
|
||||
canDecode = true
|
||||
}
|
||||
}
|
||||
if canDecode {
|
||||
exploreOp(t, st, "decode"+tag, decodeSteps(), len(decodeSteps()), false, tr, func(q modelState, qtr trace) {
|
||||
enqueue(q, depth-1, qtr)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Depth 2: an interrupted operation followed by another interrupted
|
||||
// operation, recovery checked at every quiescent point in between and
|
||||
// after. Deeper chains only revisit already-explored states (the state
|
||||
// space is finite and memoized), which the visited count makes apparent.
|
||||
enqueue(start, 2, trace{"start"})
|
||||
|
||||
// Not spec constants — collapse guards: if a refactor of the model or the
|
||||
// explorer accidentally prunes schedules, these counts crater and this
|
||||
// catches it. Update deliberately when the model changes fidelity.
|
||||
if quiescent < 15 || schedules < 500 {
|
||||
t.Fatalf("suspiciously small exploration: %d distinct quiescent states from %d schedules", quiescent, schedules)
|
||||
}
|
||||
keys := make([]string, 0, len(visited))
|
||||
for k := range visited {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
t.Logf("explored %d schedules reaching %d distinct quiescent states, all recoverable", schedules, quiescent)
|
||||
}
|
||||
@@ -1,435 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
type ecRebuilder struct {
|
||||
env *Env
|
||||
ecNodes []*EcNode
|
||||
writer io.Writer
|
||||
applyChanges bool
|
||||
collections []string
|
||||
volumeIds []needle.VolumeId
|
||||
diskType types.DiskType
|
||||
|
||||
ewg *util.ErrorWaitGroup
|
||||
ecNodesMu sync.Mutex
|
||||
}
|
||||
|
||||
// RebuildEcVolumes finds and rebuilds missing EC shards for the given
|
||||
// collections. Before rebuilding it asks volume servers to recover any shards
|
||||
// left unmounted by a missing .ecx index; such shards are invisible to the
|
||||
// master, so recovering them first avoids regenerating data that is actually
|
||||
// present. volumeIds, when non-empty, restricts the rebuild to those volumes.
|
||||
func RebuildEcVolumes(env *Env, ecNodes []*EcNode, writer io.Writer, collections []string, volumeIds []needle.VolumeId, diskType types.DiskType, maxParallelization int, applyChanges bool) error {
|
||||
erb := &ecRebuilder{
|
||||
env: env,
|
||||
ecNodes: ecNodes,
|
||||
writer: writer,
|
||||
applyChanges: applyChanges,
|
||||
collections: collections,
|
||||
volumeIds: volumeIds,
|
||||
diskType: diskType,
|
||||
|
||||
ewg: util.NewErrorWaitGroup(maxParallelization),
|
||||
}
|
||||
|
||||
// Recover shards left unmounted by a missing .ecx index before planning: such
|
||||
// shards never register with the master, so the rebuild below would treat the
|
||||
// volume as short or unrepairable even though its data is intact (issue #10104).
|
||||
erb.recoverMissingIndexes()
|
||||
|
||||
fmt.Printf("rebuildEcVolumes for %d collection(s)\n", len(collections))
|
||||
for _, c := range collections {
|
||||
erb.rebuildEcVolumes(c)
|
||||
}
|
||||
|
||||
return erb.ewg.Wait()
|
||||
}
|
||||
|
||||
func (erb *ecRebuilder) write(format string, a ...any) {
|
||||
fmt.Fprintf(erb.writer, format, a...)
|
||||
}
|
||||
|
||||
func (erb *ecRebuilder) isLocked() bool {
|
||||
return erb.env.isLocked()
|
||||
}
|
||||
|
||||
// matchesVolumeId verifies whether the rebuilder is targeted at a given volume ID.
|
||||
func (erb *ecRebuilder) matchesVolumeId(vid needle.VolumeId) bool {
|
||||
if len(erb.volumeIds) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
return slices.Contains(erb.volumeIds, vid)
|
||||
}
|
||||
|
||||
// countLocalShards returns the number of shards already present locally on the node for the given volume.
|
||||
// Unions across all of the node's disks, like prepareDataToRecover, so slot
|
||||
// accounting matches what the rebuild will actually treat as local.
|
||||
func (erb *ecRebuilder) countLocalShards(node *EcNode, collection string, volumeId needle.VolumeId) int {
|
||||
localShardsInfo := erasure_coding.NewShardsInfo()
|
||||
for _, diskInfo := range node.Info.DiskInfos {
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
if ecShardInfo.Collection == collection && needle.VolumeId(ecShardInfo.Id) == volumeId {
|
||||
localShardsInfo.Add(erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(ecShardInfo))
|
||||
}
|
||||
}
|
||||
}
|
||||
return localShardsInfo.Count()
|
||||
}
|
||||
|
||||
// selectAndReserveRebuilder atomically selects a rebuilder node with sufficient free slots
|
||||
// and reserves slots only for the non-local shards that need to be copied/generated.
|
||||
func (erb *ecRebuilder) selectAndReserveRebuilder(collection string, volumeId needle.VolumeId) (*EcNode, int, error) {
|
||||
erb.ecNodesMu.Lock()
|
||||
defer erb.ecNodesMu.Unlock()
|
||||
|
||||
if len(erb.ecNodes) == 0 {
|
||||
return nil, 0, fmt.Errorf("no ec nodes available")
|
||||
}
|
||||
|
||||
// Find the node with the most free slots, considering local shards
|
||||
var bestNode *EcNode
|
||||
var bestSlotsNeeded int
|
||||
var maxAvailableSlots int
|
||||
var minSlotsNeeded int = erasure_coding.TotalShardsCount // Start with maximum possible
|
||||
for _, node := range erb.ecNodes {
|
||||
localShards := erb.countLocalShards(node, collection, volumeId)
|
||||
slotsNeeded := erasure_coding.TotalShardsCount - localShards
|
||||
if slotsNeeded < 0 {
|
||||
slotsNeeded = 0
|
||||
}
|
||||
|
||||
if node.FreeEcSlot > maxAvailableSlots {
|
||||
maxAvailableSlots = node.FreeEcSlot
|
||||
}
|
||||
|
||||
if slotsNeeded < minSlotsNeeded {
|
||||
minSlotsNeeded = slotsNeeded
|
||||
}
|
||||
|
||||
if node.FreeEcSlot >= slotsNeeded {
|
||||
if bestNode == nil || node.FreeEcSlot > bestNode.FreeEcSlot {
|
||||
bestNode = node
|
||||
bestSlotsNeeded = slotsNeeded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if bestNode == nil {
|
||||
return nil, 0, fmt.Errorf("no node has sufficient free slots for volume %d (need at least %d slots, max available: %d)",
|
||||
volumeId, minSlotsNeeded, maxAvailableSlots)
|
||||
}
|
||||
|
||||
// Reserve slots only for non-local shards
|
||||
bestNode.FreeEcSlot -= bestSlotsNeeded
|
||||
|
||||
return bestNode, bestSlotsNeeded, nil
|
||||
}
|
||||
|
||||
// releaseRebuilder releases the reserved slots back to the rebuilder node.
|
||||
func (erb *ecRebuilder) releaseRebuilder(node *EcNode, slotsToRelease int) {
|
||||
erb.ecNodesMu.Lock()
|
||||
defer erb.ecNodesMu.Unlock()
|
||||
|
||||
// Release slots by incrementing the free slot count
|
||||
node.FreeEcSlot += slotsToRelease
|
||||
}
|
||||
|
||||
func (erb *ecRebuilder) rebuildEcVolumes(collection string) {
|
||||
fmt.Printf("rebuildEcVolumes for %q\n", collection)
|
||||
|
||||
// collect vid => each shard locations, similar to ecShardMap in topology.go
|
||||
ecShardMap := make(EcShardMap)
|
||||
erb.ecNodesMu.Lock()
|
||||
for _, ecNode := range erb.ecNodes {
|
||||
ecShardMap.registerEcNode(ecNode, collection)
|
||||
}
|
||||
erb.ecNodesMu.Unlock()
|
||||
|
||||
for vid, locations := range ecShardMap {
|
||||
if !erb.matchesVolumeId(vid) {
|
||||
continue
|
||||
}
|
||||
shardCount := locations.shardCount()
|
||||
if shardCount == erasure_coding.TotalShardsCount {
|
||||
continue
|
||||
}
|
||||
if shardCount < erasure_coding.DataShardsCount {
|
||||
erb.write("ec volume %d is unrepairable with %d shards (need %d), skipping\n", vid, shardCount, erasure_coding.DataShardsCount)
|
||||
continue
|
||||
}
|
||||
|
||||
// Capture variables for closure
|
||||
vid := vid
|
||||
locations := locations
|
||||
|
||||
erb.ewg.Add(func() error {
|
||||
// Select rebuilder and reserve slots atomically per volume
|
||||
rebuilder, slotsToReserve, err := erb.selectAndReserveRebuilder(collection, vid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to select rebuilder for volume %d: %v", vid, err)
|
||||
}
|
||||
defer erb.releaseRebuilder(rebuilder, slotsToReserve)
|
||||
|
||||
return erb.rebuildOneEcVolume(collection, vid, locations, rebuilder)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// recoverMissingIndexes asks every ec node to fetch a missing .ecx index from a
|
||||
// peer and mount the on-disk shards it could not load on its own. Shards
|
||||
// orphaned this way (index only on another server) are absent from the master
|
||||
// topology, so without this pass ec.rebuild would regenerate or give up on
|
||||
// shards whose data is actually present — and a volume whose every holder lacks
|
||||
// the index would not appear in the topology at all. Each node therefore
|
||||
// recovers all of its on-disk orphans (volume_id 0); an explicit -volumeIds
|
||||
// list narrows that to the requested volumes. On apply it refreshes the topology
|
||||
// so the rebuild planning sees the recovered shards (issue #10104).
|
||||
func (erb *ecRebuilder) recoverMissingIndexes() {
|
||||
erb.ecNodesMu.Lock()
|
||||
nodes := append([]*EcNode(nil), erb.ecNodes...)
|
||||
erb.ecNodesMu.Unlock()
|
||||
if len(nodes) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// volume_id 0 means "recover every orphan on the node"; a -volumeIds list
|
||||
// narrows recovery to those ids (each scanned across collections server-side).
|
||||
vids := erb.volumeIds
|
||||
if len(vids) == 0 {
|
||||
vids = []needle.VolumeId{0}
|
||||
}
|
||||
|
||||
if !erb.applyChanges {
|
||||
erb.write("would ask %d ec node(s) to recover EC shards left unmounted by a missing .ecx index\n", len(nodes))
|
||||
return
|
||||
}
|
||||
|
||||
for _, node := range nodes {
|
||||
for _, vid := range vids {
|
||||
err := operation.WithVolumeServerClient(false, pb.NewServerAddressFromDataNode(node.Info), erb.env.GrpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
|
||||
_, mountErr := client.VolumeEcShardsMount(context.Background(), &volume_server_pb.VolumeEcShardsMountRequest{
|
||||
VolumeId: uint32(vid),
|
||||
RecoverMissingIndex: true,
|
||||
})
|
||||
return mountErr
|
||||
})
|
||||
if err != nil {
|
||||
erb.write("%s recover missing index (volume %d): %v\n", node.Info.Id, vid, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh topology so the rebuild planning sees shards the recovery registered.
|
||||
refreshed, _, err := CollectEcNodes(erb.env, erb.diskType)
|
||||
if err != nil {
|
||||
erb.write("failed to refresh ec nodes after index recovery: %v\n", err)
|
||||
return
|
||||
}
|
||||
erb.ecNodesMu.Lock()
|
||||
erb.ecNodes = refreshed
|
||||
erb.ecNodesMu.Unlock()
|
||||
}
|
||||
|
||||
func (erb *ecRebuilder) rebuildOneEcVolume(collection string, volumeId needle.VolumeId, locations EcShardLocations, rebuilder *EcNode) error {
|
||||
if !erb.isLocked() {
|
||||
return fmt.Errorf("lock is lost")
|
||||
}
|
||||
|
||||
fmt.Printf("rebuildOneEcVolume %s %d\n", collection, volumeId)
|
||||
|
||||
// collect shard files to rebuilder local disk
|
||||
var generatedShardIds []erasure_coding.ShardId
|
||||
copiedShardIds, _, err := erb.prepareDataToRecover(rebuilder, collection, volumeId, locations)
|
||||
defer func() {
|
||||
// Clean up the working copies this run actually made, even when the
|
||||
// recoverability gate failed after some copies already succeeded:
|
||||
// they are temp files on the rebuilder nothing else reclaims. Dry-run
|
||||
// copies nothing (copiedShardIds is empty), so this issues no delete
|
||||
// RPC. Use a local error so a cleanup failure cannot mask the return.
|
||||
if !erb.applyChanges || len(copiedShardIds) == 0 {
|
||||
return
|
||||
}
|
||||
if derr := SourceServerDeleteEcShards(erb.env.GrpcDialOption, collection, volumeId, pb.NewServerAddressFromDataNode(rebuilder.Info), copiedShardIds); derr != nil {
|
||||
erb.write("%s delete copied ec shards %s %d.%v: %v\n", rebuilder.Info.Id, collection, volumeId, copiedShardIds, derr)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !erb.applyChanges {
|
||||
return nil
|
||||
}
|
||||
|
||||
// generate ec shards, and maybe ecx file
|
||||
generatedShardIds, err = erb.generateMissingShards(collection, volumeId, pb.NewServerAddressFromDataNode(rebuilder.Info))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// mount the generated shards
|
||||
err = MountEcShards(erb.env.GrpcDialOption, collection, volumeId, pb.NewServerAddressFromDataNode(rebuilder.Info), generatedShardIds)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// ensure ECNode updates are atomic
|
||||
erb.ecNodesMu.Lock()
|
||||
defer erb.ecNodesMu.Unlock()
|
||||
rebuilder.AddEcVolumeShards(volumeId, collection, generatedShardIds, erb.diskType)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (erb *ecRebuilder) generateMissingShards(collection string, volumeId needle.VolumeId, sourceLocation pb.ServerAddress) (rebuiltShardIds []erasure_coding.ShardId, err error) {
|
||||
|
||||
err = operation.WithVolumeServerClient(false, sourceLocation, erb.env.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
resp, rebuildErr := volumeServerClient.VolumeEcShardsRebuild(context.Background(), &volume_server_pb.VolumeEcShardsRebuildRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Collection: collection,
|
||||
})
|
||||
if rebuildErr == nil {
|
||||
rebuiltShardIds = erasure_coding.Uint32ToShardIds(resp.RebuiltShardIds)
|
||||
}
|
||||
return rebuildErr
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func (erb *ecRebuilder) prepareDataToRecover(rebuilder *EcNode, collection string, volumeId needle.VolumeId, locations EcShardLocations) (copiedShardIds []erasure_coding.ShardId, localShardIds []erasure_coding.ShardId, err error) {
|
||||
|
||||
needEcxFile := true
|
||||
localShardsInfo := erasure_coding.NewShardsInfo()
|
||||
for _, diskInfo := range rebuilder.Info.DiskInfos {
|
||||
for _, ecShardInfo := range diskInfo.EcShardInfos {
|
||||
if ecShardInfo.Collection == collection && needle.VolumeId(ecShardInfo.Id) == volumeId {
|
||||
needEcxFile = false
|
||||
// Union across disks: the rebuilder may hold this volume's
|
||||
// shards on more than one disk. Overwriting per-disk would
|
||||
// make a shard on a non-last disk look remote and get copied
|
||||
// onto itself (O_TRUNC) and then node-wide deleted.
|
||||
localShardsInfo.Add(erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(ecShardInfo))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
targetShardCount := erasure_coding.TotalShardsCount
|
||||
for i := erasure_coding.TotalShardsCount; i < len(locations); i++ {
|
||||
if len(locations[i]) > 0 {
|
||||
targetShardCount = i + 1
|
||||
}
|
||||
}
|
||||
|
||||
// recoverableRemoteShards counts remote shards that can contribute to the
|
||||
// rebuild. Dry-run counts the plan; apply mode counts only successful copies.
|
||||
recoverableRemoteShards := 0
|
||||
for i := 0; i < targetShardCount; i++ {
|
||||
ecNodes := locations[i]
|
||||
shardId := erasure_coding.ShardId(i)
|
||||
if len(ecNodes) == 0 {
|
||||
erb.write("missing shard %d.%d\n", volumeId, shardId)
|
||||
continue
|
||||
}
|
||||
|
||||
if localShardsInfo.Has(shardId) {
|
||||
localShardIds = append(localShardIds, shardId)
|
||||
erb.write("use existing shard %d.%d\n", volumeId, shardId)
|
||||
continue
|
||||
}
|
||||
|
||||
// The rebuilder is itself the only listed holder: never copy a shard
|
||||
// onto itself (the in-place O_TRUNC would destroy it) nor schedule it
|
||||
// for the post-rebuild delete. Treat it as already local.
|
||||
if ecNodes[0].Info.Id == rebuilder.Info.Id {
|
||||
localShardIds = append(localShardIds, shardId)
|
||||
erb.write("use existing shard %d.%d (already on rebuilder)\n", volumeId, shardId)
|
||||
continue
|
||||
}
|
||||
|
||||
if !erb.applyChanges {
|
||||
recoverableRemoteShards++
|
||||
erb.write("would copy %d.%d from %s\n", volumeId, shardId, ecNodes[0].Info.Id)
|
||||
continue
|
||||
}
|
||||
|
||||
copyErr := operation.WithVolumeServerClient(false, pb.NewServerAddressFromDataNode(rebuilder.Info), erb.env.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
_, copyErr := volumeServerClient.VolumeEcShardsCopy(context.Background(), &volume_server_pb.VolumeEcShardsCopyRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Collection: collection,
|
||||
ShardIds: []uint32{uint32(shardId)},
|
||||
CopyEcxFile: needEcxFile,
|
||||
CopyEcjFile: true,
|
||||
CopyVifFile: needEcxFile,
|
||||
SourceDataNode: string(pb.NewServerAddressFromDataNode(ecNodes[0].Info)),
|
||||
})
|
||||
return copyErr
|
||||
})
|
||||
if copyErr != nil {
|
||||
erb.write("%s failed to copy %d.%d from %s: %v\n", rebuilder.Info.Id, volumeId, shardId, ecNodes[0].Info.Id, copyErr)
|
||||
continue
|
||||
}
|
||||
recoverableRemoteShards++
|
||||
if needEcxFile {
|
||||
needEcxFile = false
|
||||
}
|
||||
erb.write("%s copied %d.%d from %s\n", rebuilder.Info.Id, volumeId, shardId, ecNodes[0].Info.Id)
|
||||
// Only shards this run actually copied are temp working files to be
|
||||
// deleted afterward; never a pre-existing local or remote shard.
|
||||
copiedShardIds = append(copiedShardIds, shardId)
|
||||
}
|
||||
|
||||
if len(localShardIds)+recoverableRemoteShards >= erasure_coding.DataShardsCount {
|
||||
return copiedShardIds, localShardIds, nil
|
||||
}
|
||||
|
||||
// Hand back what was copied so the caller deletes these orphaned working
|
||||
// shards: recovery failed, but the temp files are already on the rebuilder.
|
||||
return copiedShardIds, localShardIds, fmt.Errorf("%d shards are not enough to recover volume %d", len(localShardIds)+recoverableRemoteShards, volumeId)
|
||||
|
||||
}
|
||||
|
||||
type EcShardMap map[needle.VolumeId]EcShardLocations
|
||||
type EcShardLocations [][]*EcNode
|
||||
|
||||
func (ecShardMap EcShardMap) registerEcNode(ecNode *EcNode, collection string) {
|
||||
for _, diskInfo := range ecNode.Info.DiskInfos {
|
||||
for _, shardInfo := range diskInfo.EcShardInfos {
|
||||
if shardInfo.Collection == collection {
|
||||
existing, found := ecShardMap[needle.VolumeId(shardInfo.Id)]
|
||||
if !found {
|
||||
// Use MaxShardCount (32) to support custom EC ratios
|
||||
existing = make([][]*EcNode, erasure_coding.MaxShardCount)
|
||||
ecShardMap[needle.VolumeId(shardInfo.Id)] = existing
|
||||
}
|
||||
for _, shardId := range erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(shardInfo).Ids() {
|
||||
existing[shardId] = append(existing[shardId], ecNode)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ecShardLocations EcShardLocations) shardCount() (count int) {
|
||||
for _, locations := range ecShardLocations {
|
||||
if len(locations) > 0 {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// ScrubEcVolumes asks each volume server to scrub its EC volumes (optionally
|
||||
// narrowed to volumeIds) in the given mode, aggregating and reporting results.
|
||||
func ScrubEcVolumes(env *Env, writer io.Writer, volumeServerAddrs []pb.ServerAddress, volumeIds []uint32, mode volume_server_pb.VolumeScrubMode, forceDeletedNeedlesCheck bool, maxParallelization int, showDetails bool) error {
|
||||
var brokenVolumesStr, brokenShardsStr []string
|
||||
var details []string
|
||||
var totalVolumes, brokenVolumes, brokenShards, totalFiles uint64
|
||||
var mu sync.Mutex
|
||||
|
||||
ewg := util.NewErrorWaitGroup(maxParallelization)
|
||||
count := 0
|
||||
for _, addr := range volumeServerAddrs {
|
||||
ewg.Add(func() error {
|
||||
mu.Lock()
|
||||
count++
|
||||
fmt.Fprintf(writer, "Scrubbing %s (%d/%d)...\n", addr.String(), count, len(volumeServerAddrs))
|
||||
mu.Unlock()
|
||||
|
||||
err := operation.WithVolumeServerClient(false, addr, env.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
|
||||
res, err := volumeServerClient.ScrubEcVolume(context.Background(), &volume_server_pb.ScrubEcVolumeRequest{
|
||||
Mode: mode,
|
||||
VolumeIds: volumeIds,
|
||||
ForceDeletedNeedlesCheck: forceDeletedNeedlesCheck,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
totalVolumes += res.GetTotalVolumes()
|
||||
totalFiles += res.GetTotalFiles()
|
||||
brokenVolumes += uint64(len(res.GetBrokenVolumeIds()))
|
||||
brokenShards += uint64(len(res.GetBrokenShardInfos()))
|
||||
for _, d := range res.GetDetails() {
|
||||
details = append(details, fmt.Sprintf("[%s] %s", addr, d))
|
||||
}
|
||||
for _, vid := range res.GetBrokenVolumeIds() {
|
||||
brokenVolumesStr = append(brokenVolumesStr, fmt.Sprintf("%s:%v", addr, vid))
|
||||
}
|
||||
for _, si := range res.GetBrokenShardInfos() {
|
||||
brokenShardsStr = append(brokenShardsStr, fmt.Sprintf("%s:%v:%v", addr, si.VolumeId, si.ShardId))
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
})
|
||||
}
|
||||
if err := ewg.Wait(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Fprintf(writer, "Scrubbed %d EC files and %d volumes on %d nodes\n", totalFiles, totalVolumes, len(volumeServerAddrs))
|
||||
if brokenVolumes != 0 {
|
||||
fmt.Fprintf(writer, "\nGot scrub failures on %d EC volumes and %d EC shards :(\n", brokenVolumes, brokenShards)
|
||||
fmt.Fprintf(writer, "Affected volumes: %s\n", strings.Join(brokenVolumesStr, ", "))
|
||||
if len(brokenShardsStr) != 0 {
|
||||
fmt.Fprintf(writer, "Affected shards: %s\n", strings.Join(brokenShardsStr, ", "))
|
||||
}
|
||||
if showDetails && len(details) != 0 {
|
||||
fmt.Fprintf(writer, "Details:\n\t%s\n", strings.Join(details, "\n\t"))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
package ec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
const (
|
||||
ecShardActionTimeout = 1 * time.Minute
|
||||
)
|
||||
|
||||
// ShardRef names one EC shard copy, optionally pinned to a node address.
|
||||
type ShardRef struct {
|
||||
ShardID uint32
|
||||
Collection string
|
||||
NodeAddress string
|
||||
}
|
||||
|
||||
func (s *ShardRef) String() string {
|
||||
if s.NodeAddress == "" {
|
||||
return fmt.Sprintf("%d", s.ShardID)
|
||||
}
|
||||
return fmt.Sprintf("%d@%s", s.ShardID, s.NodeAddress)
|
||||
}
|
||||
|
||||
// ShardRefsFromString parses a comma-separated list of shard IDs, each either a
|
||||
// bare numeric ID or <shard_id>@<node_address> to pick one copy.
|
||||
func ShardRefsFromString(shards string) ([]*ShardRef, error) {
|
||||
res := []*ShardRef{}
|
||||
|
||||
for _, s := range strings.Split(shards, ",") {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return nil, fmt.Errorf("empty shard ID in %q", shards)
|
||||
}
|
||||
|
||||
// optional <shard ID>@<node address> to pick one copy
|
||||
idStr, addr, _ := strings.Cut(s, "@")
|
||||
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil || id < 0 || id >= erasure_coding.MaxShardCount {
|
||||
return nil, fmt.Errorf("invalid shard ID %q", s)
|
||||
}
|
||||
|
||||
res = append(res, &ShardRef{ShardID: uint32(id), NodeAddress: addr})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// ShardUnmountRequest describes one ec.shard.unmount run.
|
||||
type ShardUnmountRequest struct {
|
||||
Topology *master_pb.TopologyInfo
|
||||
VolumeID uint32
|
||||
Shards []*ShardRef
|
||||
Delete bool
|
||||
IgnoreInvalid bool
|
||||
Apply bool
|
||||
}
|
||||
|
||||
type ecShardUnmounter struct {
|
||||
env *Env
|
||||
writer io.Writer
|
||||
req ShardUnmountRequest
|
||||
}
|
||||
|
||||
// UnmountShards unmounts, and optionally deletes, the requested EC shard
|
||||
// copies, resolving them against the live topology first. Dry-run unless
|
||||
// req.Apply is set.
|
||||
func UnmountShards(env *Env, writer io.Writer, req ShardUnmountRequest) error {
|
||||
c := &ecShardUnmounter{env: env, writer: writer, req: req}
|
||||
return c.doShardsUnmount()
|
||||
}
|
||||
|
||||
func (c *ecShardUnmounter) write(format string, a ...any) {
|
||||
fmt.Fprintf(c.writer, format, a...)
|
||||
}
|
||||
|
||||
func (c *ecShardUnmounter) liveShardsForVolume() []*ShardRef {
|
||||
shards := []*ShardRef{}
|
||||
|
||||
for _, dci := range c.req.Topology.GetDataCenterInfos() {
|
||||
for _, ri := range dci.GetRackInfos() {
|
||||
for _, dni := range ri.GetDataNodeInfos() {
|
||||
nodeAddress := dni.GetAddress()
|
||||
for _, di := range dni.GetDiskInfos() {
|
||||
for _, eci := range di.GetEcShardInfos() {
|
||||
if eci.GetId() == c.req.VolumeID {
|
||||
sinfo := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(eci)
|
||||
for _, sid := range sinfo.Ids() {
|
||||
shards = append(shards, &ShardRef{
|
||||
ShardID: uint32(sid),
|
||||
Collection: eci.GetCollection(),
|
||||
NodeAddress: nodeAddress,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.SliceStable(shards, func(i, j int) bool { return shards[i].ShardID < shards[j].ShardID })
|
||||
return shards
|
||||
}
|
||||
|
||||
func (c *ecShardUnmounter) printShards(ss []*ShardRef) {
|
||||
for _, s := range ss {
|
||||
c.write("\t%v\n", s)
|
||||
}
|
||||
c.write("\n")
|
||||
}
|
||||
|
||||
func (c *ecShardUnmounter) doShardsUnmount() error {
|
||||
liveShards := c.liveShardsForVolume()
|
||||
c.write("Live shard topology for volume ID %d (%d shards):\n", c.req.VolumeID, len(liveShards))
|
||||
c.printShards(liveShards)
|
||||
|
||||
// resolve target shards against the live topology
|
||||
targetShards := []*ShardRef{}
|
||||
for _, ps := range c.req.Shards {
|
||||
var result *ShardRef
|
||||
for _, ts := range liveShards {
|
||||
if ts.ShardID == ps.ShardID {
|
||||
if ps.NodeAddress == "" || ps.NodeAddress == ts.NodeAddress {
|
||||
if result != nil {
|
||||
return fmt.Errorf("shard %v is ambiguous", ps)
|
||||
}
|
||||
result = ts
|
||||
}
|
||||
}
|
||||
}
|
||||
if result == nil {
|
||||
if !c.req.IgnoreInvalid {
|
||||
return fmt.Errorf("shard %v is invalid", ps)
|
||||
}
|
||||
c.write("!!! ignoring invalid shard %v\n", ps)
|
||||
} else {
|
||||
targetShards = append(targetShards, result)
|
||||
}
|
||||
}
|
||||
if len(targetShards) == 0 {
|
||||
return fmt.Errorf("got no shards to process")
|
||||
}
|
||||
|
||||
mode := "unmount"
|
||||
if c.req.Delete {
|
||||
mode = "unmount + delete"
|
||||
}
|
||||
c.write("Will %s %d shard(s):\n", mode, len(targetShards))
|
||||
c.printShards(targetShards)
|
||||
|
||||
if !c.req.Apply {
|
||||
c.write("Not proceeding in dry-run mode\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
if !c.env.isLocked() {
|
||||
return fmt.Errorf("lock is lost")
|
||||
}
|
||||
|
||||
for _, s := range targetShards {
|
||||
if err := c.unmountShard(s); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
c.write("\nAll done!\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ecShardUnmounter) unmountShard(s *ShardRef) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), ecShardActionTimeout)
|
||||
defer cancel()
|
||||
|
||||
return operation.WithVolumeServerClient(false, pb.ServerAddress(s.NodeAddress), c.env.GrpcDialOption, func(vsc volume_server_pb.VolumeServerClient) error {
|
||||
c.write("Unmounting shard %v for volume ID %d...\n", s, c.req.VolumeID)
|
||||
if _, err := vsc.VolumeEcShardsUnmount(ctx, &volume_server_pb.VolumeEcShardsUnmountRequest{
|
||||
VolumeId: c.req.VolumeID,
|
||||
ShardIds: []uint32{s.ShardID},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if c.req.Delete {
|
||||
c.write("Deleting shard %v for volume ID %d...\n", s, c.req.VolumeID)
|
||||
if _, err := vsc.VolumeEcShardsDelete(ctx, &volume_server_pb.VolumeEcShardsDeleteRequest{
|
||||
VolumeId: c.req.VolumeID,
|
||||
Collection: s.Collection,
|
||||
ShardIds: []uint32{s.ShardID},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Package ec holds the EC (erasure coding) cluster orchestration logic shared
|
||||
// by the weed shell commands and the maintenance workers: topology analysis of
|
||||
// EC shards, the encode/balance pipelines, and the volume-server RPC wrappers
|
||||
// they drive. The placement policy itself lives in
|
||||
// weed/storage/erasure_coding/ecbalancer; low-level shard mechanics live in
|
||||
// weed/storage/erasure_coding.
|
||||
package ec
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/wdclient"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Env carries the cluster access hooks EC operations need, decoupled from any
|
||||
// particular caller (shell CommandEnv, worker task, admin server).
|
||||
type Env struct {
|
||||
GrpcDialOption grpc.DialOption
|
||||
// FetchTopology returns a fresh master topology snapshot (and the master's
|
||||
// volume size limit in MB) after an optional delay.
|
||||
FetchTopology func(delay time.Duration) (*master_pb.TopologyInfo, uint64, error)
|
||||
// GetVolumeLocations returns the current replica locations for a volume id,
|
||||
// or false if the volume is unknown.
|
||||
GetVolumeLocations func(vid uint32) ([]wdclient.Location, bool)
|
||||
// IsLocked reports whether the caller still holds the cluster admin lock.
|
||||
// Callers without a lock concept return true.
|
||||
IsLocked func() bool
|
||||
}
|
||||
|
||||
// isLocked treats a nil Env or nil hook as locked, matching the shell's
|
||||
// nil-receiver behavior so dry-run paths work without a cluster connection.
|
||||
func (env *Env) isLocked() bool {
|
||||
if env == nil || env.IsLocked == nil {
|
||||
return true
|
||||
}
|
||||
return env.IsLocked()
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package empty_folder_cleanup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -22,39 +20,14 @@ const (
|
||||
DefaultQueueMaxSize = 1000
|
||||
DefaultQueueMaxAge = 2 * time.Minute
|
||||
DefaultProcessorSleep = 30 * time.Second // How often to check queue
|
||||
DefaultMaxDeletedKept = 10000 // Deleted folders remembered for the restore check
|
||||
// How long a deleted folder is kept so that a create event arriving for it can
|
||||
// still put it back. It bounds how far behind the event stream may run, not how
|
||||
// long the race window is.
|
||||
DefaultObservationWindow = 2 * time.Minute
|
||||
)
|
||||
|
||||
// DirectoryAttributes is what a restored directory needs to come back as it was.
|
||||
type DirectoryAttributes struct {
|
||||
Mode os.FileMode
|
||||
Uid uint32
|
||||
Gid uint32
|
||||
UserName string
|
||||
GroupNames []string
|
||||
}
|
||||
|
||||
// deletedFolder is a folder under observation for entries that landed while it was
|
||||
// being deleted. writtenTo is set by the create event for such an entry.
|
||||
type deletedFolder struct {
|
||||
path string
|
||||
attrs DirectoryAttributes
|
||||
deletedAt time.Time
|
||||
writtenTo bool
|
||||
}
|
||||
|
||||
// FilerOperations defines the filer operations needed by EmptyFolderCleaner
|
||||
type FilerOperations interface {
|
||||
CountDirectoryEntries(ctx context.Context, dirPath util.FullPath, limit int) (count int, err error)
|
||||
DeleteEntryMetaAndData(ctx context.Context, p util.FullPath, isRecursive, ignoreRecursiveError, shouldDeleteChunks, isFromOtherCluster bool, signatures []int32, ifNotModifiedAfter int64) error
|
||||
GetEntryAttributes(ctx context.Context, p util.FullPath) (attributes map[string][]byte, err error)
|
||||
IsDirectoryKeyObject(ctx context.Context, p util.FullPath) (bool, error)
|
||||
DirectoryAttributes(ctx context.Context, p util.FullPath) (DirectoryAttributes, error)
|
||||
EnsureDirectoryEntry(ctx context.Context, p util.FullPath, attrs DirectoryAttributes) error
|
||||
}
|
||||
|
||||
// folderState tracks the state of a folder for empty folder cleanup
|
||||
@@ -83,11 +56,6 @@ type EmptyFolderCleaner struct {
|
||||
folderCounts map[string]*folderState // Rough count cache
|
||||
bucketCleanupPolicies map[string]*bucketCleanupPolicyState // bucket path -> cleanup policy cache
|
||||
|
||||
// Folders deleted recently, kept so that a create event arriving for one of them
|
||||
// can put it back
|
||||
deleted map[string]*deletedFolder
|
||||
deletedDropped int
|
||||
|
||||
// Cleanup queue (thread-safe, has its own lock)
|
||||
cleanupQueue *CleanupQueue
|
||||
|
||||
@@ -115,7 +83,6 @@ func NewEmptyFolderCleaner(filer FilerOperations, lockRing *lock_manager.LockRin
|
||||
host: host,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
bucketCleanupPolicies: make(map[string]*bucketCleanupPolicyState),
|
||||
deleted: make(map[string]*deletedFolder),
|
||||
cleanupQueue: NewCleanupQueue(DefaultQueueMaxSize, cleanupDelay),
|
||||
maxCountCheck: DefaultMaxCountCheck,
|
||||
cacheExpiry: DefaultCacheExpiry,
|
||||
@@ -227,14 +194,6 @@ func (efc *EmptyFolderCleaner) OnCreateEvent(directory string, entryName string,
|
||||
state.lastAddTime = time.Now()
|
||||
}
|
||||
|
||||
// An entry landing in a folder we just deleted is the race this cleaner cannot
|
||||
// exclude: the folder was empty when checked and is gone now, so the entry has
|
||||
// nothing holding it. The event says so outright, which beats going back to look.
|
||||
if folder, found := efc.deleted[directory]; found {
|
||||
folder.writtenTo = true
|
||||
glog.V(2).Infof("EmptyFolderCleaner: %s was written to while being deleted, restoring it", directory)
|
||||
}
|
||||
|
||||
// Remove from cleanup queue (cancel pending cleanup)
|
||||
if efc.cleanupQueue.Remove(directory) {
|
||||
glog.V(3).Infof("EmptyFolderCleaner: cancelled cleanup for %s due to new entry", directory)
|
||||
@@ -258,8 +217,6 @@ func (efc *EmptyFolderCleaner) cleanupProcessor() {
|
||||
|
||||
// processCleanupQueue processes items from the cleanup queue
|
||||
func (efc *EmptyFolderCleaner) processCleanupQueue() {
|
||||
efc.restoreFoldersWrittenDuringDelete()
|
||||
|
||||
if efc.cleanupQueue.Len() == 0 {
|
||||
return
|
||||
}
|
||||
@@ -285,127 +242,6 @@ func (efc *EmptyFolderCleaner) processCleanupQueue() {
|
||||
}
|
||||
}
|
||||
|
||||
// restoreFoldersWrittenDuringDelete puts back folders that received an entry between
|
||||
// the emptiness check and the delete, which leaves that entry with no directory
|
||||
// holding it: reachable by its own path, but absent from any listing.
|
||||
//
|
||||
// A folder stays under observation for DefaultRestoreCheckWindow rather than being
|
||||
// checked once. A writer looks up the parent before inserting the child, so a check
|
||||
// can land in that gap and see nothing; ticks also coalesce when a pass runs long, so
|
||||
// "next pass" is not a delay at all. Re-checking for a bounded wall-clock window
|
||||
// covers both. This narrows the exposure rather than closing it - only making the
|
||||
// emptiness check and the delete atomic would do that.
|
||||
func (efc *EmptyFolderCleaner) restoreFoldersWrittenDuringDelete() {
|
||||
efc.mu.Lock()
|
||||
dropped := efc.deletedDropped
|
||||
efc.deletedDropped = 0
|
||||
var restore []*deletedFolder
|
||||
for path, folder := range efc.deleted {
|
||||
// The window applies whatever the folder's state is. Checking writtenTo first
|
||||
// would keep a folder whose restore keeps failing forever, re-counting it on
|
||||
// every pass.
|
||||
if time.Since(folder.deletedAt) >= DefaultObservationWindow {
|
||||
delete(efc.deleted, path)
|
||||
continue
|
||||
}
|
||||
if folder.writtenTo {
|
||||
restore = append(restore, folder)
|
||||
delete(efc.deleted, path)
|
||||
}
|
||||
}
|
||||
// A cascade takes ancestors along with the folder. Rebuild those from what they
|
||||
// were too: leaving them to the descendant's restore would mint them from the
|
||||
// descendant's own attributes, handing back access the ancestor did not grant.
|
||||
for i := 0; i < len(restore); i++ {
|
||||
ancestor, _ := util.FullPath(restore[i].path).DirAndName()
|
||||
for ancestor != "" && ancestor != "/" {
|
||||
if folder, found := efc.deleted[ancestor]; found {
|
||||
restore = append(restore, folder)
|
||||
delete(efc.deleted, ancestor)
|
||||
}
|
||||
ancestor, _ = util.FullPath(ancestor).DirAndName()
|
||||
}
|
||||
}
|
||||
efc.mu.Unlock()
|
||||
|
||||
if dropped > 0 {
|
||||
glog.V(1).Infof("EmptyFolderCleaner: %d deleted folders left unobserved, past the %d kept", dropped, DefaultMaxDeletedKept)
|
||||
}
|
||||
if len(restore) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Restore shallowest first, so a folder taken by the parent cascade is rebuilt
|
||||
// with its own attributes before anything below it needs it as a parent.
|
||||
sort.Slice(restore, func(i, j int) bool {
|
||||
return strings.Count(restore[i].path, "/") < strings.Count(restore[j].path, "/")
|
||||
})
|
||||
|
||||
ctx := context.Background()
|
||||
var retry []*deletedFolder
|
||||
for i, folder := range restore {
|
||||
if !efc.IsEnabled() {
|
||||
retry = append(retry, restore[i:]...)
|
||||
break
|
||||
}
|
||||
// An event named this folder, but the entry may have been removed again since,
|
||||
// in which case there is nothing to hold and it can stay gone. Ancestors pulled
|
||||
// in above carry no event and are rebuilt regardless, since the folder below
|
||||
// them needs them.
|
||||
if folder.writtenTo {
|
||||
count, err := efc.countItems(ctx, folder.path)
|
||||
if err != nil {
|
||||
glog.V(2).Infof("EmptyFolderCleaner: cannot count %s before restoring it: %v", folder.path, err)
|
||||
retry = append(retry, folder)
|
||||
continue
|
||||
}
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
glog.V(1).Infof("EmptyFolderCleaner: restoring %s, written to while it was being deleted", folder.path)
|
||||
if err := efc.filer.EnsureDirectoryEntry(ctx, util.FullPath(folder.path), folder.attrs); err != nil {
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to restore %s: %v", folder.path, err)
|
||||
retry = append(retry, folder)
|
||||
}
|
||||
}
|
||||
|
||||
if len(retry) == 0 {
|
||||
return
|
||||
}
|
||||
efc.mu.Lock()
|
||||
for _, folder := range retry {
|
||||
if _, found := efc.deleted[folder.path]; !found {
|
||||
efc.makeRoomForDeletedLocked()
|
||||
}
|
||||
efc.deleted[folder.path] = folder
|
||||
}
|
||||
efc.mu.Unlock()
|
||||
}
|
||||
|
||||
// makeRoomForDeletedLocked drops the oldest of a small sample when the set is full.
|
||||
// The newest folders are the ones whose race is still live, so they must not be the
|
||||
// ones given up; sampling keeps this cheap under heavy deletion rates.
|
||||
func (efc *EmptyFolderCleaner) makeRoomForDeletedLocked() {
|
||||
if len(efc.deleted) < DefaultMaxDeletedKept {
|
||||
return
|
||||
}
|
||||
const sampleSize = 32
|
||||
oldestPath, seen := "", 0
|
||||
for path, folder := range efc.deleted {
|
||||
if oldestPath == "" || folder.deletedAt.Before(efc.deleted[oldestPath].deletedAt) {
|
||||
oldestPath = path
|
||||
}
|
||||
if seen++; seen >= sampleSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
if oldestPath != "" {
|
||||
delete(efc.deleted, oldestPath)
|
||||
efc.deletedDropped++
|
||||
}
|
||||
}
|
||||
|
||||
// executeCleanup performs the actual cleanup of an empty folder
|
||||
func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string) {
|
||||
// The bucket-shared .uploads staging tree holds in-progress multipart uploads.
|
||||
@@ -488,25 +324,7 @@ func (efc *EmptyFolderCleaner) executeCleanup(folder string, triggeredBy string)
|
||||
return
|
||||
}
|
||||
|
||||
// Read what it would take to put this folder back before removing it; without
|
||||
// that a restore would have to invent attributes for it.
|
||||
attrs, err := efc.filer.DirectoryAttributes(ctx, util.FullPath(folder))
|
||||
if err != nil {
|
||||
glog.V(2).Infof("EmptyFolderCleaner: cannot read %s before deleting it: %v", folder, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Observe it before the delete rather than after. A delete can fail partway and
|
||||
// still leave the folder gone - the redis stores remove the folder before their
|
||||
// parent-list member - so a failure return is not proof that it is still there.
|
||||
efc.mu.Lock()
|
||||
if efc.deleted == nil {
|
||||
efc.deleted = make(map[string]*deletedFolder)
|
||||
}
|
||||
efc.makeRoomForDeletedLocked()
|
||||
efc.deleted[folder] = &deletedFolder{path: folder, attrs: attrs, deletedAt: time.Now()}
|
||||
efc.mu.Unlock()
|
||||
|
||||
// Delete the empty folder
|
||||
glog.Infof("EmptyFolderCleaner: deleting empty folder %s (triggered by %s)", folder, triggeredBy)
|
||||
if err := efc.deleteFolder(ctx, folder); err != nil {
|
||||
glog.V(2).Infof("EmptyFolderCleaner: failed to delete empty folder %s (triggered by %s): %v", folder, triggeredBy, err)
|
||||
@@ -721,7 +539,6 @@ func (efc *EmptyFolderCleaner) Stop() {
|
||||
efc.cleanupQueue.Clear()
|
||||
efc.folderCounts = make(map[string]*folderState) // Clear cache on stop
|
||||
efc.bucketCleanupPolicies = make(map[string]*bucketCleanupPolicyState)
|
||||
efc.deleted, efc.deletedDropped = make(map[string]*deletedFolder), 0
|
||||
}
|
||||
|
||||
// GetPendingCleanupCount returns the number of pending cleanup tasks (for testing)
|
||||
|
||||
@@ -2,7 +2,6 @@ package empty_folder_cleanup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -17,22 +16,6 @@ type mockFilerOps struct {
|
||||
deleteFn func(path util.FullPath) error
|
||||
attrsFn func(path util.FullPath) (map[string][]byte, error)
|
||||
isDirKeyObjFn func(path util.FullPath) (bool, error)
|
||||
ensureDirFn func(path util.FullPath, attrs DirectoryAttributes) error
|
||||
dirAttrsFn func(path util.FullPath) (DirectoryAttributes, error)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) EnsureDirectoryEntry(_ context.Context, p util.FullPath, attrs DirectoryAttributes) error {
|
||||
if m.ensureDirFn == nil {
|
||||
return nil
|
||||
}
|
||||
return m.ensureDirFn(p, attrs)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) DirectoryAttributes(_ context.Context, p util.FullPath) (DirectoryAttributes, error) {
|
||||
if m.dirAttrsFn == nil {
|
||||
return DirectoryAttributes{Mode: 0755}, nil
|
||||
}
|
||||
return m.dirAttrsFn(p)
|
||||
}
|
||||
|
||||
func (m *mockFilerOps) CountDirectoryEntries(_ context.Context, dirPath util.FullPath, _ int) (int, error) {
|
||||
@@ -217,222 +200,6 @@ func TestEmptyFolderCleaner_executeCleanup_skipsMultipartUploads(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyFolderCleaner_restoreFoldersWrittenDuringDelete(t *testing.T) {
|
||||
lockRing := lock_manager.NewLockRing(5 * time.Second)
|
||||
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"}, 0)
|
||||
|
||||
newCleaner := func(mock *mockFilerOps) *EmptyFolderCleaner {
|
||||
return &EmptyFolderCleaner{
|
||||
filer: mock,
|
||||
lockRing: lockRing,
|
||||
host: "filer1:8888",
|
||||
bucketPath: "/buckets",
|
||||
enabled: true,
|
||||
maxCountCheck: DefaultMaxCountCheck,
|
||||
cacheExpiry: DefaultCacheExpiry,
|
||||
folderCounts: make(map[string]*folderState),
|
||||
bucketCleanupPolicies: make(map[string]*bucketCleanupPolicyState),
|
||||
deleted: make(map[string]*deletedFolder),
|
||||
cleanupQueue: NewCleanupQueue(1000, 10*time.Minute),
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
const folder = "/buckets/mybucket/folder"
|
||||
|
||||
t.Run("a create event for the deleted folder puts it back", func(t *testing.T) {
|
||||
var restored []string
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(util.FullPath) (int, error) { return 0, nil },
|
||||
ensureDirFn: func(p util.FullPath, _ DirectoryAttributes) error { restored = append(restored, string(p)); return nil },
|
||||
}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
cleaner.executeCleanup(folder, "file.txt")
|
||||
|
||||
// nothing has been written to it, so it is only observed
|
||||
cleaner.processCleanupQueue()
|
||||
if len(restored) != 0 {
|
||||
t.Fatalf("a folder nothing was written to should not be restored, got %v", restored)
|
||||
}
|
||||
if len(cleaner.deleted) != 1 {
|
||||
t.Fatalf("folder should still be observed, got %d", len(cleaner.deleted))
|
||||
}
|
||||
|
||||
// the write that raced the delete arrives as a create event
|
||||
mock.countFn = func(util.FullPath) (int, error) { return 1, nil }
|
||||
cleaner.OnCreateEvent(folder, "obj", false)
|
||||
cleaner.processCleanupQueue()
|
||||
if len(restored) != 1 || restored[0] != folder {
|
||||
t.Fatalf("a folder written to while being deleted should be restored, got %v", restored)
|
||||
}
|
||||
if len(cleaner.deleted) != 0 {
|
||||
t.Fatalf("a restored folder should stop being observed, got %d", len(cleaner.deleted))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a create event elsewhere is ignored", func(t *testing.T) {
|
||||
var restored []string
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(util.FullPath) (int, error) { return 0, nil },
|
||||
ensureDirFn: func(p util.FullPath, _ DirectoryAttributes) error { restored = append(restored, string(p)); return nil },
|
||||
}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
cleaner.executeCleanup(folder, "file.txt")
|
||||
cleaner.OnCreateEvent("/buckets/mybucket/other", "obj", false)
|
||||
cleaner.processCleanupQueue()
|
||||
if len(restored) != 0 {
|
||||
t.Fatalf("only the folder written to should be restored, got %v", restored)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an entry that went away again is not restored", func(t *testing.T) {
|
||||
var restored []string
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(util.FullPath) (int, error) { return 0, nil },
|
||||
ensureDirFn: func(p util.FullPath, _ DirectoryAttributes) error { restored = append(restored, string(p)); return nil },
|
||||
}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
cleaner.executeCleanup(folder, "file.txt")
|
||||
cleaner.OnCreateEvent(folder, "obj", false)
|
||||
cleaner.processCleanupQueue()
|
||||
if len(restored) != 0 {
|
||||
t.Fatalf("an empty folder should not be restored, got %v", restored)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("observation expires", func(t *testing.T) {
|
||||
mock := &mockFilerOps{countFn: func(util.FullPath) (int, error) { return 0, nil }}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
cleaner.executeCleanup(folder, "file.txt")
|
||||
cleaner.processCleanupQueue()
|
||||
if len(cleaner.deleted) != 1 {
|
||||
t.Fatalf("folder should still be observed inside the window, got %d", len(cleaner.deleted))
|
||||
}
|
||||
|
||||
cleaner.deleted[folder].deletedAt = time.Now().Add(-DefaultObservationWindow - time.Second)
|
||||
cleaner.processCleanupQueue()
|
||||
if len(cleaner.deleted) != 0 {
|
||||
t.Fatalf("folder should stop being observed once the window has passed, got %d", len(cleaner.deleted))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a failed restore is retried", func(t *testing.T) {
|
||||
attempts := 0
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(util.FullPath) (int, error) { return 1, nil },
|
||||
ensureDirFn: func(p util.FullPath, _ DirectoryAttributes) error {
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
return errors.New("store unavailable")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
// deleted while empty, then written to
|
||||
mock.countFn = func(util.FullPath) (int, error) { return 0, nil }
|
||||
cleaner.executeCleanup(folder, "file.txt")
|
||||
mock.countFn = func(util.FullPath) (int, error) { return 1, nil }
|
||||
cleaner.OnCreateEvent(folder, "obj", false)
|
||||
|
||||
cleaner.processCleanupQueue()
|
||||
if len(cleaner.deleted) != 1 {
|
||||
t.Fatalf("a folder whose restore failed should be kept, got %d", len(cleaner.deleted))
|
||||
}
|
||||
|
||||
cleaner.processCleanupQueue()
|
||||
if attempts != 2 {
|
||||
t.Fatalf("a failed restore should be retried, got %d attempts", attempts)
|
||||
}
|
||||
if len(cleaner.deleted) != 0 {
|
||||
t.Fatalf("a restored folder should stop being observed, got %d", len(cleaner.deleted))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a folder whose restore keeps failing stops being observed", func(t *testing.T) {
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(util.FullPath) (int, error) { return 0, nil },
|
||||
ensureDirFn: func(util.FullPath, DirectoryAttributes) error { return errors.New("store unavailable") },
|
||||
}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
cleaner.executeCleanup(folder, "file.txt")
|
||||
mock.countFn = func(util.FullPath) (int, error) { return 1, nil }
|
||||
cleaner.OnCreateEvent(folder, "obj", false)
|
||||
|
||||
cleaner.processCleanupQueue()
|
||||
if len(cleaner.deleted) != 1 {
|
||||
t.Fatalf("a folder whose restore failed should be kept, got %d", len(cleaner.deleted))
|
||||
}
|
||||
|
||||
// otherwise it would be retried on every pass for the rest of the process
|
||||
cleaner.deleted[folder].deletedAt = time.Now().Add(-DefaultObservationWindow - time.Second)
|
||||
cleaner.processCleanupQueue()
|
||||
if len(cleaner.deleted) != 0 {
|
||||
t.Fatalf("the window should apply to a failing folder too, got %d", len(cleaner.deleted))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an ancestor taken by the cascade is restored with its own attributes", func(t *testing.T) {
|
||||
const ancestor = "/buckets/mybucket/data"
|
||||
const nested = ancestor + "/abc"
|
||||
|
||||
restored := map[string]DirectoryAttributes{}
|
||||
var order []string
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(util.FullPath) (int, error) { return 0, nil },
|
||||
dirAttrsFn: func(p util.FullPath) (DirectoryAttributes, error) {
|
||||
if string(p) == ancestor {
|
||||
return DirectoryAttributes{Mode: 0700, Uid: 4242}, nil
|
||||
}
|
||||
return DirectoryAttributes{Mode: 0755, Uid: 7}, nil
|
||||
},
|
||||
ensureDirFn: func(p util.FullPath, attrs DirectoryAttributes) error {
|
||||
restored[string(p)] = attrs
|
||||
order = append(order, string(p))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
// the cascade takes the nested folder and then its parent
|
||||
cleaner.executeCleanup(nested, "file.txt")
|
||||
cleaner.executeCleanup(ancestor, "abc")
|
||||
|
||||
// only the nested folder is written to
|
||||
mock.countFn = func(util.FullPath) (int, error) { return 1, nil }
|
||||
cleaner.OnCreateEvent(nested, "obj", false)
|
||||
cleaner.processCleanupQueue()
|
||||
|
||||
if len(order) != 2 || order[0] != ancestor {
|
||||
t.Fatalf("the ancestor should be rebuilt first, got %v", order)
|
||||
}
|
||||
if got := restored[ancestor]; got.Mode != 0700 || got.Uid != 4242 {
|
||||
t.Errorf("ancestor should keep its own attributes, got mode %o uid %d", got.Mode, got.Uid)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a delete that reports failure is still observed", func(t *testing.T) {
|
||||
// the redis stores drop the folder before its parent-list member, so a failure
|
||||
// return is not proof that the folder survived
|
||||
mock := &mockFilerOps{
|
||||
countFn: func(util.FullPath) (int, error) { return 0, nil },
|
||||
deleteFn: func(util.FullPath) error { return errors.New("partial delete") },
|
||||
}
|
||||
|
||||
cleaner := newCleaner(mock)
|
||||
cleaner.executeCleanup(folder, "file.txt")
|
||||
if len(cleaner.deleted) != 1 {
|
||||
t.Fatalf("a failed delete should still leave the folder observed, got %d", len(cleaner.deleted))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func Test_autoRemoveEmptyFoldersEnabled(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -373,65 +373,6 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di
|
||||
return nil
|
||||
}
|
||||
|
||||
// DirectoryAttributes reads what a directory would need to be recreated as it is.
|
||||
func (f *Filer) DirectoryAttributes(ctx context.Context, dirPath util.FullPath) (attrs empty_folder_cleanup.DirectoryAttributes, err error) {
|
||||
entry, err := f.FindEntry(ctx, dirPath)
|
||||
if err != nil {
|
||||
return attrs, err
|
||||
}
|
||||
if entry == nil {
|
||||
return attrs, filer_pb.ErrNotFound
|
||||
}
|
||||
return empty_folder_cleanup.DirectoryAttributes{
|
||||
// everything but the type bits: Perm() alone would drop setgid, setuid and
|
||||
// sticky, quietly changing group inheritance and delete semantics
|
||||
Mode: entry.Mode & (os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky),
|
||||
Uid: entry.Uid,
|
||||
Gid: entry.Gid,
|
||||
UserName: entry.UserName,
|
||||
GroupNames: entry.GroupNames,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// EnsureDirectoryEntry recreates dirPath, and any missing ancestor, for entries that
|
||||
// outlived the directory holding them. dirPath comes back with the attributes it was
|
||||
// deleted with, so a restore cannot hand back a directory more permissive than the one
|
||||
// it replaces. It is a no-op when dirPath is already there.
|
||||
func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath, attrs empty_folder_cleanup.DirectoryAttributes) error {
|
||||
existing, err := f.FindEntry(ctx, dirPath)
|
||||
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
if existing != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
holder := &Entry{FullPath: dirPath, Attr: Attr{
|
||||
Mode: attrs.Mode, Uid: attrs.Uid, Gid: attrs.Gid,
|
||||
UserName: attrs.UserName, GroupNames: attrs.GroupNames,
|
||||
}}
|
||||
dirParts := strings.Split(string(dirPath), "/")
|
||||
if err := f.ensureParentDirectoryEntry(ctx, holder, dirParts, len(dirParts)-1, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
dirEntry := &Entry{FullPath: dirPath, Attr: Attr{
|
||||
Mtime: now, Crtime: now,
|
||||
Mode: os.ModeDir | attrs.Mode,
|
||||
Uid: attrs.Uid,
|
||||
Gid: attrs.Gid,
|
||||
UserName: attrs.UserName, GroupNames: attrs.GroupNames,
|
||||
}}
|
||||
f.ensureEntryInode(dirEntry)
|
||||
if err := f.Store.InsertEntry(ctx, dirEntry); err != nil {
|
||||
return fmt.Errorf("restore directory %s: %v", dirPath, err)
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, nil, dirEntry, false, false, nil)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
|
||||
if oldEntry != nil {
|
||||
entry.Attr.Crtime = oldEntry.Attr.Crtime
|
||||
|
||||
@@ -78,8 +78,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
var chunksToDelete []*filer_pb.FileChunk
|
||||
lastFileName := ""
|
||||
includeLastFile := false
|
||||
listedChildren := !isDeletingBucket || !f.Store.CanDropWholeBucket()
|
||||
if listedChildren {
|
||||
if !isDeletingBucket || !f.Store.CanDropWholeBucket() {
|
||||
for {
|
||||
entries, _, err := f.ListDirectoryEntries(ctx, entry.FullPath, lastFileName, includeLastFile, PaginationSize, "", "", "")
|
||||
if err != nil {
|
||||
@@ -132,12 +131,8 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
|
||||
|
||||
glog.V(3).InfofCtx(ctx, "deleting directory %v delete chunks: %v", entry.FullPath, shouldDeleteChunks)
|
||||
|
||||
// a non-recursive delete already proved the folder empty above, so sweeping the
|
||||
// children now can only remove entries that raced in after that listing
|
||||
if isRecursive || !listedChildren {
|
||||
if storeDeletionErr := f.Store.DeleteFolderChildren(ctx, entry.FullPath); storeDeletionErr != nil {
|
||||
return fmt.Errorf("filer store delete: %w", storeDeletionErr)
|
||||
}
|
||||
if storeDeletionErr := f.Store.DeleteFolderChildren(ctx, entry.FullPath); storeDeletionErr != nil {
|
||||
return fmt.Errorf("filer store delete: %w", storeDeletionErr)
|
||||
}
|
||||
|
||||
f.NotifyUpdateEvent(ctx, entry, nil, shouldDeleteChunks, isFromOtherCluster, signatures)
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
package leveldb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"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/util"
|
||||
)
|
||||
|
||||
// listHookStore runs a hook once, right after a directory listing returns, so a
|
||||
// test can act inside the window between a delete's emptiness check and the
|
||||
// removal of the folder.
|
||||
type listHookStore struct {
|
||||
filer.FilerStore
|
||||
hook func()
|
||||
fired bool
|
||||
}
|
||||
|
||||
func (s *listHookStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (string, error) {
|
||||
lastFileName, err := s.FilerStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, eachEntryFunc)
|
||||
if s.hook != nil && !s.fired {
|
||||
s.fired = true
|
||||
s.hook()
|
||||
}
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
// TestNonRecursiveFolderDeleteKeepsRacingChild covers the S3 empty-folder
|
||||
// cleanup path: the delete lists a folder, finds it empty, and must not then
|
||||
// bulk-delete its children, because an object written in between would be
|
||||
// destroyed after the write was already acknowledged.
|
||||
func TestNonRecursiveFolderDeleteKeepsRacingChild(t *testing.T) {
|
||||
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
|
||||
store := &LevelDB2Store{}
|
||||
if err := store.initialize(t.TempDir(), 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hooked := &listHookStore{FilerStore: store}
|
||||
testFiler.SetStore(hooked)
|
||||
|
||||
// the test has no metadata log consumer
|
||||
ctx := filer.WithSuppressedMetadataEvents(context.Background())
|
||||
dir := util.FullPath("/buckets/testbucket/data/abc")
|
||||
child := dir.Child("obj")
|
||||
|
||||
dirEntry := &filer.Entry{FullPath: dir, Attr: filer.Attr{Mode: os.ModeDir | 0755}}
|
||||
if err := testFiler.CreateEntry(ctx, dirEntry, nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil {
|
||||
t.Fatalf("create folder: %v", err)
|
||||
}
|
||||
|
||||
hooked.hook = func() {
|
||||
entry := &filer.Entry{FullPath: child, Attr: filer.Attr{Mode: 0640}}
|
||||
if err := testFiler.CreateEntry(ctx, entry, nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil {
|
||||
t.Errorf("create entry racing the folder delete: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := testFiler.DeleteEntryMetaAndData(ctx, dir, false, false, false, false, nil, 0); err != nil {
|
||||
t.Fatalf("delete empty folder: %v", err)
|
||||
}
|
||||
|
||||
if _, err := testFiler.FindEntry(ctx, child); err != nil {
|
||||
t.Errorf("entry created during the folder delete was removed: %v", err)
|
||||
}
|
||||
|
||||
// The folder entry itself still goes, so the surviving entry is reachable by
|
||||
// path but absent from listings until the folder comes back. Pinning that here
|
||||
// keeps the remaining exposure visible; tighten it if the two steps ever become
|
||||
// atomic.
|
||||
if _, err := testFiler.FindEntry(ctx, dir); !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
t.Errorf("folder entry should still be removed, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnsureDirectoryEntryRestoresRacingParent covers the leftover of the same
|
||||
// race: the entry survives the folder delete but its directory does not, so the
|
||||
// entry drops out of listings until the directory is put back.
|
||||
func TestEnsureDirectoryEntryRestoresRacingParent(t *testing.T) {
|
||||
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
|
||||
store := &LevelDB2Store{}
|
||||
if err := store.initialize(t.TempDir(), 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hooked := &listHookStore{FilerStore: store}
|
||||
testFiler.SetStore(hooked)
|
||||
|
||||
ctx := filer.WithSuppressedMetadataEvents(context.Background())
|
||||
parent := util.FullPath("/buckets/testbucket/data")
|
||||
dir := parent.Child("abc")
|
||||
child := dir.Child("obj")
|
||||
|
||||
dirEntry := &filer.Entry{FullPath: dir, Attr: filer.Attr{Mode: os.ModeDir | 0755}}
|
||||
if err := testFiler.CreateEntry(ctx, dirEntry, nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil {
|
||||
t.Fatalf("create folder: %v", err)
|
||||
}
|
||||
|
||||
// the cleaner reads these before deleting, so a restore does not have to guess
|
||||
attrs, err := testFiler.DirectoryAttributes(ctx, dir)
|
||||
if err != nil {
|
||||
t.Fatalf("read folder attributes: %v", err)
|
||||
}
|
||||
|
||||
hooked.hook = func() {
|
||||
entry := &filer.Entry{FullPath: child, Attr: filer.Attr{Mode: 0640}}
|
||||
if err := testFiler.CreateEntry(ctx, entry, nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil {
|
||||
t.Errorf("create entry racing the folder delete: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := testFiler.DeleteEntryMetaAndData(ctx, dir, false, false, false, false, nil, 0); err != nil {
|
||||
t.Fatalf("delete empty folder: %v", err)
|
||||
}
|
||||
|
||||
if names := listNames(ctx, t, testFiler, parent); len(names) != 0 {
|
||||
t.Fatalf("folder should be gone from its parent before the restore, got %v", names)
|
||||
}
|
||||
|
||||
if err := testFiler.EnsureDirectoryEntry(ctx, dir, attrs); err != nil {
|
||||
t.Fatalf("restore folder: %v", err)
|
||||
}
|
||||
|
||||
restored, err := testFiler.FindEntry(ctx, dir)
|
||||
if err != nil {
|
||||
t.Fatalf("find restored folder: %v", err)
|
||||
}
|
||||
if !restored.IsDirectory() {
|
||||
t.Errorf("restored %s is not a directory", dir)
|
||||
}
|
||||
if names := listNames(ctx, t, testFiler, parent); len(names) != 1 || names[0] != "abc" {
|
||||
t.Errorf("restored folder should be listed under its parent, got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEnsureDirectoryEntryRestoresExactAttributes checks that a restored directory
|
||||
// comes back exactly as it was. Guessing from an ancestor, or forcing traversal bits,
|
||||
// would hand back a directory that grants access the original one denied.
|
||||
func TestEnsureDirectoryEntryRestoresExactAttributes(t *testing.T) {
|
||||
testFiler := filer.NewFiler(pb.ServerDiscovery{}, nil, "", "", "", "", "", 255, nil)
|
||||
store := &LevelDB2Store{}
|
||||
if err := store.initialize(t.TempDir(), 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testFiler.SetStore(store)
|
||||
|
||||
ctx := filer.WithSuppressedMetadataEvents(context.Background())
|
||||
// a private directory under a world-traversable parent
|
||||
dir := util.FullPath("/buckets/testbucket/data").Child("private")
|
||||
dirEntry := &filer.Entry{FullPath: dir, Attr: filer.Attr{Mode: os.ModeDir | 0700, Uid: 4242, Gid: 4343}}
|
||||
if err := testFiler.CreateEntry(ctx, dirEntry, nil, false, false, nil, false, testFiler.MaxFilenameLength); err != nil {
|
||||
t.Fatalf("create folder: %v", err)
|
||||
}
|
||||
|
||||
attrs, err := testFiler.DirectoryAttributes(ctx, dir)
|
||||
if err != nil {
|
||||
t.Fatalf("read folder attributes: %v", err)
|
||||
}
|
||||
if err := testFiler.DeleteEntryMetaAndData(ctx, dir, false, false, false, false, nil, 0); err != nil {
|
||||
t.Fatalf("delete folder: %v", err)
|
||||
}
|
||||
|
||||
if err := testFiler.EnsureDirectoryEntry(ctx, dir, attrs); err != nil {
|
||||
t.Fatalf("restore folder: %v", err)
|
||||
}
|
||||
|
||||
restored, err := testFiler.FindEntry(ctx, dir)
|
||||
if err != nil {
|
||||
t.Fatalf("find restored folder: %v", err)
|
||||
}
|
||||
if !restored.IsDirectory() {
|
||||
t.Errorf("restored %s is not a directory", dir)
|
||||
}
|
||||
if restored.Mode.Perm() != 0700 {
|
||||
t.Errorf("restored folder should keep mode 0700, got %o", restored.Mode.Perm())
|
||||
}
|
||||
if restored.Uid != 4242 || restored.Gid != 4343 {
|
||||
t.Errorf("restored folder should keep its owner, got uid=%d gid=%d", restored.Uid, restored.Gid)
|
||||
}
|
||||
}
|
||||
|
||||
func listNames(ctx context.Context, t *testing.T, f *filer.Filer, dir util.FullPath) []string {
|
||||
t.Helper()
|
||||
entries, _, err := f.ListDirectoryEntries(ctx, dir, "", false, 100, "", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("list %s: %v", dir, err)
|
||||
}
|
||||
var names []string
|
||||
for _, entry := range entries {
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -116,8 +116,7 @@ func (store *UniversalRedisStore) DeleteEntry(ctx context.Context, fullpath util
|
||||
|
||||
func (store *UniversalRedisStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) (err error) {
|
||||
|
||||
dirListKey := genDirectoryListKey(string(fullpath))
|
||||
members, err := store.Client.SMembers(ctx, dirListKey).Result()
|
||||
members, err := store.Client.SMembers(ctx, genDirectoryListKey(string(fullpath))).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete folder %s : %v", fullpath, err)
|
||||
}
|
||||
@@ -132,10 +131,6 @@ func (store *UniversalRedisStore) DeleteFolderChildren(ctx context.Context, full
|
||||
store.Client.Del(ctx, genDirectoryListKey(string(path)))
|
||||
}
|
||||
|
||||
if _, err = store.Client.Del(ctx, dirListKey).Result(); err != nil {
|
||||
return fmt.Errorf("delete folder %s list: %v", fullpath, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -187,7 +182,6 @@ func (store *UniversalRedisStore) ListDirectoryEntries(ctx context.Context, dirP
|
||||
if err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "list %s : %v", path, err)
|
||||
if err == filer_pb.ErrNotFound {
|
||||
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
|
||||
err = nil
|
||||
continue
|
||||
}
|
||||
@@ -215,32 +209,6 @@ func (store *UniversalRedisStore) ListDirectoryEntries(ctx context.Context, dirP
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
func (store *UniversalRedisStore) removeOrphanedDirectoryListMember(ctx context.Context, dirPath util.FullPath, fileName string) {
|
||||
// survive the listing request being canceled mid-repair
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
|
||||
dirListKey := genDirectoryListKey(string(dirPath))
|
||||
path := util.NewFullPath(string(dirPath), fileName)
|
||||
|
||||
if _, err := store.Client.SRem(ctx, dirListKey, fileName).Result(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// a value present again here belongs to a concurrent recreate whose SAdd raced our SRem
|
||||
exists, err := store.Client.Exists(ctx, string(path)).Result()
|
||||
if err == nil && exists == 0 {
|
||||
// empty sets self-delete, so a present child index holds children a recursive delete still needs to reach
|
||||
children, childrenErr := store.Client.Exists(ctx, genDirectoryListKey(string(path))).Result()
|
||||
if childrenErr == nil && children == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := store.Client.SAdd(ctx, dirListKey, fileName).Err(); err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "restore %s in %s: %v", fileName, dirPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
func genDirectoryListKey(dir string) (dirList string) {
|
||||
return dir + DIR_LIST_MARKER
|
||||
}
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func newTestStore(t *testing.T) (*UniversalRedisStore, util.FullPath) {
|
||||
t.Helper()
|
||||
|
||||
if os.Getenv("RUN_REDIS_TESTS") != "1" {
|
||||
t.Skip("redis tests are disabled. Start a redis-server and set RUN_REDIS_TESTS=1 to enable, REDIS_ADDR defaults to 127.0.0.1:6379.")
|
||||
}
|
||||
|
||||
addr := os.Getenv("REDIS_ADDR")
|
||||
if addr == "" {
|
||||
addr = "127.0.0.1:6379"
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
client := redis.NewClient(&redis.Options{Addr: addr})
|
||||
t.Cleanup(func() {
|
||||
if err := client.Close(); err != nil {
|
||||
t.Errorf("close redis client: %v", err)
|
||||
}
|
||||
})
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
t.Fatalf("connect to redis at %s: %v", addr, err)
|
||||
}
|
||||
|
||||
store := &UniversalRedisStore{Client: client}
|
||||
|
||||
dir := util.FullPath(fmt.Sprintf("/redis_test_%d", time.Now().UnixNano()))
|
||||
t.Cleanup(func() {
|
||||
if err := store.DeleteFolderChildren(ctx, dir); err != nil {
|
||||
t.Errorf("cleanup %s children: %v", dir, err)
|
||||
}
|
||||
if err := store.DeleteEntry(ctx, dir); err != nil {
|
||||
t.Errorf("cleanup %s: %v", dir, err)
|
||||
}
|
||||
})
|
||||
|
||||
return store, dir
|
||||
}
|
||||
|
||||
func insertTestEntry(t *testing.T, store *UniversalRedisStore, path util.FullPath) {
|
||||
t.Helper()
|
||||
|
||||
now := time.Now()
|
||||
if err := store.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func listNames(t *testing.T, store *UniversalRedisStore, dir util.FullPath) []string {
|
||||
t.Helper()
|
||||
|
||||
names := []string{}
|
||||
if _, err := store.ListDirectoryEntries(context.Background(), dir, "", true, 100, func(entry *filer.Entry) (bool, error) {
|
||||
_, name := entry.DirAndName()
|
||||
names = append(names, name)
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
t.Fatalf("ListDirectoryEntries %s: %v", dir, err)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func indexMembers(t *testing.T, store *UniversalRedisStore, dir util.FullPath) []string {
|
||||
t.Helper()
|
||||
|
||||
members, err := store.Client.SMembers(context.Background(), genDirectoryListKey(string(dir))).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("read directory index of %s: %v", dir, err)
|
||||
}
|
||||
slices.Sort(members)
|
||||
return members
|
||||
}
|
||||
|
||||
func TestListDirectoryEntriesRemovesOrphanedIndexMembers(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
|
||||
insertTestEntry(t, store, dir.Child("alive"))
|
||||
insertTestEntry(t, store, dir.Child("orphan"))
|
||||
|
||||
if err := store.Client.Del(context.Background(), string(dir.Child("orphan"))).Err(); err != nil {
|
||||
t.Fatalf("drop value key: %v", err)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "alive" {
|
||||
t.Fatalf("listed %v, want [alive]", names)
|
||||
}
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "alive" {
|
||||
t.Fatalf("directory index holds %v, want [alive]", members)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveOrphanedDirectoryListMemberKeepsRecreatedEntry(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
|
||||
insertTestEntry(t, store, dir.Child("recreated"))
|
||||
|
||||
store.removeOrphanedDirectoryListMember(context.Background(), dir, "recreated")
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "recreated" {
|
||||
t.Fatalf("directory index holds %v, want [recreated]", members)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "recreated" {
|
||||
t.Fatalf("listed %v, want [recreated]", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveOrphanedDirectoryListMemberKeepsDirectoryWithChildren(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
|
||||
sub := dir.Child("sub")
|
||||
insertTestEntry(t, store, sub)
|
||||
insertTestEntry(t, store, sub.Child("kid"))
|
||||
defer func() {
|
||||
if err := store.DeleteFolderChildren(context.Background(), sub); err != nil {
|
||||
t.Errorf("cleanup %s children: %v", sub, err)
|
||||
}
|
||||
}()
|
||||
|
||||
// evict the directory's own value while its child index is live
|
||||
if err := store.Client.Del(context.Background(), string(sub)).Err(); err != nil {
|
||||
t.Fatalf("drop value key: %v", err)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 0 {
|
||||
t.Fatalf("listed %v, want none", names)
|
||||
}
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "sub" {
|
||||
t.Fatalf("directory index holds %v, want [sub]", members)
|
||||
}
|
||||
|
||||
if exists, err := store.Client.Exists(context.Background(), string(sub.Child("kid"))).Result(); err != nil || exists != 1 {
|
||||
t.Fatalf("child value key exists=%d err=%v, want it kept", exists, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteFolderChildrenRemovesTheListing(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
insertTestEntry(t, store, dir.Child("obj"))
|
||||
|
||||
// The directory entry going away must not take the listing with it; nothing
|
||||
// else records that the child is under this directory.
|
||||
if err := store.DeleteEntry(ctx, dir); err != nil {
|
||||
t.Fatalf("DeleteEntry %s: %v", dir, err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "obj" {
|
||||
t.Errorf("child should still be listed after the directory entry is deleted, got %v", names)
|
||||
}
|
||||
|
||||
// Deleting the children takes the listing with them, rather than leaving it behind.
|
||||
if err := store.DeleteFolderChildren(ctx, dir); err != nil {
|
||||
t.Fatalf("DeleteFolderChildren %s: %v", dir, err)
|
||||
}
|
||||
if n, err := store.Client.Exists(ctx, genDirectoryListKey(string(dir))).Result(); err != nil {
|
||||
t.Fatalf("exists %s: %v", dir, err)
|
||||
} else if n != 0 {
|
||||
t.Errorf("listing key should be removed with the children, still present")
|
||||
}
|
||||
}
|
||||
@@ -118,10 +118,11 @@ func (store *UniversalRedis2Store) FindEntry(ctx context.Context, fullpath util.
|
||||
|
||||
func (store *UniversalRedis2Store) DeleteEntry(ctx context.Context, fullpath util.FullPath) (err error) {
|
||||
|
||||
// The child listing is dropped by DeleteFolderChildren, together with the
|
||||
// children it describes. Dropping it here would also discard an entry that
|
||||
// arrived after the caller judged this directory empty, and nothing else
|
||||
// records that the entry is there.
|
||||
_, err = store.Client.Del(ctx, store.getKey(genDirectoryListKey(string(fullpath)))).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete dir list %s : %v", fullpath, err)
|
||||
}
|
||||
|
||||
_, err = store.Client.Del(ctx, store.getKey(string(fullpath))).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
@@ -147,8 +148,7 @@ func (store *UniversalRedis2Store) DeleteFolderChildren(ctx context.Context, ful
|
||||
return nil
|
||||
}
|
||||
|
||||
dirListKey := store.getKey(genDirectoryListKey(string(fullpath)))
|
||||
members, err := store.Client.ZRangeByLex(ctx, dirListKey, &redis.ZRangeBy{
|
||||
members, err := store.Client.ZRangeByLex(ctx, store.getKey(genDirectoryListKey(string(fullpath))), &redis.ZRangeBy{
|
||||
Min: "-",
|
||||
Max: "+",
|
||||
}).Result()
|
||||
@@ -166,10 +166,6 @@ func (store *UniversalRedis2Store) DeleteFolderChildren(ctx context.Context, ful
|
||||
store.Client.Del(ctx, store.getKey(genDirectoryListKey(string(path))))
|
||||
}
|
||||
|
||||
if _, err = store.Client.Del(ctx, dirListKey).Result(); err != nil {
|
||||
return fmt.Errorf("DeleteFolderChildren %s list: %v", fullpath, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -209,15 +205,17 @@ func (store *UniversalRedis2Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
if err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "list %s : %v", path, err)
|
||||
if err == filer_pb.ErrNotFound {
|
||||
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
|
||||
err = nil
|
||||
continue
|
||||
}
|
||||
break
|
||||
} else {
|
||||
if isLogicallyExpired(entry) {
|
||||
store.deleteExpiredEntry(ctx, dirPath, path, fileName)
|
||||
continue
|
||||
if entry.TtlSec > 0 {
|
||||
if entry.Attr.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
|
||||
store.Client.Del(ctx, store.getKey(string(path))).Result()
|
||||
store.Client.ZRem(ctx, dirListKey, fileName).Result()
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
resEachEntryFunc, resEachEntryFuncErr := eachEntryFunc(entry)
|
||||
@@ -235,99 +233,6 @@ func (store *UniversalRedis2Store) ListDirectoryEntries(ctx context.Context, dir
|
||||
return lastFileName, err
|
||||
}
|
||||
|
||||
func (store *UniversalRedis2Store) removeOrphanedDirectoryListMember(ctx context.Context, dirPath util.FullPath, fileName string) {
|
||||
// a directory converted to super large after accumulating members still has a legacy index
|
||||
if store.isSuperLargeDirectory(string(dirPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
// survive the listing request being canceled mid-repair
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
|
||||
dirListKey := store.getKey(genDirectoryListKey(string(dirPath)))
|
||||
path := util.NewFullPath(string(dirPath), fileName)
|
||||
|
||||
if err := store.Client.ZRem(ctx, dirListKey, fileName).Err(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// InsertEntry writes the value before adding the member, so a value present
|
||||
// again here may belong to an insert that found the member still in place
|
||||
// and whose ZAddNX was therefore a no-op.
|
||||
exists, err := store.existsOnMaster(ctx, store.getKey(string(path)))
|
||||
if err == nil && exists == 0 {
|
||||
// an evicted directory may still have a live child index; empty zsets self-delete,
|
||||
// so a present index holds children a recursive delete still needs to reach
|
||||
children, childrenErr := store.existsOnMaster(ctx, store.getKey(genDirectoryListKey(string(path))))
|
||||
if childrenErr == nil && children == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := store.Client.ZAddNX(ctx, dirListKey, redis.Z{Score: 0, Member: fileName}).Err(); err != nil {
|
||||
glog.V(0).InfofCtx(ctx, "restore %s in %s: %v", fileName, dirPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
var existsScript = redis.NewScript(`return redis.call('EXISTS', KEYS[1])`)
|
||||
|
||||
// replica-routed clients (useReadOnly, routeByLatency) would run a plain EXISTS on a lagging
|
||||
// replica and misread a live value as absent, turning the repair destructive; a script always
|
||||
// runs on the key's master
|
||||
func (store *UniversalRedis2Store) existsOnMaster(ctx context.Context, key string) (int64, error) {
|
||||
return existsScript.Run(ctx, store.Client, []string{key}).Int64()
|
||||
}
|
||||
|
||||
func isLogicallyExpired(entry *filer.Entry) bool {
|
||||
return entry.TtlSec > 0 && entry.Attr.Crtime.Add(time.Duration(entry.TtlSec)*time.Second).Before(time.Now())
|
||||
}
|
||||
|
||||
// deletes the value only when it still holds exactly the bytes the expiry decision was made on;
|
||||
// single-key, so it runs on all transports where a multi-key script would be CROSSSLOT.
|
||||
// -1: already gone, 0: changed under us, 1: deleted
|
||||
var deleteIfUnchangedScript = redis.NewScript(`
|
||||
local v = redis.call('GET', KEYS[1])
|
||||
if v == false then
|
||||
return -1
|
||||
end
|
||||
if v == ARGV[1] then
|
||||
return redis.call('DEL', KEYS[1])
|
||||
end
|
||||
return 0`)
|
||||
|
||||
func (store *UniversalRedis2Store) deleteExpiredEntry(ctx context.Context, dirPath util.FullPath, path util.FullPath, fileName string) {
|
||||
// survive the listing request being canceled mid-delete
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
valueKey := store.getKey(string(path))
|
||||
|
||||
// re-read so the delete can be conditioned on exactly the bytes checked
|
||||
data, err := store.Client.Get(ctx, valueKey).Bytes()
|
||||
if err == redis.Nil {
|
||||
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
entry := &filer.Entry{FullPath: path}
|
||||
if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
|
||||
return
|
||||
}
|
||||
if !isLogicallyExpired(entry) {
|
||||
// a concurrent insert recreated it
|
||||
return
|
||||
}
|
||||
|
||||
// 0 means a concurrent recreate changed the value: keep it. -1 means the redis
|
||||
// TTL won after the re-read: the member still needs the not-found repair.
|
||||
deleted, err := deleteIfUnchangedScript.Run(ctx, store.Client, []string{valueKey}, data).Int()
|
||||
if err != nil || deleted == 0 {
|
||||
return
|
||||
}
|
||||
store.removeOrphanedDirectoryListMember(ctx, dirPath, fileName)
|
||||
}
|
||||
|
||||
func genDirectoryListKey(dir string) (dirList string) {
|
||||
return dir + DIR_LIST_MARKER
|
||||
}
|
||||
|
||||
@@ -1,331 +0,0 @@
|
||||
package redis2
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func newTestStore(t *testing.T, keyPrefix string) (*UniversalRedis2Store, util.FullPath) {
|
||||
t.Helper()
|
||||
|
||||
if os.Getenv("RUN_REDIS_TESTS") != "1" {
|
||||
t.Skip("redis2 tests are disabled. Start a redis-server and set RUN_REDIS_TESTS=1 to enable, REDIS_ADDR defaults to 127.0.0.1:6379.")
|
||||
}
|
||||
|
||||
addr := os.Getenv("REDIS_ADDR")
|
||||
if addr == "" {
|
||||
addr = "127.0.0.1:6379"
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
client := redis.NewClient(&redis.Options{Addr: addr})
|
||||
t.Cleanup(func() {
|
||||
if err := client.Close(); err != nil {
|
||||
t.Errorf("close redis client: %v", err)
|
||||
}
|
||||
})
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
t.Fatalf("connect to redis at %s: %v", addr, err)
|
||||
}
|
||||
|
||||
store := &UniversalRedis2Store{Client: client, keyPrefix: keyPrefix}
|
||||
|
||||
dir := util.FullPath(fmt.Sprintf("/redis2_test_%d", time.Now().UnixNano()))
|
||||
t.Cleanup(func() {
|
||||
if err := store.DeleteFolderChildren(ctx, dir); err != nil {
|
||||
t.Errorf("cleanup %s children: %v", dir, err)
|
||||
}
|
||||
if err := store.DeleteEntry(ctx, dir); err != nil {
|
||||
t.Errorf("cleanup %s: %v", dir, err)
|
||||
}
|
||||
})
|
||||
|
||||
return store, dir
|
||||
}
|
||||
|
||||
func insertTestEntry(t *testing.T, store *UniversalRedis2Store, path util.FullPath, ttlSec int32) {
|
||||
t.Helper()
|
||||
|
||||
now := time.Now()
|
||||
if err := store.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644, TtlSec: ttlSec},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func listNames(t *testing.T, store *UniversalRedis2Store, dir util.FullPath) []string {
|
||||
t.Helper()
|
||||
|
||||
names := []string{}
|
||||
if _, err := store.ListDirectoryEntries(context.Background(), dir, "", true, 100, func(entry *filer.Entry) (bool, error) {
|
||||
_, name := entry.DirAndName()
|
||||
names = append(names, name)
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
t.Fatalf("ListDirectoryEntries %s: %v", dir, err)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func indexMembers(t *testing.T, store *UniversalRedis2Store, dir util.FullPath) []string {
|
||||
t.Helper()
|
||||
|
||||
members, err := store.Client.ZRangeByLex(context.Background(), store.getKey(genDirectoryListKey(string(dir))), &redis.ZRangeBy{Min: "-", Max: "+"}).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("read directory index of %s: %v", dir, err)
|
||||
}
|
||||
return members
|
||||
}
|
||||
|
||||
func TestListDirectoryEntriesRemovesOrphanedIndexMembers(t *testing.T) {
|
||||
for _, keyPrefix := range []string{"", "sw:"} {
|
||||
t.Run("keyPrefix="+keyPrefix, func(t *testing.T) {
|
||||
store, dir := newTestStore(t, keyPrefix)
|
||||
|
||||
insertTestEntry(t, store, dir.Child("alive"), 0)
|
||||
insertTestEntry(t, store, dir.Child("orphan"), 0)
|
||||
|
||||
if err := store.Client.Del(context.Background(), store.getKey(string(dir.Child("orphan")))).Err(); err != nil {
|
||||
t.Fatalf("drop value key: %v", err)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "alive" {
|
||||
t.Fatalf("listed %v, want [alive]", names)
|
||||
}
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "alive" {
|
||||
t.Fatalf("directory index holds %v, want [alive]", members)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveOrphanedDirectoryListMemberKeepsRecreatedEntry(t *testing.T) {
|
||||
for _, keyPrefix := range []string{"", "sw:"} {
|
||||
t.Run("keyPrefix="+keyPrefix, func(t *testing.T) {
|
||||
store, dir := newTestStore(t, keyPrefix)
|
||||
|
||||
path := dir.Child("recreated")
|
||||
insertTestEntry(t, store, path, 0)
|
||||
|
||||
store.removeOrphanedDirectoryListMember(context.Background(), dir, "recreated")
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "recreated" {
|
||||
t.Fatalf("directory index holds %v, want [recreated]", members)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "recreated" {
|
||||
t.Fatalf("listed %v, want [recreated]", names)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveOrphanedDirectoryListMemberKeepsDirectoryWithChildren(t *testing.T) {
|
||||
for _, keyPrefix := range []string{"", "sw:"} {
|
||||
t.Run("keyPrefix="+keyPrefix, func(t *testing.T) {
|
||||
store, dir := newTestStore(t, keyPrefix)
|
||||
|
||||
sub := dir.Child("sub")
|
||||
insertTestEntry(t, store, sub, 0)
|
||||
insertTestEntry(t, store, sub.Child("kid"), 0)
|
||||
defer func() {
|
||||
if err := store.DeleteFolderChildren(context.Background(), sub); err != nil {
|
||||
t.Errorf("cleanup %s children: %v", sub, err)
|
||||
}
|
||||
}()
|
||||
|
||||
// evict the directory's own value while its child index is live
|
||||
if err := store.Client.Del(context.Background(), store.getKey(string(sub))).Err(); err != nil {
|
||||
t.Fatalf("drop value key: %v", err)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 0 {
|
||||
t.Fatalf("listed %v, want none", names)
|
||||
}
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "sub" {
|
||||
t.Fatalf("directory index holds %v, want [sub]", members)
|
||||
}
|
||||
|
||||
if exists, err := store.Client.Exists(context.Background(), store.getKey(string(sub.Child("kid")))).Result(); err != nil || exists != 1 {
|
||||
t.Fatalf("child value key exists=%d err=%v, want it kept", exists, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveOrphanedDirectoryListMemberSkipsSuperLargeDirectory(t *testing.T) {
|
||||
store, dir := newTestStore(t, "")
|
||||
store.loadSuperLargeDirectories([]string{string(dir)})
|
||||
|
||||
// a member left from before the directory became super large
|
||||
if err := store.Client.ZAdd(context.Background(), store.getKey(genDirectoryListKey(string(dir))), redis.Z{Score: 0, Member: "legacy"}).Err(); err != nil {
|
||||
t.Fatalf("plant legacy member: %v", err)
|
||||
}
|
||||
|
||||
store.removeOrphanedDirectoryListMember(context.Background(), dir, "legacy")
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "legacy" {
|
||||
t.Fatalf("directory index holds %v, want [legacy] untouched", members)
|
||||
}
|
||||
}
|
||||
|
||||
func requireValueKey(t *testing.T, store *UniversalRedis2Store, path util.FullPath) {
|
||||
t.Helper()
|
||||
|
||||
if exists, err := store.Client.Exists(context.Background(), store.getKey(string(path))).Result(); err != nil || exists != 1 {
|
||||
t.Fatalf("value key %s exists=%d err=%v, want it present", path, exists, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDirectoryEntriesRemovesIndexMembersExpiredByRedis(t *testing.T) {
|
||||
store, dir := newTestStore(t, "")
|
||||
|
||||
insertTestEntry(t, store, dir.Child("ttl"), 1)
|
||||
requireValueKey(t, store, dir.Child("ttl"))
|
||||
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
exists, err := store.Client.Exists(context.Background(), store.getKey(string(dir.Child("ttl")))).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("check value key: %v", err)
|
||||
}
|
||||
if exists == 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("redis did not expire the value key, the logical expiry path is not being bypassed")
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 0 {
|
||||
t.Fatalf("listed %v, want none", names)
|
||||
}
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 0 {
|
||||
t.Fatalf("directory index holds %v, want none", members)
|
||||
}
|
||||
}
|
||||
|
||||
// logically expired (Crtime + TtlSec long past) while the physical key survives,
|
||||
// because the redis TTL re-arms from the SET time
|
||||
func insertLogicallyExpiredTestEntry(t *testing.T, store *UniversalRedis2Store, path util.FullPath) {
|
||||
t.Helper()
|
||||
|
||||
created := time.Now().Add(-time.Hour)
|
||||
if err := store.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: path,
|
||||
Attr: filer.Attr{Crtime: created, Mtime: created, Mode: 0644, TtlSec: 60},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDirectoryEntriesDeletesLogicallyExpiredEntries(t *testing.T) {
|
||||
for _, keyPrefix := range []string{"", "sw:"} {
|
||||
t.Run("keyPrefix="+keyPrefix, func(t *testing.T) {
|
||||
store, dir := newTestStore(t, keyPrefix)
|
||||
|
||||
insertLogicallyExpiredTestEntry(t, store, dir.Child("stale"))
|
||||
requireValueKey(t, store, dir.Child("stale"))
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 0 {
|
||||
t.Fatalf("listed %v, want none", names)
|
||||
}
|
||||
|
||||
if exists, err := store.Client.Exists(context.Background(), store.getKey(string(dir.Child("stale")))).Result(); err != nil || exists != 0 {
|
||||
t.Fatalf("value key exists=%d err=%v, want it deleted", exists, err)
|
||||
}
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 0 {
|
||||
t.Fatalf("directory index holds %v, want none", members)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteExpiredEntryKeepsRecreatedValue(t *testing.T) {
|
||||
store, dir := newTestStore(t, "")
|
||||
|
||||
path := dir.Child("phoenix")
|
||||
insertLogicallyExpiredTestEntry(t, store, path)
|
||||
// a recreate lands after the lister decided to expire the old value
|
||||
insertTestEntry(t, store, path, 0)
|
||||
|
||||
store.deleteExpiredEntry(context.Background(), dir, path, "phoenix")
|
||||
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "phoenix" {
|
||||
t.Fatalf("listed %v, want [phoenix]", names)
|
||||
}
|
||||
|
||||
if members := indexMembers(t, store, dir); len(members) != 1 || members[0] != "phoenix" {
|
||||
t.Fatalf("directory index holds %v, want [phoenix]", members)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteIfUnchangedScriptOnlyDeletesSameBytes(t *testing.T) {
|
||||
store, dir := newTestStore(t, "")
|
||||
|
||||
key := store.getKey(string(dir.Child("guarded")))
|
||||
if err := store.Client.Set(context.Background(), key, "v1", 0).Err(); err != nil {
|
||||
t.Fatalf("set: %v", err)
|
||||
}
|
||||
|
||||
if deleted, err := deleteIfUnchangedScript.Run(context.Background(), store.Client, []string{key}, []byte("v2")).Int(); err != nil || deleted != 0 {
|
||||
t.Fatalf("deleted=%d err=%v, want no delete on changed bytes", deleted, err)
|
||||
}
|
||||
|
||||
if deleted, err := deleteIfUnchangedScript.Run(context.Background(), store.Client, []string{key}, []byte("v1")).Int(); err != nil || deleted != 1 {
|
||||
t.Fatalf("deleted=%d err=%v, want delete on matching bytes", deleted, err)
|
||||
}
|
||||
|
||||
if exists, err := store.Client.Exists(context.Background(), key).Result(); err != nil || exists != 0 {
|
||||
t.Fatalf("exists=%d err=%v, want key gone", exists, err)
|
||||
}
|
||||
|
||||
if deleted, err := deleteIfUnchangedScript.Run(context.Background(), store.Client, []string{key}, []byte("v1")).Int(); err != nil || deleted != -1 {
|
||||
t.Fatalf("deleted=%d err=%v, want -1 on a missing key", deleted, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteEntryKeepsChildListing(t *testing.T) {
|
||||
store, dir := newTestStore(t, "")
|
||||
ctx := context.Background()
|
||||
|
||||
insertTestEntry(t, store, dir.Child("obj"), 0)
|
||||
|
||||
// The listing is the only record that the child sits under this directory, so
|
||||
// removing the directory entry must leave it alone. An entry that arrived after
|
||||
// the caller judged the directory empty would otherwise become unreachable.
|
||||
if err := store.DeleteEntry(ctx, dir); err != nil {
|
||||
t.Fatalf("DeleteEntry %s: %v", dir, err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "obj" {
|
||||
t.Errorf("child should still be listed after the directory entry is deleted, got %v", names)
|
||||
}
|
||||
|
||||
// DeleteFolderChildren owns that cleanup, and takes the listing with it
|
||||
if err := store.DeleteFolderChildren(ctx, dir); err != nil {
|
||||
t.Fatalf("DeleteFolderChildren %s: %v", dir, err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 0 {
|
||||
t.Errorf("listing should be empty once the children are deleted, got %v", names)
|
||||
}
|
||||
if n, err := store.Client.Exists(ctx, store.getKey(genDirectoryListKey(string(dir)))).Result(); err != nil {
|
||||
t.Fatalf("exists %s: %v", dir, err)
|
||||
} else if n != 0 {
|
||||
t.Errorf("listing key should be removed with the children, still present")
|
||||
}
|
||||
}
|
||||
@@ -342,10 +342,6 @@ func (nl *ItemList) ListNames(startFrom string, visitNamesFn func(name string) b
|
||||
return nil
|
||||
}
|
||||
|
||||
func (nl *ItemList) IsEmpty() bool {
|
||||
return nl.skipList.StartLevels[0] == nil
|
||||
}
|
||||
|
||||
func (nl *ItemList) RemoteAllListElement() error {
|
||||
|
||||
t := nl.skipList
|
||||
|
||||
@@ -70,21 +70,9 @@ func removeChild(ctx context.Context, redisStore *UniversalRedis3Store, key stri
|
||||
return err
|
||||
}
|
||||
if !nameList.HasChanges() {
|
||||
// Nothing to remove. If the list is empty anyway, its header outlived the
|
||||
// removal of the last name - a delete that failed here before - so take it
|
||||
// now rather than leaving the key behind for good.
|
||||
if nameList.IsEmpty() {
|
||||
return client.Del(ctx, key).Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// An emptied list reads the same as no list at all, and keeping the header would
|
||||
// leave a key behind for every directory that is emptied.
|
||||
if nameList.IsEmpty() {
|
||||
return client.Del(ctx, key).Err()
|
||||
}
|
||||
|
||||
if err := client.Set(ctx, key, nameList.ToBytes(), 0).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -95,10 +95,11 @@ func (store *UniversalRedis3Store) FindEntry(ctx context.Context, fullpath util.
|
||||
|
||||
func (store *UniversalRedis3Store) DeleteEntry(ctx context.Context, fullpath util.FullPath) (err error) {
|
||||
|
||||
// The child listing is dropped by DeleteFolderChildren, together with the
|
||||
// children it describes. Dropping it here would also discard an entry that
|
||||
// arrived after the caller judged this directory empty, and nothing else
|
||||
// records that the entry is there.
|
||||
_, err = store.Client.Del(ctx, genDirectoryListKey(string(fullpath))).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete dir list %s : %v", fullpath, err)
|
||||
}
|
||||
|
||||
_, err = store.Client.Del(ctx, string(fullpath)).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s : %v", fullpath, err)
|
||||
@@ -117,8 +118,7 @@ func (store *UniversalRedis3Store) DeleteEntry(ctx context.Context, fullpath uti
|
||||
|
||||
func (store *UniversalRedis3Store) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) (err error) {
|
||||
|
||||
dirListKey := genDirectoryListKey(string(fullpath))
|
||||
if err = removeChildren(ctx, store, dirListKey, func(name string) error {
|
||||
return removeChildren(ctx, store, genDirectoryListKey(string(fullpath)), func(name string) error {
|
||||
path := util.NewFullPath(string(fullpath), name)
|
||||
_, err = store.Client.Del(ctx, string(path)).Result()
|
||||
if err != nil {
|
||||
@@ -127,16 +127,8 @@ func (store *UniversalRedis3Store) DeleteFolderChildren(ctx context.Context, ful
|
||||
// not efficient, but need to remove if it is a directory
|
||||
store.Client.Del(ctx, genDirectoryListKey(string(path)))
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
})
|
||||
|
||||
// removeChildren clears the skip list nodes but leaves the list itself behind
|
||||
if _, err = store.Client.Del(ctx, dirListKey).Result(); err != nil {
|
||||
return fmt.Errorf("DeleteFolderChildren %s list: %v", fullpath, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *UniversalRedis3Store) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
package redis3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-redsync/redsync/v4"
|
||||
goredis "github.com/go-redsync/redsync/v4/redis/goredis/v9"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func newTestStore(t *testing.T) (*UniversalRedis3Store, util.FullPath) {
|
||||
t.Helper()
|
||||
|
||||
if os.Getenv("RUN_REDIS_TESTS") != "1" {
|
||||
t.Skip("redis3 tests are disabled. Start a redis-server and set RUN_REDIS_TESTS=1 to enable, REDIS_ADDR defaults to 127.0.0.1:6379.")
|
||||
}
|
||||
|
||||
addr := os.Getenv("REDIS_ADDR")
|
||||
if addr == "" {
|
||||
addr = "127.0.0.1:6379"
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
client := redis.NewClient(&redis.Options{Addr: addr})
|
||||
t.Cleanup(func() {
|
||||
if err := client.Close(); err != nil {
|
||||
t.Errorf("close redis client: %v", err)
|
||||
}
|
||||
})
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
t.Fatalf("connect to redis at %s: %v", addr, err)
|
||||
}
|
||||
|
||||
store := &UniversalRedis3Store{Client: client, redsync: redsync.New(goredis.NewPool(client))}
|
||||
|
||||
dir := util.FullPath(fmt.Sprintf("/redis3_test_%d", time.Now().UnixNano()))
|
||||
t.Cleanup(func() {
|
||||
if err := store.DeleteFolderChildren(ctx, dir); err != nil {
|
||||
t.Errorf("cleanup %s children: %v", dir, err)
|
||||
}
|
||||
if err := store.DeleteEntry(ctx, dir); err != nil {
|
||||
t.Errorf("cleanup %s: %v", dir, err)
|
||||
}
|
||||
})
|
||||
|
||||
return store, dir
|
||||
}
|
||||
|
||||
func listNames(t *testing.T, store *UniversalRedis3Store, dir util.FullPath) []string {
|
||||
t.Helper()
|
||||
|
||||
names := []string{}
|
||||
if _, err := store.ListDirectoryEntries(context.Background(), dir, "", true, 100, func(entry *filer.Entry) (bool, error) {
|
||||
names = append(names, entry.Name())
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
t.Fatalf("list %s: %v", dir, err)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestDeleteEntryKeepsChildListing(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
now := time.Now()
|
||||
child := dir.Child("obj")
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{
|
||||
FullPath: child,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", child, err)
|
||||
}
|
||||
|
||||
// The listing is the only record that the child sits under this directory, so
|
||||
// removing the directory entry must leave it alone. An entry that arrived after
|
||||
// the caller judged the directory empty would otherwise become unreachable.
|
||||
if err := store.DeleteEntry(ctx, dir); err != nil {
|
||||
t.Fatalf("DeleteEntry %s: %v", dir, err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 1 || names[0] != "obj" {
|
||||
t.Errorf("child should still be listed after the directory entry is deleted, got %v", names)
|
||||
}
|
||||
|
||||
// DeleteFolderChildren owns that cleanup, and takes the listing with it
|
||||
if err := store.DeleteFolderChildren(ctx, dir); err != nil {
|
||||
t.Fatalf("DeleteFolderChildren %s: %v", dir, err)
|
||||
}
|
||||
if names := listNames(t, store, dir); len(names) != 0 {
|
||||
t.Errorf("listing should be empty once the children are deleted, got %v", names)
|
||||
}
|
||||
if n, err := store.Client.Exists(ctx, genDirectoryListKey(string(dir))).Result(); err != nil {
|
||||
t.Fatalf("exists %s: %v", dir, err)
|
||||
} else if n != 0 {
|
||||
t.Errorf("listing key should be removed with the children, still present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemovingTheLastChildDropsTheListing(t *testing.T) {
|
||||
store, dir := newTestStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
now := time.Now()
|
||||
child := dir.Child("obj")
|
||||
if err := store.InsertEntry(ctx, &filer.Entry{
|
||||
FullPath: child,
|
||||
Attr: filer.Attr{Crtime: now, Mtime: now, Mode: 0644},
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertEntry %s: %v", child, err)
|
||||
}
|
||||
|
||||
// An emptied listing must not leave its header behind: cleanup deletes such a
|
||||
// folder without touching the listing, so the key would never be collected.
|
||||
if err := store.DeleteEntry(ctx, child); err != nil {
|
||||
t.Fatalf("DeleteEntry %s: %v", child, err)
|
||||
}
|
||||
if n, err := store.Client.Exists(ctx, genDirectoryListKey(string(dir))).Result(); err != nil {
|
||||
t.Fatalf("exists %s: %v", dir, err)
|
||||
} else if n != 0 {
|
||||
t.Errorf("listing key should be gone once the last child is removed, still present")
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package filer
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -12,21 +11,6 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// FindMountedRemoteMapping returns the mount point covering dir and its remote
|
||||
// location. Matches on path components so a sibling name sharing a prefix does
|
||||
// not collide, and the longest mount wins when mounts nest.
|
||||
func FindMountedRemoteMapping(mappings *remote_pb.RemoteStorageMapping, dir string) (localMountedDir string, remoteStorageMountedLocation *remote_pb.RemoteStorageLocation, err error) {
|
||||
for k, loc := range mappings.Mappings {
|
||||
if (dir == k || strings.HasPrefix(dir, strings.TrimSuffix(k, "/")+"/")) && len(k) > len(localMountedDir) {
|
||||
localMountedDir, remoteStorageMountedLocation = k, loc
|
||||
}
|
||||
}
|
||||
if localMountedDir == "" {
|
||||
return "", nil, fmt.Errorf("%s is not mounted", dir)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func ReadMountMappings(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress) (mappings *remote_pb.RemoteStorageMapping, readErr error) {
|
||||
var oldContent []byte
|
||||
if readErr = pb.WithFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFindMountedRemoteMapping(t *testing.T) {
|
||||
mappings := &remote_pb.RemoteStorageMapping{
|
||||
Mappings: map[string]*remote_pb.RemoteStorageLocation{
|
||||
"/buckets/b": {Name: "outer"},
|
||||
"/buckets/b/sub": {Name: "inner"},
|
||||
"/buckets/foo": {Name: "foo"},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
dir string
|
||||
wantMount string
|
||||
wantName string
|
||||
wantErr bool
|
||||
}{
|
||||
{dir: "/buckets/b", wantMount: "/buckets/b", wantName: "outer"},
|
||||
{dir: "/buckets/b/other", wantMount: "/buckets/b", wantName: "outer"},
|
||||
{dir: "/buckets/b/sub", wantMount: "/buckets/b/sub", wantName: "inner"},
|
||||
{dir: "/buckets/b/sub/deep", wantMount: "/buckets/b/sub", wantName: "inner"},
|
||||
{dir: "/buckets/foo/x", wantMount: "/buckets/foo", wantName: "foo"},
|
||||
// a sibling sharing a name prefix is not under the mount
|
||||
{dir: "/buckets/foobar", wantErr: true},
|
||||
{dir: "/buckets/other", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.dir, func(t *testing.T) {
|
||||
mount, loc, err := FindMountedRemoteMapping(mappings, tt.dir)
|
||||
if tt.wantErr {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tt.wantMount, mount)
|
||||
assert.Equal(t, tt.wantName, loc.Name)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -164,9 +164,15 @@ func DetectMountInfo(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddre
|
||||
return mappings, "", nil, nil, fmt.Errorf("need to specify '-dir' option")
|
||||
}
|
||||
|
||||
localMountedDir, remoteStorageMountedLocation, findErr := FindMountedRemoteMapping(mappings, dir)
|
||||
if findErr != nil {
|
||||
return mappings, localMountedDir, remoteStorageMountedLocation, nil, findErr
|
||||
var localMountedDir string
|
||||
var remoteStorageMountedLocation *remote_pb.RemoteStorageLocation
|
||||
for k, loc := range mappings.Mappings {
|
||||
if strings.HasPrefix(dir, k) {
|
||||
localMountedDir, remoteStorageMountedLocation = k, loc
|
||||
}
|
||||
}
|
||||
if localMountedDir == "" {
|
||||
return mappings, localMountedDir, remoteStorageMountedLocation, nil, fmt.Errorf("%s is not mounted", dir)
|
||||
}
|
||||
|
||||
// find remote storage configuration
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package sts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
@@ -67,34 +66,3 @@ func TestTemporaryCredentialFormat(t *testing.T) {
|
||||
// Verify session token is not empty
|
||||
assert.NotEmpty(t, cred.SessionToken)
|
||||
}
|
||||
|
||||
// A duration that came from configuration is bounded the same as one from a
|
||||
// request: the catalog passes -s3.iceberg.credentialDurationSeconds straight
|
||||
// through.
|
||||
func TestAssumeRoleForPrincipalValidatesDuration(t *testing.T) {
|
||||
svc := NewSTSService()
|
||||
err := svc.Initialize(&STSConfig{
|
||||
TokenDuration: FlexibleDuration{time.Hour},
|
||||
MaxSessionLength: FlexibleDuration{12 * time.Hour},
|
||||
Issuer: "test-issuer",
|
||||
SigningKey: []byte("test-signing-key-at-least-32-bytes-long"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Initialize() error = %v", err)
|
||||
}
|
||||
|
||||
for _, seconds := range []int64{60, 100000} {
|
||||
duration := seconds
|
||||
_, err := svc.AssumeRoleForPrincipal(context.Background(), &AssumeRoleForPrincipalRequest{
|
||||
RoleArn: "arn:aws:iam::role/IcebergTableAccess",
|
||||
Principal: "admin",
|
||||
DurationSeconds: &duration,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("AssumeRoleForPrincipal(%ds) error = nil, want a validation error", seconds)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "DurationSeconds") {
|
||||
t.Errorf("AssumeRoleForPrincipal(%ds) error = %v, want it to name DurationSeconds", seconds, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
-99
@@ -754,20 +754,12 @@ func (s *STSService) AssumeRoleWithCredentials(ctx context.Context, request *Ass
|
||||
return nil, fmt.Errorf("role assumption denied: %w", err)
|
||||
}
|
||||
|
||||
// 4-7. Mint the session. For credential-based auth there is no source token
|
||||
// with an expiration to cap the duration against.
|
||||
return s.issueSession(request.RoleArn, request.RoleSessionName, sessionPolicy,
|
||||
request.DurationSeconds, nil, provider.Name(), externalIdentity.UserID)
|
||||
}
|
||||
|
||||
// issueSession mints temporary credentials and the self-contained JWT that
|
||||
// carries the whole session, shared by every assume-role entry point.
|
||||
func (s *STSService) issueSession(roleArn, roleSessionName, sessionPolicy string,
|
||||
durationSeconds *int64, tokenExpiration *time.Time, providerName, subject string) (*AssumeRoleResponse, error) {
|
||||
|
||||
sessionDuration := s.calculateSessionDuration(durationSeconds, tokenExpiration)
|
||||
// 4. Calculate session duration
|
||||
// For credential-based auth, there's no source token with expiration to cap against
|
||||
sessionDuration := s.calculateSessionDuration(request.DurationSeconds, nil)
|
||||
expiresAt := time.Now().Add(sessionDuration)
|
||||
|
||||
// 5. Generate session ID and temporary credentials
|
||||
sessionId, err := GenerateSessionId()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate session ID: %w", err)
|
||||
@@ -779,112 +771,38 @@ func (s *STSService) issueSession(roleArn, roleSessionName, sessionPolicy string
|
||||
return nil, fmt.Errorf("failed to generate credentials: %w", err)
|
||||
}
|
||||
|
||||
// 6. Create comprehensive JWT session token with all session information embedded
|
||||
assumedRoleUser := &AssumedRoleUser{
|
||||
AssumedRoleId: roleArn,
|
||||
Arn: GenerateAssumedRoleArn(roleArn, roleSessionName),
|
||||
Subject: subject,
|
||||
AssumedRoleId: request.RoleArn,
|
||||
Arn: GenerateAssumedRoleArn(request.RoleArn, request.RoleSessionName),
|
||||
Subject: externalIdentity.UserID,
|
||||
}
|
||||
|
||||
// Create rich JWT claims with all session information
|
||||
sessionClaims := NewSTSSessionClaims(sessionId, s.Config.Issuer, expiresAt).
|
||||
WithSessionName(roleSessionName).
|
||||
WithRoleInfo(roleArn, assumedRoleUser.Arn, assumedRoleUser.Arn).
|
||||
WithIdentityProvider(providerName, subject, "").
|
||||
WithSessionName(request.RoleSessionName).
|
||||
WithRoleInfo(request.RoleArn, assumedRoleUser.Arn, assumedRoleUser.Arn).
|
||||
WithIdentityProvider(provider.Name(), externalIdentity.UserID, "").
|
||||
WithMaxDuration(sessionDuration)
|
||||
if sessionPolicy != "" {
|
||||
sessionClaims.WithSessionPolicy(sessionPolicy)
|
||||
}
|
||||
|
||||
// Generate self-contained JWT token with all session information
|
||||
jwtToken, err := s.tokenGenerator.GenerateJWTWithClaims(sessionClaims)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate JWT session token: %w", err)
|
||||
}
|
||||
tempCredentials.SessionToken = jwtToken
|
||||
|
||||
// 7. Build and return response (no session storage needed!)
|
||||
|
||||
return &AssumeRoleResponse{
|
||||
Credentials: tempCredentials,
|
||||
AssumedRoleUser: assumedRoleUser,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// validateSessionDurationSeconds bounds a requested session lifetime the way
|
||||
// AWS STS does. Every assume-role entry point runs it, so a duration that came
|
||||
// from configuration is checked the same as one from a request.
|
||||
func validateSessionDurationSeconds(durationSeconds *int64) error {
|
||||
if durationSeconds == nil {
|
||||
return nil
|
||||
}
|
||||
if *durationSeconds < 900 || *durationSeconds > 43200 { // 15min to 12 hours
|
||||
return fmt.Errorf("DurationSeconds must be between 900 and 43200 seconds")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AssumeRoleForPrincipalRequest asks for a session on behalf of a principal the
|
||||
// calling service has already authenticated.
|
||||
type AssumeRoleForPrincipalRequest struct {
|
||||
// RoleArn is the ARN of the role to assume.
|
||||
RoleArn string
|
||||
|
||||
// Principal identifies the already-authenticated caller.
|
||||
Principal string
|
||||
|
||||
// RoleSessionName names the session.
|
||||
RoleSessionName string
|
||||
|
||||
// ProviderName records how the caller was authenticated.
|
||||
ProviderName string
|
||||
|
||||
// Policy optionally narrows the session below the role's own permissions.
|
||||
Policy *string
|
||||
|
||||
// DurationSeconds requests a session lifetime.
|
||||
DurationSeconds *int64
|
||||
}
|
||||
|
||||
// AssumeRoleForPrincipal issues session credentials for a caller that a
|
||||
// SeaweedFS service authenticated itself, such as the Iceberg catalog vending
|
||||
// scoped credentials for a table it has already authorized. There is no
|
||||
// external token left to verify at this point, so the role's trust policy is
|
||||
// the control point and is still enforced.
|
||||
func (s *STSService) AssumeRoleForPrincipal(ctx context.Context, request *AssumeRoleForPrincipalRequest) (*AssumeRoleResponse, error) {
|
||||
if !s.initialized {
|
||||
return nil, fmt.Errorf(ErrSTSServiceNotInitialized)
|
||||
}
|
||||
if request == nil {
|
||||
return nil, fmt.Errorf("request cannot be nil")
|
||||
}
|
||||
if request.RoleArn == "" {
|
||||
return nil, fmt.Errorf("role ARN cannot be empty")
|
||||
}
|
||||
if request.Principal == "" {
|
||||
return nil, fmt.Errorf("principal cannot be empty")
|
||||
}
|
||||
if err := validateSessionDurationSeconds(request.DurationSeconds); err != nil {
|
||||
return nil, fmt.Errorf("invalid request: %w", err)
|
||||
}
|
||||
|
||||
sessionPolicy := ""
|
||||
if request.Policy != nil {
|
||||
normalized, err := NormalizeSessionPolicy(*request.Policy)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid session policy: %w", err)
|
||||
}
|
||||
sessionPolicy = normalized
|
||||
}
|
||||
|
||||
identity := &providers.ExternalIdentity{
|
||||
UserID: request.Principal,
|
||||
DisplayName: request.Principal,
|
||||
Provider: request.ProviderName,
|
||||
}
|
||||
if err := s.validateRoleAssumptionForCredentials(ctx, request.RoleArn, identity); err != nil {
|
||||
return nil, fmt.Errorf("role assumption denied: %w", err)
|
||||
}
|
||||
|
||||
return s.issueSession(request.RoleArn, request.RoleSessionName, sessionPolicy,
|
||||
request.DurationSeconds, nil, request.ProviderName, request.Principal)
|
||||
}
|
||||
|
||||
// ValidateSessionToken validates a session token and returns session information
|
||||
// This method is now completely stateless - all session information is extracted from the JWT token
|
||||
func (s *STSService) ValidateSessionToken(ctx context.Context, sessionToken string) (*SessionInfo, error) {
|
||||
@@ -937,7 +855,14 @@ func (s *STSService) validateAssumeRoleWithWebIdentityRequest(request *AssumeRol
|
||||
return fmt.Errorf("RoleSessionName is required")
|
||||
}
|
||||
|
||||
return validateSessionDurationSeconds(request.DurationSeconds)
|
||||
// Validate session duration if provided
|
||||
if request.DurationSeconds != nil {
|
||||
if *request.DurationSeconds < 900 || *request.DurationSeconds > 43200 { // 15min to 12 hours
|
||||
return fmt.Errorf("DurationSeconds must be between 900 and 43200 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateWebIdentityToken validates the web identity token with strict issuer-to-provider mapping
|
||||
@@ -1170,7 +1095,14 @@ func (s *STSService) validateAssumeRoleWithCredentialsRequest(request *AssumeRol
|
||||
return fmt.Errorf("ProviderName is required")
|
||||
}
|
||||
|
||||
return validateSessionDurationSeconds(request.DurationSeconds)
|
||||
// Validate session duration if provided
|
||||
if request.DurationSeconds != nil {
|
||||
if *request.DurationSeconds < 900 || *request.DurationSeconds > 43200 { // 15min to 12 hours
|
||||
return fmt.Errorf("DurationSeconds must be between 900 and 43200 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExpireSessionForTesting manually expires a session for testing purposes
|
||||
|
||||
@@ -34,6 +34,8 @@ type dirState struct {
|
||||
cachedExpiresTime time.Time
|
||||
lastAccess time.Time
|
||||
lastRefresh time.Time
|
||||
updateWindowStart time.Time
|
||||
updateCount int
|
||||
subdirCount int32 // tracked in-memory for POSIX directory nlink
|
||||
}
|
||||
|
||||
@@ -41,6 +43,8 @@ func (d *dirState) resetCacheState() {
|
||||
d.isChildrenCached = false
|
||||
d.readDirDirect = false
|
||||
d.cachedExpiresTime = time.Time{}
|
||||
d.updateCount = 0
|
||||
d.updateWindowStart = time.Time{}
|
||||
}
|
||||
|
||||
func (ie *InodeEntry) removeOnePath(p util.FullPath) bool {
|
||||
@@ -241,6 +245,8 @@ func (i *InodeToPath) MarkChildrenCached(fullpath util.FullPath) {
|
||||
now := time.Now()
|
||||
d.lastAccess = now
|
||||
d.lastRefresh = now
|
||||
d.updateCount = 0
|
||||
d.updateWindowStart = time.Time{}
|
||||
if i.cacheMetaTtlSec > 0 {
|
||||
d.cachedExpiresTime = now.Add(i.cacheMetaTtlSec)
|
||||
}
|
||||
@@ -370,9 +376,43 @@ func (i *InodeToPath) MarkDirectoryReadThrough(fullpath util.FullPath, now time.
|
||||
d.cachedExpiresTime = time.Time{}
|
||||
d.lastAccess = now
|
||||
d.lastRefresh = time.Time{}
|
||||
d.updateCount = 0
|
||||
d.updateWindowStart = time.Time{}
|
||||
return true
|
||||
}
|
||||
|
||||
func (i *InodeToPath) RecordDirectoryUpdate(fullpath util.FullPath, now time.Time, window time.Duration, threshold int) bool {
|
||||
if threshold <= 0 || window <= 0 {
|
||||
return false
|
||||
}
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
inode, found := i.path2inode[fullpath]
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
d := i.dirStates[inode]
|
||||
if d == nil || !d.isChildrenCached {
|
||||
return false
|
||||
}
|
||||
if d.updateWindowStart.IsZero() || now.Sub(d.updateWindowStart) > window {
|
||||
d.updateWindowStart = now
|
||||
d.updateCount = 0
|
||||
}
|
||||
d.updateCount++
|
||||
if d.updateCount >= threshold {
|
||||
d.isChildrenCached = false
|
||||
d.readDirDirect = true
|
||||
d.cachedExpiresTime = time.Time{}
|
||||
d.lastAccess = now
|
||||
d.lastRefresh = time.Time{}
|
||||
d.updateCount = 0
|
||||
d.updateWindowStart = time.Time{}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (i *InodeToPath) ShouldReadDirectoryDirect(fullpath util.FullPath) bool {
|
||||
i.RLock()
|
||||
defer i.RUnlock()
|
||||
@@ -401,6 +441,8 @@ func (i *InodeToPath) MarkDirectoryRefreshed(fullpath util.FullPath, now time.Ti
|
||||
d.lastRefresh = now
|
||||
d.lastAccess = now
|
||||
d.readDirDirect = false
|
||||
d.updateCount = 0
|
||||
d.updateWindowStart = time.Time{}
|
||||
if i.cacheMetaTtlSec > 0 {
|
||||
d.cachedExpiresTime = now.Add(i.cacheMetaTtlSec)
|
||||
}
|
||||
|
||||
@@ -126,6 +126,26 @@ func TestOnlyDirectoriesGetDirState(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordDirectoryUpdateSwitchesDirectoryToReadThrough(t *testing.T) {
|
||||
root := util.FullPath("/")
|
||||
dir := util.FullPath("/data")
|
||||
|
||||
inodeToPath := NewInodeToPath(root, 60)
|
||||
inodeToPath.Lookup(dir, time.Now().Unix(), true, false, 0, true)
|
||||
inodeToPath.MarkChildrenCached(dir)
|
||||
|
||||
now := time.Now()
|
||||
if !inodeToPath.RecordDirectoryUpdate(dir, now, time.Second, 1) {
|
||||
t.Fatal("expected directory to switch to read-through mode")
|
||||
}
|
||||
if inodeToPath.IsChildrenCached(dir) {
|
||||
t.Fatal("directory should no longer be marked cached")
|
||||
}
|
||||
if !inodeToPath.ShouldReadDirectoryDirect(dir) {
|
||||
t.Fatal("directory should be served via direct reads after hot invalidation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkChildrenCachedClearsReadThroughMode(t *testing.T) {
|
||||
root := util.FullPath("/")
|
||||
dir := util.FullPath("/data")
|
||||
|
||||
@@ -54,11 +54,6 @@ type MetaCache struct {
|
||||
// instead of a record per child.
|
||||
dirVersionFloors map[util.FullPath]int64
|
||||
|
||||
// dirSections is each cached directory's listing split into name-range
|
||||
// sections, so a churn burst invalidates one section instead of the
|
||||
// whole listing. See meta_cache_sections.go.
|
||||
dirSections map[util.FullPath]*sectionList
|
||||
|
||||
// Entry invalidations run on a worker, not inline on the apply loop:
|
||||
// invalidateFunc takes the fh lock, which a flush can hold while waiting on
|
||||
// the apply loop (flushMetadataToFiler -> applyLocalMetadataEvent), so inline
|
||||
@@ -97,7 +92,6 @@ const (
|
||||
metadataCompleteBuild
|
||||
metadataAbortBuild
|
||||
metadataPurgeDir
|
||||
metadataSectionRefresh
|
||||
metadataShutdown
|
||||
)
|
||||
|
||||
@@ -108,8 +102,6 @@ type metadataApplyRequest struct {
|
||||
options MetadataResponseApplyOptions
|
||||
buildPath util.FullPath
|
||||
snapshotTsNs int64
|
||||
sections *sectionList // the completed build's section table
|
||||
refresh *sectionRefresh // one section re-listing to reconcile
|
||||
resetFn func()
|
||||
done chan error
|
||||
}
|
||||
@@ -132,7 +124,6 @@ func NewMetaCache(dbFolder string, uidGidMapper *UidGidMapper, root util.FullPat
|
||||
buildingDirs: make(map[util.FullPath]*directoryBuildState),
|
||||
dedupRing: newDedupRingBuffer(),
|
||||
dirVersionFloors: make(map[util.FullPath]int64),
|
||||
dirSections: make(map[util.FullPath]*sectionList),
|
||||
oversizedDirs: make(map[util.FullPath]struct{}),
|
||||
}
|
||||
mc.invalidateWorker = util.NewAsyncBatchWorker(func(batch []EntryInvalidation) {
|
||||
@@ -325,12 +316,11 @@ func (mc *MetaCache) BeginDirectoryBuild(ctx context.Context, dirPath util.FullP
|
||||
})
|
||||
}
|
||||
|
||||
func (mc *MetaCache) CompleteDirectoryBuild(ctx context.Context, dirPath util.FullPath, snapshotTsNs int64, sectionBounds []string) error {
|
||||
func (mc *MetaCache) CompleteDirectoryBuild(ctx context.Context, dirPath util.FullPath, snapshotTsNs int64) error {
|
||||
return mc.enqueueAndWait(ctx, metadataApplyRequest{
|
||||
kind: metadataCompleteBuild,
|
||||
buildPath: dirPath,
|
||||
snapshotTsNs: snapshotTsNs,
|
||||
sections: newSectionTable(sectionBounds),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -498,19 +488,22 @@ func (mc *MetaCache) entryVersionRecordLocked(ctx context.Context, fp util.FullP
|
||||
}
|
||||
|
||||
// entryVersionBlocksLocked reports whether a write at tsNs is already
|
||||
// reflected at fp. The path's version is its own record or, lacking one, the
|
||||
// listing floors — which cover names a listing saw present and absent alike.
|
||||
// A tombstone fences with no entry present, and a later floor outranks it; a
|
||||
// plain record only counts while its entry exists: records linger after a
|
||||
// reflected at fp. A tombstone fences with no entry present. Otherwise the
|
||||
// path's version is its own record or, lacking one, its directory's listing
|
||||
// floor — which covers children the listing saw present and absent alike.
|
||||
// A plain record only counts while its entry exists: records linger after a
|
||||
// bulk folder wipe and must not fence a recreate.
|
||||
func (mc *MetaCache) entryVersionBlocksLocked(ctx context.Context, fp util.FullPath, tsNs int64) bool {
|
||||
recordTsNs, tombstone, unversioned := mc.entryVersionRecordLocked(ctx, fp)
|
||||
if tombstone {
|
||||
return recordTsNs >= tsNs
|
||||
}
|
||||
if unversioned {
|
||||
// Local content no log position describes: fence nothing, so any
|
||||
// event can correct it.
|
||||
return false
|
||||
}
|
||||
if !tombstone && !mc.entryExistsLocked(ctx, fp) {
|
||||
if !mc.entryExistsLocked(ctx, fp) {
|
||||
recordTsNs = 0
|
||||
}
|
||||
return mc.entryVersionFloorLocked(fp, recordTsNs) >= tsNs
|
||||
@@ -527,18 +520,12 @@ func (mc *MetaCache) entryExistsLocked(ctx context.Context, fp util.FullPath) bo
|
||||
}
|
||||
|
||||
// entryVersionFloorLocked raises a path's own version record to its
|
||||
// directory's listing floor or its section's refresh floor: each listing
|
||||
// covered every name in its range at its snapshot, so a name without a later
|
||||
// record of its own is versioned at the snapshot.
|
||||
// directory's listing floor: the listing covered every child at its snapshot,
|
||||
// so a child without a later record of its own is versioned at the snapshot.
|
||||
func (mc *MetaCache) entryVersionFloorLocked(fp util.FullPath, recordTsNs int64) int64 {
|
||||
dir, name := fp.DirAndName()
|
||||
dir, _ := fp.DirAndName()
|
||||
if floor := mc.dirVersionFloors[util.FullPath(dir)]; floor > recordTsNs {
|
||||
recordTsNs = floor
|
||||
}
|
||||
if sl := mc.dirSections[util.FullPath(dir)]; sl != nil {
|
||||
if floor := sl.floorOf(name); floor > recordTsNs {
|
||||
recordTsNs = floor
|
||||
}
|
||||
return floor
|
||||
}
|
||||
return recordTsNs
|
||||
}
|
||||
@@ -605,7 +592,6 @@ func (mc *MetaCache) DeleteFolderChildren(ctx context.Context, fp util.FullPath)
|
||||
mc.Lock()
|
||||
defer mc.Unlock()
|
||||
delete(mc.dirVersionFloors, fp)
|
||||
delete(mc.dirSections, fp)
|
||||
mc.deleteChildVersionRecordsLocked(ctx, fp)
|
||||
return mc.localStore.DeleteFolderChildren(ctx, fp)
|
||||
}
|
||||
@@ -804,13 +790,11 @@ func (mc *MetaCache) handleApplyRequest(req metadataApplyRequest) error {
|
||||
case metadataBeginBuild:
|
||||
return mc.beginDirectoryBuildNow(req.buildPath)
|
||||
case metadataCompleteBuild:
|
||||
return mc.completeDirectoryBuildNow(req.ctx, req.buildPath, req.snapshotTsNs, req.sections)
|
||||
return mc.completeDirectoryBuildNow(req.ctx, req.buildPath, req.snapshotTsNs)
|
||||
case metadataAbortBuild:
|
||||
return mc.abortDirectoryBuildNow(req.buildPath)
|
||||
case metadataPurgeDir:
|
||||
return mc.purgeDirectoryChildrenNow(req.ctx, req.buildPath, req.resetFn)
|
||||
case metadataSectionRefresh:
|
||||
return mc.applySectionRefreshNow(req.ctx, req.buildPath, req.refresh)
|
||||
case metadataShutdown:
|
||||
return nil
|
||||
default:
|
||||
@@ -958,17 +942,6 @@ func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *file
|
||||
newEntry = nil
|
||||
}
|
||||
}
|
||||
// Only foreign churn counts toward section invalidation: this mount's own
|
||||
// writes are ground truth for its cache.
|
||||
if options.InvalidateEntries {
|
||||
now := time.Now()
|
||||
if oldPath != "" {
|
||||
mc.noteSectionChangeLocked(oldPath, now)
|
||||
}
|
||||
if newEntry != nil && newEntry.FullPath != oldPath {
|
||||
mc.noteSectionChangeLocked(newEntry.FullPath, now)
|
||||
}
|
||||
}
|
||||
err := mc.atomicUpdateEntryFromFilerLocked(ctx, oldPath, newEntry, allowUncachedInsert, resp.TsNs)
|
||||
if err == nil && hideNewPath {
|
||||
if purgeErr := mc.purgeEntryLocked(ctx, newPath, message.NewEntry.IsDirectory); purgeErr != nil {
|
||||
@@ -981,8 +954,6 @@ func (mc *MetaCache) applyMetadataResponseLocked(ctx context.Context, resp *file
|
||||
isDelete := message.NewEntry == nil
|
||||
isMove := message.NewEntry != nil && (message.NewParentPath != resp.Directory || message.NewEntry.Name != message.OldEntry.Name)
|
||||
if isDelete || isMove {
|
||||
delete(mc.dirVersionFloors, oldPath)
|
||||
delete(mc.dirSections, oldPath)
|
||||
if deleteErr := mc.localStore.DeleteFolderChildren(ctx, oldPath); deleteErr != nil {
|
||||
glog.V(2).Infof("delete descendants of %s: %v", oldPath, deleteErr)
|
||||
}
|
||||
@@ -1024,12 +995,11 @@ func (mc *MetaCache) purgeDirectoryChildrenNow(ctx context.Context, dirPath util
|
||||
mc.Lock()
|
||||
defer mc.Unlock()
|
||||
delete(mc.dirVersionFloors, dirPath)
|
||||
delete(mc.dirSections, dirPath)
|
||||
mc.deleteChildVersionRecordsLocked(ctx, dirPath)
|
||||
return mc.localStore.DeleteFolderChildren(ctx, dirPath)
|
||||
}
|
||||
|
||||
func (mc *MetaCache) completeDirectoryBuildNow(ctx context.Context, dirPath util.FullPath, snapshotTsNs int64, sections *sectionList) error {
|
||||
func (mc *MetaCache) completeDirectoryBuildNow(ctx context.Context, dirPath util.FullPath, snapshotTsNs int64) error {
|
||||
state := mc.buildingDirs[dirPath]
|
||||
delete(mc.buildingDirs, dirPath)
|
||||
|
||||
@@ -1042,7 +1012,6 @@ func (mc *MetaCache) completeDirectoryBuildNow(ctx context.Context, dirPath util
|
||||
// touches it. An unversioned listing (pre-upgrade filer) instead clears the
|
||||
// children's records, or a re-inserted entry would inherit a stale one.
|
||||
mc.Lock()
|
||||
mc.dirSections[dirPath] = sections
|
||||
if snapshotTsNs != 0 {
|
||||
mc.dirVersionFloors[dirPath] = snapshotTsNs
|
||||
mc.pruneSupersededTombstonesLocked(ctx, dirPath, snapshotTsNs)
|
||||
|
||||
@@ -621,7 +621,7 @@ func TestUnversionedRebuildClearsStaleVersions(t *testing.T) {
|
||||
}}); err != nil {
|
||||
t.Fatalf("batch insert: %v", err)
|
||||
}
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 0, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 0); err != nil {
|
||||
t.Fatalf("complete unversioned build: %v", err)
|
||||
}
|
||||
|
||||
@@ -717,7 +717,7 @@ func TestBuildCompletionPrunesSupersededTombstones(t *testing.T) {
|
||||
if err := mc.BeginDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
|
||||
t.Fatalf("begin build: %v", err)
|
||||
}
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 3000, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 3000); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
@@ -806,7 +806,7 @@ func TestBuildFloorVersionsChildrenWithoutPerChildRecords(t *testing.T) {
|
||||
}}); err != nil {
|
||||
t.Fatalf("batch insert: %v", err)
|
||||
}
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
@@ -889,7 +889,7 @@ func TestUnversionedWriteDoesNotInheritDirectoryFloor(t *testing.T) {
|
||||
if err := mc.BeginDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
|
||||
t.Fatalf("begin build: %v", err)
|
||||
}
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -208,7 +208,7 @@ func TestDirectoryNotificationsSuppressedDuringBuild(t *testing.T) {
|
||||
}
|
||||
|
||||
// Complete the build — buffered events should be replayed
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 150, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 150); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@ func TestEmptyDirectoryBuildReplaysAllBufferedEvents(t *testing.T) {
|
||||
}
|
||||
|
||||
// Complete with snapshotTsNs=0 — simulates empty directory listing
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/empty"), 0, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/empty"), 0); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ func TestBuildCompletionSurvivesCallerCancellation(t *testing.T) {
|
||||
// ctx.Done() first, but the operation itself still completes in the
|
||||
// apply loop. Poll for the observable side effect instead of using
|
||||
// a fixed sleep.
|
||||
_ = mc.CompleteDirectoryBuild(cancelledCtx, util.FullPath("/dir"), 100, nil)
|
||||
_ = mc.CompleteDirectoryBuild(cancelledCtx, util.FullPath("/dir"), 100)
|
||||
|
||||
// Poll until the build completes or a deadline elapses.
|
||||
deadline := time.After(2 * time.Second)
|
||||
@@ -445,7 +445,7 @@ func TestBufferedRenameUpdatesOtherDirectoryBeforeBuildCompletes(t *testing.T) {
|
||||
t.Fatalf("new path should stay hidden until build completes: %+v", newEntry)
|
||||
}
|
||||
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dst"), 100, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), util.FullPath("/dst"), 100); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -132,10 +132,9 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
}()
|
||||
|
||||
// reloadFromFiler wipes the cached children and reloads them from the filer.
|
||||
reloadFromFiler := func() (entryCount int, snapshotTsNs int64, sections sectionBoundsCollector, err error) {
|
||||
reloadFromFiler := func() (entryCount int, snapshotTsNs int64, err error) {
|
||||
err = util.Retry("ReadDirAllEntries", func() error {
|
||||
entryCount = 0
|
||||
sections = sectionBoundsCollector{}
|
||||
var batch []*filer.Entry // reset on retry, allow GC of previous entries
|
||||
if err := mc.deleteFolderChildrenForRebuild(ctx, path); err != nil {
|
||||
return fmt.Errorf("clear existing entries for %s: %w", path, err)
|
||||
@@ -150,7 +149,6 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
if maxCacheableEntries > 0 && entryCount >= maxCacheableEntries {
|
||||
return &DirectoryTooLargeError{Path: path}
|
||||
}
|
||||
sections.note(entry.Name())
|
||||
batch = append(batch, entry)
|
||||
entryCount++
|
||||
|
||||
@@ -173,10 +171,10 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return entryCount, snapshotTsNs, sections, err
|
||||
return entryCount, snapshotTsNs, err
|
||||
}
|
||||
|
||||
entryCount, snapshotTsNs, sections, fetchErr := reloadFromFiler()
|
||||
entryCount, snapshotTsNs, fetchErr := reloadFromFiler()
|
||||
if fetchErr != nil {
|
||||
var tooLarge *DirectoryTooLargeError
|
||||
if errors.As(fetchErr, &tooLarge) {
|
||||
@@ -206,7 +204,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
if entryCount, snapshotTsNs, sections, fetchErr = reloadFromFiler(); fetchErr != nil {
|
||||
if entryCount, snapshotTsNs, fetchErr = reloadFromFiler(); fetchErr != nil {
|
||||
cleanupBuild("failed")
|
||||
return nil, fmt.Errorf("confirm empty list %s: %w", path, fetchErr)
|
||||
}
|
||||
@@ -215,7 +213,7 @@ func doEnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerCl
|
||||
}
|
||||
}
|
||||
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), path, snapshotTsNs, sections.bounds); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), path, snapshotTsNs); err != nil {
|
||||
cleanupBuild("unreplayed")
|
||||
return nil, fmt.Errorf("complete build for %s: %w", path, err)
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ func TestPurgeSkippedWhileDirectoryBuilding(t *testing.T) {
|
||||
var resetCalls int32
|
||||
mc.PurgeDirectoryChildren(dir, func() { atomic.AddInt32(&resetCalls, 1) })
|
||||
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), dir, 0, nil); err != nil {
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), dir, 0); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,422 +0,0 @@
|
||||
package meta_cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// A cached directory's listing is split into contiguous name-range sections so
|
||||
// a burst of remote changes invalidates one section, not the whole listing.
|
||||
// Events keep applying to a stale section; staleness only means the next
|
||||
// listing re-validates that range against the filer before serving it, and
|
||||
// lookups in it read through until then.
|
||||
const (
|
||||
// dirSectionSize is the target entries per section, fixed when a listing
|
||||
// is built and re-derived when a re-listed section has outgrown it.
|
||||
dirSectionSize = 1024
|
||||
// sectionHotThreshold remote changes within sectionHotWindow invalidate
|
||||
// the section they land in.
|
||||
sectionHotThreshold = 64
|
||||
sectionHotWindow = 2 * time.Second
|
||||
// sectionRefreshTimeout bounds how long a readdir waits on re-validating
|
||||
// a section before serving the maintained-but-unverified cache instead.
|
||||
sectionRefreshTimeout = 5 * time.Second
|
||||
// sectionRefreshMaxEntries is the most one refresh will carry; a section
|
||||
// grown past it is cheaper to re-tile with a full directory rebuild.
|
||||
sectionRefreshMaxEntries = 4 * dirSectionSize
|
||||
)
|
||||
|
||||
// ErrRefreshRangeTooLarge reports a section that outgrew one refresh; the
|
||||
// caller should drop the directory cache so a full rebuild re-tiles it.
|
||||
var ErrRefreshRangeTooLarge = errors.New("section outgrew one refresh")
|
||||
|
||||
// sectionList: bounds[i] is the first name of section i+1; section 0 starts at
|
||||
// the beginning of the namespace, the last section runs to the end. It is a
|
||||
// plain state machine — no locking, no store; MetaCache drives it under its
|
||||
// own mutex.
|
||||
type sectionList struct {
|
||||
bounds []string
|
||||
sections []sectionState
|
||||
}
|
||||
|
||||
type sectionState struct {
|
||||
stale bool
|
||||
updateCount int
|
||||
windowStart time.Time
|
||||
// unverifiable marks a stale section whose filer stamps no listing
|
||||
// snapshots: re-listing it can never vouch for it, so stop trying and
|
||||
// leave its lookups reading through.
|
||||
unverifiable bool
|
||||
// floorTsNs is the section's own listing snapshot: a refresh at it covered
|
||||
// every name in the range, present or absent, so it fences like the
|
||||
// directory floor but for this range alone.
|
||||
floorTsNs int64
|
||||
}
|
||||
|
||||
func newSectionTable(bounds []string) *sectionList {
|
||||
return §ionList{bounds: bounds, sections: make([]sectionState, len(bounds)+1)}
|
||||
}
|
||||
|
||||
// sectionBoundsCollector derives section boundaries from an ordered listing:
|
||||
// every dirSectionSize-th name starts a new section.
|
||||
type sectionBoundsCollector struct {
|
||||
count int
|
||||
bounds []string
|
||||
}
|
||||
|
||||
func (c *sectionBoundsCollector) note(name string) {
|
||||
if c.count > 0 && c.count%dirSectionSize == 0 {
|
||||
c.bounds = append(c.bounds, name)
|
||||
}
|
||||
c.count++
|
||||
}
|
||||
|
||||
// sectionRefresh carries one section's re-listing to the apply loop.
|
||||
type sectionRefresh struct {
|
||||
lo, hi string
|
||||
entries []*filer.Entry
|
||||
snapshotTsNs int64
|
||||
}
|
||||
|
||||
func (sl *sectionList) sectionOf(name string) int {
|
||||
idx := sort.SearchStrings(sl.bounds, name)
|
||||
if idx < len(sl.bounds) && sl.bounds[idx] == name {
|
||||
idx++
|
||||
}
|
||||
return idx
|
||||
}
|
||||
|
||||
// sectionRange returns the [lo, hi) name range of section idx; "" is unbounded.
|
||||
func (sl *sectionList) sectionRange(idx int) (lo, hi string) {
|
||||
if idx > 0 {
|
||||
lo = sl.bounds[idx-1]
|
||||
}
|
||||
if idx < len(sl.bounds) {
|
||||
hi = sl.bounds[idx]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// noteChange counts one change against the section it lands in, marking the
|
||||
// section stale when a burst crosses the threshold.
|
||||
func (sl *sectionList) noteChange(name string, now time.Time) {
|
||||
s := &sl.sections[sl.sectionOf(name)]
|
||||
if s.stale {
|
||||
return
|
||||
}
|
||||
if s.windowStart.IsZero() || now.Sub(s.windowStart) > sectionHotWindow {
|
||||
s.windowStart = now
|
||||
s.updateCount = 0
|
||||
}
|
||||
s.updateCount++
|
||||
if s.updateCount >= sectionHotThreshold {
|
||||
s.stale = true
|
||||
}
|
||||
}
|
||||
|
||||
func (sl *sectionList) isFresh(name string) bool {
|
||||
return !sl.sections[sl.sectionOf(name)].stale
|
||||
}
|
||||
|
||||
// floorOf returns the refresh snapshot covering this name, or zero when its
|
||||
// section has never been re-listed. A stale section keeps fencing: what its
|
||||
// last listing established stays established.
|
||||
func (sl *sectionList) floorOf(name string) int64 {
|
||||
return sl.sections[sl.sectionOf(name)].floorTsNs
|
||||
}
|
||||
|
||||
type nameRange struct {
|
||||
lo, hi string
|
||||
}
|
||||
|
||||
// staleRangesAhead returns the invalidated ranges worth re-listing from the
|
||||
// section holding startName to the end of the directory.
|
||||
func (sl *sectionList) staleRangesAhead(startName string) (ranges []nameRange) {
|
||||
for i := sl.sectionOf(startName); i < len(sl.sections); i++ {
|
||||
if sl.sections[i].stale && !sl.sections[i].unverifiable {
|
||||
lo, hi := sl.sectionRange(i)
|
||||
ranges = append(ranges, nameRange{lo: lo, hi: hi})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// hasRange reports whether the table still has a section covering exactly
|
||||
// [lo, hi); a rebuild or re-split since a listing was taken retires the range
|
||||
// it described.
|
||||
func (sl *sectionList) hasRange(lo, hi string) bool {
|
||||
curLo, curHi := sl.sectionRange(sl.sectionOf(lo))
|
||||
return curLo == lo && curHi == hi
|
||||
}
|
||||
|
||||
// completeRefresh marks the section covering exactly [lo, hi) fresh after a
|
||||
// re-listing that fetched names at snapshotTsNs, re-splitting a section that
|
||||
// outgrew twice its target size. The snapshot becomes the section's floor. A
|
||||
// range the table no longer has is ignored — splicing bounds from a stale
|
||||
// range could leave the table unsorted — and an unversioned listing vouches
|
||||
// for nothing: the section stays stale, remembered as not worth re-listing.
|
||||
func (sl *sectionList) completeRefresh(lo, hi string, names []string, snapshotTsNs int64) bool {
|
||||
idx := sl.sectionOf(lo)
|
||||
if curLo, curHi := sl.sectionRange(idx); curLo != lo || curHi != hi {
|
||||
return false
|
||||
}
|
||||
if snapshotTsNs == 0 {
|
||||
sl.sections[idx].unverifiable = true
|
||||
return false
|
||||
}
|
||||
if len(names) > 2*dirSectionSize {
|
||||
var newBounds []string
|
||||
for i := dirSectionSize; i < len(names); i += dirSectionSize {
|
||||
newBounds = append(newBounds, names[i])
|
||||
}
|
||||
bounds := make([]string, 0, len(sl.bounds)+len(newBounds))
|
||||
bounds = append(bounds, sl.bounds[:idx]...)
|
||||
bounds = append(bounds, newBounds...)
|
||||
bounds = append(bounds, sl.bounds[idx:]...)
|
||||
sections := make([]sectionState, 0, len(bounds)+1)
|
||||
sections = append(sections, sl.sections[:idx]...)
|
||||
for i := 0; i <= len(newBounds); i++ {
|
||||
sections = append(sections, sectionState{floorTsNs: snapshotTsNs})
|
||||
}
|
||||
sections = append(sections, sl.sections[idx+1:]...)
|
||||
sl.bounds, sl.sections = bounds, sections
|
||||
} else {
|
||||
sl.sections[idx] = sectionState{floorTsNs: snapshotTsNs}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// noteSectionChangeLocked counts one remote change against the section of the
|
||||
// directory it lands in.
|
||||
func (mc *MetaCache) noteSectionChangeLocked(fp util.FullPath, now time.Time) {
|
||||
dir, name := fp.DirAndName()
|
||||
if sl := mc.dirSections[util.FullPath(dir)]; sl != nil {
|
||||
sl.noteChange(name, now)
|
||||
}
|
||||
}
|
||||
|
||||
// IsNameFresh reports whether the cached listing still vouches for this name.
|
||||
// A directory without section state vouches for all of it.
|
||||
func (mc *MetaCache) IsNameFresh(fp util.FullPath) bool {
|
||||
dir, name := fp.DirAndName()
|
||||
mc.RLock()
|
||||
defer mc.RUnlock()
|
||||
sl := mc.dirSections[util.FullPath(dir)]
|
||||
return sl == nil || sl.isFresh(name)
|
||||
}
|
||||
|
||||
func (mc *MetaCache) staleRangesAhead(dirPath util.FullPath, startName string) []nameRange {
|
||||
mc.RLock()
|
||||
defer mc.RUnlock()
|
||||
sl := mc.dirSections[dirPath]
|
||||
if sl == nil {
|
||||
return nil
|
||||
}
|
||||
return sl.staleRangesAhead(startName)
|
||||
}
|
||||
|
||||
func (mc *MetaCache) rangeStale(dirPath util.FullPath, lo string) bool {
|
||||
mc.RLock()
|
||||
defer mc.RUnlock()
|
||||
sl := mc.dirSections[dirPath]
|
||||
return sl != nil && !sl.isFresh(lo)
|
||||
}
|
||||
|
||||
// EnsureListingFresh re-validates every invalidated section from startName to
|
||||
// the end of the directory before a listing pages through them. A listing's
|
||||
// reach is unknowable up front — a resumed handle can skip far ahead, and
|
||||
// shrunken sections let one batch span many — so all of them are covered.
|
||||
func EnsureListingFresh(ctx context.Context, mc *MetaCache, client filer_pb.FilerClient, dirPath util.FullPath, startName string) error {
|
||||
ranges := mc.staleRangesAhead(dirPath, startName)
|
||||
if len(ranges) == 0 {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, sectionRefreshTimeout)
|
||||
defer cancel()
|
||||
for _, r := range ranges {
|
||||
if err := mc.refreshSection(ctx, client, dirPath, r.lo, r.hi); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc *MetaCache) refreshSection(ctx context.Context, client filer_pb.FilerClient, dirPath util.FullPath, lo, hi string) error {
|
||||
_, err, _ := mc.visitGroup.Do(string(dirPath)+"\x00section\x00"+lo, func() (interface{}, error) {
|
||||
if !mc.rangeStale(dirPath, lo) {
|
||||
return nil, nil
|
||||
}
|
||||
entries, snapshotTsNs, err := mc.listFilerRange(ctx, client, dirPath, lo, hi)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, mc.enqueueAndWait(ctx, metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: dirPath,
|
||||
refresh: §ionRefresh{lo: lo, hi: hi, entries: entries, snapshotTsNs: snapshotTsNs},
|
||||
})
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// listFilerRange reads [lo, hi) from the filer at one snapshot, paging by
|
||||
// section-sized batches.
|
||||
func (mc *MetaCache) listFilerRange(ctx context.Context, client filer_pb.FilerClient, dirPath util.FullPath, lo, hi string) (entries []*filer.Entry, snapshotTsNs int64, err error) {
|
||||
startFrom, includeStart := lo, lo != ""
|
||||
for {
|
||||
var page []*filer.Entry
|
||||
var pageCount int
|
||||
var last string
|
||||
done := false
|
||||
err = client.WithFilerClient(false, func(sc filer_pb.SeaweedFilerClient) error {
|
||||
// reset in case a failover retry re-runs a partly streamed page
|
||||
page, pageCount, last, done = nil, 0, "", false
|
||||
ts, listErr := filer_pb.DoSeaweedListWithSnapshot(ctx, sc, dirPath, "", func(pbEntry *filer_pb.Entry, isLast bool) error {
|
||||
pageCount++
|
||||
last = pbEntry.Name
|
||||
if hi != "" && pbEntry.Name >= hi {
|
||||
done = true
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
if !mc.includeSystemEntries && IsHiddenSystemEntry(string(dirPath), pbEntry.Name) {
|
||||
return nil
|
||||
}
|
||||
page = append(page, filer.FromPbEntry(string(dirPath), pbEntry))
|
||||
return nil
|
||||
}, startFrom, includeStart, dirSectionSize, snapshotTsNs)
|
||||
if listErr != nil {
|
||||
return listErr
|
||||
}
|
||||
if snapshotTsNs == 0 {
|
||||
snapshotTsNs = ts
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
entries = append(entries, page...)
|
||||
if len(entries) > sectionRefreshMaxEntries {
|
||||
return nil, 0, ErrRefreshRangeTooLarge
|
||||
}
|
||||
if done || pageCount < dirSectionSize {
|
||||
return entries, snapshotTsNs, nil
|
||||
}
|
||||
startFrom, includeStart = last, false
|
||||
}
|
||||
}
|
||||
|
||||
// applySectionRefreshNow reconciles one section against a filer listing of its
|
||||
// range, then marks it fresh. Runs on the apply loop; mutations go through the
|
||||
// version gate so the listing cannot roll back a newer applied event, and
|
||||
// pinned local-only entries (deferred creates not yet on the filer) survive.
|
||||
func (mc *MetaCache) applySectionRefreshNow(ctx context.Context, dirPath util.FullPath, r *sectionRefresh) error {
|
||||
lo, hi, snapshotTsNs := r.lo, r.hi, r.snapshotTsNs
|
||||
|
||||
// A build wipes and repopulates the store off-loop; reconciling against
|
||||
// it would sweep children the build already inserted and publish the
|
||||
// directory incomplete. The staleness dies with the build's fresh table.
|
||||
if mc.isBuildingDir(dirPath) {
|
||||
return nil
|
||||
}
|
||||
|
||||
mc.Lock()
|
||||
defer mc.Unlock()
|
||||
|
||||
// With no per-entry versions, only the section floor fences this work; a
|
||||
// range the rebuilt or re-split table no longer has gets no floor, so it
|
||||
// must not touch the store either. The lock is held through the floor
|
||||
// install below, so the check cannot go stale.
|
||||
sl := mc.dirSections[dirPath]
|
||||
if sl == nil || !sl.hasRange(lo, hi) {
|
||||
return nil
|
||||
}
|
||||
|
||||
fetchedNames := make([]string, 0, len(r.entries))
|
||||
fetched := make(map[string]struct{}, len(r.entries))
|
||||
for _, entry := range r.entries {
|
||||
fetchedNames = append(fetchedNames, entry.Name())
|
||||
fetched[entry.Name()] = struct{}{}
|
||||
if snapshotTsNs == 0 {
|
||||
// A pre-upgrade filer stamps no snapshot, leaving nothing to
|
||||
// order against: only fill gaps, so a concurrently applied event
|
||||
// can never be rolled back.
|
||||
if mc.entryExistsLocked(ctx, entry.FullPath) {
|
||||
continue
|
||||
}
|
||||
if _, tombstone := mc.getEntryVersionRecordLocked(ctx, entry.FullPath); tombstone {
|
||||
continue
|
||||
}
|
||||
if err := mc.localStore.InsertEntry(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
mc.setEntryVersionLocked(ctx, entry.FullPath, 0)
|
||||
continue
|
||||
}
|
||||
if mc.entryVersionBlocksLocked(ctx, entry.FullPath, snapshotTsNs) {
|
||||
continue
|
||||
}
|
||||
// An unversioned marker would bypass the section floor, so it cannot
|
||||
// outlive the snapshot write that replaces its content — but pinned
|
||||
// local-only state stays authoritative and is not replaced at all.
|
||||
_, _, unversioned := mc.entryVersionRecordLocked(ctx, entry.FullPath)
|
||||
if unversioned {
|
||||
if existing, findErr := mc.localStore.FindEntry(ctx, entry.FullPath); findErr == nil && existing != nil && mc.pinnedChildFn != nil && mc.pinnedChildFn(existing) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// no per-entry version: the section floor set below covers the range
|
||||
if err := mc.localStore.InsertEntry(ctx, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
if unversioned {
|
||||
// only once the write landed: if it fails, the old content keeps
|
||||
// the marker, and with it the right to be corrected by any event
|
||||
mc.clearEntryVersionLocked(ctx, entry.FullPath)
|
||||
}
|
||||
}
|
||||
|
||||
// Deletions need the snapshot as an ordering reference; without one a
|
||||
// name created after the listing would be swept away.
|
||||
if snapshotTsNs != 0 {
|
||||
var vanished []*filer.Entry
|
||||
if _, err := mc.localStore.ListDirectoryEntries(ctx, dirPath, lo, true, math.MaxInt64, func(entry *filer.Entry) (bool, error) {
|
||||
if hi != "" && entry.Name() >= hi {
|
||||
return false, nil
|
||||
}
|
||||
if _, found := fetched[entry.Name()]; !found {
|
||||
vanished = append(vanished, entry)
|
||||
}
|
||||
return true, nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range vanished {
|
||||
if mc.pinnedChildFn != nil && mc.pinnedChildFn(entry) {
|
||||
continue
|
||||
}
|
||||
if mc.entryVersionBlocksLocked(ctx, entry.FullPath, snapshotTsNs) {
|
||||
continue
|
||||
}
|
||||
if err := mc.localStore.DeleteEntry(ctx, entry.FullPath); err != nil {
|
||||
return err
|
||||
}
|
||||
mc.clearEntryVersionLocked(ctx, entry.FullPath)
|
||||
}
|
||||
}
|
||||
|
||||
// The floor fences the whole range, absent names included; an unversioned
|
||||
// listing sets none and the section stays stale, its lookups reading
|
||||
// through, with no further re-listing attempts.
|
||||
sl.completeRefresh(lo, hi, fetchedNames, snapshotTsNs)
|
||||
return nil
|
||||
}
|
||||
@@ -1,929 +0,0 @@
|
||||
package meta_cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func TestSectionOf(t *testing.T) {
|
||||
sl := newSectionTable([]string{"g", "p"})
|
||||
for name, want := range map[string]int{
|
||||
"a": 0, "f": 0,
|
||||
"g": 1, "h": 1, "o": 1,
|
||||
"p": 2, "z": 2,
|
||||
} {
|
||||
if got := sl.sectionOf(name); got != want {
|
||||
t.Errorf("sectionOf(%q) = %d, want %d", name, got, want)
|
||||
}
|
||||
}
|
||||
if lo, hi := sl.sectionRange(0); lo != "" || hi != "g" {
|
||||
t.Errorf("sectionRange(0) = %q..%q, want ..g", lo, hi)
|
||||
}
|
||||
if lo, hi := sl.sectionRange(1); lo != "g" || hi != "p" {
|
||||
t.Errorf("sectionRange(1) = %q..%q, want g..p", lo, hi)
|
||||
}
|
||||
if lo, hi := sl.sectionRange(2); lo != "p" || hi != "" {
|
||||
t.Errorf("sectionRange(2) = %q..%q, want p..", lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
func buildSectionedDir(t *testing.T, mc *MetaCache, dir util.FullPath, snapshotTsNs int64, bounds []string) {
|
||||
t.Helper()
|
||||
if err := mc.BeginDirectoryBuild(context.Background(), dir); err != nil {
|
||||
t.Fatalf("begin build: %v", err)
|
||||
}
|
||||
if err := mc.CompleteDirectoryBuild(context.Background(), dir, snapshotTsNs, bounds); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func applyChurn(t *testing.T, mc *MetaCache, dir, prefix string, n int, baseTsNs int64, options MetadataResponseApplyOptions) {
|
||||
t.Helper()
|
||||
for i := 0; i < n; i++ {
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: dir,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: fmt.Sprintf("%s%03d", prefix, i),
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Crtime: 1,
|
||||
Mtime: 1,
|
||||
FileMode: 0100644,
|
||||
FileSize: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
TsNs: baseTsNs + int64(i),
|
||||
}
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), resp, options); err != nil {
|
||||
t.Fatalf("apply churn %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionBurstInvalidatesOnlyItsSection(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
if mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("burst section should be invalidated")
|
||||
}
|
||||
if !mc.IsNameFresh(util.FullPath("/dir/zzz")) {
|
||||
t.Fatal("the other section must stay fresh")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalChangesDoNotInvalidateSections(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, nil)
|
||||
|
||||
applyChurn(t, mc, "/dir", "a-", 2*sectionHotThreshold, 2000, LocalMetadataResponseApplyOptions)
|
||||
|
||||
if !mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("this mount's own writes must not invalidate its cache")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionRefreshReconciles(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
mc.SetPinnedChildFn(func(entry *filer.Entry) bool {
|
||||
return entry.Name() == "b-pinned"
|
||||
})
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
|
||||
for _, name := range []string{"b-keep", "b-vanish", "b-pinned"} {
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: util.FullPath("/dir/" + name),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1},
|
||||
}, 0); err != nil {
|
||||
t.Fatalf("seed %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
// applied ahead of the refresh snapshot; the listing must not roll it back
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: "b-newer",
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 9, FileMode: 0100644, FileSize: 9},
|
||||
},
|
||||
},
|
||||
TsNs: 9000,
|
||||
}, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply newer event: %v", err)
|
||||
}
|
||||
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
if mc.IsNameFresh(util.FullPath("/dir/b-keep")) {
|
||||
t.Fatal("section should be stale before the refresh")
|
||||
}
|
||||
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{
|
||||
hi: "m",
|
||||
entries: []*filer.Entry{
|
||||
{
|
||||
FullPath: util.FullPath("/dir/b-keep"),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(2, 0), Mode: 0100644, FileSize: 7},
|
||||
},
|
||||
{
|
||||
FullPath: util.FullPath("/dir/b-new"),
|
||||
Attr: filer.Attr{Crtime: time.Unix(2, 0), Mtime: time.Unix(2, 0), Mode: 0100644, FileSize: 3},
|
||||
},
|
||||
},
|
||||
snapshotTsNs: 5000,
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
if !mc.IsNameFresh(util.FullPath("/dir/b-keep")) {
|
||||
t.Fatal("section should be fresh after the refresh")
|
||||
}
|
||||
entry, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-keep"))
|
||||
if err != nil || entry.FileSize != 7 {
|
||||
t.Fatalf("b-keep = %+v, %v; want size 7", entry, err)
|
||||
}
|
||||
if entry, _, err = mc.FindEntry(context.Background(), util.FullPath("/dir/b-new")); err != nil || entry.FileSize != 3 {
|
||||
t.Fatalf("b-new = %+v, %v; want size 3", entry, err)
|
||||
}
|
||||
if _, _, err = mc.FindEntry(context.Background(), util.FullPath("/dir/b-vanish")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("b-vanish error = %v, want not found", err)
|
||||
}
|
||||
if _, _, err = mc.FindEntry(context.Background(), util.FullPath("/dir/a-000")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("churned a-000 error = %v, want not found", err)
|
||||
}
|
||||
if entry, _, err = mc.FindEntry(context.Background(), util.FullPath("/dir/b-newer")); err != nil || entry.FileSize != 9 {
|
||||
t.Fatalf("b-newer = %+v, %v; want size 9 kept", entry, err)
|
||||
}
|
||||
if entry, _, err = mc.FindEntry(context.Background(), util.FullPath("/dir/b-pinned")); err != nil || entry == nil {
|
||||
t.Fatalf("pinned local-only entry must survive a refresh: %v", err)
|
||||
}
|
||||
|
||||
// a redelivered create older than the snapshot must not resurrect b-vanish
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: "b-vanish",
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0100644, FileSize: 1},
|
||||
},
|
||||
},
|
||||
TsNs: 4000,
|
||||
}, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply stale event: %v", err)
|
||||
}
|
||||
if _, _, err = mc.FindEntry(context.Background(), util.FullPath("/dir/b-vanish")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("b-vanish resurrected by a pre-snapshot event: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionRefreshSplitsOvergrownSection(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, nil)
|
||||
|
||||
count := 2*dirSectionSize + 1
|
||||
entries := make([]*filer.Entry, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
entries = append(entries, &filer.Entry{
|
||||
FullPath: util.FullPath(fmt.Sprintf("/dir/f-%05d", i)),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1},
|
||||
})
|
||||
}
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{entries: entries, snapshotTsNs: 5000},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
mc.RLock()
|
||||
sl := mc.dirSections[util.FullPath("/dir")]
|
||||
bounds := append([]string(nil), sl.bounds...)
|
||||
sections := len(sl.sections)
|
||||
mc.RUnlock()
|
||||
want := []string{fmt.Sprintf("f-%05d", dirSectionSize), fmt.Sprintf("f-%05d", 2*dirSectionSize)}
|
||||
if len(bounds) != len(want) || bounds[0] != want[0] || bounds[1] != want[1] {
|
||||
t.Fatalf("bounds = %v, want %v", bounds, want)
|
||||
}
|
||||
if sections != len(bounds)+1 {
|
||||
t.Fatalf("sections = %d, want %d", sections, len(bounds)+1)
|
||||
}
|
||||
}
|
||||
|
||||
type sectionFilerServer struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
mu sync.Mutex
|
||||
names []string // sorted; all under one directory
|
||||
snapshot int64
|
||||
requests []*filer_pb.ListEntriesRequest
|
||||
}
|
||||
|
||||
func (s *sectionFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
|
||||
s.mu.Lock()
|
||||
s.requests = append(s.requests, req)
|
||||
names := s.names
|
||||
snapshot := s.snapshot
|
||||
s.mu.Unlock()
|
||||
|
||||
sent := uint32(0)
|
||||
first := true
|
||||
for _, name := range names {
|
||||
if name < req.StartFromFileName || (name == req.StartFromFileName && !req.InclusiveStartFrom) {
|
||||
continue
|
||||
}
|
||||
resp := &filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0100644, FileSize: 1},
|
||||
}}
|
||||
if first {
|
||||
resp.SnapshotTsNs = snapshot
|
||||
first = false
|
||||
}
|
||||
if err := stream.Send(resp); err != nil {
|
||||
return err
|
||||
}
|
||||
sent++
|
||||
if req.Limit > 0 && sent >= req.Limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *sectionFilerServer) listRequests() []*filer_pb.ListEntriesRequest {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]*filer_pb.ListEntriesRequest(nil), s.requests...)
|
||||
}
|
||||
|
||||
type sectionTestFilerClient struct {
|
||||
addr string
|
||||
}
|
||||
|
||||
func (c *sectionTestFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
conn, err := grpc.NewClient(c.addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
return fn(filer_pb.NewSeaweedFilerClient(conn))
|
||||
}
|
||||
|
||||
func (c *sectionTestFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url }
|
||||
|
||||
func (c *sectionTestFilerClient) GetDataCenter() string { return "" }
|
||||
|
||||
func startSectionFilerServer(t *testing.T, s *sectionFilerServer) filer_pb.FilerClient {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(srv, s)
|
||||
go srv.Serve(listener)
|
||||
t.Cleanup(srv.Stop)
|
||||
return §ionTestFilerClient{addr: listener.Addr().String()}
|
||||
}
|
||||
|
||||
func TestEnsureListingFreshRefreshesFromFiler(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
server := §ionFilerServer{snapshot: 5000}
|
||||
for i := 0; i < 1500; i++ {
|
||||
server.names = append(server.names, fmt.Sprintf("b-%04d", i))
|
||||
}
|
||||
// at and beyond the section's end, must not be applied
|
||||
server.names = append(server.names, "m", "z-1")
|
||||
client := startSectionFilerServer(t, server)
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
if mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("section should be stale before the refresh")
|
||||
}
|
||||
|
||||
if err := EnsureListingFresh(context.Background(), mc, client, util.FullPath("/dir"), ""); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
if !mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("section should be fresh after the refresh")
|
||||
}
|
||||
for _, name := range []string{"b-0000", "b-1499"} {
|
||||
if entry, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/"+name)); err != nil || entry == nil {
|
||||
t.Fatalf("%s missing after refresh: %v", name, err)
|
||||
}
|
||||
}
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/a-000")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("churned a-000 error = %v, want not found", err)
|
||||
}
|
||||
for _, name := range []string{"m", "z-1"} {
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/"+name)); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("%s at or beyond the section's end was applied: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
requests := server.listRequests()
|
||||
if len(requests) < 2 {
|
||||
t.Fatalf("multi-page refresh made %d requests, want at least 2", len(requests))
|
||||
}
|
||||
if requests[0].SnapshotTsNs != 0 || requests[1].SnapshotTsNs != 5000 {
|
||||
t.Fatalf("snapshot not pinned across pages: %d then %d", requests[0].SnapshotTsNs, requests[1].SnapshotTsNs)
|
||||
}
|
||||
|
||||
// a fresh section costs no filer calls
|
||||
if err := EnsureListingFresh(context.Background(), mc, client, util.FullPath("/dir"), ""); err != nil {
|
||||
t.Fatalf("second refresh: %v", err)
|
||||
}
|
||||
if got := len(server.listRequests()); got != len(requests) {
|
||||
t.Fatalf("fresh section still listed the filer: %d requests, was %d", got, len(requests))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureListingFreshGivesUpOnOvergrownRange(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
server := §ionFilerServer{snapshot: 5000}
|
||||
for i := 0; i <= sectionRefreshMaxEntries; i++ {
|
||||
server.names = append(server.names, fmt.Sprintf("c-%05d", i))
|
||||
}
|
||||
client := startSectionFilerServer(t, server)
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, nil)
|
||||
applyChurn(t, mc, "/dir", "x-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
err := EnsureListingFresh(context.Background(), mc, client, util.FullPath("/dir"), "")
|
||||
if !errors.Is(err, ErrRefreshRangeTooLarge) {
|
||||
t.Fatalf("refresh error = %v, want ErrRefreshRangeTooLarge", err)
|
||||
}
|
||||
if mc.IsNameFresh(util.FullPath("/dir/x-000")) {
|
||||
t.Fatal("an aborted refresh must leave the section stale")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionNoteChangeWindowExpiry(t *testing.T) {
|
||||
sl := newSectionTable(nil)
|
||||
t0 := time.Unix(100, 0)
|
||||
for i := 0; i < sectionHotThreshold-1; i++ {
|
||||
sl.noteChange(fmt.Sprintf("f-%03d", i), t0)
|
||||
}
|
||||
if !sl.isFresh("f-000") {
|
||||
t.Fatal("below the threshold the section must stay fresh")
|
||||
}
|
||||
|
||||
// the burst never completed inside one window, so the count restarts
|
||||
t1 := t0.Add(sectionHotWindow + time.Second)
|
||||
for i := 0; i < sectionHotThreshold-1; i++ {
|
||||
sl.noteChange(fmt.Sprintf("f-%03d", i), t1)
|
||||
}
|
||||
if !sl.isFresh("f-000") {
|
||||
t.Fatal("an expired window must not carry its count forward")
|
||||
}
|
||||
|
||||
sl.noteChange("f-999", t1)
|
||||
if sl.isFresh("f-000") {
|
||||
t.Fatal("a full burst within one window must invalidate the section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionCompleteRefreshGuardsChangedTable(t *testing.T) {
|
||||
sl := newSectionTable([]string{"g", "p"})
|
||||
sl.sections[1].stale = true
|
||||
|
||||
if sl.completeRefresh("g", "q", []string{"h"}, 5000) {
|
||||
t.Fatal("a range the table no longer has must be ignored")
|
||||
}
|
||||
if sl.isFresh("h") {
|
||||
t.Fatal("an ignored refresh must not mark anything fresh")
|
||||
}
|
||||
if !sl.completeRefresh("g", "p", []string{"h"}, 5000) {
|
||||
t.Fatal("the matching range must be accepted")
|
||||
}
|
||||
if !sl.isFresh("h") {
|
||||
t.Fatal("section should be fresh after the refresh")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionCompleteRefreshSplitsMiddleSection(t *testing.T) {
|
||||
sl := newSectionTable([]string{"g", "p"})
|
||||
sl.sections[1].stale = true
|
||||
|
||||
names := make([]string, 0, 2*dirSectionSize+1)
|
||||
for i := 0; i <= 2*dirSectionSize; i++ {
|
||||
names = append(names, fmt.Sprintf("g-%05d", i))
|
||||
}
|
||||
if !sl.completeRefresh("g", "p", names, 5000) {
|
||||
t.Fatal("refresh of the middle section must be accepted")
|
||||
}
|
||||
|
||||
wantBounds := []string{"g", names[dirSectionSize], names[2*dirSectionSize], "p"}
|
||||
if len(sl.bounds) != len(wantBounds) {
|
||||
t.Fatalf("bounds = %v, want %v", sl.bounds, wantBounds)
|
||||
}
|
||||
for i, b := range wantBounds {
|
||||
if sl.bounds[i] != b {
|
||||
t.Fatalf("bounds = %v, want %v", sl.bounds, wantBounds)
|
||||
}
|
||||
}
|
||||
if len(sl.sections) != len(sl.bounds)+1 {
|
||||
t.Fatalf("sections = %d, want %d", len(sl.sections), len(sl.bounds)+1)
|
||||
}
|
||||
for _, name := range []string{"a", "g-00000", names[dirSectionSize], "z"} {
|
||||
if !sl.isFresh(name) {
|
||||
t.Fatalf("%q should be fresh after the split", name)
|
||||
}
|
||||
}
|
||||
if got := sl.sectionOf(names[dirSectionSize+1]); got != 2 {
|
||||
t.Fatalf("sectionOf(%q) = %d, want 2", names[dirSectionSize+1], got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionFloorFencesAbsentNames(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{hi: "m", snapshotTsNs: 5000},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
// a delayed create between the directory floor and the refresh snapshot,
|
||||
// for a name neither the cache nor the listing ever held
|
||||
ghost := func(tsNs int64) {
|
||||
t.Helper()
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: "b-ghost",
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0100644, FileSize: 1},
|
||||
},
|
||||
},
|
||||
TsNs: tsNs,
|
||||
}, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply ghost event: %v", err)
|
||||
}
|
||||
}
|
||||
ghost(4500)
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-ghost")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("pre-snapshot event resurrected an absent name: %v", err)
|
||||
}
|
||||
ghost(6000)
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-ghost")); err != nil {
|
||||
t.Fatalf("post-snapshot event must apply: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnversionedRefreshStaysStale(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, nil)
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{entries: []*filer.Entry{{
|
||||
FullPath: util.FullPath("/dir/b-gap"),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1},
|
||||
}}},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
if mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("an unversioned refresh vouches for nothing and must stay stale")
|
||||
}
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-gap")); err != nil {
|
||||
t.Fatalf("gap fill should still land: %v", err)
|
||||
}
|
||||
if ranges := mc.staleRangesAhead(util.FullPath("/dir"), ""); len(ranges) != 0 {
|
||||
t.Fatalf("an unverifiable section must not be re-listed, got %d ranges", len(ranges))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureListingFreshCoversAllStaleSectionsAhead(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
server := §ionFilerServer{snapshot: 5000, names: []string{"b-1", "n-1"}}
|
||||
client := startSectionFilerServer(t, server)
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
applyChurn(t, mc, "/dir", "n-", sectionHotThreshold, 3000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
if err := EnsureListingFresh(context.Background(), mc, client, util.FullPath("/dir"), ""); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
if !mc.IsNameFresh(util.FullPath("/dir/a-000")) || !mc.IsNameFresh(util.FullPath("/dir/n-000")) {
|
||||
t.Fatal("one call must re-validate every stale section ahead of the start")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionCompleteRefreshSetsFloors(t *testing.T) {
|
||||
sl := newSectionTable([]string{"g", "p"})
|
||||
sl.sections[1].stale = true
|
||||
|
||||
names := make([]string, 0, 2*dirSectionSize+1)
|
||||
for i := 0; i <= 2*dirSectionSize; i++ {
|
||||
names = append(names, fmt.Sprintf("g-%05d", i))
|
||||
}
|
||||
if !sl.completeRefresh("g", "p", names, 7000) {
|
||||
t.Fatal("refresh must be accepted")
|
||||
}
|
||||
for _, name := range []string{"g", "g-99999", names[dirSectionSize+1]} {
|
||||
if got := sl.floorOf(name); got != 7000 {
|
||||
t.Fatalf("floorOf(%q) = %d, want 7000", name, got)
|
||||
}
|
||||
}
|
||||
if got := sl.floorOf("a"); got != 0 {
|
||||
t.Fatalf("floorOf(a) = %d, want 0 for a never-refreshed section", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSectionFloorOutranksOlderTombstone(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, nil)
|
||||
|
||||
event := func(tsNs int64, oldEntry, newEntry *filer_pb.Entry) {
|
||||
t.Helper()
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{OldEntry: oldEntry, NewEntry: newEntry},
|
||||
TsNs: tsNs,
|
||||
}, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply event at %d: %v", tsNs, err)
|
||||
}
|
||||
}
|
||||
pbFile := &filer_pb.Entry{
|
||||
Name: "b-x",
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0100644, FileSize: 1},
|
||||
}
|
||||
event(1500, nil, pbFile) // create
|
||||
event(2000, &filer_pb.Entry{Name: "b-x"}, nil) // delete, leaves a tombstone at 2000
|
||||
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2500, SubscriberMetadataResponseApplyOptions)
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{snapshotTsNs: 5000},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
// the floor at 5000 outranks the tombstone at 2000
|
||||
event(4000, nil, pbFile)
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-x")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("pre-floor event applied over an older tombstone: %v", err)
|
||||
}
|
||||
event(6000, nil, pbFile)
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-x")); err != nil {
|
||||
t.Fatalf("post-floor event must apply: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMismatchedRefreshLeavesStoreAlone(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: util.FullPath("/dir/b-keep"),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1},
|
||||
}, 0); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
// a range the table does not have: the reconcile must not touch the store
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{hi: "q", snapshotTsNs: 5000, entries: []*filer.Entry{{
|
||||
FullPath: util.FullPath("/dir/b-new"),
|
||||
Attr: filer.Attr{Crtime: time.Unix(2, 0), Mtime: time.Unix(2, 0), Mode: 0100644, FileSize: 3},
|
||||
}}},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-new")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("mismatched refresh inserted an entry: %v", err)
|
||||
}
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-keep")); err != nil {
|
||||
t.Fatalf("mismatched refresh swept an entry: %v", err)
|
||||
}
|
||||
if mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("mismatched refresh must not mark anything fresh")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshClearsUnversionedMarker(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
mc.SetPinnedChildFn(func(entry *filer.Entry) bool {
|
||||
return entry.Name() == "b-pin"
|
||||
})
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, nil)
|
||||
for _, name := range []string{"b-local", "b-pin"} {
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: util.FullPath("/dir/" + name),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1},
|
||||
}, 0); err != nil { // versionTsNs 0 leaves the unversioned marker
|
||||
t.Fatalf("seed %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
refreshed := func(name string) *filer.Entry {
|
||||
return &filer.Entry{
|
||||
FullPath: util.FullPath("/dir/" + name),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(2, 0), Mode: 0100644, FileSize: 7},
|
||||
}
|
||||
}
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{snapshotTsNs: 5000, entries: []*filer.Entry{refreshed("b-local"), refreshed("b-pin")}},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
entry, versionTsNs, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-local"))
|
||||
if err != nil || entry.FileSize != 7 {
|
||||
t.Fatalf("b-local = %+v, %v; want the snapshot's size 7", entry, err)
|
||||
}
|
||||
if versionTsNs != 5000 {
|
||||
t.Fatalf("b-local version = %d, want the floor 5000 once the marker is cleared", versionTsNs)
|
||||
}
|
||||
|
||||
// a delayed event below the floor must not roll the snapshot write back
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: "b-local",
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 3, FileMode: 0100644, FileSize: 9},
|
||||
},
|
||||
},
|
||||
TsNs: 4000,
|
||||
}, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply delayed event: %v", err)
|
||||
}
|
||||
if entry, _, err = mc.FindEntry(context.Background(), util.FullPath("/dir/b-local")); err != nil || entry.FileSize != 7 {
|
||||
t.Fatalf("b-local rolled back to %+v, %v", entry, err)
|
||||
}
|
||||
|
||||
// pinned local-only state is neither replaced nor unmarked
|
||||
entry, versionTsNs, err = mc.FindEntry(context.Background(), util.FullPath("/dir/b-pin"))
|
||||
if err != nil || entry.FileSize != 1 {
|
||||
t.Fatalf("b-pin = %+v, %v; want local size 1 kept", entry, err)
|
||||
}
|
||||
if versionTsNs != 0 {
|
||||
t.Fatalf("b-pin version = %d, want 0 while pinned", versionTsNs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshSkipsBuildingDirectory(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, nil)
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
// a rebuild is streaming: its inserts must survive a refresh's sweep
|
||||
if err := mc.BeginDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
|
||||
t.Fatalf("begin build: %v", err)
|
||||
}
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: util.FullPath("/dir/b-built"),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1},
|
||||
}, 0); err != nil {
|
||||
t.Fatalf("insert mid-build: %v", err)
|
||||
}
|
||||
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{snapshotTsNs: 5000},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh: %v", err)
|
||||
}
|
||||
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/b-built")); err != nil {
|
||||
t.Fatalf("refresh swept a mid-build insert: %v", err)
|
||||
}
|
||||
if mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("a skipped refresh must not mark the section fresh")
|
||||
}
|
||||
if err := mc.AbortDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
|
||||
t.Fatalf("abort build: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSectionBorderEntries pins the border semantics: a bound-named entry
|
||||
// belongs to the section starting at the bound, a refresh sweeps [lo, hi)
|
||||
// inclusive of lo and exclusive of hi, and the neighboring sections' entries
|
||||
// come through untouched.
|
||||
func TestSectionBorderEntries(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"g", "p"})
|
||||
for _, name := range []string{"g", "h", "p"} {
|
||||
if err := mc.InsertEntry(context.Background(), &filer.Entry{
|
||||
FullPath: util.FullPath("/dir/" + name),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(1, 0), Mode: 0100644, FileSize: 1},
|
||||
}, 0); err != nil {
|
||||
t.Fatalf("seed %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
applyChurn(t, mc, "/dir", "a-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
applyChurn(t, mc, "/dir", "h-", sectionHotThreshold, 3000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
// the bound name is part of the section starting at it
|
||||
if mc.IsNameFresh(util.FullPath("/dir/a-000")) || mc.IsNameFresh(util.FullPath("/dir/g")) {
|
||||
t.Fatal("both churned sections should be stale")
|
||||
}
|
||||
|
||||
// refreshing [ , g) sweeps its churn but must not reach the bound entry
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{hi: "g", snapshotTsNs: 5000},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh section 0: %v", err)
|
||||
}
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/a-000")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("churned a-000 should be swept: %v", err)
|
||||
}
|
||||
for _, name := range []string{"g", "h", "p"} {
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/"+name)); err != nil {
|
||||
t.Fatalf("%s swept by the neighboring refresh: %v", name, err)
|
||||
}
|
||||
}
|
||||
if !mc.IsNameFresh(util.FullPath("/dir/a-000")) || mc.IsNameFresh(util.FullPath("/dir/g")) {
|
||||
t.Fatal("only the refreshed section should be fresh")
|
||||
}
|
||||
|
||||
// refreshing [g, p) covers the bound entry itself and stops before p
|
||||
if err := mc.enqueueAndWait(context.Background(), metadataApplyRequest{
|
||||
kind: metadataSectionRefresh,
|
||||
buildPath: util.FullPath("/dir"),
|
||||
refresh: §ionRefresh{lo: "g", hi: "p", snapshotTsNs: 5001, entries: []*filer.Entry{{
|
||||
FullPath: util.FullPath("/dir/h"),
|
||||
Attr: filer.Attr{Crtime: time.Unix(1, 0), Mtime: time.Unix(2, 0), Mode: 0100644, FileSize: 7},
|
||||
}}},
|
||||
}); err != nil {
|
||||
t.Fatalf("refresh section 1: %v", err)
|
||||
}
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/g")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("vanished bound entry should be swept by its own section: %v", err)
|
||||
}
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/h-000")); err != filer_pb.ErrNotFound {
|
||||
t.Fatalf("churned h-000 should be swept: %v", err)
|
||||
}
|
||||
if entry, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/h")); err != nil || entry.FileSize != 7 {
|
||||
t.Fatalf("h = %+v, %v; want size 7", entry, err)
|
||||
}
|
||||
if _, _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/p")); err != nil {
|
||||
t.Fatalf("the next bound's entry is outside the range and must survive: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChurnBeyondBuiltEntriesLandsInEdgeSection(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
|
||||
// names sorting past everything the build saw land in the last section
|
||||
applyChurn(t, mc, "/dir", "z-", sectionHotThreshold, 2000, SubscriberMetadataResponseApplyOptions)
|
||||
|
||||
if mc.IsNameFresh(util.FullPath("/dir/z-000")) {
|
||||
t.Fatal("the tail section should be invalidated")
|
||||
}
|
||||
if !mc.IsNameFresh(util.FullPath("/dir/a")) {
|
||||
t.Fatal("the head section must stay fresh")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameAcrossSectionsCountsBoth(t *testing.T) {
|
||||
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{
|
||||
"/": true,
|
||||
"/dir": true,
|
||||
})
|
||||
defer mc.Shutdown()
|
||||
|
||||
buildSectionedDir(t, mc, util.FullPath("/dir"), 1000, []string{"m"})
|
||||
|
||||
for i := 0; i < sectionHotThreshold; i++ {
|
||||
resp := &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: "/dir",
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
OldEntry: &filer_pb.Entry{Name: fmt.Sprintf("a-%03d", i)},
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: fmt.Sprintf("n-%03d", i),
|
||||
Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0100644, FileSize: 1},
|
||||
},
|
||||
NewParentPath: "/dir",
|
||||
},
|
||||
TsNs: 2000 + int64(i),
|
||||
}
|
||||
if err := mc.ApplyMetadataResponse(context.Background(), resp, SubscriberMetadataResponseApplyOptions); err != nil {
|
||||
t.Fatalf("apply rename %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
if mc.IsNameFresh(util.FullPath("/dir/a-000")) {
|
||||
t.Fatal("the vacated side's section should be invalidated")
|
||||
}
|
||||
if mc.IsNameFresh(util.FullPath("/dir/n-000")) {
|
||||
t.Fatal("the landing side's section should be invalidated")
|
||||
}
|
||||
}
|
||||
+33
-6
@@ -179,6 +179,8 @@ type WFS struct {
|
||||
dirMtimeMap map[uint64]time.Time // inode -> mtime/ctime, in-memory overlay for dirs
|
||||
entryValidSec uint64 // kernel FUSE entry cache TTL in seconds
|
||||
attrValidSec uint64 // kernel FUSE attr cache TTL in seconds
|
||||
dirHotWindow time.Duration
|
||||
dirHotThreshold int
|
||||
dirIdleEvict time.Duration
|
||||
|
||||
// openMtimeCache maps inode -> [mtime_sec, mtime_ns] from the last Open.
|
||||
@@ -220,7 +222,11 @@ type WFS struct {
|
||||
lockClient *cluster.LockClient
|
||||
}
|
||||
|
||||
const defaultDirIdleEvict = 10 * time.Minute
|
||||
const (
|
||||
defaultDirHotWindow = 2 * time.Second
|
||||
defaultDirHotThreshold = 64
|
||||
defaultDirIdleEvict = 10 * time.Minute
|
||||
)
|
||||
|
||||
func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
// Only create FilerClient for direct volume access modes
|
||||
@@ -245,6 +251,8 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
)
|
||||
}
|
||||
|
||||
dirHotWindow := defaultDirHotWindow
|
||||
dirHotThreshold := defaultDirHotThreshold
|
||||
dirIdleEvict := defaultDirIdleEvict
|
||||
if option.DirIdleEvictSec != 0 {
|
||||
dirIdleEvict = time.Duration(option.DirIdleEvictSec) * time.Second
|
||||
@@ -273,6 +281,8 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
dirMtimeMap: make(map[uint64]time.Time, 1024),
|
||||
entryValidSec: 1,
|
||||
attrValidSec: 1,
|
||||
dirHotWindow: dirHotWindow,
|
||||
dirHotThreshold: dirHotThreshold,
|
||||
dirIdleEvict: dirIdleEvict,
|
||||
}
|
||||
|
||||
@@ -308,7 +318,11 @@ func NewSeaweedFileSystem(option *Option) *WFS {
|
||||
wfs.inodeToPath.MarkChildrenCached(path)
|
||||
}, func(path util.FullPath) bool {
|
||||
return wfs.inodeToPath.IsChildrenCached(path)
|
||||
}, wfs.onEntryInvalidation, nil)
|
||||
}, wfs.onEntryInvalidation, func(dirPath util.FullPath) {
|
||||
if wfs.inodeToPath.RecordDirectoryUpdate(dirPath, time.Now(), wfs.dirHotWindow, wfs.dirHotThreshold) {
|
||||
wfs.markDirectoryReadThrough(dirPath)
|
||||
}
|
||||
})
|
||||
wfs.metaCache.SetPinnedChildFn(wfs.isLocalOnlyEntry)
|
||||
grace.OnInterrupt(func() {
|
||||
// grace calls os.Exit(0) after all hooks, so WaitForAsyncFlush
|
||||
@@ -600,7 +614,7 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, entryVersion,
|
||||
dir, _ := fullpath.DirAndName()
|
||||
dirPath := util.FullPath(dir)
|
||||
|
||||
if wfs.metaCache.IsDirectoryCached(dirPath) && wfs.metaCache.IsNameFresh(fullpath) {
|
||||
if wfs.metaCache.IsDirectoryCached(dirPath) {
|
||||
cachedEntry, cachedVersionTsNs, cacheErr := wfs.metaCache.FindEntry(context.Background(), fullpath)
|
||||
if cacheErr != nil && cacheErr != filer_pb.ErrNotFound {
|
||||
glog.Errorf("lookupEntry: cache lookup for %s failed: %v", fullpath, cacheErr)
|
||||
@@ -612,9 +626,9 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, entryVersion,
|
||||
return cachedEntry, entryVersion{tsNs: cachedVersionTsNs}, fuse.OK
|
||||
}
|
||||
// Re-check: the directory may have been evicted from cache between
|
||||
// our IsDirectoryCached check and FindEntry.
|
||||
// our IsDirectoryCached check and FindEntry (e.g. markDirectoryReadThrough).
|
||||
// If it's no longer cached, fall through to the filer lookup below.
|
||||
if wfs.metaCache.IsDirectoryCached(dirPath) && wfs.metaCache.IsNameFresh(fullpath) {
|
||||
if wfs.metaCache.IsDirectoryCached(dirPath) {
|
||||
// Authoritative ENOENT only if inodeToPath also has no record.
|
||||
// If the kernel still tracks this inode, the three layers
|
||||
// disagree; trust the filer over the local cache (the
|
||||
@@ -675,7 +689,8 @@ func (wfs *WFS) lookupEntry(fullpath util.FullPath) (*filer.Entry, entryVersion,
|
||||
glog.V(4).Infof("lookupEntry found deferred entry in local cache %s", fullpath)
|
||||
return localEntry, entryVersion{tsNs: localVersionTsNs}, fuse.OK
|
||||
}
|
||||
// Cache eviction (idle, kernel Forget) can drop the local
|
||||
// Creating many files at once can push the directory past
|
||||
// the hot threshold and evict it, which drops the local
|
||||
// placeholder a deferred create left behind. The handle
|
||||
// still holding the unflushed entry is authoritative for
|
||||
// it, so read it from there rather than reporting a file
|
||||
@@ -973,6 +988,18 @@ func (wfs *WFS) ClearCacheDir() {
|
||||
os.RemoveAll(wfs.option.getUniqueCacheDirForRead())
|
||||
}
|
||||
|
||||
// markDirectoryReadThrough drops a hot directory's cached listing. Only safe
|
||||
// from the apply loop (onDirectoryUpdate), where it serializes with a build's
|
||||
// markCachedFn; off-loop callers must use purgeDirectoryCache.
|
||||
func (wfs *WFS) markDirectoryReadThrough(dirPath util.FullPath) {
|
||||
if !wfs.inodeToPath.MarkDirectoryReadThrough(dirPath, time.Now()) {
|
||||
return
|
||||
}
|
||||
if err := wfs.metaCache.DeleteFolderChildren(context.Background(), dirPath); err != nil {
|
||||
glog.V(2).Infof("clear dir cache %s: %v", dirPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
// purgeDirectoryCache drops a directory's cached listing from off the apply loop
|
||||
// (idle eviction, kernel Forget, copy-range fallback), routing through it so a
|
||||
// stale wipe can't strand a concurrently-rebuilt directory cached-but-empty.
|
||||
|
||||
@@ -284,16 +284,6 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
|
||||
return fuse.EIO
|
||||
}
|
||||
|
||||
// Serve the maintained-but-unverified cache if the filer is unreachable.
|
||||
if err := meta_cache.EnsureListingFresh(context.Background(), wfs.metaCache, wfs, dirPath, ""); err != nil {
|
||||
if errors.Is(err, meta_cache.ErrRefreshRangeTooLarge) {
|
||||
// re-tile with a full rebuild; serve this request direct
|
||||
wfs.purgeDirectoryCache(dirPath)
|
||||
return wfs.readDirectoryDirect(input, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
glog.V(1).Infof("refresh %s sections: %v", dirPath, err)
|
||||
}
|
||||
|
||||
// Load entries from beginning to fill cache up to the requested offset
|
||||
storeLastName, loadErr := wfs.metaCache.ListDirectoryEntries(readdirContext, dirPath, "", false, skipCount+int64(batchSize), func(entry *filer.Entry) (bool, error) {
|
||||
dh.entryStream = append(dh.entryStream, entry)
|
||||
@@ -351,16 +341,6 @@ func (wfs *WFS) doReadDirectory(input *fuse.ReadIn, out DirEntrySink, isPlusMode
|
||||
lastEntryName = dh.lastListedName
|
||||
}
|
||||
|
||||
// Serve the maintained-but-unverified cache if the filer is unreachable.
|
||||
if err := meta_cache.EnsureListingFresh(context.Background(), wfs.metaCache, wfs, dirPath, lastEntryName); err != nil {
|
||||
if errors.Is(err, meta_cache.ErrRefreshRangeTooLarge) {
|
||||
// re-tile with a full rebuild; serve this request direct
|
||||
wfs.purgeDirectoryCache(dirPath)
|
||||
return wfs.readDirectoryDirect(input, out, dh, dirPath, processEachEntryFn)
|
||||
}
|
||||
glog.V(1).Infof("refresh %s sections: %v", dirPath, err)
|
||||
}
|
||||
|
||||
bufferFull := false
|
||||
storeLastName, loadErr := wfs.metaCache.ListDirectoryEntries(readdirContext, dirPath, lastEntryName, false, int64(batchSize), func(entry *filer.Entry) (bool, error) {
|
||||
currentIndex := int64(len(dh.entryStream))
|
||||
|
||||
@@ -336,7 +336,7 @@ func TestBufferedBuildEventReinvalidatesOnCompletion(t *testing.T) {
|
||||
t.Fatalf("insert listing entry: %v", err)
|
||||
}
|
||||
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 1000, nil); err != nil {
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 1000); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
wfs.metaCache.WaitForEntryInvalidations()
|
||||
@@ -846,7 +846,7 @@ func TestFloorProtectsSnapshotStateFromDelayedEvents(t *testing.T) {
|
||||
}, 2000); err != nil {
|
||||
t.Fatalf("insert listing entry: %v", err)
|
||||
}
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000, nil); err != nil {
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
@@ -1131,7 +1131,7 @@ func TestAbsenceFloorBlocksGhostCreate(t *testing.T) {
|
||||
}, 0); err != nil {
|
||||
t.Fatalf("insert listing entry: %v", err)
|
||||
}
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000, nil); err != nil {
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 2000); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
@@ -1281,7 +1281,7 @@ func TestNewerAbsenceFloorOverridesOlderTombstone(t *testing.T) {
|
||||
if err := wfs.metaCache.BeginDirectoryBuild(context.Background(), util.FullPath("/dir")); err != nil {
|
||||
t.Fatalf("begin build: %v", err)
|
||||
}
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 3000, nil); err != nil {
|
||||
if err := wfs.metaCache.CompleteDirectoryBuild(context.Background(), util.FullPath("/dir"), 3000); err != nil {
|
||||
t.Fatalf("complete build: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,215 +0,0 @@
|
||||
package volume_move
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
// EcShardMove is one planned relocation of mounted shards to another server.
|
||||
type EcShardMove struct {
|
||||
VolumeId needle.VolumeId
|
||||
Collection string
|
||||
ShardIds []erasure_coding.ShardId
|
||||
Source pb.ServerAddress
|
||||
Target pb.ServerAddress
|
||||
// TargetDisk picks the destination disk (0 lets the server pick).
|
||||
TargetDisk uint32
|
||||
}
|
||||
|
||||
// EcMoveOptions control MoveEcShards.
|
||||
type EcMoveOptions struct {
|
||||
// IoBytePerSecond limits the shard copy rate; 0 falls back to the volume
|
||||
// server's maintenance rate.
|
||||
IoBytePerSecond int64
|
||||
// Writer receives human-readable progress lines (nil discards them).
|
||||
Writer io.Writer
|
||||
// Progress, when set, receives percent/stage callbacks as the move advances.
|
||||
Progress func(percent float64, stage string)
|
||||
}
|
||||
|
||||
// MoveEcShards relocates mounted shards: copy+mount on the target, verify the
|
||||
// target registered them, then unmount+delete on the source. The verification
|
||||
// gates the destructive half — a copy/mount RPC can return OK while the shard
|
||||
// is not loadable on the target, and deleting the source then would lose it;
|
||||
// on a mismatch the source is kept so the caller can retry.
|
||||
func (m *Mover) MoveEcShards(ctx context.Context, move EcShardMove, opts EcMoveOptions) error {
|
||||
writer := opts.Writer
|
||||
if writer == nil {
|
||||
writer = io.Discard
|
||||
}
|
||||
progress := opts.Progress
|
||||
if progress == nil {
|
||||
progress = func(float64, string) {}
|
||||
}
|
||||
|
||||
// A same-server "move" cannot be expressed with these RPCs: the source
|
||||
// delete is server-wide, so it would erase the just-copied shard. Removing
|
||||
// a duplicate shard in place is RemoveEcShards. SameServer, not ==:
|
||||
// "node:8080" and "node:8080.18080" are one server.
|
||||
if SameServer(move.Source, move.Target) {
|
||||
return fmt.Errorf("refusing EC shard move of volume %d shard(s) %v onto its own server %s: the source delete is server-wide", move.VolumeId, move.ShardIds, move.Source)
|
||||
}
|
||||
|
||||
progress(10, fmt.Sprintf("copying EC shard(s) %d.%v from %s to %s", move.VolumeId, move.ShardIds, move.Source, move.Target))
|
||||
if err := m.CopyAndMountEcShards(ctx, move.VolumeId, move.Collection, move.ShardIds, move.Source, move.Target, move.TargetDisk, opts.IoBytePerSecond, writer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
progress(40, fmt.Sprintf("verifying EC shard(s) %d.%v on %s", move.VolumeId, move.ShardIds, move.Target))
|
||||
if err := m.VerifyEcShards(ctx, move.VolumeId, move.Target, move.ShardIds); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
progress(50, fmt.Sprintf("unmounting EC shard(s) %d.%v from %s", move.VolumeId, move.ShardIds, move.Source))
|
||||
fmt.Fprintf(writer, "unmount %d.%v from %s\n", move.VolumeId, move.ShardIds, move.Source)
|
||||
if err := m.UnmountEcShards(ctx, move.VolumeId, move.Source, move.ShardIds); err != nil {
|
||||
return fmt.Errorf("unmount %d.%v from %s: %v", move.VolumeId, move.ShardIds, move.Source, err)
|
||||
}
|
||||
|
||||
progress(75, fmt.Sprintf("deleting EC shard(s) %d.%v from %s", move.VolumeId, move.ShardIds, move.Source))
|
||||
fmt.Fprintf(writer, "delete %d.%v from %s\n", move.VolumeId, move.ShardIds, move.Source)
|
||||
if err := m.DeleteEcShards(ctx, move.VolumeId, move.Collection, move.Source, move.ShardIds); err != nil {
|
||||
return fmt.Errorf("delete %d.%v from %s: %v", move.VolumeId, move.ShardIds, move.Source, err)
|
||||
}
|
||||
|
||||
progress(100, fmt.Sprintf("moved EC shard(s) %d.%v from %s to %s", move.VolumeId, move.ShardIds, move.Source, move.Target))
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyAndMountEcShards has the target copy the shards (with their .ecx/.ecj/
|
||||
// .vif/.ecsum sidecars) from source and mount them. A same-address call skips
|
||||
// the copy and just mounts — ec.encode uses that to bring freshly generated
|
||||
// shards online in place.
|
||||
func (m *Mover) CopyAndMountEcShards(ctx context.Context, volumeId needle.VolumeId, collection string, shardIds []erasure_coding.ShardId, source, target pb.ServerAddress, targetDisk uint32, ioBytePerSecond int64, writer io.Writer) error {
|
||||
if writer == nil {
|
||||
writer = io.Discard
|
||||
}
|
||||
// The target dials the embedded source itself; a malformed one would
|
||||
// abort the target server, not this client.
|
||||
if !SameServer(target, source) {
|
||||
if err := checkDialable(source); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return m.withClient(false, target, func(client volume_server_pb.VolumeServerClient) error {
|
||||
if !SameServer(target, source) {
|
||||
fmt.Fprintf(writer, "copy %d.%v %s => %s\n", volumeId, shardIds, source, target)
|
||||
_, copyErr := client.VolumeEcShardsCopy(ctx, &volume_server_pb.VolumeEcShardsCopyRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Collection: collection,
|
||||
ShardIds: erasure_coding.ShardIdsToUint32(shardIds),
|
||||
CopyEcxFile: true,
|
||||
CopyEcjFile: true,
|
||||
CopyVifFile: true,
|
||||
CopyEcsumFile: true, // propagate the bitrot sidecar with the shards (no-op if the source has none)
|
||||
SourceDataNode: string(source),
|
||||
DiskId: targetDisk,
|
||||
IoBytePerSecond: ioBytePerSecond,
|
||||
})
|
||||
if copyErr != nil {
|
||||
return fmt.Errorf("copy %d.%v %s => %s: %v", volumeId, shardIds, source, target, copyErr)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(writer, "mount %d.%v on %s\n", volumeId, shardIds, target)
|
||||
_, mountErr := client.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Collection: collection,
|
||||
ShardIds: erasure_coding.ShardIdsToUint32(shardIds),
|
||||
})
|
||||
if mountErr != nil {
|
||||
return fmt.Errorf("mount %d.%v on %s: %v", volumeId, shardIds, target, mountErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// VerifyEcShards confirms server has every shard in shardIds registered for
|
||||
// the volume.
|
||||
func (m *Mover) VerifyEcShards(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, shardIds []erasure_coding.ShardId) error {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
resp, err := client.VolumeEcShardsInfo(ctx, &volume_server_pb.VolumeEcShardsInfoRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("verify EC shard(s) on %s for volume %d: %v", server, volumeId, err)
|
||||
}
|
||||
var bits, zeroSized erasure_coding.ShardBits
|
||||
for _, s := range resp.EcShardInfos {
|
||||
if s.VolumeId != uint32(volumeId) || s.ShardId >= erasure_coding.MaxShardCount {
|
||||
continue
|
||||
}
|
||||
// A zero-sized shard is residue of a failed operation, not a
|
||||
// shard; counting it as present would let a broken copy pass
|
||||
// verification and the source be deleted behind it.
|
||||
if s.Size <= 0 {
|
||||
zeroSized = zeroSized.Set(erasure_coding.ShardId(s.ShardId))
|
||||
continue
|
||||
}
|
||||
bits = bits.Set(erasure_coding.ShardId(s.ShardId))
|
||||
}
|
||||
for _, sid := range shardIds {
|
||||
if bits.Has(sid) {
|
||||
continue
|
||||
}
|
||||
if zeroSized.Has(sid) {
|
||||
return fmt.Errorf("%s has a zero-sized EC shard %d.%d after copy/mount; keeping source", server, volumeId, sid)
|
||||
}
|
||||
return fmt.Errorf("%s missing EC shard %d.%d after copy/mount; keeping source", server, volumeId, sid)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// MountEcShards mounts shards already on server.
|
||||
func (m *Mover) MountEcShards(ctx context.Context, volumeId needle.VolumeId, collection string, server pb.ServerAddress, shardIds []erasure_coding.ShardId) error {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
_, mountErr := client.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Collection: collection,
|
||||
ShardIds: erasure_coding.ShardIdsToUint32(shardIds),
|
||||
})
|
||||
return mountErr
|
||||
})
|
||||
}
|
||||
|
||||
// UnmountEcShards unmounts shards on server.
|
||||
func (m *Mover) UnmountEcShards(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, shardIds []erasure_coding.ShardId) error {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
_, unmountErr := client.VolumeEcShardsUnmount(ctx, &volume_server_pb.VolumeEcShardsUnmountRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
ShardIds: erasure_coding.ShardIdsToUint32(shardIds),
|
||||
})
|
||||
return unmountErr
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteEcShards deletes shards on server. The delete is server-wide: it
|
||||
// removes the shards from every disk of the server.
|
||||
func (m *Mover) DeleteEcShards(ctx context.Context, volumeId needle.VolumeId, collection string, server pb.ServerAddress, shardIds []erasure_coding.ShardId) error {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
_, deleteErr := client.VolumeEcShardsDelete(ctx, &volume_server_pb.VolumeEcShardsDeleteRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Collection: collection,
|
||||
ShardIds: erasure_coding.ShardIdsToUint32(shardIds),
|
||||
})
|
||||
return deleteErr
|
||||
})
|
||||
}
|
||||
|
||||
// RemoveEcShards unmounts then deletes shards in place — the dedup path for a
|
||||
// shard that already has a copy elsewhere.
|
||||
func (m *Mover) RemoveEcShards(ctx context.Context, volumeId needle.VolumeId, collection string, server pb.ServerAddress, shardIds []erasure_coding.ShardId) error {
|
||||
if err := m.UnmountEcShards(ctx, volumeId, server, shardIds); err != nil {
|
||||
return fmt.Errorf("unmount %d.%v from %s: %v", volumeId, shardIds, server, err)
|
||||
}
|
||||
if err := m.DeleteEcShards(ctx, volumeId, collection, server, shardIds); err != nil {
|
||||
return fmt.Errorf("delete %d.%v from %s: %v", volumeId, shardIds, server, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package volume_move
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
)
|
||||
|
||||
func ecMove(shardIds ...erasure_coding.ShardId) EcShardMove {
|
||||
return EcShardMove{
|
||||
VolumeId: 7,
|
||||
Collection: "c1",
|
||||
ShardIds: shardIds,
|
||||
Source: srcAddr,
|
||||
Target: dstAddr,
|
||||
TargetDisk: 2,
|
||||
}
|
||||
}
|
||||
|
||||
func dstShards(shardIds ...uint32) []*volume_server_pb.EcShardInfo {
|
||||
var infos []*volume_server_pb.EcShardInfo
|
||||
for _, sid := range shardIds {
|
||||
infos = append(infos, &volume_server_pb.EcShardInfo{VolumeId: 7, ShardId: sid, Size: 1024})
|
||||
}
|
||||
return infos
|
||||
}
|
||||
|
||||
func TestMoveEcShardsSequence(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
cluster.ecShards[string(dstAddr)] = dstShards(3, 4)
|
||||
|
||||
err := cluster.mover().MoveEcShards(context.Background(), ecMove(3, 4), EcMoveOptions{IoBytePerSecond: 77})
|
||||
if err != nil {
|
||||
t.Fatalf("MoveEcShards: %v", err)
|
||||
}
|
||||
|
||||
assertCalls(t, cluster.callList(), []string{
|
||||
"dst:8080 VolumeEcShardsCopy",
|
||||
"dst:8080 VolumeEcShardsMount",
|
||||
"dst:8080 VolumeEcShardsInfo",
|
||||
"src:8080 VolumeEcShardsUnmount",
|
||||
"src:8080 VolumeEcShardsDelete",
|
||||
})
|
||||
|
||||
copyReq := cluster.ecCopyReqs[0]
|
||||
if !copyReq.CopyEcxFile || !copyReq.CopyEcjFile || !copyReq.CopyVifFile || !copyReq.CopyEcsumFile {
|
||||
t.Errorf("shard sidecars not all copied: %+v", copyReq)
|
||||
}
|
||||
if copyReq.DiskId != 2 || copyReq.SourceDataNode != string(srcAddr) || copyReq.Collection != "c1" || copyReq.IoBytePerSecond != 77 {
|
||||
t.Errorf("copy request not propagated: %+v", copyReq)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveEcShardsVerifyFailureKeepsSource(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
cluster.ecShards[string(dstAddr)] = dstShards(3) // shard 4 didn't register
|
||||
|
||||
err := cluster.mover().MoveEcShards(context.Background(), ecMove(3, 4), EcMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "missing EC shard 7.4") {
|
||||
t.Fatalf("expected missing-shard error, got: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "src:8080 VolumeEcShardsUnmount" || call == "src:8080 VolumeEcShardsDelete" {
|
||||
t.Fatalf("source touched despite verification failure: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveEcShardsZeroSizedDestinationKeepsSource(t *testing.T) {
|
||||
// A zero-sized shard on the destination is residue of a failed operation
|
||||
// (seaweedfs issue 10730); verification must not count it as a delivered
|
||||
// shard, or the source is deleted behind a broken copy.
|
||||
cluster := newFakeCluster()
|
||||
cluster.ecShards[string(dstAddr)] = dstShards(3, 4)
|
||||
cluster.ecShards[string(dstAddr)][1].Size = 0 // shard 4 landed as an empty file
|
||||
|
||||
err := cluster.mover().MoveEcShards(context.Background(), ecMove(3, 4), EcMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "zero-sized EC shard 7.4") {
|
||||
t.Fatalf("expected zero-sized-shard rejection, got: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "src:8080 VolumeEcShardsUnmount" || call == "src:8080 VolumeEcShardsDelete" {
|
||||
t.Fatalf("source touched despite zero-sized destination shard: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveEcShardsRejectsSameServer(t *testing.T) {
|
||||
// The second target is the same server written with an explicit grpc port;
|
||||
// the guard must see through the representation difference.
|
||||
for _, target := range []pb.ServerAddress{srcAddr, pb.ServerAddress("src:8080.18080")} {
|
||||
cluster := newFakeCluster()
|
||||
move := ecMove(3)
|
||||
move.Target = target
|
||||
|
||||
err := cluster.mover().MoveEcShards(context.Background(), move, EcMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "its own server") {
|
||||
t.Fatalf("target %q: expected same-server rejection, got: %v", target, err)
|
||||
}
|
||||
if len(cluster.callList()) != 0 {
|
||||
t.Fatalf("target %q: RPCs issued for a rejected move: %v", target, cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveEcShards(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
|
||||
err := cluster.mover().RemoveEcShards(context.Background(), 7, "c1", srcAddr, []erasure_coding.ShardId{3})
|
||||
if err != nil {
|
||||
t.Fatalf("RemoveEcShards: %v", err)
|
||||
}
|
||||
|
||||
assertCalls(t, cluster.callList(), []string{
|
||||
"src:8080 VolumeEcShardsUnmount",
|
||||
"src:8080 VolumeEcShardsDelete",
|
||||
})
|
||||
}
|
||||
|
||||
func TestCopyAndMountEcShardsSameAddressMountsOnly(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
|
||||
err := cluster.mover().CopyAndMountEcShards(context.Background(), 7, "c1", []erasure_coding.ShardId{3}, srcAddr, srcAddr, 0, 0, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CopyAndMountEcShards: %v", err)
|
||||
}
|
||||
|
||||
assertCalls(t, cluster.callList(), []string{
|
||||
"src:8080 VolumeEcShardsMount",
|
||||
})
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
package volume_move
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// fakeCluster fakes the volume servers a move touches. It records every RPC as
|
||||
// "<server> <method>" so tests can assert the exact sequence, and lets tests
|
||||
// inject per-RPC errors and per-server state.
|
||||
type fakeCluster struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
|
||||
// errs fails an RPC, keyed "<server> <method>".
|
||||
errs map[string]error
|
||||
// readonly is each server's VolumeStatus.IsReadOnly answer.
|
||||
readonly map[string]bool
|
||||
// status is each server's ReadVolumeFileStatus answer.
|
||||
status map[string]*volume_server_pb.ReadVolumeFileStatusResponse
|
||||
// statusFailures fails a server's next N ReadVolumeFileStatus calls, e.g.
|
||||
// to model a target that has no volume before the copy but one after. The
|
||||
// failures use statusFailureErr, defaulting to a server-side (gRPC code
|
||||
// Unknown) volume-not-found error.
|
||||
statusFailures map[string]int
|
||||
statusFailureErr error
|
||||
// statusSeq overrides a server's next ReadVolumeFileStatus answers in
|
||||
// order, e.g. to model a source that changes between two reads.
|
||||
statusSeq map[string][]*volume_server_pb.ReadVolumeFileStatusResponse
|
||||
// ecShards is each server's VolumeEcShardsInfo answer.
|
||||
ecShards map[string][]*volume_server_pb.EcShardInfo
|
||||
|
||||
lastAppendAtNs uint64
|
||||
|
||||
copyReqs []*volume_server_pb.VolumeCopyRequest
|
||||
deleteReqs []*volume_server_pb.VolumeDeleteRequest
|
||||
ecCopyReqs []*volume_server_pb.VolumeEcShardsCopyRequest
|
||||
}
|
||||
|
||||
func newFakeCluster() *fakeCluster {
|
||||
return &fakeCluster{
|
||||
errs: make(map[string]error),
|
||||
readonly: make(map[string]bool),
|
||||
status: make(map[string]*volume_server_pb.ReadVolumeFileStatusResponse),
|
||||
statusFailures: make(map[string]int),
|
||||
statusSeq: make(map[string][]*volume_server_pb.ReadVolumeFileStatusResponse),
|
||||
ecShards: make(map[string][]*volume_server_pb.EcShardInfo),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *fakeCluster) mover() *Mover {
|
||||
return NewMoverWithClientFunc(func(streamingMode bool, addr pb.ServerAddress, fn func(client volume_server_pb.VolumeServerClient) error) error {
|
||||
return fn(&fakeClient{cluster: c, addr: string(addr)})
|
||||
})
|
||||
}
|
||||
|
||||
func (c *fakeCluster) record(addr, method string) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.calls = append(c.calls, addr+" "+method)
|
||||
return c.errs[addr+" "+method]
|
||||
}
|
||||
|
||||
func (c *fakeCluster) callList() []string {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return append([]string(nil), c.calls...)
|
||||
}
|
||||
|
||||
// fakeClient answers as the volume server at addr. Unused VolumeServerClient
|
||||
// methods panic via the embedded nil interface.
|
||||
type fakeClient struct {
|
||||
volume_server_pb.VolumeServerClient
|
||||
cluster *fakeCluster
|
||||
addr string
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeStatus(ctx context.Context, req *volume_server_pb.VolumeStatusRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeStatusResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeStatus"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeStatusResponse{IsReadOnly: f.cluster.readonly[f.addr]}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeMarkReadonly(ctx context.Context, req *volume_server_pb.VolumeMarkReadonlyRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeMarkReadonlyResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeMarkReadonly"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeMarkReadonlyResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeMarkWritable(ctx context.Context, req *volume_server_pb.VolumeMarkWritableRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeMarkWritableResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeMarkWritable"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeMarkWritableResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ReadVolumeFileStatus(ctx context.Context, req *volume_server_pb.ReadVolumeFileStatusRequest, opts ...grpc.CallOption) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "ReadVolumeFileStatus"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.cluster.mu.Lock()
|
||||
failures := f.cluster.statusFailures[f.addr]
|
||||
if failures > 0 {
|
||||
f.cluster.statusFailures[f.addr] = failures - 1
|
||||
}
|
||||
failureErr := f.cluster.statusFailureErr
|
||||
var seqResp *volume_server_pb.ReadVolumeFileStatusResponse
|
||||
if failures == 0 {
|
||||
if seq := f.cluster.statusSeq[f.addr]; len(seq) > 0 {
|
||||
seqResp = seq[0]
|
||||
f.cluster.statusSeq[f.addr] = seq[1:]
|
||||
}
|
||||
}
|
||||
resp := f.cluster.status[f.addr]
|
||||
f.cluster.mu.Unlock()
|
||||
if failures > 0 {
|
||||
if failureErr != nil {
|
||||
return nil, failureErr
|
||||
}
|
||||
return nil, status.Error(codes.Unknown, fmt.Sprintf("not found volume id %d", req.VolumeId))
|
||||
}
|
||||
if seqResp != nil {
|
||||
return seqResp, nil
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, status.Error(codes.Unknown, fmt.Sprintf("not found volume id %d", req.VolumeId))
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeCopy(ctx context.Context, req *volume_server_pb.VolumeCopyRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[volume_server_pb.VolumeCopyResponse], error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeCopy"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.cluster.mu.Lock()
|
||||
f.cluster.copyReqs = append(f.cluster.copyReqs, req)
|
||||
lastAppendAtNs := f.cluster.lastAppendAtNs
|
||||
f.cluster.mu.Unlock()
|
||||
return &fakeCopyStream{resps: []*volume_server_pb.VolumeCopyResponse{
|
||||
{ProcessedBytes: 1024},
|
||||
{LastAppendAtNs: lastAppendAtNs},
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeTailReceiver(ctx context.Context, req *volume_server_pb.VolumeTailReceiverRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeTailReceiverResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeTailReceiver"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeTailReceiverResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeDelete(ctx context.Context, req *volume_server_pb.VolumeDeleteRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeDeleteResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeDelete"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.cluster.mu.Lock()
|
||||
f.cluster.deleteReqs = append(f.cluster.deleteReqs, req)
|
||||
f.cluster.mu.Unlock()
|
||||
return &volume_server_pb.VolumeDeleteResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeConfigure(ctx context.Context, req *volume_server_pb.VolumeConfigureRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeConfigureResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeConfigure"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeConfigureResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeEcShardsCopy(ctx context.Context, req *volume_server_pb.VolumeEcShardsCopyRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeEcShardsCopyResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeEcShardsCopy"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.cluster.mu.Lock()
|
||||
f.cluster.ecCopyReqs = append(f.cluster.ecCopyReqs, req)
|
||||
f.cluster.mu.Unlock()
|
||||
return &volume_server_pb.VolumeEcShardsCopyResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeEcShardsMount(ctx context.Context, req *volume_server_pb.VolumeEcShardsMountRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeEcShardsMountResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeEcShardsMount"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeEcShardsMountResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeEcShardsUnmount(ctx context.Context, req *volume_server_pb.VolumeEcShardsUnmountRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeEcShardsUnmountResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeEcShardsUnmount"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeEcShardsUnmountResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeEcShardsDelete(ctx context.Context, req *volume_server_pb.VolumeEcShardsDeleteRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeEcShardsDeleteResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeEcShardsDelete"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeEcShardsDeleteResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) VolumeEcShardsInfo(ctx context.Context, req *volume_server_pb.VolumeEcShardsInfoRequest, opts ...grpc.CallOption) (*volume_server_pb.VolumeEcShardsInfoResponse, error) {
|
||||
if err := f.cluster.record(f.addr, "VolumeEcShardsInfo"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &volume_server_pb.VolumeEcShardsInfoResponse{EcShardInfos: f.cluster.ecShards[f.addr]}, nil
|
||||
}
|
||||
|
||||
// fakeCopyStream feeds the canned VolumeCopy responses, then io.EOF.
|
||||
type fakeCopyStream struct {
|
||||
grpc.ClientStream
|
||||
resps []*volume_server_pb.VolumeCopyResponse
|
||||
}
|
||||
|
||||
func (s *fakeCopyStream) Recv() (*volume_server_pb.VolumeCopyResponse, error) {
|
||||
if len(s.resps) == 0 {
|
||||
return nil, io.EOF
|
||||
}
|
||||
resp := s.resps[0]
|
||||
s.resps = s.resps[1:]
|
||||
return resp, nil
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
// Package volume_move implements the volume and EC shard move sequences shared
|
||||
// by the interactive shell commands (volume.move, volume.balance, ec.balance,
|
||||
// volume.tier.move, ...) and the maintenance workers (balance, ec_balance,
|
||||
// volume_tiering). The RPCs go through an injectable ClientFunc so every
|
||||
// sequence can be unit tested against a fake volume server client.
|
||||
package volume_move
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/operation"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// ClientFunc runs fn with a client for the volume server at addr. It matches
|
||||
// operation.WithVolumeServerClient, which production movers use to dial real
|
||||
// servers; tests substitute a fake client.
|
||||
type ClientFunc func(streamingMode bool, addr pb.ServerAddress, fn func(client volume_server_pb.VolumeServerClient) error) error
|
||||
|
||||
// Mover executes volume and EC shard moves against volume servers.
|
||||
type Mover struct {
|
||||
withClient ClientFunc
|
||||
}
|
||||
|
||||
func NewMover(grpcDialOption grpc.DialOption) *Mover {
|
||||
return &Mover{withClient: func(streamingMode bool, addr pb.ServerAddress, fn func(client volume_server_pb.VolumeServerClient) error) error {
|
||||
// Validated here, the single point every mover RPC dials through:
|
||||
// handing a malformed address (an unvalidated -source/-target flag)
|
||||
// to the dialer would abort the whole process instead of failing the
|
||||
// move.
|
||||
if err := checkDialable(addr); err != nil {
|
||||
return err
|
||||
}
|
||||
return operation.WithVolumeServerClient(streamingMode, addr, grpcDialOption, fn)
|
||||
}}
|
||||
}
|
||||
|
||||
// checkDialable rejects an address whose grpc normalization would abort the
|
||||
// process: for the "host:port" form, ServerAddress.ToGrpcAddress falls back
|
||||
// to a parser that calls glog.Fatalf when the port is not numeric. Everything
|
||||
// else either normalizes cleanly or fails at dial time as an ordinary error.
|
||||
// It also guards the source addresses embedded in copy/tail requests: the
|
||||
// receiving volume server dials those through the same fatal parser, so an
|
||||
// unchecked malformed source would terminate the destination server.
|
||||
func checkDialable(addr pb.ServerAddress) error {
|
||||
s := string(addr)
|
||||
colon := strings.LastIndex(s, ":")
|
||||
if colon < 0 || colon+1 >= len(s) {
|
||||
return nil // no port part; handed to the dialer untouched
|
||||
}
|
||||
ports := s[colon+1:]
|
||||
if dot := strings.LastIndex(ports, "."); dot >= 0 {
|
||||
// "port.grpcPort": different dial paths canonicalize a half-malformed
|
||||
// form differently (the method splices the grpc part in unparsed; the
|
||||
// string helper falls back to the http part + 10000), so a bad
|
||||
// component could dial an unintended server or reach the fatal
|
||||
// parser. Require both components numeric.
|
||||
if _, err := strconv.ParseUint(ports[:dot], 10, 64); err != nil {
|
||||
return fmt.Errorf("invalid volume server address %q: port %q is not a number", s, ports[:dot])
|
||||
}
|
||||
if _, err := strconv.ParseUint(ports[dot+1:], 10, 64); err != nil {
|
||||
return fmt.Errorf("invalid volume server address %q: grpc port %q is not a number", s, ports[dot+1:])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, err := strconv.ParseUint(ports, 10, 64); err != nil {
|
||||
return fmt.Errorf("invalid volume server address %q: port %q is not a number", s, ports)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewMoverWithClientFunc builds a Mover on a custom transport.
|
||||
func NewMoverWithClientFunc(withClient ClientFunc) *Mover {
|
||||
return &Mover{withClient: withClient}
|
||||
}
|
||||
|
||||
// SameServer reports whether two addresses name the same volume server. The
|
||||
// gRPC endpoint identifies the server process — each has exactly one — so
|
||||
// "node:8080" and "node:8080.18080" compare equal, while two servers sharing
|
||||
// a degenerate HTTP address (e.g. port 0 in test harnesses) stay distinct.
|
||||
// The normalization is non-fatal, unlike ServerAddress.ToGrpcAddress, whose
|
||||
// parser exits the process on a malformed port; anything unparsable compares
|
||||
// as its literal self.
|
||||
func SameServer(a, b pb.ServerAddress) bool {
|
||||
return grpcEndpoint(string(a)) == grpcEndpoint(string(b))
|
||||
}
|
||||
|
||||
// grpcEndpoint mirrors ServerAddress.ToGrpcAddress ("host:port" gets the
|
||||
// +10000 grpc port; "host:port.grpcPort" names it explicitly) but returns a
|
||||
// malformed address unchanged instead of exiting.
|
||||
func grpcEndpoint(addr string) string {
|
||||
colon := strings.LastIndex(addr, ":")
|
||||
if colon < 0 || colon+1 >= len(addr) {
|
||||
return addr
|
||||
}
|
||||
host, ports := addr[:colon], addr[colon+1:]
|
||||
if dot := strings.LastIndex(ports, "."); dot >= 0 {
|
||||
if grpcPort, err := strconv.Atoi(ports[dot+1:]); err == nil {
|
||||
return util.JoinHostPort(host, grpcPort)
|
||||
}
|
||||
return addr
|
||||
}
|
||||
httpPort, err := strconv.Atoi(ports)
|
||||
if err != nil {
|
||||
return addr
|
||||
}
|
||||
return util.JoinHostPort(host, httpPort+10000)
|
||||
}
|
||||
@@ -1,503 +0,0 @@
|
||||
package volume_move
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// ErrSourceKeptReadonly marks a move failure whose recovery deliberately keeps
|
||||
// the source volume readonly — the target copy may hold data the source lacks
|
||||
// (an ambiguous source delete, or an undeletable stale copy). Callers that
|
||||
// froze the source themselves must not thaw it on this error.
|
||||
var ErrSourceKeptReadonly = errors.New("the source volume is deliberately kept readonly")
|
||||
|
||||
// VolumeMoveOptions control LiveMoveVolume.
|
||||
type VolumeMoveOptions struct {
|
||||
// DiskType changes the volume's disk type on the target ("" keeps it).
|
||||
DiskType string
|
||||
// IoBytePerSecond throttles the copy (0 = unlimited).
|
||||
IoBytePerSecond int64
|
||||
// IdleTimeout is how long the tail phase waits for in-flight requests to
|
||||
// drain (default 5s).
|
||||
IdleTimeout time.Duration
|
||||
// Writer receives human-readable progress lines (nil discards them).
|
||||
Writer io.Writer
|
||||
// Progress, when set, receives percent/stage callbacks as the move advances.
|
||||
Progress func(percent float64, stage string)
|
||||
}
|
||||
|
||||
func (o *VolumeMoveOptions) fillDefaults() {
|
||||
if o.IdleTimeout <= 0 {
|
||||
o.IdleTimeout = 5 * time.Second
|
||||
}
|
||||
if o.Writer == nil {
|
||||
o.Writer = io.Discard
|
||||
}
|
||||
if o.Progress == nil {
|
||||
o.Progress = func(float64, string) {}
|
||||
}
|
||||
}
|
||||
|
||||
// LiveMoveVolume moves one volume between volume servers while it keeps serving
|
||||
// reads: freeze the source (readonly), copy, tail to drain in-flight requests,
|
||||
// verify the target matches the source, then delete the source. A failure
|
||||
// before the source delete restores the source's writability if this move is
|
||||
// what froze it.
|
||||
func (m *Mover) LiveMoveVolume(ctx context.Context, volumeId needle.VolumeId, source, target pb.ServerAddress, opts VolumeMoveOptions) (err error) {
|
||||
opts.fillDefaults()
|
||||
|
||||
// VolumeCopy tears down any existing copy on the target first, so a
|
||||
// same-server "move" would delete the volume and then fail to read it.
|
||||
// SameServer, not ==: "node:8080" and "node:8080.18080" are one server.
|
||||
if SameServer(source, target) {
|
||||
return fmt.Errorf("refusing to move volume %d onto its own server %s", volumeId, source)
|
||||
}
|
||||
|
||||
opts.Progress(10, fmt.Sprintf("marking volume %d readonly on %s", volumeId, source))
|
||||
sourceWasWritable, err := m.ensureVolumeReadonly(ctx, volumeId, source, true)
|
||||
// The source stays authoritative until its delete succeeds; on any earlier
|
||||
// failure undo the freeze this move added and clean up the target copy.
|
||||
// Installed before the error check: the marking RPC itself can fail after
|
||||
// the server applied the mark (e.g. its master notification failed).
|
||||
var copyStarted, copyCompleted, sourceDeleteStarted bool
|
||||
var targetHadVolume, targetStateKnown bool
|
||||
defer func() {
|
||||
if err != nil {
|
||||
if sourceDeleteStarted {
|
||||
// Past verification: the target is complete and may already hold
|
||||
// new writes, and the delete may or may not have reached the
|
||||
// source. Deleting the target or reopening the source could fork
|
||||
// the volume; keep the source readonly.
|
||||
fmt.Fprintf(opts.Writer, "volume %d is left readonly on %s: the source delete failed with the verified copy on %s mounted\n", volumeId, source, target)
|
||||
glog.Warningf("volume %d is left readonly on %s: the source delete failed with the verified copy on %s mounted", volumeId, source, target)
|
||||
err = fmt.Errorf("%w: %w", ErrSourceKeptReadonly, err)
|
||||
return
|
||||
}
|
||||
// The cleanup runs on its own deadline so an abort via cancelled
|
||||
// context still cleans up.
|
||||
cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cleanupCancel()
|
||||
cleanupTarget := copyCompleted
|
||||
if copyStarted && !copyCompleted {
|
||||
// The server can finish the copy and mount the target even when
|
||||
// the client loses the stream, so probe rather than assume.
|
||||
exists, known := m.probeVolume(cleanupCtx, volumeId, target)
|
||||
switch {
|
||||
case known && !exists:
|
||||
// nothing mounted on the target; just undo the freeze below
|
||||
case known && exists && targetStateKnown && !targetHadVolume:
|
||||
// the failed copy created it; remove it so the source stays
|
||||
// the only replica
|
||||
cleanupTarget = true
|
||||
default:
|
||||
// A copy may sit mounted on the target and its provenance
|
||||
// cannot be proven: the prior state is unknown, the target
|
||||
// held a replica before the move, or the probe failed.
|
||||
// Deleting it risks someone else's replica; reopening the
|
||||
// source beside it risks two writable replicas taking
|
||||
// divergent writes. Keep the source readonly.
|
||||
fmt.Fprintf(opts.Writer, "volume %d is left readonly on %s: a copy may exist on %s but its origin cannot be determined; delete one side explicitly, then re-run the move\n", volumeId, source, target)
|
||||
glog.Warningf("volume %d is left readonly on %s: a copy may exist on %s but its origin cannot be determined; delete one side explicitly, then re-run the move", volumeId, source, target)
|
||||
err = fmt.Errorf("%w: %w", ErrSourceKeptReadonly, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if cleanupTarget {
|
||||
// The target copy may be missing tailed entries; remove it so
|
||||
// the source stays the only replica.
|
||||
if dErr := m.DeleteVolume(cleanupCtx, volumeId, target, false, true); dErr != nil {
|
||||
// Restoring the source while the stale target stays mounted
|
||||
// risks divergent replicas; keep the source readonly. A
|
||||
// re-run refuses while the copy exists, so name the fix.
|
||||
fmt.Fprintf(opts.Writer, "volume %d is left readonly on %s: failed to delete the incomplete copy on %s: %v; delete that copy, then re-run the move\n", volumeId, source, target, dErr)
|
||||
glog.Warningf("volume %d is left readonly on %s: failed to delete the incomplete copy on %s: %v; delete that copy, then re-run the move", volumeId, source, target, dErr)
|
||||
err = fmt.Errorf("%w: %w", ErrSourceKeptReadonly, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if sourceWasWritable {
|
||||
m.restoreVolumeWritable(volumeId, source)
|
||||
} else {
|
||||
// The hard freeze added on top of a readonly-reporting status is
|
||||
// kept: it is indistinguishable from an operator's mark. It is
|
||||
// not persisted, so a volume server restart clears it.
|
||||
fmt.Fprintf(opts.Writer, "volume %d on %s keeps the readonly mark the move added; volume.mark -writable clears it if the prior readonly state was transient\n", volumeId, source)
|
||||
}
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark volume %d readonly on %s: %v", volumeId, source, err)
|
||||
}
|
||||
|
||||
targetHadVolume, targetStateKnown = m.probeVolume(ctx, volumeId, target)
|
||||
if !sourceWasWritable {
|
||||
// A readonly source next to an existing copy is the signature of a
|
||||
// previous move whose source delete failed — that copy may be the
|
||||
// authoritative one, serving writes the source never saw, and the
|
||||
// copy below would tear it down. No client-side observation proves
|
||||
// otherwise: compaction revision is shared by ordinary replicas,
|
||||
// aggregate sizes shrink under compaction, and any snapshot can be
|
||||
// invalidated by a write right after it. Fail closed on any existing
|
||||
// copy or unknown state; the operator deletes one side explicitly.
|
||||
if !targetStateKnown {
|
||||
err = fmt.Errorf("%w: cannot determine whether %s already holds a copy of volume %d; refusing to overwrite it while the source is readonly", ErrSourceKeptReadonly, target, volumeId)
|
||||
return err
|
||||
}
|
||||
if targetHadVolume {
|
||||
err = fmt.Errorf("%w: volume %d already has a copy on %s while the source on %s is readonly — likely a previous move that did not finish; delete the source to keep that copy, or delete the copy before re-running the move", ErrSourceKeptReadonly, volumeId, target, source)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
opts.Progress(20, fmt.Sprintf("copying volume %d from %s to %s", volumeId, source, target))
|
||||
fmt.Fprintf(opts.Writer, "copying volume %d from %s to %s\n", volumeId, source, target)
|
||||
copyStarted = true
|
||||
lastAppendAtNs, err := m.copyVolumeData(ctx, volumeId, source, target, opts.DiskType, opts.IoBytePerSecond, opts.Writer)
|
||||
if err != nil {
|
||||
return fmt.Errorf("copy volume %d from %s to %s: %v", volumeId, source, target, err)
|
||||
}
|
||||
copyCompleted = true
|
||||
|
||||
opts.Progress(70, fmt.Sprintf("tailing volume %d from %s to %s", volumeId, source, target))
|
||||
fmt.Fprintf(opts.Writer, "tailing volume %d from %s to %s\n", volumeId, source, target)
|
||||
tailFailed := false
|
||||
if tailErr := m.TailVolume(ctx, volumeId, source, target, lastAppendAtNs, opts.IdleTimeout); tailErr != nil {
|
||||
// A tail failure is tolerable only when the volume was already readonly
|
||||
// before this move began: frozen for the whole copy, it should have no
|
||||
// in-flight writes for the tail to drain — and the stability check
|
||||
// below still proves it. A volume this move froze can have stragglers
|
||||
// admitted just before the freeze that only the tail delivers, so
|
||||
// losing the tail there must abort the move.
|
||||
if sourceWasWritable {
|
||||
return fmt.Errorf("tail volume %d from %s to %s: %v", volumeId, source, target, tailErr)
|
||||
}
|
||||
tailFailed = true
|
||||
fmt.Fprintf(opts.Writer, "tail volume %d from %s to %s: %v\n", volumeId, source, target, tailErr)
|
||||
glog.Warningf("tail volume %d from %s to %s: %v", volumeId, source, target, tailErr)
|
||||
}
|
||||
|
||||
// Verify before the point of no return: the source is deleted only when the
|
||||
// target holds at least everything the source does. The source status is
|
||||
// read here, after the tail — a write in flight when the source was frozen
|
||||
// can still land after an earlier read, and a stale snapshot would wave
|
||||
// through an incomplete target.
|
||||
opts.Progress(85, fmt.Sprintf("verifying volume %d on %s", volumeId, target))
|
||||
sourceStatus, err := m.ReadVolumeFileStatus(ctx, volumeId, source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read volume %d status on %s: %v", volumeId, source, err)
|
||||
}
|
||||
if tailFailed {
|
||||
// A successful tail proves the source held still for the idle window; a
|
||||
// tolerated tail failure proved nothing, so substitute the same drain
|
||||
// barrier here: the source status must not change across the window.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(opts.IdleTimeout):
|
||||
}
|
||||
secondStatus, statusErr := m.ReadVolumeFileStatus(ctx, volumeId, source)
|
||||
if statusErr != nil {
|
||||
return fmt.Errorf("re-read volume %d status on %s: %v", volumeId, source, statusErr)
|
||||
}
|
||||
if secondStatus.DatFileSize != sourceStatus.DatFileSize || secondStatus.IdxFileSize != sourceStatus.IdxFileSize || secondStatus.FileCount != sourceStatus.FileCount {
|
||||
return fmt.Errorf("volume %d on %s is still changing after a failed tail; aborting the move", volumeId, source)
|
||||
}
|
||||
sourceStatus = secondStatus
|
||||
}
|
||||
targetStatus, err := m.ReadVolumeFileStatus(ctx, volumeId, target)
|
||||
if err != nil {
|
||||
return fmt.Errorf("verify volume %d on target %s before deleting source: %v", volumeId, target, err)
|
||||
}
|
||||
if err = verifyTargetNotBehind(volumeId, sourceStatus, targetStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
if targetStatus.DatFileSize > sourceStatus.DatFileSize || targetStatus.IdxFileSize > sourceStatus.IdxFileSize || targetStatus.FileCount > sourceStatus.FileCount {
|
||||
// The target announced itself writable when the copy mounted it, so
|
||||
// clients may have written to it during the tail. Those writes live on
|
||||
// the surviving copy; committing keeps them.
|
||||
fmt.Fprintf(opts.Writer, "volume %d on %s has writes beyond the source; they stay with the moved volume\n", volumeId, target)
|
||||
}
|
||||
|
||||
opts.Progress(90, fmt.Sprintf("deleting volume %d from %s", volumeId, source))
|
||||
fmt.Fprintf(opts.Writer, "deleting volume %d from %s\n", volumeId, source)
|
||||
sourceDeleteStarted = true
|
||||
if err = m.DeleteVolume(ctx, volumeId, source, false, true); err != nil {
|
||||
return fmt.Errorf("delete volume %d from %s: %v", volumeId, source, err)
|
||||
}
|
||||
|
||||
opts.Progress(100, fmt.Sprintf("moved volume %d from %s to %s", volumeId, source, target))
|
||||
fmt.Fprintf(opts.Writer, "moved volume %d from %s to %s\n", volumeId, source, target)
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyTargetNotBehind fails when the target holds less than the (frozen)
|
||||
// source — the copy or tail missed data and deleting the source would lose it.
|
||||
// A target that is ahead is not an error: the target serves writes during the
|
||||
// tail, and those belong to the copy that survives the move.
|
||||
func verifyTargetNotBehind(volumeId needle.VolumeId, source, target *volume_server_pb.ReadVolumeFileStatusResponse) error {
|
||||
if target.DatFileSize < source.DatFileSize {
|
||||
return fmt.Errorf("volume %d target is behind the source: .dat %d < %d bytes", volumeId, target.DatFileSize, source.DatFileSize)
|
||||
}
|
||||
if target.IdxFileSize < source.IdxFileSize {
|
||||
return fmt.Errorf("volume %d target is behind the source: .idx %d < %d bytes", volumeId, target.IdxFileSize, source.IdxFileSize)
|
||||
}
|
||||
if target.FileCount < source.FileCount {
|
||||
return fmt.Errorf("volume %d target is behind the source: %d < %d files", volumeId, target.FileCount, source.FileCount)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyVolume freezes the volume on source, copies it to target, and reports the
|
||||
// stamp of the last entry copied. restoreWritable also restores the source's
|
||||
// writability on success, for copies that leave the source serving; a failed
|
||||
// copy always undoes the freeze this call added.
|
||||
func (m *Mover) CopyVolume(ctx context.Context, volumeId needle.VolumeId, source, target pb.ServerAddress, diskType string, ioBytePerSecond int64, restoreWritable bool, writer io.Writer) (lastAppendAtNs uint64, err error) {
|
||||
if writer == nil {
|
||||
writer = io.Discard
|
||||
}
|
||||
if SameServer(source, target) {
|
||||
return 0, fmt.Errorf("refusing to copy volume %d onto its own server %s", volumeId, source)
|
||||
}
|
||||
// The copy is non-destructive, so a readonly-reporting source is taken as
|
||||
// is (force=false): missed concurrent deletes only make the new replica
|
||||
// trivially stale, and hard-marking here could pin a transiently readonly
|
||||
// (e.g. low-disk) source readonly with nothing to gate on it.
|
||||
sourceWasWritable, err := m.ensureVolumeReadonly(ctx, volumeId, source, false)
|
||||
defer func() {
|
||||
if sourceWasWritable && (err != nil || restoreWritable) {
|
||||
m.restoreVolumeWritable(volumeId, source)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return m.copyVolumeData(ctx, volumeId, source, target, diskType, ioBytePerSecond, writer)
|
||||
}
|
||||
|
||||
// ensureVolumeReadonly freezes the volume on server and reports whether it was
|
||||
// writable beforehand — only then may a failure path undo the freeze, since a
|
||||
// volume that was already readonly (e.g. full, or operator-set) must stay so.
|
||||
// With force, the mark is issued even when the status already reports
|
||||
// readonly: that answer also covers transient low-disk state and the
|
||||
// readonly-but-can-delete flag, and neither blocks needle deletes, so only the
|
||||
// hard mark makes the volume immutable — required before deleting the source
|
||||
// of a move. Without force, a readonly-reporting volume is left untouched.
|
||||
func (m *Mover) ensureVolumeReadonly(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, force bool) (wasWritable bool, err error) {
|
||||
err = m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
resp, statusErr := client.VolumeStatus(ctx, &volume_server_pb.VolumeStatusRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
})
|
||||
if statusErr != nil {
|
||||
return statusErr
|
||||
}
|
||||
wasWritable = !resp.IsReadOnly
|
||||
if !wasWritable && !force {
|
||||
return nil
|
||||
}
|
||||
_, readonlyErr := client.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Persist: false,
|
||||
})
|
||||
return readonlyErr
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// probeVolume reports whether server currently has the volume, and whether the
|
||||
// answer is trustworthy. The Go server answers a missing volume with a plain
|
||||
// error (gRPC code Unknown — the only way this RPC fails there); the Rust
|
||||
// server answers with codes.NotFound. Both mean the server responded and the
|
||||
// volume is absent. A transport-level failure means the state is unknown, and
|
||||
// callers deciding to delete must treat unknown as hands-off.
|
||||
func (m *Mover) probeVolume(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress) (exists bool, known bool) {
|
||||
_, err := m.ReadVolumeFileStatus(ctx, volumeId, server)
|
||||
if err == nil {
|
||||
return true, true
|
||||
}
|
||||
if s, ok := status.FromError(err); ok && (s.Code() == codes.Unknown || s.Code() == codes.NotFound) {
|
||||
return false, true
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
// restoreVolumeWritable undoes a readonly mark after a failed move. It runs on
|
||||
// its own deadline so an abort via cancelled context still restores the source,
|
||||
// and only logs a failure — the caller is already returning the move error.
|
||||
func (m *Mover) restoreVolumeWritable(volumeId needle.VolumeId, server pb.ServerAddress) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err := m.MarkVolumeWritable(ctx, volumeId, server, true, false); err != nil {
|
||||
glog.Warningf("restore volume %d writable on %s: %v", volumeId, server, err)
|
||||
}
|
||||
}
|
||||
|
||||
// copyVolumeData streams a VolumeCopy on the target, which pulls the volume
|
||||
// from source and mounts it, and returns the stamp of the last entry copied
|
||||
// for the tail phase.
|
||||
func (m *Mover) copyVolumeData(ctx context.Context, volumeId needle.VolumeId, source, target pb.ServerAddress, diskType string, ioBytePerSecond int64, writer io.Writer) (lastAppendAtNs uint64, err error) {
|
||||
// The target dials the embedded source itself; a malformed one would
|
||||
// abort the target server, not this client.
|
||||
if err = checkDialable(source); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
err = m.withClient(true, target, func(client volume_server_pb.VolumeServerClient) error {
|
||||
stream, replicateErr := client.VolumeCopy(ctx, &volume_server_pb.VolumeCopyRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
SourceDataNode: string(source),
|
||||
DiskType: diskType,
|
||||
IoBytePerSecond: ioBytePerSecond,
|
||||
})
|
||||
if replicateErr != nil {
|
||||
return replicateErr
|
||||
}
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr != nil {
|
||||
if recvErr == io.EOF {
|
||||
break
|
||||
}
|
||||
return recvErr
|
||||
}
|
||||
if resp.LastAppendAtNs != 0 {
|
||||
lastAppendAtNs = resp.LastAppendAtNs
|
||||
} else {
|
||||
fmt.Fprintf(writer, "%s => %s volume %d processed %s\n", source, target, volumeId, util.BytesToHumanReadable(uint64(resp.ProcessedBytes)))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// TailVolume has the target follow the source's appends since sinceNs until the
|
||||
// source stays idle for idleTimeout, draining requests in flight when the move
|
||||
// froze the source.
|
||||
func (m *Mover) TailVolume(ctx context.Context, volumeId needle.VolumeId, source, target pb.ServerAddress, sinceNs uint64, idleTimeout time.Duration) error {
|
||||
// The target dials the embedded source itself; a malformed one would
|
||||
// abort the target server, not this client.
|
||||
if err := checkDialable(source); err != nil {
|
||||
return err
|
||||
}
|
||||
return m.withClient(true, target, func(client volume_server_pb.VolumeServerClient) error {
|
||||
_, replicateErr := client.VolumeTailReceiver(ctx, &volume_server_pb.VolumeTailReceiverRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
SinceNs: sinceNs,
|
||||
IdleTimeoutSeconds: uint32(idleTimeout.Seconds()),
|
||||
SourceVolumeServer: string(source),
|
||||
})
|
||||
return replicateErr
|
||||
})
|
||||
}
|
||||
|
||||
// ReadVolumeFileStatus reads the volume's file sizes and needle count on server.
|
||||
func (m *Mover) ReadVolumeFileStatus(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress) (resp *volume_server_pb.ReadVolumeFileStatusResponse, err error) {
|
||||
err = m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
var statusErr error
|
||||
resp, statusErr = client.ReadVolumeFileStatus(ctx, &volume_server_pb.ReadVolumeFileStatusRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
})
|
||||
return statusErr
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteVolume removes the volume from server. When keepRemoteData is true, the
|
||||
// cloud-tier object backing the volume is left intact — used on the source side
|
||||
// of a move where another server is taking over the same .vif.
|
||||
func (m *Mover) DeleteVolume(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, onlyEmpty bool, keepRemoteData bool) error {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
_, deleteErr := client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
OnlyEmpty: onlyEmpty,
|
||||
KeepRemoteData: keepRemoteData,
|
||||
})
|
||||
return deleteErr
|
||||
})
|
||||
}
|
||||
|
||||
// MarkVolumeWritable marks the volume writable (or readonly when writable is
|
||||
// false, persisted per persist) on server.
|
||||
func (m *Mover) MarkVolumeWritable(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, writable, persist bool) (err error) {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
if writable {
|
||||
_, err = client.VolumeMarkWritable(ctx, &volume_server_pb.VolumeMarkWritableRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
})
|
||||
} else {
|
||||
_, err = client.VolumeMarkReadonly(ctx, &volume_server_pb.VolumeMarkReadonlyRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Persist: persist,
|
||||
})
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// ReplicateVolume copies a volume from source to target without touching the
|
||||
// source — the replica-creation half of a move. ioBytePerSecond limits the
|
||||
// copy rate; 0 falls back to the volume server's maintenance rate.
|
||||
func (m *Mover) ReplicateVolume(ctx context.Context, volumeId needle.VolumeId, source, target pb.ServerAddress, diskType string, ioBytePerSecond int64, writer io.Writer) error {
|
||||
if writer == nil {
|
||||
writer = io.Discard
|
||||
}
|
||||
if SameServer(source, target) {
|
||||
return fmt.Errorf("refusing to replicate volume %d onto its own server %s", volumeId, source)
|
||||
}
|
||||
// The target dials the embedded source itself; a malformed one would
|
||||
// abort the target server, not this client.
|
||||
if err := checkDialable(source); err != nil {
|
||||
return err
|
||||
}
|
||||
return m.withClient(false, target, func(client volume_server_pb.VolumeServerClient) error {
|
||||
stream, replicateErr := client.VolumeCopy(ctx, &volume_server_pb.VolumeCopyRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
SourceDataNode: string(source),
|
||||
DiskType: diskType,
|
||||
IoBytePerSecond: ioBytePerSecond,
|
||||
})
|
||||
if replicateErr != nil {
|
||||
return replicateErr
|
||||
}
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr != nil {
|
||||
if recvErr == io.EOF {
|
||||
break
|
||||
}
|
||||
return recvErr
|
||||
}
|
||||
if resp.ProcessedBytes > 0 {
|
||||
fmt.Fprintf(writer, "volume %d processed %s bytes\n", volumeId, util.BytesToHumanReadable(uint64(resp.ProcessedBytes)))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ConfigureVolumeReplication sets the replication setting on the volume at server.
|
||||
func (m *Mover) ConfigureVolumeReplication(ctx context.Context, volumeId needle.VolumeId, server pb.ServerAddress, replication string) error {
|
||||
return m.withClient(false, server, func(client volume_server_pb.VolumeServerClient) error {
|
||||
resp, configureErr := client.VolumeConfigure(ctx, &volume_server_pb.VolumeConfigureRequest{
|
||||
VolumeId: uint32(volumeId),
|
||||
Replication: replication,
|
||||
})
|
||||
if configureErr != nil {
|
||||
return configureErr
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return errors.New(resp.Error)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -1,633 +0,0 @@
|
||||
package volume_move
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
srcAddr = pb.ServerAddress("src:8080")
|
||||
dstAddr = pb.ServerAddress("dst:8080")
|
||||
)
|
||||
|
||||
func volumeStatus(datSize, idxSize, fileCount uint64) *volume_server_pb.ReadVolumeFileStatusResponse {
|
||||
return &volume_server_pb.ReadVolumeFileStatusResponse{
|
||||
DatFileSize: datSize,
|
||||
IdxFileSize: idxSize,
|
||||
FileCount: fileCount,
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameServer(t *testing.T) {
|
||||
if !SameServer("node:8080", "node:8080.18080") {
|
||||
t.Error("one server written with and without an explicit grpc port compared unequal")
|
||||
}
|
||||
// Test harnesses run several servers on HTTP port 0 with distinct grpc
|
||||
// ports; the grpc endpoint is the server's identity.
|
||||
if SameServer("127.0.0.1:0.36825", "127.0.0.1:0.38609") {
|
||||
t.Error("two servers sharing a degenerate HTTP address compared equal")
|
||||
}
|
||||
// Malformed addresses (an unvalidated -source/-target flag) must compare
|
||||
// without touching the fatal ToGrpcAddress parser.
|
||||
if !SameServer("node:abc", "node:abc") {
|
||||
t.Error("identical malformed addresses compared unequal")
|
||||
}
|
||||
if SameServer("node:abc", "node:8080") {
|
||||
t.Error("malformed and well-formed addresses compared equal")
|
||||
}
|
||||
if SameServer("", "node:8080") {
|
||||
t.Error("empty and well-formed addresses compared equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDialable(t *testing.T) {
|
||||
// Rejected: the class the fatal parser aborts on, plus dotted forms with
|
||||
// a non-numeric component — those canonicalize differently across dial
|
||||
// paths ("node:8080.bad" dials as node:bad on one and node:18080 on the
|
||||
// other, silently aliasing another server).
|
||||
for _, addr := range []pb.ServerAddress{"node:abc", "host.domain.com:x8080", "[::1]:abc",
|
||||
"node:8080.bad", "node:bad.8080", "node:.bad", "node:8080."} {
|
||||
if err := checkDialable(addr); err == nil {
|
||||
t.Errorf("%q accepted although it is unsafe to dial", addr)
|
||||
}
|
||||
}
|
||||
// Accepted: normalized cleanly, or handed to the dialer untouched where
|
||||
// a bad address fails as an ordinary error.
|
||||
for _, addr := range []pb.ServerAddress{"node:8080", "node:8080.18080", "127.0.0.1:0.36825", "", "node", "node:"} {
|
||||
if err := checkDialable(addr); err != nil {
|
||||
t.Errorf("%q rejected: %v", addr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedSourceAddressValidated(t *testing.T) {
|
||||
// The target dials the source embedded in copy/tail requests through the
|
||||
// same fatal parser; the client must reject a malformed source before
|
||||
// issuing any RPC.
|
||||
bad := pb.ServerAddress("node:abc")
|
||||
|
||||
ops := map[string]func(m *Mover) error{
|
||||
"ReplicateVolume": func(m *Mover) error {
|
||||
return m.ReplicateVolume(context.Background(), 7, bad, dstAddr, "", 0, nil)
|
||||
},
|
||||
"TailVolume": func(m *Mover) error {
|
||||
return m.TailVolume(context.Background(), 7, bad, dstAddr, 0, time.Second)
|
||||
},
|
||||
"CopyAndMountEcShards": func(m *Mover) error {
|
||||
return m.CopyAndMountEcShards(context.Background(), 7, "c1", []erasure_coding.ShardId{3}, bad, dstAddr, 0, 0, nil)
|
||||
},
|
||||
"MoveEcShards": func(m *Mover) error {
|
||||
move := ecMove(3)
|
||||
move.Source = bad
|
||||
return m.MoveEcShards(context.Background(), move, EcMoveOptions{})
|
||||
},
|
||||
}
|
||||
for name, op := range ops {
|
||||
cluster := newFakeCluster()
|
||||
err := op(cluster.mover())
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid volume server address") {
|
||||
t.Errorf("%s: expected invalid-address error, got: %v", name, err)
|
||||
}
|
||||
if len(cluster.callList()) != 0 {
|
||||
t.Errorf("%s: RPCs issued with a malformed embedded source: %v", name, cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMoverRejectsMalformedAddressWithoutDialing(t *testing.T) {
|
||||
// The production dial path must fail the move, not the process, when a
|
||||
// caller passes an unvalidated malformed address.
|
||||
mover := NewMover(grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
err := mover.LiveMoveVolume(context.Background(), 7, "node:abc", "node:8080", VolumeMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid volume server address") {
|
||||
t.Fatalf("expected invalid-address error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertCalls(t *testing.T, got, want []string) {
|
||||
t.Helper()
|
||||
if fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Fatalf("RPC sequence mismatch:\n got: %v\n want: %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeSequence(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
cluster.lastAppendAtNs = 12345
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{
|
||||
DiskType: "ssd",
|
||||
IoBytePerSecond: 42,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("LiveMoveVolume: %v", err)
|
||||
}
|
||||
|
||||
// The source status read must come after the tail: a write in flight when
|
||||
// the source was frozen can land after an earlier read, and verifying
|
||||
// against that stale snapshot would miss a missed tail. The first target
|
||||
// status read probes whether the target already held the volume, so a
|
||||
// failed copy never cleans up someone else's replica.
|
||||
assertCalls(t, cluster.callList(), []string{
|
||||
"src:8080 VolumeStatus",
|
||||
"src:8080 VolumeMarkReadonly",
|
||||
"dst:8080 ReadVolumeFileStatus",
|
||||
"dst:8080 VolumeCopy",
|
||||
"dst:8080 VolumeTailReceiver",
|
||||
"src:8080 ReadVolumeFileStatus",
|
||||
"dst:8080 ReadVolumeFileStatus",
|
||||
"src:8080 VolumeDelete",
|
||||
})
|
||||
|
||||
copyReq := cluster.copyReqs[0]
|
||||
if copyReq.DiskType != "ssd" || copyReq.IoBytePerSecond != 42 || copyReq.SourceDataNode != string(srcAddr) {
|
||||
t.Errorf("copy request not propagated: %+v", copyReq)
|
||||
}
|
||||
deleteReq := cluster.deleteReqs[0]
|
||||
if deleteReq.OnlyEmpty || !deleteReq.KeepRemoteData {
|
||||
t.Errorf("source delete must keep remote data and not be only-empty: %+v", deleteReq)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeVerifyMismatchKeepsSource(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(900, 100, 10)
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "behind the source") {
|
||||
t.Fatalf("expected target-behind error, got: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
for _, call := range calls {
|
||||
if call == "src:8080 VolumeDelete" {
|
||||
t.Fatalf("source deleted despite verification failure: %v", calls)
|
||||
}
|
||||
}
|
||||
// The incomplete target copy is removed so the restored source stays the
|
||||
// only replica, then the source is made writable again.
|
||||
if fmt.Sprint(calls[len(calls)-2:]) != fmt.Sprint([]string{"dst:8080 VolumeDelete", "src:8080 VolumeMarkWritable"}) {
|
||||
t.Fatalf("expected target cleanup then source restore, got: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeAbortKeepsSourceReadonlyWhenTargetCleanupFails(t *testing.T) {
|
||||
// Restoring the source while the stale target stays mounted risks
|
||||
// divergent replicas; the source stays readonly until a re-run recovers.
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(900, 100, 10)
|
||||
cluster.errs["dst:8080 VolumeDelete"] = errors.New("target unreachable")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected verification failure")
|
||||
}
|
||||
if !errors.Is(err, ErrSourceKeptReadonly) {
|
||||
t.Fatalf("error does not mark the source as deliberately kept readonly: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "src:8080 VolumeMarkWritable" {
|
||||
t.Fatalf("source made writable with the stale target still mounted: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeAlreadyReadonlyStaysReadonly(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.errs["dst:8080 VolumeCopy"] = errors.New("copy failed")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected copy failure")
|
||||
}
|
||||
|
||||
// The hard mark is issued even for a readonly-reporting volume: that
|
||||
// status also covers low-disk and readonly-but-can-delete states, which
|
||||
// still accept needle deletes.
|
||||
marked := false
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "src:8080 VolumeMarkReadonly" {
|
||||
marked = true
|
||||
}
|
||||
// A volume that was readonly before the move (e.g. full) must stay so.
|
||||
if call == "src:8080 VolumeMarkWritable" {
|
||||
t.Fatal("made an already-readonly volume writable after a failed move")
|
||||
}
|
||||
}
|
||||
if !marked {
|
||||
t.Fatalf("readonly-reporting source not hard-frozen: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumePreFrozenAbortCleansTarget(t *testing.T) {
|
||||
// tiering.run freezes replicas itself and thaws them after a failed move,
|
||||
// so even a move that did not do the freezing must remove its target copy
|
||||
// on abort — a stale mounted target plus a thawed source is divergence.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(900, 100, 10)
|
||||
cluster.statusFailures[string(dstAddr)] = 1 // no volume on the target before the copy
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected verification failure")
|
||||
}
|
||||
|
||||
cleaned := false
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "dst:8080 VolumeDelete" {
|
||||
cleaned = true
|
||||
}
|
||||
if call == "src:8080 VolumeMarkWritable" {
|
||||
t.Fatalf("thawed a source this move did not freeze: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
if !cleaned {
|
||||
t.Fatalf("incomplete target copy not cleaned up: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeCopyErrorCleansMountedTarget(t *testing.T) {
|
||||
// The server can finish the copy and mount the target even when the client
|
||||
// loses the stream; the abort probes the target and cleans up the copy.
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.statusFailures[string(dstAddr)] = 1 // no volume on the target before the copy
|
||||
cluster.errs["dst:8080 VolumeCopy"] = errors.New("stream lost")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected copy failure")
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
if fmt.Sprint(calls[len(calls)-2:]) != fmt.Sprint([]string{"dst:8080 VolumeDelete", "src:8080 VolumeMarkWritable"}) {
|
||||
t.Fatalf("expected target cleanup then source restore, got: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeCopyErrorUnknownTargetKeepsSourceReadonly(t *testing.T) {
|
||||
// The pre-copy probe failed at the transport level, so whether the target
|
||||
// held a replica before the move is unknown; the failed copy may still
|
||||
// have mounted a complete copy there (the server can finish after the
|
||||
// client loses the stream). Deleting it risks a healthy pre-existing
|
||||
// replica, and reopening the source beside it risks two writable replicas
|
||||
// taking divergent writes — so the source stays readonly.
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.statusFailures[string(dstAddr)] = 1
|
||||
cluster.statusFailureErr = status.Error(codes.Unavailable, "connection refused")
|
||||
cluster.errs["dst:8080 VolumeCopy"] = errors.New("stream lost")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !errors.Is(err, ErrSourceKeptReadonly) {
|
||||
t.Fatalf("expected kept-readonly failure, got: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
for _, call := range calls {
|
||||
if call == "dst:8080 VolumeDelete" {
|
||||
t.Fatalf("deleted the target with its prior state unknown: %v", calls)
|
||||
}
|
||||
if call == "src:8080 VolumeMarkWritable" {
|
||||
t.Fatalf("reopened the source beside a possibly-mounted copy: %v", calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeCopyErrorLeavesPreexistingTarget(t *testing.T) {
|
||||
// A target that held the volume before the move is someone else's replica;
|
||||
// a failed copy must not delete it.
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.errs["dst:8080 VolumeCopy"] = errors.New("copy failed")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !errors.Is(err, ErrSourceKeptReadonly) {
|
||||
t.Fatalf("expected kept-readonly failure, got: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
for _, call := range calls {
|
||||
if call == "dst:8080 VolumeDelete" {
|
||||
t.Fatalf("deleted a pre-existing target replica after a failed copy: %v", calls)
|
||||
}
|
||||
if call == "src:8080 VolumeMarkWritable" {
|
||||
t.Fatalf("reopened the source with a copy of unprovable origin on the target: %v", calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeTailErrorAborts(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.errs["dst:8080 VolumeTailReceiver"] = errors.New("tail failed")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "tail volume") {
|
||||
t.Fatalf("expected tail error, got: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
for _, call := range calls {
|
||||
if call == "src:8080 VolumeDelete" {
|
||||
t.Fatalf("source deleted despite tail failure: %v", calls)
|
||||
}
|
||||
}
|
||||
if fmt.Sprint(calls[len(calls)-2:]) != fmt.Sprint([]string{"dst:8080 VolumeDelete", "src:8080 VolumeMarkWritable"}) {
|
||||
t.Fatalf("expected target cleanup then source restore, got: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeTailErrorToleratedForReadonlySource(t *testing.T) {
|
||||
// A volume that was already readonly before the move was frozen for the
|
||||
// whole copy, so a failed tail has nothing to deliver.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.statusFailures[string(dstAddr)] = 1 // no volume on the target before the copy
|
||||
cluster.errs["dst:8080 VolumeTailReceiver"] = errors.New("tail failed")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{IdleTimeout: time.Millisecond})
|
||||
if err != nil {
|
||||
t.Fatalf("LiveMoveVolume on readonly source with failed tail: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
if calls[len(calls)-1] != "src:8080 VolumeDelete" {
|
||||
t.Fatalf("move did not complete with source delete: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeTailFailureAbortsWhenSourceStillChanging(t *testing.T) {
|
||||
// A tolerated tail failure substitutes a drain barrier: the source status
|
||||
// must hold still across the idle window, or the move aborts.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.statusFailures[string(dstAddr)] = 1 // no volume on the target before the copy
|
||||
cluster.statusSeq[string(srcAddr)] = []*volume_server_pb.ReadVolumeFileStatusResponse{
|
||||
volumeStatus(1000, 100, 10),
|
||||
volumeStatus(1024, 116, 11), // a straggler landed between the two reads
|
||||
}
|
||||
cluster.errs["dst:8080 VolumeTailReceiver"] = errors.New("tail failed")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{IdleTimeout: time.Millisecond})
|
||||
if err == nil || !strings.Contains(err.Error(), "still changing") {
|
||||
t.Fatalf("expected still-changing abort, got: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "src:8080 VolumeDelete" {
|
||||
t.Fatalf("source deleted while still changing: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeSourceDeleteFailureKeepsBothReadonly(t *testing.T) {
|
||||
// Past verification the target is complete and may hold new writes, and
|
||||
// the failed delete may or may not have reached the source. Deleting the
|
||||
// target or reopening the source could fork the volume; keep everything
|
||||
// readonly for a re-run.
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.errs["src:8080 VolumeDelete"] = errors.New("delete timed out")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected source delete failure")
|
||||
}
|
||||
if !errors.Is(err, ErrSourceKeptReadonly) {
|
||||
t.Fatalf("error does not mark the source as deliberately kept readonly: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "dst:8080 VolumeDelete" {
|
||||
t.Fatalf("deleted the verified target copy after a failed source delete: %v", cluster.callList())
|
||||
}
|
||||
if call == "src:8080 VolumeMarkWritable" {
|
||||
t.Fatalf("restored source writability next to a mounted verified copy: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeRefusesRecopyOverCompleteTarget(t *testing.T) {
|
||||
// A readonly source next to a target already holding a copy that is not
|
||||
// behind it is the signature of a previous move whose source delete
|
||||
// failed; recopying would tear down the possibly-authoritative target.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "already has a copy") {
|
||||
t.Fatalf("expected recopy refusal, got: %v", err)
|
||||
}
|
||||
if !errors.Is(err, ErrSourceKeptReadonly) {
|
||||
t.Fatalf("refusal does not mark the source as deliberately kept readonly: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "dst:8080 VolumeCopy" || call == "dst:8080 VolumeDelete" {
|
||||
t.Fatalf("touched the possibly-authoritative target: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeReadonlySourceUnknownTargetRefused(t *testing.T) {
|
||||
// With a readonly source, an unreachable target probe must fail closed:
|
||||
// the target could hold the authoritative copy of a previous move.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.statusFailures[string(dstAddr)] = 1
|
||||
cluster.statusFailureErr = status.Error(codes.Unavailable, "connection refused")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !errors.Is(err, ErrSourceKeptReadonly) {
|
||||
t.Fatalf("expected fail-closed refusal, got: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "dst:8080 VolumeCopy" {
|
||||
t.Fatalf("copied over a target in unknown state: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumePreFrozenSourceMissingRustTargetProceeds(t *testing.T) {
|
||||
// The Rust volume server answers a missing volume with codes.NotFound
|
||||
// (the Go server uses a plain error, code Unknown). Both are definitive
|
||||
// absence: with a pre-frozen source (tiering freezes before moving), a
|
||||
// NotFound misclassified as "unknown" would refuse the move with
|
||||
// ErrSourceKeptReadonly — and tiering callers then deliberately skip
|
||||
// thawing, stranding every replica readonly after an ordinary move.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.statusFailures[string(dstAddr)] = 1
|
||||
cluster.statusFailureErr = status.Error(codes.NotFound, "not found volume id 7")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("LiveMoveVolume to an empty Rust target: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
if calls[len(calls)-1] != "src:8080 VolumeDelete" {
|
||||
t.Fatalf("move did not complete with source delete: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeReadonlySourceExistingTargetRefused(t *testing.T) {
|
||||
// No client-side observation can prove an existing copy is a stale
|
||||
// remnant rather than the authoritative copy of an unfinished move —
|
||||
// compaction shrinks the authoritative copy below the stale source, and
|
||||
// any snapshot can be invalidated by a write right after it. Even a
|
||||
// target that reads as behind is refused.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(900, 90, 9)
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !errors.Is(err, ErrSourceKeptReadonly) {
|
||||
t.Fatalf("expected fail-closed refusal, got: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "dst:8080 VolumeCopy" || call == "dst:8080 VolumeDelete" {
|
||||
t.Fatalf("touched a possibly-authoritative target: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyVolumeLeavesReadonlySourceUntouched(t *testing.T) {
|
||||
// The copy is non-destructive, so a readonly-reporting source (possibly
|
||||
// only transiently, e.g. low disk) is not hard-marked.
|
||||
cluster := newFakeCluster()
|
||||
cluster.readonly[string(srcAddr)] = true
|
||||
|
||||
_, err := cluster.mover().CopyVolume(context.Background(), 7, srcAddr, dstAddr, "", 0, true, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CopyVolume: %v", err)
|
||||
}
|
||||
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "src:8080 VolumeMarkReadonly" || call == "src:8080 VolumeMarkWritable" {
|
||||
t.Fatalf("readonly source touched by a non-destructive copy: %v", cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeTargetAheadCommits(t *testing.T) {
|
||||
// The target serves writes while the move tails; a target that got ahead
|
||||
// holds those acknowledged writes, and the move must commit so they stay
|
||||
// on the surviving copy.
|
||||
cluster := newFakeCluster()
|
||||
cluster.status[string(srcAddr)] = volumeStatus(1000, 100, 10)
|
||||
cluster.status[string(dstAddr)] = volumeStatus(1100, 110, 11)
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("LiveMoveVolume with target ahead: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
if calls[len(calls)-1] != "src:8080 VolumeDelete" {
|
||||
t.Fatalf("move did not commit with source delete: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeRejectsSameServer(t *testing.T) {
|
||||
// The second target is the same server written with an explicit grpc port;
|
||||
// the guard must see through the representation difference.
|
||||
for _, target := range []pb.ServerAddress{srcAddr, pb.ServerAddress("src:8080.18080")} {
|
||||
cluster := newFakeCluster()
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, target, VolumeMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "its own server") {
|
||||
t.Fatalf("target %q: expected same-server rejection, got: %v", target, err)
|
||||
}
|
||||
if len(cluster.callList()) != 0 {
|
||||
t.Fatalf("target %q: RPCs issued for a rejected move: %v", target, cluster.callList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveMoveVolumeReadonlyMarkFailureRestores(t *testing.T) {
|
||||
// The marking RPC can fail after the server applied the mark (e.g. its
|
||||
// master notification failed), so a mark error must still restore.
|
||||
cluster := newFakeCluster()
|
||||
cluster.errs["src:8080 VolumeMarkReadonly"] = errors.New("master notification failed")
|
||||
|
||||
err := cluster.mover().LiveMoveVolume(context.Background(), 7, srcAddr, dstAddr, VolumeMoveOptions{})
|
||||
if err == nil || !strings.Contains(err.Error(), "mark volume") {
|
||||
t.Fatalf("expected mark-readonly error, got: %v", err)
|
||||
}
|
||||
|
||||
calls := cluster.callList()
|
||||
if calls[len(calls)-1] != "src:8080 VolumeMarkWritable" {
|
||||
t.Fatalf("source writability not restored after failed readonly mark: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplicateVolumePropagatesThroughput(t *testing.T) {
|
||||
cluster := newFakeCluster()
|
||||
|
||||
if err := cluster.mover().ReplicateVolume(context.Background(), 7, srcAddr, dstAddr, "ssd", 55, nil); err != nil {
|
||||
t.Fatalf("ReplicateVolume: %v", err)
|
||||
}
|
||||
copyReq := cluster.copyReqs[0]
|
||||
if copyReq.IoBytePerSecond != 55 || copyReq.DiskType != "ssd" {
|
||||
t.Errorf("replicate request not propagated: %+v", copyReq)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyVolumeRestoreWritable(t *testing.T) {
|
||||
for _, restoreWritable := range []bool{true, false} {
|
||||
cluster := newFakeCluster()
|
||||
_, err := cluster.mover().CopyVolume(context.Background(), 7, srcAddr, dstAddr, "", 0, restoreWritable, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CopyVolume(restoreWritable=%v): %v", restoreWritable, err)
|
||||
}
|
||||
restored := false
|
||||
for _, call := range cluster.callList() {
|
||||
if call == "src:8080 VolumeMarkWritable" {
|
||||
restored = true
|
||||
}
|
||||
}
|
||||
if restored != restoreWritable {
|
||||
t.Errorf("restoreWritable=%v but writability restored=%v", restoreWritable, restored)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -461,7 +461,6 @@ message VolumeEcShardsCopyRequest {
|
||||
bool copy_vif_file = 7;
|
||||
uint32 disk_id = 8; // Target disk ID for storing EC shards
|
||||
bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
|
||||
int64 io_byte_per_second = 10; // limit the copy rate; 0 falls back to the server's maintenance rate
|
||||
}
|
||||
message VolumeEcShardsCopyResponse {
|
||||
}
|
||||
|
||||
@@ -3559,19 +3559,18 @@ func (x *VolumeEcShardsRebuildResponse) GetRebuiltShardIds() []uint32 {
|
||||
}
|
||||
|
||||
type VolumeEcShardsCopyRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
CopyEcxFile bool `protobuf:"varint,4,opt,name=copy_ecx_file,json=copyEcxFile,proto3" json:"copy_ecx_file,omitempty"`
|
||||
SourceDataNode string `protobuf:"bytes,5,opt,name=source_data_node,json=sourceDataNode,proto3" json:"source_data_node,omitempty"`
|
||||
CopyEcjFile bool `protobuf:"varint,6,opt,name=copy_ecj_file,json=copyEcjFile,proto3" json:"copy_ecj_file,omitempty"`
|
||||
CopyVifFile bool `protobuf:"varint,7,opt,name=copy_vif_file,json=copyVifFile,proto3" json:"copy_vif_file,omitempty"`
|
||||
DiskId uint32 `protobuf:"varint,8,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"` // Target disk ID for storing EC shards
|
||||
CopyEcsumFile bool `protobuf:"varint,9,opt,name=copy_ecsum_file,json=copyEcsumFile,proto3" json:"copy_ecsum_file,omitempty"` // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
|
||||
IoBytePerSecond int64 `protobuf:"varint,10,opt,name=io_byte_per_second,json=ioBytePerSecond,proto3" json:"io_byte_per_second,omitempty"` // limit the copy rate; 0 falls back to the server's maintenance rate
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
CopyEcxFile bool `protobuf:"varint,4,opt,name=copy_ecx_file,json=copyEcxFile,proto3" json:"copy_ecx_file,omitempty"`
|
||||
SourceDataNode string `protobuf:"bytes,5,opt,name=source_data_node,json=sourceDataNode,proto3" json:"source_data_node,omitempty"`
|
||||
CopyEcjFile bool `protobuf:"varint,6,opt,name=copy_ecj_file,json=copyEcjFile,proto3" json:"copy_ecj_file,omitempty"`
|
||||
CopyVifFile bool `protobuf:"varint,7,opt,name=copy_vif_file,json=copyVifFile,proto3" json:"copy_vif_file,omitempty"`
|
||||
DiskId uint32 `protobuf:"varint,8,opt,name=disk_id,json=diskId,proto3" json:"disk_id,omitempty"` // Target disk ID for storing EC shards
|
||||
CopyEcsumFile bool `protobuf:"varint,9,opt,name=copy_ecsum_file,json=copyEcsumFile,proto3" json:"copy_ecsum_file,omitempty"` // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsCopyRequest) Reset() {
|
||||
@@ -3667,13 +3666,6 @@ func (x *VolumeEcShardsCopyRequest) GetCopyEcsumFile() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsCopyRequest) GetIoBytePerSecond() int64 {
|
||||
if x != nil {
|
||||
return x.IoBytePerSecond
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type VolumeEcShardsCopyResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
@@ -7432,7 +7424,7 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"collection\x122\n" +
|
||||
"\x15unsafe_ignore_sidecar\x18\x03 \x01(\bR\x13unsafeIgnoreSidecar\"K\n" +
|
||||
"\x1dVolumeEcShardsRebuildResponse\x12*\n" +
|
||||
"\x11rebuilt_shard_ids\x18\x01 \x03(\rR\x0frebuiltShardIds\"\xf9\x02\n" +
|
||||
"\x11rebuilt_shard_ids\x18\x01 \x03(\rR\x0frebuiltShardIds\"\xcc\x02\n" +
|
||||
"\x19VolumeEcShardsCopyRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" +
|
||||
"\n" +
|
||||
@@ -7444,9 +7436,7 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\rcopy_ecj_file\x18\x06 \x01(\bR\vcopyEcjFile\x12\"\n" +
|
||||
"\rcopy_vif_file\x18\a \x01(\bR\vcopyVifFile\x12\x17\n" +
|
||||
"\adisk_id\x18\b \x01(\rR\x06diskId\x12&\n" +
|
||||
"\x0fcopy_ecsum_file\x18\t \x01(\bR\rcopyEcsumFile\x12+\n" +
|
||||
"\x12io_byte_per_second\x18\n" +
|
||||
" \x01(\x03R\x0fioBytePerSecond\"\x1c\n" +
|
||||
"\x0fcopy_ecsum_file\x18\t \x01(\bR\rcopyEcsumFile\"\x1c\n" +
|
||||
"\x1aVolumeEcShardsCopyResponse\"\xbe\x01\n" +
|
||||
"\x1bVolumeEcShardsDeleteRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" +
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v7.35.0
|
||||
// source: volume_server.proto
|
||||
|
||||
@@ -794,151 +794,151 @@ type VolumeServerServer interface {
|
||||
type UnimplementedVolumeServerServer struct{}
|
||||
|
||||
func (UnimplementedVolumeServerServer) BatchDelete(context.Context, *BatchDeleteRequest) (*BatchDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method BatchDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method BatchDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCheck(context.Context, *VacuumVolumeCheckRequest) (*VacuumVolumeCheckResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VacuumVolumeCheck not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VacuumVolumeCheck not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCompact(*VacuumVolumeCompactRequest, grpc.ServerStreamingServer[VacuumVolumeCompactResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VacuumVolumeCompact not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VacuumVolumeCompact not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCommit(context.Context, *VacuumVolumeCommitRequest) (*VacuumVolumeCommitResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VacuumVolumeCommit not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VacuumVolumeCommit not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VacuumVolumeCleanup(context.Context, *VacuumVolumeCleanupRequest) (*VacuumVolumeCleanupResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VacuumVolumeCleanup not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VacuumVolumeCleanup not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) DeleteCollection(context.Context, *DeleteCollectionRequest) (*DeleteCollectionResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteCollection not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method DeleteCollection not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) AllocateVolume(context.Context, *AllocateVolumeRequest) (*AllocateVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method AllocateVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method AllocateVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeSyncStatus(context.Context, *VolumeSyncStatusRequest) (*VolumeSyncStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeSyncStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeSyncStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeIncrementalCopy(*VolumeIncrementalCopyRequest, grpc.ServerStreamingServer[VolumeIncrementalCopyResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeIncrementalCopy not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeIncrementalCopy not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeMount(context.Context, *VolumeMountRequest) (*VolumeMountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeMount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeMount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeUnmount(context.Context, *VolumeUnmountRequest) (*VolumeUnmountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeUnmount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeUnmount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeConsolidateIndex(context.Context, *VolumeConsolidateIndexRequest) (*VolumeConsolidateIndexResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeConsolidateIndex not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeConsolidateIndex not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeDelete(context.Context, *VolumeDeleteRequest) (*VolumeDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeMarkReadonly(context.Context, *VolumeMarkReadonlyRequest) (*VolumeMarkReadonlyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeMarkReadonly not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeMarkReadonly not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeMarkWritable(context.Context, *VolumeMarkWritableRequest) (*VolumeMarkWritableResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeMarkWritable not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeMarkWritable not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeConfigure(context.Context, *VolumeConfigureRequest) (*VolumeConfigureResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeConfigure not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeConfigure not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeStatus(context.Context, *VolumeStatusRequest) (*VolumeStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) GetState(context.Context, *GetStateRequest) (*GetStateResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetState not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetState not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) SetState(context.Context, *SetStateRequest) (*SetStateResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SetState not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SetState not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeCopy(*VolumeCopyRequest, grpc.ServerStreamingServer[VolumeCopyResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeCopy not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeCopy not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadVolumeFileStatus(context.Context, *ReadVolumeFileStatusRequest) (*ReadVolumeFileStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ReadVolumeFileStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReadVolumeFileStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) CopyFile(*CopyFileRequest, grpc.ServerStreamingServer[CopyFileResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method CopyFile not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method CopyFile not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReceiveFile(grpc.ClientStreamingServer[ReceiveFileRequest, ReceiveFileResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method ReceiveFile not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method ReceiveFile not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadNeedleBlob(context.Context, *ReadNeedleBlobRequest) (*ReadNeedleBlobResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ReadNeedleBlob not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReadNeedleBlob not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadNeedleMeta(context.Context, *ReadNeedleMetaRequest) (*ReadNeedleMetaResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ReadNeedleMeta not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReadNeedleMeta not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) WriteNeedleBlob(context.Context, *WriteNeedleBlobRequest) (*WriteNeedleBlobResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method WriteNeedleBlob not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method WriteNeedleBlob not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ReadAllNeedles(*ReadAllNeedlesRequest, grpc.ServerStreamingServer[ReadAllNeedlesResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method ReadAllNeedles not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method ReadAllNeedles not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTailSender(*VolumeTailSenderRequest, grpc.ServerStreamingServer[VolumeTailSenderResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeTailSender not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeTailSender not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTailReceiver(context.Context, *VolumeTailReceiverRequest) (*VolumeTailReceiverResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeTailReceiver not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeTailReceiver not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsGenerate(context.Context, *VolumeEcShardsGenerateRequest) (*VolumeEcShardsGenerateResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsGenerate not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsGenerate not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsRebuild(context.Context, *VolumeEcShardsRebuildRequest) (*VolumeEcShardsRebuildResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsRebuild not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsRebuild not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsCopy(context.Context, *VolumeEcShardsCopyRequest) (*VolumeEcShardsCopyResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsCopy not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsCopy not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsDelete(context.Context, *VolumeEcShardsDeleteRequest) (*VolumeEcShardsDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsMount(context.Context, *VolumeEcShardsMountRequest) (*VolumeEcShardsMountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsMount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsMount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsUnmount(context.Context, *VolumeEcShardsUnmountRequest) (*VolumeEcShardsUnmountResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsUnmount not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsUnmount not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardRead(*VolumeEcShardReadRequest, grpc.ServerStreamingServer[VolumeEcShardReadResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeEcShardRead not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeEcShardRead not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcBlobDelete(context.Context, *VolumeEcBlobDeleteRequest) (*VolumeEcBlobDeleteResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcBlobDelete not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcBlobDelete not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsToVolume(context.Context, *VolumeEcShardsToVolumeRequest) (*VolumeEcShardsToVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsToVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsToVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeEcShardsInfo(context.Context, *VolumeEcShardsInfoRequest) (*VolumeEcShardsInfoResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeEcShardsInfo not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeEcShardsInfo not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTierMoveDatToRemote(*VolumeTierMoveDatToRemoteRequest, grpc.ServerStreamingServer[VolumeTierMoveDatToRemoteResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeTierMoveDatToRemote not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeTierMoveDatToRemote not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeTierMoveDatFromRemote(*VolumeTierMoveDatFromRemoteRequest, grpc.ServerStreamingServer[VolumeTierMoveDatFromRemoteResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method VolumeTierMoveDatFromRemote not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method VolumeTierMoveDatFromRemote not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeServerStatus(context.Context, *VolumeServerStatusRequest) (*VolumeServerStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeServerStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeServerStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeServerLeave(context.Context, *VolumeServerLeaveRequest) (*VolumeServerLeaveResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeServerLeave not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeServerLeave not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) FetchAndWriteNeedle(context.Context, *FetchAndWriteNeedleRequest) (*FetchAndWriteNeedleResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method FetchAndWriteNeedle not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method FetchAndWriteNeedle not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ScrubVolume(context.Context, *ScrubVolumeRequest) (*ScrubVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ScrubVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ScrubVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) ScrubEcVolume(context.Context, *ScrubEcVolumeRequest) (*ScrubEcVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ScrubEcVolume not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ScrubEcVolume not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) Query(*QueryRequest, grpc.ServerStreamingServer[QueriedStripe]) error {
|
||||
return status.Error(codes.Unimplemented, "method Query not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method Query not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) VolumeNeedleStatus(context.Context, *VolumeNeedleStatusRequest) (*VolumeNeedleStatusResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method VolumeNeedleStatus not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VolumeNeedleStatus not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method Ping not implemented")
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
|
||||
}
|
||||
func (UnimplementedVolumeServerServer) mustEmbedUnimplementedVolumeServerServer() {}
|
||||
func (UnimplementedVolumeServerServer) testEmbeddedByValue() {}
|
||||
@@ -951,7 +951,7 @@ type UnsafeVolumeServerServer interface {
|
||||
}
|
||||
|
||||
func RegisterVolumeServerServer(s grpc.ServiceRegistrar, srv VolumeServerServer) {
|
||||
// If the following call panics, it indicates UnimplementedVolumeServerServer was
|
||||
// If the following call pancis, it indicates UnimplementedVolumeServerServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
|
||||
@@ -220,7 +220,6 @@ message BalanceTaskParams {
|
||||
int32 timeout_seconds = 2; // Operation timeout
|
||||
int32 max_concurrent_moves = 3; // Max concurrent moves in a batch job (0 = default 5)
|
||||
repeated BalanceMoveSpec moves = 4; // Batch: multiple volume moves in one job
|
||||
int64 io_byte_per_second = 5; // limit each move's copy rate; 0 falls back to the volume server's maintenance rate
|
||||
}
|
||||
|
||||
// ReplicationTaskParams for adding replicas
|
||||
@@ -383,7 +382,6 @@ message ErasureCodingTaskConfig {
|
||||
message BalanceTaskConfig {
|
||||
double imbalance_threshold = 1; // Threshold for triggering rebalancing (0.0-1.0)
|
||||
int32 min_server_count = 2; // Minimum number of servers required for balancing
|
||||
int64 io_byte_per_second = 3; // limit each move's copy rate; 0 falls back to the volume server's maintenance rate
|
||||
}
|
||||
|
||||
// ReplicationTaskConfig contains replication-specific configuration
|
||||
@@ -397,11 +395,6 @@ message EcBalanceTaskParams {
|
||||
int32 max_parallelization = 2; // Max parallel shard moves within a batch
|
||||
int32 timeout_seconds = 3; // Operation timeout per move
|
||||
repeated EcShardMoveSpec moves = 4; // Batch: multiple shard moves in one job
|
||||
// For a dedup move, the node that keeps the shard. The worker confirms this
|
||||
// node really holds it before deleting the copy, so a topology entry naming a
|
||||
// location that holds nothing cannot cause the last copy to be removed.
|
||||
string dedup_keep_node = 5;
|
||||
int64 io_byte_per_second = 6; // limit each shard copy's rate; 0 falls back to the volume server's maintenance rate
|
||||
}
|
||||
|
||||
// EcShardMoveSpec describes a single EC shard move within a batch
|
||||
@@ -423,7 +416,6 @@ message EcBalanceTaskConfig {
|
||||
string disk_type = 4; // Disk type filter
|
||||
repeated string preferred_tags = 5; // Preferred disk tags for placement
|
||||
string replica_placement = 6; // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
int64 io_byte_per_second = 7; // limit each shard copy's rate; 0 falls back to the volume server's maintenance rate
|
||||
}
|
||||
|
||||
// ========== Task Persistence Messages ==========
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v7.35.0
|
||||
// protoc v6.33.4
|
||||
// source: worker.proto
|
||||
|
||||
package worker_pb
|
||||
@@ -1684,7 +1684,6 @@ type BalanceTaskParams struct {
|
||||
TimeoutSeconds int32 `protobuf:"varint,2,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"` // Operation timeout
|
||||
MaxConcurrentMoves int32 `protobuf:"varint,3,opt,name=max_concurrent_moves,json=maxConcurrentMoves,proto3" json:"max_concurrent_moves,omitempty"` // Max concurrent moves in a batch job (0 = default 5)
|
||||
Moves []*BalanceMoveSpec `protobuf:"bytes,4,rep,name=moves,proto3" json:"moves,omitempty"` // Batch: multiple volume moves in one job
|
||||
IoBytePerSecond int64 `protobuf:"varint,5,opt,name=io_byte_per_second,json=ioBytePerSecond,proto3" json:"io_byte_per_second,omitempty"` // limit each move's copy rate; 0 falls back to the volume server's maintenance rate
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -1747,13 +1746,6 @@ func (x *BalanceTaskParams) GetMoves() []*BalanceMoveSpec {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *BalanceTaskParams) GetIoBytePerSecond() int64 {
|
||||
if x != nil {
|
||||
return x.IoBytePerSecond
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ReplicationTaskParams for adding replicas
|
||||
type ReplicationTaskParams struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -3058,7 +3050,6 @@ type BalanceTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
ImbalanceThreshold float64 `protobuf:"fixed64,1,opt,name=imbalance_threshold,json=imbalanceThreshold,proto3" json:"imbalance_threshold,omitempty"` // Threshold for triggering rebalancing (0.0-1.0)
|
||||
MinServerCount int32 `protobuf:"varint,2,opt,name=min_server_count,json=minServerCount,proto3" json:"min_server_count,omitempty"` // Minimum number of servers required for balancing
|
||||
IoBytePerSecond int64 `protobuf:"varint,3,opt,name=io_byte_per_second,json=ioBytePerSecond,proto3" json:"io_byte_per_second,omitempty"` // limit each move's copy rate; 0 falls back to the volume server's maintenance rate
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3107,13 +3098,6 @@ func (x *BalanceTaskConfig) GetMinServerCount() int32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *BalanceTaskConfig) GetIoBytePerSecond() int64 {
|
||||
if x != nil {
|
||||
return x.IoBytePerSecond
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ReplicationTaskConfig contains replication-specific configuration
|
||||
type ReplicationTaskConfig struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -3166,13 +3150,8 @@ type EcBalanceTaskParams struct {
|
||||
MaxParallelization int32 `protobuf:"varint,2,opt,name=max_parallelization,json=maxParallelization,proto3" json:"max_parallelization,omitempty"` // Max parallel shard moves within a batch
|
||||
TimeoutSeconds int32 `protobuf:"varint,3,opt,name=timeout_seconds,json=timeoutSeconds,proto3" json:"timeout_seconds,omitempty"` // Operation timeout per move
|
||||
Moves []*EcShardMoveSpec `protobuf:"bytes,4,rep,name=moves,proto3" json:"moves,omitempty"` // Batch: multiple shard moves in one job
|
||||
// For a dedup move, the node that keeps the shard. The worker confirms this
|
||||
// node really holds it before deleting the copy, so a topology entry naming a
|
||||
// location that holds nothing cannot cause the last copy to be removed.
|
||||
DedupKeepNode string `protobuf:"bytes,5,opt,name=dedup_keep_node,json=dedupKeepNode,proto3" json:"dedup_keep_node,omitempty"`
|
||||
IoBytePerSecond int64 `protobuf:"varint,6,opt,name=io_byte_per_second,json=ioBytePerSecond,proto3" json:"io_byte_per_second,omitempty"` // limit each shard copy's rate; 0 falls back to the volume server's maintenance rate
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *EcBalanceTaskParams) Reset() {
|
||||
@@ -3233,20 +3212,6 @@ func (x *EcBalanceTaskParams) GetMoves() []*EcShardMoveSpec {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *EcBalanceTaskParams) GetDedupKeepNode() string {
|
||||
if x != nil {
|
||||
return x.DedupKeepNode
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *EcBalanceTaskParams) GetIoBytePerSecond() int64 {
|
||||
if x != nil {
|
||||
return x.IoBytePerSecond
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// EcShardMoveSpec describes a single EC shard move within a batch
|
||||
type EcShardMoveSpec struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -3349,7 +3314,6 @@ type EcBalanceTaskConfig struct {
|
||||
DiskType string `protobuf:"bytes,4,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"` // Disk type filter
|
||||
PreferredTags []string `protobuf:"bytes,5,rep,name=preferred_tags,json=preferredTags,proto3" json:"preferred_tags,omitempty"` // Preferred disk tags for placement
|
||||
ReplicaPlacement string `protobuf:"bytes,6,opt,name=replica_placement,json=replicaPlacement,proto3" json:"replica_placement,omitempty"` // EC shard replica placement (e.g. "020"); empty falls back to master default replication
|
||||
IoBytePerSecond int64 `protobuf:"varint,7,opt,name=io_byte_per_second,json=ioBytePerSecond,proto3" json:"io_byte_per_second,omitempty"` // limit each shard copy's rate; 0 falls back to the volume server's maintenance rate
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -3426,13 +3390,6 @@ func (x *EcBalanceTaskConfig) GetReplicaPlacement() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *EcBalanceTaskConfig) GetIoBytePerSecond() int64 {
|
||||
if x != nil {
|
||||
return x.IoBytePerSecond
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// MaintenanceTaskData represents complete task state for persistence
|
||||
type MaintenanceTaskData struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -4150,14 +4107,13 @@ const file_worker_proto_rawDesc = "" +
|
||||
"collection\x18\x04 \x01(\tR\n" +
|
||||
"collection\x12\x1f\n" +
|
||||
"\vvolume_size\x18\x05 \x01(\x04R\n" +
|
||||
"volumeSize\"\xec\x01\n" +
|
||||
"volumeSize\"\xbf\x01\n" +
|
||||
"\x11BalanceTaskParams\x12\x1d\n" +
|
||||
"\n" +
|
||||
"force_move\x18\x01 \x01(\bR\tforceMove\x12'\n" +
|
||||
"\x0ftimeout_seconds\x18\x02 \x01(\x05R\x0etimeoutSeconds\x120\n" +
|
||||
"\x14max_concurrent_moves\x18\x03 \x01(\x05R\x12maxConcurrentMoves\x120\n" +
|
||||
"\x05moves\x18\x04 \x03(\v2\x1a.worker_pb.BalanceMoveSpecR\x05moves\x12+\n" +
|
||||
"\x12io_byte_per_second\x18\x05 \x01(\x03R\x0fioBytePerSecond\"k\n" +
|
||||
"\x05moves\x18\x04 \x03(\v2\x1a.worker_pb.BalanceMoveSpecR\x05moves\"k\n" +
|
||||
"\x15ReplicationTaskParams\x12#\n" +
|
||||
"\rreplica_count\x18\x01 \x01(\x05R\freplicaCount\x12-\n" +
|
||||
"\x12verify_consistency\x18\x02 \x01(\bR\x11verifyConsistency\"\x8e\x02\n" +
|
||||
@@ -4287,20 +4243,17 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x12min_volume_size_mb\x18\x03 \x01(\x05R\x0fminVolumeSizeMb\x12+\n" +
|
||||
"\x11collection_filter\x18\x04 \x01(\tR\x10collectionFilter\x12%\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"\x9b\x01\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"n\n" +
|
||||
"\x11BalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\x12+\n" +
|
||||
"\x12io_byte_per_second\x18\x03 \x01(\x03R\x0fioBytePerSecond\"I\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\"I\n" +
|
||||
"\x15ReplicationTaskConfig\x120\n" +
|
||||
"\x14target_replica_count\x18\x01 \x01(\x05R\x12targetReplicaCount\"\x93\x02\n" +
|
||||
"\x14target_replica_count\x18\x01 \x01(\x05R\x12targetReplicaCount\"\xbe\x01\n" +
|
||||
"\x13EcBalanceTaskParams\x12\x1b\n" +
|
||||
"\tdisk_type\x18\x01 \x01(\tR\bdiskType\x12/\n" +
|
||||
"\x13max_parallelization\x18\x02 \x01(\x05R\x12maxParallelization\x12'\n" +
|
||||
"\x0ftimeout_seconds\x18\x03 \x01(\x05R\x0etimeoutSeconds\x120\n" +
|
||||
"\x05moves\x18\x04 \x03(\v2\x1a.worker_pb.EcShardMoveSpecR\x05moves\x12&\n" +
|
||||
"\x0fdedup_keep_node\x18\x05 \x01(\tR\rdedupKeepNode\x12+\n" +
|
||||
"\x12io_byte_per_second\x18\x06 \x01(\x03R\x0fioBytePerSecond\"\xf7\x01\n" +
|
||||
"\x05moves\x18\x04 \x03(\v2\x1a.worker_pb.EcShardMoveSpecR\x05moves\"\xf7\x01\n" +
|
||||
"\x0fEcShardMoveSpec\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x19\n" +
|
||||
"\bshard_id\x18\x02 \x01(\rR\ashardId\x12\x1e\n" +
|
||||
@@ -4312,15 +4265,14 @@ const file_worker_proto_rawDesc = "" +
|
||||
"\x0esource_disk_id\x18\x05 \x01(\rR\fsourceDiskId\x12\x1f\n" +
|
||||
"\vtarget_node\x18\x06 \x01(\tR\n" +
|
||||
"targetNode\x12$\n" +
|
||||
"\x0etarget_disk_id\x18\a \x01(\rR\ftargetDiskId\"\xbb\x02\n" +
|
||||
"\x0etarget_disk_id\x18\a \x01(\rR\ftargetDiskId\"\x8e\x02\n" +
|
||||
"\x13EcBalanceTaskConfig\x12/\n" +
|
||||
"\x13imbalance_threshold\x18\x01 \x01(\x01R\x12imbalanceThreshold\x12(\n" +
|
||||
"\x10min_server_count\x18\x02 \x01(\x05R\x0eminServerCount\x12+\n" +
|
||||
"\x11collection_filter\x18\x03 \x01(\tR\x10collectionFilter\x12\x1b\n" +
|
||||
"\tdisk_type\x18\x04 \x01(\tR\bdiskType\x12%\n" +
|
||||
"\x0epreferred_tags\x18\x05 \x03(\tR\rpreferredTags\x12+\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\x12+\n" +
|
||||
"\x12io_byte_per_second\x18\a \x01(\x03R\x0fioBytePerSecond\"\xae\a\n" +
|
||||
"\x11replica_placement\x18\x06 \x01(\tR\x10replicaPlacement\"\xae\a\n" +
|
||||
"\x13MaintenanceTaskData\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
|
||||
"\x04type\x18\x02 \x01(\tR\x04type\x12\x1a\n" +
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v7.35.0
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.33.4
|
||||
// source: worker.proto
|
||||
|
||||
package worker_pb
|
||||
@@ -72,7 +72,7 @@ type WorkerServiceServer interface {
|
||||
type UnimplementedWorkerServiceServer struct{}
|
||||
|
||||
func (UnimplementedWorkerServiceServer) WorkerStream(grpc.BidiStreamingServer[WorkerMessage, AdminMessage]) error {
|
||||
return status.Error(codes.Unimplemented, "method WorkerStream not implemented")
|
||||
return status.Errorf(codes.Unimplemented, "method WorkerStream not implemented")
|
||||
}
|
||||
func (UnimplementedWorkerServiceServer) mustEmbedUnimplementedWorkerServiceServer() {}
|
||||
func (UnimplementedWorkerServiceServer) testEmbeddedByValue() {}
|
||||
@@ -85,7 +85,7 @@ type UnsafeWorkerServiceServer interface {
|
||||
}
|
||||
|
||||
func RegisterWorkerServiceServer(s grpc.ServiceRegistrar, srv WorkerServiceServer) {
|
||||
// If the following call panics, it indicates UnimplementedWorkerServiceServer was
|
||||
// If the following call pancis, it indicates UnimplementedWorkerServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
|
||||
@@ -2,7 +2,6 @@ package azure
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
@@ -28,10 +27,7 @@ var validAzureAccountName = regexp.MustCompile(`^[a-z0-9]{3,24}$`)
|
||||
//
|
||||
// endpoint is the blob service URL, for accounts outside the public cloud. An
|
||||
// empty endpoint derives the public one from accountName.
|
||||
//
|
||||
// A non-nil httpClient overrides the SDK transport; the volume server passes one
|
||||
// whose dialer pins the validated endpoint against DNS rebinding.
|
||||
func NewAzBlobClient(accountName, accountKey, clientID, endpoint string, httpClient *http.Client) (*azblob.Client, error) {
|
||||
func NewAzBlobClient(accountName, accountKey, clientID, endpoint string) (*azblob.Client, error) {
|
||||
|
||||
if accountName == "" {
|
||||
return nil, fmt.Errorf("azure account name is required")
|
||||
@@ -45,18 +41,13 @@ func NewAzBlobClient(accountName, accountKey, clientID, endpoint string, httpCli
|
||||
return nil, err
|
||||
}
|
||||
|
||||
options := DefaultAzBlobClientOptions()
|
||||
if httpClient != nil {
|
||||
options.Transport = httpClient
|
||||
}
|
||||
|
||||
if accountKey == "" {
|
||||
credential, err := newAzureTokenCredential(clientID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create Azure Entra ID credential for account %s: %w", accountName, err)
|
||||
}
|
||||
glog.V(1).Infof("azure %s: authenticating with Entra ID", accountName)
|
||||
client, err := azblob.NewClient(serviceURL, credential, options)
|
||||
client, err := azblob.NewClient(serviceURL, credential, DefaultAzBlobClientOptions())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create Azure client: %w", err)
|
||||
}
|
||||
@@ -67,7 +58,7 @@ func NewAzBlobClient(accountName, accountKey, clientID, endpoint string, httpCli
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create Azure credential with account name:%s: %w", accountName, err)
|
||||
}
|
||||
client, err := azblob.NewClientWithSharedKeyCredential(serviceURL, credential, options)
|
||||
client, err := azblob.NewClientWithSharedKeyCredential(serviceURL, credential, DefaultAzBlobClientOptions())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create Azure client: %w", err)
|
||||
}
|
||||
|
||||
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user