Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#643] improvement(core): Improve and fix the possible concurrent problem when visiting EntityStore #654

Merged
merged 6 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.Getter;
Expand All @@ -58,6 +59,10 @@ public class KvEntityStore implements EntityStore {
ImmutableMap.of("RocksDBKvBackend", RocksDBKvBackend.class.getCanonicalName());

@Getter @VisibleForTesting private KvBackend backend;

// Lock to control the concurrency of the entity store, to be more exact, the concurrency of
// accessing the underlying kv store.
private ReentrantReadWriteLock reentrantReadWriteLock;
private EntityKeyEncoder<byte[]> entityKeyEncoder;
private NameMappingService nameMappingService;
private EntitySerDe serDe;
Expand All @@ -69,6 +74,7 @@ public void initialize(Config config) throws RuntimeException {
// instance, We should make it configurable in the future.
this.nameMappingService = new KvNameMappingService(backend);
this.entityKeyEncoder = new BinaryEntityKeyEncoder(nameMappingService);
this.reentrantReadWriteLock = new ReentrantReadWriteLock();
}

@Override
Expand All @@ -89,14 +95,16 @@ public <E extends Entity & HasIdentifier> List<E> list(

byte[] endKey = Bytes.increment(Bytes.wrap(startKey)).get();
List<Pair<byte[], byte[]>> kvs =
backend.scan(
new KvRangeScan.KvRangeScanBuilder()
.start(startKey)
.end(endKey)
.startInclusive(true)
.endInclusive(false)
.limit(Integer.MAX_VALUE)
.build());
executeWithReadLock(
() ->
backend.scan(
new KvRangeScan.KvRangeScanBuilder()
.start(startKey)
.end(endKey)
.startInclusive(true)
.endInclusive(false)
.limit(Integer.MAX_VALUE)
.build()));

for (Pair<byte[], byte[]> pairs : kvs) {
entities.add(serDe.deserialize(pairs.getRight(), e));
Expand All @@ -112,53 +120,63 @@ public boolean exists(NameIdentifier ident, EntityType entityType) throws IOExce
return false;
}

return backend.get(key) != null;
return executeWithReadLock(() -> backend.get(key) != null);
}

@Override
public <E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
throws IOException, EntityAlreadyExistsException {
byte[] key = entityKeyEncoder.encode(e.nameIdentifier(), e.type());
byte[] value = serDe.serialize(e);
backend.put(key, value, overwritten);

executeWithWriteLock(
() -> {
backend.put(key, value, overwritten);
return null;
});
}

@Override
public <E extends Entity & HasIdentifier> E update(
NameIdentifier ident, Class<E> type, EntityType entityType, Function<E, E> updater)
throws IOException, NoSuchEntityException, AlreadyExistsException {
byte[] key = entityKeyEncoder.encode(ident, entityType);
return executeInTransaction(
() -> {
byte[] value = backend.get(key);
if (value == null) {
throw new NoSuchEntityException(ident.toString());
}

E e = serDe.deserialize(value, type);
E updatedE = updater.apply(e);
if (updatedE.nameIdentifier().equals(ident)) {
backend.put(key, serDe.serialize(updatedE), true);
return updatedE;
}

// If we have changed the name of the entity, We would do the following steps:
// Check whether the new entities already existed
boolean newEntityExist = exists(updatedE.nameIdentifier(), entityType);
if (newEntityExist) {
throw new AlreadyExistsException(
String.format(
"Entity %s already exist, please check again", updatedE.nameIdentifier()));
}

// Update the name mapping
nameMappingService.updateName(
generateKeyForMapping(ident), generateKeyForMapping(updatedE.nameIdentifier()));

// Update the entity to store
backend.put(key, serDe.serialize(updatedE), true);
return updatedE;
});
return executeWithWriteLock(
() ->
executeInTransaction(
() -> {
byte[] value = backend.get(key);
if (value == null) {
throw new NoSuchEntityException(ident.toString());
}

E e = serDe.deserialize(value, type);
E updatedE = updater.apply(e);
if (updatedE.nameIdentifier().equals(ident)) {
backend.put(key, serDe.serialize(updatedE), true);
return updatedE;
}

// If we have changed the name of the entity, We would do the following steps:
// Check whether the new entities already existed
boolean newEntityExist = exists(updatedE.nameIdentifier(), entityType);
if (newEntityExist) {
throw new AlreadyExistsException(
String.format(
"Entity %s already exist, please check again",
updatedE.nameIdentifier()));
}

// Update the name mapping
nameMappingService.updateName(
generateKeyForMapping(ident),
generateKeyForMapping(updatedE.nameIdentifier()));

// Update the entity to store
backend.put(key, serDe.serialize(updatedE), true);
return updatedE;
}));
}

private String concatIdAndName(long[] namespaceIds, String name) {
Expand Down Expand Up @@ -227,7 +245,7 @@ public <E extends Entity & HasIdentifier> E get(
throw new NoSuchEntityException(ident.toString());
}

byte[] value = backend.get(key);
byte[] value = executeWithReadLock(() -> backend.get(key));
if (value == null) {
throw new NoSuchEntityException(ident.toString());
}
Expand Down Expand Up @@ -291,44 +309,48 @@ private byte[] replacePrefixTypeInfo(byte[] encode, String subTypePrefix) {
@Override
public boolean delete(NameIdentifier ident, EntityType entityType, boolean cascade)
throws IOException {
if (!exists(ident, entityType)) {
return false;
}
return executeWithWriteLock(
() -> {
if (!exists(ident, entityType)) {
return false;
}

byte[] dataKey = entityKeyEncoder.encode(ident, entityType, true);
List<byte[]> subEntityPrefix = getSubEntitiesPrefix(ident, entityType);
if (subEntityPrefix.isEmpty()) {
// has no sub-entities
return backend.delete(dataKey);
}
byte[] dataKey = entityKeyEncoder.encode(ident, entityType, true);
List<byte[]> subEntityPrefix = getSubEntitiesPrefix(ident, entityType);
if (subEntityPrefix.isEmpty()) {
// has no sub-entities
return backend.delete(dataKey);
}

byte[] directChild = Iterables.getLast(subEntityPrefix);
byte[] endKey = Bytes.increment(Bytes.wrap(directChild)).get();
List<Pair<byte[], byte[]>> kvs =
backend.scan(
new KvRangeScan.KvRangeScanBuilder()
.start(directChild)
.end(endKey)
.startInclusive(true)
.endInclusive(false)
.limit(1)
.build());

if (!cascade && !kvs.isEmpty()) {
throw new NonEmptyEntityException(
String.format("Entity %s has sub-entities, you should remove sub-entities first", ident));
}
byte[] directChild = Iterables.getLast(subEntityPrefix);
byte[] endKey = Bytes.increment(Bytes.wrap(directChild)).get();
List<Pair<byte[], byte[]>> kvs =
backend.scan(
new KvRangeScan.KvRangeScanBuilder()
.start(directChild)
.end(endKey)
.startInclusive(true)
.endInclusive(false)
.limit(1)
.build());

if (!cascade && !kvs.isEmpty()) {
throw new NonEmptyEntityException(
String.format(
"Entity %s has sub-entities, you should remove sub-entities first", ident));
}

for (byte[] prefix : subEntityPrefix) {
backend.deleteRange(
new KvRangeScan.KvRangeScanBuilder()
.start(prefix)
.startInclusive(true)
.end(Bytes.increment(Bytes.wrap(prefix)).get())
.build());
}
for (byte[] prefix : subEntityPrefix) {
backend.deleteRange(
new KvRangeScan.KvRangeScanBuilder()
.start(prefix)
.startInclusive(true)
.end(Bytes.increment(Bytes.wrap(prefix)).get())
.build());
}

return backend.delete(dataKey);
return backend.delete(dataKey);
});
}

@Override
Expand Down Expand Up @@ -359,4 +381,27 @@ private static KvBackend createKvEntityBackend(Config config) {
"Failed to create and initialize KvBackend by name: " + backendName, e);
}
}

@FunctionalInterface
interface IOExecutable<R> {
R execute() throws IOException;
}

private <R> R executeWithReadLock(IOExecutable<R> executable) throws IOException {
reentrantReadWriteLock.readLock().lock();
try {
return executable.execute();
} finally {
reentrantReadWriteLock.readLock().unlock();
}
}

private <R> R executeWithWriteLock(IOExecutable<R> executable) throws IOException {
reentrantReadWriteLock.writeLock().lock();
try {
return executable.execute();
} finally {
reentrantReadWriteLock.writeLock().unlock();
}
}
}
Loading