NETVIRT-1519: MIP entry duplicated in FIB
[netvirt.git] / vpnmanager / impl / src / main / java / org / opendaylight / netvirt / vpnmanager / VpnRpcServiceImpl.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netvirt.vpnmanager;
9
10 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
11
12 import com.google.common.base.Optional;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashSet;
18 import java.util.concurrent.ExecutionException;
19 import java.util.function.Consumer;
20 import javax.inject.Inject;
21 import javax.inject.Singleton;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
24 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
25 import org.opendaylight.netvirt.bgpmanager.api.IBgpManager;
26 import org.opendaylight.netvirt.fibmanager.api.IFibManager;
27 import org.opendaylight.netvirt.fibmanager.api.RouteOrigin;
28 import org.opendaylight.netvirt.vpnmanager.api.IVpnManager;
29 import org.opendaylight.netvirt.vpnmanager.api.intervpnlink.InterVpnLinkCache;
30 import org.opendaylight.netvirt.vpnmanager.api.intervpnlink.InterVpnLinkDataComposite;
31 import org.opendaylight.netvirt.vpnmanager.intervpnlink.InterVpnLinkUtil;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntry;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.AddStaticRouteInput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.AddStaticRouteOutput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.AddStaticRouteOutputBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.ApplyArpConfigInput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.ApplyArpConfigOutput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.ApplyArpConfigOutputBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelOutput;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelOutputBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveStaticRouteInput;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveStaticRouteOutput;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveStaticRouteOutputBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveVpnLabelInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveVpnLabelOutput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveVpnLabelOutputBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.VpnRpcService;
50 import org.opendaylight.yangtools.yang.common.RpcError;
51 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
52 import org.opendaylight.yangtools.yang.common.RpcResult;
53 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.slf4j.helpers.FormattingTuple;
57 import org.slf4j.helpers.MessageFormatter;
58
59 @Singleton
60 public class VpnRpcServiceImpl implements VpnRpcService {
61     private static final Logger LOG = LoggerFactory.getLogger(VpnRpcServiceImpl.class);
62     private final ManagedNewTransactionRunner txRunner;
63     private final IFibManager fibManager;
64     private final IBgpManager bgpManager;
65     private final IVpnManager vpnManager;
66     private final InterVpnLinkCache interVpnLinkCache;
67     private final VpnUtil vpnUtil;
68     private final InterVpnLinkUtil interVpnLinkUtil;
69
70     @Inject
71     public VpnRpcServiceImpl(final DataBroker dataBroker,
72             final IFibManager fibManager, IBgpManager bgpManager, final IVpnManager vpnManager,
73             final InterVpnLinkCache interVpnLinkCache, VpnUtil vpnUtil, InterVpnLinkUtil interVpnLinkUtil) {
74         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
75         this.fibManager = fibManager;
76         this.bgpManager = bgpManager;
77         this.vpnManager = vpnManager;
78         this.interVpnLinkCache = interVpnLinkCache;
79         this.vpnUtil = vpnUtil;
80         this.interVpnLinkUtil = interVpnLinkUtil;
81     }
82
83     /**
84      * Generate label for the given ip prefix from the associated VPN.
85      */
86     @Override
87     public ListenableFuture<RpcResult<GenerateVpnLabelOutput>> generateVpnLabel(GenerateVpnLabelInput input) {
88         String vpnName = input.getVpnName();
89         String ipPrefix = input.getIpPrefix();
90         SettableFuture<RpcResult<GenerateVpnLabelOutput>> futureResult = SettableFuture.create();
91         String rd = vpnUtil.getVpnRd(vpnName);
92         long label = vpnUtil.getUniqueId(VpnConstants.VPN_IDPOOL_NAME,
93             VpnUtil.getNextHopLabelKey(rd != null ? rd : vpnName, ipPrefix));
94         if (label == 0) {
95             futureResult.set(RpcResultBuilder.<GenerateVpnLabelOutput>failed().withError(ErrorType.APPLICATION,
96                     formatAndLog(LOG::error, "Could not retrieve the label for prefix {} in VPN {}", ipPrefix,
97                             vpnName)).build());
98         } else {
99             GenerateVpnLabelOutput output = new GenerateVpnLabelOutputBuilder().setLabel(label).build();
100             futureResult.set(RpcResultBuilder.success(output).build());
101         }
102         return futureResult;
103     }
104
105     /**
106      * Remove label for the given ip prefix from the associated VPN.
107      */
108     @Override
109     public ListenableFuture<RpcResult<RemoveVpnLabelOutput>> removeVpnLabel(RemoveVpnLabelInput input) {
110         String vpnName = input.getVpnName();
111         String ipPrefix = input.getIpPrefix();
112         String rd = vpnUtil.getVpnRd(vpnName);
113         vpnUtil.releaseId(VpnConstants.VPN_IDPOOL_NAME,
114             VpnUtil.getNextHopLabelKey(rd != null ? rd : vpnName, ipPrefix));
115         return RpcResultBuilder.success(new RemoveVpnLabelOutputBuilder().build()).buildFuture();
116     }
117
118     private Collection<RpcError> validateAddStaticRouteInput(AddStaticRouteInput input) {
119         Collection<RpcError> rpcErrors = new ArrayList<>();
120         String destination = input.getDestination();
121         String vpnInstanceName = input.getVpnInstanceName();
122         String nexthop = input.getNexthop();
123         if (destination == null || destination.isEmpty()) {
124             String message = "destination parameter is mandatory";
125             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
126         }
127         if (vpnInstanceName == null || vpnInstanceName.isEmpty()) {
128             String message = "vpnInstanceName parameter is mandatory";
129             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
130         }
131         if (nexthop == null || nexthop.isEmpty()) {
132             String message = "nexthop parameter is mandatory";
133             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
134         }
135         return rpcErrors;
136     }
137
138     // TODO Clean up the exception handling
139     @SuppressWarnings("checkstyle:IllegalCatch")
140     @Override
141     public ListenableFuture<RpcResult<AddStaticRouteOutput>> addStaticRoute(AddStaticRouteInput input) {
142
143         SettableFuture<RpcResult<AddStaticRouteOutput>> result = SettableFuture.create();
144         String destination = input.getDestination();
145         String vpnInstanceName = input.getVpnInstanceName();
146         String nexthop = input.getNexthop();
147         Long label = input.getLabel();
148         LOG.info("Adding static route for Vpn {} with destination {}, nexthop {} and label {}",
149             vpnInstanceName, destination, nexthop, label);
150
151         Collection<RpcError> rpcErrors = validateAddStaticRouteInput(input);
152         if (!rpcErrors.isEmpty()) {
153             result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withRpcErrors(rpcErrors).build());
154             return result;
155         }
156
157         if (label == null || label == 0) {
158             label = (long) vpnUtil.getUniqueId(VpnConstants.VPN_IDPOOL_NAME,
159                 VpnUtil.getNextHopLabelKey(vpnInstanceName, destination));
160             if (label == 0) {
161                 String message = "Unable to retrieve a new Label for the new Route";
162                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(RpcError.ErrorType.APPLICATION,
163                     message).build());
164                 return result;
165             }
166         }
167
168         String vpnRd = vpnUtil.getVpnRd(input.getVpnInstanceName());
169         VpnInstanceOpDataEntry vpnOpEntry = vpnUtil.getVpnInstanceOpData(vpnRd);
170         Boolean isVxlan = VpnUtil.isL3VpnOverVxLan(vpnOpEntry.getL3vni());
171         VrfEntry.EncapType encapType = VpnUtil.getEncapType(isVxlan);
172         if (vpnRd == null) {
173             String message = "Could not find Route-Distinguisher for VpnName " + vpnInstanceName;
174             result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(RpcError.ErrorType.APPLICATION,
175                 message).build());
176             return result;
177         }
178
179         Optional<InterVpnLinkDataComposite> optIVpnLink = interVpnLinkCache.getInterVpnLinkByEndpoint(nexthop);
180         if (optIVpnLink.isPresent()) {
181             try {
182                 interVpnLinkUtil.handleStaticRoute(optIVpnLink.get(), vpnInstanceName, destination, nexthop,
183                                                    label.intValue());
184             } catch (Exception e) {
185                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(ErrorType.APPLICATION,
186                         formatAndLog(LOG::warn,
187                                 "Could not advertise route [vpn={}, prefix={}, label={}, nexthop={}] to BGP: {}", vpnRd,
188                                 destination, label, nexthop, e.getMessage(), e)).build());
189                 return result;
190             }
191         } else {
192             try {
193                 txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
194                     confTx -> vpnManager.addExtraRoute(vpnInstanceName, destination, nexthop, vpnRd,
195                             null /* routerId */, vpnOpEntry.getL3vni(), RouteOrigin.STATIC, null /* intfName */,
196                         null /*Adjacency*/, encapType, new HashSet<>() /*prefixListForRefreshFib*/,confTx)).get();
197             } catch (InterruptedException | ExecutionException e) {
198                 LOG.error("Error adding static route {}", input, e);
199                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(ErrorType.APPLICATION,
200                     "Error adding static route " + input, e).build());
201                 return result;
202             }
203         }
204
205         AddStaticRouteOutput labelOutput = new AddStaticRouteOutputBuilder().setLabel(label).build();
206         result.set(RpcResultBuilder.success(labelOutput).build());
207         return result;
208     }
209
210     private Collection<RpcError> validateRemoveStaticRouteInput(RemoveStaticRouteInput input) {
211         Collection<RpcError> rpcErrors = new ArrayList<>();
212         String destination = input.getDestination();
213         String vpnInstanceName = input.getVpnInstanceName();
214         String nexthop = input.getNexthop();
215         if (destination == null || destination.isEmpty()) {
216             String message = "destination parameter is mandatory";
217             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
218         }
219         if (vpnInstanceName == null || vpnInstanceName.isEmpty()) {
220             String message = "vpnInstanceName parameter is mandatory";
221             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
222         }
223         if (nexthop == null || nexthop.isEmpty()) {
224             String message = "nexthop parameter is mandatory";
225             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
226         }
227         return rpcErrors;
228     }
229
230     @Override
231     public ListenableFuture<RpcResult<RemoveStaticRouteOutput>> removeStaticRoute(RemoveStaticRouteInput input) {
232
233         SettableFuture<RpcResult<RemoveStaticRouteOutput>> result = SettableFuture.create();
234
235         String destination = input.getDestination();
236         String vpnInstanceName = input.getVpnInstanceName();
237         String nexthop = input.getNexthop();
238         LOG.info("Removing static route with destination={}, nexthop={} in VPN={}",
239             destination, nexthop, vpnInstanceName);
240         Collection<RpcError> rpcErrors = validateRemoveStaticRouteInput(input);
241         if (!rpcErrors.isEmpty()) {
242             result.set(RpcResultBuilder.<RemoveStaticRouteOutput>failed().withRpcErrors(rpcErrors).build());
243             return result;
244         }
245
246         String vpnRd = vpnUtil.getVpnRd(input.getVpnInstanceName());
247         if (vpnRd == null) {
248             String message = "Could not find Route-Distinguisher for VpnName " + vpnInstanceName;
249             result.set(RpcResultBuilder.<RemoveStaticRouteOutput>failed()
250                     .withError(RpcError.ErrorType.APPLICATION, message).build());
251             return result;
252         }
253
254         Optional<InterVpnLinkDataComposite> optVpnLink = interVpnLinkCache.getInterVpnLinkByEndpoint(nexthop);
255         if (optVpnLink.isPresent()) {
256             fibManager.removeOrUpdateFibEntry(vpnRd, destination, nexthop, /*writeTx*/ null);
257             bgpManager.withdrawPrefix(vpnRd, destination);
258         } else {
259             vpnManager.delExtraRoute(vpnInstanceName, destination,
260                     nexthop, vpnRd, null /* routerId */, null /* intfName */, null,
261                     null);
262         }
263         result.set(RpcResultBuilder.success(new RemoveStaticRouteOutputBuilder().build()).build());
264
265         return result;
266
267     }
268
269     private String formatAndLog(Consumer<String> logger, String template, Object arg1, Object arg2) {
270         return logAndReturnMessage(logger, MessageFormatter.format(template, arg1, arg2));
271     }
272
273     private String formatAndLog(Consumer<String> logger, String template, Object... args) {
274         return logAndReturnMessage(logger, MessageFormatter.arrayFormat(template, args));
275     }
276
277     private String logAndReturnMessage(Consumer<String> logger, FormattingTuple tuple) {
278         String message = tuple.getMessage();
279         logger.accept(message);
280         return message;
281     }
282
283     @Override
284     public ListenableFuture<RpcResult<ApplyArpConfigOutput>> applyArpConfig(ApplyArpConfigInput input) {
285         Boolean isArpLearningEnabled = input.isEnableArpLearning();
286         LOG.info("isArpLearningEnabled {}", isArpLearningEnabled);
287         SettableFuture<RpcResult<ApplyArpConfigOutput>> result = SettableFuture.create();
288         ApplyArpConfigOutputBuilder output = new ApplyArpConfigOutputBuilder();
289         VpnUtil.enableArpLearning(isArpLearningEnabled);
290         output.setEnableArpLearning(VpnUtil.isArpLearningEnabled());
291         result.set(RpcResultBuilder.success(output).build());
292         return result;
293     }
294 }