Skip to content

Commit

Permalink
[#643] improvement(core): Improve and fix the possible concurrent pro…
Browse files Browse the repository at this point in the history
…blem when visiting EntityStore (#654)

### What changes were proposed in this pull request?

Introducing the `reentrantReadWriteLock` to alleviate possible
concurrent problems to access the `KvEntityStore`

### Why are the changes needed?

`KvEntityStore` subjects to concurrent problems when multi-thread access
it at the same time. For instance, if there are
multiple threads are attempting to save the entity with the same name
identifier into the store. We must ensure that the entity can only be
saved successfully once.

Fix: #643 
Fix: #618 

### Does this PR introduce _any_ user-facing change?

No

### How was this patch tested?

New test case named `testConcurrentIssues` in `TestKvEntityStorage`
added.
  • Loading branch information
yuqi1129 authored Nov 3, 2023
1 parent 0014649 commit 53a9cab
Show file tree
Hide file tree
Showing 2 changed files with 241 additions and 75 deletions.
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

0 comments on commit 53a9cab

Please sign in to comment.