Compare commits

..
Author SHA1 Message Date
Chris Lu caa63546b1 ci: add java client release workflow 2026-07-07 23:20:17 -07:00
Chris Lu ff37d5f02d java: bump maven-gpg-plugin to 3.2.4 for headless signing 2026-07-07 23:17:44 -07:00
78 changed files with 698 additions and 3550 deletions

No files matched your search

+15 -71
View File
@@ -10,20 +10,20 @@ name: "release: java clients"
# gpg --homedir <keyring> --armor --export-secret-keys <KEYID> > key.asc
# MAVEN_GPG_PASSPHRASE - passphrase for that key
#
# A plain run publishes to Central. Check dry_run to exercise secrets, GPG
# signing, and the build without committing or publishing.
# Run with dry_run on first (default) to exercise secrets, GPG signing, and the
# build without publishing. Uncheck dry_run for the real release to Central.
on:
workflow_dispatch:
inputs:
version:
description: "Version to publish, e.g. 4.39. Leave blank to use the current SeaweedFS version."
description: "Java client version to publish, e.g. 4.39 (MAJOR.MINOR)"
type: string
required: false
required: true
dry_run:
description: "Build and GPG-sign only; skip the version commit and the Central upload"
type: boolean
default: false
default: true
permissions:
contents: write
@@ -46,31 +46,16 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
# Full history so the version-bump commit can rebase onto a moved master.
fetch-depth: 0
# An explicit input wins; otherwise fall back to the current SeaweedFS
# version (MAJOR.MINOR) from constants.go, matching its %d.%02d formatting.
- name: Resolve version
id: resolve
- name: Validate version
env:
INPUT_VERSION: ${{ inputs.version }}
VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
VERSION="$INPUT_VERSION"
if [ -z "$VERSION" ]; then
CONST=weed/util/version/constants.go
MAJOR=$(grep -oP 'MAJOR_VERSION\s*=\s*int32\(\K[0-9]+' "$CONST")
MINOR=$(grep -oP 'MINOR_VERSION\s*=\s*int32\(\K[0-9]+' "$CONST")
VERSION=$(printf '%d.%02d' "$MAJOR" "$MINOR")
echo "No version given; using current SeaweedFS version ${VERSION}."
fi
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then
echo "::error::version must be MAJOR.MINOR, e.g. 4.39 (got '$VERSION')"
exit 1
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
- name: Set up JDK 17
uses: actions/setup-java@v5
@@ -88,7 +73,7 @@ jobs:
# its seaweedfs-client dependency from the seaweedfs.client.version property.
- name: Set versions in poms
env:
VERSION: ${{ steps.resolve.outputs.version }}
VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
V=org.codehaus.mojo:versions-maven-plugin:2.16.2
@@ -100,27 +85,18 @@ jobs:
- name: Commit version bump
if: ${{ !inputs.dry_run }}
env:
VERSION: ${{ steps.resolve.outputs.version }}
VERSION: ${{ inputs.version }}
run: |
set -euo pipefail
if git diff --quiet; then
echo "Poms already at ${VERSION}; nothing to commit."
exit 0
else
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add other/java/client/pom.xml other/java/hdfs3/pom.xml
git commit -m "java ${VERSION}"
git push
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add other/java/client/pom.xml other/java/hdfs3/pom.xml
git commit -m "java ${VERSION}"
# Rebase and retry so a concurrent push to master doesn't lose the bump.
for attempt in 1 2 3 4 5; do
if git push origin HEAD:master; then
exit 0
fi
echo "push rejected (attempt ${attempt}); rebasing onto latest master"
git pull --rebase origin master
done
echo "::error::could not push version bump after retries"
exit 1
# Tests are skipped here: the integration tests need a live filer, and the
# offline unit tests already run on every push in java_unit_tests.yml.
@@ -149,35 +125,3 @@ jobs:
set -euo pipefail
[ "$DRY_RUN" = "true" ] && GOAL="clean install" || GOAL="clean deploy"
mvn -B -ntp $GOAL -DskipTests
# Bump every version the wiki quotes for the Java clients. Runs only after
# a successful real publish. Uses GITHUB_TOKEN; set a WIKI_TOKEN secret if
# the token can't push to the wiki.
- name: Update wiki client versions
if: ${{ !inputs.dry_run }}
env:
VERSION: ${{ steps.resolve.outputs.version }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WIKI_TOKEN: ${{ secrets.WIKI_TOKEN }}
run: |
set -euo pipefail
TOKEN="${WIKI_TOKEN:-$GH_TOKEN}"
git clone -q "https://x-access-token:${TOKEN}@github.com/${{ github.repository }}.wiki.git" wiki
cd wiki
for f in $(grep -rlE "seaweedfs-(client|hadoop3-client)" --include="*.md" .); do
NEWV="$VERSION" perl -0777 -i -pe '
my $v = $ENV{NEWV};
s{(<artifactId>seaweedfs-(?:client|hadoop3-client)</artifactId>\s*<version>)[0-9]+\.[0-9]+(</version>)}{$1$v$2}g;
s{(seaweedfs-(?:client|hadoop3-client):)[0-9]+\.[0-9]+}{$1$v}g;
s{(seaweedfs-(?:client|hadoop3-client)-)[0-9]+\.[0-9]+(\.jar)}{$1$v$2}g;
s{(seaweedfs-(?:client|hadoop3-client)/)[0-9]+\.[0-9]+(/)}{$1$v$2}g;
' "$f"
done
if git diff --quiet; then
echo "Wiki already references ${VERSION}."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git commit -am "java clients ${VERSION}"
git push
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.39"
appVersion: "4.38"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.39.0
version: 4.38.0
@@ -2,6 +2,8 @@
apiVersion: v1
kind: Service
metadata:
annotations:
service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
name: {{ include "seaweedfs.componentName" (list . "filer") }}
namespace: {{ .Release.Namespace }}
labels:
@@ -10,9 +12,8 @@ metadata:
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: filer
annotations:
service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
{{- if .Values.filer.annotations }}
annotations:
{{- toYaml .Values.filer.annotations | nindent 4 }}
{{- end }}
spec:
+1 -1
View File
@@ -5,7 +5,7 @@
<groupId>com.seaweedfs</groupId>
<artifactId>seaweedfs-client</artifactId>
<version>4.38</version>
<version>4.00</version>
<name>SeaweedFS Java Client</name>
<description>A java client for SeaweedFS.</description>
@@ -1,35 +0,0 @@
package seaweedfs.client;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
// Adds an HTTP Basic Auth "Authorization" header to every gRPC call so the filer can be
// reached through an Nginx reverse proxy with auth_basic enabled.
public class BasicAuthInterceptor implements ClientInterceptor {
private static final Metadata.Key<String> AUTHORIZATION_KEY =
Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
private final String headerValue;
public BasicAuthInterceptor(String headerValue) {
this.headerValue = headerValue;
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
headers.put(AUTHORIZATION_KEY, headerValue);
super.start(responseListener, headers);
}
};
}
}
@@ -14,7 +14,6 @@ import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class FilerGrpcClient {
@@ -38,8 +37,6 @@ public class FilerGrpcClient {
public final Map<String, FilerProto.Locations> vidLocations = new HashMap<>();
protected int randomClientId;
private static final AtomicBoolean plaintextBasicAuthWarned = new AtomicBoolean(false);
// Connection pool to handle concurrent requests
private static final int CHANNEL_POOL_SIZE = 4;
private final List<ManagedChannel> channelPool;
@@ -102,14 +99,6 @@ public class FilerGrpcClient {
builder.overrideAuthority(cn);
}
}
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
if (sslContext == null && plaintextBasicAuthWarned.compareAndSet(false, true)) {
logger.warn("Basic Auth is enabled on a plaintext gRPC channel; credentials are sent in cleartext. Use TLS to the proxy.");
}
builder.intercept(new BasicAuthInterceptor(basicAuthHeader));
}
return builder;
}
@@ -13,12 +13,10 @@ import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Base64;
public abstract class FilerSecurityContext extends SslContext {
//extends Netty SslContext to access its protected static utility methods in
@@ -38,11 +36,6 @@ public abstract class FilerSecurityContext extends SslContext {
private static String httpClientCertChainFilePath;
private static String httpClientPrivateKeyFilePath;
// Optional HTTP Basic Auth for reaching SeaweedFS through an Nginx reverse proxy
// that has auth_basic enabled. Applied to both the filer gRPC channel and the
// volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode.
private static volatile String basicAuthHeaderValue;
static {
String securityFileName = "security.toml";
@@ -62,9 +55,6 @@ public abstract class FilerSecurityContext extends SslContext {
Toml toml = new Toml().read(securityFile);
logger.debug("reading ssl setup from {}", securityFile);
basicAuthHeaderValue = computeBasicAuthHeaderValue(
toml.getString("basic_auth.username"), toml.getString("basic_auth.password"));
grpcTrustCertCollectionFilePath = toml.getString("grpc.ca");
logger.debug("loading gRPC ca from {}", grpcTrustCertCollectionFilePath);
grpcClientCertChainFilePath = toml.getString("grpc.client.cert");
@@ -130,30 +120,6 @@ public abstract class FilerSecurityContext extends SslContext {
return httpSslContext;
}
// Configure HTTP Basic Auth programmatically instead of via security.toml. Must be
// called before constructing a FilerClient so the credentials reach the gRPC channel.
public static void setBasicAuth(String username, String password) {
basicAuthHeaderValue = computeBasicAuthHeaderValue(username, password);
}
public static boolean isBasicAuthEnabled() {
return basicAuthHeaderValue != null;
}
// Returns the "Basic <base64(user:password)>" Authorization header value, or null
// when no Basic Auth credentials are configured.
public static String getBasicAuthHeaderValue() {
return basicAuthHeaderValue;
}
private static String computeBasicAuthHeaderValue(String username, String password) {
if (Strings.isNullOrEmpty(username)) {
return null;
}
String credentials = username + ":" + (password == null ? "" : password);
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
}
private static SslContext buildGrpcSslContext() throws SSLException {
SslContextBuilder builder = GrpcSslContexts.forClient();
if (grpcTrustCertCollectionFilePath != null) {
@@ -111,18 +111,10 @@ public class SeaweedRead {
}
int len = (int) chunkView.size - (int) (startOffset - chunkView.logicOffset);
int srcOffset = (int) (startOffset - chunkView.logicOffset + chunkView.offset);
LOG.debug("readChunkView fid:{} chunkData.length:{} chunkView.offset:{} chunkView[{};{}) startOffset:{}",
chunkView.fileId, chunkData.length, chunkView.offset, chunkView.logicOffset,
chunkView.logicOffset + chunkView.size, startOffset);
// The fetched chunk can be shorter than the view claims when a read briefly
// returns an empty body (seen right after an append). Fail clearly instead of
// letting ByteBuffer.put throw an opaque IndexOutOfBoundsException.
if (srcOffset < 0 || len < 0 || srcOffset > chunkData.length - len) {
throw new IOException("chunk " + chunkView.fileId + " returned " + chunkData.length
+ " bytes, need [" + srcOffset + "," + ((long) srcOffset + len) + ")");
}
buf.put(chunkData, srcOffset, len);
buf.put(chunkData, (int) (startOffset - chunkView.logicOffset + chunkView.offset), len);
return len;
}
@@ -136,15 +128,7 @@ public class SeaweedRead {
for (FilerProto.Location location : locations.getLocationsList()) {
String url = filerClient.getChunkUrl(chunkView.fileId, location.getUrl(), location.getPublicUrl());
try {
byte[] fetched = doFetchOneFullChunkData(chunkView, url);
// An empty (or null) body for a chunk we are reading from is never
// valid; treat it as a transient failure so the retry loop tries
// another location and backs off, rather than caching an empty chunk.
if (fetched == null || fetched.length == 0) {
lastException = new IOException("empty or null response for chunk " + chunkView.fileId + " from " + url);
continue;
}
data = fetched;
data = doFetchOneFullChunkData(chunkView, url);
lastException = null;
break;
} catch (IOException ioe) {
@@ -177,11 +161,6 @@ public class SeaweedRead {
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
}
byte[] data = null;
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
@@ -179,14 +179,7 @@ public class SeaweedWrite {
HttpPost post = new HttpPost(targetUrl);
if (auth != null && auth.length() != 0) {
// Volume JWT and Basic Auth both use the Authorization header; the JWT wins
// when present. Front the volume with a JWT-free path to use Basic Auth here.
post.addHeader("Authorization", "BEARER " + auth);
} else {
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
post.addHeader("Authorization", basicAuthHeader);
}
}
post.addHeader("Content-MD5", Base64.getEncoder().encodeToString(md.digest()));
@@ -325,7 +325,6 @@ message ObjectMutation {
bool set_content = 10; // PATCH_EXTENDED: replace Entry.content with content
bytes content = 11; // PATCH_EXTENDED: new Entry.content when set_content
bool touch_mtime = 12; // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
bool remove_empty_parent = 13; // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
}
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
@@ -1,95 +0,0 @@
package seaweedfs.client;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import org.junit.After;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class BasicAuthTest {
@After
public void clearCredentials() {
FilerSecurityContext.setBasicAuth(null, null);
}
@Test
public void noCredentialsMeansNoHeader() {
FilerSecurityContext.setBasicAuth(null, null);
assertNull(FilerSecurityContext.getBasicAuthHeaderValue());
assertFalse(FilerSecurityContext.isBasicAuthEnabled());
FilerSecurityContext.setBasicAuth("", "ignored");
assertNull(FilerSecurityContext.getBasicAuthHeaderValue());
assertFalse(FilerSecurityContext.isBasicAuthEnabled());
}
@Test
public void encodesUserAndPassword() {
FilerSecurityContext.setBasicAuth("alice", "s3cret");
String expected = "Basic " + Base64.getEncoder()
.encodeToString("alice:s3cret".getBytes(StandardCharsets.UTF_8));
assertEquals(expected, FilerSecurityContext.getBasicAuthHeaderValue());
assertTrue(FilerSecurityContext.isBasicAuthEnabled());
}
@Test
public void interceptorAddsAuthorizationHeader() {
String headerValue = "Basic dGVzdDp0ZXN0";
final Metadata[] captured = new Metadata[1];
Channel channel = new Channel() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> newCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions) {
return new ClientCall<ReqT, RespT>() {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
captured[0] = headers;
}
@Override
public void request(int numMessages) {
}
@Override
public void cancel(String message, Throwable cause) {
}
@Override
public void halfClose() {
}
@Override
public void sendMessage(ReqT message) {
}
};
}
@Override
public String authority() {
return "test";
}
};
BasicAuthInterceptor interceptor = new BasicAuthInterceptor(headerValue);
ClientCall<Object, Object> call =
interceptor.interceptCall(null, CallOptions.DEFAULT, channel);
call.start(null, new Metadata());
Metadata.Key<String> key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
assertNotNull(captured[0]);
assertEquals(headerValue, captured[0].get(key));
}
}
@@ -4,38 +4,12 @@ import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SeaweedReadTest {
// A chunk fetch that briefly returns an empty body (observed right after an
// append) must not overrun the buffer with an opaque IndexOutOfBoundsException.
@Test
public void testReadChunkShorterThanViewFailsCleanly() throws IOException {
String fileId = "7,readchunkshort01";
SeaweedRead.volumeIdCache.setLocations("7",
FilerProto.Locations.newBuilder()
.addLocations(FilerProto.Location.newBuilder().setUrl("localhost:0").build())
.build());
// seed the chunk cache with an empty body so the fetch is skipped
SeaweedRead.chunkCache.setChunk(fileId, new byte[0]);
List<SeaweedRead.VisibleInterval> visibles = new ArrayList<>();
visibles.add(new SeaweedRead.VisibleInterval(0, 175, fileId, 1L, 0, true, null, false));
ByteBuffer buf = ByteBuffer.allocate(175);
try {
SeaweedRead.read(null, visibles, 0, buf, 175);
Assert.fail("expected IOException for a chunk shorter than its view");
} catch (IOException e) {
Assert.assertTrue(e.getMessage(), e.getMessage().contains(fileId));
Assert.assertTrue(e.getMessage(), e.getMessage().contains("[0,175)"));
}
}
@Test
public void testNonOverlappingVisibleIntervals() throws IOException {
List<FilerProto.FileChunk> chunks = new ArrayList<>();
+1 -1
View File
@@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<properties>
<seaweedfs.client.version>4.38</seaweedfs.client.version>
<seaweedfs.client.version>4.00</seaweedfs.client.version>
<hadoop.version>3.4.0</hadoop.version>
</properties>
+13 -22
View File
@@ -743,14 +743,19 @@ pub fn parse_needle_id_cookie(s: &str) -> Result<(NeedleId, Cookie), String> {
let needle_id_hex = &hex_part[..split];
let cookie_hex = &hex_part[split..];
// Go parses both with strconv.ParseUint, which accepts odd-length hex
let mut key = NeedleId(
u64::from_str_radix(needle_id_hex, 16)
.map_err(|e| format!("Parse needleId error: {}", e))?,
);
let cookie = Cookie(
u32::from_str_radix(cookie_hex, 16).map_err(|e| format!("Parse cookie error: {}", e))?,
);
let needle_id_bytes = hex::decode(needle_id_hex).map_err(|e| format!("Parse needleId error: {}", e))?;
let cookie_bytes = hex::decode(cookie_hex).map_err(|e| format!("Parse cookie error: {}", e))?;
// Pad needle id to 8 bytes
let mut nid_buf = [0u8; 8];
if needle_id_bytes.len() > 8 {
return Err(format!("KeyHash is too long."));
}
let start = 8 - needle_id_bytes.len();
nid_buf[start..].copy_from_slice(&needle_id_bytes);
let mut key = NeedleId::from_bytes(&nid_buf[0..8]);
let cookie = Cookie::from_bytes(&cookie_bytes[0..4]);
// Apply delta if present (Go: n.Id += Uint64ToNeedleId(d))
if let Some(d) = delta {
@@ -936,18 +941,4 @@ mod tests {
assert_eq!(key, NeedleId(1));
assert_eq!(cookie, Cookie(0x12345678));
}
#[test]
fn test_parse_odd_length_needle_id() {
// Go's shell formats purge fids with strconv.FormatUint, which does not
// pad the needle id hex to an even length.
let (key, cookie) = parse_needle_id_cookie("100000000").unwrap();
assert_eq!(key, NeedleId(1));
assert_eq!(cookie, Cookie(0));
let fid = FileId::parse("3,12300000000").unwrap();
assert_eq!(fid.volume_id, VolumeId(3));
assert_eq!(fid.key, NeedleId(0x123));
assert_eq!(fid.cookie, Cookie(0));
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ require (
github.com/prometheus/procfs v0.16.1 // indirect
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sys v0.45.0 // indirect
)
+2 -2
View File
@@ -84,8 +84,8 @@ go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+3 -3
View File
@@ -1,17 +1,17 @@
module seaweedfs-sftp-tests
go 1.25.0
go 1.24.0
require (
github.com/pkg/sftp v1.13.7
github.com/stretchr/testify v1.10.0
golang.org/x/crypto v0.52.0
golang.org/x/crypto v0.45.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/kr/fs v0.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/sys v0.38.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+6 -6
View File
@@ -17,8 +17,8 @@ github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5t
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@@ -37,15 +37,15 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+6 -52
View File
@@ -14,38 +14,16 @@ const (
adminLockClientName = "admin-plugin"
)
const (
// A competing shell client polls the master once a second, while a local
// re-acquire would win immediately. Leave the lock free for slightly more
// than one poll interval so a waiting operator gets it first.
defaultAdminLockYieldWindow = 2 * time.Second
// After the lock has been held continuously for this long (overlapping
// reference-counted holds can keep it held indefinitely), new Acquire
// calls wait for a full release so shell clients are not starved.
defaultAdminLockFairnessWindow = time.Minute
)
// adminLocker is the subset of exclusive_locks.ExclusiveLocker the manager uses.
type adminLocker interface {
RequestLock(clientName string)
ReleaseLock()
SetMessage(message string)
}
// AdminLockManager coordinates exclusive admin locks with reference counting.
// It is safe for concurrent use.
type AdminLockManager struct {
locker adminLocker
clientName string
yieldWindow time.Duration
fairnessWindow time.Duration
locker *exclusive_locks.ExclusiveLocker
clientName string
mu sync.Mutex
cond *sync.Cond
acquiring bool
releasing bool
holdCount int
heldSince time.Time
lastAcquiredAt time.Time
lastReleasedAt time.Time
@@ -62,19 +40,13 @@ func NewAdminLockManager(masterClient *wdclient.MasterClient, clientName string)
clientName = adminLockClientName
}
manager := &AdminLockManager{
locker: exclusive_locks.NewExclusiveLocker(masterClient, adminLockName),
clientName: clientName,
yieldWindow: defaultAdminLockYieldWindow,
fairnessWindow: defaultAdminLockFairnessWindow,
locker: exclusive_locks.NewExclusiveLocker(masterClient, adminLockName),
clientName: clientName,
}
manager.cond = sync.NewCond(&manager.mu)
return manager
}
// Acquire takes the shared cluster lock, reference counted so overlapping
// admin-side holders piggyback on one lease. It must not be called while the
// caller's own call stack already holds the lock: once the fairness window
// makes new acquires wait for a full release, a nested Acquire deadlocks.
func (m *AdminLockManager) Acquire(reason string) (func(), error) {
if m == nil || m.locker == nil {
return func() {}, nil
@@ -85,28 +57,18 @@ func (m *AdminLockManager) Acquire(reason string) (func(), error) {
m.locker.SetMessage(reason)
m.currentReason = reason
}
for m.acquiring || m.releasing || (m.holdCount > 0 && time.Since(m.heldSince) > m.fairnessWindow) {
for m.acquiring {
m.cond.Wait()
}
if m.holdCount == 0 {
m.acquiring = true
m.waitingSince = time.Now().UTC()
m.waitingReason = reason
yield := time.Duration(0)
if !m.lastReleasedAt.IsZero() {
if since := time.Since(m.lastReleasedAt); since < m.yieldWindow {
yield = m.yieldWindow - since
}
}
m.mu.Unlock()
if yield > 0 {
time.Sleep(yield)
}
m.locker.RequestLock(m.clientName)
m.mu.Lock()
m.acquiring = false
m.holdCount = 1
m.heldSince = time.Now()
m.lastAcquiredAt = time.Now().UTC()
m.waitingSince = time.Time{}
m.waitingReason = ""
@@ -134,22 +96,14 @@ func (m *AdminLockManager) Release() {
}
m.holdCount--
shouldRelease := m.holdCount == 0
if shouldRelease {
// Block new acquires until ReleaseLock completes: a RequestLock
// issued while the locker still considers itself locked would no-op
// and leave a hold with no live lease.
m.releasing = true
}
m.mu.Unlock()
if shouldRelease {
m.locker.ReleaseLock()
m.mu.Lock()
m.releasing = false
m.lastReleasedAt = time.Now().UTC()
m.currentReason = ""
m.cond.Broadcast()
m.mu.Unlock()
m.locker.ReleaseLock()
}
}
-156
View File
@@ -1,156 +0,0 @@
package dash
import (
"sync"
"testing"
"time"
)
type fakeAdminLocker struct {
releaseDelay time.Duration
mu sync.Mutex
requests []time.Time
releases []time.Time // recorded when ReleaseLock returns
}
func (f *fakeAdminLocker) RequestLock(clientName string) {
f.mu.Lock()
f.requests = append(f.requests, time.Now())
f.mu.Unlock()
}
func (f *fakeAdminLocker) ReleaseLock() {
if f.releaseDelay > 0 {
time.Sleep(f.releaseDelay)
}
f.mu.Lock()
f.releases = append(f.releases, time.Now())
f.mu.Unlock()
}
func (f *fakeAdminLocker) SetMessage(message string) {}
func (f *fakeAdminLocker) counts() (int, int) {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.requests), len(f.releases)
}
func newTestLockManager(locker adminLocker, yieldWindow, fairnessWindow time.Duration) *AdminLockManager {
m := &AdminLockManager{
locker: locker,
clientName: "test",
yieldWindow: yieldWindow,
fairnessWindow: fairnessWindow,
}
m.cond = sync.NewCond(&m.mu)
return m
}
func TestAdminLockManagerRefCountsOverlappingHolds(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{}
m := newTestLockManager(locker, defaultAdminLockYieldWindow, defaultAdminLockFairnessWindow)
release1, _ := m.Acquire("a")
release2, _ := m.Acquire("b")
if requests, releases := locker.counts(); requests != 1 || releases != 0 {
t.Fatalf("expected one lease request while overlapping, got requests=%d releases=%d", requests, releases)
}
release1()
if _, releases := locker.counts(); releases != 0 {
t.Fatalf("lock released while still held by another caller")
}
release2()
if _, releases := locker.counts(); releases != 1 {
t.Fatalf("expected one release after last holder, got %d", releases)
}
}
func TestAdminLockManagerYieldsBeforeReacquire(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{}
m := newTestLockManager(locker, 100*time.Millisecond, defaultAdminLockFairnessWindow)
release, _ := m.Acquire("first")
release()
release, _ = m.Acquire("second")
release()
locker.mu.Lock()
gap := locker.requests[1].Sub(locker.releases[0])
locker.mu.Unlock()
if gap < 90*time.Millisecond {
t.Fatalf("re-acquire did not yield to competing clients: gap=%v", gap)
}
}
func TestAdminLockManagerFairnessWindowForcesFullRelease(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{}
m := newTestLockManager(locker, 20*time.Millisecond, 50*time.Millisecond)
release1, _ := m.Acquire("long-hold")
m.mu.Lock()
m.heldSince = time.Now().Add(-time.Second)
m.mu.Unlock()
acquired := make(chan func(), 1)
go func() {
release2, _ := m.Acquire("late-joiner")
acquired <- release2
}()
select {
case <-acquired:
t.Fatalf("late acquire joined a hold older than the fairness window")
case <-time.After(50 * time.Millisecond):
}
release1()
select {
case release2 := <-acquired:
release2()
case <-time.After(time.Second):
t.Fatalf("late acquire did not proceed after full release")
}
if requests, releases := locker.counts(); requests != 2 || releases != 2 {
t.Fatalf("expected a full release/re-acquire cycle, got requests=%d releases=%d", requests, releases)
}
}
func TestAdminLockManagerAcquireWaitsForReleaseInFlight(t *testing.T) {
t.Parallel()
locker := &fakeAdminLocker{releaseDelay: 50 * time.Millisecond}
m := newTestLockManager(locker, time.Millisecond, defaultAdminLockFairnessWindow)
release1, _ := m.Acquire("first")
releaseDone := make(chan struct{})
go func() {
release1()
close(releaseDone)
}()
// Let the release enter the slow ReleaseLock before re-acquiring.
time.Sleep(10 * time.Millisecond)
release2, _ := m.Acquire("second")
<-releaseDone
release2()
locker.mu.Lock()
defer locker.mu.Unlock()
if len(locker.requests) != 2 || len(locker.releases) != 2 {
t.Fatalf("unexpected lease traffic: requests=%d releases=%d", len(locker.requests), len(locker.releases))
}
if locker.requests[1].Before(locker.releases[0]) {
t.Fatalf("RequestLock ran while ReleaseLock was still in flight")
}
}
+2 -2
View File
@@ -1459,8 +1459,8 @@ func (s *AdminServer) RunPluginDetectionWithReport(
// DispatchPluginProposals dispatches a batch of proposals using the same
// capacity-aware dispatch logic as the scheduler loop (executor reservation with
// backoff, per-job retry on transient errors). The dispatch takes the cluster
// admin lock around each job itself; callers must not hold it.
// backoff, per-job retry on transient errors). The plugin lock must already be
// held by the caller.
func (s *AdminServer) DispatchPluginProposals(
ctx context.Context,
jobType string,
+8 -3
View File
@@ -595,15 +595,20 @@ func (s *AdminServer) TriggerPluginDetectionAPI(w http.ResponseWriter, r *http.R
}
// RunPluginJobTypeAPI runs full workflow for one job type: detect then dispatch detected jobs.
// RunPluginDetection and the dispatch path take the cluster admin lock
// themselves (around detection and around each job), so no lock is held
// across the whole workflow here.
func (s *AdminServer) RunPluginJobTypeAPI(w http.ResponseWriter, r *http.Request) {
jobType := strings.TrimSpace(mux.Vars(r)["jobType"])
if jobType == "" {
writeJSONError(w, http.StatusBadRequest, "jobType is required")
return
}
releaseLock, err := s.acquirePluginLock(fmt.Sprintf("plugin detect+execute %s", jobType))
if err != nil {
writeJSONError(w, http.StatusInternalServerError, err.Error())
return
}
if releaseLock != nil {
defer releaseLock()
}
var req struct {
ClusterContext json.RawMessage `json:"cluster_context"`
+1 -7
View File
@@ -424,13 +424,7 @@ func (r *Plugin) acquireAdminLock(reason string) (func(), error) {
if r == nil || r.lockManager == nil {
return func() {}, nil
}
release, err := r.lockManager.Acquire(reason)
if release == nil {
// Lock manager implementations may return a nil release when
// disabled; callers always invoke the release function.
release = func() {}
}
return release, err
return r.lockManager.Acquire(reason)
}
// RunDetectionWithReport requests one detector worker and returns proposals with request metadata.
+57 -90
View File
@@ -98,11 +98,9 @@ func (r *Plugin) laneSchedulerLoop(ls *schedulerLaneState) {
// runLaneSchedulerIteration runs one scheduling pass for a single lane,
// processing only the job types assigned to that lane.
//
// For lanes that require a lock (e.g. LaneDefault), job types are processed
// sequentially because their volume management operations share global
// state, and the cluster admin lock is taken around each detection and each
// dispatched job rather than the whole pass, so manual shell operations
// sharing the same lock can interleave between jobs.
// For lanes that require a lock (e.g. LaneDefault), all job types are
// processed sequentially under one admin lock because their volume
// management operations share global state.
//
// For lanes that do not require a lock (e.g. LaneIceberg, LaneLifecycle),
// each job type runs independently in its own goroutine so they do not
@@ -124,7 +122,7 @@ func (r *Plugin) runLaneSchedulerIteration(ls *schedulerLaneState) bool {
}
if LaneRequiresLock(ls.lane) {
return r.runLaneSchedulerIterationSequential(ls, jobTypes)
return r.runLaneSchedulerIterationLocked(ls, jobTypes)
}
return r.runLaneSchedulerIterationConcurrent(ls, jobTypes)
}
@@ -164,13 +162,21 @@ func (r *Plugin) collectDueJobTypes(ls *schedulerLaneState, jobTypes []string) (
return active, due
}
// runLaneSchedulerIterationSequential processes job types one at a time.
// Used by the default lane where volume management operations must be
// serialised. The cluster admin lock is not held across the pass;
// runJobTypeIteration and dispatchScheduledProposals take it around each
// detection and each job.
func (r *Plugin) runLaneSchedulerIterationSequential(ls *schedulerLaneState, jobTypes []string) bool {
r.setLaneLoopState(ls, "", "busy")
// runLaneSchedulerIterationLocked processes job types sequentially under a
// single admin lock. Used by the default lane where volume management
// operations must be serialised.
func (r *Plugin) runLaneSchedulerIterationLocked(ls *schedulerLaneState, jobTypes []string) bool {
r.setLaneLoopState(ls, "", "waiting_for_lock")
lockName := fmt.Sprintf("plugin scheduler:%s", ls.lane)
releaseLock, err := r.acquireAdminLock(lockName)
if err != nil {
glog.Warningf("Plugin scheduler [%s] failed to acquire lock: %v", ls.lane, err)
r.setLaneLoopState(ls, "", "idle")
return false
}
if releaseLock != nil {
defer releaseLock()
}
active, due := r.collectDueJobTypes(ls, jobTypes)
hadJobs := false
@@ -282,30 +288,6 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
return false
}
// Detection plans against the live topology, so it runs under the shared
// cluster admin lock; the lock is released as soon as detection returns.
releaseDetectionLock := func() {}
if LaneRequiresLock(JobTypeLane(jobType)) {
r.setSchedulerLoopStateForJobType(jobType, "waiting_for_lock")
release, lockErr := r.acquireAdminLock(fmt.Sprintf("plugin scheduler %s detection", jobType))
if lockErr != nil {
r.recordSchedulerDetectionError(jobType, lockErr)
r.appendActivity(JobActivity{
JobType: jobType,
Source: "admin_scheduler",
Message: fmt.Sprintf("scheduled detection aborted: %v", lockErr),
Stage: "failed",
OccurredAt: timeToPtr(time.Now().UTC()),
})
r.recordSchedulerRunComplete(jobType, "error")
return false
}
var releaseOnce sync.Once
releaseDetectionLock = func() { releaseOnce.Do(release) }
r.setSchedulerLoopStateForJobType(jobType, "detecting")
}
defer releaseDetectionLock()
detectionTimeout := policy.DetectionTimeout
remaining := time.Until(start.Add(maxRuntime))
if remaining <= 0 {
@@ -329,7 +311,6 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
detectCtx, cancelDetect := context.WithTimeout(jobCtx, detectionTimeout)
proposals, err := r.RunDetection(detectCtx, jobType, clusterContext, policy.MaxResults)
cancelDetect()
releaseDetectionLock()
if err != nil {
r.recordSchedulerDetectionError(jobType, err)
stage := "failed"
@@ -394,6 +375,26 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
r.setSchedulerLoopStateForJobType(jobType, "executing")
// Scan proposals for the maximum estimated_runtime_seconds so the
// execution phase gets enough time for large jobs (e.g. vacuum on
// big volumes). If any proposal needs more time than the remaining
// JobTypeMaxRuntime, extend the execution context accordingly.
var maxEstimatedRuntime time.Duration
for _, p := range filtered {
if p.Parameters != nil {
if est, ok := p.Parameters["estimated_runtime_seconds"]; ok {
if v := est.GetInt64Value(); v > 0 {
if d := time.Duration(v) * time.Second; d > maxEstimatedRuntime {
maxEstimatedRuntime = d
}
}
}
}
}
if maxEstimatedRuntime > maxEstimatedRuntimeCap {
maxEstimatedRuntime = maxEstimatedRuntimeCap
}
remaining = time.Until(start.Add(maxRuntime))
if remaining <= 0 {
r.appendActivity(JobActivity{
@@ -407,6 +408,17 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
return detected
}
// If the longest estimated job exceeds the remaining JobTypeMaxRuntime,
// create a new execution context with enough headroom instead of using
// jobCtx which would cancel too early.
execCtx := jobCtx
execCancel := context.CancelFunc(func() {})
if maxEstimatedRuntime > 0 && maxEstimatedRuntime > remaining {
execCtx, execCancel = context.WithTimeout(context.Background(), maxEstimatedRuntime)
remaining = maxEstimatedRuntime
}
defer execCancel()
execPolicy := policy
if execPolicy.ExecutionTimeout <= 0 {
execPolicy.ExecutionTimeout = defaultScheduledExecutionTimeout
@@ -415,15 +427,10 @@ func (r *Plugin) runJobTypeIteration(jobType string, policy schedulerPolicy) boo
execPolicy.ExecutionTimeout = remaining
}
// 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)
successCount, errorCount, canceledCount := r.dispatchScheduledProposals(execCtx, jobType, filtered, clusterContext, execPolicy)
status := "success"
if jobCtx.Err() != nil {
if execCtx.Err() != nil {
status = "timeout"
} else if errorCount > 0 || canceledCount > 0 {
status = "error"
@@ -811,11 +818,6 @@ func (r *Plugin) dispatchScheduledProposals(
ctx = context.Background()
}
// Volume management jobs mutate volume placement, so each one runs under
// the shared cluster admin lock. Taking it per job instead of around the
// whole dispatch lets manual shell operations interleave between jobs.
jobsRequireLock := LaneRequiresLock(JobTypeLane(jobType))
jobQueue := make(chan *plugin_pb.JobSpec, len(proposals))
for index, proposal := range proposals {
job := buildScheduledJobSpec(jobType, proposal, index)
@@ -898,42 +900,7 @@ func (r *Plugin) dispatchScheduledProposals(
break
}
var releaseJobLock func()
if jobsRequireLock {
var lockErr error
releaseJobLock, lockErr = r.acquireAdminLock(fmt.Sprintf("plugin scheduler %s job %s", jobType, job.JobId))
if lockErr != nil {
release()
statsMu.Lock()
errorCount++
statsMu.Unlock()
r.appendActivity(JobActivity{
JobID: job.JobId,
JobType: job.JobType,
Source: "admin_scheduler",
Message: fmt.Sprintf("scheduled execution lock failed: %v", lockErr),
Stage: "failed",
OccurredAt: timeToPtr(time.Now().UTC()),
})
break
}
// The lock may have been held by an operator for a
// while; re-check the execution window.
if ctx.Err() != nil {
releaseJobLock()
release()
r.cancelQueuedJob(job, ctx.Err())
statsMu.Lock()
canceledCount++
statsMu.Unlock()
continue jobLoop
}
}
err := r.executeScheduledJobWithExecutor(ctx, executor, job, clusterContext, policy)
if releaseJobLock != nil {
releaseJobLock()
}
release()
if errors.Is(err, errExecutorAtCapacity) {
r.trackExecutionQueued(job)
@@ -1197,6 +1164,10 @@ func (r *Plugin) executeScheduledJobWithExecutor(
return ctx.Err()
}
parent := ctx
if parent == nil {
parent = context.Background()
}
// Use the job's estimated runtime if provided and larger than the
// default execution timeout. This lets handlers like vacuum scale
// the timeout based on volume size so large volumes are not killed.
@@ -1214,11 +1185,7 @@ func (r *Plugin) executeScheduledJobWithExecutor(
}
}
}
// 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)
execCtx, cancel := context.WithTimeout(parent, timeout)
_, err := r.executeJobWithExecutor(execCtx, executor, job, clusterContext, int32(attempt))
cancel()
if err == nil {
@@ -664,12 +664,6 @@ func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
t.Fatalf("SaveJobTypeConfig: %v", err)
}
// Make the job type due immediately so the iteration reaches
// detection; the lock is only taken around due work now.
pluginSvc.schedulerMu.Lock()
pluginSvc.nextDetectionAt[tt.jobType] = time.Now().UTC().Add(-time.Second)
pluginSvc.schedulerMu.Unlock()
ls := pluginSvc.lanes[tt.lane]
pluginSvc.runLaneSchedulerIteration(ls)
@@ -680,61 +674,6 @@ func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
}
}
func TestDispatchScheduledProposalsLocksPerJob(t *testing.T) {
t.Parallel()
tests := []struct {
name string
jobType string
wantLocks int
}{
{"DefaultLaneLocksEachJob", "volume_balance", 3},
{"LifecycleLaneNeedsNoLock", "s3_lifecycle", 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
lm := &trackingLockManager{}
pluginSvc, err := New(Options{LockManager: lm})
if err != nil {
t.Fatalf("New: %v", err)
}
defer pluginSvc.Shutdown()
// The worker has capabilities but no connected session, so each
// job reserves capacity, fails to send, and moves on.
pluginSvc.registry.UpsertFromHello(&plugin_pb.WorkerHello{
WorkerId: "worker-a",
Capabilities: []*plugin_pb.JobTypeCapability{
{JobType: tt.jobType, CanExecute: true, MaxExecutionConcurrency: 4},
},
})
policy := schedulerPolicy{
ExecutionConcurrency: 1,
PerWorkerConcurrency: 1,
ExecutionTimeout: time.Second,
ExecutorReserveBackoff: time.Millisecond,
}
proposals := []*plugin_pb.JobProposal{
{ProposalId: "p1", JobType: tt.jobType, DedupeKey: "k1"},
{ProposalId: "p2", JobType: tt.jobType, DedupeKey: "k2"},
{ProposalId: "p3", JobType: tt.jobType, DedupeKey: "k3"},
}
success, errors, canceled := pluginSvc.dispatchScheduledProposals(
context.Background(), tt.jobType, proposals, &plugin_pb.ClusterContext{}, policy)
if success != 0 || canceled != 0 || errors != 3 {
t.Fatalf("unexpected dispatch counts: success=%d errors=%d canceled=%d", success, errors, canceled)
}
if got := lm.count(); got != tt.wantLocks {
t.Fatalf("lock acquired %d times, want %d", got, tt.wantLocks)
}
})
}
}
// ---------- lane-scoped prune ----------
func TestPruneSchedulerState_DefaultLaneKeepsForeignLanesAndPrunesOwnStale(t *testing.T) {
+7 -9
View File
@@ -6,8 +6,8 @@ import (
)
// SchedulerLane identifies an independent scheduling track. Each lane runs
// its own goroutine and maintains its own detection timing so that
// workloads in different lanes never block each other.
// its own goroutine, maintains its own detection timing, and acquires its
// own admin lock so that workloads in different lanes never block each other.
type SchedulerLane string
const (
@@ -39,19 +39,17 @@ var laneIdleSleep = map[SchedulerLane]time.Duration{
}
// laneRequiresLock maps each lane to whether its job types must be
// serialised and run under the shared cluster admin lock. The default
// lane needs this because volume-management operations share global
// state; the lock is taken around each detection and each job so manual
// shell operations can interleave. Other lanes run each job type
// independently without the lock.
// serialised under a single admin lock. The default lane needs this
// because volume-management operations share global state. Other
// lanes run each job type independently.
var laneRequiresLock = map[SchedulerLane]bool{
LaneDefault: true,
LaneIceberg: false,
LaneLifecycle: false,
}
// LaneRequiresLock returns true if the given lane serialises its job types
// and runs them under the cluster admin lock. Unknown lanes default to true.
// LaneRequiresLock returns true if the given lane needs a single admin
// lock to serialise its job types. Unknown lanes default to true.
func LaneRequiresLock(lane SchedulerLane) bool {
if v, ok := laneRequiresLock[lane]; ok {
return v
@@ -128,11 +128,6 @@ func (efc *EmptyFolderCleaner) OnDeleteEvent(directory string, entryName string,
return
}
// Never queue the S3 multipart staging area; the upload lifecycle owns it.
if isMultipartUploadsPath(efc.bucketPath, directory) {
return
}
// Check if we own this folder
if !efc.ownsFolder(directory) {
glog.V(4).Infof("EmptyFolderCleaner: not owner of %s, skipping", directory)
@@ -244,15 +239,6 @@ func (efc *EmptyFolderCleaner) processCleanupQueue() {
// 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.
// Deleting <bucket>/.uploads (reached here directly or via the parent cascade
// below) races a concurrent CreateMultipartUpload: the new upload's marker row
// is inserted between the emptiness check and the folder delete, then wiped,
// so the upload silently vanishes. Leave this tree to the upload lifecycle.
if isMultipartUploadsPath(efc.bucketPath, folder) {
return
}
efc.mu.Lock()
// Quick check: if we have cached count and it's > 0, skip
@@ -436,21 +422,6 @@ func isUnderPath(child, parent string) bool {
return child[len(parent)] == '/'
}
// isMultipartUploadsPath reports whether directory is the S3 multipart staging
// root <bucket>/.uploads or anything beneath it.
func isMultipartUploadsPath(bucketPath, directory string) bool {
if bucketPath == "" {
return false
}
dir, ok := util.ExtractBucketPath(bucketPath, directory, true)
if !ok {
return false
}
// requireChild guarantees directory starts with dir + "/", so slice past it.
first, _, _ := strings.Cut(directory[len(dir)+1:], "/")
return first == s3_constants.MultipartUploadsFolder
}
// isUnderBucketPath checks if directory is inside a bucket (under /buckets/<bucket>/...)
// This ensures we only clean up folders inside buckets, not the buckets themselves
func isUnderBucketPath(directory, bucketPath string) bool {
@@ -104,102 +104,6 @@ func Test_isUnderBucketPath(t *testing.T) {
}
}
func Test_isMultipartUploadsPath(t *testing.T) {
uploads := s3_constants.MultipartUploadsFolder
tests := []struct {
name string
directory string
bucketPath string
expected bool
}{
{"staging root", "/buckets/mybucket/" + uploads, "/buckets", true},
{"upload marker dir", "/buckets/mybucket/" + uploads + "/abc123", "/buckets", true},
{"nested under staging", "/buckets/mybucket/" + uploads + "/abc123/hashstates", "/buckets", true},
{"normal folder", "/buckets/mybucket/folder", "/buckets", false},
{"registry own uploads dir", "/buckets/mybucket/docker/registry/v2/_uploads/x", "/buckets", false},
{"bucket itself", "/buckets/mybucket", "/buckets", false},
{"outside buckets", "/other/" + uploads, "/buckets", false},
{"empty bucket path", "/buckets/mybucket/" + uploads, "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isMultipartUploadsPath(tt.bucketPath, tt.directory); got != tt.expected {
t.Errorf("isMultipartUploadsPath(%q, %q) = %v, want %v", tt.bucketPath, tt.directory, got, tt.expected)
}
})
}
}
func TestEmptyFolderCleaner_OnDeleteEvent_skipsMultipartUploads(t *testing.T) {
lockRing := lock_manager.NewLockRing(5 * time.Second)
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"}, 0)
cleaner := &EmptyFolderCleaner{
lockRing: lockRing,
host: "filer1:8888",
bucketPath: "/buckets",
enabled: true,
folderCounts: make(map[string]*folderState),
cleanupQueue: NewCleanupQueue(1000, 10*time.Minute),
stopCh: make(chan struct{}),
}
now := time.Now()
uploads := "/buckets/mybucket/" + s3_constants.MultipartUploadsFolder
cleaner.OnDeleteEvent(uploads, "abc123", true, now)
cleaner.OnDeleteEvent(uploads+"/abc123", "0001.part", false, now)
if cleaner.GetPendingCleanupCount() != 0 {
t.Fatalf("multipart staging paths must not be queued, got %d pending", cleaner.GetPendingCleanupCount())
}
// A normal folder is still queued, proving the guard is scoped to .uploads.
cleaner.OnDeleteEvent("/buckets/mybucket/folder", "file.txt", false, now)
if cleaner.GetPendingCleanupCount() != 1 {
t.Fatalf("normal folder should be queued, got %d pending", cleaner.GetPendingCleanupCount())
}
cleaner.Stop()
}
func TestEmptyFolderCleaner_executeCleanup_skipsMultipartUploads(t *testing.T) {
lockRing := lock_manager.NewLockRing(5 * time.Second)
lockRing.SetSnapshot([]pb.ServerAddress{"filer1:8888"}, 0)
var deleted []string
mock := &mockFilerOps{
countFn: func(util.FullPath) (int, error) { return 0, nil },
deleteFn: func(p util.FullPath) error { deleted = append(deleted, string(p)); return nil },
}
cleaner := &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),
cleanupQueue: NewCleanupQueue(1000, 10*time.Minute),
stopCh: make(chan struct{}),
}
uploads := "/buckets/mybucket/" + s3_constants.MultipartUploadsFolder
cleaner.executeCleanup(uploads, "abc123")
cleaner.executeCleanup(uploads+"/abc123", "0001.part")
if len(deleted) != 0 {
t.Fatalf("multipart staging paths must not be deleted, got %v", deleted)
}
// An empty normal folder is deleted, proving the guard did not disable cleanup.
cleaner.executeCleanup("/buckets/mybucket/folder", "file.txt")
if len(deleted) != 1 || deleted[0] != "/buckets/mybucket/folder" {
t.Fatalf("normal empty folder should be deleted, got %v", deleted)
}
}
func Test_autoRemoveEmptyFoldersEnabled(t *testing.T) {
tests := []struct {
name string
+4 -16
View File
@@ -59,14 +59,12 @@ func (m *MockOIDCProvider) Authenticate(ctx context.Context, token string) (*pro
email, _ := claims.GetClaimString("email")
displayName, _ := claims.GetClaimString("name")
groups, _ := claims.GetClaimStringSlice("groups")
rawRoles, _ := claims.GetClaimStringSlice("roles")
return &providers.ExternalIdentity{
UserID: claims.Subject,
Email: email,
DisplayName: displayName,
Groups: groups,
Roles: rawRoles,
Provider: m.name,
}, nil
}
@@ -109,26 +107,16 @@ func (m *MockOIDCProvider) ValidateToken(ctx context.Context, token string) (*pr
issuedAt = time.Unix(int64(iat), 0)
}
// Carry the token's claims through like the real provider, keeping
// the synthesized defaults for tests that rely on them
claimsMap := make(map[string]interface{}, len(jwtClaims)+2)
for k, v := range jwtClaims {
claimsMap[k] = v
}
if _, ok := claimsMap["email"]; !ok {
claimsMap["email"] = subject + "@test-domain.com"
}
if _, ok := claimsMap["name"]; !ok {
claimsMap["name"] = "Test User " + subject
}
return &providers.TokenClaims{
Subject: subject,
Issuer: issuer,
Audience: audience,
ExpiresAt: expiresAt,
IssuedAt: issuedAt,
Claims: claimsMap,
Claims: map[string]interface{}{
"email": subject + "@test-domain.com",
"name": "Test User " + subject,
},
}, nil
}
}
-5
View File
@@ -481,10 +481,6 @@ func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*provide
email, _ := claims.GetClaimString("email")
displayName, _ := claims.GetClaimString("name")
groups, _ := claims.GetClaimStringSlice("groups")
// The raw `roles` claim (e.g. from a Keycloak realm-role mapper). Surfaced into
// the STS request context below (see ExternalIdentity.Roles) so resource policies
// can gate on jwt:roles. Distinct from the provider-configured role mapping below.
rawRoles, _ := claims.GetClaimStringSlice("roles")
// Debug: Log available claims
glog.V(3).Infof("Available claims: %+v", claims.Claims)
@@ -539,7 +535,6 @@ func (p *OIDCProvider) Authenticate(ctx context.Context, token string) (*provide
Email: email,
DisplayName: displayName,
Groups: groups,
Roles: rawRoles,
Attributes: attributes,
Provider: p.name,
Issuer: claims.Issuer,
-7
View File
@@ -43,13 +43,6 @@ type ExternalIdentity struct {
// Groups are the groups the user belongs to
Groups []string `json:"groups,omitempty"`
// Roles are the roles the user holds (from the token's `roles` claim).
// Surfaced into the STS request context so resource policies can gate on
// jwt:roles - same rationale as Groups (the claim is otherwise excluded from
// attributes by the provider's processedClaims set, so it never reached the
// request context and was usable only via provider-configured role mapping).
Roles []string `json:"roles,omitempty"`
// Attributes are additional user attributes
Attributes map[string]string `json:"attributes,omitempty"`
-20
View File
@@ -640,26 +640,6 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
// Add sub as well since it's commonly used
requestContext["sub"] = externalIdentity.UserID
// Surface federated group memberships so resource (permission) policies can do
// group-based ABAC - not just role trust policies. Stored as a []string; the
// string-condition evaluator already handles multi-valued context keys, and the
// S3 middleware additionally exposes it as jwt:groups. Without this, "groups"
// was excluded from the OIDC attributes (see oidc_provider processedClaims) and
// so only usable at assume-time (trust policy), never at request-time - meaning
// a single role's permission policy could not scope access by the caller's
// groups (aggregate/ABAC).
if len(externalIdentity.Groups) > 0 {
requestContext["groups"] = externalIdentity.Groups
}
// Same for the caller's roles (the `roles` claim). Surfaced as a []string so a
// resource policy can gate on jwt:roles - the S3 middleware exposes it that way.
// Without this, "roles" was excluded from the OIDC attributes (processedClaims)
// and so unusable in a request-time permission policy.
if len(externalIdentity.Roles) > 0 {
requestContext["roles"] = externalIdentity.Roles
}
// Compute a stable parent-user hash from (sub, iss). Only this tuple is
// guaranteed stable across token refresh per OIDC Core 1.0, so this is the
// right key for any per-identity state (audit trail, future quotas).
-1
View File
@@ -325,7 +325,6 @@ message ObjectMutation {
bool set_content = 10; // PATCH_EXTENDED: replace Entry.content with content
bytes content = 11; // PATCH_EXTENDED: new Entry.content when set_content
bool touch_mtime = 12; // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
bool remove_empty_parent = 13; // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
}
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
+17 -26
View File
@@ -1476,22 +1476,21 @@ func (x *WriteCondition) GetClauses() []*WriteCondition_Clause {
// several RPCs. Data-bearing writes (entries with chunks) should be written
// before the transaction; mutations here are metadata-scoped.
type ObjectMutation struct {
state protoimpl.MessageState `protogen:"open.v1"`
Type ObjectMutation_Type `protobuf:"varint,1,opt,name=type,proto3,enum=filer_pb.ObjectMutation_Type" json:"type,omitempty"`
Directory string `protobuf:"bytes,2,opt,name=directory,proto3" json:"directory,omitempty"`
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // entry name for DELETE / PATCH_EXTENDED / RECOMPUTE_LATEST (the pointer entry)
Entry *Entry `protobuf:"bytes,4,opt,name=entry,proto3" json:"entry,omitempty"` // full entry for PUT
SetExtended map[string][]byte `protobuf:"bytes,5,rep,name=set_extended,json=setExtended,proto3" json:"set_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // PATCH_EXTENDED: keys to set
DeleteExtended []string `protobuf:"bytes,6,rep,name=delete_extended,json=deleteExtended,proto3" json:"delete_extended,omitempty"` // PATCH_EXTENDED: keys to remove
IsDeleteData bool `protobuf:"varint,7,opt,name=is_delete_data,json=isDeleteData,proto3" json:"is_delete_data,omitempty"` // DELETE: also delete chunk data
IsRecursive bool `protobuf:"varint,8,opt,name=is_recursive,json=isRecursive,proto3" json:"is_recursive,omitempty"` // DELETE: recurse into a directory
Recompute *Recompute `protobuf:"bytes,9,opt,name=recompute,proto3" json:"recompute,omitempty"` // RECOMPUTE_LATEST parameters
SetContent bool `protobuf:"varint,10,opt,name=set_content,json=setContent,proto3" json:"set_content,omitempty"` // PATCH_EXTENDED: replace Entry.content with content
Content []byte `protobuf:"bytes,11,opt,name=content,proto3" json:"content,omitempty"` // PATCH_EXTENDED: new Entry.content when set_content
TouchMtime bool `protobuf:"varint,12,opt,name=touch_mtime,json=touchMtime,proto3" json:"touch_mtime,omitempty"` // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
RemoveEmptyParent bool `protobuf:"varint,13,opt,name=remove_empty_parent,json=removeEmptyParent,proto3" json:"remove_empty_parent,omitempty"` // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
state protoimpl.MessageState `protogen:"open.v1"`
Type ObjectMutation_Type `protobuf:"varint,1,opt,name=type,proto3,enum=filer_pb.ObjectMutation_Type" json:"type,omitempty"`
Directory string `protobuf:"bytes,2,opt,name=directory,proto3" json:"directory,omitempty"`
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // entry name for DELETE / PATCH_EXTENDED / RECOMPUTE_LATEST (the pointer entry)
Entry *Entry `protobuf:"bytes,4,opt,name=entry,proto3" json:"entry,omitempty"` // full entry for PUT
SetExtended map[string][]byte `protobuf:"bytes,5,rep,name=set_extended,json=setExtended,proto3" json:"set_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // PATCH_EXTENDED: keys to set
DeleteExtended []string `protobuf:"bytes,6,rep,name=delete_extended,json=deleteExtended,proto3" json:"delete_extended,omitempty"` // PATCH_EXTENDED: keys to remove
IsDeleteData bool `protobuf:"varint,7,opt,name=is_delete_data,json=isDeleteData,proto3" json:"is_delete_data,omitempty"` // DELETE: also delete chunk data
IsRecursive bool `protobuf:"varint,8,opt,name=is_recursive,json=isRecursive,proto3" json:"is_recursive,omitempty"` // DELETE: recurse into a directory
Recompute *Recompute `protobuf:"bytes,9,opt,name=recompute,proto3" json:"recompute,omitempty"` // RECOMPUTE_LATEST parameters
SetContent bool `protobuf:"varint,10,opt,name=set_content,json=setContent,proto3" json:"set_content,omitempty"` // PATCH_EXTENDED: replace Entry.content with content
Content []byte `protobuf:"bytes,11,opt,name=content,proto3" json:"content,omitempty"` // PATCH_EXTENDED: new Entry.content when set_content
TouchMtime bool `protobuf:"varint,12,opt,name=touch_mtime,json=touchMtime,proto3" json:"touch_mtime,omitempty"` // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ObjectMutation) Reset() {
@@ -1608,13 +1607,6 @@ func (x *ObjectMutation) GetTouchMtime() bool {
return false
}
func (x *ObjectMutation) GetRemoveEmptyParent() bool {
if x != nil {
return x.RemoveEmptyParent
}
return false
}
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
// current contents of a scanned directory, atomically under the transaction's
// lock. It is mechanical: the filer picks the child that sorts first or last by
@@ -6936,7 +6928,7 @@ const file_filer_proto_rawDesc = "" +
"\x13IF_UNMODIFIED_SINCE\x10\x05\x12\x15\n" +
"\x11IF_MODIFIED_SINCE\x10\x06\x12\x19\n" +
"\x15IF_EXTENDED_NOT_EQUAL\x10\a\x12\x1c\n" +
"\x18IF_EXTENDED_TIME_ELAPSED\x10\b\"\xa2\x05\n" +
"\x18IF_EXTENDED_TIME_ELAPSED\x10\b\"\xf2\x04\n" +
"\x0eObjectMutation\x121\n" +
"\x04type\x18\x01 \x01(\x0e2\x1d.filer_pb.ObjectMutation.TypeR\x04type\x12\x1c\n" +
"\tdirectory\x18\x02 \x01(\tR\tdirectory\x12\x12\n" +
@@ -6952,8 +6944,7 @@ const file_filer_proto_rawDesc = "" +
"setContent\x12\x18\n" +
"\acontent\x18\v \x01(\fR\acontent\x12\x1f\n" +
"\vtouch_mtime\x18\f \x01(\bR\n" +
"touchMtime\x12.\n" +
"\x13remove_empty_parent\x18\r \x01(\bR\x11removeEmptyParent\x1a>\n" +
"touchMtime\x1a>\n" +
"\x10SetExtendedEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"E\n" +
+1 -1
View File
@@ -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 v6.33.4
// source: filer.proto
package filer_pb
-75
View File
@@ -1,75 +0,0 @@
package pluginworker
import (
"context"
"fmt"
"strconv"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"google.golang.org/grpc"
)
// LookupVolumeLocations asks the masters for the current registered locations
// of a volume, bypassing any client-side caches. Execution handlers use it to
// re-check a proposal against the live topology, since a proposal can go
// stale between detection and execution. Returns the location URLs
// (host:port) the master reports; an empty slice means the volume is not
// registered anywhere.
func LookupVolumeLocations(ctx context.Context, masterAddresses []string, grpcDialOption grpc.DialOption, volumeID uint32) ([]string, error) {
if grpcDialOption == nil {
return nil, fmt.Errorf("grpc dial option is not configured")
}
if len(masterAddresses) == 0 {
return nil, fmt.Errorf("no master addresses provided in cluster context")
}
vid := strconv.FormatUint(uint64(volumeID), 10)
var lastErr error
for _, address := range masterAddresses {
for _, candidate := range MasterAddressCandidates(address) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
dialCtx, cancelDial := context.WithTimeout(ctx, 5*time.Second)
conn, err := pb.GrpcDial(dialCtx, candidate, false, grpcDialOption)
cancelDial()
if err != nil {
lastErr = err
continue
}
client := master_pb.NewSeaweedClient(conn)
callCtx, cancelCall := context.WithTimeout(ctx, 10*time.Second)
resp, callErr := client.LookupVolume(callCtx, &master_pb.LookupVolumeRequest{
VolumeOrFileIds: []string{vid},
})
cancelCall()
_ = conn.Close()
if callErr != nil {
lastErr = callErr
continue
}
for _, vidLocation := range resp.VolumeIdLocations {
if vidLocation.VolumeOrFileId != vid {
continue
}
locations := make([]string, 0, len(vidLocation.Locations))
for _, location := range vidLocation.Locations {
locations = append(locations, location.Url)
}
return locations, nil
}
// The master answered but does not know the volume.
return nil, nil
}
}
if lastErr == nil {
lastErr = fmt.Errorf("no valid master address candidate")
}
return nil, lastErr
}
+7 -37
View File
@@ -4,7 +4,6 @@ import (
"context"
"crypto/sha256"
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
@@ -47,13 +46,12 @@ func TestReverseProxySignatureVerification(t *testing.T) {
}`
tests := []struct {
name string
externalUrl string // s3.externalUrl config for the backend
clientScheme string // scheme the client uses for signing
clientHost string // host the client signs against
proxyForwardsHost bool // whether proxy sets X-Forwarded-Host
portlessForwardedHost bool // nginx-style $host / $server_port: hostname in X-Forwarded-Host, port in X-Forwarded-Port
expectSuccess bool
name string
externalUrl string // s3.externalUrl config for the backend
clientScheme string // scheme the client uses for signing
clientHost string // host the client signs against
proxyForwardsHost bool // whether proxy sets X-Forwarded-Host
expectSuccess bool
}{
{
name: "non-standard port, externalUrl matches proxy address",
@@ -103,26 +101,6 @@ func TestReverseProxySignatureVerification(t *testing.T) {
proxyForwardsHost: false,
expectSuccess: false,
},
{
// The backend Host (127.0.0.1:ephemeral) shares the forwarded hostname, so the
// backend port must not shadow X-Forwarded-Port.
name: "nginx $host/$server_port forwarding, backend on same hostname",
externalUrl: "",
clientScheme: "http",
clientHost: "127.0.0.1:9000",
proxyForwardsHost: true,
portlessForwardedHost: true,
expectSuccess: true,
},
{
name: "portless X-Forwarded-Host on default port, backend on same hostname",
externalUrl: "",
clientScheme: "http",
clientHost: "127.0.0.1",
proxyForwardsHost: true,
portlessForwardedHost: true,
expectSuccess: true,
},
{
name: "proxy without X-Forwarded-Host, externalUrl saves the day",
externalUrl: "http://api.example.com:9000",
@@ -158,7 +136,6 @@ func TestReverseProxySignatureVerification(t *testing.T) {
proxy := httputil.NewSingleHostReverseProxy(backendURL)
forwardsHost := tt.proxyForwardsHost
portlessForwardedHost := tt.portlessForwardedHost
originalDirector := proxy.Director
proxy.Director = func(req *http.Request) {
originalHost := req.Host
@@ -171,14 +148,7 @@ func TestReverseProxySignatureVerification(t *testing.T) {
// (nginx proxy_pass and Kong both do this by default)
req.Host = backendURL.Host
if forwardsHost {
forwardedHost := originalHost
if portlessForwardedHost {
if h, p, splitErr := net.SplitHostPort(originalHost); splitErr == nil {
forwardedHost = h
req.Header.Set("X-Forwarded-Port", p)
}
}
req.Header.Set("X-Forwarded-Host", forwardedHost)
req.Header.Set("X-Forwarded-Host", originalHost)
req.Header.Set("X-Forwarded-Proto", originalScheme)
}
}
+39 -83
View File
@@ -29,7 +29,6 @@ import (
"net/http"
"net/url"
"regexp"
"slices"
"sort"
"strconv"
"strings"
@@ -315,57 +314,36 @@ func (iam *IdentityAccessManagement) verifyV4Signature(r *http.Request, shouldCh
)
}
// 8. Verify the signature for each plausible host value: when X-Forwarded-Host carries
// no port, the client may have signed the Host header the proxy kept or the forwarded
// host and port, and the headers alone cannot tell which.
// 8. Verify the signature, trying with X-Forwarded-Prefix first
pathForSignature := r.URL.EscapedPath()
if pathForSignature == "" {
pathForSignature = r.URL.Path
}
forwardedPrefix := r.Header.Get("X-Forwarded-Prefix")
for i, hostCandidate := range extractHostHeaderCandidates(r, iam.externalHost) {
if i > 0 && !replaceSignedHostHeader(extractedSignedHeaders, hostCandidate) {
break
}
// 9. Verify with the X-Forwarded-Prefix path first
if forwardedPrefix != "" {
cleanedPath := buildPathWithForwardedPrefix(forwardedPrefix, pathForSignature)
calculatedSignature, errCode = verify(cleanedPath)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
}
// 10. Verify with the original path
calculatedSignature, errCode = verify(pathForSignature)
if forwardedPrefix := r.Header.Get("X-Forwarded-Prefix"); forwardedPrefix != "" {
cleanedPath := buildPathWithForwardedPrefix(forwardedPrefix, pathForSignature)
calculatedSignature, errCode = verify(cleanedPath)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
}
// 11. Retry with decoded path if signature used raw path encoding
if decodedPath, decodeErr := url.PathUnescape(pathForSignature); decodeErr == nil && decodedPath != pathForSignature {
calculatedSignature, errCode = verify(decodedPath)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
// 9. Verify with the original path
calculatedSignature, errCode = verify(pathForSignature)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
// 10. Retry with decoded path if signature used raw path encoding
if decodedPath, decodeErr := url.PathUnescape(pathForSignature); decodeErr == nil && decodedPath != pathForSignature {
calculatedSignature, errCode = verify(decodedPath)
if errCode == s3err.ErrNone {
return identity, cred, calculatedSignature, authInfo, s3err.ErrNone
}
}
return nil, nil, "", nil, errCode
}
func replaceSignedHostHeader(headers http.Header, host string) bool {
replaced := false
for name := range headers {
if strings.EqualFold(name, "host") {
headers[name] = []string{host}
replaced = true
}
}
return replaced
}
// validateSTSSessionToken validates an STS session token and extracts temporary credentials
func (iam *IdentityAccessManagement) validateSTSSessionToken(r *http.Request, sessionToken string, accessKey string) (*Identity, *Credential, s3err.ErrorCode) {
// Check if IAM integration is available
@@ -882,20 +860,13 @@ func extractSignedHeaders(signedHeaders []string, r *http.Request, externalHost
return extractedSignedHeaders, s3err.ErrNone
}
// extractHostHeader returns the most likely host header value for signature verification.
// extractHostHeader returns the value of host header to use for signature verification.
// When externalHost is set (from s3.externalUrl), it is returned directly.
// Otherwise, the host is reconstructed from X-Forwarded-* headers or the request Host,
// with default port stripping to match AWS SDK SanitizeHostForHeader behavior.
func extractHostHeader(r *http.Request, externalHost string) string {
return extractHostHeaderCandidates(r, externalHost)[0]
}
// extractHostHeaderCandidates returns the host values the client may have signed, most
// likely first. When externalHost is set (from s3.externalUrl), it is the only candidate.
// Otherwise, the host is reconstructed from X-Forwarded-* headers or the request Host.
// When X-Forwarded-Host carries no port, the true client port is ambiguous: a proxy that
// kept the Host header makes the r.Host port right, one that rewrote it makes
// X-Forwarded-Port right, and a client on the scheme's default port signed no port at all.
func extractHostHeaderCandidates(r *http.Request, externalHost string) []string {
if externalHost != "" {
return []string{externalHost}
return externalHost
}
forwardedHost := r.Header.Get("X-Forwarded-Host")
@@ -924,8 +895,7 @@ func extractHostHeaderCandidates(r *http.Request, externalHost string) []string
scheme = forwardedProto
}
var host string
var ports []string
var host, port string
if forwardedHost != "" {
// X-Forwarded-Host can be a comma-separated list of hosts when there are multiple proxies.
// Use only the first host in the list and trim spaces for robustness.
@@ -938,16 +908,14 @@ func extractHostHeaderCandidates(r *http.Request, externalHost string) []string
// If the host itself contains a port, it should take precedence
if h, p, err := net.SplitHostPort(host); err == nil {
host = h
ports = []string{p}
port = p
} else {
// SplitHostPort unbrackets IPv6 hosts, so unbracket the forwarded host to match
if rh, rp, err := net.SplitHostPort(r.Host); err == nil && rh == strings.Trim(host, "[]") {
ports = append(ports, rp)
// If X-Forwarded-Host has no port, try to get port from r.Host if hostnames match
if rh, rp, err := net.SplitHostPort(r.Host); err == nil && rh == host {
port = rp
} else if forwardedPort != "" {
port = forwardedPort
}
if forwardedPort != "" {
ports = append(ports, forwardedPort)
}
ports = append(ports, "")
}
} else {
host = r.Host
@@ -959,29 +927,14 @@ func extractHostHeaderCandidates(r *http.Request, externalHost string) []string
// Otherwise, if X-Forwarded-Port is set, use it.
if h, p, err := net.SplitHostPort(host); err == nil {
host = h
ports = []string{p}
} else {
if forwardedPort != "" {
ports = append(ports, forwardedPort)
}
ports = append(ports, "")
port = p
} else if forwardedPort != "" {
port = forwardedPort
}
}
var candidates []string
for _, port := range ports {
candidate := joinSignedHost(host, port, scheme)
if !slices.Contains(candidates, candidate) {
candidates = append(candidates, candidate)
}
}
return candidates
}
// joinSignedHost renders host:port the way AWS SDKs sign it: default ports are stripped
// to match SanitizeHostForHeader, and bare IPv6 addresses lose their brackets.
// Reference: https://github.com/aws/aws-sdk-go-v2/blob/main/aws/signer/internal/v4/host.go
func joinSignedHost(host, port, scheme string) string {
// Strip default ports based on scheme to match AWS SDK SanitizeHostForHeader behavior.
// The AWS SDK strips port 80 for HTTP and port 443 for HTTPS before signing.
if port != "" && !isDefaultPort(scheme, port) {
// Strip existing brackets before calling JoinHostPort, which automatically adds
// brackets for IPv6 addresses. This prevents double-bracketing like [[::1]]:8080.
@@ -989,6 +942,9 @@ func joinSignedHost(host, port, scheme string) string {
return net.JoinHostPort(host, port)
}
// Default port was stripped, or no port present.
// For IPv6 addresses, strip brackets to match AWS SDK behavior.
// Reference: https://github.com/aws/aws-sdk-go-v2/blob/main/aws/signer/internal/v4/host.go
if strings.Contains(host, ":") {
return strings.Trim(host, "[]")
}
@@ -1167,9 +1123,9 @@ func encodePath(pathName string) string {
if runeLen < 0 {
return pathName
}
var u [utf8.UTFMax]byte
utf8.EncodeRune(u[:], s)
for _, r := range u[:runeLen] {
u := make([]byte, runeLen)
utf8.EncodeRune(u, s)
for _, r := range u {
buf.WriteByte('%')
buf.WriteByte(pathHexTable[r>>4])
buf.WriteByte(pathHexTable[r&0x0f])
-106
View File
@@ -6,7 +6,6 @@ import (
"encoding/hex"
"fmt"
"net/http"
"slices"
"testing"
"time"
@@ -522,111 +521,6 @@ func TestExtractHostHeader(t *testing.T) {
}
}
// TestExtractHostHeaderCandidates tests the alternate host values tried during verification
// when the true client-facing host is ambiguous behind a reverse proxy.
func TestExtractHostHeaderCandidates(t *testing.T) {
tests := []struct {
name string
hostHeader string
forwardedHost string
forwardedPort string
forwardedProto string
externalHost string
expected []string
}{
{
name: "externalHost is the only candidate",
hostHeader: "backend:8333",
externalHost: "api.example.com:9000",
expected: []string{"api.example.com:9000"},
},
{
name: "X-Forwarded-Host with port is trusted as-is",
hostHeader: "backend:8333",
forwardedHost: "example.com:9000",
forwardedPort: "443",
expected: []string{"example.com:9000"},
},
{
name: "plain Host with port is the only candidate",
hostHeader: "example.com:8080",
expected: []string{"example.com:8080"},
},
{
name: "portless X-Forwarded-Host, hostnames match: r.Host port first, then X-Forwarded-Port, then bare",
hostHeader: "example.com:8333",
forwardedHost: "example.com",
forwardedPort: "9000",
forwardedProto: "http",
expected: []string{"example.com:8333", "example.com:9000", "example.com"},
},
{
name: "portless X-Forwarded-Host, hostnames match, no X-Forwarded-Port: bare host as fallback",
hostHeader: "example.com:8333",
forwardedHost: "example.com",
expected: []string{"example.com:8333", "example.com"},
},
{
name: "portless X-Forwarded-Host, hostnames differ: X-Forwarded-Port, then bare",
hostHeader: "backend:8333",
forwardedHost: "example.com",
forwardedPort: "9000",
expected: []string{"example.com:9000", "example.com"},
},
{
name: "default X-Forwarded-Port collapses into the bare candidate",
hostHeader: "example.com:8333",
forwardedHost: "example.com",
forwardedPort: "443",
forwardedProto: "https",
expected: []string{"example.com:8333", "example.com"},
},
{
name: "portless Host with X-Forwarded-Port: forwarded port, then bare",
hostHeader: "example.com",
forwardedPort: "9000",
expected: []string{"example.com:9000", "example.com"},
},
{
name: "bracketed portless IPv6 X-Forwarded-Host matches the request host",
hostHeader: "[::1]:8333",
forwardedHost: "[::1]",
expected: []string{"[::1]:8333", "::1"},
},
{
name: "unbracketed portless IPv6 X-Forwarded-Host with X-Forwarded-Port",
hostHeader: "backend:8333",
forwardedHost: "::1",
forwardedPort: "8080",
expected: []string{"[::1]:8080", "::1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "http://"+tt.hostHeader+"/bucket/object", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Host = tt.hostHeader
if tt.forwardedHost != "" {
req.Header.Set("X-Forwarded-Host", tt.forwardedHost)
}
if tt.forwardedPort != "" {
req.Header.Set("X-Forwarded-Port", tt.forwardedPort)
}
if tt.forwardedProto != "" {
req.Header.Set("X-Forwarded-Proto", tt.forwardedProto)
}
result := extractHostHeaderCandidates(req, tt.externalHost)
if !slices.Equal(result, tt.expected) {
t.Errorf("extractHostHeaderCandidates() = %v, want %v", result, tt.expected)
}
})
}
}
func TestExtractSignedHeadersCase(t *testing.T) {
tests := []struct {
name string
-232
View File
@@ -1,232 +0,0 @@
package s3api
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
"github.com/seaweedfs/seaweedfs/weed/iam/oidc"
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestGroupsRolesPolicyEnforcement verifies that OIDC groups and roles claims reach
// the request-time policy evaluation of an STS session, so a single role's permission
// policy can scope bucket access with ForAnyValue:StringEquals on jwt:groups / jwt:roles.
// The full path is exercised: AssumeRoleWithWebIdentity embeds the claims in the session
// JWT, AuthenticateJWT restores them (as []interface{} after the JSON round-trip), and
// AuthorizeAction evaluates the conditions.
func TestGroupsRolesPolicyEnforcement(t *testing.T) {
ctx := context.Background()
iamManager := setupGroupsRolesIAMManager(t)
s3iam := NewS3IAMIntegration(iamManager, "localhost:8888")
// One role for everyone; each bucket statement is gated on a groups or roles claim
abacPolicy := &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{
{
Sid: "TeamABucketByGroup",
Effect: "Allow",
Action: []string{"s3:GetObject", "s3:PutObject"},
Resource: []string{
"arn:aws:s3:::team-a-bucket/*",
},
Condition: map[string]map[string]interface{}{
"ForAnyValue:StringEquals": {
"jwt:groups": "team-a",
},
},
},
{
Sid: "TeamBBucketByRole",
Effect: "Allow",
Action: []string{"s3:GetObject", "s3:PutObject"},
Resource: []string{
"arn:aws:s3:::team-b-bucket/*",
},
Condition: map[string]map[string]interface{}{
"ForAnyValue:StringEquals": {
"jwt:roles": "team-b-rw",
},
},
},
},
}
require.NoError(t, iamManager.CreatePolicy(ctx, "", "TeamABACPolicy", abacPolicy))
require.NoError(t, iamManager.CreateRole(ctx, "", "TeamABACRole", &integration.RoleDefinition{
RoleName: "TeamABACRole",
TrustPolicy: &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "test-oidc",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
AttachedPolicies: []string{"TeamABACPolicy"},
}))
tests := []struct {
name string
token string
allowTeamA bool
allowTeamB bool
}{
{
name: "group member gets team-a bucket only",
token: groupsRolesJWT(t, "team-a-user", []string{"team-a"}, nil),
allowTeamA: true,
allowTeamB: false,
},
{
name: "role holder gets team-b bucket only",
token: groupsRolesJWT(t, "team-b-user", nil, []string{"team-b-rw"}),
allowTeamA: false,
allowTeamB: true,
},
{
name: "member of both gets both buckets in one session",
token: groupsRolesJWT(t, "both-teams-user", []string{"team-a", "team-b"}, []string{"team-a-rw", "team-b-rw"}),
allowTeamA: true,
allowTeamB: true,
},
{
name: "user without matching claims is denied everywhere",
token: groupsRolesJWT(t, "no-team-user", []string{"other-team"}, []string{"other-role"}),
allowTeamA: false,
allowTeamB: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
response, err := iamManager.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
RoleArn: "arn:aws:iam::role/TeamABACRole",
WebIdentityToken: tt.token,
RoleSessionName: "abac-test-session",
})
require.NoError(t, err)
identity, errCode := authenticateSessionToken(t, s3iam, response.Credentials.SessionToken)
require.Equal(t, s3err.ErrNone, errCode)
assert.Equal(t, tt.allowTeamA, authorizeGet(ctx, s3iam, identity, "team-a-bucket"), "team-a-bucket access")
assert.Equal(t, tt.allowTeamB, authorizeGet(ctx, s3iam, identity, "team-b-bucket"), "team-b-bucket access")
})
}
}
// TestGroupsRolesSessionRequestContext pins the session round-trip itself: the groups
// and roles claims must come back from the session JWT as multi-valued context keys.
func TestGroupsRolesSessionRequestContext(t *testing.T) {
ctx := context.Background()
iamManager := setupGroupsRolesIAMManager(t)
require.NoError(t, iamManager.CreateRole(ctx, "", "ContextRole", &integration.RoleDefinition{
RoleName: "ContextRole",
TrustPolicy: &policy.PolicyDocument{
Version: "2012-10-17",
Statement: []policy.Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "test-oidc",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
}))
response, err := iamManager.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
RoleArn: "arn:aws:iam::role/ContextRole",
WebIdentityToken: groupsRolesJWT(t, "both-teams-user", []string{"team-a", "team-b"}, []string{"team-a-rw", "team-b-rw"}),
RoleSessionName: "context-test-session",
})
require.NoError(t, err)
sessionInfo, err := iamManager.GetSTSService().ValidateSessionToken(ctx, response.Credentials.SessionToken)
require.NoError(t, err)
require.NotNil(t, sessionInfo.RequestContext)
// JWT serialization turns []string into []interface{}; assert that shape so a
// future change to the condition evaluator's type handling fails loudly here.
assert.Equal(t, []interface{}{"team-a", "team-b"}, sessionInfo.RequestContext["groups"])
assert.Equal(t, []interface{}{"team-a-rw", "team-b-rw"}, sessionInfo.RequestContext["roles"])
}
func setupGroupsRolesIAMManager(t *testing.T) *integration.IAMManager {
manager := integration.NewIAMManager()
config := &integration.IAMConfig{
STS: &sts.STSConfig{
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
MaxSessionLength: sts.FlexibleDuration{Duration: time.Hour * 12},
Issuer: "test-sts",
SigningKey: []byte("test-signing-key-32-characters-long"),
},
Policy: &policy.PolicyEngineConfig{
DefaultEffect: "Deny",
StoreType: "memory",
},
Roles: &integration.RoleStoreConfig{
StoreType: "memory",
},
}
require.NoError(t, manager.Initialize(config, func() string {
return "localhost:8888"
}))
provider := oidc.NewMockOIDCProvider("test-oidc")
require.NoError(t, provider.Initialize(&oidc.OIDCConfig{
Issuer: "https://test-issuer.com",
ClientID: "test-client-id",
}))
require.NoError(t, manager.RegisterIdentityProvider(provider))
return manager
}
// groupsRolesJWT builds a web identity token carrying groups and roles claims.
func groupsRolesJWT(t *testing.T, subject string, groups, roles []string) string {
claims := jwt.MapClaims{
"iss": "https://test-issuer.com",
"sub": subject,
"aud": "test-client-id",
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
}
if groups != nil {
claims["groups"] = groups
}
if roles != nil {
claims["roles"] = roles
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("test-signing-key"))
require.NoError(t, err)
return token
}
func authenticateSessionToken(t *testing.T, s3iam *S3IAMIntegration, sessionToken string) (*IAMIdentity, s3err.ErrorCode) {
req := httptest.NewRequest("GET", "/", http.NoBody)
req.Header.Set("Authorization", "Bearer "+sessionToken)
return s3iam.AuthenticateJWT(context.Background(), req)
}
func authorizeGet(ctx context.Context, s3iam *S3IAMIntegration, identity *IAMIdentity, bucket string) bool {
req := httptest.NewRequest("GET", "/"+bucket+"/file.txt", http.NoBody)
req.Header.Set("Authorization", "Bearer "+identity.SessionToken)
return s3iam.AuthorizeAction(ctx, identity, s3_constants.ACTION_READ, bucket, "file.txt", req) == s3err.ErrNone
}
+141 -195
View File
@@ -109,15 +109,7 @@ func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Requ
// Adjust marker if it ends with delimiter to skip all entries with that prefix
marker = adjustMarkerForDelimiter(marker, delimiter)
response, err := s3a.listFilerEntries(r.Context(), listObjectsRequest{
bucket: bucket,
prefix: originalPrefix,
marker: marker,
delimiter: delimiter,
maxKeys: maxKeys,
encodingTypeUrl: encodingTypeUrl,
fetchOwner: fetchOwner,
})
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
if err != nil {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
@@ -181,15 +173,7 @@ func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Requ
// Adjust marker if it ends with delimiter to skip all entries with that prefix
marker = adjustMarkerForDelimiter(marker, delimiter)
response, err := s3a.listFilerEntries(r.Context(), listObjectsRequest{
bucket: bucket,
prefix: originalPrefix,
marker: marker,
delimiter: delimiter,
maxKeys: uint16(maxKeys),
encodingTypeUrl: encodingTypeUrl,
fetchOwner: true,
})
response, err := s3a.listFilerEntries(r.Context(), bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
if err != nil {
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
@@ -248,20 +232,7 @@ func sanitizeV1MarkerEcho(response *ListBucketResult, marker string, encodingTyp
}
}
type listObjectsRequest struct {
bucket string
prefix string
marker string
delimiter string
maxKeys uint16
encodingTypeUrl bool
fetchOwner bool
}
func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsRequest) (response ListBucketResult, err error) {
bucket, originalPrefix, originalMarker := req.bucket, req.prefix, req.marker
maxKeys, delimiter := req.maxKeys, req.delimiter
encodingTypeUrl, fetchOwner := req.encodingTypeUrl, req.fetchOwner
func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
// convert full path prefix into directory name and prefix for entry name
requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
bucketPrefix := s3a.bucketPrefix(bucket)
@@ -327,7 +298,7 @@ func (s3a *S3ApiServer) listFilerEntries(ctx context.Context, req listObjectsReq
for {
empty := true
nextMarker, doErr = s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: reqDir, prefix: prefix, marker: marker, delimiter: delimiter, bucket: bucket}, cursor, func(dir string, entry *filer_pb.Entry) {
nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, cursor, marker, delimiter, false, bucket, func(dir string, entry *filer_pb.Entry) {
empty = false
dirName, entryName, _ := entryUrlEncode(dir, entry.Name, encodingTypeUrl)
if entry.IsDirectory {
@@ -586,18 +557,7 @@ func buildTruncatedNextMarker(requestDir, prefix, nextMarker string, lastEntryWa
return nextMarker
}
type listDirectoryRequest struct {
dir string
prefix string
marker string
delimiter string
bucket string
inclusiveStartFrom bool
}
func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.SeaweedFilerClient, req listDirectoryRequest, cursor *ListingCursor, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
dir, prefix, bucket := req.dir, req.prefix, req.bucket
marker, delimiter, inclusiveStartFrom := req.marker, req.delimiter, req.inclusiveStartFrom
func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, bucket string, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
// invariants
// prefix and marker should be under dir, marker may contain "/"
// maxKeys should be updated for each recursion
@@ -611,7 +571,7 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
if strings.Contains(marker, "/") {
subDir, subMarker := toParentAndDescendants(marker)
// println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + subDir, marker: subMarker, delimiter: delimiter, bucket: bucket}, cursor, eachEntryFn)
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", cursor, subMarker, delimiter, false, bucket, eachEntryFn)
if subErr != nil {
err = subErr
return
@@ -625,170 +585,156 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
}
// now marker is also a direct child of dir
ctx, cancel := context.WithCancel(ctx)
request := &filer_pb.ListEntriesRequest{
Directory: dir,
Prefix: prefix,
Limit: uint32(cursor.maxKeys) + 2, // bucket root directory needs to skip additional s3_constants.MultipartUploadsFolder folder
StartFromFileName: marker,
InclusiveStartFrom: inclusiveStartFrom,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Entries that emit nothing (empty directories, the .uploads folder, the marker
// echo) consume the request window without consuming maxKeys, so one window may
// end before maxKeys is satisfied. Keep requesting from the last received entry
// until the quota is filled or a short window shows the directory is exhausted.
for {
request := &filer_pb.ListEntriesRequest{
Directory: dir,
Prefix: prefix,
Limit: uint32(cursor.maxKeys) + 2, // bucket root directory needs to skip additional s3_constants.MultipartUploadsFolder folder
StartFromFileName: marker,
InclusiveStartFrom: inclusiveStartFrom,
stream, listErr := client.ListEntries(ctx, request)
if listErr != nil {
if errors.Is(listErr, filer_pb.ErrNotFound) {
return
}
err = fmt.Errorf("list entries %+v: %w", request, listErr)
return
}
stream, listErr := client.ListEntries(ctx, request)
if listErr != nil {
if errors.Is(listErr, filer_pb.ErrNotFound) {
for {
resp, recvErr := stream.Recv()
if recvErr != nil {
if recvErr == io.EOF {
break
} else {
err = fmt.Errorf("iterating entries %+v: %v", request, recvErr)
return
}
err = fmt.Errorf("list entries %+v: %w", request, listErr)
return
}
entry := resp.Entry
if entry == nil {
continue
}
// listFilerEntries always calls doListFilerEntries with inclusiveStartFrom=false
// (S3 marker semantics are exclusive), but keep the guard explicit to preserve
// behavior if inclusive callers are introduced in the future.
if !inclusiveStartFrom && marker != "" && entry.Name == marker {
continue
}
var entriesReceived uint32
var lastEntryName string
for {
resp, recvErr := stream.Recv()
if recvErr != nil {
if recvErr == io.EOF {
break
} else {
err = fmt.Errorf("iterating entries %+v: %v", request, recvErr)
return
}
}
entry := resp.Entry
if entry == nil {
continue
}
entriesReceived++
lastEntryName = entry.Name
// listFilerEntries always calls doListFilerEntries with inclusiveStartFrom=false
// (S3 marker semantics are exclusive), but keep the guard explicit to preserve
// behavior if inclusive callers are introduced in the future.
if !inclusiveStartFrom && marker != "" && entry.Name == marker {
continue
}
if cursor.maxKeys <= 0 {
cursor.isTruncated = true
break
}
if cursor.maxKeys <= 0 {
cursor.isTruncated = true
break
}
// Set nextMarker only when we have quota to process this entry
nextMarker = entry.Name
// Track whether this entry is the exact directory targeted by a trailing-slash prefix
// (e.g., prefix "foo" from original prefix "foo/"). After recursing into this directory,
// we must stop processing siblings to avoid matching unrelated entries like "foo1000".
matchedPrefixDir := cursor.prefixEndsOnDelimiter && entry.Name == prefix && entry.IsDirectory
if cursor.prefixEndsOnDelimiter {
if entry.Name == prefix && entry.IsDirectory {
if delimiter != "/" {
cursor.prefixEndsOnDelimiter = false
}
} else {
continue
}
}
if entry.IsDirectory {
// glog.V(4).Infof("List Dir Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
if entry.Name == s3_constants.MultipartUploadsFolder { // FIXME no need to apply to all directories. this extra also affects maxKeys
continue
}
// Process .versions directories immediately to create logical versioned object entries
// These directories are never traversed (we continue here), so each is only encountered once
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
// Extract object name from .versions directory name
baseObjectName := strings.TrimSuffix(entry.Name, s3_constants.VersionsFolder)
// Construct full object path relative to bucket
bucketFullPath := s3a.bucketDir(bucket)
bucketRelativePath := strings.TrimPrefix(dir, bucketFullPath)
bucketRelativePath = strings.TrimPrefix(bucketRelativePath, "/")
var fullObjectPath string
if bucketRelativePath == "" {
fullObjectPath = baseObjectName
} else {
fullObjectPath = bucketRelativePath + "/" + baseObjectName
}
// Use metadata from the already-fetched .versions directory entry
if latestVersionEntry, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, entry); err == nil {
eachEntryFn(dir, latestVersionEntry)
} else if !errors.Is(err, ErrDeleteMarker) {
// Log unexpected errors (delete markers are expected)
glog.V(2).Infof("Skipping versioned object %s due to error: %v", fullObjectPath, err)
}
continue
}
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
// A trailing-slash prefix (e.g. "logs/") names one directory and asks
// whether it exists, so a real but empty directory must be reported for
// that probe.
explicitDirProbe := cursor.prefixEndsOnDelimiter
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
}
isKeyObject := entry.IsDirectoryKeyObject()
if isKeyObject {
// Directory key objects (created via PutObject with trailing "/")
// must appear as regular keys in recursive listing mode.
eachEntryFn(dir, entry)
}
// Recurse into subdirectory to list any children, noting whether the
// subtree produced any entries.
childEmitted := false
subNextMarker, subErr := s3a.doListFilerEntries(ctx, client, listDirectoryRequest{dir: dir + "/" + entry.Name, delimiter: delimiter, bucket: bucket}, cursor, func(d string, e *filer_pb.Entry) {
childEmitted = true
eachEntryFn(d, e)
})
if subErr != nil {
err = fmt.Errorf("doListFilerEntries2: %w", subErr)
return
}
// A real but empty directory (created out of band via mount, mkdir or
// the filer API, so it carries no MIME) is otherwise invisible to S3
// clients that detect directories by listing it under its own "<dir>/"
// prefix. Surface it as a directory marker for that explicit probe,
// identical to a directory created via PutObject with a trailing "/", so
// tools like hadoop-aws can find it. Plain listings are left untouched, so
// empty directories left behind by deleted objects are not shown as keys.
if explicitDirProbe && !isKeyObject && !childEmitted && !cursor.isTruncated && entry.Attributes != nil {
entry.Attributes.Mime = s3_constants.FolderMimeType
eachEntryFn(dir, entry)
}
// println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
nextMarker = entry.Name + "/" + subNextMarker
if cursor.isTruncated {
return
}
if matchedPrefixDir {
return
}
// println("doListFilerEntries2 nextMarker", nextMarker)
} else {
eachEntryFn(dir, entry)
// Set nextMarker only when we have quota to process this entry
nextMarker = entry.Name
// Track whether this entry is the exact directory targeted by a trailing-slash prefix
// (e.g., prefix "foo" from original prefix "foo/"). After recursing into this directory,
// we must stop processing siblings to avoid matching unrelated entries like "foo1000".
matchedPrefixDir := cursor.prefixEndsOnDelimiter && entry.Name == prefix && entry.IsDirectory
if cursor.prefixEndsOnDelimiter {
if entry.Name == prefix && entry.IsDirectory {
if delimiter != "/" {
cursor.prefixEndsOnDelimiter = false
}
} else {
eachEntryFn(dir, entry)
// glog.V(4).Infof("List File Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
}
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
continue
}
}
if entry.IsDirectory {
// glog.V(4).Infof("List Dir Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
if entry.Name == s3_constants.MultipartUploadsFolder { // FIXME no need to apply to all directories. this extra also affects maxKeys
continue
}
if cursor.isTruncated || entriesReceived < request.Limit {
return
// Process .versions directories immediately to create logical versioned object entries
// These directories are never traversed (we continue here), so each is only encountered once
if strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
// Extract object name from .versions directory name
baseObjectName := strings.TrimSuffix(entry.Name, s3_constants.VersionsFolder)
// Construct full object path relative to bucket
bucketFullPath := s3a.bucketDir(bucket)
bucketRelativePath := strings.TrimPrefix(dir, bucketFullPath)
bucketRelativePath = strings.TrimPrefix(bucketRelativePath, "/")
var fullObjectPath string
if bucketRelativePath == "" {
fullObjectPath = baseObjectName
} else {
fullObjectPath = bucketRelativePath + "/" + baseObjectName
}
// Use metadata from the already-fetched .versions directory entry
if latestVersionEntry, err := s3a.getLatestVersionEntryFromDirectoryEntry(bucket, fullObjectPath, entry); err == nil {
eachEntryFn(dir, latestVersionEntry)
} else if !errors.Is(err, ErrDeleteMarker) {
// Log unexpected errors (delete markers are expected)
glog.V(2).Infof("Skipping versioned object %s due to error: %v", fullObjectPath, err)
}
continue
}
if delimiter != "/" || cursor.prefixEndsOnDelimiter {
// A trailing-slash prefix (e.g. "logs/") names one directory and asks
// whether it exists, so a real but empty directory must be reported for
// that probe.
explicitDirProbe := cursor.prefixEndsOnDelimiter
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
}
isKeyObject := entry.IsDirectoryKeyObject()
if isKeyObject {
// Directory key objects (created via PutObject with trailing "/")
// must appear as regular keys in recursive listing mode.
eachEntryFn(dir, entry)
}
// Recurse into subdirectory to list any children, noting whether the
// subtree produced any entries.
childEmitted := false
subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, bucket, func(d string, e *filer_pb.Entry) {
childEmitted = true
eachEntryFn(d, e)
})
if subErr != nil {
err = fmt.Errorf("doListFilerEntries2: %w", subErr)
return
}
// A real but empty directory (created out of band via mount, mkdir or
// the filer API, so it carries no MIME) is otherwise invisible to S3
// clients that detect directories by listing it under its own "<dir>/"
// prefix. Surface it as a directory marker for that explicit probe,
// identical to a directory created via PutObject with a trailing "/", so
// tools like hadoop-aws can find it. Plain listings are left untouched, so
// empty directories left behind by deleted objects are not shown as keys.
if explicitDirProbe && !isKeyObject && !childEmitted && !cursor.isTruncated && entry.Attributes != nil {
entry.Attributes.Mime = s3_constants.FolderMimeType
eachEntryFn(dir, entry)
}
// println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
nextMarker = entry.Name + "/" + subNextMarker
if cursor.isTruncated {
return
}
if matchedPrefixDir {
return
}
// println("doListFilerEntries2 nextMarker", nextMarker)
} else {
eachEntryFn(dir, entry)
}
} else {
eachEntryFn(dir, entry)
// glog.V(4).Infof("List File Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
}
if cursor.prefixEndsOnDelimiter {
cursor.prefixEndsOnDelimiter = false
}
marker = lastEntryName
inclusiveStartFrom = false
}
// Versioned directories are processed above (lines 524-546)
return
}
func getListObjectsV2Args(values url.Values) (prefix, startAfter, delimiter string, token OptionalString, encodingTypeUrl bool, fetchOwner bool, maxkeys uint16, allowUnordered bool, errCode s3err.ErrorCode) {
@@ -1,7 +1,6 @@
package s3api
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -39,14 +38,14 @@ func TestDirectoryListedAsCommonPrefix(t *testing.T) {
var seenFiles []string
_, err := s3a.doListFilerEntries(
context.Background(),
client,
listDirectoryRequest{
dir: "/buckets/xoa-bucket/xo-vm-backups/data",
delimiter: "/", // should yield directory for CommonPrefix processing
bucket: "xoa-bucket",
},
"/buckets/xoa-bucket/xo-vm-backups/data",
"", // prefix
cursor,
"", // marker
"/", // delimiter="/" - should yield directory for CommonPrefix processing
false,
"xoa-bucket",
func(dir string, entry *filer_pb.Entry) {
if entry.IsDirectory {
seenDirs = append(seenDirs, entry.Name)
@@ -89,7 +88,7 @@ func TestEmptyDirectorySurfacedAsMarker(t *testing.T) {
// Mirrors the getFileStatus probe: prefix "logs/" with delimiter "/".
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var seen []*filer_pb.Entry
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "logs", delimiter: "/", bucket: "test"}, cursor,
_, err := s3a.doListFilerEntries(client, "/buckets/test", "logs", cursor, "", "/", false, "test",
func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry)
})
@@ -130,7 +129,7 @@ func TestNonEmptyDirectoryGetsNoPhantomMarker(t *testing.T) {
// Recursive listing under the "data/" prefix.
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var seen []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", prefix: "data", bucket: "test"}, cursor,
_, err := s3a.doListFilerEntries(client, "/buckets/test", "data", cursor, "", "", false, "test",
func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
@@ -174,7 +173,7 @@ func TestEmptyDirectoryHiddenInFlatListing(t *testing.T) {
// Plain flat listing: no prefix, no delimiter.
cursor := &ListingCursor{maxKeys: 1000}
var seen []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test", bucket: "test"}, cursor,
_, err := s3a.doListFilerEntries(client, "/buckets/test", "", cursor, "", "", false, "test",
func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
+10 -128
View File
@@ -44,7 +44,8 @@ type testFilerClient struct {
func (c *testFilerClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
entries := c.entriesByDir[in.Directory]
// Simplified mock: prefix "/" is treated as no filter for bucket root compatibility.
// Simplified mock: implements basic prefix filtering but ignores Limit, StartFromFileName, and InclusiveStartFrom
// to keep test logic focused. Prefix "/" is treated as no filter for bucket root compatibility.
if in.Prefix != "" && in.Prefix != "/" {
filtered := make([]*filer_pb.Entry, 0)
for _, e := range entries {
@@ -55,16 +56,7 @@ func (c *testFilerClient) ListEntries(ctx context.Context, in *filer_pb.ListEntr
entries = filtered
}
if in.StartFromFileName != "" {
filtered := make([]*filer_pb.Entry, 0)
for _, e := range entries {
if e.Name > in.StartFromFileName || (in.InclusiveStartFrom && e.Name == in.StartFromFileName) {
filtered = append(filtered, e)
}
}
entries = filtered
}
// Respect Limit
if in.Limit > 0 && int(in.Limit) < len(entries) {
entries = entries[:in.Limit]
}
@@ -308,7 +300,7 @@ func TestDoListFilerEntries_BucketRootPrefixSlashDelimiterSlash_ListsDirectories
cursor := &ListingCursor{maxKeys: 1000}
seen := make([]string, 0)
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", prefix: "/", delimiter: "/", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(client, "/buckets/test-bucket", "/", cursor, "", "/", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
if entry.IsDirectory {
seen = append(seen, entry.Name)
}
@@ -330,7 +322,7 @@ func TestDoListFilerEntries_ExclusiveStartSkipsMarkerEcho(t *testing.T) {
cursor := &ListingCursor{maxKeys: 1000}
var seen []string
nextMarker, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", marker: "test.txt", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
nextMarker, err := s3a.doListFilerEntries(client, "/buckets/test-bucket", "", cursor, "test.txt", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
@@ -354,7 +346,7 @@ func TestDoListFilerEntries_ExclusiveStartSkipsMarkerEchoWithSubsequentEntries(t
cursor := &ListingCursor{maxKeys: 1000}
var seen []string
nextMarker, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", marker: "test.txt", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
nextMarker, err := s3a.doListFilerEntries(client, "/buckets/test-bucket", "", cursor, "test.txt", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
seen = append(seen, entry.Name)
})
@@ -363,116 +355,6 @@ func TestDoListFilerEntries_ExclusiveStartSkipsMarkerEchoWithSubsequentEntries(t
assert.Equal(t, "zebra.txt", nextMarker)
}
func TestDoListFilerEntries_EmptyDirectoriesDoNotHideLaterEntries(t *testing.T) {
// With maxKeys=1 the listing window is 3 entries. The first window holds only
// empty directories, so the real object further down must still be found.
s3a := &S3ApiServer{}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test-bucket": {
{Name: "00-empty-1", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-2", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-3", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-4", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-5", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "zz-real", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/zz-real": {
{Name: "file.log", Attributes: &filer_pb.FuseAttributes{}},
},
},
}
cursor := &ListingCursor{maxKeys: 1}
var seen []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/zz-real/file.log"}, seen)
assert.False(t, cursor.isTruncated)
}
func TestDoListFilerEntries_EmptyDirectoriesInSubdirectoryDoNotHideSiblings(t *testing.T) {
// The recursion into "logs" gets its own listing window; empty subdirectories
// filling that window must not skip the object behind them.
s3a := &S3ApiServer{}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test-bucket": {
{Name: "logs", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/logs": {
{Name: "00-empty-1", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-2", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-3", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-4", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-5", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "zz.log", Attributes: &filer_pb.FuseAttributes{}},
},
},
}
cursor := &ListingCursor{maxKeys: 1}
var seen []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/logs/zz.log"}, seen)
assert.False(t, cursor.isTruncated)
}
func TestDoListFilerEntries_TruncationAcrossEmptyDirectories(t *testing.T) {
// Two real objects separated by empty directories: the first fills the quota
// and the listing must report truncation with a resumable marker.
s3a := &S3ApiServer{}
client := &testFilerClient{
entriesByDir: map[string][]*filer_pb.Entry{
"/buckets/test-bucket": {
{Name: "00-empty-1", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-2", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "00-empty-3", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "mm-real", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "pp-empty", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
{Name: "zz-real", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/mm-real": {
{Name: "file.log", Attributes: &filer_pb.FuseAttributes{}},
},
"/buckets/test-bucket/zz-real": {
{Name: "file.log", Attributes: &filer_pb.FuseAttributes{}},
},
},
}
cursor := &ListingCursor{maxKeys: 1}
var seen []string
nextMarker, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/mm-real/file.log"}, seen)
assert.True(t, cursor.isTruncated)
cursor = &ListingCursor{maxKeys: 1}
seen = nil
_, err = s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/test-bucket", marker: nextMarker, bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
seen = append(seen, dir+"/"+entry.Name)
cursor.maxKeys--
})
assert.NoError(t, err)
assert.Equal(t, []string{"/buckets/test-bucket/zz-real/file.log"}, seen)
assert.False(t, cursor.isTruncated)
}
func TestAllowUnorderedWithDelimiterValidation(t *testing.T) {
t.Run("should return error when allow-unordered=true and delimiter are both present", func(t *testing.T) {
// Create a request with both allow-unordered=true and delimiter
@@ -883,7 +765,7 @@ func TestListObjectsV2_Regression(t *testing.T) {
// Call doListFilerEntries directly to unit test listing logic in isolation,
// simulating parameters passed from listFilerEntries for prefix "reports/".
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/reports", prefix: "reports", bucket: "reports"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(client, "/buckets/reports", "reports", cursor, "", "", false, "reports", func(dir string, entry *filer_pb.Entry) {
if !entry.IsDirectory {
results = append(results, entry.Name)
}
@@ -921,7 +803,7 @@ func TestListObjectsV2_Regression_Sorting(t *testing.T) {
// Without the fix, Limit=1 would cause the lister to stop after "reports-archive",
// missing the intended "reports" directory.
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/reports", prefix: "reports", bucket: "reports"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(client, "/buckets/reports", "reports", cursor, "", "", false, "reports", func(dir string, entry *filer_pb.Entry) {
if !entry.IsDirectory {
results = append(results, entry.Name)
}
@@ -964,7 +846,7 @@ func TestListObjectsV2_PrefixEndingWithSlash_DoesNotMatchSiblings(t *testing.T)
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var results []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/bucket/path/to/list", prefix: "1", bucket: "bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(client, "/buckets/bucket/path/to/list", "1", cursor, "", "", false, "bucket", func(dir string, entry *filer_pb.Entry) {
if !entry.IsDirectory {
results = append(results, entry.Name)
}
@@ -996,7 +878,7 @@ func TestListObjectsV2_PrefixEndingWithSlash_WithDelimiter(t *testing.T) {
cursor := &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: true}
var results []string
_, err := s3a.doListFilerEntries(context.Background(), client, listDirectoryRequest{dir: "/buckets/bucket/path/to/list", prefix: "1", delimiter: "/", bucket: "bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(client, "/buckets/bucket/path/to/list", "1", cursor, "", "/", false, "bucket", func(dir string, entry *filer_pb.Entry) {
results = append(results, entry.Name)
})
@@ -136,7 +136,7 @@ func TestListObjectsWithVersionedObjects(t *testing.T) {
commonPrefixes := []PrefixEntry{}
bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, tt.bucket)
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: bucketPrefix[:len(bucketPrefix)-1], prefix: tt.prefix, delimiter: tt.delimiter, bucket: tt.bucket}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(filerClient, bucketPrefix[:len(bucketPrefix)-1], tt.prefix, cursor, "", tt.delimiter, false, tt.bucket, func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -237,7 +237,7 @@ func TestVersionedObjectsNoDuplication(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(1000)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -295,7 +295,7 @@ func TestVersionedObjectsWithDeleteMarker(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(1000)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -344,7 +344,7 @@ func TestVersionedObjectsMaxKeys(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(3)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(context.Background(), filerClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(filerClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -406,7 +406,7 @@ func TestVersionsDirectoryNotTraversed(t *testing.T) {
cursor := &ListingCursor{maxKeys: uint16(1000)}
contents := []ListEntry{}
_, err := s3a.doListFilerEntries(context.Background(), customClient, listDirectoryRequest{dir: "/buckets/test-bucket", bucket: "test-bucket"}, cursor, func(dir string, entry *filer_pb.Entry) {
_, err := s3a.doListFilerEntries(customClient, "/buckets/test-bucket", "", cursor, "", "", false, "test-bucket", func(dir string, entry *filer_pb.Entry) {
if cursor.maxKeys <= 0 {
return
}
@@ -111,9 +111,6 @@ func wormDeleteCondition(worm, bypass bool) *filer_pb.WriteCondition {
// rather than a dangling pointer) and deletes the version file. lock_key is the
// object (serializing the pointer recompute); for object-lock buckets the
// condition gates the delete on the version's WORM guards evaluated on the owner.
// Deleting the last version also removes the emptied .versions/ directory —
// leaving it behind would keep re-triggering the read path's self-heal rescans
// on every GET of the key (Veeam probes its deleted lock objects forever).
func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, bucket, object, versionId string, worm, bypass bool) s3err.ErrorCode {
if !isValidVersionID(versionId) {
return s3err.ErrInvalidRequest
@@ -128,7 +125,7 @@ func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, buck
Condition: cond,
Mutations: []*filer_pb.ObjectMutation{
s3a.latestPointerRecompute(bucket, object, isNewFormatVersionId(versionId), versionFileName, false),
{Type: filer_pb.ObjectMutation_DELETE, Directory: versionsPath, Name: versionFileName, IsDeleteData: true, RemoveEmptyParent: true},
{Type: filer_pb.ObjectMutation_DELETE, Directory: versionsPath, Name: versionFileName, IsDeleteData: true},
},
}
resp, err := s3a.objectTxnOnFiler(owner, req)
+7 -16
View File
@@ -1957,22 +1957,13 @@ func (s3a *S3ApiServer) healStaleLatestVersionPointer(bucket, normalizedObject s
}
if latestEntry == nil {
// No version remains: remove the residue directory outright so future
// reads take the clean ErrNotFound path instead of re-entering this
// self-heal (and its rescan + surfaced warning) on every request. The
// non-recursive rm makes this safe against a concurrent PUT — a new
// child fails the rm, and a directory removed just before that PUT's
// version file lands is recreated by the create's parent handling.
if rmErr := s3a.rm(bucketDir, versionsObjectPath, true, false); rmErr == nil {
versioningHealInfof("healed", "bucket=%s key=%s mode=empty_dir_removed", bucket, normalizedObject)
} else {
// Orphan entries (files in .versions/ that lack the version-id
// extended attribute) block the teardown and remain in place for an
// operator; fall back to clearing the stale pointer so reads at
// least short-circuit. From the S3 API perspective the object is
// correctly absent either way.
s3a.clearStaleLatestVersionPointer(bucket, normalizedObject, bucketDir, versionsObjectPath, versionsEntry, "healStaleLatestVersionPointer")
}
// Best-effort clear the stale latest-version pointer so subsequent
// reads short-circuit to ErrNotFound directly instead of replaying
// getLatestObjectVersion's read-retry loop and re-entering self-heal
// on every request. Orphan entries (files in .versions/ that lack
// the version-id extended attribute) remain in place; from the S3
// API perspective the object is correctly absent.
s3a.clearStaleLatestVersionPointer(bucket, normalizedObject, bucketDir, versionsObjectPath, versionsEntry, "healStaleLatestVersionPointer")
// Wrap filer_pb.ErrNotFound so callers can distinguish genuine
// object-absence (nothing left to promote) from scan failures
// (I/O errors during list) via errors.Is.
+3 -15
View File
@@ -9,7 +9,6 @@ import (
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
@@ -392,21 +391,10 @@ func (fs *FilerServer) applyObjectMutation(ctx context.Context, m *filer_pb.Obje
case filer_pb.ObjectMutation_DELETE:
fullpath := util.NewFullPath(m.Directory, m.Name)
err := fs.filer.DeleteEntryMetaAndData(ctx, fullpath, m.IsRecursive, false, m.IsDeleteData, fromOtherCluster, signatures, 0)
if err != nil && err != filer_pb.ErrNotFound {
return err
if err == filer_pb.ErrNotFound {
return nil
}
if m.RemoveEmptyParent {
// A parent that exists only to hold this child (e.g. a .versions/
// directory losing its last version) is torn down in the same locked
// transaction. Best-effort: a non-empty or already-removed parent is
// the expected no-op, and a failed teardown must not fail the
// already-applied delete.
parentErr := fs.filer.DeleteEntryMetaAndData(ctx, util.FullPath(m.Directory), false, false, false, fromOtherCluster, signatures, 0)
if parentErr != nil && parentErr != filer_pb.ErrNotFound && !strings.Contains(parentErr.Error(), filer.MsgFailDelNonEmptyFolder) {
glog.V(1).InfofCtx(ctx, "remove empty parent %s: %v", m.Directory, parentErr)
}
}
return nil
return err
case filer_pb.ObjectMutation_PATCH_EXTENDED:
fullpath := util.NewFullPath(m.Directory, m.Name)
@@ -619,86 +619,6 @@ func TestObjectTransactionVersionDeleteWithWorm(t *testing.T) {
}
}
// Deleting the LAST version tears down the emptied .versions/ directory in the
// same transaction (remove_empty_parent on the DELETE), so a fully-drained key
// leaves no residue to re-trigger the read path's self-heal on every GET. A
// remaining child keeps the directory; a replay after the child is already
// gone still tidies it.
func TestObjectTransactionDeleteRemovesEmptyParent(t *testing.T) {
now := time.Unix(1700000000, 0)
seed := func(withSibling bool) map[string]*filer.Entry {
entries := map[string]*filer.Entry{
"/buckets/b/obj/.versions": {
Attr: filer.Attr{Inode: 2, Mtime: now, Crtime: now, Mode: 0755 | (1 << 31)},
Extended: map[string][]byte{"latestName": []byte("v_a"), "latestVid": []byte("v1")},
},
"/buckets/b/obj/.versions/v_a": {
Attr: filer.Attr{Inode: 10, Mtime: now, Crtime: now, Mode: 0644},
Extended: map[string][]byte{"vid": []byte("v1")},
},
}
if withSibling {
entries["/buckets/b/obj/.versions/orphan"] = &filer.Entry{
Attr: filer.Attr{Inode: 11, Mtime: now, Crtime: now, Mode: 0644},
}
}
return entries
}
// Mirrors routedDeleteSpecificVersion: repoint excluding the dying version,
// then delete it and tidy the parent.
mkReq := func() *filer_pb.ObjectTransactionRequest {
return &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/b/obj",
Mutations: []*filer_pb.ObjectMutation{
{Type: filer_pb.ObjectMutation_RECOMPUTE_LATEST, Directory: "/buckets/b/obj", Name: ".versions",
Recompute: &filer_pb.Recompute{ScanDir: "/buckets/b/obj/.versions", Descending: true, ExcludeName: "v_a",
NameToKey: "latestName", CopyExtended: map[string]string{"latestVid": "vid"}}},
{Type: filer_pb.ObjectMutation_DELETE, Directory: "/buckets/b/obj/.versions", Name: "v_a", RemoveEmptyParent: true},
},
}
}
// Last version: the emptied directory goes with it.
fs, store := newTxnTestServer(seed(false))
resp, err := fs.ObjectTransaction(context.Background(), mkReq())
if err != nil || resp.Error != "" {
t.Fatalf("txn failed: err=%v resp=%q", err, resp.Error)
}
if _, ok := store.entries["/buckets/b/obj/.versions/v_a"]; ok {
t.Errorf("version should be deleted")
}
if _, ok := store.entries["/buckets/b/obj/.versions"]; ok {
t.Errorf(".versions directory emptied by the delete should be removed")
}
// A remaining child keeps the directory (non-recursive teardown declines).
fs, store = newTxnTestServer(seed(true))
resp, err = fs.ObjectTransaction(context.Background(), mkReq())
if err != nil || resp.Error != "" {
t.Fatalf("txn failed: err=%v resp=%q", err, resp.Error)
}
if _, ok := store.entries["/buckets/b/obj/.versions/orphan"]; !ok {
t.Errorf("sibling must survive the teardown attempt")
}
if _, ok := store.entries["/buckets/b/obj/.versions"]; !ok {
t.Errorf(".versions directory with a remaining child must not be removed")
}
// Replay: the child is already gone, the empty parent is still tidied.
fs, store = newTxnTestServer(map[string]*filer.Entry{
"/buckets/b/obj/.versions": {
Attr: filer.Attr{Inode: 2, Mtime: now, Crtime: now, Mode: 0755 | (1 << 31)},
},
})
resp, err = fs.ObjectTransaction(context.Background(), mkReq())
if err != nil || resp.Error != "" {
t.Fatalf("replay txn failed: err=%v resp=%q", err, resp.Error)
}
if _, ok := store.entries["/buckets/b/obj/.versions"]; ok {
t.Errorf("replayed delete should still remove the empty directory")
}
}
// PATCH_EXTENDED with touch_mtime bumps the entry's Mtime (a metadata-replace
// copy) while merging Extended.
func TestObjectTransactionPatchTouchMtime(t *testing.T) {
+6 -7
View File
@@ -85,10 +85,10 @@ func (vs *VolumeServer) VolumeTierMoveDatFromRemote(req *volume_server_pb.Volume
}
// Trim the remote file reference and persist the .vif (util.WriteFile fsyncs it)
// BEFORE deleting the remote object. After this the .vif no longer references the
// remote object, so a crash before DeleteFile merely leaks the remote object while
// the volume reloads its local .dat as non-remote. The volume must NEVER be left
// with a .vif referencing the remote object while that object is deleted.
// BEFORE deleting the remote object. After this point hasRemoteFile is false, so a
// crash before DeleteFile merely leaks the remote object while the volume reloads
// its local .dat. The volume must NEVER be left with a .vif referencing the remote
// object while that object is deleted.
v.GetVolumeInfo().Files = v.GetVolumeInfo().Files[1:]
if err := v.SaveVolumeInfo(); err != nil {
return fmt.Errorf("volume %d failed to save remote file info: %v", v.Id, err)
@@ -127,9 +127,8 @@ func swapToLocalDatBackend(v *storage.Volume, datFileName string) error {
return err
}
// Swap under the volume's data lock so concurrent reads never see a closed
// or half-swapped backend, clearing hasRemoteFile in the same step since the
// volume now serves from the local .dat.
v.SwapDataBackend(backend.NewDiskFile(dataFile), false)
// or half-swapped backend.
v.SwapDataBackend(backend.NewDiskFile(dataFile))
return nil
}
+3 -11
View File
@@ -121,8 +121,8 @@ func (f *tierTestBackendFile) ReadAt(p []byte, off int64) (int, error) {
func (f *tierTestBackendFile) WriteAt(p []byte, off int64) (int, error) { panic("not implemented") }
func (f *tierTestBackendFile) Truncate(off int64) error { panic("not implemented") }
func (f *tierTestBackendFile) Close() error { return nil }
func (f *tierTestBackendFile) Name() string { return f.key }
func (f *tierTestBackendFile) Sync() error { return nil }
func (f *tierTestBackendFile) Name() string { return f.key }
func (f *tierTestBackendFile) Sync() error { return nil }
func (f *tierTestBackendFile) GetStat() (int64, time.Time, error) {
files := f.tierInfo.GetFiles()
if len(files) == 0 {
@@ -136,9 +136,7 @@ type fakeTierStream struct {
grpc.ServerStream
}
func (s *fakeTierStream) Send(*volume_server_pb.VolumeTierMoveDatFromRemoteResponse) error {
return nil
}
func (s *fakeTierStream) Send(*volume_server_pb.VolumeTierMoveDatFromRemoteResponse) error { return nil }
func newTierTestStore(t *testing.T, dir string) *storage.Store {
t.Helper()
@@ -278,12 +276,6 @@ func TestTierMoveDatFromRemote_KeepRemote_LeavesReplicaLocal(t *testing.T) {
if _, ok := v.DataBackend.(*backend.DiskFile); !ok {
t.Fatalf("after keep-remote download the data backend must be local DiskFile, got %T", v.DataBackend)
}
// The live volume must also report non-remote immediately, without waiting for
// a remount: a delete arriving before the remount would otherwise skip the .dat
// tombstone, and the phantom-.dat guard would stay disabled.
if v.HasRemoteFile() {
t.Fatal("after download the live volume must no longer be remote-backed")
}
// Remount and confirm the volume is no longer remote-backed and reads come
// from the local .dat (matching the bytes uploaded before tiering).
+3 -4
View File
@@ -64,15 +64,14 @@ func (c *commandS3BucketList) Do(args []string, commandEnv *CommandEnv, writer i
return nil
}
collection := getCollectionName(commandEnv, entry.Name)
var collectionSize, logicalSize, fileCount float64
var collectionSize, fileCount float64
if collectionInfo, found := collectionInfos[collection]; found {
collectionSize = collectionInfo.Size
logicalSize = collectionInfo.LogicalSize()
fileCount = collectionInfo.FileCount - collectionInfo.DeleteCount
}
fmt.Fprintf(writer, " %s\tsize:%.0f\tlogical:%.0f\tchunk:%.0f", entry.Name, collectionSize, logicalSize, fileCount)
fmt.Fprintf(writer, " %s\tsize:%.0f\tchunk:%.0f", entry.Name, collectionSize, fileCount)
if entry.Quota > 0 {
fmt.Fprintf(writer, "\tquota:%d\tusage:%.2f%%", entry.Quota, logicalSize*100/float64(entry.Quota))
fmt.Fprintf(writer, "\tquota:%d\tusage:%.2f%%", entry.Quota, float64(collectionSize)*100/float64(entry.Quota))
}
// Show bucket owner (use %q to escape special characters)
if entry.Extended != nil {
+6 -47
View File
@@ -2,7 +2,6 @@ package shell
import (
"context"
"errors"
"flag"
"fmt"
"io"
@@ -39,8 +38,6 @@ func (c *commandS3VersionsAudit) Help() string {
Veeam/etc. as "Storage not found" on the next GET
- orphan (directory has files lacking the version-id extended attr,
which the post-delete cleanup path will refuse to rm)
- empty (no pointer and no children — residue of a fully-drained key;
every GET of the key replays the read-side self-heal rescan)
Example:
# Audit a whole bucket
@@ -55,10 +52,9 @@ func (c *commandS3VersionsAudit) Help() string {
s3.versions.audit -prefix /buckets/mybucket -heal
This command is read-only by default. With -heal, it clears the stale
latest-version pointer on stranded directories and removes empty ones;
the blob is already gone, so reads then return NoSuchKey via the
clean-miss path instead of replaying the 10-retry self-heal loop on
every request.
latest-version pointer on stranded directories; the blob is already
gone, so reads then return NoSuchKey via the clean-miss path instead
of replaying the 10-retry self-heal loop on every request.
`
}
@@ -85,7 +81,6 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
clean uint64
stranded uint64
orphanOnly uint64
empty uint64
healed uint64
healFailed uint64
)
@@ -122,7 +117,6 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
versionsPath := string(parentPath) + "/" + entry.Name
pointerSeen := false
hasOrphan := false
hasChild := false
const auditPageSize = 1024
var startName string
for {
@@ -134,7 +128,6 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
}
pageEntries++
lastEntryName = child.Name
hasChild = true
hasVersionId := false
if child.Extended != nil {
if _, ok := child.Extended[s3_constants.ExtVersionIdKey]; ok {
@@ -161,26 +154,12 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
switch {
case pointerFile == "":
// No pointer set. Empty, orphan-only and clean are mutually
// No pointer set. Orphan-only and clean are now mutually
// exclusive so the final report's category counts sum to
// versionsDirs.
switch {
case !hasChild:
atomic.AddUint64(&empty, 1)
if *verbose {
fmt.Fprintf(writer, "empty: %s\n", versionsPath)
}
if *doHeal {
if err := removeEmptyVersionsDir(ctx, client, parentPath, entry); err != nil {
atomic.AddUint64(&healFailed, 1)
fmt.Fprintf(writer, "heal failed: %s: %v\n", versionsPath, err)
} else {
atomic.AddUint64(&healed, 1)
}
}
case hasOrphan:
if hasOrphan {
atomic.AddUint64(&orphanOnly, 1)
default:
} else {
atomic.AddUint64(&clean, 1)
}
case pointerSeen:
@@ -211,7 +190,6 @@ func (c *commandS3VersionsAudit) Do(args []string, commandEnv *CommandEnv, write
fmt.Fprintf(writer, " clean : %d\n", clean)
fmt.Fprintf(writer, " stranded : %d\n", stranded)
fmt.Fprintf(writer, " orphan-only : %d\n", orphanOnly)
fmt.Fprintf(writer, " empty : %d\n", empty)
if *doHeal {
fmt.Fprintf(writer, " healed : %d\n", healed)
fmt.Fprintf(writer, " heal failed : %d\n", healFailed)
@@ -244,25 +222,6 @@ func healStrandedPointer(ctx context.Context, client filer_pb.SeaweedFilerClient
return err
}
// removeEmptyVersionsDir deletes a .versions/ directory that holds no
// children: residue of a fully-drained key. Non-recursive on purpose so a
// concurrent write landing a new version fails the delete instead of being
// lost with it.
func removeEmptyVersionsDir(ctx context.Context, client filer_pb.SeaweedFilerClient, parentPath util.FullPath, entry *filer_pb.Entry) error {
resp, err := client.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{
Directory: string(parentPath),
Name: entry.Name,
IsDeleteData: true,
})
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
return nil
}
// filerClientWrapper adapts a raw SeaweedFilerClient to the
// filer_pb.FilerClient interface that List / TraverseBfs expect.
type filerClientWrapper struct {
+24 -41
View File
@@ -71,12 +71,11 @@ func (c *commandVolumeBalance) Help() string {
sizes are handled correctly. Set it to 0 (or >=100) to disable. Servers running an older build that does
not report disk bytes are not gated, and balancing falls back to slot-only behavior for them.
The -byDiskUsage flag ranks servers by their reported physical disk used percentage instead of the
default slot-density metric. If any server does not report physical disk bytes (older build), ranking
falls back to the sum of volume sizes for all servers, since the two scales are not comparable. The
default metric normalizes by maxVolumeCount, so a server whose maxVolumeCount is configured too high
for its disk looks nearly empty even when its disk is physically full, and balancing can drain
less-full servers onto it. Use -byDiskUsage to balance actual disk usage instead.
The -byDiskUsage flag ranks servers by the actual data they hold (sum of volume sizes) instead of the
default slot-density metric. The default metric normalizes by maxVolumeCount, so a server whose
maxVolumeCount is configured too high for its disk looks nearly empty even when its disk is physically
full, and balancing can drain less-full servers onto it. Use -byDiskUsage to balance actual data
distribution instead. It assumes comparable disk sizes across servers of the same disk type.
Algorithm:
@@ -130,7 +129,7 @@ func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer
// TODO: remove this alias
applyBalancingAlias := balanceCommand.Bool("force", false, "apply the balancing plan (alias for -apply)")
volumesPerExec := balanceCommand.Int("volumesPerExec", 0, "how many volumes to move in one run (default is 0 for unlimited)")
byDiskUsage := balanceCommand.Bool("byDiskUsage", false, "rank servers by reported physical disk used percent instead of slot density; falls back to sum of volume sizes for all servers when any server does not report disk bytes. Use when maxVolumeCount is set too high for the disk.")
byDiskUsage := balanceCommand.Bool("byDiskUsage", false, "rank servers by actual data held (sum of volume sizes) instead of slot density; use when maxVolumeCount is set too high for the disk. Assumes comparable disk sizes per disk type.")
maxDiskUsagePercent := balanceCommand.Int("maxDiskUsagePercent", balancer.DefaultMaxDiskUsagePercent, "skip a move target whose physical disk used%% is at/above this; judged per server against its own disk, so heterogeneous disk sizes are fine. 0 or >=100 disables. Auto-skipped for servers that do not report disk bytes.")
balanceCommand.Func("volumeBy", "only apply the balancing for ALL volumes and ACTIVE or FULL", func(flagValue string) error {
@@ -340,45 +339,29 @@ func capacityByMinVolumeDensity(diskType types.DiskType, volumeSizeLimitMb uint6
}
}
// capacityByDiskUsage ranks servers by reported physical disk used percentage.
// This makes a physically full disk rank as a move source, even if the regular
// SeaweedFS volumes in topology do not make it look like the largest data holder.
// The percent scale is only comparable when every server reports disk bytes, so
// if any node lacks DiskTotalBytes (older build), all nodes fall back to the
// previous ranking by summed volume sizes with a uniform capacity: mixing the two
// scales would rank non-reporting servers as orders of magnitude fuller, and
// normalizing the fallback by MaxVolumeCount instead would reintroduce the
// over-configured-maxVolumeCount distortion this flag exists to avoid.
func capacityByDiskUsage(diskType types.DiskType, volumeSizeLimitMb uint64, nodes []*Node) DensityFunc {
if volumeSizeLimitMb == 0 {
volumeSizeLimitMb = util.VolumeSizeLimitGB * util.KiByte
}
volumeSizeLimitBytes := volumeSizeLimitMb * util.MiByte
allReportDiskBytes := true
for _, n := range nodes {
if diskInfo, found := n.info.DiskInfos[string(diskType)]; found && diskInfo != nil && diskInfo.DiskTotalBytes == 0 {
allReportDiskBytes = false
break
}
}
// capacityByActualDataUsage ranks servers purely by how much actual data they
// hold (sum of volume sizes), ignoring MaxVolumeCount. The slot-density metric
// divides by MaxVolumeCount, so a server whose MaxVolumeCount was configured too
// high for its disk looks nearly empty even when its disk is physically full and
// gets picked as a move target. This function keeps the fullest-by-data server
// ranked as full so balancing drains it instead of piling onto it. It assumes
// comparable disk sizes across servers of the same disk type. Capacity is a
// uniform constant so the density ratio is proportional to actual data; the
// constant cancels out of every ratio comparison in balanceSelectedVolume.
func capacityByActualDataUsage(diskType types.DiskType, volumeSizeLimitMb uint64) DensityFunc {
return func(info *master_pb.DataNodeInfo) (float64, uint64) {
diskInfo, found := info.DiskInfos[string(diskType)]
if !found || diskInfo == nil {
return 0, 0
}
if allReportDiskBytes && diskInfo.DiskTotalBytes > 0 {
usedBytes := uint64(0)
if diskInfo.DiskFreeBytes < diskInfo.DiskTotalBytes {
usedBytes = diskInfo.DiskTotalBytes - diskInfo.DiskFreeBytes
}
return float64(diskInfo.DiskTotalBytes) / float64(volumeSizeLimitBytes),
balancer.UsedVolumeEquivalents(usedBytes, volumeSizeLimitBytes)
}
var volumeSizes uint64
for _, volumeInfo := range diskInfo.VolumeInfos {
volumeSizes += volumeInfo.Size
}
return 1, balancer.UsedVolumeEquivalents(volumeSizes, volumeSizeLimitBytes)
if volumeSizeLimitMb == 0 {
volumeSizeLimitMb = util.VolumeSizeLimitGB * util.KiByte
}
return 1, balancer.UsedVolumeEquivalents(volumeSizes, volumeSizeLimitMb*util.MiByte)
}
}
@@ -503,7 +486,7 @@ func (c *commandVolumeBalance) balanceSelectedVolume(diskType types.DiskType, vo
}
capacityFunc := capacityByMinVolumeDensity(diskType, volumeSizeLimitMb)
if c.byDiskUsage {
capacityFunc = capacityByDiskUsage(diskType, volumeSizeLimitMb, nodes)
capacityFunc = capacityByActualDataUsage(diskType, volumeSizeLimitMb)
}
for _, dn := range nodes {
capacity, volumeCount := capacityFunc(dn.info)
@@ -561,9 +544,9 @@ func (c *commandVolumeBalance) balanceSelectedVolume(diskType types.DiskType, vo
}
sortCandidatesFn(candidateVolumes)
for _, emptyNode := range nodesWithCapacity[:fullNodeIndex] {
// In byte-usage mode the ranking ignores volume slots, so skip targets
// that are already at MaxVolumeCount so balancing never exceeds the
// slot limit.
// In byte-usage mode capacity is a uniform constant, so a target's
// free volume slots aren't reflected in its ranking; skip targets that
// are already at MaxVolumeCount so balancing never exceeds the slot limit.
if c.byDiskUsage && !emptyNode.hasFreeVolumeSlot(diskType) {
continue
}
-62
View File
@@ -444,68 +444,6 @@ func TestBalanceByDiskUsage(t *testing.T) {
}
}
// When volume servers report physical disk bytes, -byDiskUsage should use the
// filesystem fullness as the source ranking. This covers the production-shaped
// case where a 99%-used disk does not have the largest sum of regular
// VolumeInfos, so ranking by volume bytes alone drains the wrong server.
func TestBalanceByDiskUsageUsesPhysicalDiskUsageWhenReported(t *testing.T) {
const gb = 1024 * 1024 * 1024
volumeSizeLimitMb := uint64(1024)
physicalFull := makeByteNode("physical-full", 2000, 1000*gb, 10*gb, mkByteVolumes(1, 5, 1000)) // 99% used
dataHeavy := makeByteNode("data-heavy", 2000, 1000*gb, 530*gb, mkByteVolumes(101, 20, 1000)) // 47% used, more volume bytes
target := makeByteNode("target", 2000, 1000*gb, 900*gb, mkByteVolumes(201, 1, 1000)) // 10% used
beforePhysicalFull := volCount(physicalFull)
beforeDataHeavy := volCount(dataHeavy)
beforeTarget := volCount(target)
c := &commandVolumeBalance{
volumeSizeLimitMb: volumeSizeLimitMb,
byDiskUsage: true,
diskUsageHighWaterPercent: 90,
}
runBalance(t, c, []*Node{physicalFull, dataHeavy, target})
if got := volCount(physicalFull); got >= beforePhysicalFull {
t.Fatalf("-byDiskUsage should drain the physically fullest server, got %d volumes (was %d)", got, beforePhysicalFull)
}
if got := volCount(dataHeavy); got != beforeDataHeavy {
t.Fatalf("-byDiskUsage should not drain the lower physical-usage data-heavy server first, got %d volumes (was %d)", got, beforeDataHeavy)
}
if got := volCount(target); got <= beforeTarget {
t.Fatalf("expected the low-usage target to receive volumes, got %d volumes (was %d)", got, beforeTarget)
}
}
// A fleet where only some servers report physical disk bytes must not mix the
// percent scale with the volume-bytes scale: a non-reporting server's ratio is
// whole volume-equivalents while reporting servers stay below 1.0, so the
// balancer would drain a nearly empty old-build server onto physically fuller
// ones. With mixed reporting, ranking falls back to data size for everyone.
func TestBalanceByDiskUsageMixedReportingFallsBackToDataSize(t *testing.T) {
const gb = 1024 * 1024 * 1024
oldEmpty := makeByteNode("old-empty", 2000, 0, 0, mkByteVolumes(1, 2, 1000)) // no disk bytes reported
newFull := makeByteNode("new-full", 2000, 1000*gb, 500*gb, mkByteVolumes(101, 20, 1000))
newTarget := makeByteNode("new-target", 2000, 1000*gb, 990*gb, mkByteVolumes(201, 1, 1000))
beforeOldEmpty := volCount(oldEmpty)
beforeNewFull := volCount(newFull)
c := &commandVolumeBalance{
volumeSizeLimitMb: 1024,
byDiskUsage: true,
diskUsageHighWaterPercent: 90,
}
runBalance(t, c, []*Node{oldEmpty, newFull, newTarget})
if got := volCount(oldEmpty); got < beforeOldEmpty {
t.Fatalf("the nearly empty non-reporting server should not be drained, got %d volumes (was %d)", got, beforeOldEmpty)
}
if got := volCount(newFull); got >= beforeNewFull {
t.Fatalf("the data-heavy server should drain under the fallback ranking, got %d volumes (was %d)", got, beforeNewFull)
}
}
// makeByteNode builds a single-disk Node carrying physical disk bytes, for the
// disk-fullness gate tests.
func makeByteNode(id string, maxVolumeCount int64, totalBytes, freeBytes uint64, volumes []*master_pb.VolumeInformationMessage) *Node {
+170 -158
View File
@@ -6,7 +6,6 @@ import (
"io"
"strconv"
"strings"
"sync"
"time"
"slices"
@@ -50,10 +49,8 @@ func (c *commandVolumeFixReplication) Help() string {
Note:
* each time this will only add back one replica for each volume id that is under replicated.
If there are multiple replicas are missing, e.g. replica count is > 2, you may need to run this multiple times.
* do not run this too quickly within seconds, since the new volume replica may take a few seconds
* do not run this too quickly within seconds, since the new volume replica may take a few seconds
to register itself to the master.
* under-replicated volumes are copied up to -maxParallelization at a time, with at most
-maxParallelizationPerServer concurrent copies onto any single destination server.
`
}
@@ -73,7 +70,6 @@ func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv,
doDelete := volFixReplicationCommand.Bool("doDelete", true, "Also delete over-replicated volumes besides fixing under-replication")
doCheck := volFixReplicationCommand.Bool("doCheck", true, "Also check synchronization before deleting")
maxParallelization := volFixReplicationCommand.Int("maxParallelization", DefaultMaxParallelization, "run up to X tasks in parallel, whenever possible")
maxParallelizationPerServer := volFixReplicationCommand.Int("maxParallelizationPerServer", 1, "run up to X volume copies onto the same destination server in parallel")
retryCount := volFixReplicationCommand.Int("retry", 5, "how many times to retry")
volumesPerStep := volFixReplicationCommand.Int("volumesPerStep", 0, "how many volumes to fix in one cycle")
@@ -158,7 +154,7 @@ func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv,
ewg.Reset()
ewg.Add(func() error {
// find the most underpopulated data nodes
fixedVolumeReplicas, err = c.fixUnderReplicatedVolumes(commandEnv, writer, *applyChanges, underReplicatedVolumeIds, volumeReplicas, allLocations, *retryCount, *volumesPerStep, *maxParallelization, *maxParallelizationPerServer)
fixedVolumeReplicas, err = c.fixUnderReplicatedVolumes(commandEnv, writer, *applyChanges, underReplicatedVolumeIds, volumeReplicas, allLocations, *retryCount, *volumesPerStep)
return err
})
if *doDelete {
@@ -340,7 +336,7 @@ func (c *commandVolumeFixReplication) deleteOneVolume(commandEnv *CommandEnv, wr
return nil
}
func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, retryCount int, volumesPerStep int, maxParallelization int, maxParallelizationPerServer int) (fixedVolumes map[string]int, err error) {
func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location, retryCount int, volumesPerStep int) (fixedVolumes map[string]int, err error) {
fixedVolumes = map[string]int{}
if len(volumeIds) == 0 {
@@ -350,137 +346,61 @@ func (c *commandVolumeFixReplication) fixUnderReplicatedVolumes(commandEnv *Comm
if len(volumeIds) > volumesPerStep && volumesPerStep > 0 {
volumeIds = volumeIds[0:volumesPerStep]
}
// own a private copy of the locations list: the scheduler re-sorts it on
// every reservation, and the caller's slice is shared with the concurrent
// delete phases
allLocations = slices.Clone(allLocations)
scheduler := newVolumeCopyScheduler(maxParallelizationPerServer)
var fixedVolumesMu sync.Mutex
ewg := NewErrorWaitGroup(maxParallelization)
for _, vid := range volumeIds {
ewg.Add(func() error {
for i := 0; i < retryCount+1; i++ {
if copied, err := c.fixOneUnderReplicatedVolume(commandEnv, writer, applyChanges, volumeReplicas, vid, allLocations, scheduler); err == nil {
if applyChanges && copied {
fixedVolumesMu.Lock()
fixedVolumes[strconv.FormatUint(uint64(vid), 10)] = len(volumeReplicas[vid])
fixedVolumesMu.Unlock()
}
break
} else {
fmt.Fprintf(writer, "fixing under replicated volume %d: %v\n", vid, err)
for i := 0; i < retryCount+1; i++ {
var copied bool
if copied, err = c.fixOneUnderReplicatedVolume(commandEnv, writer, applyChanges, volumeReplicas, vid, allLocations); err == nil {
if applyChanges && copied {
fixedVolumes[strconv.FormatUint(uint64(vid), 10)] = len(volumeReplicas[vid])
}
break
} else {
fmt.Fprintf(writer, "fixing under replicated volume %d: %v\n", vid, err)
}
return nil
})
}
return fixedVolumes, ewg.Wait()
}
// volumeCopyScheduler serializes destination selection for concurrent volume
// copies: selection and free-slot accounting are atomic so parallel fixes see
// each other's reservations, and the per-server cap keeps many simultaneous
// copies from swamping one destination's disks.
type volumeCopyScheduler struct {
mu sync.Mutex
cond *sync.Cond
inflight map[string]int // destination dataNode.Id -> copies in flight
maxPerServer int
}
func newVolumeCopyScheduler(maxPerServer int) *volumeCopyScheduler {
if maxPerServer <= 0 {
maxPerServer = 1
}
s := &volumeCopyScheduler{
inflight: make(map[string]int),
maxPerServer: maxPerServer,
}
s.cond = sync.NewCond(&s.mu)
return s
}
// reserveTarget picks the emptiest data node satisfying the replica placement
// and reserves a volume slot on it. When every eligible destination is at the
// per-server copy cap it waits for a copy to finish instead of failing.
// Returns nil only when no data node can accept the replica at all. With
// countInflight=false (simulation) the slot is reserved but no copy is
// counted in flight.
func (s *volumeCopyScheduler) reserveTarget(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica, allLocations []location, diskType string, countInflight bool) *location {
s.mu.Lock()
defer s.mu.Unlock()
fn := capacityByFreeVolumeCount(types.ToDiskType(diskType))
for {
keepDataNodesSorted(allLocations, types.ToDiskType(diskType))
eligibleButBusy := false
for _, dst := range allLocations {
// check whether data nodes satisfy the constraints
if fn(dst.dataNode) <= 0 || !satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
continue
}
if countInflight && s.inflight[dst.dataNode.Id] >= s.maxPerServer {
eligibleButBusy = true
continue
}
addVolumeCount(dst.dataNode.DiskInfos[diskType], 1)
if countInflight {
s.inflight[dst.dataNode.Id]++
}
return &dst
}
if !eligibleButBusy {
return nil
}
s.cond.Wait()
}
return fixedVolumes, nil
}
// releaseTarget ends a copy counted by reserveTarget. A failed copy also
// returns the reserved volume slot, so retries do not drain the topology's
// free-slot accounting.
func (s *volumeCopyScheduler) releaseTarget(dst *location, diskType string, copied bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.inflight[dst.dataNode.Id]--
if s.inflight[dst.dataNode.Id] <= 0 {
delete(s.inflight, dst.dataNode.Id)
}
if !copied {
addVolumeCount(dst.dataNode.DiskInfos[diskType], -1)
}
s.cond.Broadcast()
}
func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeReplicas map[uint32][]*VolumeReplica, vid uint32, allLocations []location, scheduler *volumeCopyScheduler) (bool, error) {
func (c *commandVolumeFixReplication) fixOneUnderReplicatedVolume(commandEnv *CommandEnv, writer io.Writer, applyChanges bool, volumeReplicas map[uint32][]*VolumeReplica, vid uint32, allLocations []location) (bool, error) {
replicas := volumeReplicas[vid]
replica := pickOneReplicaToCopyFrom(replicas)
replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(replica.info.ReplicaPlacement))
foundNewLocation := false
keepDataNodesSorted(allLocations, types.ToDiskType(replica.info.DiskType))
fn := capacityByFreeVolumeCount(types.ToDiskType(replica.info.DiskType))
for _, dst := range allLocations {
// check whether data nodes satisfy the constraints
if fn(dst.dataNode) > 0 && satisfyReplicaPlacement(replicaPlacement, replicas, dst) {
// ask the volume server to replicate the volume
foundNewLocation = true
fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
dst := scheduler.reserveTarget(replicaPlacement, replicas, allLocations, replica.info.DiskType, applyChanges)
if dst == nil {
if !applyChanges {
// adjust volume count
addVolumeCount(dst.dataNode.DiskInfos[replica.info.DiskType], 1)
return true, nil
}
err := replicateVolumeToServer(commandEnv.option.GrpcDialOption, writer, needle.VolumeId(replica.info.Id),
pb.NewServerAddressFromDataNode(replica.location.dataNode),
pb.NewServerAddressFromDataNode(dst.dataNode),
replica.info.DiskType)
if err != nil {
return false, err
}
// adjust volume count
addVolumeCount(dst.dataNode.DiskInfos[replica.info.DiskType], 1)
return true, nil
}
}
if !foundNewLocation {
fmt.Fprintf(writer, "failed to place volume %d replica as %s, existing:%+v\n", replica.info.Id, replicaPlacement, len(replicas))
return false, nil
}
// ask the volume server to replicate the volume
fmt.Fprintf(writer, "replicating volume %d %s from %s to dataNode %s ...\n", replica.info.Id, replicaPlacement, replica.location.dataNode.Id, dst.dataNode.Id)
if !applyChanges {
return true, nil
}
err := replicateVolumeToServer(commandEnv.option.GrpcDialOption, writer, needle.VolumeId(replica.info.Id),
pb.NewServerAddressFromDataNode(replica.location.dataNode),
pb.NewServerAddressFromDataNode(dst.dataNode),
replica.info.DiskType)
scheduler.releaseTarget(dst, replica.info.DiskType, err == nil)
if err != nil {
return false, err
}
return true, nil
return false, nil
}
func addVolumeCount(info *master_pb.DiskInfo, count int) {
@@ -499,11 +419,24 @@ func keepDataNodesSorted(dataNodes []location, diskType types.DiskType) {
}
func satisfyReplicaCurrentLocation(replicaPlacement *super_block.ReplicaPlacement, replicas []*VolumeReplica) bool {
locs := make([]balancer.Location, len(replicas))
for i, r := range replicas {
locs[i] = toBalancerLocation(r.location)
existingDataCenters, existingRacks, _ := countReplicas(replicas)
if replicaPlacement.DiffDataCenterCount+1 > len(existingDataCenters) {
return false
}
return balancer.SatisfyReplicaCurrentLocation(replicaPlacement, locs)
if replicaPlacement.DiffRackCount+1 > len(existingRacks) {
return false
}
if replicaPlacement.SameRackCount > 0 {
foundSatisfyRack := false
for _, rackCount := range existingRacks {
if rackCount >= replicaPlacement.SameRackCount+1 {
foundSatisfyRack = true
}
}
return foundSatisfyRack
}
return true
}
/*
@@ -585,50 +518,129 @@ func (l location) DataCenter() string {
return l.dc
}
// toBalancerReplicas adapts shell replicas to the shared selection shape in
// weed/topology/balancer; selection results come back as indices into the
// same slice.
func toBalancerReplicas(replicas []*VolumeReplica) []balancer.Replica {
out := make([]balancer.Replica, len(replicas))
for i, r := range replicas {
out[i] = balancer.Replica{Location: toBalancerLocation(r.location)}
if r.info != nil {
out[i].Size = r.info.Size
out[i].ModifiedAtSecond = r.info.ModifiedAtSecond
out[i].CompactRevision = r.info.CompactRevision
out[i].ReadOnly = r.info.ReadOnly
func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
mostRecent := replicas[0]
for _, replica := range replicas {
if replica.info.ModifiedAtSecond > mostRecent.info.ModifiedAtSecond {
mostRecent = replica
}
}
return out
return mostRecent
}
func pickOneReplicaToCopyFrom(replicas []*VolumeReplica) *VolumeReplica {
if i := balancer.PickOneReplicaToCopyFrom(toBalancerReplicas(replicas)); i >= 0 {
return replicas[i]
func countReplicas(replicas []*VolumeReplica) (diffDc, diffRack, diffNode map[string]int) {
diffDc = make(map[string]int)
diffRack = make(map[string]int)
diffNode = make(map[string]int)
for _, replica := range replicas {
diffDc[replica.location.DataCenter()] += 1
diffRack[replica.location.Rack()] += 1
diffNode[replica.location.String()] += 1
}
return nil
return
}
// pickOneReplicaToDelete selects the replica to trim when over-replicated.
// It only ever removes the smallest of multiple healthy writable replicas: a
// ReadOnly/integrity-flagged replica is never chosen for deletion, and the
// trim is refused (returns nil) when removing a writable replica would leave
// only ReadOnly survivors. VolumeStatus file_count>0 alone cannot prove the
// survivors' .dat is readable, so we do not over-claim survivor health.
// pickSmallestReplica returns the smallest replica (ties broken by oldest then
// lowest compact revision), or nil for an empty set.
func pickSmallestReplica(replicas []*VolumeReplica) *VolumeReplica {
if len(replicas) == 0 {
return nil
}
sorted := slices.Clone(replicas)
slices.SortFunc(sorted, func(a, b *VolumeReplica) int {
if a.info.Size != b.info.Size {
return int(a.info.Size - b.info.Size)
}
if a.info.ModifiedAtSecond != b.info.ModifiedAtSecond {
return int(a.info.ModifiedAtSecond - b.info.ModifiedAtSecond)
}
if a.info.CompactRevision != b.info.CompactRevision {
return int(a.info.CompactRevision - b.info.CompactRevision)
}
return 0
})
return sorted[0]
}
// pickOneReplicaToDelete selects the replica to trim when over-replicated;
// see balancer.PickOneReplicaToDelete for the survivor-safety rules.
// VolumeStatus file_count>0 alone cannot prove the survivors' .dat is
// readable, so we do not over-claim survivor health.
func pickOneReplicaToDelete(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
if i := balancer.PickOneReplicaToDelete(toBalancerReplicas(replicas), replicaPlacement); i >= 0 {
return replicas[i]
// Over-replication trim: only ever remove a writable replica, and only
// when another writable one survives, so a healthy copy is never deleted
// down to a read-only (e.g. full or integrity-flagged) survivor.
var writable []*VolumeReplica
for _, r := range replicas {
if !r.info.ReadOnly {
writable = append(writable, r)
}
}
return nil
if len(writable) < 2 {
return nil
}
// Prefer a writable replica whose removal still satisfies placement, so the
// trim does not strip the only replica in a required failure domain. Fall
// back to the smallest writable if none keeps placement (a later misplaced
// cycle then re-balances).
var placementSafe []*VolumeReplica
for i, r := range replicas {
if r.info.ReadOnly {
continue
}
if !isMisplaced(otherThan(replicas, i), replicaPlacement) {
placementSafe = append(placementSafe, r)
}
}
if len(placementSafe) > 0 {
return pickSmallestReplica(placementSafe)
}
return pickSmallestReplica(writable)
}
// check and fix misplaced volumes
func isMisplaced(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) bool {
return balancer.IsMisplaced(toBalancerReplicas(replicas), replicaPlacement)
for i := 0; i < len(replicas); i++ {
others := otherThan(replicas, i)
if !satisfyReplicaPlacement(replicaPlacement, others, *replicas[i].location) {
return true
}
}
return false
}
func pickOneMisplacedVolume(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) *VolumeReplica {
if i := balancer.PickOneMisplacedVolume(toBalancerReplicas(replicas), replicaPlacement); i >= 0 {
return replicas[i]
func otherThan(replicas []*VolumeReplica, index int) (others []*VolumeReplica) {
for i := 0; i < len(replicas); i++ {
if index != i {
others = append(others, replicas[i])
}
}
return nil
return
}
func pickOneMisplacedVolume(replicas []*VolumeReplica, replicaPlacement *super_block.ReplicaPlacement) (toDelete *VolumeReplica) {
// Relocation, not over-replication: pick the smallest replica to delete
// and recreate at a correct placement. Unlike the trim this must still act
// on read-only replicas (e.g. a full but misplaced volume), so it does not
// use pickOneReplicaToDelete's writable-survivor guard.
var deletionCandidates []*VolumeReplica
for i := 0; i < len(replicas); i++ {
others := otherThan(replicas, i)
if !isMisplaced(others, replicaPlacement) {
deletionCandidates = append(deletionCandidates, replicas[i])
}
}
if toDelete = pickSmallestReplica(deletionCandidates); toDelete != nil {
return toDelete
}
return pickSmallestReplica(replicas)
}
@@ -1,144 +0,0 @@
package shell
import (
"io"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
)
func testFixLocation(dc, rack, id string, maxVolumes int64) location {
return location{
dc: dc,
rack: rack,
dataNode: &master_pb.DataNodeInfo{
Id: id,
DiskInfos: map[string]*master_pb.DiskInfo{
"": {MaxVolumeCount: maxVolumes, FreeVolumeCount: maxVolumes},
},
},
}
}
func TestReserveTargetSpreadsAcrossServers(t *testing.T) {
src := testFixLocation("dc1", "r1", "dn0", 0)
allLocations := []location{
src,
testFixLocation("dc1", "r1", "dn1", 10),
testFixLocation("dc1", "r1", "dn2", 5),
testFixLocation("dc1", "r1", "dn3", 3),
}
// keepDataNodesSorted reorders allLocations in place, so keep stable
// per-node copies; the shared dataNode pointers carry the accounting
byId := make(map[string]*location)
for _, loc := range allLocations {
loc := loc
byId[loc.dataNode.Id] = &loc
}
replicas := []*VolumeReplica{
{location: &src, info: &master_pb.VolumeInformationMessage{Id: 1}},
}
rp, _ := super_block.NewReplicaPlacementFromString("001")
// with all copies in flight, consecutive reservations must not converge on
// the emptiest server
s := newVolumeCopyScheduler(1)
var reserved []*location
got := make(map[string]bool)
for i := 0; i < 3; i++ {
dst := s.reserveTarget(rp, replicas, allLocations, "", true)
if dst == nil {
t.Fatalf("reservation %d found no destination", i)
}
reserved = append(reserved, dst)
got[dst.dataNode.Id] = true
}
for _, id := range []string{"dn1", "dn2", "dn3"} {
if !got[id] {
t.Errorf("expected a reservation on %s, got %v", id, got)
}
}
// every eligible destination is at the copy cap: the next reservation
// waits for a free slot instead of failing
done := make(chan *location)
go func() {
done <- s.reserveTarget(rp, replicas, allLocations, "", true)
}()
select {
case dst := <-done:
t.Fatalf("reserveTarget should wait while all destinations are at the copy cap, got %s", dst.dataNode.Id)
case <-time.After(100 * time.Millisecond):
}
s.releaseTarget(byId["dn1"], "", true)
var waited *location
select {
case waited = <-done:
case <-time.After(5 * time.Second):
t.Fatal("reserveTarget did not wake up after a copy slot freed")
}
if waited == nil || waited.dataNode.Id != "dn1" {
t.Fatalf("expected the freed dn1 to take the waiting copy, got %+v", waited)
}
// a successful copy keeps its volume slot, a failed one returns it
s.releaseTarget(waited, "", true)
if count := byId["dn1"].dataNode.DiskInfos[""].VolumeCount; count != 2 {
t.Errorf("dn1 should keep 2 reserved slots, got %d", count)
}
for _, dst := range reserved {
if dst.dataNode.Id != "dn1" {
s.releaseTarget(dst, "", false)
if count := dst.dataNode.DiskInfos[""].VolumeCount; count != 0 {
t.Errorf("%s should have its failed reservation returned, got volume count %d", dst.dataNode.Id, count)
}
}
}
if len(s.inflight) != 0 {
t.Errorf("all copies released, but %d still in flight", len(s.inflight))
}
}
func TestFixUnderReplicatedVolumesInParallel(t *testing.T) {
src := testFixLocation("dc1", "r1", "dn0", 0)
allLocations := []location{
src,
testFixLocation("dc1", "r1", "dn1", 4),
testFixLocation("dc1", "r1", "dn2", 4),
testFixLocation("dc1", "r1", "dn3", 4),
}
rp, _ := super_block.NewReplicaPlacementFromString("001")
volumeReplicas := make(map[uint32][]*VolumeReplica)
var volumeIds []uint32
for vid := uint32(1); vid <= 12; vid++ {
volumeReplicas[vid] = []*VolumeReplica{
{location: &src, info: &master_pb.VolumeInformationMessage{Id: vid, ReplicaPlacement: uint32(rp.Byte())}},
}
volumeIds = append(volumeIds, vid)
}
c := &commandVolumeFixReplication{collectionPattern: new(string)}
fixedVolumes, err := c.fixUnderReplicatedVolumes(nil, io.Discard, false, volumeIds, volumeReplicas, allLocations, 0, 0, 8, 1)
if err != nil {
t.Fatalf("fixUnderReplicatedVolumes: %v", err)
}
if len(fixedVolumes) != 0 {
t.Errorf("simulation should not record fixed volumes, got %d", len(fixedVolumes))
}
// 12 volumes must exactly fill the 3x4 free slots without over-reserving
// any single destination
for _, loc := range allLocations {
if loc.dataNode.Id == "dn0" {
continue
}
diskInfo := loc.dataNode.DiskInfos[""]
if diskInfo.VolumeCount != 4 || diskInfo.FreeVolumeCount != 0 {
t.Errorf("%s expected exactly 4 reserved slots, got volume count %d, free %d",
loc.dataNode.Id, diskInfo.VolumeCount, diskInfo.FreeVolumeCount)
}
}
}
+1 -5
View File
@@ -233,11 +233,7 @@ func markVolumeWritable(grpcDialOption grpc.DialOption, volumeId needle.VolumeId
}
func markVolumeReplicaWritable(grpcDialOption grpc.DialOption, volumeId needle.VolumeId, location wdclient.Location, writable, persist bool) error {
if writable {
fmt.Printf("markVolumeWritable %d on %s ...\n", volumeId, location.Url)
} else {
fmt.Printf("markVolumeReadonly %d on %s persist=%v ...\n", volumeId, location.Url, persist)
}
fmt.Printf("markVolumeReadonly %d on %s ...\n", volumeId, location.Url)
return markVolumeWritable(grpcDialOption, volumeId, location.ServerAddress(), writable, persist)
}
-26
View File
@@ -54,29 +54,3 @@ func TestParseFileIdFromString(t *testing.T) {
t.Errorf("%s : needleId is too long", fidStr1)
}
}
func TestNeedleIdFileId(t *testing.T) {
tests := []struct {
key types.NeedleId
volumeId uint32
want string
}{
{types.NeedleId(1), 3, "3,0100000000"},
{types.NeedleId(0x123), 3, "3,012300000000"},
{types.NeedleId(0x1234), 7, "7,123400000000"},
}
for _, tt := range tests {
fid := tt.key.FileId(tt.volumeId)
if fid != tt.want {
t.Errorf("NeedleId(%d).FileId(%d) = %s, want %s", tt.key, tt.volumeId, fid, tt.want)
}
fileId, err := ParseFileIdFromString(fid)
if err != nil {
t.Errorf("%s : should be OK: %v", fid, err)
continue
}
if fileId.VolumeId != VolumeId(tt.volumeId) || fileId.Key != tt.key || fileId.Cookie != 0 {
t.Errorf("src : %s, dest : %v", fid, fileId)
}
}
}
+11 -80
View File
@@ -147,9 +147,9 @@ func (f *localDirBackendFile) Truncate(off int64) error {
return os.Truncate(filepath.Join(f.backend.root, f.key), off)
}
func (f *localDirBackendFile) Close() error { return nil }
func (f *localDirBackendFile) Name() string { return f.key }
func (f *localDirBackendFile) Sync() error { return nil }
func (f *localDirBackendFile) Close() error { return nil }
func (f *localDirBackendFile) Name() string { return f.key }
func (f *localDirBackendFile) Sync() error { return nil }
func (f *localDirBackendFile) GetStat() (int64, time.Time, error) {
files := f.tierInfo.GetFiles()
if len(files) == 0 {
@@ -174,13 +174,11 @@ func registerTestBackend(t *testing.T, b *localDirBackend) {
})
}
// tierUpVolumeLive creates a real on-disk volume, writes a few needles, then
// uploads the .dat to the fake backend and rewrites the volume in remote mode
// (mirrors the production flow in volume_grpc_tier_upload.go but in-process).
// It returns the still-open volume, exactly as a volume server holds it after a
// live `volume.tier.upload` — no reload. Callers that want the on-disk state a
// server sees after restart use tierUpVolume, which closes it.
func tierUpVolumeLive(t *testing.T, dir string, vid needle.VolumeId, b *localDirBackend) (v *Volume, key string) {
// tierUpVolume creates a real on-disk volume, writes a few needles, then
// uploads the .dat to the fake backend and rewrites the volume in remote
// mode (mirrors the production flow in volume_grpc_tier_upload.go but
// in-process).
func tierUpVolume(t *testing.T, dir string, vid needle.VolumeId, b *localDirBackend) (collection string, key string) {
t.Helper()
v, err := NewVolume(dir, dir, "", vid, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
require.NoError(t, err)
@@ -210,16 +208,10 @@ func tierUpVolumeLive(t *testing.T, dir string, vid needle.VolumeId, b *localDir
require.NoError(t, v.LoadRemoteFile())
require.NoError(t, os.Remove(v.FileName(".dat")))
return v, uploadKey
}
// tierUpVolume runs tierUpVolumeLive then closes the volume. Tests using it
// reload from disk to mirror what a volume server does on restart with a
// tiered volume.
func tierUpVolume(t *testing.T, dir string, vid needle.VolumeId, b *localDirBackend) (collection string, key string) {
t.Helper()
v, uploadKey := tierUpVolumeLive(t, dir, vid, b)
// Close the volume cleanly. Tests below reload it from disk to mirror
// what a volume server does on restart with a tiered volume.
v.Close()
return v.Collection, uploadKey
}
@@ -267,67 +259,6 @@ func TestRemoteTier_DiskScanLoadsRemoteOnlyVolume(t *testing.T) {
v.Close()
}
// TestRemoteTier_LiveTierUpload_StillReportsToMaster covers a live
// `volume.tier.upload`: the .dat is removed and the volume serves from remote,
// but the same in-memory Volume keeps heartbeating with no reload. The
// phantom-.dat guard must not suppress it just because .dat is gone —
// LoadRemoteFile has flipped it into remote mode, so ToVolumeInformationMessage
// must still report it to the master. If HasRemoteFile stayed false the volume
// would vanish from the topology ("volume not found").
func TestRemoteTier_LiveTierUpload_StillReportsToMaster(t *testing.T) {
b := newLocalDirBackend(t)
registerTestBackend(t, b)
dir := t.TempDir()
const vid = needle.VolumeId(67)
v, _ := tierUpVolumeLive(t, dir, vid, b)
defer v.Close()
// A store-owned volume always carries its DiskLocation; NewVolume leaves it
// nil, so give it one for the IsReadOnly disk-space check inside the heartbeat.
v.location = &DiskLocation{Directory: dir, DiskType: types.HddType}
require.True(t, v.HasRemoteFile(), "a tier-uploaded volume is in remote mode even before any reload")
require.False(t, util.FileExists(v.FileName(".dat")), "tier-up should have removed the local .dat")
_, msg := v.ToVolumeInformationMessage()
require.NotNil(t, msg, "tier-uploaded volume must still report to master")
require.NotEmpty(t, msg.RemoteStorageName, "reported volume must carry its remote backend name")
}
// TestRemoteTier_ReloadUnderDataLock_NoDeadlock guards the reload-under-lock
// path: CommitCompact holds dataFileAccessLock and calls v.load(), which for a
// remote-tiered volume swaps the data backend. That swap must go through the
// lock-free loadRemoteFileLocked; if load() instead used the public
// LoadRemoteFile (which takes dataFileAccessLock), it would re-enter the held
// lock and deadlock.
func TestRemoteTier_ReloadUnderDataLock_NoDeadlock(t *testing.T) {
b := newLocalDirBackend(t)
registerTestBackend(t, b)
dir := t.TempDir()
const vid = needle.VolumeId(68)
v, _ := tierUpVolumeLive(t, dir, vid, b)
v.location = &DiskLocation{Directory: dir, DiskType: types.HddType}
require.True(t, v.HasRemoteFile())
done := make(chan error, 1)
go func() {
// Mirror CommitCompact: hold the data lock across the reload.
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
done <- v.load(true, false, v.needleMapKind, 0, v.Version())
}()
select {
case err := <-done:
require.NoError(t, err)
require.True(t, v.HasRemoteFile(), "volume must stay remote-tiered after reload")
v.Close()
case <-time.After(10 * time.Second):
t.Fatal("reload under dataFileAccessLock deadlocked: load() re-entered the held lock via LoadRemoteFile")
}
}
// TestRemoteTier_Move_KeepsRemoteObject simulates the move-on-source-after-copy
// step of a balance: Destroy(onlyEmpty=false, keepRemoteData=true). The remote
// object must survive — the destination's freshly-copied .vif points at it.
+2 -2
View File
@@ -102,7 +102,7 @@ func TestLocalVolumesLen(t *testing.T) {
// Mark some as remote
if i < tc.remoteVolumes {
vol.hasRemoteFile.Store(true)
vol.hasRemoteFile = true
vol.volumeInfo.Files = []*volume_server_pb.RemoteFile{
{BackendType: "s3", BackendId: "test", Key: "test-key"},
}
@@ -250,7 +250,7 @@ func createTestVolume(vid needle.VolumeId, isRemote bool) *Volume {
}
if isRemote {
vol.hasRemoteFile.Store(true)
vol.hasRemoteFile = true
vol.volumeInfo.Files = []*volume_server_pb.RemoteFile{
{BackendType: "s3", BackendId: "test", Key: "remote-key-" + strconv.Itoa(int(vid))},
}
+1 -6
View File
@@ -36,12 +36,7 @@ func (k NeedleId) String() string {
}
func (k NeedleId) FileId(volumeId uint32) string {
// pad to even length so strict hex fid parsers accept it
needleIdHex := k.String()
if len(needleIdHex)%2 == 1 {
needleIdHex = "0" + needleIdHex
}
return fmt.Sprintf("%d,%s00000000", volumeId, needleIdHex)
return fmt.Sprintf("%d,%s00000000", volumeId, k.String())
}
func ParseNeedleId(idString string) (NeedleId, error) {
+6 -19
View File
@@ -32,7 +32,7 @@ type Volume struct {
noWriteOrDelete bool // if readonly, either noWriteOrDelete or noWriteCanDelete
noWriteCanDelete bool // if readonly, either noWriteOrDelete or noWriteCanDelete
noWriteLock sync.RWMutex
hasRemoteFile atomic.Bool // if the volume is tiered: data lives in a remote backend
hasRemoteFile bool // if the volume has a remote file
MemoryMapMaxSizeMb uint32
super_block.SuperBlock
@@ -312,30 +312,17 @@ func (v *Volume) Close() {
v.doClose()
}
// SwapDataBackend atomically replaces the data backend and updates the
// remote-tier flag under dataFileAccessLock, closing the old backend. Both tier
// directions go through here so hasRemoteFile always matches the live backend:
// tier-down passes hasRemoteFile=false (now serving a local .dat), tier-up
// passes true. Keeping the swap and the flag under one lock means the heartbeat
// never observes a half-swapped backend or a flag that disagrees with it — a
// stale-false flag would make doDeleteRequest skip the new .dat's tombstones and
// disable the phantom-.dat guard.
func (v *Volume) SwapDataBackend(newBackend backend.BackendStorageFile, hasRemoteFile bool) {
// SwapDataBackend atomically replaces the data backend (e.g. swapping a
// remote-tier backend for a freshly downloaded local .dat), closing the old
// one. Held under dataFileAccessLock so a concurrent read/write never observes
// a half-swapped or closed backend.
func (v *Volume) SwapDataBackend(newBackend backend.BackendStorageFile) {
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
v.swapDataBackendLocked(newBackend, hasRemoteFile)
}
// swapDataBackendLocked is the body of SwapDataBackend for callers that already
// hold dataFileAccessLock (e.g. load() reached while CommitCompact holds the
// lock). Reusing it from those under-lock paths avoids re-entering the
// non-reentrant lock, which would deadlock.
func (v *Volume) swapDataBackendLocked(newBackend backend.BackendStorageFile, hasRemoteFile bool) {
if v.DataBackend != nil {
v.DataBackend.Close()
}
v.DataBackend = newBackend
v.hasRemoteFile.Store(hasRemoteFile)
}
func (v *Volume) doClose() {
+1 -4
View File
@@ -161,10 +161,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
v.noWriteCanDelete = true
v.noWriteOrDelete = false
glog.V(0).Infof("loading volume %d from remote %v", v.Id, v.volumeInfo)
// loadRemoteFileLocked, not LoadRemoteFile: load() is reached from
// CommitCompact with dataFileAccessLock already held, and the locking
// variant would deadlock re-entering it.
if err := v.loadRemoteFileLocked(); err != nil {
if err := v.LoadRemoteFile(); err != nil {
return fmt.Errorf("load remote file %v: %w", v.volumeInfo, err)
}
// Set lastModifiedTsSeconds from remote file to prevent premature expiry on startup
+9 -27
View File
@@ -19,15 +19,13 @@ func (v *Volume) GetVolumeInfo() *volume_server_pb.VolumeInfo {
func (v *Volume) maybeLoadVolumeInfo() (found bool) {
var err error
var hasRemoteFile bool
v.volumeInfo, hasRemoteFile, found, err = volume_info.MaybeLoadVolumeInfo(v.FileName(".vif"))
v.hasRemoteFile.Store(hasRemoteFile)
v.volumeInfo, v.hasRemoteFile, found, err = volume_info.MaybeLoadVolumeInfo(v.FileName(".vif"))
if v.volumeInfo.Version == 0 {
v.volumeInfo.Version = uint32(needle.GetCurrentVersion())
}
if hasRemoteFile {
if v.hasRemoteFile {
glog.V(0).Infof("volume %d is tiered to %s as %s and read only", v.Id,
v.volumeInfo.Files[0].BackendName(), v.volumeInfo.Files[0].Key)
} else {
@@ -57,37 +55,21 @@ func (v *Volume) maybeLoadVolumeInfo() (found bool) {
}
func (v *Volume) HasRemoteFile() bool {
return v.hasRemoteFile.Load()
return v.hasRemoteFile
}
// LoadRemoteFile swaps the data backend to the remote tier object under
// dataFileAccessLock. Call this from a context that does NOT already hold the
// lock — the live tier-upload handler, where the heartbeat may be reading the
// backend concurrently. load() must instead use loadRemoteFileLocked, since it
// can be reached with the lock already held (CommitCompact).
func (v *Volume) LoadRemoteFile() error {
v.dataFileAccessLock.Lock()
defer v.dataFileAccessLock.Unlock()
return v.loadRemoteFileLocked()
}
// loadRemoteFileLocked swaps the data backend to the remote tier object. The
// caller must hold dataFileAccessLock or be single-threaded (load() during
// construction or a compaction-commit reload). It marks the volume tiered in the
// same locked step so a later heartbeat does not treat a removed local .dat as a
// phantom volume and stop reporting it to the master.
func (v *Volume) loadRemoteFileLocked() error {
// Callers only reach here for a tiered volume (HasRemoteFile / a just-appended
// remote file), but guard the index so a stray call is a clean error, not a panic.
if len(v.volumeInfo.GetFiles()) == 0 {
return fmt.Errorf("volume %d has no remote file to load", v.Id)
}
tierFile := v.volumeInfo.GetFiles()[0]
backendStorage, found := backend.BackendStorages[tierFile.BackendName()]
if !found {
return fmt.Errorf("backend storage %s not found", tierFile.BackendName())
}
v.swapDataBackendLocked(backendStorage.NewStorageFile(tierFile.Key, v.volumeInfo), true)
if v.DataBackend != nil {
v.DataBackend.Close()
}
v.DataBackend = backendStorage.NewStorageFile(tierFile.Key, v.volumeInfo)
return nil
}
+1 -1
View File
@@ -274,7 +274,7 @@ func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
var offset uint64
var err error
size := nv.Size
if !v.HasRemoteFile() {
if !v.hasRemoteFile {
n.Data = nil
n.UpdateAppendAtNs(v.lastAppendAtNs)
offset, _, _, err = n.Append(v.DataBackend, v.Version())
-161
View File
@@ -1,161 +0,0 @@
package balancer
import (
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
)
// Replica pairs a replica's placement location with the volume attributes
// replica-selection decisions need. Like Location for placement checks, it is
// the shared shape the shell (from master_pb) and workers adapt to. Selection
// functions return an index into the given slice (-1 when nothing qualifies),
// so callers can map the choice back to their own richer replica type.
type Replica struct {
Location Location
Size uint64
ModifiedAtSecond int64
CompactRevision uint32
ReadOnly bool
}
// SatisfyReplicaCurrentLocation reports whether the existing replicas already
// span the failure domains the policy requires (enough data centers, enough
// racks, and the same-rack count somewhere). A volume whose replica count is
// right but whose spread falls short still needs another replica.
func SatisfyReplicaCurrentLocation(rp *super_block.ReplicaPlacement, replicas []Location) bool {
dcCounts, rackCounts, _ := countReplicas(replicas)
if rp.DiffDataCenterCount+1 > len(dcCounts) {
return false
}
if rp.DiffRackCount+1 > len(rackCounts) {
return false
}
if rp.SameRackCount > 0 {
for _, rackCount := range rackCounts {
if rackCount >= rp.SameRackCount+1 {
return true
}
}
return false
}
return true
}
// PickOneReplicaToCopyFrom returns the most recently modified replica, the
// best source for adding a new replica.
func PickOneReplicaToCopyFrom(replicas []Replica) int {
mostRecent := -1
for i, r := range replicas {
if mostRecent < 0 || r.ModifiedAtSecond > replicas[mostRecent].ModifiedAtSecond {
mostRecent = i
}
}
return mostRecent
}
// IsMisplaced reports whether any replica sits at a location inconsistent
// with the replication policy given the other replicas' locations.
func IsMisplaced(replicas []Replica, rp *super_block.ReplicaPlacement) bool {
for i := range replicas {
others := otherThan(replicas, i)
locs := make([]Location, len(others))
for j, r := range others {
locs[j] = r.Location
}
if !SatisfyReplicaPlacement(rp, locs, replicas[i].Location) {
return true
}
}
return false
}
// PickSmallestReplica returns the smallest replica (ties broken by oldest
// then lowest compact revision).
func PickSmallestReplica(replicas []Replica) int {
smallest := -1
for i := range replicas {
if smallest < 0 || lessReplica(replicas[i], replicas[smallest]) {
smallest = i
}
}
return smallest
}
// PickOneReplicaToDelete selects the replica to trim when over-replicated.
// It only ever removes the smallest of multiple healthy writable replicas: a
// ReadOnly/integrity-flagged replica is never chosen for deletion, and the
// trim is refused (returns -1) when removing a writable replica would leave
// only ReadOnly survivors. Among the writable replicas it prefers one whose
// removal still satisfies placement, so the trim does not strip the only
// replica in a required failure domain; it falls back to the smallest
// writable if none keeps placement (a later misplaced cycle then
// re-balances).
func PickOneReplicaToDelete(replicas []Replica, rp *super_block.ReplicaPlacement) int {
var writable []int
for i, r := range replicas {
if !r.ReadOnly {
writable = append(writable, i)
}
}
if len(writable) < 2 {
return -1
}
var placementSafe []int
for _, i := range writable {
if !IsMisplaced(otherThan(replicas, i), rp) {
placementSafe = append(placementSafe, i)
}
}
if len(placementSafe) > 0 {
return pickSmallestAmong(replicas, placementSafe)
}
return pickSmallestAmong(replicas, writable)
}
// PickOneMisplacedVolume selects the replica to delete and recreate at a
// correct placement. This is relocation, not over-replication: unlike
// PickOneReplicaToDelete it must still act on read-only replicas (e.g. a full
// but misplaced volume), so it does not use the writable-survivor guard. It
// prefers a replica whose removal leaves the others well placed, and falls
// back to the smallest replica.
func PickOneMisplacedVolume(replicas []Replica, rp *super_block.ReplicaPlacement) int {
var deletionCandidates []int
for i := range replicas {
if !IsMisplaced(otherThan(replicas, i), rp) {
deletionCandidates = append(deletionCandidates, i)
}
}
if smallest := pickSmallestAmong(replicas, deletionCandidates); smallest >= 0 {
return smallest
}
return PickSmallestReplica(replicas)
}
func pickSmallestAmong(replicas []Replica, candidates []int) int {
smallest := -1
for _, i := range candidates {
if smallest < 0 || lessReplica(replicas[i], replicas[smallest]) {
smallest = i
}
}
return smallest
}
func lessReplica(a, b Replica) bool {
if a.Size != b.Size {
return a.Size < b.Size
}
if a.ModifiedAtSecond != b.ModifiedAtSecond {
return a.ModifiedAtSecond < b.ModifiedAtSecond
}
return a.CompactRevision < b.CompactRevision
}
func otherThan(replicas []Replica, index int) (others []Replica) {
for i := range replicas {
if index != i {
others = append(others, replicas[i])
}
}
return
}
+47 -198
View File
@@ -2,7 +2,6 @@ package log_buffer
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"sync"
@@ -94,12 +93,6 @@ type LogBuffer struct {
hasOffsets bool
// Disk chunk cache for historical data reads
diskChunkCache *DiskChunkCache
// curSnap is a GC-owned copy of the current window's append-only prefix
// buf[:len(curSnap)], shared by all readers so each byte is copied once per
// window instead of once per reader. Extended lazily under curSnapMu; reset
// at seal. Existing holders keep their prefix slices, which never mutate.
curSnapMu sync.Mutex
curSnap []byte
sync.RWMutex
}
@@ -613,13 +606,6 @@ func (logBuffer *LogBuffer) copyToFlushInternal(withCallback bool) *dataToFlush
// CRITICAL: logBuffer.offset is the "next offset to assign", so last offset in buffer is offset-1
lastOffsetInBuffer := logBuffer.offset - 1
logBuffer.buf = logBuffer.prevBuffers.SealBuffer(logBuffer.startTime, logBuffer.stopTime, logBuffer.buf, logBuffer.pos, logBuffer.bufferStartOffset, lastOffsetInBuffer)
// Hand a fully extended prefix snapshot to the sealed slot so sealed
// readers reuse it instead of re-copying the window; reset for the next
// window either way (holders keep their immutable prefix slices).
if len(logBuffer.curSnap) == logBuffer.pos {
logBuffer.prevBuffers.buffers[len(logBuffer.prevBuffers.buffers)-1].snapshot = logBuffer.curSnap[:logBuffer.pos:logBuffer.pos]
}
logBuffer.curSnap = nil
// Use zero time (time.Time{}) not epoch time (time.Unix(0,0))
// Epoch time (1970) breaks time-based reads after flush
logBuffer.startTime = time.Time{}
@@ -715,11 +701,7 @@ func (d *dataToFlush) releaseMemory() {
bufferPool.Put(d.data)
}
// ReadFromBuffer returns the in-memory log data at lastReadPosition. isPooled
// reports whether the returned buffer is a private pooled copy the caller must
// return via ReleaseMemory; when false the buffer wraps a snapshot shared with
// other readers and must not be released (or written to).
func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bufferCopy *bytes.Buffer, batchIndex int64, isPooled bool, err error) {
func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bufferCopy *bytes.Buffer, batchIndex int64, err error) {
logBuffer.RLock()
defer logBuffer.RUnlock()
@@ -746,19 +728,19 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Case 3: try disk read (historical data might exist)
if requestedOffset < logBuffer.offset {
// Data was in the buffer range but buffer is now empty = flushed to disk
return nil, -2, false, ResumeFromDiskError
return nil, -2, ResumeFromDiskError
}
// requestedOffset == logBuffer.offset: Current position
// CRITICAL: For subscribers starting from offset 0, try disk read first
// (historical data might exist from previous runs)
if requestedOffset == 0 && logBuffer.bufferStartOffset == 0 && logBuffer.offset == 0 {
// Initial state: try disk read before waiting for new data
return nil, -2, false, ResumeFromDiskError
return nil, -2, ResumeFromDiskError
}
// Otherwise, wait for new data to arrive
return nil, logBuffer.offset, false, nil
return nil, logBuffer.offset, nil
}
return logBuffer.currentSnapshotView(0, logBuffer.pos), logBuffer.offset, false, nil
return copiedBytes(logBuffer.buf[:logBuffer.pos]), logBuffer.offset, nil
}
// Check previous buffers for the requested offset
@@ -768,9 +750,9 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// (prevBuffers are created when buffer is flushed)
if buf.size == 0 {
// Empty prevBuffer covering this offset means data was flushed
return nil, -2, false, ResumeFromDiskError
return nil, -2, ResumeFromDiskError
}
return sharedBufferView(buf, 0), buf.offset, false, nil
return copiedBytes(buf.buf[:buf.size]), buf.offset, nil
}
}
@@ -778,16 +760,16 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if requestedOffset < logBuffer.bufferStartOffset {
// Data not in current buffers - must be on disk (flushed or never existed)
// Return ResumeFromDiskError to trigger disk read
return nil, -2, false, ResumeFromDiskError
return nil, -2, ResumeFromDiskError
}
if requestedOffset > logBuffer.offset {
// Future data, not available yet
return nil, logBuffer.offset, false, nil
return nil, logBuffer.offset, nil
}
// Offset not found - return nil
return nil, logBuffer.offset, false, nil
return nil, logBuffer.offset, nil
}
// TIMESTAMP-BASED READ (original logic)
@@ -816,7 +798,7 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Buffer is empty - return ResumeFromDiskError so caller can read from disk
// This fixes issue #4977 where SubscribeMetadata stalls because
// MetaAggregator.MetaLogBuffer is empty in single-filer setups
return nil, -2, false, ResumeFromDiskError
return nil, -2, ResumeFromDiskError
} else if lastReadPosition.Time.Before(tsMemory) { // case 2.3
// For time-based reads, only check timestamp for disk reads
// Don't use offset comparisons as they're not meaningful for time-based subscriptions
@@ -830,7 +812,7 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Treat first read with sentinel/zero offset as inclusive of earliest in-memory data
} else {
// Data not in memory buffers - read from disk
return nil, -2, false, ResumeFromDiskError
return nil, -2, ResumeFromDiskError
}
}
@@ -839,17 +821,17 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if lastReadPosition.Time.Equal(logBuffer.stopTime) && !logBuffer.stopTime.IsZero() {
// For first-read sentinel/zero offset, allow inclusive read at the boundary
if lastReadPosition.Offset > 0 {
return nil, logBuffer.offset, false, nil
return nil, logBuffer.offset, nil
}
}
if lastReadPosition.Time.After(logBuffer.stopTime) && !logBuffer.stopTime.IsZero() {
return nil, logBuffer.offset, false, nil
return nil, logBuffer.offset, nil
}
// Also check prevBuffers when current buffer is empty (startTime is zero)
if lastReadPosition.Time.Before(logBuffer.startTime) || logBuffer.startTime.IsZero() {
for _, buf := range logBuffer.prevBuffers.buffers {
if buf.startTime.After(lastReadPosition.Time) {
return sharedBufferView(buf, 0), buf.offset, false, nil
return copiedBytes(buf.buf[:buf.size]), buf.offset, nil
}
if !buf.startTime.After(lastReadPosition.Time) && buf.stopTime.After(lastReadPosition.Time) {
searchTime := lastReadPosition.Time
@@ -860,19 +842,19 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if err != nil {
// Buffer corruption detected - return error wrapped with ErrBufferCorrupted
glog.Errorf("ReadFromBuffer: buffer corruption in prevBuffer: %v", err)
return nil, -1, false, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
return nil, -1, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
}
if pos < buf.size {
return sharedBufferView(buf, pos), buf.offset, false, nil
return copiedBytes(buf.buf[pos:buf.size]), buf.offset, nil
}
}
}
// If current buffer is not empty, return it
if logBuffer.pos > 0 {
return logBuffer.currentSnapshotView(0, logBuffer.pos), logBuffer.offset, false, nil
return copiedBytes(logBuffer.buf[:logBuffer.pos]), logBuffer.offset, nil
}
// Buffer is empty and no data in prevBuffers - wait for new data
return nil, logBuffer.offset, false, nil
return nil, logBuffer.offset, nil
}
lastTs := lastReadPosition.Time.UnixNano()
@@ -904,7 +886,7 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if err != nil {
// Buffer corruption detected in binary search
glog.Errorf("ReadFromBuffer: buffer corruption at idx[%d] pos %d: %v", mid, pos, err)
return nil, -1, false, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
return nil, -1, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
}
if t <= searchTs {
l = mid + 1
@@ -915,11 +897,11 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
if err != nil {
// Buffer corruption detected in binary search (previous entry)
glog.Errorf("ReadFromBuffer: buffer corruption at idx[%d] pos %d: %v", mid-1, logBuffer.idx[mid-1], err)
return nil, -1, false, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
return nil, -1, fmt.Errorf("%w: %v", ErrBufferCorrupted, err)
}
}
if prevT <= searchTs {
return logBuffer.currentSnapshotView(pos, logBuffer.pos), logBuffer.offset, false, nil
return copiedBytes(logBuffer.buf[pos:logBuffer.pos]), logBuffer.offset, nil
}
h = mid
}
@@ -927,13 +909,9 @@ func (logBuffer *LogBuffer) ReadFromBuffer(lastReadPosition MessagePosition) (bu
// Binary search didn't find the timestamp - data may have been flushed to disk already
// Returning -2 signals to caller that data is not available in memory
return nil, -2, false, nil
return nil, -2, nil
}
// ReleaseMemory returns a pooled buffer for reuse. Only call it for buffers
// ReadFromBuffer reported as pooled: recycling a shared sealed-window view
// would let the next copiedBytes overwrite bytes other readers still hold.
func (logBuffer *LogBuffer) ReleaseMemory(b *bytes.Buffer) {
bufferPool.Put(b)
}
@@ -958,6 +936,18 @@ var bufferPool = sync.Pool{
},
}
// logEntryPool reduces allocations in readTs which is called frequently during binary search
var logEntryPool = sync.Pool{
New: func() interface{} {
return &filer_pb.LogEntry{}
},
}
// resetLogEntry clears a LogEntry for pool reuse
func resetLogEntry(e *filer_pb.LogEntry) {
proto.Reset(e)
}
func copiedBytes(buf []byte) (copied *bytes.Buffer) {
copied = bufferPool.Get().(*bytes.Buffer)
copied.Reset()
@@ -965,37 +955,6 @@ func copiedBytes(buf []byte) (copied *bytes.Buffer) {
return
}
// sharedBufferView wraps the sealed window's shared snapshot from pos onward.
// The returned buffer aliases memory shared with other readers: it must be
// treated as read-only and never passed to ReleaseMemory (the full-slice cap
// makes an accidental append reallocate instead of scribbling on the snapshot).
func sharedBufferView(mb *MemBuffer, pos int) *bytes.Buffer {
snap := mb.sharedSnapshot()
return bytes.NewBuffer(snap[pos:len(snap):len(snap)])
}
// currentSnapshotView returns buf[from:to] of the current window as a view of
// the shared prefix snapshot, extending the snapshot to cover [0:to) first.
// buf[:pos] is append-only until the window seals, so extension only ever
// appends stable bytes; earlier holders' slices are unaffected. Callers must
// hold the read lock (keeps buf and pos stable during extension).
func (logBuffer *LogBuffer) currentSnapshotView(from, to int) *bytes.Buffer {
logBuffer.curSnapMu.Lock()
if cap(logBuffer.curSnap) < to {
// First use in this window (or the rare window whose array outgrew the
// previous one): size to the window array so extensions never reallocate.
grown := make([]byte, len(logBuffer.curSnap), len(logBuffer.buf))
copy(grown, logBuffer.curSnap)
logBuffer.curSnap = grown
}
if len(logBuffer.curSnap) < to {
logBuffer.curSnap = append(logBuffer.curSnap, logBuffer.buf[len(logBuffer.curSnap):to]...)
}
snap := logBuffer.curSnap[:to]
logBuffer.curSnapMu.Unlock()
return bytes.NewBuffer(snap[from:to:to])
}
func readTs(buf []byte, pos int) (size int, ts int64, err error) {
// Bounds check for size field (overflow-safe)
if pos < 0 || pos > len(buf)-4 {
@@ -1011,129 +970,19 @@ func readTs(buf []byte, pos int) (size int, ts int64, err error) {
entryData := buf[pos+4 : pos+4+size]
// Read only LogEntry.ts_ns rather than unmarshaling the whole entry. This
// runs on every binary-search probe in ReadFromBuffer; a full proto.Unmarshal
// there allocates fresh slices for the data/key byte fields on each call, which
// dominated allocation churn under metadata-subscription fan-out.
ts, err = readTsNs(entryData)
// Use pooled LogEntry to avoid allocation on every call
logEntry := logEntryPool.Get().(*filer_pb.LogEntry)
defer func() {
resetLogEntry(logEntry)
logEntryPool.Put(logEntry)
}()
err = proto.Unmarshal(entryData, logEntry)
if err != nil {
return 0, 0, fmt.Errorf("corrupted log buffer at pos %d, size %d: %w", pos, size, err)
// Return error instead of failing fast
// This allows caller to handle corruption gracefully
return 0, 0, fmt.Errorf("corrupted log buffer: failed to unmarshal LogEntry at pos %d, size %d: %w", pos, size, err)
}
return size, ts, nil
}
// readTsNs scans a marshaled LogEntry and returns its ts_ns (field 1, varint)
// without decoding the data/key byte fields. Fields serialize in number order,
// so ts_ns is normally the first tag and this returns after one varint; the full
// scan keeps it correct for any field order. A missing field 1 means the proto3
// default, ts_ns == 0.
func readTsNs(entryData []byte) (tsNs int64, err error) {
for i := 0; i < len(entryData); {
tag, n := binary.Uvarint(entryData[i:])
if n <= 0 {
return 0, fmt.Errorf("bad field tag at %d", i)
}
i += n
fieldNum := tag >> 3
switch tag & 0x7 { // wire type
case 0: // varint
v, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return 0, fmt.Errorf("bad varint for field %d", fieldNum)
}
i += m
if fieldNum == 1 { // ts_ns
return int64(v), nil
}
case 1: // 64-bit
i += 8
case 2: // length-delimited: read length, skip payload without copying
l, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return 0, fmt.Errorf("bad length for field %d", fieldNum)
}
i += m
if l > uint64(len(entryData)-i) {
return 0, fmt.Errorf("field %d length %d overruns buffer", fieldNum, l)
}
i += int(l)
case 5: // 32-bit
i += 4
default:
return 0, fmt.Errorf("unknown wire type for field %d", fieldNum)
}
if i > len(entryData) {
return 0, fmt.Errorf("field %d overruns buffer", fieldNum)
}
}
return 0, nil
}
// unmarshalLogEntryAliased decodes a marshaled LogEntry into out, pointing the
// data and key fields at sub-slices of entryData instead of copying them. A full
// proto.Unmarshal allocates fresh slices for those byte fields on every entry
// (protobuf consumeBytesNoZero), which dominated allocation churn when many
// metadata subscribers each re-read the in-memory log window.
//
// The aliased data/key are only valid while entryData is, i.e. for the duration
// of the eachLogEntryFn callback. Callers must copy anything they retain past the
// callback; all current subscribers do (they re-decode data into their own event
// or hand it to a synchronous grpc Send).
func unmarshalLogEntryAliased(entryData []byte, out *filer_pb.LogEntry) error {
out.TsNs = 0
out.PartitionKeyHash = 0
out.Data = nil
out.Key = nil
out.Offset = 0
for i := 0; i < len(entryData); {
tag, n := binary.Uvarint(entryData[i:])
if n <= 0 {
return fmt.Errorf("bad field tag at %d", i)
}
i += n
fieldNum := tag >> 3
switch tag & 0x7 { // wire type
case 0: // varint: ts_ns / partition_key_hash / offset
v, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return fmt.Errorf("bad varint for field %d", fieldNum)
}
i += m
switch fieldNum {
case 1:
out.TsNs = int64(v)
case 2:
out.PartitionKeyHash = int32(v)
case 5:
out.Offset = int64(v)
}
case 2: // length-delimited: data / key, aliased not copied
l, m := binary.Uvarint(entryData[i:])
if m <= 0 {
return fmt.Errorf("bad length for field %d", fieldNum)
}
i += m
if l > uint64(len(entryData)-i) {
return fmt.Errorf("field %d length %d overruns buffer", fieldNum, l)
}
switch fieldNum {
case 3:
out.Data = entryData[i : i+int(l)]
case 4:
out.Key = entryData[i : i+int(l)]
}
i += int(l)
case 1: // 64-bit
i += 8
case 5: // 32-bit
i += 4
default:
return fmt.Errorf("unknown wire type for field %d", fieldNum)
}
if i > len(entryData) {
return fmt.Errorf("field %d overruns buffer", fieldNum)
}
}
return nil
return size, logEntry.TsNs, nil
}
@@ -118,7 +118,7 @@ func TestReadFromBufferCorruption(t *testing.T) {
// Try to read - should detect corruption
startPos := MessagePosition{Time: lb.startTime}
buf, offset, _, err := lb.ReadFromBuffer(startPos)
buf, offset, err := lb.ReadFromBuffer(startPos)
// Should return corruption error
if err == nil {
@@ -148,7 +148,7 @@ func TestFlushOffsetGap_ReproduceDataLoss(t *testing.T) {
for testOffset := int64(0); testOffset < currentOffset; testOffset += 10 {
// Try to read from buffer
requestPosition := NewMessagePositionFromOffset(testOffset)
buf, _, _, err := logBuffer.ReadFromBuffer(requestPosition)
buf, _, err := logBuffer.ReadFromBuffer(requestPosition)
isReadable := (buf != nil && len(buf.Bytes()) > 0) || err == ResumeFromDiskError
status := "OK"
@@ -50,7 +50,7 @@ func TestBufferQueryability(t *testing.T) {
// Test immediate queryability - read from buffer starting from beginning
startPosition := NewMessagePosition(0, 0) // Start from beginning
bufferCopy, batchIndex, _, err := logBuffer.ReadFromBuffer(startPosition)
bufferCopy, batchIndex, err := logBuffer.ReadFromBuffer(startPosition)
if err != nil {
t.Fatalf("ReadFromBuffer failed: %v", err)
@@ -131,7 +131,7 @@ func TestMultipleEntriesQueryability(t *testing.T) {
// Read all entries
startPosition := NewMessagePosition(0, 0)
bufferCopy, batchIndex, _, err := logBuffer.ReadFromBuffer(startPosition)
bufferCopy, batchIndex, err := logBuffer.ReadFromBuffer(startPosition)
if err != nil {
t.Fatalf("ReadFromBuffer failed: %v", err)
@@ -207,7 +207,7 @@ func TestSchemaRegistryScenario(t *testing.T) {
// Simulate the SQL query scenario - read from offset 0
startPosition := NewMessagePosition(0, 0)
bufferCopy, _, _, err := logBuffer.ReadFromBuffer(startPosition)
bufferCopy, _, err := logBuffer.ReadFromBuffer(startPosition)
if err != nil {
t.Fatalf("Schema registry scenario failed: %v", err)
@@ -268,7 +268,7 @@ func TestTimeBasedFirstReadBeforeEarliest(t *testing.T) {
// Start read 1ns before earliest memory, with offset sentinel (-2)
startPos := NewMessagePosition(baseTs.Add(-time.Nanosecond).UnixNano(), -2)
buf, _, _, err := logBuffer.ReadFromBuffer(startPos)
buf, _, err := logBuffer.ReadFromBuffer(startPos)
if err != nil {
t.Fatalf("ReadFromBuffer returned err: %v", err)
}
@@ -293,7 +293,7 @@ func TestEarliestTimeExactRead(t *testing.T) {
}
startPos := NewMessagePosition(ts.UnixNano(), -2)
buf, _, _, err := logBuffer.ReadFromBuffer(startPos)
buf, _, err := logBuffer.ReadFromBuffer(startPos)
if err != nil {
t.Fatalf("ReadFromBuffer err: %v", err)
}
+6 -6
View File
@@ -101,7 +101,7 @@ func TestReadFromBufferTimestampBased_AfterFlushReturnsNewerData(t *testing.T) {
}
}
buf, _, _, err := lb.ReadFromBuffer(NewMessagePosition(sealed.stopTime.UnixNano(), sealed.offset))
buf, _, err := lb.ReadFromBuffer(NewMessagePosition(sealed.stopTime.UnixNano(), sealed.offset))
if err != nil {
t.Fatalf("ReadFromBuffer returned error: %v", err)
}
@@ -200,7 +200,7 @@ func TestReadFromBuffer_OldOffsetReturnsResumeFromDiskError(t *testing.T) {
requestPosition := NewMessagePositionFromOffset(tt.requestedOffset)
// Try to read from the buffer
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
// Verify the error matches expectations
if tt.expectError != nil {
@@ -257,7 +257,7 @@ func TestReadFromBuffer_OldOffsetWithNoPrevBuffers(t *testing.T) {
// Before the fix, this would return (nil, offset, nil) causing an infinite wait
// After the fix, this should return ResumeFromDiskError
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
t.Logf("DEBUG: ReadFromBuffer returned: buf=%v, batchIdx=%d, err=%v", buf != nil, batchIdx, err)
t.Logf("DEBUG: Buffer state: bufferStartOffset=%d, offset=%d, pos=%d",
@@ -295,7 +295,7 @@ func TestReadFromBuffer_EmptyBufferAtCurrentOffset(t *testing.T) {
// BUG: Without fix, this returns empty buffer instead of checking disk
// FIX: Should return ResumeFromDiskError because buffer is empty (pos=0) despite valid range
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
t.Logf("DEBUG: ReadFromBuffer returned: buf=%v, batchIdx=%d, err=%v", buf != nil, batchIdx, err)
t.Logf("DEBUG: Buffer state: bufferStartOffset=%d, offset=%d, pos=%d",
@@ -362,7 +362,7 @@ func TestReadFromBuffer_OffsetRanges(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
requestPosition := NewMessagePositionFromOffset(tc.requestedOffset)
_, _, _, err := lb.ReadFromBuffer(requestPosition)
_, _, err := lb.ReadFromBuffer(requestPosition)
if tc.expectedError != nil {
if err != tc.expectedError {
@@ -424,7 +424,7 @@ func TestReadFromBuffer_InitializedFromDisk(t *testing.T) {
// Schema Registry tries to read offset 0 (should be on disk)
requestPosition := NewMessagePositionFromOffset(0)
buf, batchIdx, _, err := lb.ReadFromBuffer(requestPosition)
buf, batchIdx, err := lb.ReadFromBuffer(requestPosition)
t.Logf("After writing new message:")
t.Logf(" bufferStartOffset=%d, offset=%d, pos=%d", lb.bufferStartOffset, lb.offset, lb.pos)
+14 -18
View File
@@ -6,6 +6,8 @@ import (
"fmt"
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
@@ -101,7 +103,6 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
// loop through all messages
var bytesBuf *bytes.Buffer
var bytesBufPooled bool
var batchIndex int64
lastReadPosition = startPosition
var entryCounter int64
@@ -114,7 +115,7 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
// responsive 250ms cadence resumes for active readers.
caughtUpToDiskHead := false
defer func() {
if bytesBuf != nil && bytesBufPooled {
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
}
// println("LoopProcessLogData", readerName, "sent messages total", entryCounter)
@@ -122,11 +123,10 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
for {
if bytesBuf != nil && bytesBufPooled {
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
bytesBuf = nil // keep the deferred release from double-freeing if ReadFromBuffer panics
}
bytesBuf, batchIndex, bytesBufPooled, err = logBuffer.ReadFromBuffer(lastReadPosition)
bytesBuf, batchIndex, err = logBuffer.ReadFromBuffer(lastReadPosition)
if err == ResumeFromDiskError {
// Try to read from disk if readFromDiskFn is available
if logBuffer.ReadFromDiskFn != nil {
@@ -150,11 +150,11 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
// HasData() and ReadFromBuffer lock separately, so a racing write can make
// HasData() see data the empty-buffer read missed. Re-read; only bail if the
// position is genuinely behind the in-memory window (flushed to disk).
reBuf, _, rePooled, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
reBuf, _, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
if reErr == ResumeFromDiskError {
return lastReadPosition, isDone, ResumeFromDiskError
}
if reBuf != nil && rePooled {
if reBuf != nil {
logBuffer.ReleaseMemory(reBuf)
}
continue
@@ -261,8 +261,7 @@ func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition
entryData := buf[pos+4 : pos+4+int(size)]
logEntry := &filer_pb.LogEntry{}
// data/key alias entryData; valid only within eachLogDataFn below.
if err = unmarshalLogEntryAliased(entryData, logEntry); err != nil {
if err = proto.Unmarshal(entryData, logEntry); err != nil {
glog.Errorf("unexpected unmarshal mq_pb.Message: %v", err)
pos += 4 + int(size)
continue
@@ -317,14 +316,13 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
// loop through all messages
var bytesBuf *bytes.Buffer
var bytesBufPooled bool
var offset int64
lastReadPosition = startPosition
var entryCounter int64
// See LoopProcessLogData for the caughtUpToDiskHead invariant.
caughtUpToDiskHead := false
defer func() {
if bytesBuf != nil && bytesBufPooled {
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
}
// println("LoopProcessLogDataWithOffset", readerName, "sent messages total", entryCounter)
@@ -338,11 +336,10 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
return
}
if bytesBuf != nil && bytesBufPooled {
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
bytesBuf = nil // keep the deferred release from double-freeing if ReadFromBuffer panics
}
bytesBuf, offset, bytesBufPooled, err = logBuffer.ReadFromBuffer(lastReadPosition)
bytesBuf, offset, err = logBuffer.ReadFromBuffer(lastReadPosition)
glog.V(4).Infof("ReadFromBuffer for %s returned bytesBuf=%v, offset=%d, err=%v", readerName, bytesBuf != nil, offset, err)
// Check for buffer corruption error before other error handling
@@ -378,11 +375,11 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
// HasData() and ReadFromBuffer lock separately, so a racing write can make
// HasData() see data the empty-buffer read missed. Re-read; only bail if the
// position is genuinely behind the in-memory window (flushed to disk).
reBuf, _, rePooled, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
reBuf, _, reErr := logBuffer.ReadFromBuffer(lastReadPosition)
if reErr == ResumeFromDiskError {
return lastReadPosition, isDone, ResumeFromDiskError
}
if reBuf != nil && rePooled {
if reBuf != nil {
logBuffer.ReleaseMemory(reBuf)
}
continue
@@ -526,8 +523,7 @@ func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, star
entryData := buf[pos+4 : pos+4+int(size)]
logEntry := &filer_pb.LogEntry{}
// data/key alias entryData; valid only within eachLogDataFn below.
if err = unmarshalLogEntryAliased(entryData, logEntry); err != nil {
if err = proto.Unmarshal(entryData, logEntry); err != nil {
glog.Errorf("unexpected unmarshal mq_pb.Message: %v", err)
pos += 4 + int(size)
continue
-230
View File
@@ -1,230 +0,0 @@
package log_buffer
import (
"bytes"
"math"
"math/rand"
"testing"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// readTsNs must return exactly what a full proto.Unmarshal would put in TsNs,
// for every field combination, without decoding data/key.
func TestReadTsNsMatchesUnmarshal(t *testing.T) {
cases := []*filer_pb.LogEntry{
{}, // all defaults: ts_ns absent on the wire => 0
{TsNs: 1}, // minimal
{TsNs: 1783396413597780505}, // realistic nanosecond timestamp
{TsNs: math.MaxInt64}, // 9-byte varint
{TsNs: -1}, // negative int64 => 10-byte varint
{TsNs: math.MinInt64}, // extreme negative
{TsNs: 42, PartitionKeyHash: 7}, // ts followed by another varint field
{TsNs: 12345, Data: []byte("some-metadata-event-payload"), Key: []byte("/buckets/pvc-x/1.log")},
{TsNs: 99, Data: make([]byte, 64*1024), Key: []byte("k"), Offset: 555}, // large data, all fields
{Data: []byte("no-ts"), Key: []byte("k"), Offset: 9}, // ts_ns == 0 with other fields present
}
for i, e := range cases {
data, err := proto.Marshal(e)
if err != nil {
t.Fatalf("case %d marshal: %v", i, err)
}
got, err := readTsNs(data)
if err != nil {
t.Fatalf("case %d readTsNs: %v", i, err)
}
if got != e.TsNs {
t.Errorf("case %d: readTsNs=%d want %d", i, got, e.TsNs)
}
}
}
// Fuzz against proto.Unmarshal with randomized entries.
func TestReadTsNsFuzz(t *testing.T) {
r := rand.New(rand.NewSource(1))
for i := 0; i < 5000; i++ {
e := &filer_pb.LogEntry{
TsNs: r.Int63() - r.Int63(),
PartitionKeyHash: r.Int31(),
Offset: r.Int63(),
}
if r.Intn(2) == 0 {
e.Data = make([]byte, r.Intn(300))
r.Read(e.Data)
}
if r.Intn(2) == 0 {
e.Key = make([]byte, r.Intn(64))
r.Read(e.Key)
}
data, err := proto.Marshal(e)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var want filer_pb.LogEntry
if err := proto.Unmarshal(data, &want); err != nil {
t.Fatalf("unmarshal: %v", err)
}
got, err := readTsNs(data)
if err != nil {
t.Fatalf("readTsNs iter %d: %v", i, err)
}
if got != want.TsNs {
t.Fatalf("iter %d: readTsNs=%d want %d", i, got, want.TsNs)
}
}
}
// readTsNs must not panic and must report an error on truncated/garbage input.
func TestReadTsNsCorrupted(t *testing.T) {
inputs := [][]byte{
{0x08}, // ts_ns tag with no value
{0x1a, 0xff, 0xff, 0xff}, // data field, length overruns buffer
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}, // overlong tag
}
for i, in := range inputs {
if _, err := readTsNs(in); err == nil {
t.Errorf("input %d: expected error, got nil", i)
}
}
}
// unmarshalLogEntryAliased must produce the same fields as proto.Unmarshal.
func TestUnmarshalLogEntryAliasedMatchesUnmarshal(t *testing.T) {
r := rand.New(rand.NewSource(2))
for i := 0; i < 5000; i++ {
e := &filer_pb.LogEntry{
TsNs: r.Int63() - r.Int63(),
PartitionKeyHash: r.Int31() - r.Int31(),
Offset: r.Int63() - r.Int63(),
}
if r.Intn(2) == 0 {
e.Data = make([]byte, r.Intn(4096))
r.Read(e.Data)
}
if r.Intn(2) == 0 {
e.Key = make([]byte, r.Intn(128))
r.Read(e.Key)
}
data, err := proto.Marshal(e)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var want, got filer_pb.LogEntry
if err := proto.Unmarshal(data, &want); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if err := unmarshalLogEntryAliased(data, &got); err != nil {
t.Fatalf("aliased iter %d: %v", i, err)
}
if got.TsNs != want.TsNs || got.PartitionKeyHash != want.PartitionKeyHash ||
got.Offset != want.Offset || !bytes.Equal(got.Data, want.Data) || !bytes.Equal(got.Key, want.Key) {
t.Fatalf("iter %d mismatch:\n got=%+v\nwant=%+v", i, &got, &want)
}
}
}
// The decoded data/key must point into the source buffer, not a copy.
func TestUnmarshalLogEntryAliasedAliases(t *testing.T) {
data, err := proto.Marshal(&filer_pb.LogEntry{TsNs: 5, Data: []byte("payload"), Key: []byte("path")})
if err != nil {
t.Fatal(err)
}
var out filer_pb.LogEntry
if err := unmarshalLogEntryAliased(data, &out); err != nil {
t.Fatal(err)
}
if string(out.Data) != "payload" || string(out.Key) != "path" {
t.Fatalf("decoded data=%q key=%q", out.Data, out.Key)
}
for i := range data { // mutate source; an alias must observe it, a copy must not
data[i] ^= 0xFF
}
if string(out.Data) == "payload" || string(out.Key) == "path" {
t.Fatal("data/key were copied, expected an alias into the source buffer")
}
}
// sampleEntryData returns a marshaled LogEntry whose Data is a realistic
// marshaled metadata event, as delivered on the subscribe path.
func sampleEntryData(tb testing.TB) []byte {
event := &filer_pb.SubscribeMetadataResponse{
Directory: "/buckets/pvc-bf458866-0413-4cca-99c6-3b7386a80855",
EventNotification: &filer_pb.EventNotification{
NewEntry: &filer_pb.Entry{
Name: "object-000123",
Attributes: &filer_pb.FuseAttributes{FileSize: 4096, Mtime: 1783396413},
Chunks: []*filer_pb.FileChunk{
{FileId: "3,01637037d6", Size: 4096, Fid: &filer_pb.FileId{VolumeId: 3, FileKey: 23283, Cookie: 2015}},
},
},
},
}
payload, err := proto.Marshal(event)
if err != nil {
tb.Fatal(err)
}
data, err := proto.Marshal(&filer_pb.LogEntry{
TsNs: 1783396413597780505, PartitionKeyHash: 12345, Offset: 2013258,
Key: []byte("/buckets/pvc-bf458866/object-000123"), Data: payload,
})
if err != nil {
tb.Fatal(err)
}
return data
}
// Per-entry decode cost on the delivery path: the old full unmarshal copies the
// data/key byte fields; the aliased decode does not. The delta is what the fix
// saves for every entry a subscriber reads (and, for non-matching entries a
// subscriber filters out, the whole saving with nothing decoded downstream).
func BenchmarkLogEntryDecodeCopy(b *testing.B) {
data := sampleEntryData(b)
var out filer_pb.LogEntry
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := proto.Unmarshal(data, &out); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkLogEntryDecodeAlias(b *testing.B) {
data := sampleEntryData(b)
var out filer_pb.LogEntry
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := unmarshalLogEntryAliased(data, &out); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkReadTs(b *testing.B) {
e := &filer_pb.LogEntry{
TsNs: 1783396413597780505,
PartitionKeyHash: 12345,
Data: make([]byte, 4*1024), // typical metadata event payload
Key: []byte("/buckets/pvc-bf458866/1.log"),
Offset: 2013258,
}
data, err := proto.Marshal(e)
if err != nil {
b.Fatal(err)
}
buf := make([]byte, 4+len(data))
util.Uint32toBytes(buf, uint32(len(data)))
copy(buf[4:], data)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, _, err := readTs(buf, 0); err != nil {
b.Fatal(err)
}
}
}
-22
View File
@@ -2,7 +2,6 @@ package log_buffer
import (
"fmt"
"sync"
"time"
)
@@ -13,25 +12,6 @@ type MemBuffer struct {
stopTime time.Time
startOffset int64 // First offset in this buffer
offset int64 // Last offset in this buffer (endOffset)
// snapshot is a GC-owned copy of buf[:size] shared by all readers of this
// sealed window, so N subscribers reading the same window cost one copy
// instead of N pooled copies. Created lazily by the first reader; travels
// with the window when SealBuffer shifts slots. Immutable once created.
snapMu sync.Mutex
snapshot []byte
}
// sharedSnapshot returns the shared read-only copy of this sealed window,
// creating it on first use. Callers must hold the LogBuffer read lock, which
// keeps buf stable (SealBuffer mutates slots only under the write lock).
func (mb *MemBuffer) sharedSnapshot() []byte {
mb.snapMu.Lock()
defer mb.snapMu.Unlock()
if mb.snapshot == nil {
mb.snapshot = append([]byte(nil), mb.buf[:mb.size]...)
}
return mb.snapshot
}
type SealedBuffers struct {
@@ -61,7 +41,6 @@ func (sbs *SealedBuffers) SealBuffer(startTime, stopTime time.Time, buf []byte,
sbs.buffers[i].stopTime = sbs.buffers[i+1].stopTime
sbs.buffers[i].startOffset = sbs.buffers[i+1].startOffset
sbs.buffers[i].offset = sbs.buffers[i+1].offset
sbs.buffers[i].snapshot = sbs.buffers[i+1].snapshot // snapshot follows its window
}
sbs.buffers[size-1].buf = buf
sbs.buffers[size-1].size = pos
@@ -69,7 +48,6 @@ func (sbs *SealedBuffers) SealBuffer(startTime, stopTime time.Time, buf []byte,
sbs.buffers[size-1].stopTime = stopTime
sbs.buffers[size-1].startOffset = startOffset
sbs.buffers[size-1].offset = endOffset
sbs.buffers[size-1].snapshot = nil
return oldBuf
}
@@ -1,275 +0,0 @@
package log_buffer
import (
"fmt"
"runtime/debug"
"sync"
"testing"
"time"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
func addEntries(tb testing.TB, lb *LogBuffer, n int, payloadSize int, tag string) {
payload := make([]byte, payloadSize)
for i := 0; i < n; i++ {
key := []byte(fmt.Sprintf("/%s/%d", tag, i))
if err := lb.AddDataToBuffer(key, payload, time.Now().UnixNano()); err != nil {
tb.Fatal(err)
}
}
}
// Sealed-window reads must hand every reader the same shared snapshot rather
// than a fresh copy each.
func TestSealedReadsShareOneSnapshot(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 10, 1024, "a")
lb.ForceFlush() // seal the window
addEntries(t, lb, 1, 1024, "b")
pos := NewMessagePosition(1, -2) // far in the past => sealed window hit
buf1, _, pooled1, err1 := lb.ReadFromBuffer(pos)
buf2, _, pooled2, err2 := lb.ReadFromBuffer(pos)
if err1 != nil || err2 != nil {
t.Fatalf("read errors: %v %v", err1, err2)
}
if buf1 == nil || buf2 == nil {
t.Fatal("expected sealed data in memory")
}
if pooled1 || pooled2 {
t.Fatalf("sealed reads should not be pooled copies: %v %v", pooled1, pooled2)
}
b1, b2 := buf1.Bytes(), buf2.Bytes()
if len(b1) == 0 || len(b1) != len(b2) {
t.Fatalf("unexpected lengths %d %d", len(b1), len(b2))
}
if &b1[0] != &b2[0] {
t.Fatal("sealed reads made independent copies; expected one shared snapshot")
}
}
// A shared snapshot must stay intact after its window rotates out and the
// backing array is recycled and overwritten by new writes.
func TestSharedSnapshotSurvivesRecycle(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 5, 2048, "keep")
lb.ForceFlush()
pos := NewMessagePosition(1, -2)
buf, _, pooled, err := lb.ReadFromBuffer(pos)
if err != nil || buf == nil || pooled {
t.Fatalf("expected shared sealed read, got buf=%v pooled=%v err=%v", buf != nil, pooled, err)
}
before := append([]byte(nil), buf.Bytes()...)
// Rotate the sealed window all the way out so its array is recycled and
// overwritten with different content.
for i := 0; i < PreviousBufferCount+1; i++ {
addEntries(t, lb, 5, 2048, "overwrite")
lb.ForceFlush()
}
addEntries(t, lb, 5, 2048, "overwrite")
if string(before) != string(buf.Bytes()) {
t.Fatal("shared snapshot content changed after its window was recycled")
}
}
// Race test: concurrent lagging readers against a writer that keeps sealing
// and recycling windows. Every delivered entry must unmarshal cleanly with the
// expected payload — corruption here means a reader saw recycled bytes.
func TestSharedSnapshotConcurrentIntegrity(t *testing.T) {
// The writer below is deliberately unthrottled, so transient marshal garbage
// scales with host speed; on linux/386 a fast runner can hit the 4GB
// address-space ceiling. Cap the heap so the GC paces the writer instead.
prevLimit := debug.SetMemoryLimit(1 << 30)
defer debug.SetMemoryLimit(prevLimit)
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
const payloadByte = 0x5A
payload := make([]byte, 8*1024)
for i := range payload {
payload[i] = payloadByte
}
var stop sync.WaitGroup
done := make(chan struct{})
stop.Add(1)
go func() { // writer: fill and seal aggressively so arrays recycle under the readers
defer stop.Done()
for i := 0; ; i++ {
select {
case <-done:
return
default:
}
if err := lb.AddDataToBuffer([]byte(fmt.Sprintf("/k/%d", i)), payload, time.Now().UnixNano()); err != nil {
t.Error(err)
return
}
if i%200 == 0 {
lb.ForceFlush()
}
}
}()
var readers sync.WaitGroup
errCh := make(chan error, 16)
for r := 0; r < 8; r++ {
readers.Add(1)
go func(r int) {
defer readers.Done()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
start := NewMessagePosition(time.Now().Add(-500*time.Millisecond).UnixNano(), -2)
lb.LoopProcessLogData(fmt.Sprintf("r%d", r), start, 0,
func() bool { return time.Now().Before(deadline) },
func(le *filer_pb.LogEntry) (bool, error) {
if len(le.Data) != len(payload) {
err := fmt.Errorf("payload length %d, want %d", len(le.Data), len(payload))
select {
case errCh <- err:
default:
}
return true, err
}
for _, b := range le.Data {
if b != payloadByte {
err := fmt.Errorf("corrupted payload byte %x", b)
select {
case errCh <- err:
default:
}
return true, err
}
}
return false, nil
})
}
}(r)
}
readers.Wait()
close(done)
stop.Wait()
select {
case err := <-errCh:
t.Fatal(err)
default:
}
}
// Current-window reads must share the prefix snapshot: two behind-readers get
// views of the same backing array, and the view content must stay intact while
// the writer keeps appending and eventually seals and recycles the window.
func TestCurrentWindowPrefixSharing(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 8, 1024, "cur")
pos := NewMessagePosition(1, -2) // behind => full current-window read
buf1, _, pooled1, err1 := lb.ReadFromBuffer(pos)
buf2, _, pooled2, err2 := lb.ReadFromBuffer(pos)
if err1 != nil || err2 != nil || buf1 == nil || buf2 == nil {
t.Fatalf("reads: %v %v %v %v", buf1 != nil, err1, buf2 != nil, err2)
}
if pooled1 || pooled2 {
t.Fatalf("current-window behind-reads should be shared, got pooled %v %v", pooled1, pooled2)
}
b1, b2 := buf1.Bytes(), buf2.Bytes()
if len(b1) == 0 || len(b1) != len(b2) || &b1[0] != &b2[0] {
t.Fatalf("expected one shared prefix snapshot, lens %d %d", len(b1), len(b2))
}
before := append([]byte(nil), b1...)
// Keep appending: the prefix must be extended, not reallocated or mutated.
addEntries(t, lb, 8, 1024, "more")
buf3, _, _, err3 := lb.ReadFromBuffer(pos)
if err3 != nil || buf3 == nil {
t.Fatalf("read3: %v %v", buf3 != nil, err3)
}
if len(buf3.Bytes()) <= len(before) {
t.Fatalf("extended read %d should exceed first read %d", len(buf3.Bytes()), len(before))
}
if string(buf3.Bytes()[:len(before)]) != string(before) {
t.Fatal("prefix changed when the snapshot was extended")
}
// Seal + rotate the window fully out; earlier views must stay intact.
for i := 0; i < PreviousBufferCount+1; i++ {
lb.ForceFlush()
addEntries(t, lb, 4, 1024, "rotate")
}
if string(b1) != string(before) {
t.Fatal("shared current-window view changed after seal and recycle")
}
}
// A sealed window whose prefix snapshot was fully extended must reuse it
// rather than re-copying on the first sealed read.
func TestSealHandsOffCompleteSnapshot(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 6, 512, "h")
pos := NewMessagePosition(1, -2)
buf1, _, _, err := lb.ReadFromBuffer(pos) // extends prefix snapshot to full window
if err != nil || buf1 == nil {
t.Fatalf("read1: %v %v", buf1 != nil, err)
}
lb.ForceFlush()
addEntries(t, lb, 1, 512, "next")
buf2, _, pooled, err := lb.ReadFromBuffer(pos) // sealed read of the same window
if err != nil || buf2 == nil || pooled {
t.Fatalf("read2: buf=%v pooled=%v err=%v", buf2 != nil, pooled, err)
}
b1, b2 := buf1.Bytes(), buf2.Bytes()
if len(b1) == 0 || len(b1) > len(b2) || &b1[0] != &b2[0] {
t.Fatalf("sealed read should reuse the handed-off snapshot (lens %d %d)", len(b1), len(b2))
}
}
// Sanity: sealed-read content must byte-match what a proto round-trip expects.
func TestSharedSnapshotContentMatches(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, func(*LogBuffer, time.Time, time.Time, []byte, int64, int64) {}, nil, nil)
defer lb.ShutdownLogBuffer()
addEntries(t, lb, 3, 512, "x")
lb.ForceFlush()
buf, _, _, err := lb.ReadFromBuffer(NewMessagePosition(1, -2))
if err != nil || buf == nil {
t.Fatalf("read: buf=%v err=%v", buf != nil, err)
}
data := buf.Bytes()
count := 0
for pos := 0; pos+4 < len(data); {
size, _, err := readTs(data, pos)
if err != nil {
t.Fatalf("entry %d: %v", count, err)
}
var le filer_pb.LogEntry
if err := proto.Unmarshal(data[pos+4:pos+4+size], &le); err != nil {
t.Fatalf("entry %d unmarshal: %v", count, err)
}
if want := fmt.Sprintf("/x/%d", count); string(le.Key) != want {
t.Fatalf("entry %d key %q, want %q", count, le.Key, want)
}
pos += 4 + size
count++
}
if count != 3 {
t.Fatalf("read %d entries, want 3", count)
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ import (
var (
MAJOR_VERSION = int32(4)
MINOR_VERSION = int32(39)
MINOR_VERSION = int32(38)
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
VERSION = util.SizeLimit + " " + VERSION_NUMBER
COMMIT = ""
+5 -48
View File
@@ -723,23 +723,19 @@ func (h *VolumeBalanceHandler) executeSingleMove(
return err
}
execErr := h.checkMoveStillValid(execCtx, request.GetClusterContext().GetMasterGrpcAddresses(), params.VolumeId, params.Sources[0].Node, params.Targets[0].Node)
if execErr == nil {
execErr = task.Execute(execCtx, params)
}
if execErr != nil {
if err := task.Execute(execCtx, params); err != nil {
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId,
JobType: request.Job.JobType,
State: plugin_pb.JobState_JOB_STATE_FAILED,
ProgressPercent: 100,
Stage: "failed",
Message: execErr.Error(),
Message: err.Error(),
Activities: []*plugin_pb.ActivityEvent{
pluginworker.BuildExecutorActivity("failed", execErr.Error()),
pluginworker.BuildExecutorActivity("failed", err.Error()),
},
})
return execErr
return err
}
sourceNode := params.Sources[0].Node
@@ -770,41 +766,6 @@ func (h *VolumeBalanceHandler) executeSingleMove(
})
}
// checkMoveStillValid re-checks a planned move against the master's live
// view right before executing it. The admin lock is released between
// detection and execution, so the plan can go stale: the volume may have
// left the source, or the target may have gained a replica that the copy
// would overwrite and the source delete would then reduce to a single copy.
// Without master addresses (older admin) the check is skipped and the move
// relies on the task's own execution-time guards.
func (h *VolumeBalanceHandler) checkMoveStillValid(ctx context.Context, masterAddresses []string, volumeID uint32, sourceNode, targetNode string) error {
if len(masterAddresses) == 0 {
glog.Warningf("volume balance: no master addresses in cluster context, skipping pre-move check for volume %d", volumeID)
return nil
}
locations, err := pluginworker.LookupVolumeLocations(ctx, masterAddresses, h.grpcDialOption, volumeID)
if err != nil {
return fmt.Errorf("pre-move check for volume %d: %w", volumeID, err)
}
return checkMovePreconditions(locations, volumeID, sourceNode, targetNode)
}
func checkMovePreconditions(locations []string, volumeID uint32, sourceNode, targetNode string) error {
sourceFound := false
for _, location := range locations {
switch strings.TrimSpace(location) {
case targetNode:
return fmt.Errorf("stale move: volume %d already has a replica on target %s", volumeID, targetNode)
case sourceNode:
sourceFound = true
}
}
if !sourceFound {
return fmt.Errorf("stale move: volume %d is no longer on source %s", volumeID, sourceNode)
}
return nil
}
// executeBatchMoves runs multiple volume moves concurrently within a single job.
func (h *VolumeBalanceHandler) executeBatchMoves(
ctx context.Context,
@@ -920,7 +881,6 @@ func (h *VolumeBalanceHandler) executeBatchMoves(
sem := make(chan struct{}, maxConcurrent)
results := make(chan moveResult, totalMoves)
masterAddresses := request.GetClusterContext().GetMasterGrpcAddresses()
for i, move := range moves {
sem <- struct{}{} // acquire slot
@@ -939,10 +899,7 @@ func (h *VolumeBalanceHandler) executeBatchMoves(
})
moveParams := buildMoveTaskParams(m, bp)
err := h.checkMoveStillValid(batchCtx, masterAddresses, m.VolumeId, m.SourceNode, m.TargetNode)
if err == nil {
err = task.Execute(batchCtx, moveParams)
}
err := task.Execute(batchCtx, moveParams)
results <- moveResult{
index: idx,
volumeID: m.VolumeId,
@@ -503,9 +503,6 @@ func TestExecuteDispatchesBatchPath(t *testing.T) {
err = handler.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: job,
}, sender)
if err != nil {
t.Fatalf("handler.Execute: %v", err)
}
// Expect an error since no real volume servers exist
// But verify the batch path was taken by checking the assigned message
@@ -795,30 +792,3 @@ func (r *recordingDetectionSender) SendActivity(event *plugin_pb.ActivityEvent)
}
return nil
}
func TestCheckMovePreconditions(t *testing.T) {
tests := []struct {
name string
locations []string
wantErr string
}{
{"valid move", []string{"10.0.0.1:8080", "10.0.0.3:8080"}, ""},
{"volume left the source", []string{"10.0.0.3:8080"}, "no longer on source"},
{"volume gone entirely", nil, "no longer on source"},
{"target already has a replica", []string{"10.0.0.1:8080", "10.0.0.2:8080"}, "already has a replica on target"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := checkMovePreconditions(tt.locations, 5, "10.0.0.1:8080", "10.0.0.2:8080")
if tt.wantErr == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("expected error containing %q, got %v", tt.wantErr, err)
}
})
}
}