Example usage for com.google.common.util.concurrent JdkFutureAdapters listenInPoolThread

List of usage examples for com.google.common.util.concurrent JdkFutureAdapters listenInPoolThread

Introduction

In this page you can find the example usage for com.google.common.util.concurrent JdkFutureAdapters listenInPoolThread.

Prototype

public static <V> ListenableFuture<V> listenInPoolThread(Future<V> future) 

Source Link

Document

Assigns a thread to the given Future to provide ListenableFuture functionality.

Usage

From source file:org.opendaylight.netvirt.natservice.internal.NatTunnelInterfaceStateListener.java

private void hndlTepAddForDnatInEachRtr(RoutersList router, String nextHopIp, BigInteger tepAddedDpnId) {
    //DNAT : Advertise the new route to the floating IP having the new TEP IP as the next hop IP
    final String routerName = router.getRouter();

    InstanceIdentifier<RouterPorts> routerPortsId = NatUtil.getRouterPortsId(routerName);
    Optional<RouterPorts> optRouterPorts = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
            routerPortsId);//from   w w w  .j av a  2  s . co m
    if (!optRouterPorts.isPresent()) {
        LOG.debug("NAT Service : DNAT -> Could not read Router Ports data object with id: {} from DNAT "
                + "FloatinIpInfo", routerName);
        return;
    }
    RouterPorts routerPorts = optRouterPorts.get();
    Uuid extNwId = routerPorts.getExternalNetworkId();
    final String vpnName = NatUtil.getAssociatedVPN(dataBroker, extNwId, LOG);
    if (vpnName == null) {
        LOG.info("NAT Service : DNAT -> No External VPN associated with ext nw {} for router {}", extNwId,
                routerName);
        return;
    }

    String rd = NatUtil.getVpnRd(dataBroker, vpnName);
    long routerId = NatUtil.getVpnId(dataBroker, routerName);
    ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName);
    if (extNwProvType == null) {
        return;
    }
    String gwMacAddress = null;
    long l3Vni = 0;
    WriteTransaction writeTx = null;
    if (extNwProvType == ProviderTypes.VXLAN) {
        // Get the External Gateway MAC Address which is Router gateway MAC address for SNAT
        gwMacAddress = NatUtil.getExtGwMacAddFromRouterId(dataBroker, routerId);
        //get l3Vni value for external VPN
        l3Vni = NatEvpnUtil.getL3Vni(dataBroker, rd);
        //Create writeTx Object
        writeTx = dataBroker.newWriteOnlyTransaction();
    }
    List<Ports> interfaces = routerPorts.getPorts();
    for (Ports port : interfaces) {
        //Get the DPN on which this interface resides
        final String interfaceName = port.getPortName();
        final BigInteger fipCfgdDpnId = NatUtil.getDpnForInterface(interfaceService, interfaceName);
        if (fipCfgdDpnId.equals(BigInteger.ZERO)) {
            LOG.info("NAT Service : DNAT -> Skip processing Floating ip configuration for the port {}, "
                    + "since no DPN present for it", interfaceName);
            continue;
        }
        if (!fipCfgdDpnId.equals(tepAddedDpnId)) {
            LOG.debug(
                    "NAT Service : DNAT -> TEP added DPN {} is not the DPN {} which has the "
                            + "floating IP configured for the port: {}",
                    tepAddedDpnId, fipCfgdDpnId, interfaceName);
            continue;
        }
        List<InternalToExternalPortMap> intExtPortMapList = port.getInternalToExternalPortMap();
        for (InternalToExternalPortMap intExtPortMap : intExtPortMapList) {
            final String internalIp = intExtPortMap.getInternalIp();
            final String externalIp = intExtPortMap.getExternalIp();
            LOG.debug("NAT Service : DNAT -> Advertising the FIB route to the floating IP {} configured "
                    + "for the port: {}", externalIp, interfaceName);
            long serviceId = 0;
            if (extNwProvType == ProviderTypes.VXLAN) {
                LOG.debug("NAT Service : DNAT -> Advertise the route to the externalIp {} having nextHopIp {}",
                        externalIp, nextHopIp);
                NatEvpnUtil.addRoutesForVxLanProvType(dataBroker, bgpManager, fibManager, vpnName, rd,
                        externalIp, nextHopIp, l3Vni, interfaceName, gwMacAddress, writeTx, RouteOrigin.STATIC,
                        fipCfgdDpnId);
                serviceId = l3Vni;
            } else {
                long label = floatingIPListener.getOperationalIpMapping(routerName, interfaceName, internalIp);
                if (label == NatConstants.INVALID_ID) {
                    LOG.debug("NAT Service : DNAT -> Unable to advertise to the DC GW since label is invalid");
                    return;
                }
                LOG.debug("NAT Service : DNAT -> Advertise the route to the externalIp {} having nextHopIp {}",
                        externalIp, nextHopIp);
                long l3vni = 0;
                if (nvpnManager.getEnforceOpenstackSemanticsConfig()) {
                    l3vni = NatOverVxlanUtil.getInternetVpnVni(idManager, vpnName, l3vni).longValue();
                }
                NatUtil.addPrefixToBGP(dataBroker, bgpManager, fibManager, vpnName, rd, null,
                        externalIp + "/32", nextHopIp, null, null, label, l3vni, LOG, RouteOrigin.STATIC,
                        fipCfgdDpnId);
                serviceId = label;
            }

            //Install custom FIB routes (Table 21 -> Push MPLS label to Tunnel port
            List<Instruction> customInstructions = new ArrayList<>();
            customInstructions.add(new InstructionGotoTable(NwConstants.PDNAT_TABLE).buildInstruction(0));
            CreateFibEntryInput input = new CreateFibEntryInputBuilder().setVpnName(vpnName)
                    .setSourceDpid(fipCfgdDpnId).setInstruction(customInstructions)
                    .setIpAddress(externalIp + "/32").setServiceId(serviceId).setInstruction(customInstructions)
                    .build();
            Future<RpcResult<Void>> future = fibRpcService.createFibEntry(input);
            ListenableFuture<RpcResult<Void>> listenableFuture = JdkFutureAdapters.listenInPoolThread(future);

            Futures.addCallback(listenableFuture, new FutureCallback<RpcResult<Void>>() {

                @Override
                public void onFailure(Throwable error) {
                    LOG.error("NAT Service : DNAT -> Error in generate label or fib install process", error);
                }

                @Override
                public void onSuccess(RpcResult<Void> result) {
                    if (result.isSuccessful()) {
                        LOG.info("NAT Service : DNAT -> Successfully installed custom FIB routes for prefix {}",
                                externalIp);
                    } else {
                        LOG.error(
                                "NAT Service : DNAT -> Error in rpc call to create custom Fib "
                                        + "entries for prefix {} in DPN {}, {}",
                                externalIp, fipCfgdDpnId, result.getErrors());
                    }
                }
            });
        }
        if (writeTx != null) {
            writeTx.submit();
        }
    }
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskFactory.java

/**
 * @param taskContext task context/* w  ww  .ja  v  a  2 s . c o  m*/
 * @param input remove group input
 * @param cookie switch connection distinguisher cookie value
 * @return task remove group task
 */
public static OFRpcTask<RemoveGroupInput, RpcResult<UpdateGroupOutput>> createRemoveGroupTask(
        final OFRpcTaskContext taskContext, RemoveGroupInput input,
        final SwitchConnectionDistinguisher cookie) {
    class OFRpcTaskImpl extends OFRpcTask<RemoveGroupInput, RpcResult<UpdateGroupOutput>> {

        public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
                RemoveGroupInput input) {
            super(taskContext, cookie, input);
        }

        @Override
        public ListenableFuture<RpcResult<UpdateGroupOutput>> call() {
            ListenableFuture<RpcResult<UpdateGroupOutput>> result = SettableFuture.create();

            // Convert the AddGroupInput to GroupModInput
            GroupModInputBuilder ofGroupModInput = GroupConvertor.toGroupModInput(getInput(), getVersion(),
                    getSession().getFeatures().getDatapathId());
            final Long xId = getSession().getNextXid();
            ofGroupModInput.setXid(xId);

            Future<RpcResult<UpdateGroupOutput>> resultFromOFLib = getMessageService()
                    .groupMod(ofGroupModInput.build(), getCookie());
            result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);

            result = OFRpcTaskUtil.chainFutureBarrier(this, result);
            OFRpcTaskUtil.hookFutureNotification(this, result, getRpcNotificationProviderService(),
                    createGroupRemovedNotification(getInput()));

            return result;
        }

        @Override
        public Boolean isBarrier() {
            return getInput().isBarrier();
        }
    }

    return new OFRpcTaskImpl(taskContext, cookie, input);
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskFactory.java

/**
 * @param taskContext task context/*  www .j  ava 2s.  com*/
 * @param input meter removed input
 * @param cookie switch connection distinguisher cookie value
 * @return task meter remove task
 */
public static OFRpcTask<RemoveMeterInput, RpcResult<UpdateMeterOutput>> createRemoveMeterTask(
        OFRpcTaskContext taskContext, RemoveMeterInput input, SwitchConnectionDistinguisher cookie) {

    class OFRpcTaskImpl extends OFRpcTask<RemoveMeterInput, RpcResult<UpdateMeterOutput>> {

        public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
                RemoveMeterInput input) {
            super(taskContext, cookie, input);
        }

        @Override
        public ListenableFuture<RpcResult<UpdateMeterOutput>> call() {
            ListenableFuture<RpcResult<UpdateMeterOutput>> result = SettableFuture.create();

            // Convert the AddGroupInput to GroupModInput
            MeterModInputBuilder ofMeterModInput = MeterConvertor.toMeterModInput(getInput(), getVersion());
            final Long xId = getSession().getNextXid();
            ofMeterModInput.setXid(xId);

            Future<RpcResult<UpdateMeterOutput>> resultFromOFLib = getMessageService()
                    .meterMod(ofMeterModInput.build(), getCookie());
            result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);

            result = OFRpcTaskUtil.chainFutureBarrier(this, result);
            OFRpcTaskUtil.hookFutureNotification(this, result, getRpcNotificationProviderService(),
                    createMeterRemovedNotification(getInput()));

            return result;
        }

        @Override
        public Boolean isBarrier() {
            return getInput().isBarrier();
        }
    }

    return new OFRpcTaskImpl(taskContext, cookie, input);

}

From source file:org.opendaylight.vpnservice.natservice.internal.ExternalRoutersListener.java

public void advToBgpAndInstallFibAndTsFlows(final BigInteger dpnId, final short tableId, final String vpnName,
        final long routerId, final String externalIp, VpnRpcService vpnService, final FibRpcService fibService,
        final IBgpManager bgpManager, final DataBroker dataBroker, final Logger log) {
    LOG.debug(/*  w w  w.jav  a  2  s .  c  o  m*/
            "NAT Service : advToBgpAndInstallFibAndTsFlows() entry for DPN ID {}, tableId {}, vpnname {} and externalIp {}",
            dpnId, tableId, vpnName, externalIp);
    //Generate VPN label for the external IP
    GenerateVpnLabelInput labelInput = new GenerateVpnLabelInputBuilder().setVpnName(vpnName)
            .setIpPrefix(externalIp).build();
    Future<RpcResult<GenerateVpnLabelOutput>> labelFuture = vpnService.generateVpnLabel(labelInput);

    //On successful generation of the VPN label, advertise the route to the BGP and install the FIB routes.
    ListenableFuture<RpcResult<Void>> future = Futures.transform(
            JdkFutureAdapters.listenInPoolThread(labelFuture),
            new AsyncFunction<RpcResult<GenerateVpnLabelOutput>, RpcResult<Void>>() {

                @Override
                public ListenableFuture<RpcResult<Void>> apply(RpcResult<GenerateVpnLabelOutput> result)
                        throws Exception {
                    if (result.isSuccessful()) {
                        LOG.debug("NAT Service : inside apply with result success");
                        GenerateVpnLabelOutput output = result.getResult();
                        long label = output.getLabel();

                        //Inform BGP
                        String rd = NatUtil.getVpnRd(dataBroker, vpnName);
                        String nextHopIp = NatUtil.getEndpointIpAddressForDPN(dataBroker, dpnId);
                        NatUtil.addPrefixToBGP(bgpManager, rd, externalIp, nextHopIp, label, log);

                        //Get IPMaps from the DB for the router ID
                        List<IpMap> dbIpMaps = NaptManager.getIpMapList(dataBroker, routerId);
                        if (dbIpMaps != null) {
                            for (IpMap dbIpMap : dbIpMaps) {
                                String dbExternalIp = dbIpMap.getExternalIp();
                                //Select the IPMap, whose external IP is the IP for which FIB is installed
                                if (externalIp.equals(dbExternalIp)) {
                                    String dbInternalIp = dbIpMap.getInternalIp();
                                    IpMapKey dbIpMapKey = dbIpMap.getKey();
                                    LOG.debug("Setting label {} for internalIp {} and externalIp {}", label,
                                            dbInternalIp, externalIp);
                                    IpMap newIpm = new IpMapBuilder().setKey(dbIpMapKey)
                                            .setInternalIp(dbInternalIp).setExternalIp(dbExternalIp)
                                            .setLabel(label).build();
                                    MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL,
                                            naptManager.getIpMapIdentifier(routerId, dbInternalIp), newIpm);
                                    break;
                                }
                            }
                        } else {
                            LOG.error(
                                    "NAT Service : Failed to write label {} for externalIp {} for routerId {} in DS",
                                    label, externalIp, routerId);
                        }

                        //Install custom FIB routes
                        List<Instruction> customInstructions = new ArrayList<>();
                        customInstructions
                                .add(new InstructionInfo(InstructionType.goto_table, new long[] { tableId })
                                        .buildInstruction(0));
                        makeTunnelTableEntry(dpnId, label, customInstructions);
                        makeLFibTableEntry(dpnId, label, tableId);

                        CreateFibEntryInput input = new CreateFibEntryInputBuilder().setVpnName(vpnName)
                                .setSourceDpid(dpnId).setIpAddress(externalIp).setServiceId(label)
                                .setInstruction(customInstructions).build();
                        Future<RpcResult<Void>> future = fibService.createFibEntry(input);
                        return JdkFutureAdapters.listenInPoolThread(future);
                    } else {
                        LOG.error("NAT Service : inside apply with result failed");
                        String errMsg = String.format(
                                "Could not retrieve the label for prefix %s in VPN %s, %s", externalIp, vpnName,
                                result.getErrors());
                        return Futures.immediateFailedFuture(new RuntimeException(errMsg));
                    }
                }
            });

    Futures.addCallback(future, new FutureCallback<RpcResult<Void>>() {

        @Override
        public void onFailure(Throwable error) {
            log.error("NAT Service : Error in generate label or fib install process", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                log.info("NAT Service : Successfully installed custom FIB routes for prefix {}", externalIp);
            } else {
                log.error(
                        "NAT Service : Error in rpc call to create custom Fib entries for prefix {} in DPN {}, {}",
                        externalIp, dpnId, result.getErrors());
            }
        }
    });
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskFactory.java

/**
 * @param taskContext task context//  w w w  .  j  ava2  s .  c om
 * @param input get all statistics input
 * @param cookie switch connection distinguisher cookie value
 * @return task get all group statistics task
 */
public static OFRpcTask<GetAllGroupStatisticsInput, RpcResult<GetAllGroupStatisticsOutput>> createGetAllGroupStatisticsTask(
        final OFRpcTaskContext taskContext, GetAllGroupStatisticsInput input,
        SwitchConnectionDistinguisher cookie) {

    class OFRpcTaskImpl extends OFRpcTask<GetAllGroupStatisticsInput, RpcResult<GetAllGroupStatisticsOutput>> {

        public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
                GetAllGroupStatisticsInput input) {
            super(taskContext, cookie, input);
        }

        @Override
        public ListenableFuture<RpcResult<GetAllGroupStatisticsOutput>> call() {
            final SettableFuture<RpcResult<GetAllGroupStatisticsOutput>> result = SettableFuture.create();

            if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
                RpcResult<GetAllGroupStatisticsOutput> rpcResult = RpcResultBuilder
                        .success(new GetAllGroupStatisticsOutputBuilder().build()).build();

                return Futures.immediateFuture(rpcResult);
            } else {

                // Generate xid to associate it with the request
                final Long xid = taskContext.getSession().getNextXid();

                // Create multipart request body for fetch all the group stats
                MultipartRequestGroupCaseBuilder caseBuilder = new MultipartRequestGroupCaseBuilder();
                MultipartRequestGroupBuilder mprGroupBuild = new MultipartRequestGroupBuilder();
                mprGroupBuild.setGroupId(new GroupId(BinContent.intToUnsignedLong(
                        org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Group.OFPGALL
                                .getIntValue())));
                caseBuilder.setMultipartRequestGroup(mprGroupBuild.build());

                // Create multipart request header
                MultipartRequestInputBuilder mprInput = createMultipartHeader(MultipartType.OFPMPGROUP,
                        taskContext, xid);

                // Set request body to main multipart request
                mprInput.setMultipartRequestBody(caseBuilder.build());

                // Send the request, no cookies associated, use any connection

                Future<RpcResult<Void>> resultFromOFLib = getMessageService().multipartRequest(mprInput.build(),
                        getCookie());
                ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters
                        .listenInPoolThread(resultFromOFLib);

                Futures.addCallback(resultLib, new ResultCallback<GetAllGroupStatisticsOutput>(result) {
                    @Override
                    public GetAllGroupStatisticsOutput createResult() {
                        GetAllGroupStatisticsOutputBuilder groupStatBuilder = new GetAllGroupStatisticsOutputBuilder()
                                .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
                        return groupStatBuilder.build();
                    }
                });

                return result;
            }
        }
    }

    return new OFRpcTaskImpl(taskContext, cookie, input);
}

From source file:org.opendaylight.netvirt.natservice.internal.ExternalRoutersListener.java

public void advToBgpAndInstallFibAndTsFlows(final BigInteger dpnId, final short tableId, final String vpnName,
        final long routerId, final String routerName, final String externalIp, final Routers router,
        VpnRpcService vpnService, final FibRpcService fibService, final IBgpManager bgpManager,
        final DataBroker dataBroker, final Logger log) {
    LOG.debug("NAT Service : advToBgpAndInstallFibAndTsFlows() entry for DPN ID {}, tableId {}, vpnname {} "
            + "and externalIp {}", dpnId, tableId, vpnName, externalIp);
    String nextHopIp = NatUtil.getEndpointIpAddressForDPN(dataBroker, dpnId);
    String rd = NatUtil.getVpnRd(dataBroker, vpnName);
    if (rd == null || rd.isEmpty()) {
        LOG.error("NAT Service : Unable to get RD for VPN Name {}", vpnName);
        return;/* ww w .  j av a  2 s  . co m*/
    }
    ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName);
    if (extNwProvType == null) {
        return;
    }
    if (extNwProvType == ProviderTypes.VXLAN) {
        WriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
        evpnSnatFlowProgrammer.evpnAdvToBgpAndInstallFibAndTsFlows(dpnId, tableId, externalIp, vpnName, rd,
                nextHopIp, writeTx, routerId);
        writeTx.submit();
        return;
    }
    //Generate VPN label for the external IP
    GenerateVpnLabelInput labelInput = new GenerateVpnLabelInputBuilder().setVpnName(vpnName)
            .setIpPrefix(externalIp).build();
    Future<RpcResult<GenerateVpnLabelOutput>> labelFuture = vpnService.generateVpnLabel(labelInput);

    //On successful generation of the VPN label, advertise the route to the BGP and install the FIB routes.
    ListenableFuture<RpcResult<Void>> future = Futures.transform(
            JdkFutureAdapters.listenInPoolThread(labelFuture),
            (AsyncFunction<RpcResult<GenerateVpnLabelOutput>, RpcResult<Void>>) result -> {
                if (result.isSuccessful()) {
                    LOG.debug("NAT Service : inside apply with result success");
                    GenerateVpnLabelOutput output = result.getResult();
                    final long label = output.getLabel();

                    int externalIpInDsFlag = 0;
                    //Get IPMaps from the DB for the router ID
                    List<IpMap> dbIpMaps = NaptManager.getIpMapList(dataBroker, routerId);
                    if (dbIpMaps != null) {
                        for (IpMap dbIpMap : dbIpMaps) {
                            String dbExternalIp = dbIpMap.getExternalIp();
                            //Select the IPMap, whose external IP is the IP for which FIB is installed
                            if (dbExternalIp.contains(externalIp)) {
                                String dbInternalIp = dbIpMap.getInternalIp();
                                IpMapKey dbIpMapKey = dbIpMap.getKey();
                                LOG.debug("Setting label {} for internalIp {} and externalIp {}", label,
                                        dbInternalIp, externalIp);
                                IpMap newIpm = new IpMapBuilder().setKey(dbIpMapKey).setInternalIp(dbInternalIp)
                                        .setExternalIp(dbExternalIp).setLabel(label).build();
                                MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL,
                                        naptManager.getIpMapIdentifier(routerId, dbInternalIp), newIpm);
                                externalIpInDsFlag++;
                            }
                        }
                        if (externalIpInDsFlag <= 0) {
                            LOG.debug("NAT Service : External Ip {} not found in DS, Failed to update label {} "
                                    + "for routerId {} in DS", externalIp, label, routerId);
                            String errMsg = String.format("Failed to update label %s due to external Ip %s not"
                                    + " found in DS for router %s", label, externalIp, routerId);
                            return Futures.immediateFailedFuture(new Exception(errMsg));
                        }
                    } else {
                        LOG.error("NAT Service : Failed to write label {} for externalIp {} for "
                                + "routerId {} in DS", label, externalIp, routerId);
                    }
                    //Inform BGP
                    long l3vni = 0;
                    if (nvpnManager.getEnforceOpenstackSemanticsConfig()) {
                        l3vni = NatOverVxlanUtil.getInternetVpnVni(idManager, vpnName, l3vni).longValue();
                    }
                    Routers extRouter = router != null ? router
                            : NatUtil.getRoutersFromConfigDS(dataBroker, routerName);
                    Uuid externalSubnetId = NatUtil.getExternalSubnetForRouterExternalIp(dataBroker, externalIp,
                            extRouter);
                    NatUtil.addPrefixToBGP(dataBroker, bgpManager, fibManager, vpnName, rd, externalSubnetId,
                            externalIp, nextHopIp, extRouter.getNetworkId().getValue(), null, label, l3vni, log,
                            RouteOrigin.STATIC, dpnId);

                    //Install custom FIB routes
                    List<Instruction> tunnelTableCustomInstructions = new ArrayList<>();
                    tunnelTableCustomInstructions.add(new InstructionGotoTable(tableId).buildInstruction(0));
                    makeTunnelTableEntry(dpnId, label, l3vni, tunnelTableCustomInstructions);
                    makeLFibTableEntry(dpnId, label, tableId);

                    //Install custom FIB routes - FIB table.
                    List<Instruction> fibTableCustomInstructions = createFibTableCustomInstructions(dataBroker,
                            tableId, routerName, externalIp);
                    if (nvpnManager.getEnforceOpenstackSemanticsConfig()) {
                        //Install the flow table 25->44 If there is no FIP Match on table 25 (PDNAT_TABLE)
                        NatUtil.makePreDnatToSnatTableEntry(mdsalManager, dpnId,
                                NwConstants.INBOUND_NAPT_TABLE);
                    }
                    String fibExternalIp = externalIp.contains("/32") ? externalIp : (externalIp + "/32");
                    CreateFibEntryInput input = new CreateFibEntryInputBuilder().setVpnName(vpnName)
                            .setSourceDpid(dpnId).setIpAddress(fibExternalIp).setServiceId(label)
                            .setInstruction(fibTableCustomInstructions).build();
                    Future<RpcResult<Void>> future1 = fibService.createFibEntry(input);
                    return JdkFutureAdapters.listenInPoolThread(future1);
                } else {
                    LOG.error("NAT Service : inside apply with result failed");
                    String errMsg = String.format("Could not retrieve the label for prefix %s in VPN %s, %s",
                            externalIp, vpnName, result.getErrors());
                    return Futures.immediateFailedFuture(new RuntimeException(errMsg));
                }
            });

    Futures.addCallback(future, new FutureCallback<RpcResult<Void>>() {

        @Override
        public void onFailure(Throwable error) {
            log.error("NAT Service : Error in generate label or fib install process", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                log.info("NAT Service : Successfully installed custom FIB routes for prefix {}", externalIp);
            } else {
                log.error("NAT Service : Error in rpc call to create custom Fib entries for prefix {} in "
                        + "DPN {}, {}", externalIp, dpnId, result.getErrors());
            }
        }
    });
}

From source file:org.opendaylight.netvirt.natservice.internal.NatTunnelInterfaceStateListener.java

private void hndlTepDelForDnatInEachRtr(RoutersList router, BigInteger tepDeletedDpnId) {
    //DNAT : Withdraw the routes from the BGP
    String routerName = router.getRouter();
    LOG.debug("NAT Service : DNAT -> Trying to clear routes to the Floating IP associated to the router {}",
            routerName);/*from  w ww. ja va2 s  .  co  m*/

    InstanceIdentifier<RouterPorts> routerPortsId = NatUtil.getRouterPortsId(routerName);
    Optional<RouterPorts> optRouterPorts = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
            routerPortsId);
    if (!optRouterPorts.isPresent()) {
        LOG.debug("NAT Service : DNAT -> Could not read Router Ports data object with id: {} from DNAT "
                + "FloatingIpInfo", routerName);
        return;
    }
    RouterPorts routerPorts = optRouterPorts.get();
    Uuid extNwId = routerPorts.getExternalNetworkId();
    final String vpnName = NatUtil.getAssociatedVPN(dataBroker, extNwId, LOG);
    if (vpnName == null) {
        LOG.info("NAT Service : DNAT -> No External VPN associated with Ext N/W {} for Router {}", extNwId,
                routerName);
        return;
    }
    String rd = NatUtil.getVpnRd(dataBroker, vpnName);
    ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName);
    if (extNwProvType == null) {
        return;
    }
    long l3Vni = 0;
    if (extNwProvType == ProviderTypes.VXLAN) {
        //get l3Vni value for external VPN
        l3Vni = NatEvpnUtil.getL3Vni(dataBroker, rd);
        if (l3Vni == NatConstants.DEFAULT_L3VNI_VALUE) {
            LOG.error("NAT Service : Unable to retrieve L3VNI value for RD {}", rd);
            return;
        }
    }
    List<Ports> interfaces = routerPorts.getPorts();
    for (Ports port : interfaces) {
        //Get the DPN on which this interface resides
        String interfaceName = port.getPortName();
        BigInteger fipCfgdDpnId = NatUtil.getDpnForInterface(interfaceService, interfaceName);
        if (fipCfgdDpnId.equals(BigInteger.ZERO)) {
            LOG.info("NAT Service : DNAT -> Abort processing Floating ip configuration. No DPN for port : {}",
                    interfaceName);
            continue;
        }
        if (!fipCfgdDpnId.equals(tepDeletedDpnId)) {
            LOG.info(
                    "NAT Service : DNAT -> TEP deleted DPN {} is not the DPN {} which has the "
                            + "floating IP configured for the port: {}",
                    tepDeletedDpnId, fipCfgdDpnId, interfaceName);
            continue;
        }
        List<InternalToExternalPortMap> intExtPortMapList = port.getInternalToExternalPortMap();
        for (InternalToExternalPortMap intExtPortMap : intExtPortMapList) {
            String internalIp = intExtPortMap.getInternalIp();
            String externalIp = intExtPortMap.getExternalIp();
            LOG.debug("NAT Service : DNAT -> Withdrawing the FIB route to the floating IP {} "
                    + "configured for the port: {}", externalIp, interfaceName);
            NatUtil.removePrefixFromBGP(dataBroker, bgpManager, fibManager, rd, externalIp + "/32", vpnName,
                    LOG);
            long serviceId = 0;
            if (extNwProvType == ProviderTypes.VXLAN) {
                serviceId = l3Vni;
            } else {
                long label = floatingIPListener.getOperationalIpMapping(routerName, interfaceName, internalIp);
                if (label == NatConstants.INVALID_ID) {
                    LOG.debug("NAT Service : DNAT -> Unable to remove the table 21 entry pushing the "
                            + "MPLS label to the tunnel since label is invalid");
                    return;
                }
                serviceId = label;
            }
            RemoveFibEntryInput input = new RemoveFibEntryInputBuilder().setVpnName(vpnName)
                    .setSourceDpid(fipCfgdDpnId).setIpAddress(externalIp + "/32").setServiceId(serviceId)
                    .build();
            Future<RpcResult<Void>> future = fibRpcService.removeFibEntry(input);
            ListenableFuture<RpcResult<Void>> listenableFuture = JdkFutureAdapters.listenInPoolThread(future);

            Futures.addCallback(listenableFuture, new FutureCallback<RpcResult<Void>>() {

                @Override
                public void onFailure(Throwable error) {
                    LOG.error("NAT Service : DNAT -> Error in removing the table 21 entry pushing "
                            + "the MPLS label to the tunnel since label is invalid ", error);
                }

                @Override
                public void onSuccess(RpcResult<Void> result) {
                    if (result.isSuccessful()) {
                        LOG.info("NAT Service : DNAT -> Successfully removed the entry pushing the "
                                + "MPLS label to the tunnel");
                    } else {
                        LOG.error(
                                "NAT Service : DNAT -> Error in fib rpc call to remove the table 21 "
                                        + "entry pushing the MPLS label to the tunnnel due to {}",
                                result.getErrors());
                    }
                }
            });
        }
    }
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskFactory.java

/**
 * @param taskContext task context/*  ww w. j a v a  2  s  .com*/
 * @param input get group description input
 * @param cookie switch connection distinguisher cookie value
 * @return task get group description task
 */
public static OFRpcTask<GetGroupDescriptionInput, RpcResult<GetGroupDescriptionOutput>> createGetGroupDescriptionTask(
        final OFRpcTaskContext taskContext, GetGroupDescriptionInput input,
        SwitchConnectionDistinguisher cookie) {
    class OFRpcTaskImpl extends OFRpcTask<GetGroupDescriptionInput, RpcResult<GetGroupDescriptionOutput>> {

        public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
                GetGroupDescriptionInput input) {
            super(taskContext, cookie, input);
        }

        @Override
        public ListenableFuture<RpcResult<GetGroupDescriptionOutput>> call() throws Exception {
            final SettableFuture<RpcResult<GetGroupDescriptionOutput>> result = SettableFuture.create();

            if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
                RpcResult<GetGroupDescriptionOutput> rpcResult = RpcResultBuilder
                        .success(new GetGroupDescriptionOutputBuilder().build()).build();
                return Futures.immediateFuture(rpcResult);
            } else {
                final Long xid = taskContext.getSession().getNextXid();

                MultipartRequestGroupDescCaseBuilder mprGroupDescCaseBuild = new MultipartRequestGroupDescCaseBuilder();
                MultipartRequestInputBuilder mprInput = createMultipartHeader(MultipartType.OFPMPGROUPDESC,
                        taskContext, xid);
                mprInput.setMultipartRequestBody(mprGroupDescCaseBuild.build());
                Future<RpcResult<Void>> resultFromOFLib = getMessageService().multipartRequest(mprInput.build(),
                        getCookie());
                ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters
                        .listenInPoolThread(resultFromOFLib);

                Futures.addCallback(resultLib, new ResultCallback<GetGroupDescriptionOutput>(result) {
                    @Override
                    public GetGroupDescriptionOutput createResult() {
                        GetGroupDescriptionOutputBuilder groupStatBuilder = new GetGroupDescriptionOutputBuilder()
                                .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
                        return groupStatBuilder.build();
                    }
                });
                return result;
            }
        }
    }

    return new OFRpcTaskImpl(taskContext, cookie, input);
}

From source file:org.opendaylight.statistics.StatisticsImpl.java

private void createIdPool() {
    if (checkPoolExists()) {
        return;/*from   w w w . ja  v  a  2s.c  om*/
    }
    CreateIdPoolInput createPool = new CreateIdPoolInputBuilder()
            .setPoolName(CountersServiceUtils.COUNTERS_PULL_NAME)
            .setLow(CountersServiceUtils.COUNTERS_PULL_START)
            .setHigh(CountersServiceUtils.COUNTERS_PULL_START + CountersServiceUtils.COUNTERS_PULL_END).build();
    Future<RpcResult<Void>> result = idManagerService.createIdPool(createPool);
    Futures.addCallback(JdkFutureAdapters.listenInPoolThread(result), new FutureCallback<RpcResult<Void>>() {

        @Override
        public void onFailure(Throwable error) {
            LOG.error("Failed to create idPool for Aliveness Monitor Service", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                LOG.debug("Created IdPool for tap");
            } else {
                LOG.error("RPC to create Idpool failed {}", result.getErrors());
            }
        }
    });
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskFactory.java

/**
 * @param taskContext task context// w  w  w.j  a  v  a  2  s .c  o m
 * @param input get group feature input
 * @param cookie switch connection distinguisher cookie value
 * @return task get group feature task
 */
public static OFRpcTask<GetGroupFeaturesInput, RpcResult<GetGroupFeaturesOutput>> createGetGroupFeaturesTask(
        final OFRpcTaskContext taskContext, GetGroupFeaturesInput input, SwitchConnectionDistinguisher cookie) {
    class OFRpcTaskImpl extends OFRpcTask<GetGroupFeaturesInput, RpcResult<GetGroupFeaturesOutput>> {

        public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
                GetGroupFeaturesInput input) {
            super(taskContext, cookie, input);
            // TODO Auto-generated constructor stub
        }

        @Override
        public ListenableFuture<RpcResult<GetGroupFeaturesOutput>> call() throws Exception {
            final SettableFuture<RpcResult<GetGroupFeaturesOutput>> result = SettableFuture.create();

            if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
                RpcResult<GetGroupFeaturesOutput> rpcResult = RpcResultBuilder
                        .success(new GetGroupFeaturesOutputBuilder().build()).build();
                return Futures.immediateFuture(rpcResult);
            } else {
                final Long xid = taskContext.getSession().getNextXid();

                MultipartRequestGroupFeaturesCaseBuilder mprGroupFeaturesBuild = new MultipartRequestGroupFeaturesCaseBuilder();
                MultipartRequestInputBuilder mprInput = createMultipartHeader(MultipartType.OFPMPGROUPFEATURES,
                        taskContext, xid);
                mprInput.setMultipartRequestBody(mprGroupFeaturesBuild.build());
                Future<RpcResult<Void>> resultFromOFLib = getMessageService().multipartRequest(mprInput.build(),
                        getCookie());
                ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters
                        .listenInPoolThread(resultFromOFLib);

                Futures.addCallback(resultLib, new ResultCallback<GetGroupFeaturesOutput>(result) {
                    @Override
                    public GetGroupFeaturesOutput createResult() {
                        GetGroupFeaturesOutputBuilder groupFeatureBuilder = new GetGroupFeaturesOutputBuilder()
                                .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
                        return groupFeatureBuilder.build();
                    }
                });
                return result;
            }
        }
    }

    return new OFRpcTaskImpl(taskContext, cookie, input);
}