use of org.janusgraph.diskstorage.TemporaryBackendException in project janusgraph by JanusGraph.
the class LuceneIndex method mutate.
@Override
public void mutate(Map<String, Map<String, IndexMutation>> mutations, KeyInformation.IndexRetriever information, BaseTransaction tx) throws BackendException {
final Transaction ltx = (Transaction) tx;
writerLock.lock();
try {
for (final Map.Entry<String, Map<String, IndexMutation>> stores : mutations.entrySet()) {
mutateStores(stores, information);
}
ltx.postCommit();
} catch (final IOException e) {
throw new TemporaryBackendException("Could not update Lucene index", e);
} finally {
writerLock.unlock();
}
}
use of org.janusgraph.diskstorage.TemporaryBackendException in project janusgraph by JanusGraph.
the class LuceneIndex method restore.
@Override
public void restore(Map<String, Map<String, List<IndexEntry>>> documents, KeyInformation.IndexRetriever information, BaseTransaction tx) throws BackendException {
writerLock.lock();
try {
for (final Map.Entry<String, Map<String, List<IndexEntry>>> stores : documents.entrySet()) {
IndexReader reader = null;
try {
final String store = stores.getKey();
final IndexWriter writer = getWriter(store, information);
final KeyInformation.StoreRetriever storeRetriever = information.get(store);
reader = DirectoryReader.open(writer, true, true);
final IndexSearcher searcher = new IndexSearcher(reader);
for (final Map.Entry<String, List<IndexEntry>> entry : stores.getValue().entrySet()) {
final String docID = entry.getKey();
final List<IndexEntry> content = entry.getValue();
if (content == null || content.isEmpty()) {
if (log.isTraceEnabled())
log.trace("Deleting document [{}]", docID);
writer.deleteDocuments(new Term(DOCID, docID));
continue;
}
final Document doc = retrieveOrCreate(docID, searcher);
Iterators.removeIf(doc.iterator(), field -> !field.name().equals(DOCID));
addToDocument(doc, content, storeRetriever, true);
// write the old document to the index with the modifications
writer.updateDocument(new Term(DOCID, docID), doc);
}
writer.commit();
} finally {
IOUtils.closeQuietly(reader);
}
}
tx.commit();
} catch (final IOException e) {
throw new TemporaryBackendException("Could not update Lucene index", e);
} finally {
writerLock.unlock();
}
}
use of org.janusgraph.diskstorage.TemporaryBackendException in project janusgraph by JanusGraph.
the class ConsistentKeyIDAuthority method getIDBlock.
@Override
public synchronized IDBlock getIDBlock(final int partition, final int idNamespace, Duration timeout) throws BackendException {
Preconditions.checkArgument(partition >= 0 && partition < (1 << partitionBitWidth), "Invalid partition id [%s] for bit width [%s]", partition, partitionBitWidth);
// can be any non-negative value
Preconditions.checkArgument(idNamespace >= 0);
final Timer methodTime = times.getTimer().start();
final long blockSize = getBlockSize(idNamespace);
final long idUpperBound = getIdUpperBound(idNamespace);
final int maxAvailableBits = (VariableLong.unsignedBitLength(idUpperBound) - 1) - uniqueIdBitWidth;
Preconditions.checkArgument(maxAvailableBits > 0, "Unique id bit width [%s] is too wide for id-namespace [%s] id bound [%s]", uniqueIdBitWidth, idNamespace, idUpperBound);
final long idBlockUpperBound = (1L << maxAvailableBits);
final List<Integer> exhaustedUniquePIDs = new ArrayList<>(randomUniqueIDLimit);
Duration backoffMS = idApplicationWaitMS;
Preconditions.checkArgument(idBlockUpperBound > blockSize, "Block size [%s] is larger than upper bound [%s] for bit width [%s]", blockSize, idBlockUpperBound, uniqueIdBitWidth);
while (methodTime.elapsed().compareTo(timeout) < 0) {
final int uniquePID = getUniquePartitionID();
final StaticBuffer partitionKey = getPartitionKey(partition, idNamespace, uniquePID);
try {
long nextStart = getCurrentID(partitionKey);
if (idBlockUpperBound - blockSize <= nextStart) {
log.info("ID overflow detected on partition({})-namespace({}) with uniqueid {}. Current id {}, block size {}, and upper bound {} for bit width {}.", partition, idNamespace, uniquePID, nextStart, blockSize, idBlockUpperBound, uniqueIdBitWidth);
if (randomizeUniqueId) {
exhaustedUniquePIDs.add(uniquePID);
if (exhaustedUniquePIDs.size() == randomUniqueIDLimit)
throw new IDPoolExhaustedException(String.format("Exhausted %d uniqueid(s) on partition(%d)-namespace(%d): %s", exhaustedUniquePIDs.size(), partition, idNamespace, StringUtils.join(exhaustedUniquePIDs, ",")));
else
throw new UniqueIDExhaustedException(String.format("Exhausted ID partition(%d)-namespace(%d) with uniqueid %d (uniqueid attempt %d/%d)", partition, idNamespace, uniquePID, exhaustedUniquePIDs.size(), randomUniqueIDLimit));
}
throw new IDPoolExhaustedException("Exhausted id block for partition(" + partition + ")-namespace(" + idNamespace + ") with upper bound: " + idBlockUpperBound);
}
// calculate the start (inclusive) and end (exclusive) of the allocation we're about to attempt
assert idBlockUpperBound - blockSize > nextStart;
long nextEnd = nextStart + blockSize;
StaticBuffer target = null;
// attempt to write our claim on the next id block
boolean success = false;
try {
Timer writeTimer = times.getTimer().start();
target = getBlockApplication(nextEnd, writeTimer.getStartTime());
// copy for the inner class
final StaticBuffer finalTarget = target;
BackendOperation.execute(txh -> {
idStore.mutate(partitionKey, Collections.singletonList(StaticArrayEntry.of(finalTarget)), KeyColumnValueStore.NO_DELETIONS, txh);
return true;
}, this, times);
writeTimer.stop();
final boolean distributed = manager.getFeatures().isDistributed();
Duration writeElapsed = writeTimer.elapsed();
if (idApplicationWaitMS.compareTo(writeElapsed) < 0 && distributed) {
throw new TemporaryBackendException("Wrote claim for id block [" + nextStart + ", " + nextEnd + ") in " + (writeElapsed) + " => too slow, threshold is: " + idApplicationWaitMS);
} else {
assert 0 != target.length();
final StaticBuffer[] slice = getBlockSlice(nextEnd);
if (distributed) {
sleepAndConvertInterrupts(idApplicationWaitMS.plus(waitGracePeriod));
}
// Read all id allocation claims on this partition, for the counter value we're claiming
final List<Entry> blocks = BackendOperation.execute((BackendOperation.Transactional<List<Entry>>) txh -> idStore.getSlice(new KeySliceQuery(partitionKey, slice[0], slice[1]), txh), this, times);
if (blocks == null)
throw new TemporaryBackendException("Could not read from storage");
if (blocks.isEmpty())
throw new PermanentBackendException("It seems there is a race-condition in the block application. " + "If you have multiple JanusGraph instances running on one physical machine, ensure that they have unique machine idAuthorities");
/* If our claim is the lexicographically first one, then our claim
* is the most senior one and we own this id block
*/
if (target.equals(blocks.get(0).getColumnAs(StaticBuffer.STATIC_FACTORY))) {
ConsistentKeyIDBlock idBlock = new ConsistentKeyIDBlock(nextStart, blockSize, uniqueIdBitWidth, uniquePID);
if (log.isDebugEnabled()) {
log.debug("Acquired ID block [{}] on partition({})-namespace({}) (my rid is {})", idBlock, partition, idNamespace, uid);
}
success = true;
return idBlock;
} else {
// Another claimant beat us to this id block -- try again.
log.debug("Failed to acquire ID block [{},{}) (another host claimed it first)", nextStart, nextEnd);
}
}
} finally {
if (!success && null != target) {
// Delete claim to not pollute id space
for (int attempt = 0; attempt < ROLLBACK_ATTEMPTS; attempt++) {
try {
// copy for the inner class
final StaticBuffer finalTarget = target;
BackendOperation.execute(txh -> {
idStore.mutate(partitionKey, KeyColumnValueStore.NO_ADDITIONS, Collections.singletonList(finalTarget), txh);
return true;
}, new // Use normal consistency level for these non-critical delete operations
BackendOperation.TransactionalProvider() {
@Override
public StoreTransaction openTx() throws BackendException {
return manager.beginTransaction(storeTxConfigBuilder.build());
}
@Override
public void close() {
}
}, times);
break;
} catch (BackendException e) {
log.warn("Storage exception while deleting old block application - retrying in {}", rollbackWaitTime, e);
if (!rollbackWaitTime.isZero())
sleepAndConvertInterrupts(rollbackWaitTime);
}
}
}
}
} catch (UniqueIDExhaustedException e) {
// No need to increment the backoff wait time or to sleep
log.warn(e.getMessage());
} catch (TemporaryBackendException e) {
backoffMS = Durations.min(backoffMS.multipliedBy(2), idApplicationWaitMS.multipliedBy(32));
log.warn("Temporary storage exception while acquiring id block - retrying in {}: {}", backoffMS, e);
sleepAndConvertInterrupts(backoffMS);
}
}
throw new TemporaryLockingException(String.format("Reached timeout %d (%s elapsed) when attempting to allocate id block on partition(%d)-namespace(%d)", timeout.getNano(), methodTime, partition, idNamespace));
}
use of org.janusgraph.diskstorage.TemporaryBackendException in project janusgraph by JanusGraph.
the class IDPoolTest method testAllocationTimeoutAndRecovery.
@Test
public void testAllocationTimeoutAndRecovery() throws BackendException {
IMocksControl ctrl = EasyMock.createStrictControl();
final int partition = 42;
final int idNamespace = 777;
final Duration timeout = Duration.ofSeconds(1L);
final IDAuthority mockAuthority = ctrl.createMock(IDAuthority.class);
// Sleep for two seconds, then throw a BackendException
// this whole delegate could be deleted if we abstracted StandardIDPool's internal executor and stopwatches
expect(mockAuthority.getIDBlock(partition, idNamespace, timeout)).andDelegateTo(new IDAuthority() {
@Override
public IDBlock getIDBlock(int partition, int idNamespace, Duration timeout) throws BackendException {
assertThrows(InterruptedException.class, () -> Thread.sleep(2000L));
throw new TemporaryBackendException("slow backend");
}
@Override
public List<KeyRange> getLocalIDPartition() {
throw new IllegalArgumentException();
}
@Override
public void setIDBlockSizer(IDBlockSizer sizer) {
throw new IllegalArgumentException();
}
@Override
public void close() {
throw new IllegalArgumentException();
}
@Override
public String getUniqueID() {
throw new IllegalArgumentException();
}
@Override
public boolean supportsInterruption() {
return true;
}
});
expect(mockAuthority.getIDBlock(partition, idNamespace, timeout)).andReturn(new IDBlock() {
@Override
public long numIds() {
return 2;
}
@Override
public long getId(long index) {
return 200;
}
});
expect(mockAuthority.supportsInterruption()).andStubReturn(true);
ctrl.replay();
StandardIDPool pool = new StandardIDPool(mockAuthority, partition, idNamespace, Integer.MAX_VALUE, timeout, 0.1);
assertThrows(JanusGraphException.class, pool::nextID);
long nextID = pool.nextID();
assertEquals(200, nextID);
ctrl.verify();
}
use of org.janusgraph.diskstorage.TemporaryBackendException in project janusgraph by JanusGraph.
the class MockIDAuthority method getIDBlock.
@Override
public IDBlock getIDBlock(final int partition, final int idNamespace, Duration timeout) throws BackendException {
// Delay artificially
if (delayAcquisitionMS > 0) {
try {
Thread.sleep(delayAcquisitionMS);
} catch (InterruptedException e) {
throw new TemporaryBackendException(e);
}
}
Preconditions.checkArgument(partition >= 0);
Preconditions.checkArgument(idNamespace >= 0);
Long p = (((long) partition) << Integer.SIZE) + ((long) idNamespace);
long size = blockSizer.getBlockSize(idNamespace);
AtomicLong id = ids.get(p);
if (id == null) {
ids.putIfAbsent(p, new AtomicLong(1));
id = ids.get(p);
Preconditions.checkNotNull(id);
}
long lowerBound = id.getAndAdd(size);
if (lowerBound >= blockSizeLimit) {
throw new IDPoolExhaustedException("Reached partition limit: " + blockSizeLimit);
}
return new MockIDBlock(lowerBound, Math.min(size, blockSizeLimit - lowerBound));
}
Aggregations