Java 5 migration
[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 com.google.common.base.Optional;
11 import com.google.common.util.concurrent.SettableFuture;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.concurrent.Future;
15 import java.util.function.Consumer;
16 import javax.inject.Inject;
17 import javax.inject.Singleton;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.netvirt.bgpmanager.api.IBgpManager;
20 import org.opendaylight.netvirt.fibmanager.api.IFibManager;
21 import org.opendaylight.netvirt.fibmanager.api.RouteOrigin;
22 import org.opendaylight.netvirt.vpnmanager.api.IVpnManager;
23 import org.opendaylight.netvirt.vpnmanager.api.intervpnlink.InterVpnLinkCache;
24 import org.opendaylight.netvirt.vpnmanager.api.intervpnlink.InterVpnLinkDataComposite;
25 import org.opendaylight.netvirt.vpnmanager.intervpnlink.InterVpnLinkUtil;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntry;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.AddStaticRouteInput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.AddStaticRouteOutput;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.AddStaticRouteOutputBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelOutput;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelOutputBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveStaticRouteInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveVpnLabelInput;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.VpnRpcService;
38 import org.opendaylight.yangtools.yang.common.RpcError;
39 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
40 import org.opendaylight.yangtools.yang.common.RpcResult;
41 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.slf4j.helpers.FormattingTuple;
45 import org.slf4j.helpers.MessageFormatter;
46
47 @Singleton
48 public class VpnRpcServiceImpl implements VpnRpcService {
49     private static final Logger LOG = LoggerFactory.getLogger(VpnRpcServiceImpl.class);
50     private final DataBroker dataBroker;
51     private final IdManagerService idManager;
52     private final IFibManager fibManager;
53     private final IBgpManager bgpManager;
54     private final IVpnManager vpnManager;
55     private final InterVpnLinkCache interVpnLinkCache;
56
57     @Inject
58     public VpnRpcServiceImpl(final DataBroker dataBroker, final IdManagerService idManager,
59             final IFibManager fibManager, IBgpManager bgpManager, final IVpnManager vpnManager,
60             final InterVpnLinkCache interVpnLinkCache) {
61         this.dataBroker = dataBroker;
62         this.idManager = idManager;
63         this.fibManager = fibManager;
64         this.bgpManager = bgpManager;
65         this.vpnManager = vpnManager;
66         this.interVpnLinkCache = interVpnLinkCache;
67     }
68
69     /**
70      * Generate label for the given ip prefix from the associated VPN.
71      */
72     @Override
73     public Future<RpcResult<GenerateVpnLabelOutput>> generateVpnLabel(GenerateVpnLabelInput input) {
74         String vpnName = input.getVpnName();
75         String ipPrefix = input.getIpPrefix();
76         SettableFuture<RpcResult<GenerateVpnLabelOutput>> futureResult = SettableFuture.create();
77         String rd = VpnUtil.getVpnRd(dataBroker, vpnName);
78         long label = VpnUtil.getUniqueId(idManager, VpnConstants.VPN_IDPOOL_NAME,
79             VpnUtil.getNextHopLabelKey(rd != null ? rd : vpnName, ipPrefix));
80         if (label == 0) {
81             futureResult.set(RpcResultBuilder.<GenerateVpnLabelOutput>failed().withError(ErrorType.APPLICATION,
82                     formatAndLog(LOG::error, "Could not retrieve the label for prefix {} in VPN {}", ipPrefix,
83                             vpnName)).build());
84         } else {
85             GenerateVpnLabelOutput output = new GenerateVpnLabelOutputBuilder().setLabel(label).build();
86             futureResult.set(RpcResultBuilder.success(output).build());
87         }
88         return futureResult;
89     }
90
91     /**
92      * Remove label for the given ip prefix from the associated VPN.
93      */
94     @Override
95     public Future<RpcResult<Void>> removeVpnLabel(RemoveVpnLabelInput input) {
96         String vpnName = input.getVpnName();
97         String ipPrefix = input.getIpPrefix();
98         String rd = VpnUtil.getVpnRd(dataBroker, vpnName);
99         SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
100         VpnUtil.releaseId(idManager, VpnConstants.VPN_IDPOOL_NAME,
101             VpnUtil.getNextHopLabelKey(rd != null ? rd : vpnName, ipPrefix));
102         futureResult.set(RpcResultBuilder.<Void>success().build());
103         return futureResult;
104     }
105
106     private Collection<RpcError> validateAddStaticRouteInput(AddStaticRouteInput input) {
107         Collection<RpcError> rpcErrors = new ArrayList<>();
108         String destination = input.getDestination();
109         String vpnInstanceName = input.getVpnInstanceName();
110         String nexthop = input.getNexthop();
111         if (destination == null || destination.isEmpty()) {
112             String message = "destination parameter is mandatory";
113             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
114         }
115         if (vpnInstanceName == null || vpnInstanceName.isEmpty()) {
116             String message = "vpnInstanceName parameter is mandatory";
117             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
118         }
119         if (nexthop == null || nexthop.isEmpty()) {
120             String message = "nexthop parameter is mandatory";
121             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "addStaticRoute", message));
122         }
123         return rpcErrors;
124     }
125
126     // TODO Clean up the exception handling
127     @SuppressWarnings("checkstyle:IllegalCatch")
128     @Override
129     public Future<RpcResult<AddStaticRouteOutput>> addStaticRoute(AddStaticRouteInput input) {
130
131         SettableFuture<RpcResult<AddStaticRouteOutput>> result = SettableFuture.create();
132         String destination = input.getDestination();
133         String vpnInstanceName = input.getVpnInstanceName();
134         String nexthop = input.getNexthop();
135         Long label = input.getLabel();
136         LOG.info("Adding static route for Vpn {} with destination {}, nexthop {} and label {}",
137             vpnInstanceName, destination, nexthop, label);
138
139         Collection<RpcError> rpcErrors = validateAddStaticRouteInput(input);
140         if (!rpcErrors.isEmpty()) {
141             result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withRpcErrors(rpcErrors).build());
142             return result;
143         }
144
145         if (label == null || label == 0) {
146             label = (long) VpnUtil.getUniqueId(idManager, VpnConstants.VPN_IDPOOL_NAME,
147                 VpnUtil.getNextHopLabelKey(vpnInstanceName, destination));
148             if (label == 0) {
149                 String message = "Unable to retrieve a new Label for the new Route";
150                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(RpcError.ErrorType.APPLICATION,
151                     message).build());
152                 return result;
153             }
154         }
155
156         String vpnRd = VpnUtil.getVpnRd(dataBroker, input.getVpnInstanceName());
157         VpnInstanceOpDataEntry vpnOpEntry = VpnUtil.getVpnInstanceOpData(dataBroker, vpnRd);
158         Boolean isVxlan = VpnUtil.isL3VpnOverVxLan(vpnOpEntry.getL3vni());
159         VrfEntry.EncapType encapType = VpnUtil.getEncapType(isVxlan);
160         if (vpnRd == null) {
161             String message = "Could not find Route-Distinguisher for VpnName " + vpnInstanceName;
162             result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(RpcError.ErrorType.APPLICATION,
163                 message).build());
164             return result;
165         }
166
167         Optional<InterVpnLinkDataComposite> optIVpnLink = interVpnLinkCache.getInterVpnLinkByEndpoint(nexthop);
168         if (optIVpnLink.isPresent()) {
169             try {
170                 InterVpnLinkUtil.handleStaticRoute(optIVpnLink.get(), vpnInstanceName, destination, nexthop,
171                                                    label.intValue(),
172                                                    dataBroker, fibManager, bgpManager);
173             } catch (Exception e) {
174                 result.set(RpcResultBuilder.<AddStaticRouteOutput>failed().withError(ErrorType.APPLICATION,
175                         formatAndLog(LOG::warn,
176                                 "Could not advertise route [vpn={}, prefix={}, label={}, nexthop={}] to BGP: {}", vpnRd,
177                                 destination, label, nexthop, e.getMessage(), e)).build());
178                 return result;
179             }
180         } else {
181             vpnManager.addExtraRoute(vpnInstanceName, destination, nexthop, vpnRd, null /* routerId */,
182                     vpnOpEntry.getL3vni(), RouteOrigin.STATIC, null /* intfName */,
183                             null /*Adjacency*/, encapType, null);
184         }
185
186         AddStaticRouteOutput labelOutput = new AddStaticRouteOutputBuilder().setLabel(label).build();
187         result.set(RpcResultBuilder.success(labelOutput).build());
188         return result;
189     }
190
191     private Collection<RpcError> validateRemoveStaticRouteInput(RemoveStaticRouteInput input) {
192         Collection<RpcError> rpcErrors = new ArrayList<>();
193         String destination = input.getDestination();
194         String vpnInstanceName = input.getVpnInstanceName();
195         String nexthop = input.getNexthop();
196         if (destination == null || destination.isEmpty()) {
197             String message = "destination parameter is mandatory";
198             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
199         }
200         if (vpnInstanceName == null || vpnInstanceName.isEmpty()) {
201             String message = "vpnInstanceName parameter is mandatory";
202             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
203         }
204         if (nexthop == null || nexthop.isEmpty()) {
205             String message = "nexthop parameter is mandatory";
206             rpcErrors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL, "removeStaticRoute", message));
207         }
208         return rpcErrors;
209     }
210
211     @Override
212     public Future<RpcResult<Void>> removeStaticRoute(RemoveStaticRouteInput input) {
213
214         SettableFuture<RpcResult<Void>> result = SettableFuture.create();
215
216         String destination = input.getDestination();
217         String vpnInstanceName = input.getVpnInstanceName();
218         String nexthop = input.getNexthop();
219         LOG.info("Removing static route with destination={}, nexthop={} in VPN={}",
220             destination, nexthop, vpnInstanceName);
221         Collection<RpcError> rpcErrors = validateRemoveStaticRouteInput(input);
222         if (!rpcErrors.isEmpty()) {
223             result.set(RpcResultBuilder.<Void>failed().withRpcErrors(rpcErrors).build());
224             return result;
225         }
226
227         String vpnRd = VpnUtil.getVpnRd(dataBroker, input.getVpnInstanceName());
228         if (vpnRd == null) {
229             String message = "Could not find Route-Distinguisher for VpnName " + vpnInstanceName;
230             result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, message).build());
231             return result;
232         }
233
234         Optional<InterVpnLinkDataComposite> optVpnLink = interVpnLinkCache.getInterVpnLinkByEndpoint(nexthop);
235         if (optVpnLink.isPresent()) {
236             fibManager.removeOrUpdateFibEntry(vpnRd, destination, nexthop, /*writeTx*/ null);
237             bgpManager.withdrawPrefix(vpnRd, destination);
238         } else {
239             vpnManager.delExtraRoute(vpnInstanceName, destination,
240                     nexthop, vpnRd, null /* routerId */, null /* intfName */, null);
241         }
242         result.set(RpcResultBuilder.<Void>success().build());
243
244         return result;
245     }
246
247     private String formatAndLog(Consumer<String> logger, String template, Object arg1, Object arg2) {
248         return logAndReturnMessage(logger, MessageFormatter.format(template, arg1, arg2));
249     }
250
251     private String formatAndLog(Consumer<String> logger, String template, Object... args) {
252         return logAndReturnMessage(logger, MessageFormatter.arrayFormat(template, args));
253     }
254
255     private String logAndReturnMessage(Consumer<String> logger, FormattingTuple tuple) {
256         String message = tuple.getMessage();
257         logger.accept(message);
258         return message;
259     }
260 }