NETVIRT-1630 migrate to md-sal APIs
[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.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.SettableFuture;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.HashSet;
17 import java.util.Optional;
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.genius.infra.ManagedNewTransactionRunner;
23 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
24 import org.opendaylight.mdsal.binding.api.DataBroker;
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.opendaylight.yangtools.yang.common.Uint32;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.slf4j.helpers.FormattingTuple;
58 import org.slf4j.helpers.MessageFormatter;
59
60 @Singleton
61 public class VpnRpcServiceImpl implements VpnRpcService {
62     private static final Logger LOG = LoggerFactory.getLogger(VpnRpcServiceImpl.class);
63     private final ManagedNewTransactionRunner txRunner;
64     private final IFibManager fibManager;
65     private final IBgpManager bgpManager;
66     private final IVpnManager vpnManager;
67     private final InterVpnLinkCache interVpnLinkCache;
68     private final VpnUtil vpnUtil;
69     private final InterVpnLinkUtil interVpnLinkUtil;
70
71     @Inject
72     public VpnRpcServiceImpl(final DataBroker dataBroker,
73             final IFibManager fibManager, IBgpManager bgpManager, final IVpnManager vpnManager,
74             final InterVpnLinkCache interVpnLinkCache, VpnUtil vpnUtil, InterVpnLinkUtil interVpnLinkUtil) {
75         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
76         this.fibManager = fibManager;
77         this.bgpManager = bgpManager;
78         this.vpnManager = vpnManager;
79         this.interVpnLinkCache = interVpnLinkCache;
80         this.vpnUtil = vpnUtil;
81         this.interVpnLinkUtil = interVpnLinkUtil;
82     }
83
84     /**
85      * Generate label for the given ip prefix from the associated VPN.
86      */
87     @Override
88     public ListenableFuture<RpcResult<GenerateVpnLabelOutput>> generateVpnLabel(GenerateVpnLabelInput input) {
89         String vpnName = input.getVpnName();
90         String ipPrefix = input.getIpPrefix();
91         SettableFuture<RpcResult<GenerateVpnLabelOutput>> futureResult = SettableFuture.create();
92         String rd = vpnUtil.getVpnRd(vpnName);
93         Uint32 label = vpnUtil.getUniqueId(VpnConstants.VPN_IDPOOL_NAME,
94             VpnUtil.getNextHopLabelKey(rd != null ? rd : vpnName, ipPrefix));
95         if (label == null || label.longValue() == VpnConstants.INVALID_LABEL) {
96             futureResult.set(RpcResultBuilder.<GenerateVpnLabelOutput>failed().withError(ErrorType.APPLICATION,
97                     formatAndLog(LOG::error, "Could not retrieve the label for prefix {} in VPN {}", ipPrefix,
98                             vpnName)).build());
99         } else {
100             GenerateVpnLabelOutput output = new GenerateVpnLabelOutputBuilder().setLabel(label).build();
101             futureResult.set(RpcResultBuilder.success(output).build());
102         }
103         return futureResult;
104     }
105
106     /**
107      * Remove label for the given ip prefix from the associated VPN.
108      */
109     @Override
110     public ListenableFuture<RpcResult<RemoveVpnLabelOutput>> removeVpnLabel(RemoveVpnLabelInput input) {
111         String vpnName = input.getVpnName();
112         String ipPrefix = input.getIpPrefix();
113         String rd = vpnUtil.getVpnRd(vpnName);
114         vpnUtil.releaseId(VpnConstants.VPN_IDPOOL_NAME,
115             VpnUtil.getNextHopLabelKey(rd != null ? rd : vpnName, ipPrefix));
116         return RpcResultBuilder.success(new RemoveVpnLabelOutputBuilder().build()).buildFuture();
117     }
118
119     private Collection<RpcError> validateAddStaticRouteInput(AddStaticRouteInput input) {
120         Collection<RpcError> rpcErrors = new ArrayList<>();
121         String destination = input.getDestination();
122         String vpnInstanceName = input.getVpnInstanceName();
123         String nexthop = input.getNexthop();
124         if (destination == null || destination.isEmpty()) {
125             String message = "destination parameter is mandatory";
126             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
127         }
128         if (vpnInstanceName == null || vpnInstanceName.isEmpty()) {
129             String message = "vpnInstanceName parameter is mandatory";
130             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
131         }
132         if (nexthop == null || nexthop.isEmpty()) {
133             String message = "nexthop parameter is mandatory";
134             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
135         }
136         return rpcErrors;
137     }
138
139     // TODO Clean up the exception handling
140     @SuppressWarnings("checkstyle:IllegalCatch")
141     @Override
142     public ListenableFuture<RpcResult<AddStaticRouteOutput>> addStaticRoute(AddStaticRouteInput input) {
143
144         SettableFuture<RpcResult<AddStaticRouteOutput>> result = SettableFuture.create();
145         String destination = input.getDestination();
146         String vpnInstanceName = input.getVpnInstanceName();
147         String nexthop = input.getNexthop();
148         Uint32 label = input.getLabel();
149         LOG.info("Adding static route for Vpn {} with destination {}, nexthop {} and label {}",
150             vpnInstanceName, destination, nexthop, label);
151
152         Collection<RpcError> rpcErrors = validateAddStaticRouteInput(input);
153         if (!rpcErrors.isEmpty()) {
154             result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withRpcErrors(rpcErrors).build());
155             return result;
156         }
157
158         if (label == null || label.longValue() == VpnConstants.INVALID_LABEL) {
159             label = vpnUtil.getUniqueId(VpnConstants.VPN_IDPOOL_NAME,
160                 VpnUtil.getNextHopLabelKey(vpnInstanceName, destination));
161             if (label.longValue() == VpnConstants.INVALID_LABEL) {
162                 String message = "Unable to retrieve a new Label for the new Route";
163                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(RpcError.ErrorType.APPLICATION,
164                     message).build());
165                 LOG.error("addStaticRoute: Unable to retrieve label for static route with destination {}, vpninstance"
166                         + " {}, nexthop {}", destination, vpnInstanceName, nexthop);
167                 return result;
168             }
169         }
170
171         String vpnRd = vpnUtil.getVpnRd(input.getVpnInstanceName());
172         VpnInstanceOpDataEntry vpnOpEntry = vpnUtil.getVpnInstanceOpData(vpnRd);
173         Boolean isVxlan = VpnUtil.isL3VpnOverVxLan(vpnOpEntry.getL3vni());
174         VrfEntry.EncapType encapType = VpnUtil.getEncapType(isVxlan);
175         if (vpnRd == null) {
176             String message = "Could not find Route-Distinguisher for VpnName " + vpnInstanceName;
177             result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(RpcError.ErrorType.APPLICATION,
178                 message).build());
179             return result;
180         }
181
182         Optional<InterVpnLinkDataComposite> optIVpnLink = interVpnLinkCache.getInterVpnLinkByEndpoint(nexthop);
183         if (optIVpnLink.isPresent()) {
184             try {
185                 interVpnLinkUtil.handleStaticRoute(optIVpnLink.get(), vpnInstanceName, destination, nexthop, label);
186             } catch (Exception e) {
187                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(ErrorType.APPLICATION,
188                         formatAndLog(LOG::warn,
189                                 "Could not advertise route [vpn={}, prefix={}, label={}, nexthop={}] to BGP: {}", vpnRd,
190                                 destination, label, nexthop, e.getMessage(), e)).build());
191                 return result;
192             }
193         } else {
194             try {
195                 txRunner.callWithNewWriteOnlyTransactionAndSubmit(CONFIGURATION,
196                     confTx -> vpnManager.addExtraRoute(vpnInstanceName, destination, nexthop, vpnRd,
197                             null /* routerId */, vpnOpEntry.getL3vni(),
198                             RouteOrigin.STATIC, null /* intfName */,
199                         null /*Adjacency*/, encapType, new HashSet<>() /*prefixListForRefreshFib*/,confTx)).get();
200             } catch (InterruptedException | ExecutionException e) {
201                 LOG.error("Error adding static route {}", input, e);
202                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(ErrorType.APPLICATION,
203                     "Error adding static route " + input, e).build());
204                 return result;
205             }
206         }
207
208         AddStaticRouteOutput labelOutput = new AddStaticRouteOutputBuilder().setLabel(label).build();
209         result.set(RpcResultBuilder.success(labelOutput).build());
210         return result;
211     }
212
213     private Collection<RpcError> validateRemoveStaticRouteInput(RemoveStaticRouteInput input) {
214         Collection<RpcError> rpcErrors = new ArrayList<>();
215         String destination = input.getDestination();
216         String vpnInstanceName = input.getVpnInstanceName();
217         String nexthop = input.getNexthop();
218         if (destination == null || destination.isEmpty()) {
219             String message = "destination parameter is mandatory";
220             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
221         }
222         if (vpnInstanceName == null || vpnInstanceName.isEmpty()) {
223             String message = "vpnInstanceName parameter is mandatory";
224             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
225         }
226         if (nexthop == null || nexthop.isEmpty()) {
227             String message = "nexthop parameter is mandatory";
228             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
229         }
230         return rpcErrors;
231     }
232
233     @Override
234     public ListenableFuture<RpcResult<RemoveStaticRouteOutput>> removeStaticRoute(RemoveStaticRouteInput input) {
235
236         SettableFuture<RpcResult<RemoveStaticRouteOutput>> result = SettableFuture.create();
237
238         String destination = input.getDestination();
239         String vpnInstanceName = input.getVpnInstanceName();
240         String nexthop = input.getNexthop();
241         LOG.info("Removing static route with destination={}, nexthop={} in VPN={}",
242             destination, nexthop, vpnInstanceName);
243         Collection<RpcError> rpcErrors = validateRemoveStaticRouteInput(input);
244         if (!rpcErrors.isEmpty()) {
245             result.set(RpcResultBuilder.<RemoveStaticRouteOutput>failed().withRpcErrors(rpcErrors).build());
246             return result;
247         }
248
249         String vpnRd = vpnUtil.getVpnRd(input.getVpnInstanceName());
250         if (vpnRd == null) {
251             String message = "Could not find Route-Distinguisher for VpnName " + vpnInstanceName;
252             result.set(RpcResultBuilder.<RemoveStaticRouteOutput>failed()
253                     .withError(RpcError.ErrorType.APPLICATION, message).build());
254             return result;
255         }
256
257         Optional<InterVpnLinkDataComposite> optVpnLink = interVpnLinkCache.getInterVpnLinkByEndpoint(nexthop);
258         if (optVpnLink.isPresent()) {
259             fibManager.removeOrUpdateFibEntry(vpnRd, destination, nexthop, /*writeTx*/ null);
260             bgpManager.withdrawPrefix(vpnRd, destination);
261         } else {
262             vpnManager.delExtraRoute(vpnInstanceName, destination,
263                     nexthop, vpnRd, null /* routerId */, null /* intfName */, null,
264                     null);
265         }
266         result.set(RpcResultBuilder.success(new RemoveStaticRouteOutputBuilder().build()).build());
267
268         return result;
269
270     }
271
272     private String formatAndLog(Consumer<String> logger, String template, Object arg1, Object arg2) {
273         return logAndReturnMessage(logger, MessageFormatter.format(template, arg1, arg2));
274     }
275
276     private String formatAndLog(Consumer<String> logger, String template, Object... args) {
277         return logAndReturnMessage(logger, MessageFormatter.arrayFormat(template, args));
278     }
279
280     private String logAndReturnMessage(Consumer<String> logger, FormattingTuple tuple) {
281         String message = tuple.getMessage();
282         logger.accept(message);
283         return message;
284     }
285
286     @Override
287     public ListenableFuture<RpcResult<ApplyArpConfigOutput>> applyArpConfig(ApplyArpConfigInput input) {
288         Boolean isArpLearningEnabled = input.isEnableArpLearning();
289         LOG.info("isArpLearningEnabled {}", isArpLearningEnabled);
290         SettableFuture<RpcResult<ApplyArpConfigOutput>> result = SettableFuture.create();
291         ApplyArpConfigOutputBuilder output = new ApplyArpConfigOutputBuilder();
292         VpnUtil.enableArpLearning(isArpLearningEnabled);
293         output.setEnableArpLearning(VpnUtil.isArpLearningEnabled());
294         result.set(RpcResultBuilder.success(output).build());
295         return result;
296     }
297 }