com.google.common.util.concurrent.FluentFuture Java Examples

The following examples show how to use com.google.common.util.concurrent.FluentFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractPeer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
final synchronized FluentFuture<? extends CommitInfo> removePeer(final @Nullable YangInstanceIdentifier peerPath) {
    if (peerPath == null) {
        return CommitInfo.emptyFluentFuture();
    }
    LOG.info("Closed per Peer {} removed", peerPath);
    final DOMDataTreeWriteTransaction tx = this.domChain.newWriteOnlyTransaction();
    tx.delete(LogicalDatastoreType.OPERATIONAL, peerPath);
    final FluentFuture<? extends CommitInfo> future = tx.commit();
    future.addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.debug("Peer {} removed", peerPath);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("Failed to remove Peer {}", peerPath, throwable);
        }
    }, MoreExecutors.directExecutor());
    return future;
}
 
Example #2
Source File: AbstractTopologyBuilder.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Destroy the current operational topology data. Note a valid transaction must be provided.
 */
private synchronized FluentFuture<? extends CommitInfo> destroyOperationalTopology() {
    requireNonNull(this.chain, "A valid transaction chain must be provided.");
    final WriteTransaction trans = this.chain.newWriteOnlyTransaction();
    trans.delete(LogicalDatastoreType.OPERATIONAL, getInstanceIdentifier());
    final FluentFuture<? extends CommitInfo> future = trans.commit();
    future.addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.trace("Operational topology removed {}", AbstractTopologyBuilder.this.topology);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("Unable to reset operational topology {} (transaction {})",
                AbstractTopologyBuilder.this.topology, trans.getIdentifier(), throwable);
        }
    }, MoreExecutors.directExecutor());
    clearTopology();
    return future;
}
 
Example #3
Source File: ApplicationPeer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized FluentFuture<? extends CommitInfo> close() {
    setActive(false);
    if (this.registration != null) {
        this.registration.close();
        this.registration = null;
    }
    if (this.adjRibInWriter != null) {
        this.adjRibInWriter.releaseChain();
    }
    if (this.effectiveRibInWriter != null) {
        this.effectiveRibInWriter.close();
    }
    final FluentFuture<? extends CommitInfo> future;
    future = removePeer(this.peerPath);
    closeDomChain();
    if (this.trackerRegistration != null) {
        this.trackerRegistration.close();
        this.trackerRegistration = null;
    }
    return future;
}
 
Example #4
Source File: BmpMonitoringStationImpl.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
    LOG.info("BMP Monitor Singleton Service {} instance closed, Monitor Id {}",
            getIdentifier().getName(), this.monitorId.getValue());
    if (this.channel != null) {
        this.channel.close().addListener((ChannelFutureListener) future -> {
            Preconditions.checkArgument(future.isSuccess(),
                    "Channel failed to close: %s", future.cause());
            BmpMonitoringStationImpl.this.sessionManager.close();
        });
    }

    final DOMDataTreeWriteTransaction wTx = this.domDataBroker.newWriteOnlyTransaction();
    wTx.delete(LogicalDatastoreType.OPERATIONAL, this.yangMonitorId);
    LOG.info("BMP monitoring station {} closed.", this.monitorId.getValue());
    return wTx.commit();
}
 
Example #5
Source File: AdjRibInWriter.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
void removeRoutes(final MpUnreachNlri nlri) {
    final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
    final TableContext ctx = this.tables.get(key);
    if (ctx == null) {
        LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
        return;
    }
    LOG.trace("Removing routes {}", nlri);
    final DOMDataTreeWriteTransaction tx = this.chain.getDomChain().newWriteOnlyTransaction();
    ctx.removeRoutes(tx, nlri);
    final FluentFuture<? extends CommitInfo> future = tx.commit();
    this.submitted = future;
    future.addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.trace("Removing routes {}, succeed", nlri);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("Removing routes failed", throwable);
        }
    }, MoreExecutors.directExecutor());
}
 
Example #6
Source File: BGPPeer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized FluentFuture<? extends CommitInfo> releaseConnection() {
    LOG.info("Closing session with peer");
    this.sessionUp = false;
    this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close);
    this.adjRibOutListenerSet.clear();
    final FluentFuture<? extends CommitInfo> future;
    if (!isRestartingGracefully()) {
        future = terminateConnection();
    } else {
        final Set<TablesKey> gracefulTables = getGracefulTables();
        this.ribWriter.storeStaleRoutes(gracefulTables);
        future = this.ribWriter.clearTables(Sets.difference(this.tables, gracefulTables));
        if (isPeerRestarting()) {
            this.peerRestartStopwatch = Stopwatch.createStarted();
            handleRestartTimer();
        }
    }
    releaseBindingChain();

    closeSession();
    return future;
}
 
Example #7
Source File: BGPPeer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized FluentFuture<? extends CommitInfo> terminateConnection() {
    final FluentFuture<? extends CommitInfo> future;
    if (this.trackerRegistration != null) {
        this.trackerRegistration.close();
        this.trackerRegistration = null;
    }
    if (this.rpcRegistration != null) {
        this.rpcRegistration.close();
    }
    this.ribWriter.releaseChain();

    if (this.effRibInWriter != null) {
        this.effRibInWriter.close();
    }
    this.tables = ImmutableSet.of();
    this.addPathTableMaps = Collections.emptyMap();
    future = removePeer(this.peerPath);
    resetState();

    return future;
}
 
Example #8
Source File: ConnectedGraphServer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Destroy the current operational topology data. Note a valid transaction must be provided.
 */
private synchronized FluentFuture<? extends CommitInfo> destroyOperationalGraphModel() {
    requireNonNull(this.chain, "A valid transaction chain must be provided.");
    final WriteTransaction trans = this.chain.newWriteOnlyTransaction();
    trans.delete(LogicalDatastoreType.OPERATIONAL, this.graphTopologyIdentifier);
    trans.delete(LogicalDatastoreType.CONFIGURATION, this.graphTopologyIdentifier);
    final FluentFuture<? extends CommitInfo> future = trans.commit();
    future.addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.trace("Operational GraphModel removed {}", ConnectedGraphServer.this.graphTopologyIdentifier);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("Unable to reset operational GraphModel {} (transaction {})",
                    ConnectedGraphServer.this.graphTopologyIdentifier, trans.getIdentifier(), throwable);
        }
    }, MoreExecutors.directExecutor());

    /* Clear Connected Graph */
    for (ConnectedGraph graph : graphs.values()) {
        ((ConnectedGraphImpl) graph).clear();
    }
    return future;
}
 
Example #9
Source File: Utils.java    From bazel with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ProtoParseWithRegistry")
public static ListenableFuture<ActionResult> downloadAsActionResult(
    ActionKey actionDigest,
    BiFunction<Digest, OutputStream, ListenableFuture<Void>> downloadFunction) {
  ByteArrayOutputStream data = new ByteArrayOutputStream(/* size= */ 1024);
  ListenableFuture<Void> download = downloadFunction.apply(actionDigest.getDigest(), data);
  return FluentFuture.from(download)
      .transformAsync(
          (v) -> {
            try {
              return Futures.immediateFuture(ActionResult.parseFrom(data.toByteArray()));
            } catch (InvalidProtocolBufferException e) {
              return Futures.immediateFailedFuture(e);
            }
          },
          MoreExecutors.directExecutor())
      .catching(CacheNotFoundException.class, (e) -> null, MoreExecutors.directExecutor());
}
 
Example #10
Source File: MdsalUtilsAsync.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Executes read as non blocking transaction and assign a default callback
 * to close the transaction.
 *
 * @param store
 *            {@link LogicalDatastoreType} to read
 * @param path
 *            {@link InstanceIdentifier} for path to read
 * @param <D>
 *            The data object type
 * @return The {@link FluentFuture} object to which you can assign a
 *         callback
 */
public <D extends DataObject> FluentFuture<Optional<D>> read(
                                    final LogicalDatastoreType store,
                                    final InstanceIdentifier<D> path)  {
    final ReadTransaction transaction = databroker.newReadOnlyTransaction();
    final FluentFuture<Optional<D>> future = transaction.read(store, path);
    final FutureCallback<Optional<D>> closeTransactionCallback = new FutureCallback<Optional<D>>() {
        @Override
        public void onSuccess(final Optional<D> result) {
            transaction.close();
        }

        @Override
        public void onFailure(final Throwable ex) {
            transaction.close();
        }
    };
    future.addCallback(closeTransactionCallback, MoreExecutors.directExecutor());
    return future;
}
 
Example #11
Source File: MdsalUtils.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public boolean exists(
    final LogicalDatastoreType store, final InstanceIdentifier<? extends DataObject> path) {
    int trialNo = 0;
    ReadTransaction transaction = databroker.newReadOnlyTransaction();
    do {
        try {
            FluentFuture<Boolean> result = transaction.exists(store, path);
            transaction.close();
            return result.get().booleanValue();
        } catch (InterruptedException | ExecutionException e) {
            if (trialNo == 0) {
                logReadFailureError(path, " mdsal Read failed exception retrying the read after sleep");
            }
            try {
                transaction.close();
                Thread.sleep(MDSAL_READ_SLEEP_INTERVAL_MS);
                transaction = databroker.newReadOnlyTransaction();
            } catch (InterruptedException e1) {
                logReadFailureError(path, " Sleep interrupted");
            }
        }
    } while (trialNo++ < MDSAL_MAX_READ_TRIALS);
    logReadFailureError(path, " All read trials exceeded");
    return false;
}
 
Example #12
Source File: OvsdbConnectionManager.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public OvsdbConnectionInstance getConnectionInstance(final InstanceIdentifier<Node> nodePath) {
    if (nodeIdVsConnectionInstance.get(nodePath) != null) {
        return nodeIdVsConnectionInstance.get(nodePath);
    }
    try {
        ReadTransaction transaction = db.newReadOnlyTransaction();
        FluentFuture<Optional<Node>> nodeFuture = transaction.read(
                LogicalDatastoreType.OPERATIONAL, nodePath);
        transaction.close();
        Optional<Node> optional = nodeFuture.get();
        if (optional.isPresent()) {
            return this.getConnectionInstance(optional.get());
        } else {
            LOG.debug("Node was not found on the path in the operational DS: {}", nodePath);
            return null;
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
        return null;
    }
}
 
Example #13
Source File: SouthboundProvider.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
private void initializeOvsdbTopology(final LogicalDatastoreType type) {
    InstanceIdentifier<Topology> path = InstanceIdentifier
            .create(NetworkTopology.class)
            .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
    ReadWriteTransaction transaction = db.newReadWriteTransaction();
    FluentFuture<Boolean> ovsdbTp = transaction.exists(type, path);
    try {
        if (!ovsdbTp.get().booleanValue()) {
            TopologyBuilder tpb = new TopologyBuilder();
            tpb.setTopologyId(SouthboundConstants.OVSDB_TOPOLOGY_ID);
            transaction.mergeParentStructurePut(type, path, tpb.build());
            transaction.commit();
        } else {
            transaction.cancel();
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Error initializing ovsdb topology", e);
    }
}
 
Example #14
Source File: BridgeConfigReconciliationTaskTest.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    NodeKey nodeKey = new NodeKey(new NodeId(new Uri(NODE_ID)));

    iid = SouthboundMapper.createInstanceIdentifier(nodeKey.getNodeId());
    SouthboundProvider.setBridgesReconciliationInclusionList(Arrays.asList(BR_INT));
    Node brIntNode = createBridgeNode(NODE_ID + "/bridge/" + BR_INT);
    Optional<Node> nodeOptional = Optional.of(brIntNode);
    FluentFuture<Optional<Node>> readNodeFuture =
            FluentFutures.immediateFluentFuture(nodeOptional);
    when(reconciliationManager.getDb()).thenReturn(db);
    ReadTransaction tx = mock(ReadTransaction.class);
    Mockito.when(db.newReadOnlyTransaction()).thenReturn(tx);
    Mockito.when(tx.read(any(LogicalDatastoreType.class),any(InstanceIdentifier.class)))
            .thenReturn(readNodeFuture);

    when(topology.getNode()).thenReturn(Map.of(brIntNode.key(), brIntNode));

    configurationReconciliationTask =
            new BridgeConfigReconciliationTask(reconciliationManager, ovsdbConnectionManager, iid,
                    ovsdbConnectionInstance, mock(InstanceIdentifierCodec.class));
}
 
Example #15
Source File: OvsdbConnectionManagerTest.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testConnected() throws Exception {
    OvsdbConnectionInstance client = mock(OvsdbConnectionInstance.class);
    suppress(MemberMatcher.method(OvsdbConnectionManager.class, "connectedButCallBacksNotRegistered",
            OvsdbClient.class));
    when(ovsdbConnManager.connectedButCallBacksNotRegistered(any(OvsdbClient.class))).thenReturn(client);
    doNothing().when(client).registerCallbacks(any());

    //TODO: Write unit tests for EntityOwnershipService
    when(client.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class));
    field(OvsdbConnectionManager.class, "entityConnectionMap").set(ovsdbConnManager, entityConnectionMap);
    suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getEntityFromConnectionInstance",
            OvsdbConnectionInstance.class));

    //TODO: Write unit tests for entity ownership service related code.
    suppress(MemberMatcher.method(OvsdbConnectionManager.class, "registerEntityForOwnership",
            OvsdbConnectionInstance.class));

    ReadTransaction tx = mock(ReadTransaction.class);
    when(db.newReadOnlyTransaction()).thenReturn(tx);
    when(tx.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class)))
            .thenReturn(mock(FluentFuture.class));
    when(client.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class));

    ovsdbConnManager.connected(externalClient);
}
 
Example #16
Source File: HwvtepSouthboundProvider.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
private void initializeHwvtepTopology(final LogicalDatastoreType type) {
    InstanceIdentifier<Topology> path = InstanceIdentifier
            .create(NetworkTopology.class)
            .child(Topology.class, new TopologyKey(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID));
    ReadWriteTransaction transaction = dataBroker.newReadWriteTransaction();
    FluentFuture<Boolean> hwvtepTp = transaction.exists(type, path);
    try {
        if (!hwvtepTp.get().booleanValue()) {
            TopologyBuilder tpb = new TopologyBuilder();
            tpb.setTopologyId(HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID);
            transaction.mergeParentStructurePut(type, path, tpb.build());
            transaction.commit();
        } else {
            transaction.cancel();
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Error initializing hwvtep topology", e);
    }
}
 
Example #17
Source File: TransactionInvokerImpl.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized void executeCommand(final TransactionCommand command) {
    final ReadWriteTransaction transaction = chain.newReadWriteTransaction();
    transactionInFlight = transaction;
    recordPendingTransaction(command, transaction);
    command.execute(transaction);
    FluentFuture<?> ft = transaction.commit();
    command.setTransactionResultFuture(ft);
    ft.addCallback(new FutureCallback<Object>() {
        @Override
        public void onSuccess(final Object result) {
            forgetSuccessfulTransaction(transaction);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            // NOOP - handled by failure of transaction chain
        }
    }, MoreExecutors.directExecutor());
}
 
Example #18
Source File: MdsalUtils.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Executes put as a blocking transaction.
 *
 * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
 * @param path {@link InstanceIdentifier} for path to read
 * @param <D> the data object type
 * @return the result of the request
 */
public <D extends DataObject> boolean put(
        final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, D data)  {
    boolean result = false;
    final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
    transaction.mergeParentStructurePut(logicalDatastoreType, path, data);
    FluentFuture<? extends CommitInfo> future = transaction.commit();
    try {
        future.get();
        result = true;
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Failed to put {} ", path, e);
    }
    return result;
}
 
Example #19
Source File: ServerSessionManager.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
    if (this.isClosed.getAndSet(true)) {
        LOG.error("Session Manager has already been closed.");
        return CommitInfo.emptyFluentFuture();
    }
    for (final TopologySessionListener node : this.nodes.values()) {
        node.close();
    }
    this.nodes.clear();
    for (final TopologyNodeState topologyNodeState : this.state.values()) {
        topologyNodeState.close();
    }
    this.state.clear();

    final WriteTransaction t = this.dependenciesProvider.getDataBroker().newWriteOnlyTransaction();
    t.delete(LogicalDatastoreType.OPERATIONAL, this.topology);
    final FluentFuture<? extends CommitInfo> future = t.commit();
    future.addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.debug("Topology {} removed", ServerSessionManager.this.topology);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.warn("Failed to remove Topology {}", ServerSessionManager.this.topology, throwable);
        }
    }, MoreExecutors.directExecutor());
    return future;
}
 
Example #20
Source File: MdsalUtilsAsync.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Executes merge as non blocking transaction and return the future.
 *
 * @param logicalDatastoreType
 *            {@link LogicalDatastoreType} which should be modified
 * @param path
 *            {@link InstanceIdentifier} for path to read
 * @param <D>
 *            The data object type
 * @param withParent
 *            Whether or not to create missing parent.
 * @return The {@link FluentFuture} object to which you can assign a
 *         callback
 */
// FIXME: eliminate the boolean flag here to separate out the distinct code paths
public <D extends DataObject> FluentFuture<? extends CommitInfo> merge(
                                    final LogicalDatastoreType logicalDatastoreType,
                                    final InstanceIdentifier<D> path,
                                    final D data,
                                    final boolean withParent)  {
    final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
    if (withParent) {
        transaction.mergeParentStructureMerge(logicalDatastoreType, path, data);
    } else {
        transaction.merge(logicalDatastoreType, path, data);
    }
    return transaction.commit();
}
 
Example #21
Source File: MdsalUtils.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Executes merge as a blocking transaction.
 *
 * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
 * @param path {@link InstanceIdentifier} for path to read
 * @param <D> the data object type
 * @return the result of the request
 */
public <D extends DataObject> boolean merge(
        final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, D data)  {
    boolean result = false;
    final WriteTransaction transaction = databroker.newWriteOnlyTransaction();
    transaction.mergeParentStructureMerge(logicalDatastoreType, path, data);
    FluentFuture<? extends CommitInfo> future = transaction.commit();
    try {
        future.get();
        result = true;
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Failed to merge {} ", path, e);
    }
    return result;
}
 
Example #22
Source File: MdsalUtilsAsyncTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testMerge() {
    final String operationDesc = "testMerge";
    final SupportingNode supportingNodeBuilder1 = new SupportingNodeBuilder().withKey(
            new SupportingNodeKey(new NodeId("id1"), TOPOLOGY_TEST)).build();
    final SupportingNode supportingNodeBuilder2 = new SupportingNodeBuilder().withKey(
            new SupportingNodeKey(new NodeId("id2"), TOPOLOGY_TEST)).build();

    final Node data1 = new NodeBuilder(DATA).setSupportingNode(
            Collections.singletonList(supportingNodeBuilder1)).build();
    final Node data2 = new NodeBuilder(DATA).setSupportingNode(
            Collections.singletonList(supportingNodeBuilder2)).build();

    mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data1, operationDesc, true);
    assertEquals(data1, readDS());

    final FluentFuture<? extends CommitInfo> future =
            mdsalUtilsAsync.merge(LogicalDatastoreType.CONFIGURATION, TEST_IID, data2, true);
    future.addCallback(new FutureCallback<CommitInfo>() {

        @Override
        public void onSuccess(final CommitInfo result) {
            assertEquals(2, readDS().getSupportingNode().size());
        }

        @Override
        public void onFailure(final Throwable ex) {
            fail(ex.getMessage());
        }
    }, MoreExecutors.directExecutor());
}
 
Example #23
Source File: MdsalUtilsAsyncTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testRead() {
    final FluentFuture<? extends CommitInfo> fut =
            mdsalUtilsAsync.put(LogicalDatastoreType.CONFIGURATION, TEST_IID, DATA);

    fut.addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            final FluentFuture<Optional<Node>> future =
                    mdsalUtilsAsync.read(LogicalDatastoreType.CONFIGURATION, TEST_IID);
            Optional<Node> optNode;
            try {
                optNode = future.get();
                if (optNode.isPresent()) {
                    assertEquals(DATA, optNode.get());
                } else {
                    fail("Couldn't read node");
                }
            } catch (InterruptedException | ExecutionException e) {
                fail(e.getMessage());
            }
        }

        @Override
        public void onFailure(final Throwable ex) {
            fail(ex.getMessage());
        }
    }, MoreExecutors.directExecutor());
}
 
Example #24
Source File: PCEPTopologyProviderBean.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
    LOG.info("Close PCEP Topology Provider Singleton Service {}", getIdentifier().getName());
    if (this.serviceInstantiated) {
        this.serviceInstantiated = false;
        return this.pcepTopoProvider.closeServiceInstance();
    }
    return CommitInfo.emptyFluentFuture();
}
 
Example #25
Source File: OvsdbNodeRemoveCommand.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void execute(ReadWriteTransaction transaction) {
    FluentFuture<Optional<Node>> ovsdbNodeFuture = transaction.read(
            LogicalDatastoreType.OPERATIONAL, getOvsdbConnectionInstance().getInstanceIdentifier());
    Optional<Node> ovsdbNodeOptional;
    try {
        ovsdbNodeOptional = ovsdbNodeFuture.get();
        if (ovsdbNodeOptional.isPresent()) {
            Node ovsdbNode = ovsdbNodeOptional.get();
            OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.augmentation(OvsdbNodeAugmentation.class);
            if (checkIfOnlyConnectedManager(ovsdbNodeAugmentation)) {
                if (ovsdbNodeAugmentation != null) {
                    Map<ManagedNodeEntryKey, ManagedNodeEntry> entries =
                            ovsdbNodeAugmentation.getManagedNodeEntry();
                    if (entries != null) {
                        for (ManagedNodeEntry managedNode : entries.values()) {
                            transaction.delete(
                                    LogicalDatastoreType.OPERATIONAL, managedNode.getBridgeRef().getValue());
                        }
                    } else {
                        LOG.debug("{} had no managed nodes", ovsdbNode.getNodeId().getValue());
                    }
                } else {
                    LOG.warn("{} had no OvsdbNodeAugmentation", ovsdbNode.getNodeId().getValue());
                }
                LOG.debug("Deleting node {} from oper", getOvsdbConnectionInstance().getInstanceIdentifier());
                transaction.delete(LogicalDatastoreType.OPERATIONAL,
                        getOvsdbConnectionInstance().getInstanceIdentifier());
            } else {
                LOG.debug("Other southbound plugin instances in cluster are connected to the device,"
                        + " not deleting OvsdbNode from operational data store.");
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Failure to delete ovsdbNode", e);
    }
}
 
Example #26
Source File: PCEPTopologyProvider.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public FluentFuture<? extends CommitInfo> closeServiceInstance() {
    //FIXME return also channelClose once ListenableFuture implements wildcard
    this.channel.close().addListener((ChannelFutureListener) future ->
            checkArgument(future.isSuccess(), "Channel failed to close: %s", future.cause()));

    if (this.network != null) {
        this.network.close();
        this.network = null;
    }
    if (this.element != null) {
        this.element.close();
        this.element = null;
    }
    return this.manager.closeServiceInstance();
}
 
Example #27
Source File: Stateful07TopologySessionListener.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private ListenableFuture<OperationResult> triggerLspSyncronization(final TriggerSyncArgs input) {
    LOG.trace("Trigger Lsp Resynchronization {}", input);

    // Make sure the LSP exists
    final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName());
    final FluentFuture<Optional<ReportedLsp>> f = readOperationalData(lsp);
    if (f == null) {
        return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future();
    }
    return Futures.transformAsync(f, new ResyncLspFunction(input), MoreExecutors.directExecutor());
}
 
Example #28
Source File: OvsdbConnectionManagerTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testDisconnected() throws Exception {
    ConnectionInfo key = mock(ConnectionInfo.class);
    PowerMockito.mockStatic(SouthboundMapper.class);
    when(SouthboundMapper.createConnectionInfo(any(OvsdbClient.class))).thenReturn(key);

    OvsdbConnectionInstance ovsdbConnectionInstance = mock(OvsdbConnectionInstance.class);
    clients = new ConcurrentHashMap<>();
    clients.put(key, ovsdbConnectionInstance);
    MemberModifier.field(OvsdbConnectionManager.class, "clients").set(ovsdbConnManager, clients);

    suppress(MemberMatcher.method(OvsdbConnectionManager.class, "getConnectionInstance", ConnectionInfo.class));
    when(ovsdbConnManager.getConnectionInstance(any(ConnectionInfo.class))).thenReturn(ovsdbConnectionInstance);
    doNothing().when(txInvoker).invoke(any(TransactionCommand.class));

    when(SouthboundMapper.suppressLocalIpPort(any(ConnectionInfo.class))).thenReturn(key);

    // TODO: Write unit tests for EntityOwnershipService
    suppress(MemberMatcher.method(OvsdbConnectionManager.class, "unregisterEntityForOwnership",
            OvsdbConnectionInstance.class));
    instanceIdentifiers = new ConcurrentHashMap<>();
    field(OvsdbConnectionManager.class, "instanceIdentifiers").set(ovsdbConnManager, instanceIdentifiers);
    field(OvsdbConnectionManager.class, "nodeIdVsConnectionInstance").set(ovsdbConnManager, new HashMap<>());

    MemberModifier.suppress(MemberMatcher.method(OvsdbConnectionManager.class, "reconcileConnection",
            InstanceIdentifier.class, OvsdbNodeAugmentation.class));
    ReadTransaction tx = mock(ReadTransaction.class);
    when(db.newReadOnlyTransaction()).thenReturn(tx);
    when(tx.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class)))
            .thenReturn(mock(FluentFuture.class));
    when(tx.exists(any(LogicalDatastoreType.class), any(InstanceIdentifier.class)))
        .thenReturn(mock(FluentFuture.class));
    when(ovsdbConnectionInstance.getInstanceIdentifier()).thenReturn(mock(InstanceIdentifier.class));
    ovsdbConnManager.disconnected(externalClient);
    Map<ConnectionInfo, OvsdbConnectionInstance> testClients = Whitebox.getInternalState(ovsdbConnManager,
            "clients");
    assertEquals("Error, size of the hashmap is incorrect", 0, testClients.size());
}
 
Example #29
Source File: SouthboundUtilTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testGetManagingNode() throws Exception {
    OvsdbBridgeAttributes mn = mock(OvsdbBridgeAttributes.class);
    DataBroker db = mock(DataBroker.class);
    OvsdbNodeRef ref = mock(OvsdbNodeRef.class);
    ReadTransaction transaction = mock(ReadTransaction.class);
    when(db.newReadOnlyTransaction()).thenReturn(transaction);
    when(mn.getManagedBy()).thenReturn(ref);
    when(ref.getValue()).thenAnswer(
            (Answer<InstanceIdentifier<Node>>) invocation -> (InstanceIdentifier<Node>) mock(
                    InstanceIdentifier.class));
    FluentFuture<Optional<Node>> nf = mock(FluentFuture.class);
    when(transaction.read(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class))).thenReturn(nf);
    doNothing().when(transaction).close();

    //node, ovsdbNode not null
    Node node = mock(Node.class);
    OvsdbNodeAugmentation ovsdbNode = mock(OvsdbNodeAugmentation.class);
    when(nf.get()).thenReturn(Optional.of(node));
    when(node.augmentation(OvsdbNodeAugmentation.class)).thenReturn(ovsdbNode);
    assertEquals("Failed to return correct Optional object", Optional.of(ovsdbNode),
            SouthboundUtil.getManagingNode(db, mn));

    //node not null, ovsdbNode null
    when(nf.get()).thenReturn(Optional.empty());
    assertEquals("Failed to return correct Optional object", Optional.empty(),
            SouthboundUtil.getManagingNode(db, mn));

    //optional null
    when(nf.get()).thenReturn(null);
    assertEquals("Failed to return correct Optional object", Optional.empty(),
            SouthboundUtil.getManagingNode(db, mn));

    //ref null
    when(mn.getManagedBy()).thenReturn(null);
    assertEquals("Failed to return correct Optional object", Optional.empty(),
            SouthboundUtil.getManagingNode(db, mn));
}
 
Example #30
Source File: FilesystemSchemaSourceCache.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public synchronized FluentFuture<? extends T> getSource(final SourceIdentifier sourceIdentifier) {
    final File file = sourceIdToFile(sourceIdentifier, storageDirectory);
    if (file.exists() && file.canRead()) {
        LOG.trace("Source {} found in cache as {}", sourceIdentifier, file);
        final SchemaSourceRepresentation restored = STORAGE_ADAPTERS.get(representation).restore(sourceIdentifier,
                file);
        return immediateFluentFuture(representation.cast(restored));
    }

    LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
    return immediateFailedFluentFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
}