use of com.google.common.util.concurrent.FutureCallback in project controller by opendaylight.
the class ConcurrentDOMDataBroker method doCanCommit.
private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture, final DOMDataTreeWriteTransaction transaction, final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
final long startTime = System.nanoTime();
final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();
// Not using Futures.allAsList here to avoid its internal overhead.
FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
@Override
public void onSuccess(final Boolean result) {
if (result == null || !result) {
handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER, new TransactionCommitFailedException("Can Commit failed, no detailed cause available."));
} else if (!cohortIterator.hasNext()) {
// All cohorts completed successfully - we can move on to the preCommit phase
doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
} else {
Futures.addCallback(cohortIterator.next().canCommit(), this, MoreExecutors.directExecutor());
}
}
@Override
public void onFailure(final Throwable failure) {
handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER, failure);
}
};
ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
}
use of com.google.common.util.concurrent.FutureCallback in project openflowplugin by opendaylight.
the class DeviceContextImpl method handlePacketInMessage.
private void handlePacketInMessage(final PacketIn packetIn, final Class<?> implementedInterface, final Match match) {
messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH);
final ConnectionAdapter connectionAdapter = getPrimaryConnectionContext().getConnectionAdapter();
if (packetIn == null) {
LOG.debug("Received a null packet from switch {}", connectionAdapter.getRemoteAddress());
messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_TRANSLATE_SRC_FAILURE);
return;
}
final OpenflowVersion openflowVersion = OpenflowVersion.get(deviceInfo.getVersion());
// Try to get ingress from match
final NodeConnectorRef nodeConnectorRef = Objects.nonNull(packetIn.getIngress()) ? packetIn.getIngress() : Optional.ofNullable(match).map(Match::getInPort).map(nodeConnectorId -> InventoryDataServiceUtil.portNumberfromNodeConnectorId(openflowVersion, nodeConnectorId)).map(portNumber -> InventoryDataServiceUtil.nodeConnectorRefFromDatapathIdPortno(deviceInfo.getDatapathId(), portNumber, openflowVersion)).orElse(null);
messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_TRANSLATE_OUT_SUCCESS);
if (!packetInLimiter.acquirePermit()) {
LOG.debug("Packet limited");
// TODO: save packet into emergency slot if possible
messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_PACKET_IN_LIMIT_REACHED_AND_DROPPED);
return;
}
final ListenableFuture<?> offerNotification = notificationPublishService.offerNotification(new PacketReceivedBuilder(packetIn).setIngress(nodeConnectorRef).setMatch(MatchUtil.transformMatch(match, org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.packet.received.Match.class)).build());
if (NotificationPublishService.REJECTED.equals(offerNotification)) {
LOG.debug("notification offer rejected");
messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_NOTIFICATION_REJECTED);
packetInLimiter.drainLowWaterMark();
packetInLimiter.releasePermit();
return;
}
Futures.addCallback(offerNotification, new FutureCallback<Object>() {
@Override
public void onSuccess(final Object result) {
messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_SUCCESS);
packetInLimiter.releasePermit();
}
@Override
public void onFailure(final Throwable throwable) {
messageSpy.spyMessage(implementedInterface, MessageSpy.StatisticsGroup.FROM_SWITCH_NOTIFICATION_REJECTED);
LOG.debug("notification offer failed: {}", throwable.getMessage());
LOG.trace("notification offer failed..", throwable);
packetInLimiter.releasePermit();
}
}, MoreExecutors.directExecutor());
}
use of com.google.common.util.concurrent.FutureCallback in project openflowplugin by opendaylight.
the class SalTableServiceImplTest method setup.
@Override
public void setup() {
handleResultFuture = SettableFuture.create();
when(mockedRequestContext.getFuture()).thenReturn(handleResultFuture);
Mockito.doAnswer((Answer<Void>) invocation -> {
final FutureCallback<OfHeader> callback = (FutureCallback<OfHeader>) invocation.getArguments()[2];
callback.onSuccess(null);
return null;
}).when(mockedOutboundQueue).commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
salTableService = new SalTableServiceImpl(mockedRequestContextStack, mockedDeviceContext, convertorManager, MultipartWriterProviderFactory.createDefaultProvider(mockedDeviceContext));
}
use of com.google.common.util.concurrent.FutureCallback in project openflowplugin by opendaylight.
the class DeviceFlowRegistryImpl method fillFromDatastore.
private CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> fillFromDatastore(final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<FlowCapableNode> path) {
// Create new read-only transaction
final ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();
// Bail out early if transaction is null
if (transaction == null) {
return Futures.immediateFailedCheckedFuture(new ReadFailedException("Read transaction is null"));
}
// Prepare read operation from datastore for path
final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> future = transaction.read(logicalDatastoreType, path);
// Bail out early if future is null
if (future == null) {
return Futures.immediateFailedCheckedFuture(new ReadFailedException("Future from read transaction is null"));
}
Futures.addCallback(future, new FutureCallback<Optional<FlowCapableNode>>() {
@Override
public void onSuccess(@Nonnull Optional<FlowCapableNode> result) {
result.asSet().stream().filter(Objects::nonNull).filter(flowCapableNode -> Objects.nonNull(flowCapableNode.getTable())).flatMap(flowCapableNode -> flowCapableNode.getTable().stream()).filter(Objects::nonNull).filter(table -> Objects.nonNull(table.getFlow())).flatMap(table -> table.getFlow().stream()).filter(Objects::nonNull).filter(flow -> Objects.nonNull(flow.getId())).forEach(flowConsumer);
// After we are done with reading from datastore, close the transaction
transaction.close();
}
@Override
public void onFailure(Throwable throwable) {
// Even when read operation failed, close the transaction
transaction.close();
}
}, MoreExecutors.directExecutor());
return future;
}
use of com.google.common.util.concurrent.FutureCallback in project cassandra by apache.
the class ViewBuilder method build.
private synchronized void build() {
if (isStopped) {
logger.debug("Stopped build for view({}.{}) after covering {} keys", ksName, view.name, keysBuilt);
return;
}
// Get the local ranges for which the view hasn't already been built nor it's building
RangesAtEndpoint replicatedRanges = StorageService.instance.getLocalReplicas(ksName);
Replicas.temporaryAssertFull(replicatedRanges);
Set<Range<Token>> newRanges = replicatedRanges.ranges().stream().map(r -> r.subtractAll(builtRanges)).flatMap(Set::stream).map(r -> r.subtractAll(pendingRanges.keySet())).flatMap(Set::stream).collect(Collectors.toSet());
// If there are no new nor pending ranges we should finish the build
if (newRanges.isEmpty() && pendingRanges.isEmpty()) {
finish();
return;
}
// Split the new local ranges and add them to the pending set
DatabaseDescriptor.getPartitioner().splitter().map(s -> s.split(newRanges, NUM_TASKS)).orElse(newRanges).forEach(r -> pendingRanges.put(r, Pair.<Token, Long>create(null, 0L)));
// Submit a new view build task for each building range.
// We keep record of all the submitted tasks to be able of stopping them.
List<Future<Long>> futures = pendingRanges.entrySet().stream().map(e -> new ViewBuilderTask(baseCfs, view, e.getKey(), e.getValue().left, e.getValue().right)).peek(tasks::add).map(CompactionManager.instance::submitViewBuilder).collect(toList());
// Add a callback to process any eventual new local range and mark the view as built, doing a delayed retry if
// the tasks don't succeed
Future<List<Long>> future = FutureCombiner.allOf(futures);
future.addCallback(new FutureCallback<List<Long>>() {
public void onSuccess(List<Long> result) {
keysBuilt += result.stream().mapToLong(x -> x).sum();
builtRanges.addAll(pendingRanges.keySet());
pendingRanges.clear();
build();
}
public void onFailure(Throwable t) {
if (t instanceof CompactionInterruptedException) {
internalStop(true);
keysBuilt = tasks.stream().mapToLong(ViewBuilderTask::keysBuilt).sum();
logger.info("Interrupted build for view({}.{}) after covering {} keys", ksName, view.name, keysBuilt);
} else {
ScheduledExecutors.nonPeriodicTasks.schedule(() -> loadStatusAndBuild(), 5, TimeUnit.MINUTES);
logger.warn("Materialized View failed to complete, sleeping 5 minutes before restarting", t);
}
}
});
this.future = future;
}
Aggregations