Search in sources :

Example 61 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project presto by prestodb.

the class ContinuousTaskStatusFetcher method scheduleNextRequest.

private synchronized void scheduleNextRequest() {
    // stopped or done?
    TaskStatus taskStatus = getTaskStatus();
    if (!running || taskStatus.getState().isDone()) {
        return;
    }
    // outstanding request?
    if (future != null && !future.isDone()) {
        // this should never happen
        log.error("Can not reschedule update because an update is already running");
        return;
    }
    // if throttled due to error, asynchronously wait for timeout and try again
    ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit();
    if (!errorRateLimit.isDone()) {
        errorRateLimit.addListener(this::scheduleNextRequest, executor);
        return;
    }
    Request.Builder requestBuilder;
    ResponseHandler responseHandler;
    if (thriftTransportEnabled) {
        requestBuilder = ThriftRequestUtils.prepareThriftGet(thriftProtocol);
        responseHandler = new ThriftResponseHandler(unwrapThriftCodec(taskStatusCodec));
    } else if (binaryTransportEnabled) {
        requestBuilder = getBinaryTransportBuilder(prepareGet());
        responseHandler = createFullSmileResponseHandler((SmileCodec<TaskStatus>) taskStatusCodec);
    } else {
        requestBuilder = getJsonTransportBuilder(prepareGet());
        responseHandler = createAdaptingJsonResponseHandler((JsonCodec<TaskStatus>) taskStatusCodec);
    }
    Request request = requestBuilder.setUri(uriBuilderFrom(taskStatus.getSelf()).appendPath("status").build()).setHeader(PRESTO_CURRENT_STATE, taskStatus.getState().toString()).setHeader(PRESTO_MAX_WAIT, refreshMaxWait.toString()).build();
    errorTracker.startRequest();
    future = httpClient.executeAsync(request, responseHandler);
    currentRequestStartNanos.set(System.nanoTime());
    FutureCallback callback;
    if (thriftTransportEnabled) {
        callback = new ThriftHttpResponseHandler(this, request.getUri(), stats.getHttpResponseStats(), REMOTE_TASK_ERROR);
    } else {
        callback = new SimpleHttpResponseHandler<>(this, request.getUri(), stats.getHttpResponseStats(), REMOTE_TASK_ERROR);
    }
    Futures.addCallback(future, callback, executor);
}
Also used : ThriftResponseHandler(com.facebook.airlift.http.client.thrift.ThriftResponseHandler) SimpleHttpResponseHandler(com.facebook.presto.server.SimpleHttpResponseHandler) ThriftHttpResponseHandler(com.facebook.presto.server.thrift.ThriftHttpResponseHandler) FullSmileResponseHandler.createFullSmileResponseHandler(com.facebook.presto.server.smile.FullSmileResponseHandler.createFullSmileResponseHandler) ResponseHandler(com.facebook.airlift.http.client.ResponseHandler) AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler(com.facebook.presto.server.smile.AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler) ThriftHttpResponseHandler(com.facebook.presto.server.thrift.ThriftHttpResponseHandler) Request(com.facebook.airlift.http.client.Request) ThriftResponseHandler(com.facebook.airlift.http.client.thrift.ThriftResponseHandler) TaskStatus(com.facebook.presto.execution.TaskStatus) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 62 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project cassandra by apache.

the class SecondaryIndexManager method buildIndexesBlocking.

/**
 * Performs a blocking (re)indexing/recovery of the specified SSTables for the specified indexes.
 *
 * If the index doesn't support ALL {@link Index.LoadType} it performs a recovery {@link Index#getRecoveryTaskSupport()}
 * instead of a build {@link Index#getBuildTaskSupport()}
 *
 * @param sstables      the SSTables to be (re)indexed
 * @param indexes       the indexes to be (re)built for the specifed SSTables
 * @param isFullRebuild True if this method is invoked as a full index rebuild, false otherwise
 */
@SuppressWarnings({ "unchecked" })
private void buildIndexesBlocking(Collection<SSTableReader> sstables, Set<Index> indexes, boolean isFullRebuild) {
    if (indexes.isEmpty())
        return;
    // Mark all indexes as building: this step must happen first, because if any index can't be marked, the whole
    // process needs to abort
    markIndexesBuilding(indexes, isFullRebuild, false);
    // Build indexes in a try/catch, so that any index not marked as either built or failed will be marked as failed:
    final Set<Index> builtIndexes = Sets.newConcurrentHashSet();
    final Set<Index> unbuiltIndexes = Sets.newConcurrentHashSet();
    // Any exception thrown during index building that could be suppressed by the finally block
    Exception accumulatedFail = null;
    try {
        logger.info("Submitting index {} of {} for data in {}", isFullRebuild ? "recovery" : "build", indexes.stream().map(i -> i.getIndexMetadata().name).collect(Collectors.joining(",")), sstables.stream().map(SSTableReader::toString).collect(Collectors.joining(",")));
        // Group all building tasks
        Map<Index.IndexBuildingSupport, Set<Index>> byType = new HashMap<>();
        for (Index index : indexes) {
            IndexBuildingSupport buildOrRecoveryTask = isFullRebuild ? index.getBuildTaskSupport() : index.getRecoveryTaskSupport();
            Set<Index> stored = byType.computeIfAbsent(buildOrRecoveryTask, i -> new HashSet<>());
            stored.add(index);
        }
        // Schedule all index building tasks with a callback to mark them as built or failed
        List<Future<?>> futures = new ArrayList<>(byType.size());
        byType.forEach((buildingSupport, groupedIndexes) -> {
            SecondaryIndexBuilder builder = buildingSupport.getIndexBuildTask(baseCfs, groupedIndexes, sstables);
            final AsyncPromise<Object> build = new AsyncPromise<>();
            CompactionManager.instance.submitIndexBuild(builder).addCallback(new FutureCallback() {

                @Override
                public void onFailure(Throwable t) {
                    logAndMarkIndexesFailed(groupedIndexes, t, false);
                    unbuiltIndexes.addAll(groupedIndexes);
                    build.tryFailure(t);
                }

                @Override
                public void onSuccess(Object o) {
                    groupedIndexes.forEach(i -> markIndexBuilt(i, isFullRebuild));
                    logger.info("Index build of {} completed", getIndexNames(groupedIndexes));
                    builtIndexes.addAll(groupedIndexes);
                    build.trySuccess(o);
                }
            });
            futures.add(build);
        });
        // Finally wait for the index builds to finish and flush the indexes that built successfully
        FBUtilities.waitOnFutures(futures);
    } catch (Exception e) {
        accumulatedFail = e;
        throw e;
    } finally {
        try {
            // Fail any indexes that couldn't be marked
            Set<Index> failedIndexes = Sets.difference(indexes, Sets.union(builtIndexes, unbuiltIndexes));
            if (!failedIndexes.isEmpty()) {
                logAndMarkIndexesFailed(failedIndexes, accumulatedFail, false);
            }
            // Flush all built indexes with an aynchronous callback to log the success or failure of the flush
            flushIndexesBlocking(builtIndexes, new FutureCallback() {

                String indexNames = StringUtils.join(builtIndexes.stream().map(i -> i.getIndexMetadata().name).collect(Collectors.toList()), ',');

                @Override
                public void onFailure(Throwable ignored) {
                    logger.info("Index flush of {} failed", indexNames);
                }

                @Override
                public void onSuccess(Object ignored) {
                    logger.info("Index flush of {} completed", indexNames);
                }
            });
        } catch (Exception e) {
            if (accumulatedFail != null) {
                accumulatedFail.addSuppressed(e);
            } else {
                throw e;
            }
        }
    }
}
Also used : SSTableSet(org.apache.cassandra.db.lifecycle.SSTableSet) IndexTarget(org.apache.cassandra.cql3.statements.schema.IndexTarget) LoggerFactory(org.slf4j.LoggerFactory) org.apache.cassandra.db(org.apache.cassandra.db) TimeoutException(java.util.concurrent.TimeoutException) INotification(org.apache.cassandra.notifications.INotification) StringUtils(org.apache.commons.lang3.StringUtils) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) UnfilteredPartitionIterator(org.apache.cassandra.db.partitions.UnfilteredPartitionIterator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) org.apache.cassandra.index.transactions(org.apache.cassandra.index.transactions) INotificationConsumer(org.apache.cassandra.notifications.INotificationConsumer) ColumnFilter(org.apache.cassandra.db.filter.ColumnFilter) com.google.common.collect(com.google.common.collect) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) Longs(com.google.common.primitives.Longs) FBUtilities(org.apache.cassandra.utils.FBUtilities) SSTableAddedNotification(org.apache.cassandra.notifications.SSTableAddedNotification) ExecutorUtils.shutdown(org.apache.cassandra.utils.ExecutorUtils.shutdown) Collectors(java.util.stream.Collectors) Stream(java.util.stream.Stream) SinglePartitionPager(org.apache.cassandra.service.pager.SinglePartitionPager) IndexBuildingSupport(org.apache.cassandra.index.Index.IndexBuildingSupport) DataLimits(org.apache.cassandra.db.filter.DataLimits) Joiner(com.google.common.base.Joiner) java.util(java.util) CompactionManager(org.apache.cassandra.db.compaction.CompactionManager) PartitionUpdate(org.apache.cassandra.db.partitions.PartitionUpdate) ColumnMetadata(org.apache.cassandra.schema.ColumnMetadata) Callable(java.util.concurrent.Callable) Constructor(java.lang.reflect.Constructor) Function(java.util.function.Function) Indexes(org.apache.cassandra.schema.Indexes) org.apache.cassandra.db.rows(org.apache.cassandra.db.rows) Strings(com.google.common.base.Strings) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) JVMStabilityInspector(org.apache.cassandra.utils.JVMStabilityInspector) Logger(org.slf4j.Logger) RowFilter(org.apache.cassandra.db.filter.RowFilter) IndexMetadata(org.apache.cassandra.schema.IndexMetadata) Tracing(org.apache.cassandra.tracing.Tracing) ClusteringIndexSliceFilter(org.apache.cassandra.db.filter.ClusteringIndexSliceFilter) FutureCallback(com.google.common.util.concurrent.FutureCallback) ExecutorPlus(org.apache.cassandra.concurrent.ExecutorPlus) org.apache.cassandra.utils.concurrent(org.apache.cassandra.utils.concurrent) TimeUnit(java.util.concurrent.TimeUnit) CassandraIndex(org.apache.cassandra.index.internal.CassandraIndex) Global.executorFactory(org.apache.cassandra.concurrent.ExecutorFactory.Global.executorFactory) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ImmediateExecutor(org.apache.cassandra.concurrent.ImmediateExecutor) ExecutorUtils.awaitTermination(org.apache.cassandra.utils.ExecutorUtils.awaitTermination) View(org.apache.cassandra.db.lifecycle.View) SSTableSet(org.apache.cassandra.db.lifecycle.SSTableSet) CassandraIndex(org.apache.cassandra.index.internal.CassandraIndex) TimeoutException(java.util.concurrent.TimeoutException) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) SSTableReader(org.apache.cassandra.io.sstable.format.SSTableReader) IndexBuildingSupport(org.apache.cassandra.index.Index.IndexBuildingSupport) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 63 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project flink by apache.

the class FlinkKinesisProducer method open.

// --------------------------- Lifecycle methods ---------------------------
@Override
public void open(Configuration parameters) throws Exception {
    super.open(parameters);
    schema.open(RuntimeContextInitializationContextAdapters.serializationAdapter(getRuntimeContext(), metricGroup -> metricGroup.addGroup("user")));
    // check and pass the configuration properties
    KinesisProducerConfiguration producerConfig = KinesisConfigUtil.getValidatedProducerConfiguration(configProps);
    producer = getKinesisProducer(producerConfig);
    final MetricGroup kinesisMectricGroup = getRuntimeContext().getMetricGroup().addGroup(KINESIS_PRODUCER_METRIC_GROUP);
    this.backpressureCycles = kinesisMectricGroup.counter(METRIC_BACKPRESSURE_CYCLES);
    kinesisMectricGroup.gauge(METRIC_OUTSTANDING_RECORDS_COUNT, producer::getOutstandingRecordsCount);
    backpressureLatch = new TimeoutLatch();
    callback = new FutureCallback<UserRecordResult>() {

        @Override
        public void onSuccess(UserRecordResult result) {
            backpressureLatch.trigger();
            if (!result.isSuccessful()) {
                if (failOnError) {
                    // only remember the first thrown exception
                    if (thrownException == null) {
                        thrownException = new RuntimeException("Record was not sent successful");
                    }
                } else {
                    LOG.warn("Record was not sent successful");
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            backpressureLatch.trigger();
            if (failOnError) {
                thrownException = t;
            } else {
                LOG.warn("An exception occurred while processing a record", t);
            }
        }
    };
    if (this.customPartitioner != null) {
        this.customPartitioner.initialize(getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getNumberOfParallelSubtasks());
    }
    final RuntimeContext ctx = getRuntimeContext();
    ctx.registerUserCodeClassLoaderReleaseHookIfAbsent(KINESIS_PRODUCER_RELEASE_HOOK_NAME, () -> this.runClassLoaderReleaseHook(ctx.getUserCodeClassLoader()));
    LOG.info("Started Kinesis producer instance for region '{}'", producerConfig.getRegion());
}
Also used : MoreExecutors(com.google.common.util.concurrent.MoreExecutors) RuntimeContext(org.apache.flink.api.common.functions.RuntimeContext) KinesisSerializationSchema(org.apache.flink.streaming.connectors.kinesis.serialization.KinesisSerializationSchema) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) LoggerFactory(org.slf4j.LoggerFactory) PublicEvolving(org.apache.flink.annotation.PublicEvolving) RuntimeContextInitializationContextAdapters(org.apache.flink.api.common.serialization.RuntimeContextInitializationContextAdapters) FunctionSnapshotContext(org.apache.flink.runtime.state.FunctionSnapshotContext) KinesisProducerConfiguration(com.amazonaws.services.kinesis.producer.KinesisProducerConfiguration) ByteBuffer(java.nio.ByteBuffer) KinesisProducer(com.amazonaws.services.kinesis.producer.KinesisProducer) InstantiationUtil(org.apache.flink.util.InstantiationUtil) TimeoutLatch(org.apache.flink.streaming.connectors.kinesis.util.TimeoutLatch) Preconditions.checkNotNull(org.apache.flink.util.Preconditions.checkNotNull) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) Properties(java.util.Properties) CheckpointedFunction(org.apache.flink.streaming.api.checkpoint.CheckpointedFunction) FunctionInitializationContext(org.apache.flink.runtime.state.FunctionInitializationContext) Configuration(org.apache.flink.configuration.Configuration) KinesisConfigUtil(org.apache.flink.streaming.connectors.kinesis.util.KinesisConfigUtil) Field(java.lang.reflect.Field) FutureCallback(com.google.common.util.concurrent.FutureCallback) RichSinkFunction(org.apache.flink.streaming.api.functions.sink.RichSinkFunction) UserRecordFailedException(com.amazonaws.services.kinesis.producer.UserRecordFailedException) VisibleForTesting(org.apache.flink.annotation.VisibleForTesting) TimeUnit(java.util.concurrent.TimeUnit) MetricGroup(org.apache.flink.metrics.MetricGroup) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) Preconditions.checkArgument(org.apache.flink.util.Preconditions.checkArgument) AwsSdkMetrics(com.amazonaws.metrics.AwsSdkMetrics) Attempt(com.amazonaws.services.kinesis.producer.Attempt) UserRecordResult(com.amazonaws.services.kinesis.producer.UserRecordResult) Counter(org.apache.flink.metrics.Counter) SerializationSchema(org.apache.flink.api.common.serialization.SerializationSchema) KinesisProducerConfiguration(com.amazonaws.services.kinesis.producer.KinesisProducerConfiguration) TimeoutLatch(org.apache.flink.streaming.connectors.kinesis.util.TimeoutLatch) MetricGroup(org.apache.flink.metrics.MetricGroup) UserRecordResult(com.amazonaws.services.kinesis.producer.UserRecordResult) RuntimeContext(org.apache.flink.api.common.functions.RuntimeContext)

Example 64 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project genius by opendaylight.

the class AlivenessMonitor method monitorStart.

@Override
public Future<RpcResult<MonitorStartOutput>> monitorStart(MonitorStartInput input) {
    RpcResultBuilder<MonitorStartOutput> rpcResultBuilder;
    final Config in = input.getConfig();
    Long profileId = in.getProfileId();
    LOG.debug("Monitor Start invoked with Config: {}, Profile Id: {}", in, profileId);
    try {
        if (in.getMode() != MonitoringMode.OneOne) {
            throw new UnsupportedConfigException("Unsupported Monitoring mode. Currently one-one mode is supported");
        }
        Optional<MonitorProfile> optProfile = SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker, LogicalDatastoreType.OPERATIONAL, getMonitorProfileId(profileId));
        final MonitorProfile profile;
        if (!optProfile.isPresent()) {
            String errMsg = String.format("No monitoring profile associated with Id: %d", profileId);
            LOG.error("Monitor start failed. {}", errMsg);
            throw new RuntimeException(errMsg);
        } else {
            profile = optProfile.get();
        }
        final EtherTypes ethType = profile.getProtocolType();
        String interfaceName = null;
        EndpointType srcEndpointType = in.getSource().getEndpointType();
        if (srcEndpointType instanceof Interface) {
            Interface endPoint = (Interface) srcEndpointType;
            interfaceName = endPoint.getInterfaceName();
        } else {
            throw new UnsupportedConfigException("Unsupported source Endpoint type. Only Interface Endpoint currently supported for monitoring");
        }
        if (Strings.isNullOrEmpty(interfaceName)) {
            throw new RuntimeException("Interface Name not defined in the source Endpoint");
        }
        // Initially the support is for one monitoring per interface.
        // Revisit the retrieving monitor id logic when the multiple
        // monitoring for same interface is needed.
        EndpointType destEndpointType = null;
        if (in.getDestination() != null) {
            destEndpointType = in.getDestination().getEndpointType();
        }
        String idKey = getUniqueKey(interfaceName, ethType.toString(), srcEndpointType, destEndpointType);
        final long monitorId = getUniqueId(idKey);
        Optional<MonitoringInfo> optKey = SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker, LogicalDatastoreType.OPERATIONAL, getMonitoringInfoId(monitorId));
        final AlivenessProtocolHandler<?> handler;
        if (optKey.isPresent()) {
            String message = String.format("Monitoring for the interface %s with this configuration " + "is already registered.", interfaceName);
            LOG.warn("Monitoring for the interface {} with this configuration is already registered.", interfaceName);
            MonitorStartOutput output = new MonitorStartOutputBuilder().setMonitorId(monitorId).build();
            rpcResultBuilder = RpcResultBuilder.success(output).withWarning(ErrorType.APPLICATION, "config-exists", message);
            return Futures.immediateFuture(rpcResultBuilder.build());
        } else {
            // Construct the monitor key
            final MonitoringInfo monitoringInfo = new MonitoringInfoBuilder().setId(monitorId).setMode(in.getMode()).setProfileId(profileId).setDestination(in.getDestination()).setSource(in.getSource()).build();
            // Construct the initial monitor state
            handler = alivenessProtocolHandlerRegistry.get(ethType);
            final String monitoringKey = handler.getUniqueMonitoringKey(monitoringInfo);
            MonitoringStateBuilder monitoringStateBuilder = new MonitoringStateBuilder().setMonitorKey(monitoringKey).setMonitorId(monitorId).setState(LivenessState.Unknown).setStatus(MonitorStatus.Started);
            if (ethType != EtherTypes.Bfd) {
                monitoringStateBuilder.setRequestCount(INITIAL_COUNT).setResponsePendingCount(INITIAL_COUNT);
            }
            MonitoringState monitoringState = monitoringStateBuilder.build();
            Futures.addCallback(txRunner.callWithNewWriteOnlyTransactionAndSubmit(tx -> {
                tx.put(LogicalDatastoreType.OPERATIONAL, getMonitoringInfoId(monitorId), monitoringInfo, CREATE_MISSING_PARENT);
                LOG.debug("adding oper monitoring info {}", monitoringInfo);
                tx.put(LogicalDatastoreType.OPERATIONAL, getMonitorStateId(monitoringKey), monitoringState, CREATE_MISSING_PARENT);
                LOG.debug("adding oper monitoring state {}", monitoringState);
                MonitoridKeyEntry mapEntry = new MonitoridKeyEntryBuilder().setMonitorId(monitorId).setMonitorKey(monitoringKey).build();
                tx.put(LogicalDatastoreType.OPERATIONAL, getMonitorMapId(monitorId), mapEntry, CREATE_MISSING_PARENT);
                LOG.debug("adding oper map entry {}", mapEntry);
            }), new FutureCallback<Void>() {

                @Override
                public void onFailure(Throwable error) {
                    String errorMsg = String.format("Adding Monitoring info: %s in Datastore failed", monitoringInfo);
                    LOG.warn("Adding Monitoring info: {} in Datastore failed", monitoringInfo, error);
                    throw new RuntimeException(errorMsg, error);
                }

                @Override
                public void onSuccess(Void noarg) {
                    lockMap.put(monitoringKey, new Semaphore(1, true));
                    if (ethType == EtherTypes.Bfd) {
                        handler.startMonitoringTask(monitoringInfo);
                        return;
                    }
                    // Schedule task
                    LOG.debug("Scheduling monitor task for config: {}", in);
                    scheduleMonitoringTask(monitoringInfo, profile.getMonitorInterval());
                }
            }, callbackExecutorService);
        }
        associateMonitorIdWithInterface(monitorId, interfaceName);
        MonitorStartOutput output = new MonitorStartOutputBuilder().setMonitorId(monitorId).build();
        rpcResultBuilder = RpcResultBuilder.success(output);
    } catch (UnsupportedConfigException e) {
        LOG.error("Start Monitoring Failed. ", e);
        rpcResultBuilder = RpcResultBuilder.<MonitorStartOutput>failed().withError(ErrorType.APPLICATION, e.getMessage(), e);
    }
    return Futures.immediateFuture(rpcResultBuilder.build());
}
Also used : IpAddress(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.endpoint.endpoint.type.IpAddress) LoadingCache(com.google.common.cache.LoadingCache) EventData(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.event.EventData) PacketInReason(org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketInReason) EventDataBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.event.EventDataBuilder) Future(java.util.concurrent.Future) MonitoringInfo(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.configs.MonitoringInfo) Optional(com.google.common.base.Optional) MonitoringState(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitoring.states.MonitoringState) CreateIdPoolInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInput) ReleaseIdInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInput) Ethernet(org.opendaylight.genius.mdsalutil.packet.Ethernet) InterfaceMonitorEntry(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411._interface.monitor.map.InterfaceMonitorEntry) ErrorType(org.opendaylight.yangtools.yang.common.RpcError.ErrorType) AlivenessProtocolHandler(org.opendaylight.genius.alivenessmonitor.protocols.AlivenessProtocolHandler) Executors(java.util.concurrent.Executors) DataBroker(org.opendaylight.controller.md.sal.binding.api.DataBroker) MonitorProfileCreateOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorProfileCreateOutput) Predicate(com.google.common.base.Predicate) AlivenessMonitorService(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.AlivenessMonitorService) MonitorUnpauseInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorUnpauseInput) InterfaceMonitorEntryKey(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411._interface.monitor.map.InterfaceMonitorEntryKey) InterfaceMonitorEntryBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411._interface.monitor.map.InterfaceMonitorEntryBuilder) MonitorProfileGetOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorProfileGetOutput) MonitoringStateBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitoring.states.MonitoringStateBuilder) Interface(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.endpoint.endpoint.type.Interface) MonitorProfileDeleteInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorProfileDeleteInput) PacketReceived(org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived) ReadWriteTransaction(org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction) AllocateIdOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput) MonitorStatus(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorStatus) ArrayList(java.util.ArrayList) AlivenessProtocolHandlerRegistry(org.opendaylight.genius.alivenessmonitor.protocols.AlivenessProtocolHandlerRegistry) Strings(com.google.common.base.Strings) MonitorProfileCreateOutputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorProfileCreateOutputBuilder) MonitorEventBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorEventBuilder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MonitorPauseInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorPauseInput) EtherTypes(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.EtherTypes) AlivenessMonitorUtil.getInterfaceMonitorMapId(org.opendaylight.genius.alivenessmonitor.internal.AlivenessMonitorUtil.getInterfaceMonitorMapId) FutureCallback(com.google.common.util.concurrent.FutureCallback) ExecutionException(java.util.concurrent.ExecutionException) MonitorStopInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorStopInput) Futures(com.google.common.util.concurrent.Futures) MonitorStartInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorStartInput) MonitoringMode(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitoringMode) Preconditions(com.google.common.base.Preconditions) MonitorProfileGetInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorProfileGetInput) PacketException(org.opendaylight.openflowplugin.libraries.liblldp.PacketException) AlivenessMonitorUtil.getMonitorProfileId(org.opendaylight.genius.alivenessmonitor.internal.AlivenessMonitorUtil.getMonitorProfileId) MonitorProfileCreateInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorProfileCreateInput) SingleTransactionDataBroker(org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker) ScheduledFuture(java.util.concurrent.ScheduledFuture) MonitoridKeyEntry(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitorid.key.map.MonitoridKeyEntry) LoggerFactory(org.slf4j.LoggerFactory) NotificationPublishService(org.opendaylight.controller.md.sal.binding.api.NotificationPublishService) SettableFuture(com.google.common.util.concurrent.SettableFuture) MonitorEvent(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorEvent) ThreadFactoryProvider(org.opendaylight.infrautils.utils.concurrent.ThreadFactoryProvider) PreDestroy(javax.annotation.PreDestroy) MonitoringInfoBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.configs.MonitoringInfoBuilder) ManagedNewTransactionRunner(org.opendaylight.genius.infra.ManagedNewTransactionRunner) AlivenessMonitorUtil.getMonitoringInfoId(org.opendaylight.genius.alivenessmonitor.internal.AlivenessMonitorUtil.getMonitoringInfoId) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LogicalDatastoreType(org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType) Packet(org.opendaylight.openflowplugin.libraries.liblldp.Packet) AlivenessMonitorUtil.getMonitorMapId(org.opendaylight.genius.alivenessmonitor.internal.AlivenessMonitorUtil.getMonitorMapId) AllocateIdInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput) CacheLoader(com.google.common.cache.CacheLoader) List(java.util.List) EndpointType(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.endpoint.EndpointType) CacheBuilder(com.google.common.cache.CacheBuilder) MonitorStartOutputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorStartOutputBuilder) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) PacketProcessingListener(org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingListener) LivenessState(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.LivenessState) MonitorProfileGetOutputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorProfileGetOutputBuilder) Singleton(javax.inject.Singleton) JdkFutureAdapters(com.google.common.util.concurrent.JdkFutureAdapters) NetUtils(org.opendaylight.openflowplugin.libraries.liblldp.NetUtils) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) ReadOnlyTransaction(org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction) SendToController(org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.SendToController) CreateIdPoolInputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.CreateIdPoolInputBuilder) Profile(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.profile.create.input.Profile) ManagedNewTransactionRunnerImpl(org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl) Config(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.start.input.Config) Nonnull(javax.annotation.Nonnull) ExecutorService(java.util.concurrent.ExecutorService) MonitoridKeyEntryBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitorid.key.map.MonitoridKeyEntryBuilder) Logger(org.slf4j.Logger) Semaphore(java.util.concurrent.Semaphore) MonitorStartOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorStartOutput) ReleaseIdInputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.ReleaseIdInputBuilder) MonitorProfile(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.profiles.MonitorProfile) IdManagerService(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService) TimeUnit(java.util.concurrent.TimeUnit) MonitorProfileBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.profiles.MonitorProfileBuilder) RpcResultBuilder(org.opendaylight.yangtools.yang.common.RpcResultBuilder) AllocateIdInputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder) Collections(java.util.Collections) AlivenessMonitorUtil.getMonitorStateId(org.opendaylight.genius.alivenessmonitor.internal.AlivenessMonitorUtil.getMonitorStateId) Config(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.start.input.Config) MonitoringStateBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitoring.states.MonitoringStateBuilder) MonitoringInfoBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.configs.MonitoringInfoBuilder) Semaphore(java.util.concurrent.Semaphore) EtherTypes(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.EtherTypes) MonitoringState(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitoring.states.MonitoringState) MonitorStartOutputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorStartOutputBuilder) EndpointType(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.endpoint.EndpointType) MonitorStartOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.MonitorStartOutput) MonitoringInfo(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.configs.MonitoringInfo) MonitorProfile(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.profiles.MonitorProfile) MonitoridKeyEntryBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitorid.key.map.MonitoridKeyEntryBuilder) Interface(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.endpoint.endpoint.type.Interface) MonitoridKeyEntry(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitorid.key.map.MonitoridKeyEntry)

Example 65 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project genius by opendaylight.

the class AlivenessMonitor method resumeMonitoring.

private void resumeMonitoring(final long monitorId) {
    final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction();
    ListenableFuture<Optional<MonitoringInfo>> readInfoResult = tx.read(LogicalDatastoreType.OPERATIONAL, getMonitoringInfoId(monitorId));
    Futures.addCallback(readInfoResult, new FutureCallback<Optional<MonitoringInfo>>() {

        @Override
        public void onFailure(Throwable error) {
            String msg = String.format("Unable to read monitoring info associated with monitor id %d", monitorId);
            LOG.error("Monitor resume Failed. {}", msg, error);
            tx.close();
        }

        @Override
        public void onSuccess(@Nonnull Optional<MonitoringInfo> optInfo) {
            if (optInfo.isPresent()) {
                final MonitoringInfo info = optInfo.get();
                ListenableFuture<Optional<MonitorProfile>> readProfile = tx.read(LogicalDatastoreType.OPERATIONAL, getMonitorProfileId(info.getProfileId()));
                Futures.addCallback(readProfile, new FutureCallback<Optional<MonitorProfile>>() {

                    @Override
                    public void onFailure(Throwable error) {
                        String msg = String.format("Unable to read Monitoring profile associated with id %d", info.getProfileId());
                        LOG.warn("Monitor resume Failed. {}", msg, error);
                        tx.close();
                    }

                    @Override
                    public void onSuccess(@Nonnull Optional<MonitorProfile> optProfile) {
                        tx.close();
                        if (optProfile.isPresent()) {
                            updateMonitorStatusTo(monitorId, MonitorStatus.Started, currentStatus -> currentStatus != MonitorStatus.Started);
                            MonitorProfile profile = optProfile.get();
                            LOG.debug("Monitor Resume - Scheduling monitoring task for Id: {}", monitorId);
                            scheduleMonitoringTask(info, profile.getMonitorInterval());
                        } else {
                            String msg = String.format("Monitoring profile associated with id %d is not present", info.getProfileId());
                            LOG.warn("Monitor resume Failed. {}", msg);
                        }
                    }
                }, MoreExecutors.directExecutor());
            } else {
                tx.close();
                String msg = String.format("Monitoring info associated with id %d is not present", monitorId);
                LOG.warn("Monitor resume Failed. {}", msg);
            }
        }
    }, MoreExecutors.directExecutor());
}
Also used : Optional(com.google.common.base.Optional) MonitoringInfo(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.configs.MonitoringInfo) Nonnull(javax.annotation.Nonnull) MonitorProfile(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.alivenessmonitor.rev160411.monitor.profiles.MonitorProfile) ReadOnlyTransaction(org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Aggregations

FutureCallback (com.google.common.util.concurrent.FutureCallback)70 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)33 List (java.util.List)33 ArrayList (java.util.ArrayList)27 Futures (com.google.common.util.concurrent.Futures)24 Logger (org.slf4j.Logger)19 LoggerFactory (org.slf4j.LoggerFactory)19 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)18 IOException (java.io.IOException)18 Set (java.util.Set)17 Collections (java.util.Collections)16 Map (java.util.Map)16 TimeUnit (java.util.concurrent.TimeUnit)16 Optional (com.google.common.base.Optional)15 ExecutionException (java.util.concurrent.ExecutionException)15 Nonnull (javax.annotation.Nonnull)15 Nullable (javax.annotation.Nullable)15 Collection (java.util.Collection)13 Future (java.util.concurrent.Future)13 Collectors (java.util.stream.Collectors)12