mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
604d391012 | ||
|
|
689e98ea4c | ||
|
|
f905b33f19 | ||
|
|
cb958290c8 | ||
|
|
3d076dfcdf | ||
|
|
12ef22477a | ||
|
|
bd9e9a37c2 | ||
|
|
7d1ad72e74 | ||
|
|
89dbcb44c7 | ||
|
|
276be51d04 | ||
|
|
760f88e294 | ||
|
|
46b10efcce | ||
|
|
a963c1309c | ||
|
|
3836311f8f | ||
|
|
5a9287642f | ||
|
|
f9b494c576 | ||
|
|
db0ec9e9b3 | ||
|
|
207aa69a9d | ||
|
|
036d1117d2 | ||
|
|
7092edfb06 | ||
|
|
4ff3147ee5 | ||
|
|
0ea67a4438 | ||
|
|
663af6fccb | ||
|
|
63ab6c6190 | ||
|
|
a7cc8fb767 | ||
|
|
ef0967bead | ||
|
|
e7cbfdcc44 | ||
|
|
5b7e2d9e9e | ||
|
|
889af96779 | ||
|
|
6b2ad112a8 | ||
|
|
16412c374a | ||
|
|
efcee4a186 | ||
|
|
e6aed012f8 | ||
|
|
4cf028f683 | ||
|
|
a9fda6b50f | ||
|
|
f6b130f61c | ||
|
|
3880e7ee5a | ||
|
|
c7fc40c76c | ||
|
|
c812a37c83 | ||
|
|
6c54935723 | ||
|
|
50ac729a71 | ||
|
|
40a95a8ef5 |
No files matched your search
@@ -44,7 +44,7 @@ jobs:
|
||||
- name: Run Client Unit Tests
|
||||
working-directory: other/java/client
|
||||
run: |
|
||||
mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest
|
||||
mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest,FilerJwtTest
|
||||
|
||||
- name: Run HDFS3 Configuration Tests
|
||||
working-directory: other/java/hdfs3
|
||||
|
||||
@@ -169,7 +169,10 @@ func Run(args []string) int {
|
||||
}
|
||||
|
||||
func runWithOptions(opts *Options) bool {
|
||||
util.LoadConfiguration("security", false)
|
||||
if err := util.LoadSecurityConfigurationOrError(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// Validate options.
|
||||
if opts.MasterAddr == "" {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/peterh/liner"
|
||||
"github.com/seaweedfs/seaweedfs/weed/query/engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/grace"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/sqlutil"
|
||||
@@ -106,6 +107,11 @@ func Run(args []string) int {
|
||||
}
|
||||
|
||||
func runWithOptions(opts *Options) bool {
|
||||
if err := util.LoadSecurityConfigurationOrError(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// Initialize SQL engine with master address for service discovery.
|
||||
sqlEngine := engine.NewSQLEngine(opts.Master)
|
||||
|
||||
|
||||
@@ -129,12 +129,15 @@ recursive, and the folder may hold files SeaweedFS never saw.
|
||||
|
||||
An access token and its refresh token both live about a year. The client
|
||||
refreshes the access token when it expires or when the API answers 401, and
|
||||
uses the rotated refresh token Yandex returns. The refreshed token is kept in
|
||||
memory only: a client cannot write the configuration back to the filer. A
|
||||
restart within the token's lifetime keeps working with the stored refresh
|
||||
token; once Yandex rejects it (`invalid_grant`), issue a new one with
|
||||
`-yandex.oauth_url` and `-yandex.code` above. Yandex recommends refreshing a
|
||||
long-lived token every three months.
|
||||
uses the new refresh token Yandex returns. The refreshed token is kept in
|
||||
memory only: a client cannot write the configuration back to the filer, so
|
||||
every restart, and every other process using the same configuration, starts
|
||||
again from the stored refresh token. Yandex does not document whether that
|
||||
token stays valid once a newer one has been issued, so after a refresh a
|
||||
restart can fail with `invalid_grant`. Then, or when the stored token nears
|
||||
the end of its year, issue a new one with `-yandex.oauth_url` and
|
||||
`-yandex.code` above. Yandex recommends refreshing a long-lived token every
|
||||
three months.
|
||||
|
||||
## Not covered
|
||||
|
||||
|
||||
@@ -384,6 +384,7 @@ require (
|
||||
github.com/pierrre/geohash v1.0.0 // indirect
|
||||
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
|
||||
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
|
||||
github.com/pingcap/goleveldb v0.0.0-20191226122134-f82aafb29989 // indirect
|
||||
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
|
||||
github.com/pingcap/log v1.1.1-0.20221110025148-ca232912c9f3 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.55"
|
||||
appVersion: "4.56"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.55.0
|
||||
version: 4.56.0
|
||||
+1060
-1031
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 54 KiB |
@@ -42,12 +42,26 @@ public class FileChunkManifest {
|
||||
// avoid deprecated chunk.getFileId()
|
||||
resolvedChunks.add(t.toBuilder().setFileId(FilerClient.toFileId(t.getFid())).build());
|
||||
}
|
||||
dataChunks.addAll(resolveChunkManifest(filerClient, resolvedChunks));
|
||||
dataChunks.addAll(resolveChunkManifest(filerClient, cutToManifestSpan(chunk, resolvedChunks)));
|
||||
}
|
||||
|
||||
return dataChunks;
|
||||
}
|
||||
|
||||
// A truncate may have shortened a manifest and left the chunks it holds whole.
|
||||
static List<FilerProto.FileChunk> cutToManifestSpan(FilerProto.FileChunk manifest, List<FilerProto.FileChunk> held) {
|
||||
long end = manifest.getOffset() + manifest.getSize();
|
||||
List<FilerProto.FileChunk> cut = new ArrayList<>(held.size());
|
||||
for (FilerProto.FileChunk chunk : held) {
|
||||
if (chunk.getOffset() + chunk.getSize() <= end) {
|
||||
cut.add(chunk);
|
||||
} else if (chunk.getOffset() < end) {
|
||||
cut.add(chunk.toBuilder().setSize(end - chunk.getOffset()).build());
|
||||
}
|
||||
}
|
||||
return cut;
|
||||
}
|
||||
|
||||
private static byte[] fetchChunk(final FilerClient filerClient, FilerProto.FileChunk chunk) throws IOException {
|
||||
|
||||
String vid = "" + chunk.getFid().getVolumeId();
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package seaweedfs.client;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.Base64;
|
||||
|
||||
// Credentials for a filer's own HTTP port: [filer.basic_auth], [jwt.filer_signing] and
|
||||
// [jwt.filer_signing.read]. Each FilerClient starts from its own copy of the security.toml values.
|
||||
public final class FilerCredentials {
|
||||
|
||||
private static final long DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS = 10;
|
||||
private static final long DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS = 60;
|
||||
|
||||
private volatile String basicAuthUser = "";
|
||||
private volatile String basicAuthPassword = "";
|
||||
private volatile String basicAuthHeaderValue;
|
||||
private volatile String signingKey = "";
|
||||
private volatile long signingExpiresAfterSeconds = DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS;
|
||||
private volatile String readSigningKey = "";
|
||||
private volatile long readSigningExpiresAfterSeconds = DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS;
|
||||
|
||||
public FilerCredentials() {
|
||||
}
|
||||
|
||||
public FilerCredentials(FilerCredentials other) {
|
||||
synchronized (other) {
|
||||
basicAuthUser = other.basicAuthUser;
|
||||
basicAuthPassword = other.basicAuthPassword;
|
||||
basicAuthHeaderValue = other.basicAuthHeaderValue;
|
||||
signingKey = other.signingKey;
|
||||
signingExpiresAfterSeconds = other.signingExpiresAfterSeconds;
|
||||
readSigningKey = other.readSigningKey;
|
||||
readSigningExpiresAfterSeconds = other.readSigningExpiresAfterSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
// A null argument keeps the current value. Like the filer, an empty password turns
|
||||
// Basic Auth off and an empty user is allowed.
|
||||
public synchronized void setBasicAuth(String user, String password) {
|
||||
if (user != null) {
|
||||
basicAuthUser = user;
|
||||
}
|
||||
if (password != null) {
|
||||
basicAuthPassword = password;
|
||||
}
|
||||
basicAuthHeaderValue = basicAuthPassword.isEmpty() ? null
|
||||
: FilerSecurityContext.encodeBasicAuth(basicAuthUser, basicAuthPassword);
|
||||
}
|
||||
|
||||
// A null key or expiresAfterSeconds <= 0 keeps the current value; an empty key turns signing off.
|
||||
public synchronized void setJwtSigningKey(String key, long expiresAfterSeconds) {
|
||||
if (key != null) {
|
||||
signingKey = key;
|
||||
}
|
||||
if (expiresAfterSeconds > 0) {
|
||||
signingExpiresAfterSeconds = expiresAfterSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
// Same as setJwtSigningKey, for the read key.
|
||||
public synchronized void setJwtReadSigningKey(String key, long expiresAfterSeconds) {
|
||||
if (key != null) {
|
||||
readSigningKey = key;
|
||||
}
|
||||
if (expiresAfterSeconds > 0) {
|
||||
readSigningExpiresAfterSeconds = expiresAfterSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the Authorization header value for an HTTP request addressed to the filer:
|
||||
// a filer JWT for the access level when its key is set, else [filer.basic_auth], else
|
||||
// [basic_auth]; null when none is configured. The filer reads GET and HEAD with the read key.
|
||||
public String getAuthorizationHeaderValue(boolean isWrite) {
|
||||
String key = isWrite ? signingKey : readSigningKey;
|
||||
if (!key.isEmpty()) {
|
||||
return "BEARER " + genJwtForFilerServer(key.getBytes(StandardCharsets.UTF_8),
|
||||
isWrite ? signingExpiresAfterSeconds : readSigningExpiresAfterSeconds);
|
||||
}
|
||||
String basicAuth = basicAuthHeaderValue;
|
||||
if (basicAuth != null) {
|
||||
return basicAuth;
|
||||
}
|
||||
return FilerSecurityContext.getBasicAuthHeaderValue();
|
||||
}
|
||||
|
||||
// Mints an HS256 token with only an "exp" claim, like security.GenJwtForFilerServer.
|
||||
static String genJwtForFilerServer(byte[] signingKey, long expiresAfterSeconds) {
|
||||
Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
|
||||
long exp = System.currentTimeMillis() / 1000 + expiresAfterSeconds;
|
||||
String signingInput = encoder.encodeToString("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8))
|
||||
+ "." + encoder.encodeToString(("{\"exp\":" + exp + "}").getBytes(StandardCharsets.UTF_8));
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
|
||||
return signingInput + "." + encoder.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("cannot sign filer jwt", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ public class FilerGrpcClient {
|
||||
private String replication = "";
|
||||
private int volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT;
|
||||
private String filerAddress;
|
||||
private final FilerCredentials filerCredentials = new FilerCredentials(FilerSecurityContext.getFilerCredentials());
|
||||
|
||||
public FilerGrpcClient(String host, int port, int grpcPort, String cn) {
|
||||
this(host, port, grpcPort, cn, sslContext);
|
||||
@@ -154,6 +155,11 @@ public class FilerGrpcClient {
|
||||
return SeaweedFilerGrpc.newFutureStub(getChannel());
|
||||
}
|
||||
|
||||
// Credentials for this client's requests to the filer's HTTP port; changes affect only this client.
|
||||
public FilerCredentials getFilerCredentials() {
|
||||
return filerCredentials;
|
||||
}
|
||||
|
||||
public void setAccessVolumeServerDirectly() {
|
||||
this.volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT;
|
||||
}
|
||||
@@ -183,9 +189,18 @@ public class FilerGrpcClient {
|
||||
case VOLUME_SERVER_ACCESS_PUBLIC_URL:
|
||||
return String.format("%s://%s/%s", protocol, publicUrl, chunkId);
|
||||
case VOLUME_SERVER_ACCESS_FILER_PROXY:
|
||||
return String.format("%s://%s/?proxyChunkId=%s", protocol, this.filerAddress, chunkId);
|
||||
return proxyChunkUrlPrefix() + chunkId;
|
||||
default:
|
||||
return String.format("%s://%s/%s", protocol, url, chunkId);
|
||||
}
|
||||
}
|
||||
|
||||
// Reports whether a chunk URL addresses this client's filer chunk proxy rather than a volume server.
|
||||
public boolean isProxyChunkUrl(String url) {
|
||||
return isAccessVolumeServerByFilerProxy() && url != null && url.startsWith(proxyChunkUrlPrefix());
|
||||
}
|
||||
|
||||
private String proxyChunkUrlPrefix() {
|
||||
return String.format("%s://%s/?proxyChunkId=", protocol, this.filerAddress);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,8 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
// volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode.
|
||||
private static volatile String basicAuthHeaderValue;
|
||||
|
||||
private static final FilerCredentials filerCredentials = new FilerCredentials();
|
||||
|
||||
|
||||
static {
|
||||
String securityFileName = "security.toml";
|
||||
@@ -64,6 +66,11 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
|
||||
basicAuthHeaderValue = computeBasicAuthHeaderValue(
|
||||
toml.getString("basic_auth.username"), toml.getString("basic_auth.password"));
|
||||
filerCredentials.setBasicAuth(toml.getString("filer.basic_auth.user"), toml.getString("filer.basic_auth.password"));
|
||||
filerCredentials.setJwtSigningKey(toml.getString("jwt.filer_signing.key"),
|
||||
toml.getLong("jwt.filer_signing.expires_after_seconds", 0L));
|
||||
filerCredentials.setJwtReadSigningKey(toml.getString("jwt.filer_signing.read.key"),
|
||||
toml.getLong("jwt.filer_signing.read.expires_after_seconds", 0L));
|
||||
|
||||
grpcTrustCertCollectionFilePath = toml.getString("grpc.ca");
|
||||
logger.debug("loading gRPC ca from {}", grpcTrustCertCollectionFilePath);
|
||||
@@ -86,7 +93,7 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
}
|
||||
}
|
||||
|
||||
if (toml.getBoolean("https.client.enabled")) {
|
||||
if (toml.getBoolean("https.client.enabled", false)) {
|
||||
httpTrustCertCollectionFilePath = toml.getString("https.client.ca");
|
||||
logger.debug("loading HTTP ca from {}", httpTrustCertCollectionFilePath);
|
||||
httpClientCertChainFilePath = toml.getString("https.client.cert");
|
||||
@@ -146,11 +153,20 @@ public abstract class FilerSecurityContext extends SslContext {
|
||||
return basicAuthHeaderValue;
|
||||
}
|
||||
|
||||
// The filer credentials read from security.toml; each FilerClient copies them.
|
||||
static FilerCredentials getFilerCredentials() {
|
||||
return filerCredentials;
|
||||
}
|
||||
|
||||
private static String computeBasicAuthHeaderValue(String username, String password) {
|
||||
if (Strings.isNullOrEmpty(username)) {
|
||||
return null;
|
||||
}
|
||||
String credentials = username + ":" + (password == null ? "" : password);
|
||||
return encodeBasicAuth(username, password == null ? "" : password);
|
||||
}
|
||||
|
||||
static String encodeBasicAuth(String username, String password) {
|
||||
String credentials = username + ":" + password;
|
||||
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
|
||||
@@ -136,7 +136,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);
|
||||
byte[] fetched = doFetchOneFullChunkData(filerClient, 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.
|
||||
@@ -171,15 +171,19 @@ public class SeaweedRead {
|
||||
|
||||
}
|
||||
|
||||
private static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException {
|
||||
private static byte[] doFetchOneFullChunkData(FilerClient filerClient, ChunkView chunkView, String url) throws IOException {
|
||||
|
||||
HttpGet request = new HttpGet(url);
|
||||
|
||||
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
|
||||
|
||||
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
|
||||
if (basicAuthHeader != null) {
|
||||
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
|
||||
String authHeader = FilerSecurityContext.getBasicAuthHeaderValue();
|
||||
if (filerClient.isProxyChunkUrl(url)) {
|
||||
authHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(false);
|
||||
request.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG);
|
||||
}
|
||||
if (authHeader != null) {
|
||||
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
|
||||
}
|
||||
|
||||
byte[] data = null;
|
||||
@@ -187,6 +191,11 @@ public class SeaweedRead {
|
||||
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
|
||||
|
||||
try {
|
||||
int status = response.getStatusLine().getStatusCode();
|
||||
if (status / 100 != 2) {
|
||||
throw new IOException("fetch " + url + ": " + response.getStatusLine());
|
||||
}
|
||||
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
Header contentEncodingHeader = entity.getContentEncoding();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package seaweedfs.client;
|
||||
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
@@ -90,4 +91,7 @@ public class SeaweedUtil {
|
||||
}
|
||||
return host + ":" + port;
|
||||
}
|
||||
|
||||
// Redirects would carry the filer credential to the redirect target.
|
||||
static final RequestConfig PROXY_CHUNK_REQUEST_CONFIG = RequestConfig.custom().setRedirectsEnabled(false).build();
|
||||
}
|
||||
@@ -135,7 +135,7 @@ public class SeaweedWrite {
|
||||
cipherKeyString = ByteString.copyFrom(cipherKey);
|
||||
}
|
||||
|
||||
String etag = multipartUpload(targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey);
|
||||
String etag = multipartUpload(filerClient, targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey);
|
||||
|
||||
return FilerProto.FileChunk.newBuilder()
|
||||
.setFileId(fileId)
|
||||
@@ -167,7 +167,8 @@ public class SeaweedWrite {
|
||||
}
|
||||
}
|
||||
|
||||
private static String multipartUpload(String targetUrl,
|
||||
private static String multipartUpload(FilerClient filerClient,
|
||||
String targetUrl,
|
||||
String auth,
|
||||
final byte[] bytes,
|
||||
final long bytesOffset, final long bytesLength,
|
||||
@@ -193,7 +194,14 @@ public class SeaweedWrite {
|
||||
}
|
||||
|
||||
HttpPost post = new HttpPost(targetUrl);
|
||||
if (auth != null && auth.length() != 0) {
|
||||
String filerAuthHeader = null;
|
||||
if (filerClient.isProxyChunkUrl(targetUrl)) {
|
||||
filerAuthHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(true);
|
||||
post.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG);
|
||||
}
|
||||
if (filerAuthHeader != null) {
|
||||
post.addHeader("Authorization", filerAuthHeader);
|
||||
} else 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);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package seaweedfs.client;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class FileChunkManifestTest {
|
||||
|
||||
private static FilerProto.FileChunk chunk(int volumeId, long key, long offset, long size) {
|
||||
return FilerProto.FileChunk.newBuilder()
|
||||
.setFid(FilerProto.FileId.newBuilder().setVolumeId(volumeId).setFileKey(key).setCookie(1))
|
||||
.setOffset(offset)
|
||||
.setSize(size)
|
||||
.setModifiedTsNs(1)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCutToManifestSpanCutsAShortenedManifest() throws IOException {
|
||||
List<FilerProto.FileChunk> held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100), chunk(9, 3, 200, 100));
|
||||
FilerProto.FileChunk manifest = chunk(9, 4, 0, 150).toBuilder().setIsChunkManifest(true).build();
|
||||
|
||||
List<FilerProto.FileChunk> cut = FileChunkManifest.cutToManifestSpan(manifest, held);
|
||||
Assert.assertEquals(2, cut.size());
|
||||
Assert.assertEquals(held.get(0), cut.get(0));
|
||||
Assert.assertEquals(100, cut.get(1).getOffset());
|
||||
Assert.assertEquals(50, cut.get(1).getSize());
|
||||
Assert.assertEquals(100, held.get(1).getSize());
|
||||
|
||||
List<SeaweedRead.VisibleInterval> visibles = ReadChunks.readResolvedChunks(cut);
|
||||
Assert.assertEquals(150, visibles.get(visibles.size() - 1).stop);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCutToManifestSpanLeavesAWholeManifestAlone() {
|
||||
List<FilerProto.FileChunk> held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100));
|
||||
FilerProto.FileChunk manifest = chunk(9, 4, 0, 200).toBuilder().setIsChunkManifest(true).build();
|
||||
Assert.assertEquals(held, FileChunkManifest.cutToManifestSpan(manifest, held));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package seaweedfs.client;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.ServerBuilder;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class FilerJwtTest {
|
||||
|
||||
private FilerCredentials credentials;
|
||||
|
||||
@Before
|
||||
public void clearCredentials() {
|
||||
FilerSecurityContext.setBasicAuth(null, null);
|
||||
credentials = new FilerCredentials();
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearProxyBasicAuth() {
|
||||
FilerSecurityContext.setBasicAuth(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filerJwtIsSignedHs256WithExp() throws Exception {
|
||||
long before = System.currentTimeMillis() / 1000;
|
||||
String token = FilerCredentials.genJwtForFilerServer("write-key".getBytes(StandardCharsets.UTF_8), 10);
|
||||
long after = System.currentTimeMillis() / 1000;
|
||||
|
||||
String[] parts = token.split("\\.");
|
||||
assertEquals(3, parts.length);
|
||||
assertEquals("{\"alg\":\"HS256\",\"typ\":\"JWT\"}", decode(parts[0]));
|
||||
long exp = exp(decode(parts[1]));
|
||||
assertTrue(exp >= before + 10 && exp <= after + 10);
|
||||
assertEquals(sign("write-key", parts[0] + "." + parts[1]), parts[2]);
|
||||
assertFalse(token.contains("="));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noCredentialsMeansNoFilerHeader() {
|
||||
assertNull(credentials.getAuthorizationHeaderValue(true));
|
||||
assertNull(credentials.getAuthorizationHeaderValue(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessLevelPicksItsSigningKey() throws Exception {
|
||||
credentials.setJwtSigningKey("write-key", 0);
|
||||
credentials.setJwtReadSigningKey("read-key", 0);
|
||||
long now = System.currentTimeMillis() / 1000;
|
||||
|
||||
String[] write = bearer(credentials.getAuthorizationHeaderValue(true));
|
||||
assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]);
|
||||
assertTrue(exp(decode(write[1])) - now <= 11);
|
||||
|
||||
String[] read = bearer(credentials.getAuthorizationHeaderValue(false));
|
||||
assertEquals(sign("read-key", read[0] + "." + read[1]), read[2]);
|
||||
assertTrue(exp(decode(read[1])) - now >= 60);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basicAuthCoversAccessLevelsWithoutKey() {
|
||||
FilerSecurityContext.setBasicAuth("proxy", "proxy-pass");
|
||||
assertEquals(FilerSecurityContext.getBasicAuthHeaderValue(),
|
||||
credentials.getAuthorizationHeaderValue(false));
|
||||
|
||||
credentials.setBasicAuth("filer", "filer-pass");
|
||||
String filerBasic = "Basic " + Base64.getEncoder()
|
||||
.encodeToString("filer:filer-pass".getBytes(StandardCharsets.UTF_8));
|
||||
assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false));
|
||||
|
||||
credentials.setJwtSigningKey("write-key", 5);
|
||||
assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("BEARER "));
|
||||
assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filerBasicAuthFollowsThePassword() {
|
||||
credentials.setBasicAuth("filer", "");
|
||||
assertNull(credentials.getAuthorizationHeaderValue(false));
|
||||
|
||||
credentials.setBasicAuth("", "only-pass");
|
||||
assertEquals("Basic " + Base64.getEncoder().encodeToString(":only-pass".getBytes(StandardCharsets.UTF_8)),
|
||||
credentials.getAuthorizationHeaderValue(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullKeepsTheCurrentValue() throws Exception {
|
||||
credentials.setBasicAuth("filer", "old-pass");
|
||||
credentials.setBasicAuth(null, "new-pass");
|
||||
assertEquals("Basic " + Base64.getEncoder().encodeToString("filer:new-pass".getBytes(StandardCharsets.UTF_8)),
|
||||
credentials.getAuthorizationHeaderValue(false));
|
||||
|
||||
credentials.setJwtSigningKey("write-key", 0);
|
||||
credentials.setJwtSigningKey(null, 300);
|
||||
long now = System.currentTimeMillis() / 1000;
|
||||
String[] write = bearer(credentials.getAuthorizationHeaderValue(true));
|
||||
assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]);
|
||||
assertTrue(exp(decode(write[1])) - now >= 300);
|
||||
|
||||
credentials.setJwtSigningKey("", 0);
|
||||
assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("Basic "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void copiesSignIndependently() throws Exception {
|
||||
credentials.setJwtSigningKey("shared-key", 0);
|
||||
FilerCredentials a = new FilerCredentials(credentials);
|
||||
FilerCredentials b = new FilerCredentials(credentials);
|
||||
b.setJwtSigningKey("b-key", 0);
|
||||
|
||||
String[] fromA = bearer(a.getAuthorizationHeaderValue(true));
|
||||
String[] fromB = bearer(b.getAuthorizationHeaderValue(true));
|
||||
assertEquals(sign("shared-key", fromA[0] + "." + fromA[1]), fromA[2]);
|
||||
assertEquals(sign("b-key", fromB[0] + "." + fromB[1]), fromB[2]);
|
||||
String[] fromDefaults = bearer(credentials.getAuthorizationHeaderValue(true));
|
||||
assertEquals(sign("shared-key", fromDefaults[0] + "." + fromDefaults[1]), fromDefaults[2]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onlyFilerProxyUrlsAreFilerRequests() throws Exception {
|
||||
Server filerGrpc = startFilerGrpc();
|
||||
FilerClient filerClient = new FilerClient("127.0.0.1", 8888, filerGrpc.getPort(), "");
|
||||
try {
|
||||
String proxyUrl = "http://127.0.0.1:8888/?proxyChunkId=3,01637037d6";
|
||||
assertFalse(filerClient.isProxyChunkUrl(proxyUrl));
|
||||
|
||||
filerClient.setAccessVolumeServerByFilerProxy();
|
||||
assertEquals(proxyUrl, filerClient.getChunkUrl("3,01637037d6", "volume:8080", "volume:8080"));
|
||||
assertTrue(filerClient.isProxyChunkUrl(proxyUrl));
|
||||
assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/3,01637037d6"));
|
||||
assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/?proxyChunkId=/3,01637037d6"));
|
||||
assertFalse(filerClient.isProxyChunkUrl("http://127.0.0.1:8888.example/?proxyChunkId=3,01637037d6"));
|
||||
assertFalse(filerClient.isProxyChunkUrl(null));
|
||||
} finally {
|
||||
filerClient.shutdown();
|
||||
filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void proxyChunkReadDoesNotFollowRedirects() throws Exception {
|
||||
AtomicInteger targetHits = new AtomicInteger();
|
||||
HttpServer target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
target.createContext("/", exchange -> {
|
||||
targetHits.incrementAndGet();
|
||||
respond(exchange, 200, "leaked");
|
||||
});
|
||||
List<String> filerAuth = new CopyOnWriteArrayList<>();
|
||||
HttpServer filer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
filer.createContext("/", exchange -> {
|
||||
filerAuth.add(exchange.getRequestHeaders().getFirst("Authorization"));
|
||||
if (filerAuth.size() == 1) {
|
||||
exchange.getResponseHeaders().set("Location", "http://127.0.0.1:" + target.getAddress().getPort() + "/");
|
||||
respond(exchange, 302, "");
|
||||
} else {
|
||||
respond(exchange, 200, "chunk");
|
||||
}
|
||||
});
|
||||
Server filerGrpc = startFilerGrpc();
|
||||
target.start();
|
||||
filer.start();
|
||||
FilerClient filerClient = new FilerClient("127.0.0.1", filer.getAddress().getPort(), filerGrpc.getPort(), "");
|
||||
try {
|
||||
filerClient.setAccessVolumeServerByFilerProxy();
|
||||
filerClient.getFilerCredentials().setJwtReadSigningKey("read-key", 0);
|
||||
FilerProto.Locations locations = FilerProto.Locations.newBuilder()
|
||||
.addLocations(FilerProto.Location.newBuilder().setUrl("volume:8080")).build();
|
||||
|
||||
byte[] data = SeaweedRead.doFetchFullChunkData(filerClient,
|
||||
new SeaweedRead.ChunkView("3,01637037d6", 0, 5, 0, true, null, false), locations);
|
||||
|
||||
assertEquals("chunk", new String(data, StandardCharsets.UTF_8));
|
||||
assertEquals(0, targetHits.get());
|
||||
assertEquals(2, filerAuth.size());
|
||||
assertTrue(filerAuth.get(0).startsWith("BEARER "));
|
||||
} finally {
|
||||
filerClient.shutdown();
|
||||
filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
|
||||
filer.stop(0);
|
||||
target.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
private static Server startFilerGrpc() throws IOException {
|
||||
return ServerBuilder.forPort(0).addService(new SeaweedFilerGrpc.SeaweedFilerImplBase() {
|
||||
@Override
|
||||
public void getFilerConfiguration(FilerProto.GetFilerConfigurationRequest request,
|
||||
StreamObserver<FilerProto.GetFilerConfigurationResponse> observer) {
|
||||
observer.onNext(FilerProto.GetFilerConfigurationResponse.getDefaultInstance());
|
||||
observer.onCompleted();
|
||||
}
|
||||
}).build().start();
|
||||
}
|
||||
|
||||
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static String[] bearer(String header) {
|
||||
assertTrue(header.startsWith("BEARER "));
|
||||
return header.substring("BEARER ".length()).split("\\.");
|
||||
}
|
||||
|
||||
private static String decode(String part) {
|
||||
return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static long exp(String payload) {
|
||||
Matcher m = Pattern.compile("^\\{\"exp\":(\\d+)\\}$").matcher(payload);
|
||||
assertTrue(payload, m.matches());
|
||||
return Long.parseLong(m.group(1));
|
||||
}
|
||||
|
||||
private static String sign(String key, String signingInput) throws Exception {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,75 @@ The test suite covers:
|
||||
hadoop fs -put local.txt seaweedfs://localhost:8888/test/
|
||||
```
|
||||
|
||||
### Secured filer
|
||||
|
||||
With `fs.seaweed.volume.server.access` set to `filerProxy`, chunk reads and writes go to the
|
||||
filer's HTTP port, so they need the filer's HTTP credentials. The client signs a filer JWT
|
||||
when it has the filer's `jwt.filer_signing` key (writes) or
|
||||
`jwt.filer_signing.read` key (reads), and otherwise sends the `[filer.basic_auth]`
|
||||
credentials. These credentials are sent only to the filer, never to volume servers. In `direct`
|
||||
and `publicUrl` modes chunk requests go straight to volume servers, so the filer's HTTP
|
||||
credentials are not used; writes carry the volume token from the volume assignment as before.
|
||||
gRPC mTLS comes from the `[grpc]` section as before, but it does not cover these HTTP chunk requests:
|
||||
to keep the credentials off plain HTTP, serve the filer HTTP port over HTTPS (`[https.filer]`
|
||||
on the filer) and enable `[https.client]` here. The client checks the certificate chain but
|
||||
not the host name, so set `https.client.ca` to a CA that issues certificates only for your
|
||||
SeaweedFS servers.
|
||||
|
||||
`security.toml` (read from `./`, `~/.seaweedfs/` or `/etc/seaweedfs/`), using the filer's
|
||||
own values:
|
||||
|
||||
```toml
|
||||
[jwt.filer_signing]
|
||||
key = "<filer write key>"
|
||||
|
||||
[jwt.filer_signing.read]
|
||||
key = "<filer read key>"
|
||||
|
||||
# or, for a filer with Basic Auth
|
||||
[filer.basic_auth]
|
||||
user = "<user>"
|
||||
password = "<password>"
|
||||
|
||||
[grpc]
|
||||
ca = "/etc/seaweedfs/ca.crt"
|
||||
|
||||
[grpc.client]
|
||||
cert = "/etc/seaweedfs/client.crt"
|
||||
key = "/etc/seaweedfs/client.key"
|
||||
|
||||
[https.client]
|
||||
enabled = true
|
||||
ca = "/etc/seaweedfs/ca.crt"
|
||||
cert = "/etc/seaweedfs/client.crt"
|
||||
key = "/etc/seaweedfs/client.key"
|
||||
```
|
||||
|
||||
The same values can be set in `core-site.xml`. Each option overrides only its own
|
||||
`security.toml` value (for example, a password alone keeps the `security.toml` user), and
|
||||
applies only to that filesystem. The secrets can also come from a Hadoop credential provider:
|
||||
|
||||
```xml
|
||||
<property>
|
||||
<name>fs.seaweed.volume.server.access</name>
|
||||
<value>filerProxy</value>
|
||||
</property>
|
||||
<property>
|
||||
<name>fs.seaweed.filer.jwt.signing.key</name>
|
||||
<value>filer write key</value>
|
||||
</property>
|
||||
<property>
|
||||
<name>fs.seaweed.filer.jwt.signing.read.key</name>
|
||||
<value>filer read key</value>
|
||||
</property>
|
||||
<!-- token lifetimes, defaults 10 and 60 seconds:
|
||||
fs.seaweed.filer.jwt.signing.expires.after.seconds
|
||||
fs.seaweed.filer.jwt.signing.read.expires.after.seconds -->
|
||||
<!-- or Basic Auth:
|
||||
fs.seaweed.filer.basic.auth.user
|
||||
fs.seaweed.filer.basic.auth.password -->
|
||||
```
|
||||
|
||||
## Continuous Integration
|
||||
|
||||
For CI environments, tests can be run in two modes:
|
||||
|
||||
@@ -10,6 +10,7 @@ import org.apache.hadoop.util.Progressable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import seaweedfs.client.FilerProto;
|
||||
import seaweedfs.client.FilerCredentials;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
@@ -30,6 +31,12 @@ public class SeaweedFileSystem extends FileSystem {
|
||||
public static final String FS_SEAWEED_VOLUME_SERVER_ACCESS = "fs.seaweed.volume.server.access";
|
||||
public static final int FS_SEAWEED_DEFAULT_BUFFER_SIZE = 4 * 1024 * 1024;
|
||||
public static final String FS_SEAWEED_FILER_CN = "fs.seaweed.filer.cn";
|
||||
public static final String FS_SEAWEED_FILER_BASIC_AUTH_USER = "fs.seaweed.filer.basic.auth.user";
|
||||
public static final String FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD = "fs.seaweed.filer.basic.auth.password";
|
||||
public static final String FS_SEAWEED_FILER_JWT_SIGNING_KEY = "fs.seaweed.filer.jwt.signing.key";
|
||||
public static final String FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES = "fs.seaweed.filer.jwt.signing.expires.after.seconds";
|
||||
public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY = "fs.seaweed.filer.jwt.signing.read.key";
|
||||
public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES = "fs.seaweed.filer.jwt.signing.read.expires.after.seconds";
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SeaweedFileSystem.class);
|
||||
|
||||
@@ -69,6 +76,21 @@ public class SeaweedFileSystem extends FileSystem {
|
||||
seaweedFileSystemStore = new SeaweedFileSystemStore(host, port, grpcPort, cn, conf);
|
||||
}
|
||||
|
||||
// Each option set here overrides only its own [filer.basic_auth] or [jwt.filer_signing] value of security.toml.
|
||||
static void applyFilerCredentials(Configuration conf, FilerCredentials credentials) throws IOException {
|
||||
credentials.setBasicAuth(conf.get(FS_SEAWEED_FILER_BASIC_AUTH_USER),
|
||||
secret(conf, FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD));
|
||||
credentials.setJwtSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_KEY),
|
||||
conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 0));
|
||||
credentials.setJwtReadSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY),
|
||||
conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 0));
|
||||
}
|
||||
|
||||
private static String secret(Configuration conf, String name) throws IOException {
|
||||
char[] value = conf.getPassword(name);
|
||||
return value == null ? null : new String(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
super.close();
|
||||
|
||||
@@ -27,9 +27,15 @@ public class SeaweedFileSystemStore {
|
||||
private FilerClient filerClient;
|
||||
private Configuration conf;
|
||||
|
||||
public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) {
|
||||
public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) throws IOException {
|
||||
filerClient = new FilerClient(host, port, grpcPort, cn);
|
||||
this.conf = conf;
|
||||
try {
|
||||
SeaweedFileSystem.applyFilerCredentials(conf, filerClient.getFilerCredentials());
|
||||
} catch (IOException | RuntimeException e) {
|
||||
close();
|
||||
throw e;
|
||||
}
|
||||
String volumeServerAccessMode = this.conf.get(FS_SEAWEED_VOLUME_SERVER_ACCESS, "direct");
|
||||
if (volumeServerAccessMode.equals("publicUrl")) {
|
||||
filerClient.setAccessVolumeServerByPublicUrl();
|
||||
|
||||
@@ -4,6 +4,12 @@ import org.apache.hadoop.conf.Configuration;
|
||||
import org.apache.hadoop.fs.Path;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import seaweedfs.client.FilerCredentials;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@@ -87,4 +93,57 @@ public class SeaweedFileSystemConfigTest {
|
||||
// Test default port constant
|
||||
assertEquals(8888, SeaweedFileSystem.FS_SEAWEED_DEFAULT_PORT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilerCredentialsFromConfiguration() throws Exception {
|
||||
FilerCredentials credentials = new FilerCredentials();
|
||||
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_USER, "alice");
|
||||
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "s3cret");
|
||||
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
|
||||
String basic = "Basic " + Base64.getEncoder().encodeToString("alice:s3cret".getBytes(StandardCharsets.UTF_8));
|
||||
assertEquals(basic, credentials.getAuthorizationHeaderValue(true));
|
||||
|
||||
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_KEY, "write-key");
|
||||
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 120);
|
||||
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
|
||||
long now = System.currentTimeMillis() / 1000;
|
||||
assertTrue(signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now >= 119);
|
||||
assertEquals(basic, credentials.getAuthorizationHeaderValue(false));
|
||||
|
||||
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY, "read-key");
|
||||
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 240);
|
||||
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
|
||||
long readExp = signedExp(credentials.getAuthorizationHeaderValue(false), "read-key") - now;
|
||||
assertTrue(readExp >= 239 && readExp <= 245);
|
||||
long writeExp = signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now;
|
||||
assertTrue(writeExp >= 119 && writeExp <= 125);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilerCredentialOptionsOverrideOneValueEach() throws Exception {
|
||||
FilerCredentials credentials = new FilerCredentials();
|
||||
credentials.setBasicAuth("toml-user", "toml-pass");
|
||||
credentials.setJwtReadSigningKey("toml-read-key", 0);
|
||||
|
||||
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "new-pass");
|
||||
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 300);
|
||||
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
|
||||
|
||||
assertEquals("Basic " + Base64.getEncoder().encodeToString("toml-user:new-pass".getBytes(StandardCharsets.UTF_8)),
|
||||
credentials.getAuthorizationHeaderValue(true));
|
||||
long exp = signedExp(credentials.getAuthorizationHeaderValue(false), "toml-read-key");
|
||||
assertTrue(exp - System.currentTimeMillis() / 1000 >= 299);
|
||||
}
|
||||
|
||||
// Asserts the header is a filer JWT signed with key and returns its exp claim.
|
||||
private static long signedExp(String header, String key) throws Exception {
|
||||
assertTrue(header, header.startsWith("BEARER "));
|
||||
String[] parts = header.substring("BEARER ".length()).split("\\.");
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
assertEquals(Base64.getUrlEncoder().withoutPadding().encodeToString(
|
||||
mac.doFinal((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8))), parts[2]);
|
||||
String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
return Long.parseLong(payload.replaceAll("[^0-9]", ""));
|
||||
}
|
||||
}
|
||||
@@ -5458,7 +5458,7 @@
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "EC Shard Copy Failures by reason",
|
||||
"description": "Rate of failed EC shard copies into each volume server by collection and reason (source_not_found, empty_index, no_space, timeout, io_error, other). The volume server log names the volume, shards and source of each failure.",
|
||||
"description": "Failed EC shard copies into each volume server per rate interval, by collection and reason (source_not_found, empty_index, no_space, timeout, io_error, other). The volume server log names the volume, shards and source of each failure.",
|
||||
"type": "timeseries",
|
||||
"id": 269,
|
||||
"gridPos": {
|
||||
@@ -5505,7 +5505,7 @@
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "ops",
|
||||
"unit": "short",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
@@ -5540,7 +5540,7 @@
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (instance, collection, reason) (rate(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"expr": "sum by (instance, collection, reason) ((last_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) and (min_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) < last_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[1d] offset $__rate_interval))) or (increase(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) and count_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[1d] offset $__rate_interval)) or (last_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[$__rate_interval]) unless count_over_time(SeaweedFS_volumeServer_ec_shard_copy_failures_total{cluster=~\"$cluster\"}[1d] offset $__rate_interval)))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{instance}} {{collection}} {{reason}}"
|
||||
@@ -7826,6 +7826,390 @@
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC QPS by method",
|
||||
"description": "gRPC calls to the filer (mounts, S3 gateways, peers, shell), by method.",
|
||||
"type": "timeseries",
|
||||
"id": 271,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 103
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "reqps",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (method) (rate(SeaweedFS_filer_grpc_request_total{cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC Errors by method and code",
|
||||
"description": "gRPC calls to the filer that did not end OK. NotFound is mostly lookups of names that do not exist.",
|
||||
"type": "timeseries",
|
||||
"id": 272,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 103
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "reqps",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (method, code) (rate(SeaweedFS_filer_grpc_request_total{code!=\"OK\", cluster=~\"$cluster\"}[$__rate_interval]))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}} {{code}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC Duration p99 by method",
|
||||
"description": "Subscriptions, health watches and client streams are counted but not timed.",
|
||||
"type": "timeseries",
|
||||
"id": 273,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 111
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "s",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"title": "Filer gRPC Duration p50 by method",
|
||||
"description": "Subscriptions, health watches and client streams are counted but not timed.",
|
||||
"type": "timeseries",
|
||||
"id": 274,
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 111
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
"mode": "palette-classic"
|
||||
},
|
||||
"custom": {
|
||||
"axisBorderShow": false,
|
||||
"axisCenteredZero": false,
|
||||
"axisColorMode": "text",
|
||||
"axisLabel": "",
|
||||
"axisPlacement": "auto",
|
||||
"barAlignment": 0,
|
||||
"drawStyle": "line",
|
||||
"fillOpacity": 10,
|
||||
"gradientMode": "none",
|
||||
"hideFrom": {
|
||||
"legend": false,
|
||||
"tooltip": false,
|
||||
"viz": false
|
||||
},
|
||||
"insertNulls": false,
|
||||
"lineInterpolation": "linear",
|
||||
"lineWidth": 1,
|
||||
"pointSize": 4,
|
||||
"scaleDistribution": {
|
||||
"type": "linear"
|
||||
},
|
||||
"showPoints": "never",
|
||||
"spanNulls": false,
|
||||
"stacking": {
|
||||
"group": "A",
|
||||
"mode": "none"
|
||||
},
|
||||
"thresholdsStyle": {
|
||||
"mode": "off"
|
||||
}
|
||||
},
|
||||
"mappings": [],
|
||||
"unit": "s",
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"calcs": [
|
||||
"lastNotNull",
|
||||
"max"
|
||||
],
|
||||
"displayMode": "table",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${DS_PROMETHEUS}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "histogram_quantile(0.50, sum(rate(SeaweedFS_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))",
|
||||
"range": true,
|
||||
"refId": "A",
|
||||
"legendFormat": "{{method}}"
|
||||
}
|
||||
],
|
||||
"pluginVersion": "10.3.1"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
Generated
+1
@@ -6338,6 +6338,7 @@ dependencies = [
|
||||
"protoc-bin-vendored",
|
||||
"reqwest 0.12.28",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"seaweed-common",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
|
||||
Generated
+16
@@ -4067,6 +4067,7 @@ dependencies = [
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4165,6 +4166,19 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-health"
|
||||
version = "0.14.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fcfab99db777fba2802f0dfa861d1628d1ae916fb199d29819941f139ae85082"
|
||||
dependencies = [
|
||||
"prost 0.14.4",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
"tonic-prost",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tonic-prost"
|
||||
version = "0.14.6"
|
||||
@@ -4639,6 +4653,7 @@ dependencies = [
|
||||
"tokio-stream",
|
||||
"toml",
|
||||
"tonic",
|
||||
"tonic-health",
|
||||
"tonic-prost",
|
||||
"tonic-prost-build",
|
||||
"tonic-reflection",
|
||||
@@ -4647,6 +4662,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"webpki-roots",
|
||||
"windows-sys 0.61.2",
|
||||
"x509-parser",
|
||||
"xxhash-rust",
|
||||
|
||||
@@ -42,6 +42,7 @@ tokio-io-timeout = "1"
|
||||
tonic = { version = "0.14", features = ["tls-aws-lc"] }
|
||||
tonic-prost = "0.14"
|
||||
tonic-reflection = "0.14"
|
||||
tonic-health = "0.14"
|
||||
prost = "0.14"
|
||||
prost-types = "0.14"
|
||||
|
||||
@@ -67,6 +68,7 @@ jsonwebtoken = { version = "10", features = ["rust_crypto"] }
|
||||
rustls = "0.23"
|
||||
tokio-rustls = "0.26"
|
||||
rustls-pemfile = "2"
|
||||
webpki-roots = "1"
|
||||
|
||||
# LevelDB (via RocksDB for better Rust support)
|
||||
# Using rusty-leveldb for pure Rust LevelDB
|
||||
|
||||
+111
-45
@@ -22,6 +22,15 @@ fn process_env(key: &str) -> Option<OsString> {
|
||||
|
||||
/// `std::env::var`'s view of an [`EnvLookup`]: unset and non-UTF-8 both read
|
||||
/// as absent, exactly as `std::env::var(key).ok()` does.
|
||||
fn parse_common_names(value: &str) -> Vec<String> {
|
||||
value
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(String::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn env_string(env: EnvLookup<'_>, key: &str) -> Option<String> {
|
||||
env(key).and_then(|value| value.into_string().ok())
|
||||
}
|
||||
@@ -166,7 +175,7 @@ pub struct Cli {
|
||||
|
||||
/// Maximum numbers of volumes, count[,count]...
|
||||
/// If set to zero, the limit will be auto configured as free disk space divided by volume size.
|
||||
#[arg(long = "max", default_value = "8")]
|
||||
#[arg(long = "max", default_value = "10")]
|
||||
pub max: String,
|
||||
|
||||
/// Comma separated IP addresses having write permission. No limit if empty.
|
||||
@@ -324,6 +333,7 @@ pub struct VolumeServerConfig {
|
||||
pub grpc_ca_file: String,
|
||||
pub grpc_allowed_wildcard_domain: String,
|
||||
pub grpc_volume_allowed_common_names: Vec<String>,
|
||||
pub grpc_health_check_common_names: Vec<String>,
|
||||
pub tls_policy: TlsPolicy,
|
||||
/// Path to security.toml — stored for SIGHUP reload.
|
||||
pub security_file: String,
|
||||
@@ -1019,6 +1029,7 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
|
||||
grpc_ca_file: sec.grpc_ca_file,
|
||||
grpc_allowed_wildcard_domain: sec.grpc_allowed_wildcard_domain,
|
||||
grpc_volume_allowed_common_names: sec.grpc_volume_allowed_common_names,
|
||||
grpc_health_check_common_names: sec.grpc_health_check_common_names,
|
||||
tls_policy: sec.tls_policy,
|
||||
security_file: cli.security_file,
|
||||
allow_untrusted_remote_endpoints: cli.allow_untrusted_remote_endpoints,
|
||||
@@ -1052,6 +1063,7 @@ pub struct SecurityConfig {
|
||||
pub grpc_ca_file: String,
|
||||
pub grpc_allowed_wildcard_domain: String,
|
||||
pub grpc_volume_allowed_common_names: Vec<String>,
|
||||
pub grpc_health_check_common_names: Vec<String>,
|
||||
pub tls_policy: TlsPolicy,
|
||||
pub access_ui: bool,
|
||||
/// The file was read; otherwise only defaults and WEED_ overrides are set.
|
||||
@@ -1145,48 +1157,20 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
|
||||
if trimmed.starts_with('#') || trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[jwt.signing.read]" {
|
||||
section = Section::JwtSigningRead;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[jwt.signing]" {
|
||||
section = Section::JwtSigning;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[https.client]" {
|
||||
section = Section::HttpsClient;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[grpc]" {
|
||||
section = Section::Grpc;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[https.volume]" {
|
||||
section = Section::HttpsVolume;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[grpc.volume]" {
|
||||
section = Section::GrpcVolume;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[tls]" {
|
||||
section = Section::Tls;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[guard]" {
|
||||
section = Section::Guard;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[access]" {
|
||||
section = Section::Access;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "[fips]" {
|
||||
section = Section::Fips;
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with('[') {
|
||||
section = Section::None;
|
||||
if let Some(header) = section_header(trimmed) {
|
||||
section = match header {
|
||||
"[jwt.signing.read]" => Section::JwtSigningRead,
|
||||
"[jwt.signing]" => Section::JwtSigning,
|
||||
"[https.client]" => Section::HttpsClient,
|
||||
"[grpc]" => Section::Grpc,
|
||||
"[https.volume]" => Section::HttpsVolume,
|
||||
"[grpc.volume]" => Section::GrpcVolume,
|
||||
"[tls]" => Section::Tls,
|
||||
"[guard]" => Section::Guard,
|
||||
"[access]" => Section::Access,
|
||||
"[fips]" => Section::Fips,
|
||||
_ => Section::None,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1222,6 +1206,9 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
|
||||
"allowed_wildcard_domain" => {
|
||||
cfg.grpc_allowed_wildcard_domain = value.to_string()
|
||||
}
|
||||
"health_check_commonNames" => {
|
||||
cfg.grpc_health_check_common_names = parse_common_names(value)
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Section::HttpsVolume => match key {
|
||||
@@ -1290,6 +1277,20 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
|
||||
cfg
|
||||
}
|
||||
|
||||
/// The table header on a trimmed security.toml line, without the trailing
|
||||
/// comment TOML allows after it (`[fips] # policy` is `[fips]`), or `None`
|
||||
/// when the line is not a header. None of the sections read here has a `#`
|
||||
/// in its name.
|
||||
fn section_header(trimmed: &str) -> Option<&str> {
|
||||
if !trimmed.starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
let header = trimmed
|
||||
.split_once('#')
|
||||
.map_or(trimmed, |(header, _)| header);
|
||||
Some(header.trim_end())
|
||||
}
|
||||
|
||||
/// Reads the right-hand side of `key = value` the way TOML (and so Go) does:
|
||||
/// escapes decoded, literal strings kept as written, a trailing comment
|
||||
/// dropped. Text TOML rejects keeps the plain quote trimming.
|
||||
@@ -1328,8 +1329,26 @@ fn resolve_fips_setting_with_env(
|
||||
reason: e.to_string(),
|
||||
});
|
||||
}
|
||||
let file_value = parse_security_config_with_env(&path.to_string_lossy(), env).fips_mode;
|
||||
seaweed_common::fips::resolve(Some(&path), file_value.as_deref(), env)
|
||||
let parsed = parse_security_config_with_env(&path.to_string_lossy(), env);
|
||||
fips_setting_from_parsed(path, &parsed, env)
|
||||
}
|
||||
|
||||
/// The FIPS mode `parsed`, the security.toml at `path`, sets with `env`
|
||||
/// applied. A parse that could not read the file is an error like the first
|
||||
/// read, so a file that stops being readable between the two reads cannot
|
||||
/// leave the mode off.
|
||||
fn fips_setting_from_parsed(
|
||||
path: PathBuf,
|
||||
parsed: &SecurityConfig,
|
||||
env: EnvLookup<'_>,
|
||||
) -> Result<seaweed_common::fips::Setting, seaweed_common::fips::FipsModeError> {
|
||||
if !parsed.file_read {
|
||||
return Err(seaweed_common::fips::FipsModeError::File {
|
||||
path,
|
||||
reason: "could not be read".to_string(),
|
||||
});
|
||||
}
|
||||
seaweed_common::fips::resolve(Some(&path), parsed.fips_mode.as_deref(), env)
|
||||
}
|
||||
|
||||
fn resolve_security_config_path(path: &str, env: EnvLookup<'_>) -> Option<PathBuf> {
|
||||
@@ -1408,6 +1427,9 @@ fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
|
||||
if let Some(v) = env_string(env, "WEED_GRPC_VOLUME_ALLOWED_COMMONNAMES") {
|
||||
cfg.grpc_volume_allowed_common_names = v.split(',').map(|name| name.to_string()).collect();
|
||||
}
|
||||
if let Some(v) = env_string(env, "WEED_GRPC_HEALTH_CHECK_COMMONNAMES") {
|
||||
cfg.grpc_health_check_common_names = parse_common_names(&v);
|
||||
}
|
||||
if let Some(v) = env_string(env, "WEED_TLS_MIN_VERSION") {
|
||||
cfg.tls_policy.min_version = v;
|
||||
}
|
||||
@@ -2067,6 +2089,7 @@ client_key = "/etc/seaweedfs/volume-client-key.pem"
|
||||
r#"
|
||||
[grpc]
|
||||
allowed_wildcard_domain = ".example.com"
|
||||
health_check_commonNames = "blackbox, ,probe"
|
||||
|
||||
[grpc.volume]
|
||||
allowed_commonNames = "volume-a.internal,volume-b.internal"
|
||||
@@ -2083,6 +2106,10 @@ allowed_commonNames = "volume-a.internal,volume-b.internal"
|
||||
String::from("volume-b.internal")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
cfg.grpc_health_check_common_names,
|
||||
vec![String::from("blackbox"), String::from("probe")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2316,6 +2343,24 @@ previous_key = "read-old"
|
||||
assert!(resolve_fips_setting_with_env(path, &fake_env(&[])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_section_headers_with_a_trailing_comment() {
|
||||
use seaweed_common::fips::FipsMode;
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
let text = "[fips] # deployment policy\nmode = \"on\"\n\
|
||||
[jwt.signing] # comment\nkey = \"secret\"\n\
|
||||
[other] # not read\nkey = \"ignored\"\n";
|
||||
std::fs::write(tmp.path(), text).unwrap();
|
||||
let path = tmp.path().to_str().unwrap();
|
||||
assert!(text.parse::<toml::Table>().is_ok(), "TOML, as Go reads it");
|
||||
|
||||
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
|
||||
assert_eq!(cfg.fips_mode.as_deref(), Some("on"));
|
||||
assert_eq!(cfg.jwt_signing_key, b"secret");
|
||||
let setting = resolve_fips_setting_with_env(path, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fips_mode_refuses_a_security_file_it_cannot_read() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
@@ -2332,6 +2377,27 @@ previous_key = "read-old"
|
||||
assert_eq!(setting.mode, seaweed_common::fips::FipsMode::Off);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fips_mode_refuses_a_parse_that_did_not_read_the_file() {
|
||||
use seaweed_common::fips::FipsMode;
|
||||
let path = PathBuf::from("/etc/seaweedfs/security.toml");
|
||||
let unread = SecurityConfig::default();
|
||||
let err = fips_setting_from_parsed(path.clone(), &unread, &fake_env(&[])).unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("could not be read; cannot tell whether it sets fips.mode"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
let read = SecurityConfig {
|
||||
file_read: true,
|
||||
fips_mode: Some("on".to_string()),
|
||||
..SecurityConfig::default()
|
||||
};
|
||||
let setting = fips_setting_from_parsed(path, &read, &fake_env(&[])).unwrap();
|
||||
assert_eq!(setting.mode, FipsMode::On);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_env_override_takes_precedence_over_file() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
|
||||
+262
-23
@@ -5,6 +5,7 @@ use tracing::{error, info, warn};
|
||||
use seaweed_volume::config::{self, VolumeServerConfig};
|
||||
use seaweed_volume::metrics;
|
||||
use seaweed_volume::pb::volume_server_pb::volume_server_server::VolumeServerServer;
|
||||
use seaweed_volume::security::health_check_access::HealthCheckOnlyLayer;
|
||||
use seaweed_volume::security::tls::{
|
||||
GrpcClientAuthPolicy, TlsPolicy, build_rustls_server_config,
|
||||
build_rustls_server_config_with_grpc_client_auth,
|
||||
@@ -168,28 +169,22 @@ fn build_outgoing_http_client(
|
||||
));
|
||||
}
|
||||
|
||||
let mut builder = outgoing_client_builder(redirect_policy);
|
||||
if !config.https_client_ca_file.is_empty() {
|
||||
let ca_pem = std::fs::read(&config.https_client_ca_file).map_err(|e| {
|
||||
let ca_pem = if config.https_client_ca_file.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(std::fs::read(&config.https_client_ca_file).map_err(|e| {
|
||||
format!(
|
||||
"Failed to read HTTPS client CA file '{}': {}",
|
||||
config.https_client_ca_file, e
|
||||
)
|
||||
})?;
|
||||
let cert = reqwest::Certificate::from_pem(&ca_pem).map_err(|e| {
|
||||
format!(
|
||||
"Failed to parse HTTPS client CA PEM '{}': {}",
|
||||
config.https_client_ca_file, e
|
||||
)
|
||||
})?;
|
||||
builder = builder.add_root_certificate(cert);
|
||||
}
|
||||
})?)
|
||||
};
|
||||
|
||||
match (
|
||||
let identity = match (
|
||||
config.https_client_cert_file.is_empty(),
|
||||
config.https_client_key_file.is_empty(),
|
||||
) {
|
||||
(true, true) => {}
|
||||
(true, true) => None,
|
||||
(false, false) => {
|
||||
let cert_pem = std::fs::read(&config.https_client_cert_file).map_err(|e| {
|
||||
format!(
|
||||
@@ -203,6 +198,45 @@ fn build_outgoing_http_client(
|
||||
config.https_client_key_file, e
|
||||
)
|
||||
})?;
|
||||
Some((cert_pem, key_pem))
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"HTTPS client requires both cert and key, got cert='{}' key='{}'",
|
||||
config.https_client_cert_file, config.https_client_key_file
|
||||
)
|
||||
.into());
|
||||
}
|
||||
};
|
||||
|
||||
let mut builder = outgoing_client_builder(redirect_policy);
|
||||
if seaweed_common::fips::process_mode().is_fips() {
|
||||
let tls = fips_outgoing_tls_config(
|
||||
ca_pem.as_deref(),
|
||||
identity.as_ref().map(|(cert, key)| (cert.as_slice(), key.as_slice())),
|
||||
Arc::new(seaweed_common::tls::crypto_provider()),
|
||||
)
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"Failed to build the HTTPS client TLS configuration (ca '{}', cert '{}', key '{}'): {}",
|
||||
config.https_client_ca_file,
|
||||
config.https_client_cert_file,
|
||||
config.https_client_key_file,
|
||||
e
|
||||
)
|
||||
})?;
|
||||
builder = builder.use_preconfigured_tls(tls);
|
||||
} else {
|
||||
if let Some(ca_pem) = &ca_pem {
|
||||
let cert = reqwest::Certificate::from_pem(ca_pem).map_err(|e| {
|
||||
format!(
|
||||
"Failed to parse HTTPS client CA PEM '{}': {}",
|
||||
config.https_client_ca_file, e
|
||||
)
|
||||
})?;
|
||||
builder = builder.add_root_certificate(cert);
|
||||
}
|
||||
if let Some((cert_pem, key_pem)) = identity {
|
||||
let mut identity_pem = cert_pem;
|
||||
if !identity_pem.ends_with(b"\n") {
|
||||
identity_pem.push(b'\n');
|
||||
@@ -216,18 +250,45 @@ fn build_outgoing_http_client(
|
||||
})?;
|
||||
builder = builder.identity(identity);
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"HTTPS client requires both cert and key, got cert='{}' key='{}'",
|
||||
config.https_client_cert_file, config.https_client_key_file
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok((builder.build()?, scheme.to_string()))
|
||||
}
|
||||
|
||||
/// The outgoing HTTPS client configuration in FIPS mode: the roots, CA and
|
||||
/// identity reqwest would use, with the Extended Master Secret required on
|
||||
/// TLS 1.2 as Go requires it. reqwest leaves `require_ems` at rustls's
|
||||
/// default, which is off for a provider that is not FIPS-validated.
|
||||
fn fips_outgoing_tls_config(
|
||||
ca_pem: Option<&[u8]>,
|
||||
identity: Option<(&[u8], &[u8])>,
|
||||
provider: Arc<rustls::crypto::CryptoProvider>,
|
||||
) -> Result<rustls::ClientConfig, Box<dyn std::error::Error>> {
|
||||
use rustls::pki_types::pem::PemObject;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
|
||||
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
if let Some(ca) = ca_pem {
|
||||
for cert in CertificateDer::pem_slice_iter(ca) {
|
||||
roots.add(cert?)?;
|
||||
}
|
||||
}
|
||||
let builder = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.with_root_certificates(roots);
|
||||
let mut tls = match identity {
|
||||
Some((cert, key)) => {
|
||||
let chain = CertificateDer::pem_slice_iter(cert).collect::<Result<Vec<_>, _>>()?;
|
||||
builder.with_client_auth_cert(chain, PrivateKeyDer::from_pem_slice(key)?)?
|
||||
}
|
||||
None => builder.with_no_client_auth(),
|
||||
};
|
||||
tls.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
tls.require_ems = true;
|
||||
Ok(tls)
|
||||
}
|
||||
|
||||
fn tls_policy_is_configured(policy: &TlsPolicy) -> bool {
|
||||
!policy.min_version.is_empty()
|
||||
|| !policy.max_version.is_empty()
|
||||
@@ -249,6 +310,7 @@ fn build_grpc_server_tls_acceptor(
|
||||
tls_policy: &TlsPolicy,
|
||||
allowed_wildcard_domain: &str,
|
||||
allowed_common_names: &[String],
|
||||
health_check_common_names: &[String],
|
||||
) -> Result<Option<TlsAcceptor>, Box<dyn std::error::Error>> {
|
||||
if cert_path.is_empty() && key_path.is_empty() {
|
||||
return Ok(None);
|
||||
@@ -262,6 +324,7 @@ fn build_grpc_server_tls_acceptor(
|
||||
let client_auth_policy = GrpcClientAuthPolicy {
|
||||
allowed_common_names: allowed_common_names.to_vec(),
|
||||
allowed_wildcard_domain: allowed_wildcard_domain.to_string(),
|
||||
health_check_common_names: health_check_common_names.to_vec(),
|
||||
};
|
||||
let mut server_config = build_rustls_server_config_with_grpc_client_auth(
|
||||
cert_path,
|
||||
@@ -329,6 +392,32 @@ fn build_volume_grpc_service(
|
||||
.max_encoding_message_size(GRPC_MAX_MESSAGE_SIZE)
|
||||
}
|
||||
|
||||
const GRPC_HEALTH_SERVICES: [&str; 3] = [
|
||||
"",
|
||||
<VolumeServerServer<VolumeGrpcService> as tonic::server::NamedService>::NAME,
|
||||
<tonic_health::pb::health_server::HealthServer<tonic_health::server::HealthService> as tonic::server::NamedService>::NAME,
|
||||
];
|
||||
|
||||
async fn build_grpc_health_service() -> (
|
||||
tonic_health::server::HealthReporter,
|
||||
tonic_health::pb::health_server::HealthServer<impl tonic_health::pb::health_server::Health>,
|
||||
) {
|
||||
let (reporter, service) = tonic_health::server::health_reporter();
|
||||
for name in GRPC_HEALTH_SERVICES {
|
||||
reporter
|
||||
.set_service_status(name, tonic_health::ServingStatus::Serving)
|
||||
.await;
|
||||
}
|
||||
(reporter, service)
|
||||
}
|
||||
|
||||
/// Ends open Watch streams, which graceful shutdown would otherwise wait on.
|
||||
async fn end_grpc_health_watches(mut reporter: tonic_health::server::HealthReporter) {
|
||||
for name in GRPC_HEALTH_SERVICES {
|
||||
reporter.clear_service_status(name).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_idle_timeout<S>(
|
||||
stream: S,
|
||||
idle_timeout: std::time::Duration,
|
||||
@@ -578,6 +667,7 @@ async fn run(
|
||||
&config.tls_policy,
|
||||
&config.grpc_allowed_wildcard_domain,
|
||||
&config.grpc_volume_allowed_common_names,
|
||||
&config.grpc_health_check_common_names,
|
||||
)?;
|
||||
|
||||
info!("Starting HTTP server on {}", admin_addr);
|
||||
@@ -740,6 +830,7 @@ async fn run(
|
||||
let grpc_handle = {
|
||||
let grpc_state = state.clone();
|
||||
let grpc_tls_acceptor = grpc_tls_acceptor.clone();
|
||||
let health_check_only = HealthCheckOnlyLayer::new(&config.grpc_health_check_common_names);
|
||||
let mut shutdown_rx = shutdown_tx.subscribe();
|
||||
let shutdown_tx_grpc = shutdown_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
@@ -754,17 +845,21 @@ async fn run(
|
||||
.register_encoded_file_descriptor_set(seaweed_volume::pb::FILE_DESCRIPTOR_SET)
|
||||
.build_v1alpha()
|
||||
.expect("Failed to build gRPC reflection v1alpha service");
|
||||
let (health_reporter, health_service) = build_grpc_health_service().await;
|
||||
let result = if let Some(tls_acceptor) = grpc_tls_acceptor {
|
||||
let incoming =
|
||||
grpc_tls_incoming(grpc_listener, tls_acceptor, GRPC_TLS_HANDSHAKE_TIMEOUT);
|
||||
info!("gRPC server listening on {} (TLS enabled)", grpc_local_addr);
|
||||
build_grpc_server_builder()
|
||||
.layer(health_check_only)
|
||||
.layer(GrpcRequestIdLayer)
|
||||
.add_service(reflection_v1)
|
||||
.add_service(reflection_v1alpha)
|
||||
.add_service(health_service)
|
||||
.add_service(build_volume_grpc_service(grpc_service))
|
||||
.serve_with_incoming_shutdown(incoming, async move {
|
||||
let _ = shutdown_rx.recv().await;
|
||||
end_grpc_health_watches(health_reporter).await;
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
@@ -774,9 +869,11 @@ async fn run(
|
||||
.layer(GrpcRequestIdLayer)
|
||||
.add_service(reflection_v1)
|
||||
.add_service(reflection_v1alpha)
|
||||
.add_service(health_service)
|
||||
.add_service(build_volume_grpc_service(grpc_service))
|
||||
.serve_with_incoming_shutdown(incoming, async move {
|
||||
let _ = shutdown_rx.recv().await;
|
||||
end_grpc_health_watches(health_reporter).await;
|
||||
})
|
||||
.await
|
||||
};
|
||||
@@ -1165,6 +1262,61 @@ mod tests {
|
||||
/// A connect that never finishes fails at the 5 s bound. It stalls in the
|
||||
/// resolver, which the connect bound also covers, because that needs no
|
||||
/// routing: a real unanswered SYN depends on the host's network.
|
||||
#[tokio::test]
|
||||
async fn grpc_health_answers_for_the_volume_server() {
|
||||
use tonic_health::pb::{HealthCheckRequest, health_client::HealthClient};
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (health_reporter, health_service) = super::build_grpc_health_service().await;
|
||||
tokio::spawn(
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(health_service)
|
||||
.serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)),
|
||||
);
|
||||
let channel = tonic::transport::Endpoint::from_shared(format!("http://{}", addr))
|
||||
.unwrap()
|
||||
.connect()
|
||||
.await
|
||||
.unwrap();
|
||||
let mut client = HealthClient::new(channel);
|
||||
for service in ["", "volume_server_pb.VolumeServer", "grpc.health.v1.Health"] {
|
||||
let response = client
|
||||
.check(HealthCheckRequest {
|
||||
service: service.to_string(),
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("Check({:?}): {}", service, e));
|
||||
assert_eq!(
|
||||
response.into_inner().status,
|
||||
tonic_health::pb::health_check_response::ServingStatus::Serving as i32,
|
||||
"Check({:?})",
|
||||
service
|
||||
);
|
||||
}
|
||||
let err = client
|
||||
.check(HealthCheckRequest {
|
||||
service: "master_pb.Seaweed".to_string(),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), tonic::Code::NotFound);
|
||||
|
||||
let mut watch = client
|
||||
.watch(HealthCheckRequest {
|
||||
service: String::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.into_inner();
|
||||
assert!(watch.message().await.unwrap().is_some());
|
||||
super::end_grpc_health_watches(health_reporter).await;
|
||||
let ended = tokio::time::timeout(std::time::Duration::from_secs(5), watch.message())
|
||||
.await
|
||||
.expect("Watch still open after end_grpc_health_watches");
|
||||
assert!(matches!(ended, Ok(None)), "{:?}", ended);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn outgoing_client_bounds_a_stalled_connect() {
|
||||
struct Stalled;
|
||||
@@ -1189,6 +1341,24 @@ mod tests {
|
||||
assert_eq!(started.elapsed(), super::OUTGOING_CONNECT_TIMEOUT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fips_outgoing_tls_requires_ems() {
|
||||
let provider = std::sync::Arc::new(seaweed_common::tls::provider_for(
|
||||
seaweed_common::fips::FipsMode::On,
|
||||
));
|
||||
let tls = super::fips_outgoing_tls_config(
|
||||
Some(TEST_CA_PEM.as_bytes()),
|
||||
Some((TEST_LEAF_PEM.as_bytes(), TEST_LEAF_KEY_PEM.as_bytes())),
|
||||
provider.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(tls.require_ems);
|
||||
assert_eq!(tls.alpn_protocols, vec![b"http/1.1".to_vec()]);
|
||||
|
||||
let malformed_ca = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
|
||||
assert!(super::fips_outgoing_tls_config(Some(malformed_ca), None, provider).is_err());
|
||||
}
|
||||
|
||||
fn write_pem(dir: &tempfile::TempDir, name: &str, body: &str) -> String {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, body).unwrap();
|
||||
@@ -1205,7 +1375,7 @@ mod tests {
|
||||
let ca = write_pem(dir, "ca.pem", TEST_CA_PEM);
|
||||
let cert = write_pem(dir, "leaf.pem", TEST_LEAF_PEM);
|
||||
let key = write_pem(dir, "leaf.key", TEST_LEAF_KEY_PEM);
|
||||
build_grpc_server_tls_acceptor(&cert, &key, &ca, &TlsPolicy::default(), "", &[])
|
||||
build_grpc_server_tls_acceptor(&cert, &key, &ca, &TlsPolicy::default(), "", &[], &[])
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
}
|
||||
@@ -1287,11 +1457,78 @@ mod tests {
|
||||
);
|
||||
|
||||
assert!(
|
||||
build_grpc_server_tls_acceptor(&cert, &key, "", &TlsPolicy::default(), "", &[])
|
||||
build_grpc_server_tls_acceptor(&cert, &key, "", &TlsPolicy::default(), "", &[], &[])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// A certificate on grpc.health_check_commonNames passes the handshake even
|
||||
/// with allowed_commonNames set, and reaches only the health service.
|
||||
#[tokio::test]
|
||||
async fn test_grpc_health_check_common_name_reaches_only_health() {
|
||||
use seaweed_volume::pb::volume_server_pb::{
|
||||
VolumeServerStatusRequest, volume_server_client::VolumeServerClient,
|
||||
};
|
||||
use seaweed_volume::security::health_check_access::HealthCheckOnlyLayer;
|
||||
use tonic::transport::{Certificate, ClientTlsConfig, Endpoint, Identity};
|
||||
use tonic_health::pb::{HealthCheckRequest, health_client::HealthClient};
|
||||
|
||||
seaweed_volume::security::tls::install_default_crypto_provider();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cert = write_pem(&dir, "leaf.pem", TEST_LEAF_PEM);
|
||||
let key = write_pem(&dir, "leaf.key", TEST_LEAF_KEY_PEM);
|
||||
let ca = write_pem(&dir, "ca.pem", TEST_CA_PEM);
|
||||
let health_names = vec!["localhost".to_string()];
|
||||
let acceptor = build_grpc_server_tls_acceptor(
|
||||
&cert,
|
||||
&key,
|
||||
&ca,
|
||||
&TlsPolicy::default(),
|
||||
"",
|
||||
&["volume".to_string()],
|
||||
&health_names,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let incoming = grpc_tls_incoming(listener, acceptor, GRPC_TLS_HANDSHAKE_TIMEOUT);
|
||||
let (_health_reporter, health_service) = super::build_grpc_health_service().await;
|
||||
tokio::spawn(
|
||||
tonic::transport::Server::builder()
|
||||
.layer(HealthCheckOnlyLayer::new(&health_names))
|
||||
.add_service(health_service)
|
||||
.serve_with_incoming(incoming),
|
||||
);
|
||||
|
||||
let tls = ClientTlsConfig::new()
|
||||
.ca_certificate(Certificate::from_pem(TEST_CA_PEM))
|
||||
.identity(Identity::from_pem(TEST_LEAF_PEM, TEST_LEAF_KEY_PEM))
|
||||
.domain_name("localhost");
|
||||
let channel = Endpoint::from_shared(format!("https://{}", addr))
|
||||
.unwrap()
|
||||
.tls_config(tls)
|
||||
.unwrap()
|
||||
.connect()
|
||||
.await
|
||||
.unwrap();
|
||||
let response = HealthClient::new(channel.clone())
|
||||
.check(HealthCheckRequest {
|
||||
service: String::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
response.into_inner().status,
|
||||
tonic_health::pb::health_check_response::ServingStatus::Serving as i32
|
||||
);
|
||||
let err = VolumeServerClient::new(channel)
|
||||
.volume_server_status(VolumeServerStatusRequest {})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), tonic::Code::PermissionDenied, "{}", err);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_grpc_server_tls_errors_when_files_are_missing() {
|
||||
assert!(
|
||||
@@ -1302,6 +1539,7 @@ mod tests {
|
||||
&TlsPolicy::default(),
|
||||
"",
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
@@ -1338,6 +1576,7 @@ mod tests {
|
||||
},
|
||||
"",
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! - Guard: combines whitelist IP checking with JWT token validation
|
||||
//! - JWT: HS256 HMAC signing with file-id claims
|
||||
|
||||
pub mod health_check_access;
|
||||
pub mod tls;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use hyper::http;
|
||||
use rustls::pki_types::CertificateDer;
|
||||
use tonic::transport::server::{TcpConnectInfo, TlsConnectInfo};
|
||||
use tower::{Layer, Service};
|
||||
|
||||
use super::tls::parse_common_name;
|
||||
|
||||
const GRPC_HEALTH_SERVICE_PREFIX: &str = "/grpc.health.v1.Health/";
|
||||
|
||||
/// Confines clients whose certificate common name is in
|
||||
/// grpc.health_check_commonNames to the gRPC health service, like the Go
|
||||
/// servers' healthCheckOnlyTap. A name on allowed_commonNames too stays
|
||||
/// confined.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct HealthCheckOnlyLayer {
|
||||
names: Arc<HashSet<String>>,
|
||||
}
|
||||
|
||||
impl HealthCheckOnlyLayer {
|
||||
pub fn new(names: &[String]) -> Self {
|
||||
Self {
|
||||
names: Arc::new(names.iter().cloned().collect()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Layer<S> for HealthCheckOnlyLayer {
|
||||
type Service = HealthCheckOnlyService<S>;
|
||||
|
||||
fn layer(&self, inner: S) -> Self::Service {
|
||||
HealthCheckOnlyService {
|
||||
inner,
|
||||
names: self.names.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HealthCheckOnlyService<S> {
|
||||
inner: S,
|
||||
names: Arc<HashSet<String>>,
|
||||
}
|
||||
|
||||
impl<S, B> Service<http::Request<B>> for HealthCheckOnlyService<S>
|
||||
where
|
||||
S: Service<http::Request<B>, Response = http::Response<tonic::body::Body>>,
|
||||
S::Future: Send + 'static,
|
||||
{
|
||||
type Response = http::Response<tonic::body::Body>;
|
||||
type Error = S::Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
self.inner.poll_ready(cx)
|
||||
}
|
||||
|
||||
fn call(&mut self, request: http::Request<B>) -> Self::Future {
|
||||
let peer_certs = request
|
||||
.extensions()
|
||||
.get::<TlsConnectInfo<TcpConnectInfo>>()
|
||||
.and_then(|info| info.peer_certs());
|
||||
if let Some(common_name) = health_check_confined(
|
||||
&self.names,
|
||||
request.uri().path(),
|
||||
peer_certs.as_deref().map(Vec::as_slice),
|
||||
) {
|
||||
let status = tonic::Status::permission_denied(format!(
|
||||
"certificate {:?} may only call the gRPC health service",
|
||||
common_name
|
||||
));
|
||||
return Box::pin(async move { Ok(status.into_http()) });
|
||||
}
|
||||
Box::pin(self.inner.call(request))
|
||||
}
|
||||
}
|
||||
|
||||
fn health_check_confined(
|
||||
names: &HashSet<String>,
|
||||
path: &str,
|
||||
peer_certs: Option<&[CertificateDer<'static>]>,
|
||||
) -> Option<String> {
|
||||
if names.is_empty() || path.starts_with(GRPC_HEALTH_SERVICE_PREFIX) {
|
||||
return None;
|
||||
}
|
||||
let common_name = parse_common_name(peer_certs?.first()?).ok()?;
|
||||
names.contains(&common_name).then_some(common_name)
|
||||
}
|
||||
@@ -26,6 +26,9 @@ pub struct TlsPolicy {
|
||||
pub struct GrpcClientAuthPolicy {
|
||||
pub allowed_common_names: Vec<String>,
|
||||
pub allowed_wildcard_domain: String,
|
||||
/// Pass the handshake like allowed_common_names, but HealthCheckOnlyLayer
|
||||
/// lets them call only the gRPC health service.
|
||||
pub health_check_common_names: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -53,6 +56,7 @@ struct CommonNameVerifier {
|
||||
inner: Arc<dyn ClientCertVerifier>,
|
||||
allowed_common_names: HashSet<String>,
|
||||
allowed_wildcard_domain: String,
|
||||
health_check_common_names: HashSet<String>,
|
||||
}
|
||||
|
||||
impl ClientCertVerifier for CommonNameVerifier {
|
||||
@@ -86,7 +90,8 @@ impl ClientCertVerifier for CommonNameVerifier {
|
||||
&common_name,
|
||||
&self.allowed_common_names,
|
||||
&self.allowed_wildcard_domain,
|
||||
) {
|
||||
) || self.health_check_common_names.contains(&common_name)
|
||||
{
|
||||
return Ok(ClientCertVerified::assertion());
|
||||
}
|
||||
Err(rustls::Error::General(format!(
|
||||
@@ -186,6 +191,11 @@ fn build_rustls_server_config_with_client_auth(
|
||||
.cloned()
|
||||
.collect(),
|
||||
allowed_wildcard_domain: client_auth_policy.allowed_wildcard_domain.clone(),
|
||||
health_check_common_names: client_auth_policy
|
||||
.health_check_common_names
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
})
|
||||
} else {
|
||||
verifier
|
||||
@@ -449,7 +459,7 @@ fn parse_cipher_suite_name(value: &str) -> Result<CipherSuite, TlsPolicyError> {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_common_name(cert: &CertificateDer<'_>) -> Result<String, TlsPolicyError> {
|
||||
pub(crate) fn parse_common_name(cert: &CertificateDer<'_>) -> Result<String, TlsPolicyError> {
|
||||
let (_, certificate) = X509Certificate::from_der(cert.as_ref())
|
||||
.map_err(|e| TlsPolicyError(format!("parse X.509 certificate failed: {}", e)))?;
|
||||
let common_name = certificate
|
||||
|
||||
@@ -454,6 +454,7 @@ mod tests {
|
||||
grpc_ca_file: String::new(),
|
||||
grpc_allowed_wildcard_domain: String::new(),
|
||||
grpc_volume_allowed_common_names: vec![],
|
||||
grpc_health_check_common_names: vec![],
|
||||
tls_policy: TlsPolicy::default(),
|
||||
security_file: String::new(),
|
||||
}
|
||||
|
||||
@@ -51,7 +51,6 @@ fn scrub_mode_label(mode: i32) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Go formats the id in decimal; fs.verify matches the "needle not found " prefix.
|
||||
/// Maps a failed EC shard copy to a bounded reason label. Errors from the
|
||||
/// source arrive as gRPC text, so it matches messages. Mirrors Go's
|
||||
/// ecShardCopyFailureReason.
|
||||
@@ -82,6 +81,7 @@ fn ec_shard_copy_failure_reason(status: &Status) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Go formats the id in decimal; fs.verify matches the "needle not found " prefix.
|
||||
fn needle_not_found(needle_id: NeedleId) -> Status {
|
||||
Status::not_found(format!("needle not found {}", needle_id.0))
|
||||
}
|
||||
@@ -1604,6 +1604,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
let rp = crate::storage::super_block::ReplicaPlacement::from_string(&req.replication)
|
||||
.map_err(|e| Status::invalid_argument(e.to_string()))?;
|
||||
@@ -2007,6 +2008,8 @@ impl VolumeServer for VolumeGrpcService {
|
||||
) -> Result<Response<volume_server_pb::VolumeMountResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(req.collection.as_deref().unwrap_or_default())
|
||||
.map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
// A decode in flight may be mid-compaction on this volume's
|
||||
@@ -2367,6 +2370,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
if !self.state.allow_untrusted_remote_endpoints {
|
||||
@@ -3457,6 +3461,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
let collection = &req.collection;
|
||||
|
||||
@@ -3927,6 +3932,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
if !self.state.allow_untrusted_remote_endpoints {
|
||||
@@ -4007,6 +4013,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsDeleteResponse>, Status> {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
if req.full_teardown {
|
||||
@@ -4150,6 +4157,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
request: Request<volume_server_pb::VolumeEcShardsMountRequest>,
|
||||
) -> Result<Response<volume_server_pb::VolumeEcShardsMountResponse>, Status> {
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
// Pre-validate the ENTIRE batch before any mutation: validating inside
|
||||
@@ -4481,6 +4489,7 @@ impl VolumeServer for VolumeGrpcService {
|
||||
self.check_grpc_admin_auth(&request)?;
|
||||
self.state.check_maintenance()?;
|
||||
let req = request.into_inner();
|
||||
check_volume_collection(&req.collection).map_err(Status::invalid_argument)?;
|
||||
let vid = VolumeId(req.volume_id);
|
||||
|
||||
// Staged mode: the caller decoded off-box and streamed the normal volume
|
||||
@@ -6023,6 +6032,8 @@ mod copy_source {
|
||||
.await
|
||||
.map_err(|e| Status::internal(format!("read volume file status failed, {}", e)))?
|
||||
.into_inner();
|
||||
super::check_volume_collection(&vol_info.collection)
|
||||
.map_err(|e| Status::internal(format!("source volume {}: {}", volume_id, e)))?;
|
||||
Ok(Self(vol_info))
|
||||
}
|
||||
}
|
||||
@@ -13375,6 +13386,150 @@ mod tests {
|
||||
assert!(err.message().contains("is being copied"), "{}", err.message());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_handlers_reject_a_collection_that_leaves_the_volume_dir() {
|
||||
use volume_server_pb::*;
|
||||
let (service, _tmp) = make_local_service_with_volume("collection_check", None);
|
||||
for collection in ["..", "../outside", "a/b", "a\\b"] {
|
||||
let c = || collection.to_string();
|
||||
let errs = [
|
||||
(
|
||||
"allocate_volume",
|
||||
service
|
||||
.allocate_volume(Request::new(AllocateVolumeRequest {
|
||||
volume_id: 7,
|
||||
collection: c(),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
(
|
||||
"volume_mount",
|
||||
service
|
||||
.volume_mount(Request::new(VolumeMountRequest {
|
||||
volume_id: 7,
|
||||
collection: Some(c()),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
(
|
||||
"volume_copy",
|
||||
service
|
||||
.volume_copy(Request::new(VolumeCopyRequest {
|
||||
volume_id: 7,
|
||||
collection: c(),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
(
|
||||
"volume_ec_shards_rebuild",
|
||||
service
|
||||
.volume_ec_shards_rebuild(Request::new(VolumeEcShardsRebuildRequest {
|
||||
volume_id: 7,
|
||||
collection: c(),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
(
|
||||
"volume_ec_shards_copy",
|
||||
service
|
||||
.volume_ec_shards_copy(Request::new(VolumeEcShardsCopyRequest {
|
||||
volume_id: 7,
|
||||
collection: c(),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
(
|
||||
"volume_ec_shards_delete",
|
||||
service
|
||||
.volume_ec_shards_delete(Request::new(VolumeEcShardsDeleteRequest {
|
||||
volume_id: 7,
|
||||
collection: c(),
|
||||
full_teardown: true,
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
(
|
||||
"volume_ec_shards_mount",
|
||||
service
|
||||
.volume_ec_shards_mount(Request::new(VolumeEcShardsMountRequest {
|
||||
volume_id: 7,
|
||||
collection: c(),
|
||||
shard_ids: vec![0],
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
(
|
||||
"volume_ec_shards_to_volume",
|
||||
service
|
||||
.volume_ec_shards_to_volume(Request::new(VolumeEcShardsToVolumeRequest {
|
||||
volume_id: 7,
|
||||
collection: c(),
|
||||
from_staged: true,
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err(),
|
||||
),
|
||||
];
|
||||
for (name, err) in errs {
|
||||
let err = err.unwrap_or_else(|| panic!("{name}({collection:?}) succeeded"));
|
||||
assert_eq!(
|
||||
err.code(),
|
||||
tonic::Code::InvalidArgument,
|
||||
"{name}({collection:?})"
|
||||
);
|
||||
assert!(
|
||||
err.message().contains("invalid collection"),
|
||||
"{name}({collection:?}): {}",
|
||||
err.message()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_volume_copy_rejects_a_source_collection_that_leaves_the_volume_dir() {
|
||||
let (source_service, _source_tmp) = make_local_service_with_volume("a\\b", None);
|
||||
let (port, _shutdown) = serve_source(source_service).await;
|
||||
let (dest_service, _dest_tmp) = make_local_service_with_volume("", None);
|
||||
dest_service
|
||||
.state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.delete_volume(VolumeId(1), false, false, false)
|
||||
.unwrap();
|
||||
|
||||
let err = dest_service
|
||||
.volume_copy(Request::new(volume_server_pb::VolumeCopyRequest {
|
||||
volume_id: 1,
|
||||
source_data_node: format!("127.0.0.1:1.{}", port),
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.err()
|
||||
.expect("copy from a source reporting a path collection succeeded");
|
||||
assert!(
|
||||
err.message().contains("invalid collection"),
|
||||
"{}",
|
||||
err.message()
|
||||
);
|
||||
}
|
||||
|
||||
/// The staged adoption renames .copying files into place and mounts, so
|
||||
/// it holds the copy claim for the whole span — Go's adoptStagedVolume.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -174,6 +174,7 @@ mod tests {
|
||||
grpc_ca_file: String::new(),
|
||||
grpc_allowed_wildcard_domain: String::new(),
|
||||
grpc_volume_allowed_common_names: vec![],
|
||||
grpc_health_check_common_names: vec![],
|
||||
tls_policy: TlsPolicy::default(),
|
||||
security_file: String::new(),
|
||||
}
|
||||
|
||||
Generated
+1
@@ -6363,6 +6363,7 @@ dependencies = [
|
||||
"protoc-bin-vendored",
|
||||
"reqwest 0.12.28",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pemfile",
|
||||
"seaweed-common",
|
||||
"thiserror 2.0.20",
|
||||
|
||||
@@ -17,6 +17,9 @@ prost.workspace = true
|
||||
# System roots for volume servers behind public CAs, as Go's http client.
|
||||
reqwest = { version = "0.12", default-features = false, features = ["multipart", "rustls-tls-native-roots"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
# The system roots for the FIPS-mode client configuration sw-client builds
|
||||
# itself; the version reqwest's rustls-tls-native-roots uses.
|
||||
rustls-native-certs = "0.8"
|
||||
# The process-wide rustls provider every SeaweedFS Rust binary installs.
|
||||
seaweed-common = { path = "../../../seaweed-common" }
|
||||
thiserror = "2"
|
||||
|
||||
@@ -486,12 +486,31 @@ async fn expand_chunks(
|
||||
};
|
||||
let manifest = FileChunkManifest::decode(raw.as_slice())
|
||||
.with_context(|| format!("decode manifest {fid}"))?;
|
||||
let sub = Box::pin(expand_chunks(client, volumes, &manifest.chunks, decoder)).await?;
|
||||
let held = cut_to_manifest_span(chunk, manifest.chunks);
|
||||
let sub = Box::pin(expand_chunks(client, volumes, &held, decoder)).await?;
|
||||
data.extend(sub);
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// The chunks a manifest holds, cut to the manifest's span: a truncate may
|
||||
/// have shortened the manifest and left its chunks whole.
|
||||
fn cut_to_manifest_span(manifest: &FileChunk, held: Vec<FileChunk>) -> Vec<FileChunk> {
|
||||
let end = manifest.offset + manifest.size as i64;
|
||||
held.into_iter()
|
||||
.filter_map(|mut c| {
|
||||
if c.offset + c.size as i64 <= end {
|
||||
return Some(c);
|
||||
}
|
||||
if c.offset >= end {
|
||||
return None;
|
||||
}
|
||||
c.size = (end - c.offset) as u64;
|
||||
Some(c)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Resolve data chunks into non-overlapping visible intervals (latest write wins).
|
||||
fn resolve_visibles(chunks: &[FileChunk]) -> Vec<Visible> {
|
||||
if let Some(visibles) = resolve_visibles_ordered_non_overlapping(chunks) {
|
||||
@@ -1454,6 +1473,42 @@ mod tests {
|
||||
assert_eq!(tail, &plain[19..], "a size past u64::MAX reads to EOF");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_shortened_manifest_reads_only_its_span() {
|
||||
let plain: Vec<u8> = (0..16u8).map(|i| i + 1).collect();
|
||||
let inner = FileChunkManifest {
|
||||
chunks: vec![chunk("1,aa", 0, 8, 1), chunk("1,bb", 8, 8, 1)],
|
||||
};
|
||||
let needles = HashMap::from([
|
||||
("1,mm".to_string(), inner.encode_to_vec()),
|
||||
("1,aa".to_string(), plain[..8].to_vec()),
|
||||
("1,bb".to_string(), plain[8..].to_vec()),
|
||||
]);
|
||||
let volumes = VolumeReader::with_transport(Arc::new(BytesTransport {
|
||||
needles,
|
||||
reads: AtomicUsize::new(0),
|
||||
whole_reads: AtomicUsize::new(0),
|
||||
}));
|
||||
volumes.location_cache.learn(1, vec!["h:1".into()]);
|
||||
let mut manifest = chunk("1,mm", 0, 12, 1);
|
||||
manifest.is_chunk_manifest = true;
|
||||
let entry = Entry {
|
||||
attributes: Some(crate::filer_pb::FuseAttributes {
|
||||
file_size: 20,
|
||||
..Default::default()
|
||||
}),
|
||||
chunks: vec![manifest],
|
||||
..Default::default()
|
||||
};
|
||||
let mut client = FilerClient::connect_lazy("127.0.0.1:1").unwrap();
|
||||
let got = read_file(&mut client, &volumes, &entry, 0, 20)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut want = plain[..12].to_vec();
|
||||
want.resize(20, 0);
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn encrypted_chunks_need_a_decoder() {
|
||||
let (entry, plain, _, volumes) = encrypted_file();
|
||||
|
||||
@@ -238,9 +238,8 @@ impl HttpTransport {
|
||||
pub fn with_tls(tls: &HttpsTls) -> Result<Self> {
|
||||
install_crypto_provider();
|
||||
let builder = reqwest::Client::builder().connect_timeout(VOLUME_CONNECT_TIMEOUT);
|
||||
let builder = if tls.insecure_skip_verify && seaweed_common::fips::process_mode().is_fips()
|
||||
{
|
||||
builder.use_preconfigured_tls(unverified_tls_config(
|
||||
let builder = if seaweed_common::fips::process_mode().is_fips() {
|
||||
builder.use_preconfigured_tls(fips_tls_config(
|
||||
tls,
|
||||
Arc::new(seaweed_common::tls::crypto_provider()),
|
||||
)?)
|
||||
@@ -283,24 +282,31 @@ fn reqwest_tls(builder: reqwest::ClientBuilder, tls: &HttpsTls) -> Result<reqwes
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
/// The client configuration for `https.client.insecure_skip_verify` in FIPS
|
||||
/// mode, on `provider`. reqwest's verifier for that setting advertises its own
|
||||
/// signature schemes (SHA-1, Ed448) whatever the provider allows, so this one
|
||||
/// is built here: the server certificate is not checked, but handshake
|
||||
/// signatures are, with the provider's algorithms, and only its schemes are
|
||||
/// offered. HTTP/1.1 only, as the volume servers speak it.
|
||||
fn unverified_tls_config(
|
||||
tls: &HttpsTls,
|
||||
provider: Arc<CryptoProvider>,
|
||||
) -> Result<rustls::ClientConfig> {
|
||||
let verifier = Arc::new(UnverifiedServer {
|
||||
provider: provider.clone(),
|
||||
});
|
||||
let builder = rustls::ClientConfig::builder_with_provider(provider)
|
||||
/// The client configuration for `tls` in FIPS mode, on `provider`. It is
|
||||
/// built here rather than by reqwest for two reasons: reqwest leaves
|
||||
/// `require_ems` at rustls's default, which is off for a provider that is not
|
||||
/// FIPS-validated, while Go requires the Extended Master Secret for TLS 1.2
|
||||
/// in FIPS mode; and reqwest's verifier for `insecure_skip_verify` advertises
|
||||
/// its own signature schemes (SHA-1, Ed448) whatever the provider allows.
|
||||
/// Server certificates are checked against `ca` (the system roots without
|
||||
/// one); with `insecure_skip_verify` they are not, but handshake signatures
|
||||
/// still are, with the provider's algorithms, and only its schemes are
|
||||
/// offered, and a malformed `ca` is still refused, as reqwest refuses it on
|
||||
/// every path. HTTP/1.1 only, as the volume servers speak it.
|
||||
fn fips_tls_config(tls: &HttpsTls, provider: Arc<CryptoProvider>) -> Result<rustls::ClientConfig> {
|
||||
let builder = rustls::ClientConfig::builder_with_provider(provider.clone())
|
||||
.with_safe_default_protocol_versions()
|
||||
.context("TLS versions")?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(verifier);
|
||||
.context("TLS versions")?;
|
||||
let builder = if tls.insecure_skip_verify {
|
||||
if let Some(ca) = &tls.ca_pem {
|
||||
ca_roots(ca)?;
|
||||
}
|
||||
builder
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(UnverifiedServer { provider }))
|
||||
} else {
|
||||
builder.with_root_certificates(root_certificates(tls)?)
|
||||
};
|
||||
let mut config = match (&tls.cert_pem, &tls.key_pem) {
|
||||
(Some(cert), Some(key)) => {
|
||||
let chain = CertificateDer::pem_slice_iter(cert)
|
||||
@@ -315,10 +321,47 @@ fn unverified_tls_config(
|
||||
_ => bail!("https.client needs both cert and key, or neither"),
|
||||
};
|
||||
config.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
config.require_ems = config.require_ems || seaweed_common::tls::require_ems();
|
||||
config.require_ems = true;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The roots server certificates are checked against: the certificates in
|
||||
/// `https.client.ca`, else the system's.
|
||||
fn root_certificates(tls: &HttpsTls) -> Result<rustls::RootCertStore> {
|
||||
match &tls.ca_pem {
|
||||
Some(ca) => ca_roots(ca),
|
||||
None => native_roots(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The certificates in an `https.client.ca` PEM, refused when one does not
|
||||
/// parse, as reqwest refuses them.
|
||||
fn ca_roots(ca: &[u8]) -> Result<rustls::RootCertStore> {
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
for cert in CertificateDer::pem_slice_iter(ca) {
|
||||
roots
|
||||
.add(cert.context("https.client.ca")?)
|
||||
.context("https.client.ca")?;
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
/// The system's root certificates as reqwest loads them: ones rustls cannot
|
||||
/// parse are skipped, and it is an error only when none parses and some did
|
||||
/// not.
|
||||
fn native_roots() -> Result<rustls::RootCertStore> {
|
||||
let loaded = rustls_native_certs::load_native_certs();
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
let (added, ignored) = roots.add_parsable_certificates(loaded.certs);
|
||||
if added == 0 && ignored > 0 {
|
||||
bail!(
|
||||
"no valid certificate in the system root store: {:?}",
|
||||
loaded.errors
|
||||
);
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
/// Accepts any server certificate and host name, as `insecure_skip_verify`
|
||||
/// asks, while verifying the handshake signatures with the provider's
|
||||
/// algorithms and offering only their schemes.
|
||||
@@ -573,31 +616,148 @@ mod tests {
|
||||
recorder.0.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() {
|
||||
let provider = Arc::new(seaweed_common::tls::provider_for(
|
||||
/// The provider FIPS mode installs.
|
||||
fn fips_provider() -> Arc<CryptoProvider> {
|
||||
Arc::new(seaweed_common::tls::provider_for(
|
||||
seaweed_common::fips::FipsMode::On,
|
||||
));
|
||||
let config = unverified_tls_config(&HttpsTls::default(), provider).unwrap();
|
||||
let mut offered = offered_schemes(config);
|
||||
))
|
||||
}
|
||||
|
||||
/// `https.client` with certificate checks off, as FIPS mode builds it.
|
||||
fn unverified() -> HttpsTls {
|
||||
HttpsTls {
|
||||
insecure_skip_verify: true,
|
||||
..HttpsTls::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// `https.client` with `ca` set to the lance test CA.
|
||||
fn with_test_ca() -> HttpsTls {
|
||||
HttpsTls {
|
||||
ca_pem: Some(TEST_CA.to_vec()),
|
||||
..HttpsTls::default()
|
||||
}
|
||||
}
|
||||
|
||||
const TEST_CA: &[u8] = include_bytes!("../../lance/tests/tls/ca.pem");
|
||||
const TEST_LEAF: &[u8] = include_bytes!("../../lance/tests/tls/a.pem");
|
||||
const TEST_LEAF_KEY: &[u8] = include_bytes!("../../lance/tests/tls/a.key");
|
||||
|
||||
/// Runs a full handshake between `config` and a server presenting the
|
||||
/// lance test leaf for `localhost`, in memory.
|
||||
fn handshake(config: rustls::ClientConfig) -> std::result::Result<(), rustls::Error> {
|
||||
let chain = CertificateDer::pem_slice_iter(TEST_LEAF)
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
let key = PrivateKeyDer::from_pem_slice(TEST_LEAF_KEY).unwrap();
|
||||
let server_config = rustls::ServerConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::aws_lc_rs::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(chain, key)
|
||||
.unwrap();
|
||||
let name = ServerName::try_from("localhost").unwrap();
|
||||
let mut client = rustls::ClientConnection::new(Arc::new(config), name).unwrap();
|
||||
let mut server = rustls::ServerConnection::new(Arc::new(server_config)).unwrap();
|
||||
while client.is_handshaking() || server.is_handshaking() {
|
||||
let mut flight = Vec::new();
|
||||
client.write_tls(&mut flight).unwrap();
|
||||
if !flight.is_empty() {
|
||||
server.read_tls(&mut flight.as_slice()).unwrap();
|
||||
server.process_new_packets()?;
|
||||
}
|
||||
let mut flight = Vec::new();
|
||||
server.write_tls(&mut flight).unwrap();
|
||||
if !flight.is_empty() {
|
||||
client.read_tls(&mut flight.as_slice()).unwrap();
|
||||
client.process_new_packets()?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `offered` and the FIPS signature schemes, each sorted.
|
||||
fn sorted_against_fips(
|
||||
mut offered: Vec<SignatureScheme>,
|
||||
) -> (Vec<SignatureScheme>, Vec<SignatureScheme>) {
|
||||
let mut want = seaweed_common::tls::FIPS_SIGNATURE_SCHEMES.to_vec();
|
||||
offered.sort_by_key(|s| u16::from(*s));
|
||||
want.sort_by_key(|s| u16::from(*s));
|
||||
(offered, want)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unverified_tls_in_fips_mode_offers_only_the_fips_schemes() {
|
||||
let config = fips_tls_config(&unverified(), fips_provider()).unwrap();
|
||||
assert!(config.require_ems);
|
||||
let (offered, want) = sorted_against_fips(offered_schemes(config));
|
||||
assert_eq!(offered, want);
|
||||
assert!(!offered.contains(&SignatureScheme::ED448));
|
||||
assert!(!offered.contains(&SignatureScheme::RSA_PKCS1_SHA1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unverified_tls_needs_both_halves_of_the_identity() {
|
||||
let provider = Arc::new(seaweed_common::tls::provider_for(
|
||||
seaweed_common::fips::FipsMode::On,
|
||||
));
|
||||
let half = HttpsTls {
|
||||
cert_pem: Some(b"x".to_vec()),
|
||||
fn verified_tls_in_fips_mode_requires_ems_and_checks_the_server() {
|
||||
let config = fips_tls_config(&with_test_ca(), fips_provider()).unwrap();
|
||||
assert!(config.require_ems);
|
||||
let (offered, want) = sorted_against_fips(offered_schemes(config.clone()));
|
||||
assert_eq!(offered, want);
|
||||
handshake(config).unwrap();
|
||||
|
||||
let wrong_ca = HttpsTls {
|
||||
ca_pem: Some(TEST_LEAF.to_vec()),
|
||||
..HttpsTls::default()
|
||||
};
|
||||
assert!(unverified_tls_config(&half, provider).is_err());
|
||||
let config = fips_tls_config(&wrong_ca, fips_provider()).unwrap();
|
||||
let err = handshake(config).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, rustls::Error::InvalidCertificate(_)),
|
||||
"{err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A PEM certificate block whose DER is not a certificate.
|
||||
const MALFORMED_CA: &[u8] = b"-----BEGIN CERTIFICATE-----
|
||||
AAAA
|
||||
-----END CERTIFICATE-----
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_malformed_ca_is_refused_with_and_without_certificate_checks() {
|
||||
for insecure_skip_verify in [false, true] {
|
||||
let tls = HttpsTls {
|
||||
ca_pem: Some(MALFORMED_CA.to_vec()),
|
||||
insecure_skip_verify,
|
||||
..HttpsTls::default()
|
||||
};
|
||||
let err = fips_tls_config(&tls, fips_provider()).unwrap_err();
|
||||
assert!(format!("{err:#}").contains("https.client.ca"), "{err:#}");
|
||||
assert!(
|
||||
HttpTransport::with_tls(&tls).is_err(),
|
||||
"off mode, insecure_skip_verify = {insecure_skip_verify}"
|
||||
);
|
||||
}
|
||||
let tls = HttpsTls {
|
||||
ca_pem: Some(TEST_CA.to_vec()),
|
||||
..unverified()
|
||||
};
|
||||
assert!(fips_tls_config(&tls, fips_provider()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fips_tls_needs_both_halves_of_the_identity() {
|
||||
let half = HttpsTls {
|
||||
cert_pem: Some(b"x".to_vec()),
|
||||
..unverified()
|
||||
};
|
||||
assert!(fips_tls_config(&half, fips_provider()).is_err());
|
||||
let half = HttpsTls {
|
||||
cert_pem: Some(b"x".to_vec()),
|
||||
..with_test_ca()
|
||||
};
|
||||
assert!(fips_tls_config(&half, fips_provider()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -254,6 +254,7 @@ spark = (SparkSession.builder
|
||||
.config("spark.hadoop.hive.metastore.schema.verification.record.version", "false")
|
||||
.config("spark.jars.ivy", ivy_dir)
|
||||
.config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:3.3.2,com.amazonaws:aws-java-sdk-bundle:1.12.262")
|
||||
.config("spark.jars.repositories", "https://maven-central.storage-download.googleapis.com/maven2/")
|
||||
.config("spark.hadoop.fs.s3a.access.key", "test")
|
||||
.config("spark.hadoop.fs.s3a.secret.key", "test")
|
||||
.config("spark.hadoop.fs.s3a.endpoint", "host.docker.internal:%d")
|
||||
|
||||
@@ -326,9 +326,17 @@ func (c *Cluster) waitForTCP(addr string) error {
|
||||
return fmt.Errorf("timed out waiting for tcp %s", addr)
|
||||
}
|
||||
|
||||
// stopProcess interrupts cmd and waits for it to exit, killing it after 10s.
|
||||
// A server that does not exit cleanly on SIGINT fails the test: a panic or a
|
||||
// hang on shutdown is a bug the tests would otherwise never see.
|
||||
// stopTimeout bounds a server's exit after SIGINT; stopDiskTimeout replaces it
|
||||
// once a thread of the server has been seen in an uninterruptible wait, such
|
||||
// as the close fsync on a slow CI disk.
|
||||
var (
|
||||
stopTimeout = 10 * time.Second
|
||||
stopDiskTimeout = time.Minute
|
||||
)
|
||||
|
||||
// stopProcess interrupts cmd and waits for it to exit, killing it after
|
||||
// stopTimeout. A server that does not exit cleanly on SIGINT fails the test: a
|
||||
// panic or a hang on shutdown is a bug the tests would otherwise never see.
|
||||
func stopProcess(tb testing.TB, name string, cmd *exec.Cmd) {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return
|
||||
@@ -340,18 +348,72 @@ func stopProcess(tb testing.TB, name string, cmd *exec.Cmd) {
|
||||
done <- cmd.Wait()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-time.After(10 * time.Second):
|
||||
start := time.Now()
|
||||
tick := time.NewTicker(100 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
diskWait := false
|
||||
for {
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
tb.Errorf("%s did not exit cleanly on SIGINT: %v", name, err)
|
||||
}
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
threads, inDiskWait := processThreads(cmd.Process.Pid)
|
||||
diskWait = diskWait || inDiskWait
|
||||
limit := stopTimeout
|
||||
if diskWait {
|
||||
limit = stopDiskTimeout
|
||||
}
|
||||
if time.Since(start) < limit {
|
||||
continue
|
||||
}
|
||||
_ = cmd.Process.Kill()
|
||||
<-done
|
||||
tb.Errorf("%s did not exit within 10s of SIGINT", name)
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
tb.Errorf("%s did not exit cleanly on SIGINT: %v", name, err)
|
||||
}
|
||||
tb.Errorf("%s did not exit within %v of SIGINT, threads: %s", name, limit, threads)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// processThreads summarizes pid's threads from /proc as "name state wchan"
|
||||
// with counts, and reports whether any is in uninterruptible sleep (D).
|
||||
func processThreads(pid int) (string, bool) {
|
||||
dir := fmt.Sprintf("/proc/%d/task", pid)
|
||||
tasks, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return "unavailable", false
|
||||
}
|
||||
counts := map[string]int{}
|
||||
var order []string
|
||||
inDiskWait := false
|
||||
for _, task := range tasks {
|
||||
stat, err := os.ReadFile(filepath.Join(dir, task.Name(), "stat"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
s := string(stat)
|
||||
open, end := strings.IndexByte(s, '('), strings.LastIndexByte(s, ')')
|
||||
if open < 0 || end < open || end+2 >= len(s) {
|
||||
continue
|
||||
}
|
||||
state := s[end+2]
|
||||
inDiskWait = inDiskWait || state == 'D'
|
||||
wchan, _ := os.ReadFile(filepath.Join(dir, task.Name(), "wchan"))
|
||||
key := fmt.Sprintf("%s %c %s", s[open+1:end], state, wchan)
|
||||
if counts[key] == 0 {
|
||||
order = append(order, key)
|
||||
}
|
||||
counts[key]++
|
||||
}
|
||||
parts := make([]string, 0, len(order))
|
||||
for _, key := range order {
|
||||
parts = append(parts, fmt.Sprintf("%dx[%s]", counts[key], key))
|
||||
}
|
||||
return strings.Join(parts, " "), inDiskWait
|
||||
}
|
||||
|
||||
func newWorkDir() (dir string, keepLogs bool, err error) {
|
||||
keepLogs = os.Getenv("VOLUME_SERVER_IT_KEEP_LOGS") == "1"
|
||||
dir, err = os.MkdirTemp("", "seaweedfs_volume_server_it_")
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package framework
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type errorRecorder struct {
|
||||
testing.TB
|
||||
errs []string
|
||||
}
|
||||
|
||||
func (r *errorRecorder) Errorf(format string, args ...any) {
|
||||
r.errs = append(r.errs, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
func TestStopProcessReportsTheThreadsOfAServerIgnoringSIGINT(t *testing.T) {
|
||||
if runtime.GOOS != "linux" {
|
||||
t.Skip("thread states come from /proc")
|
||||
}
|
||||
defer func(d time.Duration) { stopTimeout = d }(stopTimeout)
|
||||
stopTimeout = 200 * time.Millisecond
|
||||
|
||||
cmd := exec.Command("sh", "-c", `trap "" INT; exec sleep 30`)
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
}()
|
||||
waitForSleepThread(t, cmd.Process.Pid)
|
||||
rec := &errorRecorder{TB: t}
|
||||
stopProcess(rec, "server", cmd)
|
||||
|
||||
if len(rec.errs) != 1 || !strings.Contains(rec.errs[0], "server did not exit within") || !strings.Contains(rec.errs[0], "1x[sleep S ") {
|
||||
t.Fatalf("errors = %q", rec.errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessThreadsFindsNoDiskWaitInAnIdleProcess(t *testing.T) {
|
||||
if runtime.GOOS != "linux" {
|
||||
t.Skip("thread states come from /proc")
|
||||
}
|
||||
cmd := exec.Command("sleep", "30")
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
}()
|
||||
waitForSleepThread(t, cmd.Process.Pid)
|
||||
|
||||
threads, inDiskWait := processThreads(cmd.Process.Pid)
|
||||
if inDiskWait || !strings.HasPrefix(threads, "1x[sleep S ") {
|
||||
t.Fatalf("threads = %q, inDiskWait = %v", threads, inDiskWait)
|
||||
}
|
||||
}
|
||||
|
||||
// waitForSleepThread waits until pid has exec'd sleep and is sleeping, so
|
||||
// a SIGINT trap set before the exec is in place.
|
||||
func waitForSleepThread(t *testing.T, pid int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
threads, _ := processThreads(pid)
|
||||
if strings.HasPrefix(threads, "1x[sleep S ") {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("pid %d never reached sleep: %q", pid, threads)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -113,14 +113,15 @@ func getCollectionName(filerGroup, bucketName string) string {
|
||||
}
|
||||
|
||||
type AdminServer struct {
|
||||
masterClient *wdclient.MasterClient
|
||||
templateFS http.FileSystem
|
||||
dataDir string
|
||||
filerGroup string
|
||||
grpcDialOption grpc.DialOption
|
||||
cacheExpiration time.Duration
|
||||
lastCacheUpdate time.Time
|
||||
cachedTopology *ClusterTopology
|
||||
masterClient *wdclient.MasterClient
|
||||
templateFS http.FileSystem
|
||||
dataDir string
|
||||
filerGroup string
|
||||
grpcDialOption grpc.DialOption
|
||||
filerTokenSource security.FilerTokenSource
|
||||
cacheExpiration time.Duration
|
||||
lastCacheUpdate time.Time
|
||||
cachedTopology *ClusterTopology
|
||||
|
||||
// dashSamples is a bounded in-memory ring of recent cluster snapshots that
|
||||
// powers the dashboard's at-a-glance sparklines (see dashboard_metrics.go),
|
||||
@@ -215,6 +216,7 @@ func NewAdminServer(masters string, filerGroup string, templateFS http.FileSyste
|
||||
dataDir: dataDir,
|
||||
filerGroup: filerGroup,
|
||||
grpcDialOption: grpcDialOption,
|
||||
filerTokenSource: security.FilerAdminToken,
|
||||
cacheExpiration: defaultCacheTimeout,
|
||||
filerCacheExpiration: defaultFilerCacheTimeout,
|
||||
configPersistence: NewConfigPersistence(dataDir),
|
||||
|
||||
@@ -30,7 +30,7 @@ func (s *AdminServer) WithFilerClient(f func(client filer_pb.SeaweedFilerClient)
|
||||
return fmt.Errorf("no filer available")
|
||||
}
|
||||
|
||||
return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, s.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return f(client)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type dashAuthFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
}
|
||||
|
||||
func (dashAuthFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
|
||||
return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets", FilerGroup: "test"}, nil
|
||||
}
|
||||
|
||||
func (dashAuthFiler) LookupDirectoryEntry(context.Context, *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{}}, nil
|
||||
}
|
||||
|
||||
func dashAuthCheck(ctx context.Context, key security.SigningKey, require bool) error {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
values := md.Get("authorization")
|
||||
if len(key) == 0 {
|
||||
if require && len(values) == 0 {
|
||||
return status.Error(codes.Unauthenticated, "authentication required")
|
||||
}
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if len(values) != 1 {
|
||||
return status.Error(codes.Unauthenticated, "authentication required")
|
||||
}
|
||||
const prefix = "Bearer "
|
||||
if len(values[0]) <= len(prefix) || values[0][:len(prefix)] != prefix || !security.IsFilerAdminToken(key, security.EncodedJwt(values[0][len(prefix):])) {
|
||||
return status.Error(codes.Unauthenticated, "invalid authentication")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dashAuthAddress(address string) pb.ServerAddress {
|
||||
_, portText, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return pb.ServerAddress(address)
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil {
|
||||
return pb.ServerAddress(address)
|
||||
}
|
||||
return pb.NewServerAddressWithGrpcPort(address, port)
|
||||
}
|
||||
|
||||
func startDashAuthFiler(t *testing.T, key security.SigningKey, require bool) pb.ServerAddress {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal("listen")
|
||||
}
|
||||
server := grpc.NewServer(
|
||||
grpc.UnaryInterceptor(func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
if err := dashAuthCheck(ctx, key, require); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}),
|
||||
grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
if err := dashAuthCheck(stream.Context(), key, require); err != nil {
|
||||
return err
|
||||
}
|
||||
return handler(srv, stream)
|
||||
}),
|
||||
)
|
||||
filer_pb.RegisterSeaweedFilerServer(server, dashAuthFiler{})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
address := dashAuthAddress(listener.Addr().String())
|
||||
t.Cleanup(func() {
|
||||
server.Stop()
|
||||
_ = listener.Close()
|
||||
pb.InvalidateGrpcConnection(address.ToGrpcAddress())
|
||||
})
|
||||
return address
|
||||
}
|
||||
|
||||
func dashTestKey(t *testing.T) security.SigningKey {
|
||||
t.Helper()
|
||||
bytes := make([]byte, 32)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
t.Fatal("generate disposable signing key")
|
||||
}
|
||||
return security.SigningKey(hex.EncodeToString(bytes))
|
||||
}
|
||||
|
||||
func TestAdminFilerReadsUsePerCallAdminToken(t *testing.T) {
|
||||
key := dashTestKey(t)
|
||||
otherKey := dashTestKey(t)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
require bool
|
||||
source security.FilerTokenSource
|
||||
want codes.Code
|
||||
}{
|
||||
{
|
||||
name: "valid token",
|
||||
require: true,
|
||||
source: func(context.Context) (security.EncodedJwt, error) {
|
||||
return security.GenJwtForFilerAdmin(key, 10), nil
|
||||
},
|
||||
want: codes.OK,
|
||||
},
|
||||
{
|
||||
name: "wrong key",
|
||||
require: true,
|
||||
source: func(context.Context) (security.EncodedJwt, error) {
|
||||
return security.GenJwtForFilerAdmin(otherKey, 10), nil
|
||||
},
|
||||
want: codes.Unauthenticated,
|
||||
},
|
||||
{
|
||||
name: "missing token",
|
||||
require: true,
|
||||
want: codes.Unauthenticated,
|
||||
},
|
||||
{
|
||||
name: "optional no key",
|
||||
require: false,
|
||||
want: codes.OK,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
serverKey := key
|
||||
if tc.name == "optional no key" {
|
||||
serverKey = nil
|
||||
}
|
||||
address := startDashAuthFiler(t, serverKey, tc.require)
|
||||
server := &AdminServer{
|
||||
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
filerTokenSource: tc.source,
|
||||
cachedFilers: []string{string(address)},
|
||||
lastFilerUpdate: time.Now(),
|
||||
filerCacheExpiration: time.Hour,
|
||||
}
|
||||
config, err := server.getFilerConfig()
|
||||
if status.Code(err) != tc.want {
|
||||
t.Fatalf("admin filer configuration read code=%v, want %v", status.Code(err), tc.want)
|
||||
}
|
||||
if tc.want == codes.OK {
|
||||
if config.BucketsPath != "/buckets" || config.FilerGroup != "test" {
|
||||
t.Fatal("admin filer configuration response was not preserved")
|
||||
}
|
||||
if _, err := server.getFilerConf(); err != nil {
|
||||
t.Fatal("admin filer.conf read was refused")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ func (s *AdminServer) GetMountClients() (*MountClientsData, error) {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), mountClientsFilerTimeout)
|
||||
defer cancel()
|
||||
err := pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := pb.WithGrpcFilerClient(false, 0, pb.ServerAddress(filerAddr), s.grpcDialOption, s.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.ListMetadataSubscribers(ctx, &filer_pb.ListMetadataSubscribersRequest{
|
||||
ClientTypes: mountClientTypes,
|
||||
})
|
||||
|
||||
@@ -70,6 +70,47 @@ func filterActivitiesByLane(activities []plugin.JobActivity, laneFilter string)
|
||||
return filtered
|
||||
}
|
||||
|
||||
func parseVolumeIDFilter(raw string) (uint32, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0, nil
|
||||
}
|
||||
value, err := strconv.ParseUint(raw, 10, 32)
|
||||
if err != nil || value == 0 {
|
||||
return 0, fmt.Errorf("invalid volume_id %q", raw)
|
||||
}
|
||||
return uint32(value), nil
|
||||
}
|
||||
|
||||
func filterTrackedJobsByVolume(jobs []plugin.TrackedJob, volumeID uint32) []plugin.TrackedJob {
|
||||
if volumeID == 0 {
|
||||
return jobs
|
||||
}
|
||||
|
||||
filtered := make([]plugin.TrackedJob, 0, len(jobs))
|
||||
for _, job := range jobs {
|
||||
if job.VolumeID == volumeID {
|
||||
filtered = append(filtered, job)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
func filterActivitiesByJobs(activities []plugin.JobActivity, jobs []plugin.TrackedJob) []plugin.JobActivity {
|
||||
jobIDs := make(map[string]struct{}, len(jobs))
|
||||
for _, job := range jobs {
|
||||
jobIDs[job.JobID] = struct{}{}
|
||||
}
|
||||
|
||||
filtered := make([]plugin.JobActivity, 0, len(activities))
|
||||
for _, activity := range activities {
|
||||
if _, ok := jobIDs[activity.JobID]; ok {
|
||||
filtered = append(filtered, activity)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// GetPluginStatusAPI returns plugin status.
|
||||
func (s *AdminServer) GetPluginStatusAPI(w http.ResponseWriter, r *http.Request) {
|
||||
plugin := s.GetPlugin()
|
||||
@@ -153,10 +194,15 @@ func (s *AdminServer) GetPluginJobsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
jobType := strings.TrimSpace(query.Get("job_type"))
|
||||
state := strings.TrimSpace(query.Get("state"))
|
||||
laneFilter := strings.TrimSpace(query.Get("lane"))
|
||||
volumeID, err := parseVolumeIDFilter(query.Get("volume_id"))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
limit := parsePositiveInt(query.Get("limit"), 200)
|
||||
// Apply the lane before the limit, or a busy lane's newest rows crowd out a quiet lane.
|
||||
// Apply the filters before the limit, or a busy lane's newest rows crowd out a quiet lane.
|
||||
listLimit := limit
|
||||
if laneFilter != "" {
|
||||
if laneFilter != "" || volumeID != 0 {
|
||||
listLimit = 0
|
||||
}
|
||||
jobs := s.ListPluginJobs(jobType, state, listLimit)
|
||||
@@ -165,6 +211,7 @@ func (s *AdminServer) GetPluginJobsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
jobs = filterTrackedJobsByLane(jobs, laneFilter)
|
||||
jobs = filterTrackedJobsByVolume(jobs, volumeID)
|
||||
if len(jobs) > limit {
|
||||
jobs = jobs[:limit]
|
||||
}
|
||||
@@ -261,9 +308,14 @@ func (s *AdminServer) GetPluginActivitiesAPI(w http.ResponseWriter, r *http.Requ
|
||||
query := r.URL.Query()
|
||||
jobType := strings.TrimSpace(query.Get("job_type"))
|
||||
laneFilter := strings.TrimSpace(query.Get("lane"))
|
||||
volumeID, err := parseVolumeIDFilter(query.Get("volume_id"))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
limit := parsePositiveInt(query.Get("limit"), 500)
|
||||
listLimit := limit
|
||||
if laneFilter != "" {
|
||||
if laneFilter != "" || volumeID != 0 {
|
||||
listLimit = 0
|
||||
}
|
||||
activities := s.ListPluginActivities(jobType, listLimit)
|
||||
@@ -272,6 +324,9 @@ func (s *AdminServer) GetPluginActivitiesAPI(w http.ResponseWriter, r *http.Requ
|
||||
return
|
||||
}
|
||||
activities = filterActivitiesByLane(activities, laneFilter)
|
||||
if volumeID != 0 {
|
||||
activities = filterActivitiesByJobs(activities, filterTrackedJobsByVolume(s.ListPluginJobs(jobType, "", 0), volumeID))
|
||||
}
|
||||
if len(activities) > limit {
|
||||
activities = activities[:limit]
|
||||
}
|
||||
|
||||
@@ -290,3 +290,75 @@ func TestPluginJobsAndActivitiesAPILimitAfterLaneFilter(t *testing.T) {
|
||||
t.Fatalf("default lane activities: got %d rows, want the limit of 2", len(rows))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluginJobsAndActivitiesAPIVolumeIDFilter(t *testing.T) {
|
||||
dataDir := t.TempDir()
|
||||
store, err := plugin.NewConfigStore(dataDir)
|
||||
if err != nil {
|
||||
t.Fatalf("NewConfigStore: %v", err)
|
||||
}
|
||||
now := time.Now()
|
||||
var jobs []plugin.TrackedJob
|
||||
var activities []plugin.JobActivity
|
||||
for i := 0; i < 6; i++ {
|
||||
jobType, jobID, volumeID := "erasure_coding", fmt.Sprintf("ec-%d", i), uint32(7)
|
||||
if i%2 == 1 {
|
||||
jobType, jobID, volumeID = "vacuum", fmt.Sprintf("vacuum-%d", i), uint32(8)
|
||||
}
|
||||
at := now.Add(-time.Duration(i) * time.Minute)
|
||||
jobs = append(jobs, plugin.TrackedJob{JobID: jobID, JobType: jobType, VolumeID: volumeID, State: plugin.StateSucceeded, UpdatedAt: &at})
|
||||
activities = append(activities, plugin.JobActivity{JobID: jobID, JobType: jobType, Message: "done", OccurredAt: &at})
|
||||
}
|
||||
if err := store.SaveTrackedJobs(jobs); err != nil {
|
||||
t.Fatalf("SaveTrackedJobs: %v", err)
|
||||
}
|
||||
if err := store.SaveActivities(activities); err != nil {
|
||||
t.Fatalf("SaveActivities: %v", err)
|
||||
}
|
||||
p, err := plugin.New(plugin.Options{DataDir: dataDir})
|
||||
if err != nil {
|
||||
t.Fatalf("plugin.New: %v", err)
|
||||
}
|
||||
defer p.Shutdown()
|
||||
s := &AdminServer{plugin: p}
|
||||
|
||||
get := func(handler http.HandlerFunc, url string, wantStatus int) []map[string]any {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler(recorder, httptest.NewRequest(http.MethodGet, url, nil))
|
||||
if recorder.Code != wantStatus {
|
||||
t.Fatalf("%s: status %d, want %d", url, recorder.Code, wantStatus)
|
||||
}
|
||||
if wantStatus != http.StatusOK {
|
||||
return nil
|
||||
}
|
||||
var rows []map[string]any
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &rows); err != nil {
|
||||
t.Fatalf("%s: %v", url, err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
idsOf := func(rows []map[string]any) []string {
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, fmt.Sprint(row["job_id"]))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
if ids := idsOf(get(s.GetPluginJobsAPI, "/api/plugin/jobs?limit=2&volume_id=8", http.StatusOK)); fmt.Sprint(ids) != "[vacuum-1 vacuum-3]" {
|
||||
t.Fatalf("volume 8 jobs: got %v", ids)
|
||||
}
|
||||
if ids := idsOf(get(s.GetPluginJobsAPI, "/api/plugin/jobs?volume_id=7&job_type=vacuum", http.StatusOK)); len(ids) != 0 {
|
||||
t.Fatalf("volume 7 vacuum jobs: got %v, want none", ids)
|
||||
}
|
||||
if ids := idsOf(get(s.GetPluginActivitiesAPI, "/api/plugin/activities?limit=2&volume_id=7", http.StatusOK)); fmt.Sprint(ids) != "[ec-0 ec-2]" {
|
||||
t.Fatalf("volume 7 activities: got %v", ids)
|
||||
}
|
||||
if ids := idsOf(get(s.GetPluginActivitiesAPI, "/api/plugin/activities?volume_id=9", http.StatusOK)); len(ids) != 0 {
|
||||
t.Fatalf("volume 9 activities: got %v, want none", ids)
|
||||
}
|
||||
for _, bad := range []string{"0", "-1", "abc", "4294967296"} {
|
||||
get(s.GetPluginJobsAPI, "/api/plugin/jobs?volume_id="+bad, http.StatusBadRequest)
|
||||
get(s.GetPluginActivitiesAPI, "/api/plugin/activities?volume_id="+bad, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
@@ -100,9 +100,9 @@ func (s *WorkerGrpcServer) StartWithTLS(bindIp string, port int, listener net.Li
|
||||
}
|
||||
|
||||
// Create gRPC server with optional TLS
|
||||
tlsOption, _ := security.LoadServerTLS(util.GetViper(), "grpc.admin")
|
||||
tlsOption, healthCheckOption := security.LoadServerTLS(util.GetViper(), "grpc.admin")
|
||||
s.mtlsEnabled = tlsOption != nil
|
||||
grpcServer := pb.NewGrpcServer(tlsOption)
|
||||
grpcServer := pb.NewGrpcServer(tlsOption, healthCheckOption)
|
||||
|
||||
worker_pb.RegisterWorkerServiceServer(grpcServer, s)
|
||||
if plugin := s.adminServer.GetPlugin(); plugin != nil {
|
||||
@@ -182,6 +182,7 @@ func (s *WorkerGrpcServer) Stop() error {
|
||||
|
||||
// Stop gRPC server
|
||||
if s.grpcServer != nil {
|
||||
pb.StopHealthWatches(s.grpcServer)
|
||||
s.grpcServer.GracefulStop()
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
|
||||
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
@@ -805,6 +806,9 @@ func mergeTrackedStatusIntoDetail(detail *TrackedJob, tracked *TrackedJob) {
|
||||
if detail.DedupeKey == "" {
|
||||
detail.DedupeKey = tracked.DedupeKey
|
||||
}
|
||||
if detail.VolumeID == 0 {
|
||||
detail.VolumeID = tracked.VolumeID
|
||||
}
|
||||
if detail.Summary == "" {
|
||||
detail.Summary = tracked.Summary
|
||||
}
|
||||
@@ -942,6 +946,7 @@ func (r *Plugin) trackExecutionStart(requestID, workerID string, job *plugin_pb.
|
||||
tracked.RequestID = requestID
|
||||
tracked.WorkerID = workerID
|
||||
tracked.DedupeKey = job.DedupeKey
|
||||
tracked.VolumeID = pluginworker.ReadUint32Config(job.Parameters, "volume_id", 0)
|
||||
tracked.Summary = job.Summary
|
||||
tracked.State = strings.ToLower(plugin_pb.JobState_JOB_STATE_ASSIGNED.String())
|
||||
tracked.Progress = 0
|
||||
@@ -962,6 +967,7 @@ func (r *Plugin) trackExecutionStart(requestID, workerID string, job *plugin_pb.
|
||||
detail.RequestID = requestID
|
||||
detail.WorkerID = workerID
|
||||
detail.DedupeKey = job.DedupeKey
|
||||
detail.VolumeID = trackedSnapshot.VolumeID
|
||||
detail.Summary = job.Summary
|
||||
detail.Detail = job.Detail
|
||||
detail.Parameters = enrichTrackedJobParameters(job.JobType, configValueMapToPlain(job.Parameters))
|
||||
@@ -1017,6 +1023,7 @@ func (r *Plugin) trackExecutionQueued(job *plugin_pb.JobSpec) {
|
||||
|
||||
tracked.JobType = job.JobType
|
||||
tracked.DedupeKey = job.DedupeKey
|
||||
tracked.VolumeID = pluginworker.ReadUint32Config(job.Parameters, "volume_id", 0)
|
||||
tracked.Summary = job.Summary
|
||||
tracked.State = strings.ToLower(plugin_pb.JobState_JOB_STATE_PENDING.String())
|
||||
tracked.Progress = 0
|
||||
@@ -1034,6 +1041,7 @@ func (r *Plugin) trackExecutionQueued(job *plugin_pb.JobSpec) {
|
||||
detail.JobID = job.JobId
|
||||
detail.JobType = job.JobType
|
||||
detail.DedupeKey = job.DedupeKey
|
||||
detail.VolumeID = trackedSnapshot.VolumeID
|
||||
detail.Summary = job.Summary
|
||||
detail.Detail = job.Detail
|
||||
detail.Parameters = enrichTrackedJobParameters(job.JobType, configValueMapToPlain(job.Parameters))
|
||||
|
||||
@@ -170,6 +170,51 @@ func TestTrackExecutionQueuedMarksPendingState(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrackedJobsKeepVolumeID(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pluginSvc, err := New(Options{})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
defer pluginSvc.Shutdown()
|
||||
|
||||
pluginSvc.trackExecutionQueued(&plugin_pb.JobSpec{
|
||||
JobId: "job-ec-17",
|
||||
JobType: "erasure_coding",
|
||||
Parameters: map[string]*plugin_pb.ConfigValue{
|
||||
"volume_id": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 17}},
|
||||
},
|
||||
})
|
||||
pluginSvc.trackExecutionStart("req-1", "worker-a", &plugin_pb.JobSpec{
|
||||
JobId: "job-vacuum-23",
|
||||
JobType: "vacuum",
|
||||
Parameters: map[string]*plugin_pb.ConfigValue{
|
||||
"volume_id": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: "23"}},
|
||||
},
|
||||
}, 1)
|
||||
pluginSvc.trackExecutionQueued(&plugin_pb.JobSpec{JobId: "job-no-volume", JobType: "iceberg"})
|
||||
|
||||
want := map[string]uint32{"job-ec-17": 17, "job-vacuum-23": 23, "job-no-volume": 0}
|
||||
jobs := pluginSvc.ListTrackedJobs("", "", 0)
|
||||
if len(jobs) != len(want) {
|
||||
t.Fatalf("expected %d tracked jobs, got %d", len(want), len(jobs))
|
||||
}
|
||||
for _, job := range jobs {
|
||||
if job.VolumeID != want[job.JobID] {
|
||||
t.Fatalf("job %s: volume id %d, want %d", job.JobID, job.VolumeID, want[job.JobID])
|
||||
}
|
||||
}
|
||||
|
||||
detail, found, err := pluginSvc.BuildJobDetail("job-ec-17", 10, 0)
|
||||
if err != nil || !found || detail.Job == nil {
|
||||
t.Fatalf("BuildJobDetail: found=%v err=%v", found, err)
|
||||
}
|
||||
if detail.Job.VolumeID != 17 {
|
||||
t.Fatalf("detail volume id %d, want 17", detail.Job.VolumeID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleJobProgressUpdateCarriesWorkerIDInActivities(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -90,7 +90,9 @@ var jobTypeLaneMap = map[string]SchedulerLane{
|
||||
"iceberg_maintenance": LaneIceberg,
|
||||
|
||||
// S3 lifecycle management
|
||||
"s3_lifecycle": LaneLifecycle,
|
||||
"s3_lifecycle": LaneLifecycle,
|
||||
"filer_ttl": LaneLifecycle,
|
||||
"meta_log_purge": LaneLifecycle,
|
||||
|
||||
// Lance table maintenance. Without these the job types fall back to the
|
||||
// default lane, which serialises everything under the cluster admin lock
|
||||
|
||||
@@ -44,6 +44,7 @@ type TrackedJob struct {
|
||||
RequestID string `json:"request_id"`
|
||||
WorkerID string `json:"worker_id"`
|
||||
DedupeKey string `json:"dedupe_key,omitempty"`
|
||||
VolumeID uint32 `json:"volume_id,omitempty"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Parameters map[string]interface{} `json:"parameters,omitempty"`
|
||||
|
||||
@@ -383,6 +383,7 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
<div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
|
||||
<h5 class="mb-0"><i class="bi bi-list me-2"></i>Job Queue</h5>
|
||||
<div class="d-flex gap-2 align-items-center flex-wrap">
|
||||
<input type="number" min="1" max="4294967295" step="1" autocomplete="off" class="form-control form-control-sm plugin-monitor-volume-filter" placeholder="Volume ID" title="Show only jobs of this volume" style="width: 130px;"/>
|
||||
<small class="text-muted">States: pending/assigned/running</small>
|
||||
</div>
|
||||
</div>
|
||||
@@ -451,6 +452,7 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
<div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
|
||||
<h5 class="mb-0"><i class="bi bi-list-check me-2"></i>Execution Jobs</h5>
|
||||
<div class="d-flex gap-2 align-items-center flex-wrap">
|
||||
<input type="number" min="1" max="4294967295" step="1" autocomplete="off" class="form-control form-control-sm plugin-monitor-volume-filter" placeholder="Volume ID" title="Show only jobs and activities of this volume" style="width: 130px;"/>
|
||||
<select class="form-select form-select-sm" id="plugin-monitor-job-state-filter" style="min-width: 180px;">
|
||||
<option value="">All States</option>
|
||||
<option value="assigned">Assigned</option>
|
||||
@@ -612,6 +614,7 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
activeSubTab: 'configuration',
|
||||
initialNavigationApplied: false,
|
||||
monitorExecutionJobState: '',
|
||||
monitorVolumeID: '',
|
||||
workers: [],
|
||||
jobs: [],
|
||||
activities: [],
|
||||
@@ -622,6 +625,10 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
allJobs: [],
|
||||
allActivities: [],
|
||||
monitorRowsScope: null,
|
||||
detectionActivities: [],
|
||||
detectionRowsScope: null,
|
||||
monitorRefreshSeq: 0,
|
||||
monitorCommittedRefreshID: 0,
|
||||
refreshError: '',
|
||||
loadedJobType: '',
|
||||
descriptor: null,
|
||||
@@ -643,6 +650,24 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
return url + sep + 'job_type=' + encodeURIComponent(jobType);
|
||||
}
|
||||
|
||||
function appendVolumeParam(url) {
|
||||
if (!state.monitorVolumeID) return url;
|
||||
var sep = url.indexOf('?') === -1 ? '?' : '&';
|
||||
return url + sep + 'volume_id=' + encodeURIComponent(state.monitorVolumeID);
|
||||
}
|
||||
|
||||
function readMonitorVolumeFilter(input) {
|
||||
if (input.validity && input.validity.badInput) {
|
||||
return null;
|
||||
}
|
||||
var value = String(input.value || '').trim();
|
||||
if (!value) {
|
||||
return '';
|
||||
}
|
||||
var volumeID = /^[0-9]+$/.test(value) ? Number(value) : 0;
|
||||
return volumeID >= 1 && volumeID <= 4294967295 ? String(volumeID) : null;
|
||||
}
|
||||
|
||||
function getCSRFToken() {
|
||||
var meta = document.querySelector('meta[name="csrf-token"]');
|
||||
if (!meta) {
|
||||
@@ -1877,7 +1902,7 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
}
|
||||
|
||||
var filteredActivities = [];
|
||||
var activities = Array.isArray(state.activities) ? state.activities : [];
|
||||
var activities = Array.isArray(state.detectionActivities) ? state.detectionActivities : [];
|
||||
for (var i = 0; i < activities.length; i++) {
|
||||
var activity = activities[i] || {};
|
||||
var jobType = String(activity.job_type || '').trim();
|
||||
@@ -3102,28 +3127,42 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
// The newest 500 rows cluster-wide may hold none of the selected job type on a busy
|
||||
// cluster, so the job-type sub-tabs fetch their own server-side filtered window.
|
||||
var scopedJobType = monitorJobTypeScope();
|
||||
var sameScope = state.monitorRowsScope === scopedJobType;
|
||||
var scopedVolume = state.monitorVolumeID;
|
||||
var rowsScope = scopedJobType + '|' + scopedVolume;
|
||||
var scopedRows = scopedJobType || scopedVolume;
|
||||
var refreshID = ++state.monitorRefreshSeq;
|
||||
|
||||
// A failed request keeps its last rows; the rest still land and the failure is rethrown.
|
||||
// A failed request keeps the rows committed when this refresh lands; the rest still
|
||||
// land and the failure is rethrown.
|
||||
var failure = null;
|
||||
function keepOnFailure(promise, previous) {
|
||||
var failed = {};
|
||||
function keepOnFailure(promise) {
|
||||
return promise.catch(function(e) {
|
||||
failure = failure || e;
|
||||
return previous;
|
||||
return failed;
|
||||
});
|
||||
}
|
||||
function kept(value, previous) {
|
||||
return value === failed ? previous : value;
|
||||
}
|
||||
|
||||
var allJobsPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/jobs?limit=500')), state.allJobs);
|
||||
var allActivitiesPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/activities?limit=500')), state.allActivities);
|
||||
var jobsPromise = scopedJobType ? keepOnFailure(pluginRequest('GET', appendJobTypeParam(appendLaneParam('/api/plugin/jobs?limit=500'), scopedJobType)), sameScope ? state.jobs : null) : allJobsPromise;
|
||||
var activitiesPromise = scopedJobType ? keepOnFailure(pluginRequest('GET', appendJobTypeParam(appendLaneParam('/api/plugin/activities?limit=500'), scopedJobType)), sameScope ? state.activities : null) : allActivitiesPromise;
|
||||
var schedulerPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/scheduler-states')), state.schedulerStates);
|
||||
var allJobsPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/jobs?limit=500')));
|
||||
var allActivitiesPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/activities?limit=500')));
|
||||
var jobsPromise = scopedRows ? keepOnFailure(pluginRequest('GET', appendVolumeParam(appendJobTypeParam(appendLaneParam('/api/plugin/jobs?limit=500'), scopedJobType)))) : allJobsPromise;
|
||||
var activitiesPromise = scopedRows ? keepOnFailure(pluginRequest('GET', appendVolumeParam(appendJobTypeParam(appendLaneParam('/api/plugin/activities?limit=500'), scopedJobType)))) : allActivitiesPromise;
|
||||
// Detection scans belong to no job, so the volume filter would hide every one of them.
|
||||
var detectionActivitiesPromise = activitiesPromise;
|
||||
if (scopedVolume) {
|
||||
detectionActivitiesPromise = scopedJobType ? keepOnFailure(pluginRequest('GET', appendJobTypeParam(appendLaneParam('/api/plugin/activities?limit=500'), scopedJobType))) : allActivitiesPromise;
|
||||
}
|
||||
var schedulerPromise = keepOnFailure(pluginRequest('GET', appendLaneParam('/api/plugin/scheduler-states')));
|
||||
var schedulerStatusPromise = pluginRequest('GET', appendLaneParam('/api/plugin/scheduler-status'));
|
||||
|
||||
var allJobs = await allJobsPromise;
|
||||
var allActivities = await allActivitiesPromise;
|
||||
var jobs = await jobsPromise;
|
||||
var activities = await activitiesPromise;
|
||||
var detectionActivities = await detectionActivitiesPromise;
|
||||
var schedulerStates = await schedulerPromise;
|
||||
var schedulerStatus = null;
|
||||
try {
|
||||
@@ -3131,15 +3170,26 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
} catch (e) {
|
||||
schedulerStatus = null;
|
||||
}
|
||||
if (monitorJobTypeScope() !== scopedJobType) {
|
||||
if (monitorJobTypeScope() !== scopedJobType || state.monitorVolumeID !== scopedVolume || refreshID < state.monitorCommittedRefreshID) {
|
||||
return;
|
||||
}
|
||||
state.monitorCommittedRefreshID = refreshID;
|
||||
|
||||
var sameScope = state.monitorRowsScope === rowsScope;
|
||||
allJobs = kept(allJobs, state.allJobs);
|
||||
allActivities = kept(allActivities, state.allActivities);
|
||||
jobs = kept(jobs, sameScope ? state.jobs : null);
|
||||
activities = kept(activities, sameScope ? state.activities : null);
|
||||
detectionActivities = kept(detectionActivities, state.detectionRowsScope === scopedJobType ? state.detectionActivities : null);
|
||||
schedulerStates = kept(schedulerStates, state.schedulerStates);
|
||||
|
||||
state.allJobs = Array.isArray(allJobs) ? allJobs : [];
|
||||
state.allActivities = Array.isArray(allActivities) ? allActivities : [];
|
||||
state.jobs = Array.isArray(jobs) ? jobs : state.allJobs;
|
||||
state.activities = Array.isArray(activities) ? activities : state.allActivities;
|
||||
state.monitorRowsScope = scopedJobType;
|
||||
state.jobs = Array.isArray(jobs) ? jobs : (scopedVolume ? [] : state.allJobs);
|
||||
state.activities = Array.isArray(activities) ? activities : (scopedVolume ? [] : state.allActivities);
|
||||
state.monitorRowsScope = rowsScope;
|
||||
state.detectionActivities = Array.isArray(detectionActivities) ? detectionActivities : state.allActivities;
|
||||
state.detectionRowsScope = scopedJobType;
|
||||
state.schedulerStates = Array.isArray(schedulerStates) ? schedulerStates : [];
|
||||
state.schedulerStatus = schedulerStatus && schedulerStatus.scheduler ? schedulerStatus.scheduler : null;
|
||||
state.schedulerLock = schedulerStatus && schedulerStatus.lock ? schedulerStatus.lock : null;
|
||||
@@ -3202,6 +3252,28 @@ templ Plugin(page string, initialJob string, lane string) {
|
||||
});
|
||||
}
|
||||
|
||||
var monitorVolumeFilters = document.querySelectorAll('.plugin-monitor-volume-filter');
|
||||
for (var v = 0; v < monitorVolumeFilters.length; v++) {
|
||||
monitorVolumeFilters[v].addEventListener('change', async function(event) {
|
||||
var volumeID = readMonitorVolumeFilter(event.target);
|
||||
if (volumeID !== null) {
|
||||
state.monitorVolumeID = volumeID;
|
||||
}
|
||||
for (var k = 0; k < monitorVolumeFilters.length; k++) {
|
||||
monitorVolumeFilters[k].value = state.monitorVolumeID;
|
||||
}
|
||||
if (volumeID === null) {
|
||||
notify('Volume ID must be a whole number from 1 to 4294967295', 'warning');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await refreshJobsAndActivities();
|
||||
} catch (refreshErr) {
|
||||
notify('Monitoring refresh failed: ' + refreshErr.message, 'error');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var expireBtn = document.getElementById('plugin-expire-job-btn');
|
||||
if (expireBtn) {
|
||||
expireBtn.addEventListener('click', function() {
|
||||
|
||||
@@ -109,7 +109,7 @@ func Plugin(page string, initialJob string, lane string) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next scheduled check</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=\"mb-3\"><div class=\"small text-muted\">Selected Job Type</div><div class=\"fw-semibold\" id=\"plugin-selected-job-type\">-</div></div><div class=\"mb-3\"><div class=\"d-flex justify-content-between align-items-center mb-2\"><h6 class=\"mb-0\">Descriptor</h6><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"plugin-refresh-schema-btn\"><i class=\"bi bi-cloud-download me-1\"></i>Refresh Schema</button></div><div class=\"alert alert-light border\" id=\"plugin-descriptor-summary\">Select a job type to load schema and config.</div></div><div class=\"mb-3\"><h6>Admin Config Form</h6><div id=\"plugin-admin-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No admin form loaded.</div></div></div><div class=\"mb-3\"><h6>Worker Config Form</h6><div id=\"plugin-worker-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No worker form loaded.</div></div></div><div class=\"d-flex flex-wrap gap-2\"><button type=\"button\" class=\"btn btn-primary\" id=\"plugin-save-config-btn\"><i class=\"bi bi-floppy me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"bi bi-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btnLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<div class=\"plugin-section plugin-section-overview\"><div class=\"row mb-4\"><div class=\"col-md-3 mb-3\"><div class=\"card border-info h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Workers</div><h4 class=\"mb-0\" id=\"plugin-status-workers\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-warning h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Active Jobs</div><h4 class=\"mb-0\" id=\"plugin-status-active-jobs\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-success h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Activities (recent)</div><h4 class=\"mb-0\" id=\"plugin-status-activities\">0</h4></div></div></div><div class=\"col-md-3 mb-3\"><div class=\"card border-secondary h-100\"><div class=\"card-body text-center\"><div class=\"text-uppercase text-muted small mb-1\">Next scheduled check</div><h4 class=\"mb-0 plugin-scheduler-next-run\">-</h4><div class=\"text-muted small plugin-scheduler-next-run-meta\"></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-bar-chart me-2\"></i>Per Job Type Summary</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Active Jobs</th><th>Recent Activities</th></tr></thead> <tbody id=\"plugin-jobtype-summary-body\"><tr><td colspan=\"3\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header d-flex justify-content-between align-items-center flex-wrap gap-2\"><h5 class=\"mb-0\"><i class=\"bi bi-clock me-2\"></i>Scheduler State</h5><small class=\"text-muted\">Sequential scheduler with per-job runtime limits</small></div><div class=\"card-body p-0\"><div class=\"table-responsive\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light\"><tr><th>Job Type</th><th>Enabled</th><th>Detector</th><th>In Flight</th><th>Max Runtime</th><th>Exec Global</th><th>Exec/Worker</th><th>Executor Workers</th><th>Effective Exec</th><th>Last Run</th></tr></thead> <tbody id=\"plugin-scheduler-table-body\"><tr><td colspan=\"10\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div><div class=\"row mb-4\"><div class=\"col-12\"><div class=\"card shadow-sm\"><div class=\"card-header\"><h5 class=\"mb-0\"><i class=\"bi bi-people me-2\"></i>Workers</h5></div><div class=\"card-body p-0\"><div class=\"table-responsive\" style=\"max-height: 560px; overflow-y: auto;\"><table class=\"table table-sm table-hover mb-0\"><thead class=\"table-light sticky-top\"><tr><th>Worker</th><th>Address</th><th>Capabilities</th><th>Load</th></tr></thead> <tbody id=\"plugin-workers-table-body\"><tr><td colspan=\"4\" class=\"text-muted text-center py-3\">Loading...</td></tr></tbody></table></div></div></div></div></div></div><div class=\"plugin-section plugin-section-configuration\"><div class=\"row mb-4\"><div class=\"col-lg-8 mb-3\"><div class=\"card shadow-sm h-100\"><div class=\"card-header d-flex justify-content-between align-items-center\"><h5 class=\"mb-0\"><i class=\"bi bi-sliders me-2\"></i>Job Type Configuration</h5><small class=\"text-muted\" id=\"plugin-config-updated-at\">Not loaded</small></div><div class=\"card-body\"><div class=\"mb-3\"><div class=\"small text-muted\">Selected Job Type</div><div class=\"fw-semibold\" id=\"plugin-selected-job-type\">-</div></div><div class=\"mb-3\"><div class=\"d-flex justify-content-between align-items-center mb-2\"><h6 class=\"mb-0\">Descriptor</h6><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"plugin-refresh-schema-btn\"><i class=\"bi bi-cloud-download me-1\"></i>Refresh Schema</button></div><div class=\"alert alert-light border\" id=\"plugin-descriptor-summary\">Select a job type to load schema and config.</div></div><div class=\"mb-3\"><h6>Admin Config Form</h6><div id=\"plugin-admin-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No admin form loaded.</div></div></div><div class=\"mb-3\"><h6>Worker Config Form</h6><div id=\"plugin-worker-config-form\" class=\"plugin-form-root\"><div class=\"text-muted\">No worker form loaded.</div></div></div><div class=\"d-flex flex-wrap gap-2\"><button type=\"button\" class=\"btn btn-primary\" id=\"plugin-save-config-btn\"><i class=\"bi bi-floppy me-1\"></i>Save Config</button> <button type=\"button\" class=\"btn btn-outline-primary\" id=\"plugin-trigger-detection-btn\"><i class=\"bi bi-search me-1\"></i>Run Detection</button> <button type=\"button\" class=\"btn btnLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -21,7 +22,10 @@ type LockClient struct {
|
||||
// RequestContext, when set before using the client, supplies per-attempt
|
||||
// metadata for lock, renewal and unlock RPCs. Generic clients retain their
|
||||
// existing authority when it is nil.
|
||||
RequestContext func(context.Context) context.Context
|
||||
RequestContext func(context.Context) context.Context
|
||||
// TokenSource supplies per-call filer authorization. A nil source preserves
|
||||
// the existing anonymous behavior.
|
||||
TokenSource security.FilerTokenSource
|
||||
maxLockDuration time.Duration
|
||||
sleepDuration time.Duration
|
||||
seedFiler pb.ServerAddress
|
||||
@@ -436,7 +440,7 @@ func (lock *LiveLock) StopShortLivedLock() error {
|
||||
defer func() {
|
||||
atomic.StoreInt32(&lock.isLocked, 0)
|
||||
}()
|
||||
return pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), lock.lc.lockRpcTimeout)
|
||||
defer cancel()
|
||||
if lock.lc.RequestContext != nil {
|
||||
@@ -495,7 +499,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
previousHostFiler := lock.hostFiler
|
||||
previousOwner := lock.owner
|
||||
|
||||
err = pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err = pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Bound each attempt: a ring member that is reachable from the masters
|
||||
// but not from this filer would otherwise block on the connect timeout.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout)
|
||||
|
||||
@@ -2,8 +2,11 @@ package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -11,8 +14,12 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// The gateway must resolve a lock key to the same primary the filers do,
|
||||
@@ -323,6 +330,166 @@ func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.L
|
||||
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
|
||||
}
|
||||
|
||||
type rotatingAuthLockFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
keys []security.SigningKey
|
||||
authorizations chan int
|
||||
}
|
||||
|
||||
type identityLockFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
seen chan bool
|
||||
}
|
||||
|
||||
func (s *identityLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
values := md.Get("authorization")
|
||||
valid := len(values) == 1 && values[0] == "Bearer caller-identity"
|
||||
s.seen <- valid
|
||||
if !valid {
|
||||
return nil, status.Error(codes.Unauthenticated, "missing caller identity")
|
||||
}
|
||||
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
|
||||
}
|
||||
|
||||
func (s *rotatingAuthLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
values := md.Get("authorization")
|
||||
authenticatedBy := -1
|
||||
if len(values) == 1 && strings.HasPrefix(values[0], security.BearerPrefix) {
|
||||
for i, key := range s.keys {
|
||||
if security.IsFilerAdminToken(key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) {
|
||||
authenticatedBy = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s.authorizations <- authenticatedBy
|
||||
if authenticatedBy < 0 {
|
||||
return nil, status.Error(codes.Unauthenticated, "missing or invalid filer authorization")
|
||||
}
|
||||
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
|
||||
}
|
||||
|
||||
func lockTestSigningKey(t *testing.T) security.SigningKey {
|
||||
t.Helper()
|
||||
bytes := make([]byte, 32)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return security.SigningKey(hex.EncodeToString(bytes))
|
||||
}
|
||||
|
||||
func TestLockClientResolvesFilerTokenForEachAttempt(t *testing.T) {
|
||||
keys := []security.SigningKey{lockTestSigningKey(t), lockTestSigningKey(t)}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
filer := &rotatingAuthLockFiler{keys: keys, authorizations: make(chan int, 2)}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, filer)
|
||||
go grpcServer.Serve(listener)
|
||||
defer grpcServer.Stop()
|
||||
|
||||
host, port, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
var tokenNumber uint64
|
||||
lc.TokenSource = func(context.Context) (security.EncodedJwt, error) {
|
||||
n := atomic.AddUint64(&tokenNumber, 1)
|
||||
return security.GenJwtForFilerAdmin(keys[(n-1)%uint64(len(keys))], 60), nil
|
||||
}
|
||||
|
||||
lock := lc.NewShortLivedLock("test-key", "test-owner")
|
||||
if lock == nil {
|
||||
t.Fatal("expected the lock to be acquired")
|
||||
}
|
||||
if err := lock.AttemptToLock(time.Second); err != nil {
|
||||
t.Fatalf("renew lock: %v", err)
|
||||
}
|
||||
|
||||
first := <-filer.authorizations
|
||||
second := <-filer.authorizations
|
||||
if first < 0 || second < 0 {
|
||||
t.Fatal("expected authorization on both attempts")
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("expected a freshly resolved token on renewal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockClientTokenSourceErrorDoesNotDispatch(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
filer := &rotatingAuthLockFiler{authorizations: make(chan int, 1)}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, filer)
|
||||
go grpcServer.Serve(listener)
|
||||
defer grpcServer.Stop()
|
||||
|
||||
host, port, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
lc.TokenSource = func(context.Context) (security.EncodedJwt, error) {
|
||||
return "", fmt.Errorf("token source unavailable")
|
||||
}
|
||||
lock := &LiveLock{
|
||||
key: "test-key",
|
||||
hostFiler: lc.seedFiler,
|
||||
grpcDialOption: lc.grpcDialOption,
|
||||
lc: lc,
|
||||
}
|
||||
if _, _, err := lock.doLock(time.Second, time.Second); err == nil {
|
||||
t.Fatal("expected token-source error")
|
||||
}
|
||||
select {
|
||||
case <-filer.authorizations:
|
||||
t.Fatal("token-source error dispatched a filer RPC")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockClientNilTokenSourcePreservesRequestContext(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
filer := &identityLockFiler{seen: make(chan bool, 1)}
|
||||
grpcServer := grpc.NewServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, filer)
|
||||
go grpcServer.Serve(listener)
|
||||
defer grpcServer.Stop()
|
||||
|
||||
host, port, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("split host port: %v", err)
|
||||
}
|
||||
lc := NewLockClient(grpc.WithTransportCredentials(insecure.NewCredentials()), pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
|
||||
lc.RequestContext = func(ctx context.Context) context.Context {
|
||||
return metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer caller-identity")
|
||||
}
|
||||
lock := lc.NewShortLivedLock("test-key", "test-owner")
|
||||
if lock == nil {
|
||||
t.Fatal("expected the existing caller identity to acquire the lock")
|
||||
}
|
||||
select {
|
||||
case valid := <-filer.seen:
|
||||
if !valid {
|
||||
t.Fatal("existing caller identity was not preserved")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("filer did not receive the request")
|
||||
}
|
||||
}
|
||||
|
||||
// A ring member that accepts connections but never answers must not swallow
|
||||
// the retry window: when its budget is spent the seed route still gets an
|
||||
// attempt before acquisition gives up.
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
const RenewInterval = time.Second * 3
|
||||
@@ -21,51 +22,71 @@ type ReplicateFunc func(server pb.ServerAddress, key string, expiredAtNs int64,
|
||||
|
||||
type DistributedLockManager struct {
|
||||
lockManager *LockManager
|
||||
mutations *util.LockTable[string]
|
||||
LockRing *LockRing
|
||||
Host pb.ServerAddress
|
||||
ReplicateFn ReplicateFunc // set by filer server after creation
|
||||
// TransferFn waits for the receiver; an error may still mean it committed.
|
||||
TransferFn func(pb.ServerAddress, *Lock) error
|
||||
// RetryTransferFn enqueues work without waiting for this key gate.
|
||||
RetryTransferFn func(string)
|
||||
// Tests set this before concurrent use, to observe admission contention.
|
||||
onMutationWait func(string)
|
||||
}
|
||||
|
||||
func NewDistributedLockManager(host pb.ServerAddress) *DistributedLockManager {
|
||||
return &DistributedLockManager{
|
||||
lockManager: NewLockManager(),
|
||||
mutations: util.NewLockTable[string](),
|
||||
LockRing: NewLockRing(time.Second * 5),
|
||||
Host: host,
|
||||
}
|
||||
}
|
||||
|
||||
func (dlm *DistributedLockManager) acquireMutation(key string) *util.ActiveLock {
|
||||
if mutation, ok := dlm.mutations.TryAcquireLock("lock mutation", key, util.ExclusiveLock); ok {
|
||||
return mutation
|
||||
}
|
||||
if dlm.onMutationWait != nil {
|
||||
dlm.onMutationWait(key)
|
||||
}
|
||||
return dlm.mutations.AcquireLock("lock mutation", key, util.ExclusiveLock)
|
||||
}
|
||||
|
||||
func (dlm *DistributedLockManager) LockWithTimeout(key string, expiredAtNs int64, token string, owner string) (lockOwner string, renewToken string, generation int64, movedTo pb.ServerAddress, err error) {
|
||||
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
if primary == "" {
|
||||
err = NoLockServerError
|
||||
mutation := dlm.acquireMutation(key)
|
||||
defer dlm.mutations.ReleaseLock(key, mutation)
|
||||
if movedTo, err = dlm.serverLocked(key); err != nil || movedTo != "" {
|
||||
return
|
||||
}
|
||||
if primary != dlm.Host {
|
||||
// If this is a renewal (non-empty token) and we still hold the lock locally,
|
||||
// serve it here rather than redirecting. This handles the window between
|
||||
// ring update and lock transfer completion — the old primary remains
|
||||
// authoritative for locks it still holds.
|
||||
if token != "" {
|
||||
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && (lock.Token == token || lock.PrevToken == token) {
|
||||
var seq int64
|
||||
lockOwner, renewToken, generation, seq, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
|
||||
if err == nil && renewToken != "" {
|
||||
dlm.replicateToBackup(key, expiredAtNs, renewToken, token, owner, generation, seq, false)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
movedTo = primary
|
||||
return
|
||||
}
|
||||
var seq int64
|
||||
lockOwner, renewToken, generation, seq, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
|
||||
var seq, leaseExpires int64
|
||||
lockOwner, renewToken, generation, seq, leaseExpires, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
|
||||
if err == nil && renewToken != "" {
|
||||
dlm.replicateToBackup(key, expiredAtNs, renewToken, token, owner, generation, seq, false)
|
||||
dlm.replicateToBackup(key, leaseExpires, renewToken, token, owner, generation, seq, false)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// serverLocked runs under key's mutation gate. It returns the primary to
|
||||
// forward to, or "" when this node serves key. The new owner must receive any
|
||||
// local lease first, since only it can rotate the renewal token; this holds
|
||||
// even when a request wins admission before the topology callback.
|
||||
func (dlm *DistributedLockManager) serverLocked(key string) (movedTo pb.ServerAddress, err error) {
|
||||
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
if primary != "" && primary != dlm.Host {
|
||||
if primary, err = dlm.transferToOwnerLocked(key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if primary == "" {
|
||||
return "", NoLockServerError
|
||||
}
|
||||
if primary == dlm.Host {
|
||||
return "", nil
|
||||
}
|
||||
return primary, nil
|
||||
}
|
||||
|
||||
func (dlm *DistributedLockManager) FindLockOwner(key string) (owner string, movedTo pb.ServerAddress, err error) {
|
||||
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
if primary == "" {
|
||||
@@ -88,32 +109,14 @@ func (dlm *DistributedLockManager) FindLockOwner(key string) (owner string, move
|
||||
}
|
||||
|
||||
func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.ServerAddress, err error) {
|
||||
primary, _ := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
if primary == "" {
|
||||
err = NoLockServerError
|
||||
mutation := dlm.acquireMutation(key)
|
||||
defer dlm.mutations.ReleaseLock(key, mutation)
|
||||
if movedTo, err = dlm.serverLocked(key); err != nil || movedTo != "" {
|
||||
return
|
||||
}
|
||||
if primary != dlm.Host {
|
||||
// If we still hold this lock locally, serve the unlock here
|
||||
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && token != "" && (lock.Token == token || lock.PrevToken == token) {
|
||||
var isUnlocked bool
|
||||
var generation int64
|
||||
var seq int64
|
||||
isUnlocked, generation, seq, err = dlm.lockManager.Unlock(key, token)
|
||||
if isUnlocked {
|
||||
dlm.replicateToBackup(key, 0, "", "", "", generation, seq, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
movedTo = primary
|
||||
return
|
||||
}
|
||||
var isUnlocked bool
|
||||
var generation int64
|
||||
var seq int64
|
||||
isUnlocked, generation, seq, err = dlm.lockManager.Unlock(key, token)
|
||||
if isUnlocked {
|
||||
dlm.replicateToBackup(key, 0, "", "", "", generation, seq, true)
|
||||
released, err := dlm.lockManager.Unlock(key, token)
|
||||
if released != nil {
|
||||
dlm.replicateToBackup(key, released.ExpiredAtNs, released.Token, "", released.Owner, released.Generation, released.Seq, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -122,8 +125,8 @@ func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.
|
||||
// It is used when a server is down and the lock is moved to another server.
|
||||
// After inserting, it replicates to the backup for this key.
|
||||
func (dlm *DistributedLockManager) InsertLock(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
|
||||
if dlm.lockManager.InsertLock(key, expiredAtNs, token, prevToken, owner, generation, seq) {
|
||||
dlm.replicateToBackup(key, expiredAtNs, token, prevToken, owner, generation, seq, false)
|
||||
if effectiveExpiry, accepted := dlm.lockManager.InsertLock(key, expiredAtNs, token, prevToken, owner, generation, seq); accepted {
|
||||
dlm.replicateToBackup(key, effectiveExpiry, token, prevToken, owner, generation, seq, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,9 +140,9 @@ func (dlm *DistributedLockManager) RemoveBackupLock(key string) {
|
||||
dlm.lockManager.RemoveLock(key)
|
||||
}
|
||||
|
||||
// RemoveBackupLockIfSeq removes a local copy only if the incoming mutation is not older.
|
||||
func (dlm *DistributedLockManager) RemoveBackupLockIfSeq(key string, generation int64, seq int64) {
|
||||
dlm.lockManager.RemoveBackupLockIfSeq(key, generation, seq)
|
||||
// RemoveBackupLockIfSeq records a release and removes only the matching lease.
|
||||
func (dlm *DistributedLockManager) RemoveBackupLockIfSeq(key string, generation int64, seq int64, token string, expiredAtNs int64) {
|
||||
dlm.lockManager.RemoveBackupLockIfSeq(key, generation, seq, token, expiredAtNs)
|
||||
}
|
||||
|
||||
func (dlm *DistributedLockManager) SelectNotOwnedLocks(servers []pb.ServerAddress) (locks []*Lock) {
|
||||
@@ -180,6 +183,70 @@ func (dlm *DistributedLockManager) GetLock(key string) (*Lock, bool) {
|
||||
return dlm.lockManager.GetLock(key)
|
||||
}
|
||||
|
||||
// TransferLockToOwner serializes a fresh snapshot and handoff with local
|
||||
// mutations. Incoming replication bypasses admission so the receiver can
|
||||
// replicate back. The retry worker also calls it without a ring change.
|
||||
func (dlm *DistributedLockManager) TransferLockToOwner(key string) error {
|
||||
mutation := dlm.acquireMutation(key)
|
||||
defer dlm.mutations.ReleaseLock(key, mutation)
|
||||
_, err := dlm.transferToOwnerLocked(key)
|
||||
return err
|
||||
}
|
||||
|
||||
// transferToOwnerLocked returns the primary that owns the lease afterwards.
|
||||
func (dlm *DistributedLockManager) transferToOwnerLocked(key string) (owner pb.ServerAddress, err error) {
|
||||
defer func() {
|
||||
if err != nil && dlm.RetryTransferFn != nil {
|
||||
dlm.RetryTransferFn(key)
|
||||
}
|
||||
}()
|
||||
primary, backup := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
current, found := dlm.lockManager.GetLock(key)
|
||||
if !found {
|
||||
return primary, nil
|
||||
}
|
||||
if primary == "" {
|
||||
return "", NoLockServerError
|
||||
}
|
||||
if primary == dlm.Host {
|
||||
if current.handoff {
|
||||
dlm.lockManager.PromoteLock(key)
|
||||
}
|
||||
return primary, nil
|
||||
}
|
||||
if current.IsBackup && !current.handoff && backup == dlm.Host {
|
||||
return primary, nil
|
||||
}
|
||||
if dlm.TransferFn == nil {
|
||||
return "", LockHandoffPending
|
||||
}
|
||||
transferred, found := dlm.lockManager.beginTransfer(key)
|
||||
if !found {
|
||||
return primary, nil
|
||||
}
|
||||
// On error keep the frozen copy: the receiver may have committed.
|
||||
if err = dlm.TransferFn(primary, transferred); err != nil {
|
||||
return primary, fmt.Errorf("%w: %w", LockHandoffPending, err)
|
||||
}
|
||||
// Background retries can overlap a newer topology callback. Never evict
|
||||
// a lease now owned here or discard it before its newest owner receives it.
|
||||
currentPrimary, currentBackup := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
if currentPrimary == dlm.Host {
|
||||
dlm.lockManager.PromoteLock(key)
|
||||
} else if currentPrimary == primary {
|
||||
dlm.lockManager.finishTransfer(key, transferred.Token, currentBackup == dlm.Host)
|
||||
} else {
|
||||
return "", LockHandoffPending
|
||||
}
|
||||
return currentPrimary, nil
|
||||
}
|
||||
|
||||
// ReplicateLock sends an existing lease to its current backup after a topology
|
||||
// change, recording that the local lease may now have a remote copy.
|
||||
func (dlm *DistributedLockManager) ReplicateLock(lock *Lock) {
|
||||
dlm.replicateToBackup(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq, false)
|
||||
}
|
||||
|
||||
// replicateToBackup asynchronously replicates a lock operation to the backup server
|
||||
func (dlm *DistributedLockManager) replicateToBackup(key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
_, backup := dlm.LockRing.GetPrimaryAndBackup(key)
|
||||
@@ -187,6 +254,9 @@ func (dlm *DistributedLockManager) replicateToBackup(key string, expiredAtNs int
|
||||
return // single-server deployment, no backup
|
||||
}
|
||||
if dlm.ReplicateFn != nil {
|
||||
if !isUnlock && !dlm.lockManager.markReplicated(key, token) {
|
||||
return
|
||||
}
|
||||
go dlm.ReplicateFn(backup, key, expiredAtNs, token, prevToken, owner, generation, seq, isUnlock)
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
|
||||
// Wire up replication: each node's ReplicateFn calls the backup's DLM directly
|
||||
for _, dlm := range c.nodes {
|
||||
d := dlm // capture
|
||||
d.TransferFn = c.transferLease
|
||||
d.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
c.mu.Lock()
|
||||
target, ok := c.nodes[server]
|
||||
@@ -41,7 +42,7 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
|
||||
return // server is down
|
||||
}
|
||||
if isUnlock {
|
||||
target.RemoveBackupLockIfSeq(key, generation, seq)
|
||||
target.RemoveBackupLockIfSeq(key, generation, seq, token, expiredAtNs)
|
||||
} else {
|
||||
target.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
|
||||
}
|
||||
@@ -51,6 +52,17 @@ func newTestCluster(hosts ...pb.ServerAddress) *testCluster {
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *testCluster) transferLease(server pb.ServerAddress, lock *Lock) error {
|
||||
c.mu.Lock()
|
||||
target := c.nodes[server]
|
||||
c.mu.Unlock()
|
||||
if target == nil {
|
||||
return fmt.Errorf("handoff target %s is down", server)
|
||||
}
|
||||
target.InsertLock(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *testCluster) removeNode(host pb.ServerAddress) {
|
||||
c.mu.Lock()
|
||||
delete(c.nodes, host)
|
||||
@@ -70,6 +82,7 @@ func (c *testCluster) addNode(host pb.ServerAddress) {
|
||||
c.mu.Unlock()
|
||||
|
||||
// Wire up replication
|
||||
dlm.TransferFn = c.transferLease
|
||||
dlm.ReplicateFn = func(server pb.ServerAddress, key string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64, isUnlock bool) {
|
||||
c.mu.Lock()
|
||||
target, ok := c.nodes[server]
|
||||
@@ -78,7 +91,7 @@ func (c *testCluster) addNode(host pb.ServerAddress) {
|
||||
return
|
||||
}
|
||||
if isUnlock {
|
||||
target.RemoveBackupLockIfSeq(key, generation, seq)
|
||||
target.RemoveBackupLockIfSeq(key, generation, seq, token, expiredAtNs)
|
||||
} else {
|
||||
target.InsertBackupLock(key, expiredAtNs, token, prevToken, owner, generation, seq)
|
||||
}
|
||||
@@ -630,7 +643,7 @@ func TestDLM_NodeDropAndJoin_OwnershipDisruption(t *testing.T) {
|
||||
func TestDLM_RenewalDuringTransferWindow(t *testing.T) {
|
||||
// When a new node joins and steals a key range from a surviving node,
|
||||
// there's a window between ring update and lock transfer. During this
|
||||
// window, a client renewal should still succeed on the old primary
|
||||
// window, a client renewal through the old primary should hand off and redirect
|
||||
// (because it still holds the lock locally).
|
||||
hosts := []pb.ServerAddress{"filer1:8888", "filer2:8888", "filer3:8888"}
|
||||
cluster := newTestCluster(hosts...)
|
||||
@@ -664,11 +677,13 @@ func TestDLM_RenewalDuringTransferWindow(t *testing.T) {
|
||||
newPrimary := cluster.get(primaryHost).LockRing.GetPrimary(key)
|
||||
require.NotEqual(t, primaryHost, newPrimary, "key should have moved to a different primary")
|
||||
|
||||
// Renewal on the OLD primary should still succeed because it holds the lock locally
|
||||
// Renewal through the old primary hands the lease off, then follows the redirect.
|
||||
newToken, _, err := cluster.renewLock(key, "owner1", renewToken, 30*time.Second, primaryHost)
|
||||
require.NoError(t, err, "renewal on old primary should succeed during transfer window")
|
||||
assert.NotEmpty(t, newToken, "should get a new token from old primary")
|
||||
t.Logf("Key %s: primary changed from %s to %s, but renewal on old primary succeeded", key, primaryHost, newPrimary)
|
||||
assert.NotEmpty(t, newToken, "should get a new token from the new primary")
|
||||
installed, found := cluster.get(newPrimary).GetLock(key)
|
||||
require.True(t, found)
|
||||
require.Equal(t, newToken, installed.Token, "the new primary must issue the renewal")
|
||||
}
|
||||
|
||||
func TestDLM_ReplayedRenewalExtendsBackupExpiry(t *testing.T) {
|
||||
@@ -767,13 +782,13 @@ func TestDLM_StaleReplicationRejected(t *testing.T) {
|
||||
assert.Equal(t, int64(4), lock.Seq)
|
||||
|
||||
// Stale unlock (seq=2) should not delete the lock
|
||||
removed := lm.RemoveBackupLockIfSeq("key1", 1, 2)
|
||||
removed := lm.RemoveBackupLockIfSeq("key1", 1, 2, "token-newer", time.Now().Add(30*time.Second).UnixNano())
|
||||
assert.False(t, removed, "stale unlock should be rejected")
|
||||
_, found = lm.GetLock("key1")
|
||||
assert.True(t, found, "lock should still exist after stale unlock")
|
||||
|
||||
// Valid unlock (seq=5) should delete
|
||||
removed = lm.RemoveBackupLockIfSeq("key1", 1, 5)
|
||||
removed = lm.RemoveBackupLockIfSeq("key1", 1, 5, "token-newer", time.Now().Add(30*time.Second).UnixNano())
|
||||
assert.True(t, removed, "valid unlock should be accepted")
|
||||
_, found = lm.GetLock("key1")
|
||||
assert.False(t, found, "lock should be removed after valid unlock")
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package lock_manager
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDLM_TransferLockUsesFreshSnapshot(t *testing.T) {
|
||||
dlm := NewDistributedLockManager("handoff:8888")
|
||||
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
_, original, _, _, err := dlm.LockWithTimeout("key", expires, "", "owner")
|
||||
require.NoError(t, err)
|
||||
// A topology callback may have enumerated this key before its renewal.
|
||||
_, renewed, _, _, err := dlm.LockWithTimeout("key", expires, original, "owner")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, handOff(t, dlm, "key", true, func(current *Lock) error {
|
||||
require.Equal(t, renewed, current.Token)
|
||||
require.EqualValues(t, 2, current.Seq)
|
||||
// The receiver can replicate the lease back before acknowledging.
|
||||
within(t, "incoming replication during the handoff", func() {
|
||||
dlm.InsertBackupLock(current.Key, current.ExpiredAtNs, current.Token, current.PrevToken, current.Owner, current.Generation, current.Seq)
|
||||
})
|
||||
return nil
|
||||
}))
|
||||
current, found := dlm.GetLock("key")
|
||||
require.True(t, found)
|
||||
require.True(t, current.IsBackup)
|
||||
require.Equal(t, renewed, current.Token)
|
||||
}
|
||||
|
||||
func TestDLM_TransferLockFailureFreezesAuthority(t *testing.T) {
|
||||
dlm := NewDistributedLockManager("handoff:8888")
|
||||
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
_, token, _, _, err := dlm.LockWithTimeout("key", expires, "", "owner")
|
||||
require.NoError(t, err)
|
||||
failed := errors.New("handoff failed")
|
||||
target := NewDistributedLockManager("target:8888")
|
||||
target.LockRing.SetSnapshot([]pb.ServerAddress{target.Host}, 1)
|
||||
require.ErrorIs(t, handOff(t, dlm, "key", false, func(current *Lock) error {
|
||||
// The receiver committed, but its acknowledgement was lost.
|
||||
target.InsertLock(current.Key, current.ExpiredAtNs, current.Token, current.PrevToken, current.Owner, current.Generation, current.Seq)
|
||||
// A stalled handoff must not hold a global mutex across its RPC.
|
||||
var err error
|
||||
within(t, "another key during the stalled handoff", func() {
|
||||
_, _, _, _, err = dlm.LockWithTimeout("other-key", expires, "", "other-owner")
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return failed
|
||||
}), failed)
|
||||
// Back on the old ring, the frozen local copy itself must refuse.
|
||||
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, dlm.LockRing.Version()+1)
|
||||
current, found := dlm.GetLock("key")
|
||||
require.True(t, found)
|
||||
require.True(t, current.IsBackup)
|
||||
_, renewed, _, _, err := dlm.LockWithTimeout("key", expires, token, "owner")
|
||||
require.ErrorIs(t, err, LockHandoffPending)
|
||||
require.Empty(t, renewed, "an ambiguous handoff cannot retain renewal authority")
|
||||
_, renewed, _, _, err = target.LockWithTimeout("key", expires, token, "owner")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, renewed)
|
||||
require.NotEqual(t, token, renewed)
|
||||
_, err = dlm.Unlock("key", token)
|
||||
require.ErrorIs(t, err, LockHandoffPending)
|
||||
}
|
||||
|
||||
func TestDLM_TransferCompletionPreservesDifferentLease(t *testing.T) {
|
||||
for _, keepBackup := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(keepBackup), func(t *testing.T) {
|
||||
dlm := NewDistributedLockManager("handoff:8888")
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
dlm.InsertLock("key", expires, "original/secret", "", "owner", 1, 1)
|
||||
require.NoError(t, handOff(t, dlm, "key", keepBackup, func(*Lock) error {
|
||||
// Incoming replication is independent of client admission.
|
||||
dlm.InsertLock("key", expires, "replacement/secret", "", "new-owner", 2, 1)
|
||||
return nil
|
||||
}))
|
||||
current, found := dlm.GetLock("key")
|
||||
require.True(t, found)
|
||||
require.Equal(t, "replacement/secret", current.Token)
|
||||
require.False(t, current.IsBackup, "completion must not demote a different lease")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Confirm actual same-key admission contention, rather than inferring it from
|
||||
// a goroutine start or a sleep in the RPC test.
|
||||
func TestDLM_UnlockWaitsForHandoffAdmission(t *testing.T) {
|
||||
source := NewDistributedLockManager("source:8888")
|
||||
target := NewDistributedLockManager("target:8888")
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, 1)
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
_, token, _, _, err := source.LockWithTimeout("key", expires, "", "owner")
|
||||
require.NoError(t, err)
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{target.Host}, 2)
|
||||
entered, proceed := make(chan struct{}), make(chan struct{})
|
||||
waiting := make(chan struct{})
|
||||
source.onMutationWait = func(key string) {
|
||||
if key == "key" {
|
||||
close(waiting)
|
||||
}
|
||||
}
|
||||
var unblockOnce sync.Once
|
||||
unblock := func() { unblockOnce.Do(func() { close(proceed) }) }
|
||||
defer unblock()
|
||||
source.TransferFn = func(_ pb.ServerAddress, lock *Lock) error {
|
||||
close(entered)
|
||||
<-proceed
|
||||
target.InsertLock(lock.Key, lock.ExpiredAtNs, lock.Token, lock.PrevToken, lock.Owner, lock.Generation, lock.Seq)
|
||||
return nil
|
||||
}
|
||||
transferred := make(chan error, 1)
|
||||
go func() { transferred <- source.TransferLockToOwner("key") }()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("handoff did not start")
|
||||
}
|
||||
released := make(chan pb.ServerAddress, 1)
|
||||
go func() { moved, _ := source.Unlock("key", token); released <- moved }()
|
||||
select {
|
||||
case <-waiting:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("unlock did not reach contended admission")
|
||||
}
|
||||
select {
|
||||
case <-released:
|
||||
t.Fatal("unlock bypassed the handoff gate")
|
||||
default:
|
||||
}
|
||||
unblock()
|
||||
select {
|
||||
case err := <-transferred:
|
||||
require.NoError(t, err)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("handoff did not finish")
|
||||
}
|
||||
select {
|
||||
case moved := <-released:
|
||||
require.Equal(t, target.Host, moved)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("unlock did not finish after the handoff")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDLM_HandoffCompletionRechecksOwner(t *testing.T) {
|
||||
for _, next := range []pb.ServerAddress{"source:8888", "third:8888"} {
|
||||
t.Run(string(next), func(t *testing.T) {
|
||||
source := NewDistributedLockManager("source:8888")
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, 1)
|
||||
_, _, _, _, err := source.LockWithTimeout("key", time.Now().Add(time.Minute).UnixNano(), "", "owner")
|
||||
require.NoError(t, err)
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{"target:8888"}, 2)
|
||||
var destination pb.ServerAddress
|
||||
var retries int
|
||||
source.RetryTransferFn = func(key string) { require.Equal(t, "key", key); retries++ }
|
||||
source.TransferFn = func(to pb.ServerAddress, _ *Lock) error {
|
||||
destination = to
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{next}, 3)
|
||||
return nil
|
||||
}
|
||||
err = source.TransferLockToOwner("key")
|
||||
current, found := source.GetLock("key")
|
||||
require.True(t, found, "an old handoff cannot discard the newest owner's lease")
|
||||
if next == source.Host {
|
||||
require.NoError(t, err)
|
||||
require.False(t, current.IsBackup)
|
||||
} else {
|
||||
require.ErrorIs(t, err, LockHandoffPending)
|
||||
require.Equal(t, 1, retries)
|
||||
require.NoError(t, source.TransferLockToOwner("key"))
|
||||
require.Equal(t, next, destination)
|
||||
_, found = source.GetLock("key")
|
||||
require.False(t, found)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDLM_ServesLocallyWhenHandoffEndsHere(t *testing.T) {
|
||||
source := NewDistributedLockManager("source:8888")
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, 1)
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
_, token, _, _, err := source.LockWithTimeout("key", expires, "", "owner")
|
||||
require.NoError(t, err)
|
||||
version := int64(1)
|
||||
source.TransferFn = func(pb.ServerAddress, *Lock) error {
|
||||
version++
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{source.Host}, version)
|
||||
return nil
|
||||
}
|
||||
moveAway := func() {
|
||||
version++
|
||||
source.LockRing.SetSnapshot([]pb.ServerAddress{"target:8888"}, version)
|
||||
}
|
||||
moveAway()
|
||||
_, renewed, _, movedTo, err := source.LockWithTimeout("key", expires, token, "owner")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, movedTo, "the ring moved back here during the handoff")
|
||||
require.NotEqual(t, token, renewed)
|
||||
moveAway()
|
||||
movedTo, err = source.Unlock("key", renewed)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, movedTo)
|
||||
_, found := source.GetLock("key")
|
||||
require.False(t, found)
|
||||
}
|
||||
|
||||
// handOff moves key away from dlm and sends it through transfer. With
|
||||
// keepBackup, dlm stays in the ring as the key's backup.
|
||||
func handOff(t *testing.T, dlm *DistributedLockManager, key string, keepBackup bool, transfer func(*Lock) error) error {
|
||||
t.Helper()
|
||||
moveAway(t, dlm, key, keepBackup)
|
||||
dlm.TransferFn = func(_ pb.ServerAddress, lock *Lock) error { return transfer(lock) }
|
||||
return dlm.TransferLockToOwner(key)
|
||||
}
|
||||
|
||||
func moveAway(t *testing.T, dlm *DistributedLockManager, key string, keepBackup bool) {
|
||||
t.Helper()
|
||||
for i := 0; i < 100; i++ {
|
||||
servers := []pb.ServerAddress{pb.ServerAddress(fmt.Sprintf("target-%d:8888", i))}
|
||||
if keepBackup {
|
||||
servers = append(servers, dlm.Host)
|
||||
}
|
||||
dlm.LockRing.SetSnapshot(servers, dlm.LockRing.Version()+1)
|
||||
if primary, backup := dlm.LockRing.GetPrimaryAndBackup(key); primary != dlm.Host && (backup == dlm.Host) == keepBackup {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("no ring moves %s away from %s", key, dlm.Host)
|
||||
}
|
||||
|
||||
// within fails the test if fn has not returned after five seconds.
|
||||
func within(t *testing.T, what string, fn func()) {
|
||||
t.Helper()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
fn()
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s did not finish", what)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package lock_manager
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -15,13 +16,33 @@ var LockErrorNonEmptyTokenOnExpiredLock = fmt.Errorf("lock: non-empty token on a
|
||||
var LockErrorTokenMismatch = fmt.Errorf("lock: token mismatch")
|
||||
var UnlockErrorTokenMismatch = fmt.Errorf("unlock: token mismatch")
|
||||
var LockNotFound = fmt.Errorf("lock not found")
|
||||
var LockHandoffPending = fmt.Errorf("lock handoff pending")
|
||||
|
||||
// LockManager local lock manager, used by distributed lock manager
|
||||
type LockManager struct {
|
||||
locks map[string]*Lock
|
||||
locks map[string]*Lock
|
||||
// Released lease identities are retained only until their maximum expiry.
|
||||
removed map[releasedLease]int64
|
||||
accessLock sync.RWMutex
|
||||
nextGeneration atomic.Int64
|
||||
}
|
||||
type releasedLease struct{ path, id string }
|
||||
|
||||
// Tokens are opaque to clients. Keep a stable acquisition ID while rotating the
|
||||
// secret on renewal; local generation counters can overlap across primaries.
|
||||
func leaseID(token string) string {
|
||||
id, _, _ := strings.Cut(token, "/")
|
||||
return id
|
||||
}
|
||||
|
||||
func newLockToken(previous string) string {
|
||||
id := leaseID(previous)
|
||||
if id == "" {
|
||||
id = uuid.New().String()
|
||||
}
|
||||
return id + "/" + uuid.New().String()
|
||||
}
|
||||
|
||||
type Lock struct {
|
||||
Token string
|
||||
PrevToken string // token superseded by the latest renewal; a holder whose renewal response was lost still presents it
|
||||
@@ -31,6 +52,8 @@ type Lock struct {
|
||||
IsBackup bool // true if this node holds the lock as a backup
|
||||
Generation int64 // monotonic fencing token, increments on fresh acquisition
|
||||
Seq int64 // per-lock sequence number, increments on every mutation (acquire/renew/unlock)
|
||||
replicated bool // a copy may exist elsewhere, requiring a release record
|
||||
handoff bool // renewal authority has moved, but delivery may need retry
|
||||
}
|
||||
|
||||
func NewLockManager() *LockManager {
|
||||
@@ -72,13 +95,37 @@ func (lm *LockManager) advanceGenerationFloor(generation int64) {
|
||||
}
|
||||
}
|
||||
|
||||
func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner string) (lockOwner, renewToken string, generation int64, seq int64, err error) {
|
||||
// rememberRemoval runs under accessLock. Delayed messages for this lease are
|
||||
// rejected until its maximum expiry, after which inserts reject them as expired.
|
||||
func (lm *LockManager) rememberRemoval(path, token string, expiredAtNs int64) {
|
||||
if token == "" || expiredAtNs <= time.Now().UnixNano() {
|
||||
return
|
||||
}
|
||||
if lm.removed == nil {
|
||||
lm.removed = make(map[releasedLease]int64)
|
||||
}
|
||||
key := releasedLease{path, leaseID(token)}
|
||||
lm.removed[key] = max(lm.removed[key], expiredAtNs)
|
||||
}
|
||||
|
||||
func (lm *LockManager) wasRemoved(path, token string) bool {
|
||||
return lm.removed[releasedLease{path, leaseID(token)}] > time.Now().UnixNano()
|
||||
}
|
||||
|
||||
// Lock also returns the effective expiry for replication. Renewals cannot
|
||||
// shorten it, so a release carries a validity bound for every older RPC.
|
||||
func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner string) (lockOwner, renewToken string, generation int64, seq int64, leaseExpires int64, err error) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
leaseExpires = expiredAtNs
|
||||
|
||||
glog.V(4).Infof("lock %s %v %v %v", path, time.Unix(0, expiredAtNs), token, owner)
|
||||
|
||||
if oldValue, found := lm.locks[path]; found {
|
||||
if oldValue.handoff && oldValue.ExpiredAtNs > time.Now().UnixNano() {
|
||||
err = LockHandoffPending
|
||||
return
|
||||
}
|
||||
if oldValue.ExpiredAtNs > 0 && oldValue.ExpiredAtNs < time.Now().UnixNano() {
|
||||
// lock is expired, set to a new lock
|
||||
if token != "" {
|
||||
@@ -87,7 +134,7 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
|
||||
return
|
||||
} else {
|
||||
// new lock
|
||||
renewToken = uuid.New().String()
|
||||
renewToken = newLockToken("")
|
||||
generation = lm.NextGeneration()
|
||||
seq = 1
|
||||
glog.V(4).Infof("key %s new token %v owner %v generation %d", path, renewToken, owner, generation)
|
||||
@@ -96,14 +143,15 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
|
||||
}
|
||||
}
|
||||
// not expired
|
||||
leaseExpires = max(expiredAtNs, oldValue.ExpiredAtNs)
|
||||
lockOwner = oldValue.Owner
|
||||
if oldValue.Token == token {
|
||||
// token matches, renew the lock
|
||||
renewToken = uuid.New().String()
|
||||
renewToken = newLockToken(oldValue.Token)
|
||||
generation = oldValue.Generation // keep same generation on renewal
|
||||
seq = oldValue.Seq + 1
|
||||
glog.V(4).Infof("key %s old token %v owner %v => %v owner %v", path, oldValue.Token, oldValue.Owner, renewToken, owner)
|
||||
lm.locks[path] = &Lock{Token: renewToken, PrevToken: oldValue.Token, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
|
||||
lm.locks[path] = &Lock{Token: renewToken, PrevToken: oldValue.Token, ExpiredAtNs: leaseExpires, Owner: owner, Generation: generation, Seq: seq, replicated: oldValue.replicated}
|
||||
return
|
||||
}
|
||||
if token != "" && token == oldValue.PrevToken && owner == oldValue.Owner {
|
||||
@@ -113,7 +161,7 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
|
||||
renewToken = oldValue.Token
|
||||
generation = oldValue.Generation
|
||||
seq = oldValue.Seq + 1
|
||||
oldValue.ExpiredAtNs = expiredAtNs
|
||||
oldValue.ExpiredAtNs = leaseExpires
|
||||
oldValue.Seq = seq
|
||||
return
|
||||
}
|
||||
@@ -130,7 +178,7 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
|
||||
glog.V(4).Infof("key %s no lock owner %v", path, owner)
|
||||
if token == "" {
|
||||
// new lock
|
||||
renewToken = uuid.New().String()
|
||||
renewToken = newLockToken("")
|
||||
generation = lm.NextGeneration()
|
||||
seq = 1
|
||||
glog.V(4).Infof("key %s new token %v owner %v generation %d", path, renewToken, owner, generation)
|
||||
@@ -144,55 +192,60 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
|
||||
}
|
||||
}
|
||||
|
||||
func (lm *LockManager) Unlock(path string, token string) (isUnlocked bool, generation int64, seq int64, err error) {
|
||||
// Unlock returns the released lease and its maximum expiry atomically, including
|
||||
// when the caller uses a superseded token after losing a renewal response.
|
||||
func (lm *LockManager) Unlock(path, token string) (*Lock, error) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
|
||||
if oldValue, found := lm.locks[path]; found {
|
||||
now := time.Now()
|
||||
if oldValue.ExpiredAtNs > 0 && oldValue.ExpiredAtNs < now.UnixNano() {
|
||||
// lock is expired, delete it
|
||||
isUnlocked = true
|
||||
generation = oldValue.Generation
|
||||
seq = oldValue.Seq + 1
|
||||
glog.V(4).Infof("key %s expired at %v", path, time.Unix(0, oldValue.ExpiredAtNs))
|
||||
delete(lm.locks, path)
|
||||
return
|
||||
}
|
||||
if oldValue.Token == token || (token != "" && token == oldValue.PrevToken) {
|
||||
isUnlocked = true
|
||||
generation = oldValue.Generation
|
||||
seq = oldValue.Seq + 1
|
||||
glog.V(4).Infof("key %s unlocked with %v", path, token)
|
||||
delete(lm.locks, path)
|
||||
return
|
||||
} else {
|
||||
isUnlocked = false
|
||||
err = UnlockErrorTokenMismatch
|
||||
return
|
||||
}
|
||||
old, found := lm.locks[path]
|
||||
if !found {
|
||||
return nil, LockNotFound
|
||||
}
|
||||
err = LockNotFound
|
||||
return
|
||||
if old.handoff {
|
||||
return nil, LockHandoffPending
|
||||
}
|
||||
expired := old.ExpiredAtNs > 0 && old.ExpiredAtNs < time.Now().UnixNano()
|
||||
if !expired && old.Token != token && (token == "" || token != old.PrevToken) {
|
||||
return nil, UnlockErrorTokenMismatch
|
||||
}
|
||||
if expired {
|
||||
glog.V(4).Infof("key %s expired at %v", path, time.Unix(0, old.ExpiredAtNs))
|
||||
} else {
|
||||
glog.V(4).Infof("key %s unlocked with %v", path, token)
|
||||
}
|
||||
released := *old
|
||||
released.Seq++
|
||||
if released.replicated {
|
||||
lm.rememberRemoval(path, released.Token, released.ExpiredAtNs)
|
||||
}
|
||||
delete(lm.locks, path)
|
||||
return &released, nil
|
||||
}
|
||||
|
||||
func (lm *LockManager) CleanUp() {
|
||||
|
||||
for {
|
||||
time.Sleep(1 * time.Minute)
|
||||
now := time.Now().UnixNano()
|
||||
time.Sleep(time.Minute)
|
||||
lm.cleanUp(time.Now().UnixNano())
|
||||
}
|
||||
}
|
||||
|
||||
lm.accessLock.Lock()
|
||||
for key, value := range lm.locks {
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
if now > value.ExpiredAtNs {
|
||||
glog.V(4).Infof("key %s expired at %v", key, time.Unix(0, value.ExpiredAtNs))
|
||||
delete(lm.locks, key)
|
||||
}
|
||||
func (lm *LockManager) cleanUp(now int64) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
for key, lock := range lm.locks {
|
||||
if lock != nil && now >= lock.ExpiredAtNs {
|
||||
glog.V(4).Infof("key %s expired at %v", key, time.Unix(0, lock.ExpiredAtNs))
|
||||
delete(lm.locks, key)
|
||||
}
|
||||
lm.accessLock.Unlock()
|
||||
}
|
||||
for key, expires := range lm.removed {
|
||||
if now >= expires {
|
||||
delete(lm.removed, key)
|
||||
}
|
||||
}
|
||||
if len(lm.removed) == 0 {
|
||||
lm.removed = nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,20 +273,15 @@ func (lm *LockManager) SelectLocks(selectFn func(key string) bool) (locks []*Loc
|
||||
return
|
||||
}
|
||||
|
||||
// InsertLock inserts a lock from a transfer if it is newer than the current state.
|
||||
func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) bool {
|
||||
// InsertLock inserts a lock from a transfer if it is newer than the current
|
||||
// state, returning the effective expiry atomically with installation.
|
||||
func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) (leaseExpires int64, accepted bool) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
|
||||
if existing, found := lm.locks[path]; found {
|
||||
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) <= 0 {
|
||||
glog.V(4).Infof("lock %s: rejecting stale transfer gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
|
||||
return false
|
||||
}
|
||||
if lock := lm.insertCopyLocked(path, expiredAtNs, token, prevToken, owner, generation, seq, false); lock != nil {
|
||||
return lock.ExpiredAtNs, true
|
||||
}
|
||||
lm.locks[path] = &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
|
||||
lm.advanceGenerationFloor(generation)
|
||||
return true
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// InsertBackupLock inserts or updates a lock as a backup copy.
|
||||
@@ -243,50 +291,115 @@ func (lm *LockManager) InsertLock(path string, expiredAtNs int64, token string,
|
||||
func (lm *LockManager) InsertBackupLock(path string, expiredAtNs int64, token string, prevToken string, owner string, generation int64, seq int64) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
lm.insertCopyLocked(path, expiredAtNs, token, prevToken, owner, generation, seq, true)
|
||||
}
|
||||
|
||||
if existing, found := lm.locks[path]; found {
|
||||
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) <= 0 {
|
||||
glog.V(4).Infof("backup lock %s: rejecting stale gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
|
||||
return
|
||||
}
|
||||
lm.locks[path] = &Lock{
|
||||
Token: token,
|
||||
PrevToken: prevToken,
|
||||
ExpiredAtNs: expiredAtNs,
|
||||
Owner: owner,
|
||||
IsBackup: existing.IsBackup,
|
||||
Generation: generation,
|
||||
Seq: seq,
|
||||
}
|
||||
lm.advanceGenerationFloor(generation)
|
||||
return
|
||||
// insertCopyLocked runs under accessLock. It rejects a copy that is expired,
|
||||
// released, or not newer than the live lock, and never shortens the same lease.
|
||||
func (lm *LockManager) insertCopyLocked(path string, expiredAtNs int64, token, prevToken, owner string, generation, seq int64, asBackup bool) *Lock {
|
||||
now := time.Now().UnixNano()
|
||||
if expiredAtNs <= now || lm.wasRemoved(path, token) {
|
||||
return nil
|
||||
}
|
||||
lm.locks[path] = &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, IsBackup: true, Generation: generation, Seq: seq}
|
||||
lock := &Lock{Token: token, PrevToken: prevToken, ExpiredAtNs: expiredAtNs, Owner: owner, IsBackup: asBackup, Generation: generation, Seq: seq, replicated: true}
|
||||
if existing, found := lm.locks[path]; found && existing.ExpiredAtNs > now {
|
||||
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) <= 0 {
|
||||
glog.V(4).Infof("lock %s: rejecting stale copy gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
|
||||
return nil
|
||||
}
|
||||
sameLease := leaseID(existing.Token) == leaseID(token)
|
||||
if sameLease {
|
||||
lock.ExpiredAtNs = max(expiredAtNs, existing.ExpiredAtNs)
|
||||
}
|
||||
if asBackup {
|
||||
lock.IsBackup = existing.IsBackup
|
||||
lock.handoff = existing.handoff && sameLease
|
||||
}
|
||||
}
|
||||
lm.locks[path] = lock
|
||||
lm.advanceGenerationFloor(generation)
|
||||
return lock
|
||||
}
|
||||
|
||||
// markReplicated must precede sending a copy. If release won the race, skip
|
||||
// the send; otherwise unlock will retain this lease's identity until expiry.
|
||||
func (lm *LockManager) markReplicated(path, token string) bool {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
lock, found := lm.locks[path]
|
||||
if !found || leaseID(lock.Token) != leaseID(token) {
|
||||
return false
|
||||
}
|
||||
lock.replicated = true
|
||||
return true
|
||||
}
|
||||
|
||||
// beginTransfer freezes local renewal authority before sending an RPC. Even a
|
||||
// failed RPC may have installed the lease on its receiver.
|
||||
func (lm *LockManager) beginTransfer(path string) (*Lock, bool) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
lock, found := lm.locks[path]
|
||||
if !found || lock.ExpiredAtNs <= time.Now().UnixNano() {
|
||||
return nil, false
|
||||
}
|
||||
lock.replicated, lock.handoff, lock.IsBackup = true, true, true
|
||||
cp := *lock
|
||||
cp.Key = path
|
||||
return &cp, true
|
||||
}
|
||||
|
||||
// finishTransfer changes only the lease that was handed off. A different lease
|
||||
// installed by incoming replication while the RPC was in flight must survive.
|
||||
func (lm *LockManager) finishTransfer(path, token string, keepBackup bool) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
if lock, found := lm.locks[path]; found && leaseID(lock.Token) == leaseID(token) {
|
||||
if keepBackup {
|
||||
lock.IsBackup = true
|
||||
lock.handoff = false
|
||||
} else {
|
||||
delete(lm.locks, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RemoveLock removes a lock by key
|
||||
func (lm *LockManager) RemoveLock(path string) {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
// Ownership eviction is not a release: the same live mutation may return
|
||||
// in a later transfer. Only completed releases create tombstones.
|
||||
delete(lm.locks, path)
|
||||
}
|
||||
|
||||
// RemoveBackupLockIfSeq removes the local copy only if the incoming mutation is
|
||||
// not older than the current (generation, seq). This prevents a late unlock from
|
||||
// deleting a newer reacquired lock whose seq has reset.
|
||||
func (lm *LockManager) RemoveBackupLockIfSeq(path string, generation int64, seq int64) bool {
|
||||
// RemoveBackupLockIfSeq records a release even if its acquire has not arrived.
|
||||
// A release can only delete its own lease, never a different primary's lease
|
||||
// whose local generation may be smaller or equal.
|
||||
func (lm *LockManager) RemoveBackupLockIfSeq(path string, generation, seq int64, token string, expiredAtNs int64) bool {
|
||||
lm.accessLock.Lock()
|
||||
defer lm.accessLock.Unlock()
|
||||
|
||||
lm.advanceGenerationFloor(generation)
|
||||
if existing, found := lm.locks[path]; found {
|
||||
if compareMutationVersion(generation, seq, existing.Generation, existing.Seq) >= 0 {
|
||||
delete(lm.locks, path)
|
||||
return true
|
||||
// Older primaries omitted release metadata. Preserve ordered releases
|
||||
// for their legacy tokens without letting them delete a new lease.
|
||||
// For slash-format tokens, equal generations can belong to different
|
||||
// primaries. Without a lease ID it is safer to retain the lease until
|
||||
// expiry than to delete an unrelated acquisition during an upgrade.
|
||||
if token == "" && !strings.Contains(existing.Token, "/") {
|
||||
token = existing.Token
|
||||
}
|
||||
glog.V(4).Infof("backup lock %s: rejecting stale unlock gen=%d seq=%d (current gen=%d seq=%d)", path, generation, seq, existing.Generation, existing.Seq)
|
||||
return false
|
||||
if existing.Generation != generation || leaseID(existing.Token) != leaseID(token) {
|
||||
lm.rememberRemoval(path, token, expiredAtNs)
|
||||
return false
|
||||
}
|
||||
if seq < existing.Seq {
|
||||
return false
|
||||
}
|
||||
expiredAtNs = max(expiredAtNs, existing.ExpiredAtNs)
|
||||
delete(lm.locks, path)
|
||||
}
|
||||
lm.rememberRemoval(path, token, expiredAtNs)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -347,6 +460,7 @@ func (lm *LockManager) PromoteLock(key string) bool {
|
||||
|
||||
if lock, found := lm.locks[key]; found && lock.IsBackup {
|
||||
lock.IsBackup = false
|
||||
lock.handoff = false
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -359,6 +473,7 @@ func (lm *LockManager) DemoteLock(key string) bool {
|
||||
|
||||
if lock, found := lm.locks[key]; found && !lock.IsBackup {
|
||||
lock.IsBackup = true
|
||||
lock.replicated = true
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -35,7 +35,7 @@ func TestLockManager_InsertLockAdvancesGenerationCounter(t *testing.T) {
|
||||
|
||||
lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token1", "", "owner1", 12, 1)
|
||||
|
||||
_, renewToken, generation, _, err := lm.Lock("key2", time.Now().Add(30*time.Second).UnixNano(), "", "owner2")
|
||||
_, renewToken, generation, _, _, err := lm.Lock("key2", time.Now().Add(30*time.Second).UnixNano(), "", "owner2")
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, renewToken)
|
||||
assert.Greater(t, generation, int64(12))
|
||||
@@ -57,7 +57,7 @@ func TestLockManager_InsertBackupLockRejectsOlderGeneration(t *testing.T) {
|
||||
func TestLockManager_InsertBackupLockKeepsPrimaryRole(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
|
||||
ok := lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 8, 1)
|
||||
ok := inserted(lm.InsertLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-old", "", "owner1", 8, 1))
|
||||
assert.True(t, ok)
|
||||
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 2)
|
||||
@@ -75,7 +75,7 @@ func TestLockManager_RemoveBackupLockRejectsOlderGeneration(t *testing.T) {
|
||||
|
||||
lm.InsertBackupLock("key1", time.Now().Add(30*time.Second).UnixNano(), "token-new", "", "owner1", 8, 1)
|
||||
|
||||
removed := lm.RemoveBackupLockIfSeq("key1", 7, 9)
|
||||
removed := lm.RemoveBackupLockIfSeq("key1", 7, 9, "token-old", time.Now().Add(30*time.Second).UnixNano())
|
||||
assert.False(t, removed)
|
||||
|
||||
lock, found := lm.GetLock("key1")
|
||||
@@ -89,36 +89,36 @@ func TestLockManager_LostRenewalResponseReplaysToken(t *testing.T) {
|
||||
lm := NewLockManager()
|
||||
expires := time.Now().Add(30 * time.Second).UnixNano()
|
||||
|
||||
_, token1, _, _, err := lm.Lock("key1", expires, "", "owner1")
|
||||
_, token1, _, _, _, err := lm.Lock("key1", expires, "", "owner1")
|
||||
assert.NoError(t, err)
|
||||
|
||||
// The renewal rotated token1 to token2; the client never learned it.
|
||||
_, token2, _, _, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
_, token2, _, _, _, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, token1, token2)
|
||||
|
||||
// Retrying with the superseded token replays the current one instead of
|
||||
// conflicting with its own lease until it expires.
|
||||
owner, replayed, _, _, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
owner, replayed, _, _, _, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "owner1", owner)
|
||||
assert.Equal(t, token2, replayed)
|
||||
|
||||
// A replay from a different owner still mismatches.
|
||||
_, _, _, _, err = lm.Lock("key1", expires, token1, "intruder")
|
||||
_, _, _, _, _, err = lm.Lock("key1", expires, token1, "intruder")
|
||||
assert.Error(t, err)
|
||||
|
||||
// The next rotation retires the superseded token for good.
|
||||
_, token3, _, _, err := lm.Lock("key1", expires, token2, "owner1")
|
||||
_, token3, _, _, _, err := lm.Lock("key1", expires, token2, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, token2, token3)
|
||||
_, _, _, _, err = lm.Lock("key1", expires, token1, "owner1")
|
||||
_, _, _, _, _, err = lm.Lock("key1", expires, token1, "owner1")
|
||||
assert.Error(t, err)
|
||||
|
||||
// A superseded token still releases its own lock.
|
||||
unlocked, _, _, err := lm.Unlock("key1", token2)
|
||||
released, err := lm.Unlock("key1", token2)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, unlocked)
|
||||
assert.NotNil(t, released)
|
||||
}
|
||||
|
||||
func TestLockManager_LostRenewalReplayAdvancesSeq(t *testing.T) {
|
||||
@@ -126,16 +126,16 @@ func TestLockManager_LostRenewalReplayAdvancesSeq(t *testing.T) {
|
||||
expires := time.Now().Add(30 * time.Second).UnixNano()
|
||||
later := time.Now().Add(60 * time.Second).UnixNano()
|
||||
|
||||
_, token1, _, _, err := lm.Lock("key1", expires, "", "owner1")
|
||||
_, token1, _, _, _, err := lm.Lock("key1", expires, "", "owner1")
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, token2, _, seq2, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
_, token2, _, seq2, _, err := lm.Lock("key1", expires, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
|
||||
// A replay that extends the lease must advance seq, otherwise backups
|
||||
// reject the replicated expiry as a stale mutation and can grant the
|
||||
// lock when the old expiry passes after a promotion.
|
||||
_, replayed, _, seq3, err := lm.Lock("key1", later, token1, "owner1")
|
||||
_, replayed, _, seq3, _, err := lm.Lock("key1", later, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, token2, replayed)
|
||||
assert.Equal(t, seq2+1, seq3)
|
||||
@@ -146,7 +146,7 @@ func TestLockManager_LostRenewalReplayAdvancesSeq(t *testing.T) {
|
||||
assert.Equal(t, seq3, lock.Seq)
|
||||
|
||||
// Repeated retries keep advancing instead of colliding at one seq.
|
||||
_, _, _, seq4, err := lm.Lock("key1", later, token1, "owner1")
|
||||
_, _, _, seq4, _, err := lm.Lock("key1", later, token1, "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, seq3+1, seq4)
|
||||
}
|
||||
@@ -166,8 +166,10 @@ func TestLockManager_InsertBackupLockKeepsPrevToken(t *testing.T) {
|
||||
|
||||
// Once promoted, the node still replays a retry of the superseded token.
|
||||
assert.True(t, lm.PromoteLock("key1"))
|
||||
owner, replayed, _, _, err := lm.Lock("key1", expires, "token1", "owner1")
|
||||
owner, replayed, _, _, _, err := lm.Lock("key1", expires, "token1", "owner1")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "owner1", owner)
|
||||
assert.Equal(t, "token2", replayed)
|
||||
}
|
||||
|
||||
func inserted(_ int64, accepted bool) bool { return accepted }
|
||||
@@ -0,0 +1,49 @@
|
||||
package lock_manager
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLiveLockMayReturnAfterOwnershipEviction(t *testing.T) {
|
||||
for _, selectLocks := range []bool{false, true} {
|
||||
manager := NewLockManager()
|
||||
expiry := time.Now().Add(time.Minute).UnixNano()
|
||||
manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)
|
||||
if selectLocks {
|
||||
manager.SelectLocks(func(string) bool { return true })
|
||||
} else {
|
||||
manager.RemoveLock("key")
|
||||
}
|
||||
if !inserted(manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)) {
|
||||
t.Fatalf("live transfer rejected after eviction (SelectLocks=%v)", selectLocks)
|
||||
}
|
||||
if released, err := manager.Unlock("key", "token"); released == nil || err != nil {
|
||||
t.Fatalf("unlock: released=%v err=%v", released, err)
|
||||
}
|
||||
if inserted(manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)) {
|
||||
t.Fatal("completed unlock resurrected by transfer")
|
||||
}
|
||||
// Installing and then evicting a newer acquisition must not erase the
|
||||
// earlier release record. The newer live lease may still return.
|
||||
_, nextToken, gen, seq, _, err := manager.Lock("key", expiry, "", "next-owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if selectLocks {
|
||||
manager.SelectLocks(func(string) bool { return true })
|
||||
} else {
|
||||
manager.RemoveLock("key")
|
||||
}
|
||||
if inserted(manager.InsertLock("key", expiry, "token", "", "owner", 3, 1)) {
|
||||
t.Fatal("new acquisition and ownership eviction erased an earlier release")
|
||||
}
|
||||
manager.InsertBackupLock("key", expiry, "token", "", "owner", 3, 1)
|
||||
if _, found := manager.GetLock("key"); found {
|
||||
t.Fatal("earlier release resurrected by replication after ownership eviction")
|
||||
}
|
||||
if !inserted(manager.InsertLock("key", expiry, nextToken, "", "next-owner", gen, seq)) {
|
||||
t.Fatal("newer live lease could not return after ownership eviction")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
package lock_manager
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type leaseMutation struct {
|
||||
key, token, prev, owner string
|
||||
expires, gen, seq int64
|
||||
unlock bool
|
||||
}
|
||||
|
||||
func captureLeaseMutations(t *testing.T, dlm *DistributedLockManager) func() leaseMutation {
|
||||
t.Helper()
|
||||
messages := make(chan leaseMutation, 4)
|
||||
dlm.ReplicateFn = func(_ pb.ServerAddress, key string, expires int64, token, prev, owner string, gen, seq int64, unlock bool) {
|
||||
messages <- leaseMutation{key, token, prev, owner, expires, gen, seq, unlock}
|
||||
}
|
||||
return func() leaseMutation {
|
||||
t.Helper()
|
||||
select {
|
||||
case m := <-messages:
|
||||
return m
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("replication callback not invoked")
|
||||
return leaseMutation{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m leaseMutation) deliver(dlm *DistributedLockManager) {
|
||||
if m.unlock {
|
||||
dlm.RemoveBackupLockIfSeq(m.key, m.gen, m.seq, m.token, m.expires)
|
||||
} else {
|
||||
dlm.InsertBackupLock(m.key, m.expires, m.token, m.prev, m.owner, m.gen, m.seq)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDLM_FreshPrimaryAfterReleasedLease(t *testing.T) {
|
||||
for _, previousGeneration := range []int{1, 20} {
|
||||
t.Run(fmt.Sprint(previousGeneration), func(t *testing.T) {
|
||||
a := NewDistributedLockManager("release-a:8888")
|
||||
c := NewDistributedLockManager("release-c:8888")
|
||||
initial := []pb.ServerAddress{a.Host, c.Host}
|
||||
a.LockRing.SetSnapshot(initial, 1)
|
||||
// A newly joined or restarted process has an empty generation counter.
|
||||
b := NewDistributedLockManager("release-b:8888")
|
||||
next := []pb.ServerAddress{a.Host, b.Host, c.Host}
|
||||
b.LockRing.SetSnapshot(next, 2)
|
||||
key := ""
|
||||
for i := 0; i < 1000; i++ {
|
||||
candidate := fmt.Sprintf("key-%d", i)
|
||||
oldPrimary, _ := a.LockRing.GetPrimaryAndBackup(candidate)
|
||||
primary, backup := b.LockRing.GetPrimaryAndBackup(candidate)
|
||||
if oldPrimary == a.Host && primary == b.Host && backup == a.Host {
|
||||
key = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
require.NotEmpty(t, key)
|
||||
receiveA := captureLeaseMutations(t, a)
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
var acquire, release leaseMutation
|
||||
var previousAcquires []leaseMutation
|
||||
for i := 0; i < previousGeneration; i++ {
|
||||
_, token, _, moved, err := a.LockWithTimeout(key, expires, "", "writer")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, moved)
|
||||
acquire = receiveA()
|
||||
previousAcquires = append(previousAcquires, acquire)
|
||||
acquire.deliver(c)
|
||||
_, err = a.Unlock(key, token)
|
||||
require.NoError(t, err)
|
||||
release = receiveA()
|
||||
release.deliver(c)
|
||||
}
|
||||
require.NotEmpty(t, a.lockManager.removed)
|
||||
require.Empty(t, a.AllLocks()) // topology handoff has no live lease to transfer
|
||||
a.LockRing.SetSnapshot(next, 2)
|
||||
receiveB := captureLeaseMutations(t, b)
|
||||
_, token, gen, moved, err := b.LockWithTimeout(key, expires, "", "writer")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, moved)
|
||||
require.EqualValues(t, 1, gen)
|
||||
require.NotEqual(t, leaseID(acquire.token), leaseID(token))
|
||||
receiveB().deliver(a)
|
||||
lock, found := a.GetLock(key)
|
||||
require.True(t, found, "new primary's valid lease must be replicated")
|
||||
require.Equal(t, token, lock.Token)
|
||||
|
||||
// Old releases must not delete a distinct lease, even at an equal or
|
||||
// higher generation. Old transfers must still be rejected.
|
||||
release.deliver(a)
|
||||
for _, delayed := range previousAcquires {
|
||||
delayed.deliver(a)
|
||||
require.False(t, inserted(a.lockManager.InsertLock(key, delayed.expires, delayed.token, delayed.prev, delayed.owner, delayed.gen, delayed.seq)))
|
||||
}
|
||||
lock, found = a.GetLock(key)
|
||||
require.True(t, found)
|
||||
require.Equal(t, token, lock.Token)
|
||||
|
||||
// B fails before its lease expires; A must preserve that lease.
|
||||
a.LockRing.SetSnapshot([]pb.ServerAddress{a.Host}, 3)
|
||||
require.True(t, a.PromoteLock(key))
|
||||
_, conflicting, _, _, err := a.LockWithTimeout(key, expires, "", "another-owner")
|
||||
require.Error(t, err)
|
||||
require.Empty(t, conflicting)
|
||||
_, renewed, _, _, err := a.LockWithTimeout(key, expires, token, "writer")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, renewed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDLM_ReleaseCoversAllRenewalExpiries(t *testing.T) {
|
||||
a := NewDistributedLockManager("expiry-a:8888")
|
||||
b := NewDistributedLockManager("expiry-b:8888")
|
||||
hosts := []pb.ServerAddress{a.Host, b.Host}
|
||||
a.LockRing.SetSnapshot(hosts, 1)
|
||||
b.LockRing.SetSnapshot(hosts, 1)
|
||||
if primary, _ := a.LockRing.GetPrimaryAndBackup("key"); primary != a.Host {
|
||||
a, b = b, a
|
||||
}
|
||||
receive := captureLeaseMutations(t, a)
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
_, token1, _, _, err := a.LockWithTimeout("key", expires, "", "owner")
|
||||
require.NoError(t, err)
|
||||
acquire := receive()
|
||||
_, token2, _, _, err := a.LockWithTimeout("key", time.Now().Add(time.Second).UnixNano(), token1, "owner")
|
||||
require.NoError(t, err)
|
||||
renewal := receive()
|
||||
require.NotEqual(t, token1, token2)
|
||||
require.Equal(t, leaseID(token1), leaseID(token2))
|
||||
require.Equal(t, expires, renewal.expires, "renewal cannot shorten the validity bound")
|
||||
// Retry a lost response with a shorter requested TTL as well.
|
||||
_, replayed, _, _, err := a.LockWithTimeout("key", time.Now().Add(time.Second).UnixNano(), token1, "owner")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, token2, replayed)
|
||||
retry := receive()
|
||||
_, err = a.Unlock("key", token1) // release using the superseded token
|
||||
require.NoError(t, err)
|
||||
release := receive()
|
||||
require.True(t, release.unlock)
|
||||
require.Equal(t, token2, release.token)
|
||||
require.Equal(t, expires, release.expires)
|
||||
release.deliver(b)
|
||||
for _, delayed := range []leaseMutation{acquire, renewal, retry} {
|
||||
delayed.deliver(b)
|
||||
require.False(t, inserted(b.lockManager.InsertLock(delayed.key, delayed.expires, delayed.token, delayed.prev, delayed.owner, delayed.gen, delayed.seq)))
|
||||
}
|
||||
_, found := b.GetLock("key")
|
||||
require.False(t, found)
|
||||
require.NotEmpty(t, a.lockManager.removed, "renewal must preserve replication tracking")
|
||||
b.lockManager.cleanUp(expires - 1)
|
||||
require.Len(t, b.lockManager.removed, 1)
|
||||
b.lockManager.cleanUp(expires)
|
||||
require.Nil(t, b.lockManager.removed)
|
||||
}
|
||||
|
||||
func TestDLM_LocalReleasesDoNotRetainRecords(t *testing.T) {
|
||||
dlm := NewDistributedLockManager("single:8888")
|
||||
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
|
||||
for i := 0; i < 1000; i++ {
|
||||
key := fmt.Sprintf("object-%d", i)
|
||||
_, token, _, _, err := dlm.LockWithTimeout(key, time.Now().Add(time.Minute).UnixNano(), "", "writer")
|
||||
require.NoError(t, err)
|
||||
_, err = dlm.Unlock(key, token)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.Empty(t, dlm.AllLocks())
|
||||
require.Empty(t, dlm.lockManager.removed)
|
||||
}
|
||||
|
||||
func TestLockManager_ReleaseRecordReclamation(t *testing.T) {
|
||||
manager := NewLockManager()
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
for i := 0; i < 1000; i++ {
|
||||
key := fmt.Sprintf("object-%d", i)
|
||||
token := fmt.Sprintf("lease-%d/secret", i)
|
||||
require.True(t, inserted(manager.InsertLock(key, expires, token, "", "writer", int64(i+1), 1)))
|
||||
released, err := manager.Unlock(key, token)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, released)
|
||||
}
|
||||
require.Empty(t, manager.AllLocks())
|
||||
require.Len(t, manager.removed, 1000)
|
||||
manager.cleanUp(expires)
|
||||
require.Nil(t, manager.removed)
|
||||
|
||||
// Replay the exact original payload after its actual validity bound passes.
|
||||
expiredLease := time.Now().Add(100 * time.Millisecond).UnixNano()
|
||||
require.True(t, inserted(manager.InsertLock("expired", expiredLease, "expired-lease/secret", "", "writer", 1, 1)))
|
||||
released, err := manager.Unlock("expired", "expired-lease/secret")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, released)
|
||||
require.Eventually(t, func() bool { return time.Now().UnixNano() >= expiredLease }, time.Second, time.Millisecond)
|
||||
manager.cleanUp(time.Now().UnixNano())
|
||||
require.Nil(t, manager.removed)
|
||||
require.False(t, inserted(manager.InsertLock("expired", expiredLease, "expired-lease/secret", "", "writer", 1, 1)))
|
||||
manager.InsertBackupLock("expired", expiredLease, "expired-lease/secret", "", "writer", 1, 1)
|
||||
manager.RemoveBackupLockIfSeq("expired", 1, 2, "expired-lease/secret", expiredLease)
|
||||
require.Empty(t, manager.locks)
|
||||
require.Nil(t, manager.removed)
|
||||
}
|
||||
|
||||
func TestLockManager_FirstReplicationRacesWithRelease(t *testing.T) {
|
||||
for _, replicateFirst := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(replicateFirst), func(t *testing.T) {
|
||||
manager := NewLockManager()
|
||||
_, token, _, _, _, err := manager.Lock("key", time.Now().Add(time.Minute).UnixNano(), "", "owner")
|
||||
require.NoError(t, err)
|
||||
if replicateFirst {
|
||||
require.True(t, manager.markReplicated("key", token))
|
||||
}
|
||||
released, err := manager.Unlock("key", token)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, released)
|
||||
require.False(t, manager.markReplicated("key", token), "a released local lease cannot be sent later")
|
||||
require.Equal(t, replicateFirst, len(manager.removed) != 0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDLM_HandoffTracksPreviouslyLocalLease(t *testing.T) {
|
||||
dlm := NewDistributedLockManager("handoff:8888")
|
||||
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, 1)
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
_, token, _, _, err := dlm.LockWithTimeout("key", expires, "", "owner")
|
||||
require.NoError(t, err)
|
||||
locks := dlm.AllLocks()
|
||||
require.Len(t, locks, 1)
|
||||
require.NoError(t, handOff(t, dlm, "key", true, func(current *Lock) error {
|
||||
require.Equal(t, token, current.Token)
|
||||
return nil
|
||||
}))
|
||||
dlm.LockRing.SetSnapshot([]pb.ServerAddress{dlm.Host}, dlm.LockRing.Version()+1)
|
||||
_, err = dlm.Unlock("key", token)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, dlm.lockManager.removed)
|
||||
require.NoError(t, handOff(t, dlm, "key", true, func(*Lock) error {
|
||||
t.Fatal("released lease was handed off")
|
||||
return nil
|
||||
}))
|
||||
require.False(t, inserted(dlm.lockManager.InsertLock("key", expires, token, "", "owner", locks[0].Generation, locks[0].Seq)))
|
||||
}
|
||||
|
||||
func TestLockManager_LegacyReleaseMetadata(t *testing.T) {
|
||||
manager := NewLockManager()
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
manager.InsertBackupLock("key", expires, "legacy-token", "", "owner", 1, 1)
|
||||
require.True(t, manager.RemoveBackupLockIfSeq("key", 1, 2, "", 0))
|
||||
_, found := manager.GetLock("key")
|
||||
require.False(t, found)
|
||||
require.True(t, inserted(manager.InsertLock("key", expires, "new-lease/secret", "", "owner", 1, 1)))
|
||||
// An old primary could have released the previous generation-1 lease,
|
||||
// or a handed-off slash-format lease. Its identityless message cannot
|
||||
// distinguish those cases. Keep the valid lease until its expiry rather
|
||||
// than permitting a stale release to delete a different acquisition.
|
||||
require.False(t, manager.RemoveBackupLockIfSeq("key", 1, 2, "", 0))
|
||||
lock, found := manager.GetLock("key")
|
||||
require.True(t, found)
|
||||
require.Equal(t, "new-lease/secret", lock.Token)
|
||||
}
|
||||
|
||||
func TestDLM_TransferReplicatesEffectiveExpiry(t *testing.T) {
|
||||
for _, incomingTTL := range []time.Duration{30 * time.Second, time.Minute, 90 * time.Second} {
|
||||
t.Run(incomingTTL.String(), func(t *testing.T) {
|
||||
a, b := NewDistributedLockManager("expiry-a:8888"), NewDistributedLockManager("expiry-b:8888")
|
||||
hosts := []pb.ServerAddress{a.Host, b.Host}
|
||||
a.LockRing.SetSnapshot(hosts, 1)
|
||||
b.LockRing.SetSnapshot(hosts, 1)
|
||||
if primary, _ := a.LockRing.GetPrimaryAndBackup("key"); primary != a.Host {
|
||||
a, b = b, a
|
||||
}
|
||||
now := time.Now()
|
||||
storedExpiry := now.Add(time.Minute).UnixNano()
|
||||
incomingExpiry := now.Add(incomingTTL).UnixNano()
|
||||
require.True(t, inserted(a.lockManager.InsertLock("key", storedExpiry, "lease/old", "", "owner", 1, 1)))
|
||||
receive := captureLeaseMutations(t, a)
|
||||
a.InsertLock("key", incomingExpiry, "lease/new", "lease/old", "owner", 1, 2)
|
||||
mutation := receive()
|
||||
require.Equal(t, max(storedExpiry, incomingExpiry), mutation.expires)
|
||||
mutation.deliver(b)
|
||||
primary, found := a.GetLock("key")
|
||||
require.True(t, found)
|
||||
backup, found := b.GetLock("key")
|
||||
require.True(t, found)
|
||||
require.Equal(t, primary.ExpiredAtNs, backup.ExpiredAtNs)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package lock_manager_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
lm "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
func TestLockManager_ReleasedLockDoesNotResurrect(t *testing.T) {
|
||||
for _, releaseFirst := range []bool{false, true} {
|
||||
name := "insert_release_delayed_renewal"
|
||||
if releaseFirst {
|
||||
name = "release_before_insert"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
backup := lm.NewLockManager()
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
if !releaseFirst {
|
||||
backup.InsertBackupLock("key", expires, "lease/token", "", "owner", 1, 1)
|
||||
}
|
||||
if !backup.RemoveBackupLockIfSeq("key", 1, 3, "lease/token3", expires) {
|
||||
t.Fatal("release unexpectedly rejected")
|
||||
}
|
||||
backup.InsertBackupLock("key", expires, "lease/token2", "lease/token", "owner", 1, 2)
|
||||
if got, ok := backup.GetLock("key"); ok {
|
||||
t.Fatalf("released lock resurrected: owner=%s generation=%d seq=%d", got.Owner, got.Generation, got.Seq)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockManager_StaleTransferDoesNotResurrect(t *testing.T) {
|
||||
manager := lm.NewLockManager()
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
manager.InsertLock("key", expires, "token", "", "owner", 3, 1)
|
||||
if released, err := manager.Unlock("key", "token"); released == nil || err != nil {
|
||||
t.Fatalf("unlock: released=%v err=%v", released, err)
|
||||
}
|
||||
if _, accepted := manager.InsertLock("key", expires, "token", "", "owner", 3, 1); accepted {
|
||||
t.Fatal("completed release was undone by a stale transfer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockManager_OrderedReleaseKeepsNewerLease(t *testing.T) {
|
||||
backup := lm.NewLockManager()
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
backup.InsertBackupLock("key", expires, "lease/token", "", "owner", 1, 1)
|
||||
backup.RemoveBackupLockIfSeq("key", 1, 2, "lease/token", expires)
|
||||
if _, ok := backup.GetLock("key"); ok {
|
||||
t.Fatal("ordered release failed")
|
||||
}
|
||||
backup.InsertBackupLock("key", expires, "new", "", "new-owner", 2, 1)
|
||||
backup.RemoveBackupLockIfSeq("key", 1, 2, "lease/token", expires)
|
||||
got, ok := backup.GetLock("key")
|
||||
if !ok || got.Generation != 2 {
|
||||
t.Fatal("older delete removed a newer live record")
|
||||
}
|
||||
}
|
||||
|
||||
// Drive the real asynchronous replication callback and actual DLM acquire /
|
||||
// release APIs. The callback is a controllable reliable network: each captured
|
||||
// message is delivered exactly once, with no loss, duplication or fabrication.
|
||||
func TestDLM_AsyncReplicationReleaseFailover(t *testing.T) {
|
||||
for _, reordered := range []bool{false, true} {
|
||||
name := "ordered_control"
|
||||
if reordered {
|
||||
name = "reordered"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
hosts := []pb.ServerAddress{"filer-a:8888", "filer-b:8888"}
|
||||
a, b := lm.NewDistributedLockManager(hosts[0]), lm.NewDistributedLockManager(hosts[1])
|
||||
a.LockRing.SetSnapshot(append([]pb.ServerAddress(nil), hosts...), 1)
|
||||
b.LockRing.SetSnapshot(append([]pb.ServerAddress(nil), hosts...), 1)
|
||||
key := "replication-key"
|
||||
primary, _ := a.LockRing.GetPrimaryAndBackup(key)
|
||||
if primary != a.Host {
|
||||
a, b = b, a
|
||||
}
|
||||
type message struct {
|
||||
expires, generation, seq int64
|
||||
token, prev, owner string
|
||||
isUnlock bool
|
||||
}
|
||||
network := make(chan message, 4)
|
||||
a.ReplicateFn = func(_ pb.ServerAddress, _ string, expiry int64, token, prev, owner string, gen, seq int64, unlock bool) {
|
||||
network <- message{expiry, gen, seq, token, prev, owner, unlock}
|
||||
}
|
||||
receive := func() message {
|
||||
select {
|
||||
case m := <-network:
|
||||
return m
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("replication callback not invoked")
|
||||
return message{}
|
||||
}
|
||||
}
|
||||
deliver := func(m message) {
|
||||
if m.isUnlock {
|
||||
b.RemoveBackupLockIfSeq(key, m.generation, m.seq, m.token, m.expires)
|
||||
} else {
|
||||
b.InsertBackupLock(key, m.expires, m.token, m.prev, m.owner, m.generation, m.seq)
|
||||
}
|
||||
}
|
||||
expires := time.Now().Add(time.Minute).UnixNano()
|
||||
_, token, _, moved, err := a.LockWithTimeout(key, expires, "", "alice")
|
||||
if err != nil || moved != "" || token == "" {
|
||||
t.Fatalf("acquire: %v moved=%s", err, moved)
|
||||
}
|
||||
acquire := receive()
|
||||
if moved, err := a.Unlock(key, token); err != nil || moved != "" {
|
||||
t.Fatalf("unlock: %v moved=%s", err, moved)
|
||||
}
|
||||
release := receive()
|
||||
if reordered {
|
||||
deliver(release)
|
||||
deliver(acquire)
|
||||
} else {
|
||||
deliver(acquire)
|
||||
deliver(release)
|
||||
}
|
||||
// Remove the old primary only after both replication RPCs completed.
|
||||
b.LockRing.SetSnapshot([]pb.ServerAddress{b.Host}, 2)
|
||||
b.PromoteLock(key)
|
||||
_, newToken, _, moved, err := b.LockWithTimeout(key, expires, "", "bob")
|
||||
if err != nil || moved != "" || newToken == "" {
|
||||
t.Fatalf("completed release must allow new owner after failover: error=%v moved=%s token=%q", err, moved, newToken)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ const DefaultMasterMaintenanceScripts = `
|
||||
ec.encode -fullPercent=95 -quietFor=1h
|
||||
ec.rebuild -apply
|
||||
ec.balance -apply
|
||||
fs.log.purge -daysAgo=7
|
||||
volume.deleteEmpty -quietFor=24h -apply
|
||||
volume.balance -apply
|
||||
volume.fix.replication -apply
|
||||
|
||||
@@ -167,7 +167,7 @@ func init() {
|
||||
f.defaultLevelDbDirectory = cmdFiler.Flag.String("defaultStoreDir", ".", "if filer.toml is empty, use an embedded filer store in the directory")
|
||||
f.concurrentUploadLimitMB = cmdFiler.Flag.Int("concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
|
||||
f.concurrentFileUploadLimit = cmdFiler.Flag.Int("concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
|
||||
f.inflightUploadDataTimeout = cmdFiler.Flag.Duration("inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 429, 0 means no limit")
|
||||
f.inflightUploadDataTimeout = cmdFiler.Flag.Duration("inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 503 and Retry-After, 0 means no limit")
|
||||
f.debug = cmdFiler.Flag.Bool("debug", false, "serves runtime profiling data, e.g., http://localhost:<debug.port>/debug/pprof/goroutine?debug=2")
|
||||
f.debugPort = cmdFiler.Flag.Int("debug.port", 6060, "http port for debugging")
|
||||
f.localSocket = cmdFiler.Flag.String("localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
|
||||
@@ -537,7 +537,8 @@ func (fo *FilerOptions) startFiler() {
|
||||
glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err)
|
||||
}
|
||||
grpcTLSOption, grpcTLSReloadOption := security.LoadServerTLS(util.GetViper(), "grpc.filer")
|
||||
grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, fs.GrpcScopeServerOptions()...)
|
||||
grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, weed_server.FilerGrpcMetricsServerOptions()...)
|
||||
grpcOptions = append(grpcOptions, fs.GrpcScopeServerOptions()...)
|
||||
grpcS := pb.NewGrpcServer(grpcOptions...)
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcS, fs)
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
// snapshot below sets the start point; no checkpoint read needed
|
||||
glog.V(0).Infof("initialSnapshot requested — walking live tree before subscribing")
|
||||
} else {
|
||||
lastOffsetTsNs, err := getOffsetWithFallback(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
lastOffsetTsNs, err := getOffsetWithFallback(grpcDialOption, sourceFiler, security.FilerAdminToken, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read backup offset: %w", err)
|
||||
} else if lastOffsetTsNs > 0 {
|
||||
@@ -181,11 +181,17 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
*backupOption.proxyByFiler); err != nil {
|
||||
return resumeTsNs, fmt.Errorf("filersource initialization failed: %v", err)
|
||||
}
|
||||
filerSource.SetFilerTokenSource(security.FilerAdminToken)
|
||||
dataSink.SetSourceFiler(filerSource)
|
||||
if tokenSink, ok := dataSink.(interface {
|
||||
SetFilerTokenSource(security.FilerTokenSource)
|
||||
}); ok {
|
||||
tokenSink.SetFilerTokenSource(security.FilerAdminToken)
|
||||
}
|
||||
|
||||
if err := repl_util.InitializeSSEForReplication(filerSource); err != nil {
|
||||
return resumeTsNs, fmt.Errorf("SSE initialization failed: %v", err)
|
||||
}
|
||||
dataSink.SetSourceFiler(filerSource)
|
||||
if err := replication.CheckSinkDigest(filerSource.GrpcAddress(), filerSource.Digest, dataSink); err != nil {
|
||||
if replication.IsDigestMismatch(err) {
|
||||
glog.Exitf("%v", err)
|
||||
@@ -220,7 +226,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
// The walk can take hours on large trees; retry the tiny KV write a
|
||||
// handful of times before giving up so a flaky filer KV doesn't force
|
||||
// the whole walk to repeat on the next retry loop iteration.
|
||||
if err := persistSnapshotOffset(grpcDialOption, sourceFiler, sinkId, snapshotTsNs); err != nil {
|
||||
if err := persistSnapshotOffset(grpcDialOption, sourceFiler, sinkId, snapshotTsNs, security.FilerAdminToken); err != nil {
|
||||
glog.Errorf("initialSnapshot: FAILED to persist offset %d for sinkId %d after retries: %v — the next retry will redo the full walk", snapshotTsNs, sinkId, err)
|
||||
return 0, fmt.Errorf("persist initial snapshot offset: %w", err)
|
||||
}
|
||||
@@ -300,7 +306,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
defer ticker.Stop()
|
||||
persist := func() {
|
||||
if ts := resumeTsNsFor(processor); ts != lastPersistedTsNs.Load() {
|
||||
if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, ts); err == nil {
|
||||
if err := setOffset(grpcDialOption, sourceFiler, security.FilerAdminToken, BackupKeyPrefix, sinkId, ts); err == nil {
|
||||
lastPersistedTsNs.Store(ts)
|
||||
} else {
|
||||
glog.Warningf("persist backup offset: %v", err)
|
||||
@@ -366,6 +372,7 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
StartTsNs: startFrom.UnixNano(),
|
||||
StopTsNs: 0,
|
||||
EventErrorType: eventErrorType,
|
||||
FilerTokenSource: security.FilerAdminToken,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
@@ -487,12 +494,16 @@ func eventSupersessionProbe(resp *filer_pb.SubscribeMetadataResponse) (util.Full
|
||||
// errors. Losing this write forces a full re-walk on the next retry loop
|
||||
// iteration, so a small retry budget here is far cheaper than paying the
|
||||
// walk cost again on a large tree.
|
||||
func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64) error {
|
||||
func persistSnapshotOffset(grpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sinkId int32, tsNs int64, tokenSource ...security.FilerTokenSource) error {
|
||||
const attempts = 4
|
||||
backoff := 500 * time.Millisecond
|
||||
var source security.FilerTokenSource
|
||||
if len(tokenSource) > 0 {
|
||||
source = tokenSource[0]
|
||||
}
|
||||
var lastErr error
|
||||
for i := 1; i <= attempts; i++ {
|
||||
if err := setOffset(grpcDialOption, sourceFiler, BackupKeyPrefix, sinkId, tsNs); err == nil {
|
||||
if err := setOffset(grpcDialOption, sourceFiler, source, BackupKeyPrefix, sinkId, tsNs); err == nil {
|
||||
return nil
|
||||
} else {
|
||||
lastErr = err
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type backupAuthKVFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
key security.SigningKey
|
||||
mu sync.Mutex
|
||||
kv map[string][]byte
|
||||
}
|
||||
|
||||
func (s *backupAuthKVFiler) authenticate(ctx context.Context) error {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
values := md.Get("authorization")
|
||||
if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) ||
|
||||
!security.IsFilerAdminToken(s.key, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))) {
|
||||
return status.Error(codes.Unauthenticated, "missing or invalid filer authorization")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *backupAuthKVFiler) KvGet(_ context.Context, request *filer_pb.KvGetRequest) (*filer_pb.KvGetResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return &filer_pb.KvGetResponse{Value: append([]byte(nil), s.kv[string(request.Key)]...)}, nil
|
||||
}
|
||||
|
||||
func (s *backupAuthKVFiler) KvPut(_ context.Context, request *filer_pb.KvPutRequest) (*filer_pb.KvPutResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.kv[string(request.Key)] = append([]byte(nil), request.Value...)
|
||||
return &filer_pb.KvPutResponse{}, nil
|
||||
}
|
||||
|
||||
func backupAuthKey(t *testing.T) security.SigningKey {
|
||||
t.Helper()
|
||||
buf := make([]byte, 32)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return security.SigningKey(hex.EncodeToString(buf))
|
||||
}
|
||||
|
||||
func startBackupAuthKVFiler(t *testing.T, filer *backupAuthKVFiler) (pb.ServerAddress, grpc.DialOption) {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := grpc.NewServer(grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
if err := filer.authenticate(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}))
|
||||
filer_pb.RegisterSeaweedFilerServer(server, filer)
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() {
|
||||
server.Stop()
|
||||
_ = listener.Close()
|
||||
})
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
return pb.NewServerAddressWithGrpcPort("127.0.0.1:8888", port), grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
}
|
||||
|
||||
func TestBackupOffsetUsesProtectedPerCallOperation(t *testing.T) {
|
||||
key := backupAuthKey(t)
|
||||
filer := &backupAuthKVFiler{key: key, kv: make(map[string][]byte)}
|
||||
address, dial := startBackupAuthKVFiler(t, filer)
|
||||
tokenSource := security.FilerTokenSource(func(context.Context) (security.EncodedJwt, error) {
|
||||
return security.GenJwtForFilerAdmin(key, 60), nil
|
||||
})
|
||||
prefix := BackupKeyPrefix
|
||||
const signature = int32(43)
|
||||
if err := setOffset(dial, address, tokenSource, prefix, signature, 1234); err != nil {
|
||||
t.Fatalf("protected backup offset write: %v", err)
|
||||
}
|
||||
got, err := getOffset(dial, address, tokenSource, prefix, signature)
|
||||
if err != nil {
|
||||
t.Fatalf("protected backup offset read: %v", err)
|
||||
}
|
||||
if got != 1234 {
|
||||
t.Fatalf("backup offset = %d, want 1234", got)
|
||||
}
|
||||
|
||||
// Keep this assertion at the stored-value boundary: it proves the real KV
|
||||
// calls completed through the protected adapter, while avoiding token output.
|
||||
keyBytes := []byte(prefix + "____")
|
||||
util.Uint32toBytes(keyBytes[len(prefix):], uint32(signature))
|
||||
filer.mu.Lock()
|
||||
defer filer.mu.Unlock()
|
||||
if _, ok := filer.kv[string(keyBytes)]; !ok {
|
||||
t.Fatal("protected backup offset was not persisted")
|
||||
}
|
||||
}
|
||||
@@ -84,28 +84,28 @@ func TestBackupOffset_HistoricalFallbackThenIndependence(t *testing.T) {
|
||||
sinkId, legacySinkId := backupCheckpointIds("/", s, false)
|
||||
|
||||
// pre-upgrade state: only the shared historical checkpoint exists
|
||||
if err := setOffset(dial, filerAddr, BackupKeyPrefix, legacySinkId, 111); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 111); err != nil {
|
||||
t.Fatalf("seed historical offset: %v", err)
|
||||
}
|
||||
got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
if err != nil || got != 111 {
|
||||
t.Fatalf("fallback read = (%d, %v), want (111, nil)", got, err)
|
||||
}
|
||||
|
||||
// the backup checkpoints under its own key and prefers it from then on
|
||||
if err := setOffset(dial, filerAddr, BackupKeyPrefix, sinkId, 222); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, sinkId, 222); err != nil {
|
||||
t.Fatalf("write destination-scoped offset: %v", err)
|
||||
}
|
||||
got, err = getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
got, err = getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
if err != nil || got != 222 {
|
||||
t.Fatalf("destination-scoped read = (%d, %v), want (222, nil)", got, err)
|
||||
}
|
||||
|
||||
// another backup advancing the historical key no longer moves this one
|
||||
if err := setOffset(dial, filerAddr, BackupKeyPrefix, legacySinkId, 333); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, legacySinkId, 333); err != nil {
|
||||
t.Fatalf("advance historical offset: %v", err)
|
||||
}
|
||||
got, err = getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
got, err = getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, sinkId, BackupKeyPrefix, legacySinkId)
|
||||
if err != nil || got != 222 {
|
||||
t.Fatalf("read after historical advance = (%d, %v), want (222, nil)", got, err)
|
||||
}
|
||||
@@ -120,17 +120,17 @@ func TestBackupOffset_DistinctDestinationsDoNotShare(t *testing.T) {
|
||||
idA, legacyA := backupCheckpointIds("/", &stubSink{name: "s3", dir: "/", destination: "s3.us-west-004.backblazeb2.com|seaweed-backup-a|/"}, false)
|
||||
idB, legacyB := backupCheckpointIds("/", &stubSink{name: "s3", dir: "/", destination: "s3.us-east-005.backblazeb2.com|seaweed-backup-b|/"}, false)
|
||||
|
||||
if err := setOffset(dial, filerAddr, BackupKeyPrefix, idA, 1000); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idA, 1000); err != nil {
|
||||
t.Fatalf("write A: %v", err)
|
||||
}
|
||||
if err := setOffset(dial, filerAddr, BackupKeyPrefix, idB, 2000); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, BackupKeyPrefix, idB, 2000); err != nil {
|
||||
t.Fatalf("write B: %v", err)
|
||||
}
|
||||
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, idA, BackupKeyPrefix, legacyA); err != nil || got != 1000 {
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, idA, BackupKeyPrefix, legacyA); err != nil || got != 1000 {
|
||||
t.Fatalf("A reads (%d, %v), want (1000, nil)", got, err)
|
||||
}
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, BackupKeyPrefix, idB, BackupKeyPrefix, legacyB); err != nil || got != 2000 {
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, nil, BackupKeyPrefix, idB, BackupKeyPrefix, legacyB); err != nil || got != 2000 {
|
||||
t.Fatalf("B reads (%d, %v), want (2000, nil)", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ func runFilerCat(cmd *Command, args []string) bool {
|
||||
writer = f
|
||||
}
|
||||
|
||||
pb.WithFilerClient(false, util.RandomInt32(), filerCat.filerAddress, filerCat.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err = pb.WithGrpcFilerClient(false, util.RandomInt32(), filerCat.filerAddress, filerCat.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
request := &filer_pb.LookupDirectoryEntryRequest{
|
||||
Name: name,
|
||||
@@ -119,6 +119,10 @@ func runFilerCat(cmd *Command, args []string) bool {
|
||||
return filer.StreamContent(&filerCat, writer, respLookupEntry.Entry.GetChunks(), 0, int64(filer.FileSize(respLookupEntry.Entry)))
|
||||
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "read %s: %v\n", filerSource, err)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -186,7 +186,7 @@ func runCopy(cmd *Command, args []string) bool {
|
||||
}
|
||||
|
||||
func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb.ServerAddress) (masters []string, collection, replication string, dirBuckets string, maxMB uint32, cipher bool, digest string, err error) {
|
||||
err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("get filer %s configuration: %v", filerGrpcAddress, err)
|
||||
@@ -318,7 +318,7 @@ func (worker *FileCopyWorker) checkExistingFileFirst(task FileCopyTask, f *os.Fi
|
||||
return
|
||||
}
|
||||
|
||||
err = pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err = pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
request := &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: task.destinationUrlPath,
|
||||
@@ -387,7 +387,7 @@ func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) err
|
||||
chunks = append(chunks, uploadResult.ToPbFileChunk(finalFileId, 0, time.Now().UnixNano()))
|
||||
}
|
||||
|
||||
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
request := &filer_pb.CreateEntryRequest{
|
||||
Directory: task.destinationUrlPath,
|
||||
Entry: &filer_pb.Entry{
|
||||
@@ -524,7 +524,7 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File,
|
||||
return fmt.Errorf("create manifest: %w", manifestErr)
|
||||
}
|
||||
|
||||
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
request := &filer_pb.CreateEntryRequest{
|
||||
Directory: task.destinationUrlPath,
|
||||
Entry: &filer_pb.Entry{
|
||||
@@ -614,12 +614,9 @@ func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, off
|
||||
var _ = filer_pb.FilerClient(&FileCopyWorker{})
|
||||
|
||||
func (worker *FileCopyWorker) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) (err error) {
|
||||
|
||||
filerGrpcAddress := worker.filerAddress.ToGrpcAddress()
|
||||
err = pb.WithGrpcClient(context.Background(), streamingMode, worker.signature, func(grpcConnection *grpc.ClientConn) error {
|
||||
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
|
||||
err = pb.WithGrpcFilerClient(streamingMode, worker.signature, worker.filerAddress, worker.options.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return fn(client)
|
||||
}, filerGrpcAddress, false, worker.options.grpcDialOption)
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -388,6 +388,7 @@ func (metaBackup *FilerMetaBackupOptions) streamMetadataBackup(startTime time.Ti
|
||||
StartTsNs: startTime.UnixNano(),
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
FilerTokenSource: security.FilerAdminToken,
|
||||
}
|
||||
|
||||
return pb.FollowMetadata(pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
@@ -422,7 +423,7 @@ var _ = filer_pb.FilerClient(&FilerMetaBackupOptions{})
|
||||
|
||||
func (metaBackup *FilerMetaBackupOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
|
||||
return pb.WithFilerClient(streamingMode, metaBackup.clientId, pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return pb.WithGrpcFilerClient(streamingMode, metaBackup.clientId, pb.ServerAddress(*metaBackup.filerAddress), metaBackup.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return fn(client)
|
||||
})
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ type scanFilerClient struct {
|
||||
}
|
||||
|
||||
func (c *scanFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return pb.WithFilerClient(streamingMode, c.signature, c.address, c.grpcDialOption, fn)
|
||||
return pb.WithGrpcFilerClient(streamingMode, c.signature, c.address, c.grpcDialOption, security.FilerAdminToken, fn)
|
||||
}
|
||||
|
||||
func (c *scanFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url }
|
||||
@@ -298,14 +298,15 @@ func runFilerMetaScan(cmd *Command, args []string) bool {
|
||||
|
||||
scan := func(directRead bool) error {
|
||||
option := &pb.MetadataFollowOption{
|
||||
ClientName: "scan",
|
||||
ClientId: util.RandomInt32(),
|
||||
ClientEpoch: 0,
|
||||
SelfSignature: 0,
|
||||
PathPrefix: *scanPathPrefix,
|
||||
StartTsNs: startTs.UnixNano(),
|
||||
StopTsNs: stopTsNs,
|
||||
EventErrorType: pb.TrivialOnError,
|
||||
ClientName: "scan",
|
||||
ClientId: util.RandomInt32(),
|
||||
ClientEpoch: 0,
|
||||
SelfSignature: 0,
|
||||
FilerTokenSource: security.FilerAdminToken,
|
||||
PathPrefix: *scanPathPrefix,
|
||||
StartTsNs: startTs.UnixNano(),
|
||||
StopTsNs: stopTsNs,
|
||||
EventErrorType: pb.TrivialOnError,
|
||||
}
|
||||
if directRead {
|
||||
// The server hands out log chunk fids and this reads them straight
|
||||
|
||||
@@ -118,6 +118,7 @@ func runFilerMetaTail(cmd *Command, args []string) bool {
|
||||
StartTsNs: time.Now().Add(-*tailStart).UnixNano(),
|
||||
StopTsNs: untilTsNs,
|
||||
EventErrorType: pb.TrivialOnError,
|
||||
FilerTokenSource: security.FilerAdminToken,
|
||||
}
|
||||
|
||||
tailErr := pb.FollowMetadata(pb.ServerAddress(*tailFiler), grpcDialOption, metadataFollowOption, func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
|
||||
@@ -26,18 +26,19 @@ type RemoteGatewayOptions struct {
|
||||
include *string
|
||||
exclude *string
|
||||
|
||||
mappings *remote_pb.RemoteStorageMapping
|
||||
remoteConfs map[string]*remote_pb.RemoteConf
|
||||
bucketsDir string
|
||||
clientId int32
|
||||
clientEpoch int32
|
||||
resumeTsNs int64
|
||||
mappings *remote_pb.RemoteStorageMapping
|
||||
remoteConfs map[string]*remote_pb.RemoteConf
|
||||
bucketsDir string
|
||||
clientId int32
|
||||
clientEpoch int32
|
||||
resumeTsNs int64
|
||||
filerTokenSource security.FilerTokenSource
|
||||
}
|
||||
|
||||
var _ = filer_pb.FilerClient(&RemoteGatewayOptions{})
|
||||
|
||||
func (option *RemoteGatewayOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return pb.WithFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return pb.WithGrpcFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, option.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return fn(client)
|
||||
})
|
||||
}
|
||||
@@ -88,6 +89,7 @@ func runFilerRemoteGateway(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
remoteGatewayOptions.grpcDialOption = grpcDialOption
|
||||
remoteGatewayOptions.filerTokenSource = security.FilerAdminToken
|
||||
|
||||
filerAddress := pb.ServerAddress(*remoteGatewayOptions.filerAddress)
|
||||
|
||||
@@ -98,6 +100,7 @@ func runFilerRemoteGateway(cmd *Command, args []string) bool {
|
||||
"/", // does not matter
|
||||
*remoteGatewayOptions.readChunkFromFiler,
|
||||
)
|
||||
filerSource.SetFilerTokenSource(remoteGatewayOptions.filerTokenSource)
|
||||
|
||||
remoteGatewayOptions.bucketsDir = "/buckets"
|
||||
// check buckets again
|
||||
|
||||
@@ -33,7 +33,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
return err
|
||||
}
|
||||
|
||||
lastOffsetTs, err := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, *option.timeAgo, option.resumeTsNs)
|
||||
lastOffsetTs, err := collectLastSyncOffset(option, option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, *option.timeAgo, option.resumeTsNs, option.filerTokenSource)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -51,7 +51,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
now := time.Now().UnixNano()
|
||||
glog.V(0).Infof("remote sync %s progressed to %v %0.2f/sec", *option.filerAddress, time.Unix(0, offsetTsNs), float64(counter)/(float64(now-lastLogTsNs)/1e9))
|
||||
lastLogTsNs = now
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, resumeTsNsFor(processor))
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, resumeTsNsFor(processor), option.filerTokenSource)
|
||||
})
|
||||
|
||||
option.clientEpoch++
|
||||
@@ -67,6 +67,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
StartTsNs: lastOffsetTs.UnixNano(),
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
FilerTokenSource: option.filerTokenSource,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
@@ -74,7 +75,7 @@ func (option *RemoteGatewayOptions) followBucketUpdatesAndUploadToRemote(filerSo
|
||||
}
|
||||
|
||||
err = pb.FollowMetadata(pb.ServerAddress(*option.filerAddress), option.grpcDialOption, metadataFollowOption, processEventFnWithOffset)
|
||||
option.resumeTsNs = saveResumeOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, processor)
|
||||
option.resumeTsNs = saveResumeOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.bucketsDir, processor, option.filerTokenSource)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -709,7 +710,7 @@ func extractBucketPath(bucketsDir, dir string) (util.FullPath, bool) {
|
||||
|
||||
func (option *RemoteGatewayOptions) collectRemoteStorageConf() (err error) {
|
||||
|
||||
if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress)); err != nil {
|
||||
if mappings, err := filer.ReadMountMappings(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), option.filerTokenSource); err != nil {
|
||||
if err == filer_pb.ErrNotFound {
|
||||
return fmt.Errorf("remote storage is not configured in filer server")
|
||||
}
|
||||
|
||||
@@ -28,14 +28,15 @@ type RemoteSyncOptions struct {
|
||||
resumeTsNs int64
|
||||
// what resumeTsNs was earned under: the directory's remote location, and
|
||||
// the offset stored when it was kept (resumeFor)
|
||||
resumeLoc *remote_pb.RemoteStorageLocation
|
||||
resumeStoredNs int64
|
||||
resumeLoc *remote_pb.RemoteStorageLocation
|
||||
resumeStoredNs int64
|
||||
filerTokenSource security.FilerTokenSource
|
||||
}
|
||||
|
||||
var _ = filer_pb.FilerClient(&RemoteSyncOptions{})
|
||||
|
||||
func (option *RemoteSyncOptions) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return pb.WithFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return pb.WithGrpcFilerClient(streamingMode, option.clientId, pb.ServerAddress(*option.filerAddress), option.grpcDialOption, option.filerTokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return fn(client)
|
||||
})
|
||||
}
|
||||
@@ -98,6 +99,7 @@ func runFilerRemoteSynchronize(cmd *Command, args []string) bool {
|
||||
util.LoadSecurityConfiguration()
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
remoteSyncOptions.grpcDialOption = grpcDialOption
|
||||
remoteSyncOptions.filerTokenSource = security.FilerAdminToken
|
||||
|
||||
dir := *remoteSyncOptions.dir
|
||||
filerAddress := pb.ServerAddress(*remoteSyncOptions.filerAddress)
|
||||
@@ -109,6 +111,7 @@ func runFilerRemoteSynchronize(cmd *Command, args []string) bool {
|
||||
"/", // does not matter
|
||||
*remoteSyncOptions.readChunkFromFiler,
|
||||
)
|
||||
filerSource.SetFilerTokenSource(remoteSyncOptions.filerTokenSource)
|
||||
|
||||
if *remoteSyncOptions.allMounts {
|
||||
if dir != "" {
|
||||
|
||||
@@ -110,7 +110,7 @@ func newMountSupervisor(option *RemoteSyncOptions, filerSource *source.FilerSour
|
||||
return followMountedDir(o, filerSource, dir, watch)
|
||||
}
|
||||
m.readOffset = func(dir string) (int64, error) {
|
||||
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), dir)
|
||||
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), dir, option.filerTokenSource)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
|
||||
"github.com/seaweedfs/seaweedfs/weed/replication/source"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
|
||||
"google.golang.org/grpc"
|
||||
@@ -75,23 +76,23 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource
|
||||
// remote.unmount completing in between (its mapping write, its purge,
|
||||
// then its offset) would start a follow that saw the directory mounted
|
||||
// past the unmount's table, into its purge.
|
||||
storedOffsetNs, err := remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir)
|
||||
storedOffsetNs, err := remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read sync offset of %s: %w", mountedDir, err)
|
||||
}
|
||||
|
||||
// read filer remote storage mount mappings
|
||||
_, mountKey, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir)
|
||||
_, mountKey, remoteStorageMountLocation, remoteStorage, detectErr := filer.DetectMountInfo(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource)
|
||||
if err := option.resumeFor(mountedDir, mountKey, remoteStorageMountLocation, detectErr, storedOffsetNs); err != nil {
|
||||
return err
|
||||
}
|
||||
dirLoc := dirRemoteLocation(mountKey, mountedDir, remoteStorageMountLocation)
|
||||
guard := &offsetGuard{dir: mountedDir, last: storedOffsetNs,
|
||||
read: func() (int64, error) {
|
||||
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir)
|
||||
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, option.filerTokenSource)
|
||||
},
|
||||
write: func(ts int64) error {
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, ts)
|
||||
return remote_storage.SetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountedDir, ts, option.filerTokenSource)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -105,7 +106,7 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource
|
||||
return err
|
||||
}
|
||||
lastOffsetTs, err = startAfterMountOffset(lastOffsetTs, mountKey, mountedDir, *option.timeAgo, option.resumeTsNs, func() (int64, error) {
|
||||
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountKey)
|
||||
return remote_storage.GetSyncOffset(option.grpcDialOption, pb.ServerAddress(*option.filerAddress), mountKey, option.filerTokenSource)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -164,6 +165,7 @@ func followMountedDir(option *RemoteSyncOptions, filerSource *source.FilerSource
|
||||
StartTsNs: lastOffsetTs.UnixNano(),
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
FilerTokenSource: option.filerTokenSource,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
@@ -233,9 +235,9 @@ func startAfterMountOffset(start time.Time, mountKey, dir string, timeAgo time.D
|
||||
// recomputes -timeAgo from now, so a failure before the first checkpoint
|
||||
// would otherwise start the retry after the event it failed on. The offset is
|
||||
// returned for the retry in this process, which must not depend on the write.
|
||||
func saveResumeOffset(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string, processor *MetadataProcessor) int64 {
|
||||
func saveResumeOffset(grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, dir string, processor *MetadataProcessor, tokenSource ...security.FilerTokenSource) int64 {
|
||||
return saveResumeOffsetWith(func(ts int64) error {
|
||||
return remote_storage.SetSyncOffset(grpcDialOption, filerAddress, dir, ts)
|
||||
return remote_storage.SetSyncOffset(grpcDialOption, filerAddress, dir, ts, tokenSource...)
|
||||
}, dir, processor)
|
||||
}
|
||||
|
||||
@@ -1490,7 +1492,7 @@ func retriedWriteFile(client remote_storage.RemoteStorageClient, filerSource fil
|
||||
return
|
||||
}
|
||||
|
||||
func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, mountedDir string, timeAgo time.Duration, resumeTsNs int64) (time.Time, error) {
|
||||
func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc.DialOption, filerAddress pb.ServerAddress, mountedDir string, timeAgo time.Duration, resumeTsNs int64, tokenSource ...security.FilerTokenSource) (time.Time, error) {
|
||||
if resumeTsNs > 0 {
|
||||
// the previous attempt pinned where it stopped, which can sit behind
|
||||
// both the saved offset and a recomputed -timeAgo window
|
||||
@@ -1504,7 +1506,9 @@ func collectLastSyncOffset(filerClient filer_pb.FilerClient, grpcDialOption grpc
|
||||
entry, _, _, err := filer_pb.GetEntry(ctx, filerClient, util.FullPath(mountedDir))
|
||||
return entry, err
|
||||
},
|
||||
func() (int64, error) { return remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir) })
|
||||
func() (int64, error) {
|
||||
return remote_storage.GetSyncOffset(grpcDialOption, filerAddress, mountedDir, tokenSource...)
|
||||
})
|
||||
}
|
||||
|
||||
// collectLastSyncOffsetFrom is collectLastSyncOffset with the saved offset
|
||||
|
||||
+31
-19
@@ -78,6 +78,7 @@ type syncState struct {
|
||||
sourcePath string
|
||||
targetPath string
|
||||
sourceFilerSignature int32
|
||||
tokenSource security.FilerTokenSource
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -177,6 +178,8 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
// per-cluster HTTPS clients for volume server connections
|
||||
var httpClientA, httpClientB *util_http_client.HTTPClient
|
||||
var jwtForFilerA, jwtForFilerB security.FilerJwtProvider
|
||||
tokenSourceA := security.FilerAdminTokenFromFile(*syncOptions.aSecurity)
|
||||
tokenSourceB := security.FilerAdminTokenFromFile(*syncOptions.bSecurity)
|
||||
if *syncOptions.aSecurity != "" {
|
||||
var err error
|
||||
if httpClientA, err = security.LoadHTTPClientFromFile(*syncOptions.aSecurity); err != nil {
|
||||
@@ -205,13 +208,13 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
go statsCollect.StartMetricsServer(*syncOptions.metricsHttpIp, *syncOptions.metricsHttpPort)
|
||||
|
||||
// read a filer signature
|
||||
aFilerSignature, aFilerDigest, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA)
|
||||
aFilerSignature, aFilerDigest, aFilerErr := replication.ReadFilerSignature(grpcDialOptionA, filerA, tokenSourceA)
|
||||
if aFilerErr != nil {
|
||||
glog.Errorf("get filer 'a' signature %d error from %s to %s: %v", aFilerSignature, *syncOptions.filerA, *syncOptions.filerB, aFilerErr)
|
||||
return true
|
||||
}
|
||||
// read b filer signature
|
||||
bFilerSignature, bFilerDigest, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB)
|
||||
bFilerSignature, bFilerDigest, bFilerErr := replication.ReadFilerSignature(grpcDialOptionB, filerB, tokenSourceB)
|
||||
if bFilerErr != nil {
|
||||
glog.Errorf("get filer 'b' signature %d error from %s to %s: %v", bFilerSignature, *syncOptions.filerA, *syncOptions.filerB, bFilerErr)
|
||||
return true
|
||||
@@ -230,7 +233,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
if offsetTsNs == 0 {
|
||||
return
|
||||
}
|
||||
if err := setOffset(state.grpcDialOption, state.targetFiler, getSignaturePrefixByPath(state.sourcePath, state.targetPath), state.sourceFilerSignature, offsetTsNs); err != nil {
|
||||
if err := setOffset(state.grpcDialOption, state.targetFiler, state.tokenSource, getSignaturePrefixByPath(state.sourcePath, state.targetPath), state.sourceFilerSignature, offsetTsNs); err != nil {
|
||||
glog.Errorf("failed to save checkpoint for %s on shutdown: %v", name, err)
|
||||
} else {
|
||||
glog.V(0).Infof("saved checkpoint for %s on shutdown: %v", name, time.Unix(0, offsetTsNs))
|
||||
@@ -244,7 +247,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
go func() {
|
||||
// a->b
|
||||
// set synchronization start timestamp to offset
|
||||
initOffsetError := initOffsetFromTsMs(grpcDialOptionB, filerB, aFilerSignature, *syncOptions.aFromTsMs, getSignaturePrefixByPath(*syncOptions.aPath, *syncOptions.bPath))
|
||||
initOffsetError := initOffsetFromTsMs(grpcDialOptionB, filerB, tokenSourceB, aFilerSignature, *syncOptions.aFromTsMs, getSignaturePrefixByPath(*syncOptions.aPath, *syncOptions.bPath))
|
||||
if initOffsetError != nil {
|
||||
glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.aFromTsMs, *syncOptions.filerA, *syncOptions.filerB, initOffsetError)
|
||||
os.Exit(2)
|
||||
@@ -277,7 +280,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
httpClientA,
|
||||
httpClientB,
|
||||
jwtForFilerA,
|
||||
jwtForFilerB)
|
||||
jwtForFilerB,
|
||||
tokenSourceA,
|
||||
tokenSourceB)
|
||||
if err != nil {
|
||||
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerA, *syncOptions.filerB, err)
|
||||
time.Sleep(1747 * time.Millisecond)
|
||||
@@ -288,7 +293,7 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
if !*syncOptions.isActivePassive {
|
||||
// b->a
|
||||
// set synchronization start timestamp to offset
|
||||
initOffsetError := initOffsetFromTsMs(grpcDialOptionA, filerA, bFilerSignature, *syncOptions.bFromTsMs, getSignaturePrefixByPath(*syncOptions.bPath, *syncOptions.aPath))
|
||||
initOffsetError := initOffsetFromTsMs(grpcDialOptionA, filerA, tokenSourceA, bFilerSignature, *syncOptions.bFromTsMs, getSignaturePrefixByPath(*syncOptions.bPath, *syncOptions.aPath))
|
||||
if initOffsetError != nil {
|
||||
glog.Errorf("init offset from timestamp %d error from %s to %s: %v", *syncOptions.bFromTsMs, *syncOptions.filerB, *syncOptions.filerA, initOffsetError)
|
||||
os.Exit(2)
|
||||
@@ -322,7 +327,9 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
httpClientB,
|
||||
httpClientA,
|
||||
jwtForFilerB,
|
||||
jwtForFilerA)
|
||||
jwtForFilerA,
|
||||
tokenSourceB,
|
||||
tokenSourceA)
|
||||
if err != nil {
|
||||
glog.Errorf("sync from %s to %s: %v", *syncOptions.filerB, *syncOptions.filerA, err)
|
||||
time.Sleep(2147 * time.Millisecond)
|
||||
@@ -335,14 +342,14 @@ func runFilerSynchronize(cmd *Command, args []string) bool {
|
||||
}
|
||||
|
||||
// initOffsetFromTsMs Initialize offset
|
||||
func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, sourceFilerSignature int32, fromTsMs int64, signaturePrefix string) error {
|
||||
func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, tokenSource security.FilerTokenSource, sourceFilerSignature int32, fromTsMs int64, signaturePrefix string) error {
|
||||
if fromTsMs <= 0 {
|
||||
return nil
|
||||
}
|
||||
// convert to nanosecond
|
||||
fromTsNs := fromTsMs * 1000_000
|
||||
// If not successful, exit the program.
|
||||
setOffsetErr := setOffset(grpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, fromTsNs)
|
||||
setOffsetErr := setOffset(grpcDialOption, targetFiler, tokenSource, signaturePrefix, sourceFilerSignature, fromTsNs)
|
||||
if setOffsetErr != nil {
|
||||
return setOffsetErr
|
||||
}
|
||||
@@ -353,14 +360,15 @@ func initOffsetFromTsMs(grpcDialOption grpc.DialOption, targetFiler pb.ServerAdd
|
||||
func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourcePath string, sourceExcludePaths []string, sourceReadChunkFromFiler bool, targetGrpcDialOption grpc.DialOption, targetFiler pb.ServerAddress, targetPath string,
|
||||
replicationStr, collection string, ttlSec int, sinkWriteChunkByFiler bool, diskType string, debug bool, concurrency int, chunkConcurrency int, doDeleteFiles bool, sourceFilerSignature int32, targetFilerSignature int32, statePtr *atomic.Pointer[syncState],
|
||||
sourceHttpClient *util_http_client.HTTPClient, sinkHttpClient *util_http_client.HTTPClient,
|
||||
sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider) error {
|
||||
sourceJwtProvider security.FilerJwtProvider, sinkJwtProvider security.FilerJwtProvider,
|
||||
sourceTokenSource security.FilerTokenSource, sinkTokenSource security.FilerTokenSource) error {
|
||||
|
||||
// if first time, start from now
|
||||
// if has previously synced, resume from that point of time
|
||||
// the historical key ignored the target path; falling back to it lets a
|
||||
// sync that predates target-scoped keys survive the upgrade
|
||||
signaturePrefix := getSignaturePrefixByPath(sourcePath, targetPath)
|
||||
sourceFilerOffsetTsNs, err := getOffsetWithFallback(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, getSignaturePrefixByPath(sourcePath, "/"), sourceFilerSignature)
|
||||
sourceFilerOffsetTsNs, err := getOffsetWithFallback(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, getSignaturePrefixByPath(sourcePath, "/"), sourceFilerSignature)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -377,6 +385,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
if sourceJwtProvider != nil {
|
||||
filerSource.SetFilerJwtProvider(sourceJwtProvider)
|
||||
}
|
||||
filerSource.SetFilerTokenSource(sourceTokenSource)
|
||||
filerSink := &filersink.FilerSink{}
|
||||
filerSink.DoInitialize(targetFiler.ToHttpAddress(), targetFiler.ToGrpcAddress(), targetPath, replicationStr, collection, ttlSec, diskType, targetGrpcDialOption, sinkWriteChunkByFiler)
|
||||
filerSink.SetChunkConcurrency(chunkConcurrency)
|
||||
@@ -386,6 +395,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
if sinkJwtProvider != nil {
|
||||
filerSink.SetFilerJwtProvider(sinkJwtProvider)
|
||||
}
|
||||
filerSink.SetFilerTokenSource(sinkTokenSource)
|
||||
filerSink.SetSourceFiler(filerSource)
|
||||
|
||||
persistEventFn := genProcessFunction(sourcePath, targetPath, sourceExcludePaths, nil, nil, nil, filerSink, doDeleteFiles, debug)
|
||||
@@ -418,6 +428,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
sourcePath: sourcePath,
|
||||
targetPath: targetPath,
|
||||
sourceFilerSignature: sourceFilerSignature,
|
||||
tokenSource: sinkTokenSource,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -479,7 +490,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
lastProgressedTsNs = offsetTsNs
|
||||
// collect synchronous offset
|
||||
statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(offsetTsNs))
|
||||
return setOffset(targetGrpcDialOption, targetFiler, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor))
|
||||
return setOffset(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor))
|
||||
})
|
||||
|
||||
prefix := sourcePath
|
||||
@@ -499,6 +510,7 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi
|
||||
StopTsNs: 0,
|
||||
EventErrorType: pb.RetryForeverOnError,
|
||||
FilerJwtProvider: sourceJwtProvider,
|
||||
FilerTokenSource: sourceTokenSource,
|
||||
GetResumeTsNs: func() int64 {
|
||||
return resumeTsNsFor(processor)
|
||||
},
|
||||
@@ -540,9 +552,9 @@ func getSignaturePrefixByPath(sourcePath, targetPath string) string {
|
||||
return prefix
|
||||
}
|
||||
|
||||
func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) {
|
||||
func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32) (lastOffsetTsNs int64, readErr error) {
|
||||
|
||||
readErr = pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
readErr = pb.WithGrpcFilerClient(false, signature, filer, grpcDialOption, tokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
syncKey := []byte(signaturePrefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
|
||||
|
||||
@@ -573,10 +585,10 @@ func getOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signature
|
||||
// instead of replaying from zero. Writes must go only to the current key:
|
||||
// keeping the historical key warm would re-create the very sharing between
|
||||
// streams that a key-scheme change separates.
|
||||
func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, legacySignaturePrefix string, legacySignature int32) (int64, error) {
|
||||
lastOffsetTsNs, err := getOffset(grpcDialOption, filer, signaturePrefix, signature)
|
||||
func getOffsetWithFallback(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32, legacySignaturePrefix string, legacySignature int32) (int64, error) {
|
||||
lastOffsetTsNs, err := getOffset(grpcDialOption, filer, tokenSource, signaturePrefix, signature)
|
||||
if err == nil && lastOffsetTsNs == 0 {
|
||||
lastOffsetTsNs, err = getOffset(grpcDialOption, filer, legacySignaturePrefix, legacySignature)
|
||||
lastOffsetTsNs, err = getOffset(grpcDialOption, filer, tokenSource, legacySignaturePrefix, legacySignature)
|
||||
}
|
||||
return lastOffsetTsNs, err
|
||||
}
|
||||
@@ -622,7 +634,7 @@ func resumeTsNsFor(p *MetadataProcessor) int64 {
|
||||
// lands late can be told apart from the fresher write it would shadow.
|
||||
var offsetWriteSeq atomic.Int64
|
||||
|
||||
func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signaturePrefix string, signature int32, offsetTsNs int64) error {
|
||||
func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, tokenSource security.FilerTokenSource, signaturePrefix string, signature int32, offsetTsNs int64) error {
|
||||
syncKey := []byte(signaturePrefix + "____")
|
||||
util.Uint32toBytes(syncKey[len(signaturePrefix):len(signaturePrefix)+4], uint32(signature))
|
||||
key := string(filer) + "\x00" + string(syncKey)
|
||||
@@ -643,7 +655,7 @@ func setOffset(grpcDialOption grpc.DialOption, filer pb.ServerAddress, signature
|
||||
}
|
||||
checkpoint.lastSeq = seq
|
||||
|
||||
return pb.WithFilerClient(false, signature, filer, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return pb.WithGrpcFilerClient(false, signature, filer, grpcDialOption, tokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
|
||||
valueBuf := make([]byte, 8)
|
||||
util.Uint64toBytes(valueBuf, uint64(offsetTsNs))
|
||||
|
||||
@@ -60,21 +60,21 @@ func TestSyncOffset_HistoricalFallbackThenIndependence(t *testing.T) {
|
||||
prefixB := getSignaturePrefixByPath("/data", "/backup-b")
|
||||
|
||||
// pre-upgrade state: both syncs shared the historical key
|
||||
if err := setOffset(dial, filerAddr, historical, sourceSig, 111); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, historical, sourceSig, 111); err != nil {
|
||||
t.Fatalf("seed historical offset: %v", err)
|
||||
}
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, prefixA, sourceSig, historical, sourceSig); err != nil || got != 111 {
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixA, sourceSig, historical, sourceSig); err != nil || got != 111 {
|
||||
t.Fatalf("A fallback read = (%d, %v), want (111, nil)", got, err)
|
||||
}
|
||||
|
||||
// A checkpoints under its own key; B still resumes from the historical one
|
||||
if err := setOffset(dial, filerAddr, prefixA, sourceSig, 222); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, prefixA, sourceSig, 222); err != nil {
|
||||
t.Fatalf("write A offset: %v", err)
|
||||
}
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, prefixA, sourceSig, historical, sourceSig); err != nil || got != 222 {
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixA, sourceSig, historical, sourceSig); err != nil || got != 222 {
|
||||
t.Fatalf("A read = (%d, %v), want (222, nil)", got, err)
|
||||
}
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, prefixB, sourceSig, historical, sourceSig); err != nil || got != 111 {
|
||||
if got, err := getOffsetWithFallback(dial, filerAddr, nil, prefixB, sourceSig, historical, sourceSig); err != nil || got != 111 {
|
||||
t.Fatalf("B read = (%d, %v), want (111, nil)", got, err)
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) {
|
||||
prefix := getSignaturePrefixByPath("/data", "/backup-stale")
|
||||
sourceSig := int32(77)
|
||||
|
||||
if err := setOffset(dial, filerAddr, prefix, sourceSig, 300); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 300); err != nil {
|
||||
t.Fatalf("seed offset: %v", err)
|
||||
}
|
||||
|
||||
@@ -107,10 +107,10 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) {
|
||||
checkpoint.lastSeq = offsetWriteSeq.Load() + 1000
|
||||
checkpoint.Unlock()
|
||||
|
||||
if err := setOffset(dial, filerAddr, prefix, sourceSig, 100); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 100); err != nil {
|
||||
t.Fatalf("stale write: %v", err)
|
||||
}
|
||||
if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 300 {
|
||||
if got, err := getOffset(dial, filerAddr, nil, prefix, sourceSig); err != nil || got != 300 {
|
||||
t.Fatalf("after stale write = (%d, %v), want (300, nil)", got, err)
|
||||
}
|
||||
|
||||
@@ -118,10 +118,10 @@ func TestSyncOffset_StaleWriteDropped(t *testing.T) {
|
||||
checkpoint.Lock()
|
||||
checkpoint.lastSeq = 0
|
||||
checkpoint.Unlock()
|
||||
if err := setOffset(dial, filerAddr, prefix, sourceSig, 199); err != nil {
|
||||
if err := setOffset(dial, filerAddr, nil, prefix, sourceSig, 199); err != nil {
|
||||
t.Fatalf("floored write: %v", err)
|
||||
}
|
||||
if got, err := getOffset(dial, filerAddr, prefix, sourceSig); err != nil || got != 199 {
|
||||
if got, err := getOffset(dial, filerAddr, nil, prefix, sourceSig); err != nil || got != 199 {
|
||||
t.Fatalf("after floored write = (%d, %v), want (199, nil)", got, err)
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,8 @@ func runFilerSyncVerify(cmd *Command, args []string) bool {
|
||||
glog.Fatalf("load security config for filer B: %v", err)
|
||||
}
|
||||
}
|
||||
tokenSourceA := security.FilerAdminTokenFromFile(*syncVerifyOptions.aSecurity)
|
||||
tokenSourceB := security.FilerAdminTokenFromFile(*syncVerifyOptions.bSecurity)
|
||||
|
||||
filerA := pb.ServerAddress(*syncVerifyOptions.filerA)
|
||||
filerB := pb.ServerAddress(*syncVerifyOptions.filerB)
|
||||
@@ -96,7 +98,7 @@ func runFilerSyncVerify(cmd *Command, args []string) bool {
|
||||
if err := runVerifySync(filerA, filerB, *syncVerifyOptions.aPath, *syncVerifyOptions.bPath,
|
||||
*syncVerifyOptions.isActivePassive, *syncVerifyOptions.modifiedTimeAgo,
|
||||
*syncVerifyOptions.jsonOutput,
|
||||
grpcDialOptionA, grpcDialOptionB); err != nil {
|
||||
grpcDialOptionA, grpcDialOptionB, tokenSourceA, tokenSourceB); err != nil {
|
||||
glog.Errorf("verify sync: %v", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
@@ -184,13 +186,13 @@ type summaryRecord struct {
|
||||
type simpleFilerClient struct {
|
||||
grpcAddress pb.ServerAddress
|
||||
grpcDialOption grpc.DialOption
|
||||
tokenSource security.FilerTokenSource
|
||||
}
|
||||
|
||||
func (c *simpleFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return pb.WithGrpcClient(context.Background(), streamingMode, 0, func(grpcConnection *grpc.ClientConn) error {
|
||||
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
|
||||
return pb.WithGrpcFilerClient(streamingMode, 0, c.grpcAddress, c.grpcDialOption, c.tokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return fn(client)
|
||||
}, c.grpcAddress.ToGrpcAddress(), false, c.grpcDialOption)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *simpleFilerClient) AdjustedUrl(location *filer_pb.Location) string {
|
||||
@@ -204,10 +206,11 @@ func (c *simpleFilerClient) GetDataCenter() string {
|
||||
func runVerifySync(filerA, filerB pb.ServerAddress, aPath, bPath string,
|
||||
isActivePassive bool, modifiedTimeAgo time.Duration,
|
||||
jsonOutput bool,
|
||||
grpcDialOptionA, grpcDialOptionB grpc.DialOption) error {
|
||||
grpcDialOptionA, grpcDialOptionB grpc.DialOption,
|
||||
tokenSourceA, tokenSourceB security.FilerTokenSource) error {
|
||||
|
||||
clientA := &simpleFilerClient{grpcAddress: filerA, grpcDialOption: grpcDialOptionA}
|
||||
clientB := &simpleFilerClient{grpcAddress: filerB, grpcDialOption: grpcDialOptionB}
|
||||
clientA := &simpleFilerClient{grpcAddress: filerA, grpcDialOption: grpcDialOptionA, tokenSource: tokenSourceA}
|
||||
clientB := &simpleFilerClient{grpcAddress: filerB, grpcDialOption: grpcDialOptionB, tokenSource: tokenSourceB}
|
||||
|
||||
var cutoffTime time.Time
|
||||
if modifiedTimeAgo > 0 {
|
||||
|
||||
@@ -274,6 +274,13 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'writebackCache' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
case "concurrentWriteMerge":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.concurrentWriteMerge = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'concurrentWriteMerge' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
case "asyncDio":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.asyncDio = &parsed
|
||||
|
||||
+1
-1
@@ -89,7 +89,7 @@ func (iamopt *IamOptions) startIamServer() bool {
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
var digest string
|
||||
for {
|
||||
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("get filer configuration: %v", err)
|
||||
|
||||
@@ -485,7 +485,7 @@ func initMiniFilerFlags() {
|
||||
miniFilerOptions.saveToFilerLimit = cmdMini.Flag.Int("filer.saveToFilerLimit", 0, "files smaller than this limit will be saved in filer store")
|
||||
miniFilerOptions.concurrentUploadLimitMB = cmdMini.Flag.Int("filer.concurrentUploadLimitMB", 0, "limit total concurrent upload size")
|
||||
miniFilerOptions.concurrentFileUploadLimit = cmdMini.Flag.Int("filer.concurrentFileUploadLimit", 0, "limit number of concurrent file uploads")
|
||||
miniFilerOptions.inflightUploadDataTimeout = cmdMini.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 429, 0 means no limit")
|
||||
miniFilerOptions.inflightUploadDataTimeout = cmdMini.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 503 and Retry-After, 0 means no limit")
|
||||
miniFilerOptions.localSocket = cmdMini.Flag.String("filer.localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
|
||||
miniFilerOptions.showUIDirectoryDelete = cmdMini.Flag.Bool("filer.ui.deleteDir", true, "enable filer UI show delete directory button")
|
||||
miniFilerOptions.downloadMaxMBps = cmdMini.Flag.Int("filer.downloadMaxMBps", 0, "download max speed for each download request, in MB per second")
|
||||
@@ -2474,7 +2474,7 @@ func ensureMiniBuckets(bucketSpec string) error {
|
||||
// Derive from miniClientsCtx so Ctrl+C cancels the bucket RPCs, and bound
|
||||
// with a short timeout (per bucket) so a stalled filer cannot block the
|
||||
// welcome message indefinitely.
|
||||
return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
return pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
for _, name := range names {
|
||||
if err := s3bucket.VerifyS3BucketName(name); err != nil {
|
||||
glog.Warningf("invalid bucket name %q: %v", name, err)
|
||||
@@ -2552,7 +2552,7 @@ func createMiniTableBuckets(servable []tableBucketEntry) ([]tableBucketEntry, er
|
||||
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
|
||||
var ready []tableBucketEntry
|
||||
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
manager := s3tables.NewManager()
|
||||
mgrClient := s3tables.NewManagerClient(client)
|
||||
for _, bucket := range servable {
|
||||
|
||||
@@ -15,7 +15,7 @@ func TestMiniDefaultPluginJobTypes(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("buildPluginWorkerHandlers(mini default) err = %v", err)
|
||||
}
|
||||
if len(handlers) != 7 {
|
||||
t.Fatalf("expected mini default job types to include 7 handlers, got %d", len(handlers))
|
||||
if len(handlers) != 9 {
|
||||
t.Fatalf("expected mini default job types to include 9 handlers, got %d", len(handlers))
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,8 @@ type MountOptions struct {
|
||||
|
||||
// Distributed locking for cross-mount write coordination and POSIX
|
||||
// advisory locks (flock/fcntl)
|
||||
distributedLock *bool
|
||||
distributedLock *bool
|
||||
concurrentWriteMerge *bool
|
||||
|
||||
// POSIX compliance options
|
||||
posixDirNlink *bool
|
||||
@@ -163,6 +164,7 @@ func init() {
|
||||
|
||||
// Distributed lock for cross-mount write coordination
|
||||
mountOptions.distributedLock = cmdMount.Flag.Bool("dlm", false, "coordinate writes across mounts (only one mount writes a file at a time) and honor POSIX advisory locks (flock/fcntl) across mounts by routing them to the owner filer")
|
||||
mountOptions.concurrentWriteMerge = cmdMount.Flag.Bool("concurrentWriteMerge", false, "when another mount wrote a file this mount has unflushed writes to, merge both mounts' writes instead of failing the later flush with EIO")
|
||||
|
||||
// POSIX compliance options
|
||||
mountOptions.posixDirNlink = cmdMount.Flag.Bool("posix.dirNLink", false, "report POSIX-compliant directory nlink (2 + subdirectory count); costs one directory listing per stat")
|
||||
|
||||
@@ -149,7 +149,7 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr
|
||||
var err error
|
||||
var digest string
|
||||
for i := 0; i < 10; i++ {
|
||||
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, nil, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err)
|
||||
@@ -253,6 +253,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
|
||||
MetadataFlushSeconds: *option.metadataFlushSeconds,
|
||||
DirIdleEvictSec: *option.dirIdleEvictSec,
|
||||
EnableDistributedLock: option.distributedLock != nil && *option.distributedLock,
|
||||
ConcurrentWriteMerge: option.concurrentWriteMerge != nil && *option.concurrentWriteMerge,
|
||||
WritebackCache: option.writebackCache != nil && *option.writebackCache,
|
||||
NfsExport: option.nfsExport != nil && *option.nfsExport,
|
||||
EagerFilerCreate: p.eagerFilerCreate,
|
||||
|
||||
+1
-1
@@ -328,7 +328,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
var filerDigest string
|
||||
|
||||
for {
|
||||
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("get filer configuration: %v", err)
|
||||
|
||||
@@ -17,12 +17,18 @@ recursive_delete = false
|
||||
# increase this if using tools like Spark that create temporary directories.
|
||||
#s3.empty_folder_cleanup_delay = "2m"
|
||||
# where the filer's internal system metadata log chunks are stored.
|
||||
# By default the log follows the filer's -collection flag; set this to keep
|
||||
# the internal log in its own collection, out of the default one.
|
||||
# By default the log has its own collection, so purging old log days frees
|
||||
# whole volumes. Set it to "" to keep the log in the filer's -collection.
|
||||
# Avoid a name a bucket maps to: deleting that bucket drops the collection.
|
||||
# Keep the target stable: log chunks written under an older value are not
|
||||
# moved, and old log entries keep referencing that collection's volumes.
|
||||
#metaLog.collection = "filer-meta"
|
||||
#metaLog.collection = "_meta"
|
||||
#metaLog.replication = ""
|
||||
# volumes added each time the metadata log collection needs to grow.
|
||||
# Keep this many free volume slots for it beside the master's volume_growth
|
||||
# count; 0 uses the master's count. When the collection cannot grow, log
|
||||
# chunks go to the filer's -collection until it can.
|
||||
#metaLog.volumeGrowthCount = 2
|
||||
|
||||
####################################################
|
||||
# The following are filer store options
|
||||
|
||||
@@ -55,6 +55,8 @@ storage_class = "STANDARD_IA"
|
||||
# 000 has only one copy, copy_1
|
||||
# 010 and 001 has two copies, copy_2
|
||||
# 011 has only 3 copies, copy_3
|
||||
# The filer's metadata log collection grows by metaLog.volumeGrowthCount in
|
||||
# filer.toml instead; volume servers keep room for both by default (-max=10).
|
||||
[master.volume_growth]
|
||||
copy_1 = 7 # create 1 x 7 = 7 actual volumes
|
||||
copy_2 = 6 # create 2 x 6 = 12 actual volumes
|
||||
|
||||
@@ -214,6 +214,16 @@ allowed_wildcard_domain = "" # .mycompany.com
|
||||
# allowlist and refuse to start when per-target keys are their only allowlist.
|
||||
allowed_server_commonNames = "" # comma-separated server identities
|
||||
allowed_server_wildcard_domain = "" # .mycompany.com
|
||||
# Client certificate common names that every mTLS gRPC server accepts for the
|
||||
# standard grpc.health.v1.Health service only. Give a monitoring probe a
|
||||
# CA-signed client certificate with one of these names, e.g. blackbox_exporter's
|
||||
# grpc prober, or grpc_health_probe with -tls-client-cert run as a Kubernetes
|
||||
# exec probe (the built-in Kubernetes grpc probe cannot present a client
|
||||
# certificate). The probe can check that the port serves and that the server
|
||||
# certificate is valid, but any other RPC is refused with PermissionDenied. The
|
||||
# names need no place in allowed_commonNames, and a name listed here stays
|
||||
# confined even if it is.
|
||||
health_check_commonNames = "" # comma-separated, e.g. "blackbox-exporter"
|
||||
|
||||
# Volume server gRPC options (server-side)
|
||||
# Enables mTLS for incoming gRPC connections to volume server
|
||||
|
||||
@@ -69,7 +69,7 @@ var (
|
||||
serverDisableHttp = cmdServer.Flag.Bool("disableHttp", false, "disable http requests, only gRPC operations are allowed.")
|
||||
serverIamConfig = cmdServer.Flag.String("iam.config", "", "path to the advanced IAM config file for S3. An alias for -s3.iam.config, but with lower priority.")
|
||||
volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
|
||||
volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
|
||||
volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
|
||||
volumeMinFreeSpacePercent = cmdServer.Flag.String("volume.minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
|
||||
volumeMinFreeSpace = cmdServer.Flag.String("volume.minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
|
||||
serverMetricsHttpPort = cmdServer.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
|
||||
@@ -132,7 +132,7 @@ func init() {
|
||||
filerOptions.saveToFilerLimit = cmdServer.Flag.Int("filer.saveToFilerLimit", 0, "Small files smaller than this limit can be cached in filer store.")
|
||||
filerOptions.concurrentUploadLimitMB = cmdServer.Flag.Int("filer.concurrentUploadLimitMB", 0, "limit total concurrent upload size, 0 means unlimited")
|
||||
filerOptions.concurrentFileUploadLimit = cmdServer.Flag.Int("filer.concurrentFileUploadLimit", 0, "limit number of concurrent file uploads, 0 means unlimited")
|
||||
filerOptions.inflightUploadDataTimeout = cmdServer.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 429, 0 means no limit")
|
||||
filerOptions.inflightUploadDataTimeout = cmdServer.Flag.Duration("filer.inflightUploadDataTimeout", 60*time.Second, "how long an upload waits for a slot under the concurrent upload limits before it is rejected with 503 and Retry-After, 0 means no limit")
|
||||
filerOptions.localSocket = cmdServer.Flag.String("filer.localSocket", "", "default to /tmp/seaweedfs-filer-<port>.sock")
|
||||
filerOptions.showUIDirectoryDelete = cmdServer.Flag.Bool("filer.ui.deleteDir", true, "enable filer UI show delete directory button")
|
||||
filerOptions.downloadMaxMBps = cmdServer.Flag.Int("filer.downloadMaxMBps", 0, "download max speed for each download request, in MB per second")
|
||||
|
||||
@@ -137,7 +137,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
|
||||
|
||||
// Connect to the filer service and try to retrieve basic configuration.
|
||||
for {
|
||||
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
|
||||
|
||||
@@ -44,6 +44,7 @@ func runShell(command *Command, args []string) bool {
|
||||
|
||||
util.LoadSecurityConfiguration()
|
||||
shellOptions.GrpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client")
|
||||
shellOptions.FilerTokenSource = security.FilerAdminToken
|
||||
shellOptions.Directory = "/"
|
||||
|
||||
util.LoadConfiguration("shell", false)
|
||||
|
||||
@@ -9,10 +9,12 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
func gracefulStopGrpc(grpcS *grpc.Server, timeout time.Duration) {
|
||||
glog.V(0).Infof("Gracefully stopping gRPC server")
|
||||
pb.StopHealthWatches(grpcS)
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
grpcS.GracefulStop()
|
||||
|
||||
@@ -268,7 +268,7 @@ var cmdVolume = &Command{
|
||||
|
||||
var (
|
||||
volumeFolders = cmdVolume.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
|
||||
maxVolumeCounts = cmdVolume.Flag.String("max", "8", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
|
||||
maxVolumeCounts = cmdVolume.Flag.String("max", "10", "maximum numbers of volumes, count[,count]... If set to zero, the limit will be auto configured as free disk space divided by volume size.")
|
||||
volumeWhiteListOption = cmdVolume.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
|
||||
minFreeSpacePercent = cmdVolume.Flag.String("minFreeSpacePercent", "1", "minimum free disk space (default to 1%). Low disk space will mark all volumes as ReadOnly (deprecated, use minFreeSpace instead).")
|
||||
minFreeSpace = cmdVolume.Flag.String("minFreeSpace", "", "min free disk space (value<=100 as percentage like 1, other as human readable bytes, like 10GiB). Low disk space will mark all volumes as ReadOnly.")
|
||||
@@ -591,6 +591,7 @@ func shutdown(publicHttpDown httpdown.Server, clusterHttpServer httpdown.Server,
|
||||
}
|
||||
|
||||
glog.V(0).Infof("graceful stop gRPC ...")
|
||||
pb.StopHealthWatches(grpcS)
|
||||
grpcS.GracefulStop()
|
||||
|
||||
volumeServer.Shutdown()
|
||||
|
||||
@@ -118,7 +118,7 @@ func (wo *WebDavOption) startWebDav() bool {
|
||||
var digest string
|
||||
// connect to filer
|
||||
for {
|
||||
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
|
||||
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
|
||||
|
||||
@@ -19,7 +19,9 @@ func TestWorkerDefaultJobTypes(t *testing.T) {
|
||||
"admin_script",
|
||||
"ec_balance",
|
||||
"erasure_coding",
|
||||
"filer_ttl",
|
||||
"iceberg_maintenance",
|
||||
"meta_log_purge",
|
||||
"s3_lifecycle",
|
||||
"vacuum",
|
||||
"volume_balance",
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -14,11 +15,13 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
@@ -34,6 +37,68 @@ type policyTestFilerServer struct {
|
||||
beforeUpdate func(string, string) error
|
||||
}
|
||||
|
||||
const filerEtcAuthTestKey = "filer-etc-auth-test-key-32-bytes-long"
|
||||
|
||||
func TestFilerEtcStoreUsesPerCallAdminToken(t *testing.T) {
|
||||
t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", "")
|
||||
t.Setenv("WEED_JWT_FILER_SIGNING_KEY", filerEtcAuthTestKey)
|
||||
|
||||
server := newPolicyTestFilerServer()
|
||||
checkAuth := func(ctx context.Context) error {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
values := md.Get("authorization")
|
||||
if len(values) != 1 || !strings.HasPrefix(values[0], security.BearerPrefix) {
|
||||
return status.Error(codes.Unauthenticated, "missing filer admin token")
|
||||
}
|
||||
token := security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix))
|
||||
if !security.IsFilerAdminToken(security.SigningKey(filerEtcAuthTestKey), token) {
|
||||
return status.Error(codes.Unauthenticated, "invalid filer admin token")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
grpcServer := grpc.NewServer(
|
||||
grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
if err := checkAuth(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}),
|
||||
grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
if err := checkAuth(stream.Context()); err != nil {
|
||||
return err
|
||||
}
|
||||
return handler(srv, stream)
|
||||
}),
|
||||
)
|
||||
filer_pb.RegisterSeaweedFilerServer(grpcServer, server)
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func() { _ = grpcServer.Serve(listener) }()
|
||||
t.Cleanup(func() {
|
||||
grpcServer.Stop()
|
||||
_ = listener.Close()
|
||||
})
|
||||
|
||||
host, portString, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
grpcPort, err := strconv.Atoi(portString)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &FilerEtcStore{}
|
||||
store.SetFilerAddressFunc(func() pb.ServerAddress {
|
||||
return pb.NewServerAddress(host, 1, grpcPort)
|
||||
}, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
|
||||
if _, err := store.ListPolicyNames(context.Background()); err != nil {
|
||||
t.Fatalf("ListPolicyNames: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newPolicyTestFilerServer() *policyTestFilerServer {
|
||||
return &policyTestFilerServer{
|
||||
entries: make(map[string]*filer_pb.Entry),
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/security"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
@@ -71,7 +72,7 @@ func (store *FilerEtcStore) withFilerClient(fn func(client filer_pb.SeaweedFiler
|
||||
}
|
||||
|
||||
// Use the pb.WithGrpcFilerClient helper similar to existing code
|
||||
return pb.WithGrpcFilerClient(false, 0, filerAddress, dialOption, fn)
|
||||
return pb.WithGrpcFilerClient(false, 0, filerAddress, dialOption, security.FilerAdminToken, fn)
|
||||
}
|
||||
|
||||
func (store *FilerEtcStore) Shutdown() {
|
||||
|
||||
@@ -246,7 +246,7 @@ func (group *ChunkGroup) SetChunks(chunks []*filer_pb.FileChunk) error {
|
||||
return err
|
||||
}
|
||||
|
||||
dataChunks = append(dataChunks, resolvedChunks...)
|
||||
dataChunks = append(dataChunks, cutToManifestSpan(chunk, resolvedChunks)...)
|
||||
}
|
||||
|
||||
sections := make(map[SectionIndex]*FileChunkSection)
|
||||
|
||||
Loaded 100 of 332 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user