Fix lisp route for public interfaces
[groupbasedpolicy.git] / renderers / vpp / src / main / java / org / opendaylight / groupbasedpolicy / renderer / vpp / iface / InterfaceManager.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. 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
9 package org.opendaylight.groupbasedpolicy.renderer.vpp.iface;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.HashMultimap;
15 import com.google.common.collect.SetMultimap;
16 import com.google.common.eventbus.Subscribe;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20
21 import java.util.List;
22 import java.util.Set;
23 import java.util.concurrent.ExecutionException;
24
25 import javax.annotation.Nonnull;
26 import javax.annotation.Nullable;
27
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
31 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.AbstractInterfaceCommand;
32 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.LoopbackCommand;
33 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.TapPortCommand;
34 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.VhostUserCommand;
35 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.VhostUserCommand.VhostUserCommandBuilder;
36 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.interfaces.ConfigCommand;
37 import org.opendaylight.groupbasedpolicy.renderer.vpp.config.ConfigUtil;
38 import org.opendaylight.groupbasedpolicy.renderer.vpp.event.NodeOperEvent;
39 import org.opendaylight.groupbasedpolicy.renderer.vpp.event.VppEndpointConfEvent;
40 import org.opendaylight.groupbasedpolicy.renderer.vpp.lisp.flat.overlay.FlatOverlayManager;
41 import org.opendaylight.groupbasedpolicy.renderer.vpp.policy.acl.AccessListWrapper;
42 import org.opendaylight.groupbasedpolicy.renderer.vpp.util.GbpNetconfTransaction;
43 import org.opendaylight.groupbasedpolicy.renderer.vpp.util.General.Operations;
44 import org.opendaylight.groupbasedpolicy.renderer.vpp.util.MountedDataBrokerProvider;
45 import org.opendaylight.groupbasedpolicy.renderer.vpp.util.VppIidFactory;
46 import org.opendaylight.groupbasedpolicy.renderer.vpp.util.VppRendererProcessingException;
47 import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
48 import org.opendaylight.vbd.impl.transaction.VbdNetconfTransaction;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.LocationType;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.location.type.ExternalLocationCase;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.location.type.ExternalLocationCaseBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.renderers.renderer.renderer.policy.configuration.endpoints.AddressEndpointWithLocation;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425.ExcludeFromPolicy;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes.InterfaceTypeChoice;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes._interface.type.choice.LoopbackCase;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes._interface.type.choice.TapCase;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes._interface.type.choice.VhostUserCase;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425.config.VppEndpoint;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.VhostUserRole;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.VppInterfaceAugmentation;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.interfaces._interface.L2;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.interfaces._interface.L2Builder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.l2.config.attributes.Interconnection;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.l2.config.attributes.interconnection.BridgeBased;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.l2.config.attributes.interconnection.BridgeBasedBuilder;
68 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
69 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
70 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73
74 public class InterfaceManager implements AutoCloseable {
75
76     private static final Logger LOG = LoggerFactory.getLogger(InterfaceManager.class);
77     private final MountedDataBrokerProvider mountDataProvider;
78     private final VppEndpointLocationProvider vppEndpointLocationProvider;
79     private final SetMultimap<NodeId, String> excludedFromPolicy = HashMultimap.create();
80     private final FlatOverlayManager flatOverlayManager;
81
82     public InterfaceManager(@Nonnull MountedDataBrokerProvider mountDataProvider, @Nonnull DataBroker dataProvider,
83                             FlatOverlayManager flatOverlayManager) {
84         this.mountDataProvider = Preconditions.checkNotNull(mountDataProvider);
85         this.vppEndpointLocationProvider = new VppEndpointLocationProvider(dataProvider);
86         this.flatOverlayManager = flatOverlayManager;
87     }
88
89     @Subscribe
90     @SuppressWarnings("OptionalGetWithoutIsPresent")
91     public synchronized void vppEndpointChanged(VppEndpointConfEvent event) {
92         String message;
93         final VppEndpoint oldVppEndpoint = event.getBefore().orNull();
94         final VppEndpoint newVppEndpoint = event.getAfter().orNull();
95         try {
96         switch (event.getDtoModificationType()) {
97             case CREATED: {
98                 Preconditions.checkNotNull(newVppEndpoint);
99                     vppEndpointCreated(newVppEndpoint).get();
100                 message = String.format("Vpp endpoint %s on node %s and interface %s created",
101                         newVppEndpoint.getAddress(), newVppEndpoint.getVppNodeId().getValue(),
102                         newVppEndpoint.getVppInterfaceName());
103                 updatePolicyExcludedEndpoints(newVppEndpoint, true).get();
104             }
105             break;
106             case UPDATED: {
107                 Preconditions.checkNotNull(oldVppEndpoint);
108                 Preconditions.checkNotNull(newVppEndpoint);
109                 vppEndpointUpdated(oldVppEndpoint, newVppEndpoint).get();
110                 message = String.format("Vpp endpoint %s on node %s and interface %s updated",
111                         newVppEndpoint.getAddress(), newVppEndpoint.getVppNodeId().getValue(),
112                         newVppEndpoint.getVppInterfaceName());
113                         updatePolicyExcludedEndpoints(oldVppEndpoint, true).get();
114             }
115             break;
116             case DELETED: {
117                 Preconditions.checkNotNull(oldVppEndpoint);
118                 vppEndpointDeleted(oldVppEndpoint).get();
119                 message = String.format("Vpp endpoint %s on node %s and interface %s removed",
120                         oldVppEndpoint.getAddress(), oldVppEndpoint.getVppNodeId().getValue(),
121                         oldVppEndpoint.getVppInterfaceName());
122                 updatePolicyExcludedEndpoints(event.getBefore().get(), false).get();
123             }
124             break;
125                 default: {
126                     message = "Unknown event modification type: " + event.getDtoModificationType();
127                     LOG.error("Failed to process VPP endpoint {}. {}",
128                             (oldVppEndpoint != null) ? oldVppEndpoint.getKey() : newVppEndpoint.getKey(),
129                             event.getAfter(), new VppRendererProcessingException(message));
130                 }
131         }
132         LOG.info(message);
133         } catch (InterruptedException | ExecutionException e) {
134             LOG.error("Failed to process changed vpp endpoint. before: {}, after: {}.Exception: {} ", event.getBefore(),
135                     event.getAfter(), e);
136         }
137     }
138
139     private ListenableFuture<Boolean> updatePolicyExcludedEndpoints(VppEndpoint vppEndpoint, boolean created) {
140         if (vppEndpoint == null || vppEndpoint.getAugmentation(ExcludeFromPolicy.class) == null) {
141             return Futures.immediateFuture(true);
142         }
143         if (created) {
144             LOG.trace("Interface excluded from policy: node:{} interface:{}", vppEndpoint.getVppNodeId(),
145                     vppEndpoint.getVppInterfaceName());
146             excludedFromPolicy.put(vppEndpoint.getVppNodeId(), vppEndpoint.getVppInterfaceName());
147             return Futures.immediateFuture(true);
148         }
149         return Futures.immediateFuture(excludedFromPolicy.remove(vppEndpoint.getVppNodeId(),
150                 vppEndpoint.getVppInterfaceName()));
151     }
152
153     private ListenableFuture<Void> vppEndpointCreated(VppEndpoint vppEndpoint) {
154         InterfaceTypeChoice interfaceTypeChoice = vppEndpoint.getInterfaceTypeChoice();
155         LOG.trace("Creating VPP endpoint {}, type of {}", vppEndpoint, interfaceTypeChoice);
156         Optional<AbstractInterfaceCommand> potentialIfaceCommand = Optional.absent();
157         if (interfaceTypeChoice instanceof VhostUserCase) {
158             potentialIfaceCommand = createVhostInterfaceWithoutBdCommand(vppEndpoint, Operations.PUT);
159         } else if (interfaceTypeChoice instanceof TapCase) {
160             potentialIfaceCommand = createTapInterfaceWithoutBdCommand(vppEndpoint, Operations.PUT);
161         } else if (interfaceTypeChoice instanceof LoopbackCase){
162             if (!ConfigUtil.getInstance().isL3FlatEnabled()) {
163                 potentialIfaceCommand = createLoopbackWithoutBdCommand(vppEndpoint, Operations.PUT);
164             }
165             else {
166                 LOG.trace("L3 flat enabled: LISP in VPP renderer will take care of creating loopback.");
167             }
168         }
169         if (!potentialIfaceCommand.isPresent()) {
170             LOG.debug("Interface/PUT command was not created for VppEndpoint point {}", vppEndpoint);
171             return Futures.immediateFuture(null);
172         }
173         ConfigCommand ifaceWithoutBdCommand = potentialIfaceCommand.get();
174         InstanceIdentifier<Node> vppNodeIid = VppIidFactory.getNetconfNodeIid(vppEndpoint.getVppNodeId());
175         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
176         if (!potentialVppDataProvider.isPresent()) {
177             final String message = "Cannot get data broker for mount point " + vppNodeIid;
178             LOG.warn(message);
179             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
180         }
181         return createInterfaceWithEndpointLocation(ifaceWithoutBdCommand, vppNodeIid, vppEndpoint);
182     }
183
184     public ListenableFuture<Void> createInterfaceOnVpp(final ConfigCommand createIfaceWithoutBdCommand,
185                                                        final InstanceIdentifier<Node> vppIid) {
186         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppIid, createIfaceWithoutBdCommand,
187                 GbpNetconfTransaction.RETRY_COUNT);
188         if (transactionState) {
189             LOG.trace("Creating Interface on VPP: {}", createIfaceWithoutBdCommand);
190             return Futures.immediateFuture(null);
191         } else {
192             final String message = "Failed to create Interface on VPP: " + createIfaceWithoutBdCommand;
193             LOG.warn(message);
194             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
195         }
196     }
197
198     private ListenableFuture<Void> createInterfaceWithEndpointLocation(final ConfigCommand createIfaceWithoutBdCommand,
199                                                                        final InstanceIdentifier<Node> vppIid,
200                                                                        final VppEndpoint vppEndpoint) {
201         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppIid, createIfaceWithoutBdCommand,
202                 GbpNetconfTransaction.RETRY_COUNT);
203         if (transactionState) {
204             LOG.debug("Create interface on VPP command was successful. VPP: {} Command: {}", vppIid,
205                     createIfaceWithoutBdCommand);
206             return vppEndpointLocationProvider.createLocationForVppEndpoint(vppEndpoint);
207         } else {
208             final String message = "Create interface on VPP command was not successful. VPP: " + vppIid
209             + " Command: " + createIfaceWithoutBdCommand;
210             LOG.warn(message);
211             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
212         }
213     }
214
215     private ListenableFuture<Void> vppEndpointUpdated(@Nonnull final VppEndpoint oldVppEndpoint,
216                                                       @Nonnull final VppEndpoint newVppEndpoint) {
217         if(!oldVppEndpoint.equals(newVppEndpoint)) {
218             LOG.debug("Updating vpp endpoint, old EP: {} new EP: {}", oldVppEndpoint, newVppEndpoint);
219             return Futures.transformAsync(vppEndpointDeleted(oldVppEndpoint),
220                 input -> vppEndpointCreated(newVppEndpoint), MoreExecutors.directExecutor());
221         }
222         LOG.debug("Update skipped, provided before/after vpp endpoints are equal");
223         return Futures.immediateFuture(null);
224     }
225
226     private ListenableFuture<Void> vppEndpointDeleted(@Nonnull VppEndpoint vppEndpoint) {
227         InterfaceTypeChoice interfaceTypeChoice = vppEndpoint.getInterfaceTypeChoice();
228         LOG.trace("Deleting VPP endpoint {}, type of {}", vppEndpoint, interfaceTypeChoice.toString());
229         Optional<AbstractInterfaceCommand> potentialIfaceCommand = Optional.absent();
230         if (interfaceTypeChoice instanceof VhostUserCase) {
231             potentialIfaceCommand = createVhostInterfaceWithoutBdCommand(vppEndpoint, Operations.DELETE);
232         } else if (interfaceTypeChoice instanceof TapCase) {
233             potentialIfaceCommand = createTapInterfaceWithoutBdCommand(vppEndpoint, Operations.DELETE);
234         } else if (interfaceTypeChoice instanceof LoopbackCase){
235             if (!ConfigUtil.getInstance().isL3FlatEnabled()) {
236                 potentialIfaceCommand = createLoopbackWithoutBdCommand(vppEndpoint, Operations.DELETE);
237             }
238             else {
239                 LOG.trace("L3 flat enabled: LISP in VPP renderer will take care of delete for loopback.");
240             }
241         }
242
243
244         if (!potentialIfaceCommand.isPresent()) {
245             LOG.debug("Interface/DELETE command was not created for VppEndpoint point {}", vppEndpoint);
246             return Futures.immediateFuture(null);
247         }
248         AbstractInterfaceCommand ifaceWithoutBdCommand = potentialIfaceCommand.get();
249         InstanceIdentifier<Node> vppNodeIid = VppIidFactory.getNetconfNodeIid(vppEndpoint.getVppNodeId());
250         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
251         if (!potentialVppDataProvider.isPresent()) {
252             final String message = "Cannot get data broker for mount point " + vppNodeIid;
253             LOG.warn(message);
254             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
255         }
256
257         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
258             flatOverlayManager.handleInterfaceDeleteForFlatOverlay(vppEndpoint);
259         }
260         return deleteIfaceOnVpp(ifaceWithoutBdCommand, vppNodeIid, vppEndpoint);
261     }
262
263     private ListenableFuture<Void> deleteIfaceOnVpp(AbstractInterfaceCommand interfaceCommand,
264         InstanceIdentifier<Node> vppIid, VppEndpoint vppEndpoint) {
265         final boolean transactionState = GbpNetconfTransaction.netconfSyncedDelete(vppIid, interfaceCommand,
266             GbpNetconfTransaction.RETRY_COUNT);
267         if (transactionState) {
268             LOG.debug("Delete interface on VPP command was successful: VPP: {} Command: {}", vppIid, interfaceCommand);
269             AccessListWrapper.removeAclsForInterface(vppIid, new InterfaceKey(interfaceCommand.getName()));
270             return vppEndpointLocationProvider.deleteLocationForVppEndpoint(vppEndpoint);
271         } else {
272             final String message = "Delete interface on VPP command was not successful: VPP: " + vppIid
273                     + " Command: " + interfaceCommand;
274             LOG.warn(message);
275             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
276         }
277     }
278
279     @Subscribe
280     public synchronized void vppNodeChanged(NodeOperEvent event) {
281         switch (event.getDtoModificationType()) {
282             case CREATED:
283                 if (event.isAfterConnected()) {
284                     // TODO read VppEndpoints or cache them during vppEndpointChanged()
285                 }
286                 break;
287             case UPDATED:
288                 if (!event.isBeforeConnected() && event.isAfterConnected()) {
289                     // TODO reconciliation - diff between disconnected snapshot and current snapshot
290                 }
291                 break;
292             case DELETED:
293                 if (event.isBeforeConnected()) {
294                     // TODO we could do snapshot of VppEndpoints
295                     // which can be used for reconciliation
296                 }
297                 break;
298         }
299     }
300
301     private Optional<AbstractInterfaceCommand> createVhostInterfaceWithoutBdCommand(@Nonnull VppEndpoint vppEp,
302                                                                                     @Nonnull Operations operations) {
303         if (!hasNodeAndInterface(vppEp)) {
304             LOG.debug("Interface command is not created for {}", vppEp);
305             return Optional.absent();
306         }
307         VhostUserCommandBuilder builder = VhostUserCommand.builder();
308         builder.setName(vppEp.getVppInterfaceName());
309         InterfaceTypeChoice interfaceTypeChoice = vppEp.getInterfaceTypeChoice();
310         if (interfaceTypeChoice instanceof VhostUserCase) {
311             VhostUserCase vhostUserIface = (VhostUserCase) interfaceTypeChoice;
312             String socket = vhostUserIface.getSocket();
313             if (Strings.isNullOrEmpty(socket)) {
314                 LOG.debug("Vhost user interface command is not created because socket is missing. {}", vppEp);
315                 return Optional.absent();
316             }
317             builder.setSocket(socket);
318             builder.setRole(VhostUserRole.Client);
319         }
320         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
321             builder.setEnableProxyArp(true);
322             builder.setSnatEnabled(true);
323         }
324         VhostUserCommand vhostUserCommand =
325                 builder.setOperation(operations).setDescription(vppEp.getDescription()).build();
326         return Optional.of(vhostUserCommand);
327     }
328
329     private Optional<AbstractInterfaceCommand> createTapInterfaceWithoutBdCommand(@Nonnull VppEndpoint vppEp,
330             @Nonnull Operations operation) {
331         if (!hasNodeAndInterface(vppEp)) {
332             LOG.debug("Interface command is not created for {}", vppEp);
333             return Optional.absent();
334         }
335         TapPortCommand.TapPortCommandBuilder builder = TapPortCommand.builder();
336         InterfaceTypeChoice interfaceTypeChoice = vppEp.getInterfaceTypeChoice();
337         if (interfaceTypeChoice instanceof TapCase) {
338             TapCase tapIface = (TapCase) interfaceTypeChoice;
339             String name = tapIface.getName();
340             if (Strings.isNullOrEmpty(name)) {
341                 LOG.debug("Tap interface command is not created because name is missing. {}", vppEp);
342                 return Optional.absent();
343             }
344             builder.setTapName(name);
345         }
346
347         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
348             builder.setEnableProxyArp(true);
349         }
350
351         TapPortCommand tapPortCommand = builder
352                 .setOperation(operation)
353                 .setDescription(vppEp.getDescription())
354                 .setInterfaceName(vppEp.getVppInterfaceName())
355                 .build();
356         return Optional.of(tapPortCommand);
357     }
358
359     private Optional<AbstractInterfaceCommand> createLoopbackWithoutBdCommand(@Nonnull VppEndpoint vppEp,
360         @Nonnull Operations operation) {
361         if (!hasNodeAndInterface(vppEp)) {
362             LOG.debug("Interface command is not created for {}", vppEp);
363             return Optional.absent();
364         }
365         LoopbackCommand.LoopbackCommandBuilder builder = LoopbackCommand.builder();
366         LoopbackCase loopIface = (LoopbackCase) vppEp.getInterfaceTypeChoice();
367
368         builder.setPhysAddress(loopIface.getPhysAddress());
369         builder.setBvi(loopIface.isBvi());
370         builder.setIpAddress(loopIface.getIpAddress());
371         builder.setIpPrefix(loopIface.getIpPrefix());
372
373         LoopbackCommand loopbackCommand = builder
374             .setOperation(operation)
375             .setDescription(vppEp.getDescription())
376             .setInterfaceName(vppEp.getVppInterfaceName())
377             .build();
378
379         return Optional.of(loopbackCommand);
380     }
381
382     /**
383      * Adds bridge domain to an interface if the interface exist.<br>
384      * It rewrites bridge domain in case it already exist.<br>
385      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update location
386      * when the interface is created successfully.<br>
387      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
388      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
389      * containing message in {@link Exception#getMessage()}
390      *
391      * @param bridgeDomainName bridge domain
392      * @param addrEpWithLoc    {@link AddressEndpointWithLocation} containing
393      *                         {@link ExternalLocationCase} where
394      *                         {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
395      *                         and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
396      * @param aclWrappers wrappers for ACLs
397      * @param enableBvi BVI enabled/disabled
398      * @return {@link ListenableFuture}
399      */
400     public synchronized ListenableFuture<Void> addBridgeDomainToInterface(@Nonnull String bridgeDomainName,
401         @Nonnull AddressEndpointWithLocation addrEpWithLoc, @Nonnull List<AccessListWrapper> aclWrappers,
402         boolean enableBvi) {
403         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
404         InstanceIdentifier<Node> vppNodeIid = (InstanceIdentifier<Node>) epLoc.getExternalNodeMountPoint();
405         String interfacePath = epLoc.getExternalNodeConnector();
406
407         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
408                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
409         if (!optInterfaceIid.isPresent()) {
410             return Futures.immediateFailedFuture(
411                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
412         }
413         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
414         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
415         if (!potentialVppDataProvider.isPresent()) {
416             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
417         }
418         Optional<Interface> optInterface = GbpNetconfTransaction.read(vppNodeIid, LogicalDatastoreType.CONFIGURATION,
419                 interfaceIid, GbpNetconfTransaction.RETRY_COUNT);
420
421         if (!optInterface.isPresent()) {
422             return Futures.immediateFailedFuture(new Exception("Interface "
423                     + interfaceIid.firstKeyOf(Interface.class) + " does not exist on node " + vppNodeIid));
424         }
425         String existingBridgeDomain = resolveBridgeDomain(optInterface.get());
426         if (bridgeDomainName.equals(existingBridgeDomain)) {
427             LOG.debug("Bridge domain {} already exists on interface {}", bridgeDomainName, interfacePath);
428             String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
429             if (!bridgeDomainPath.equals(epLoc.getExternalNode())) {
430                 return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
431                         .setExternalNode(bridgeDomainPath)
432                         .setExternalNodeMountPoint(vppNodeIid)
433                         .setExternalNodeConnector(interfacePath)
434                         .build(), addrEpWithLoc.getKey());
435             }
436             return Futures.immediateFuture(null);
437         }
438         InstanceIdentifier<L2> l2Iid =
439                 interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
440         Optional<L2> optL2 = GbpNetconfTransaction.read(vppNodeIid, LogicalDatastoreType.CONFIGURATION,
441                 l2Iid, GbpNetconfTransaction.RETRY_COUNT);
442         L2Builder l2Builder = (optL2.isPresent()) ? new L2Builder(optL2.get()) : new L2Builder();
443         L2 l2 = l2Builder.setInterconnection(new BridgeBasedBuilder()
444                 .setBridgeDomain(bridgeDomainName)
445                 .setBridgedVirtualInterface(enableBvi)
446                 .build()).build();
447         LOG.debug("Adding bridge domain {} to interface {}", bridgeDomainName, interfacePath);
448         LOG.info("Debugging L2: iid={}, data={}", l2Iid, l2);
449         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppNodeIid, l2Iid, l2,
450                 GbpNetconfTransaction.RETRY_COUNT);
451         if (transactionState) {
452             LOG.debug("Adding bridge domain {} to interface {} successful", bridgeDomainName, interfacePath);
453             Set<String> excludedIfaces = excludedFromPolicy.get(vppNodeIid.firstKeyOf(Node.class).getNodeId());
454             if (!isExcludedFromPolicy(vppNodeIid.firstKeyOf(Node.class).getNodeId(),
455                     interfaceIid.firstKeyOf(Interface.class).getName())) {
456                 // can apply ACLs on interfaces in bridge domains
457                 aclWrappers.forEach(aclWrapper -> {
458                     LOG.debug("Writing access list for interface {} on a node {}.", interfaceIid, vppNodeIid);
459                     aclWrapper.writeAcl(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
460                     aclWrapper.writeAclRefOnIface(vppNodeIid, interfaceIid);
461                 });
462             }
463             String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
464             return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
465                     .setExternalNode(bridgeDomainPath)
466                     .setExternalNodeMountPoint(vppNodeIid)
467                     .setExternalNodeConnector(interfacePath)
468                     .build(), addrEpWithLoc.getKey());
469         } else {
470             final String message =
471                 "Adding bridge domain " + bridgeDomainName + " to interface " + interfacePath + " failed";
472             LOG.warn(message);
473             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
474         }
475     }
476
477     public boolean isExcludedFromPolicy(@Nonnull NodeId nodeId,@Nonnull String interfaceName) {
478         Set<String> excludedIfaces = excludedFromPolicy.get(nodeId);
479         if(excludedIfaces != null && excludedIfaces.contains(interfaceName)) {
480             return true;
481         }
482         return false;
483     }
484
485     public ListenableFuture<Void> configureInterface(InstanceIdentifier<Node> vppIid, InterfaceKey ifaceKey,
486         @Nullable String bridgeDomainName, @Nullable Boolean enableBvi) {
487         L2Builder l2Builder = readL2ForInterface(vppIid, ifaceKey);
488         L2 l2 = l2Builder.setInterconnection(new BridgeBasedBuilder()
489             .setBridgeDomain(bridgeDomainName)
490             .setBridgedVirtualInterface(enableBvi)
491             .build()).build();
492         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppIid,
493             VppIidFactory.getL2ForInterfaceIid(ifaceKey), l2, GbpNetconfTransaction.RETRY_COUNT);
494         if (transactionState) {
495             LOG.debug("Adding bridge domain {} to interface {}", bridgeDomainName,
496                 VppIidFactory.getInterfaceIID(ifaceKey));
497             return Futures.immediateFuture(null);
498         } else {
499             final String message = "Failed to add bridge domain " + bridgeDomainName + " to interface "
500                     + VppIidFactory.getInterfaceIID(ifaceKey);
501             LOG.warn(message);
502             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
503         }
504     }
505
506     public ListenableFuture<Void> removeInterfaceFromBridgeDomain(InstanceIdentifier<Node> vppIid,
507         InterfaceKey ifaceKey) {
508         L2Builder l2Builder = readL2ForInterface(vppIid, ifaceKey);
509         if (l2Builder.getInterconnection() == null || !(l2Builder.getInterconnection() instanceof BridgeBased)) {
510             LOG.warn("Interface already not in bridge domain {} ", ifaceKey);
511             return Futures.immediateFuture(null);
512         }
513         final boolean transactionState = GbpNetconfTransaction.netconfSyncedDelete(vppIid,
514                 VppIidFactory.getL2ForInterfaceIid(ifaceKey), GbpNetconfTransaction.RETRY_COUNT);
515         if (transactionState) {
516             LOG.debug("Removing bridge domain from interface {}", VppIidFactory.getInterfaceIID(ifaceKey));
517             return Futures.immediateFuture(null);
518         } else {
519             final String message = "Failed to remove bridge domain from interface "
520                     + VppIidFactory.getInterfaceIID(ifaceKey);
521             LOG.warn(message);
522             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
523         }
524     }
525
526     private L2Builder readL2ForInterface(InstanceIdentifier<Node> vppIid, InterfaceKey ifaceKey) {
527         InstanceIdentifier<L2> l2Iid = VppIidFactory.getL2ForInterfaceIid(ifaceKey);
528         final ReadOnlyTransaction rwTxRead = VbdNetconfTransaction.NODE_DATA_BROKER_MAP.get(vppIid).getKey()
529             .newReadOnlyTransaction();
530         Optional<L2> optL2 = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, l2Iid, rwTxRead);
531         rwTxRead.close();
532         return  (optL2.isPresent()) ? new L2Builder(optL2.get()) : new L2Builder();
533     }
534
535     /**
536      * Removes bridge domain (if exist) from an interface (if exist).<br>
537      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update endpoint
538      * location.
539      * <p>
540      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
541      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
542      * containing message in {@link Exception#getMessage()}
543      *
544      * @param addrEpWithLoc {@link AddressEndpointWithLocation} containing
545      *                      {@link ExternalLocationCase} where
546      *                      {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
547      *                      and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
548      * @return {@link ListenableFuture}
549      */
550     public synchronized @Nonnull ListenableFuture<Void> deleteBridgeDomainFromInterface(
551             @Nonnull AddressEndpointWithLocation addrEpWithLoc) {
552         // TODO update ACLs for peers
553         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
554         InstanceIdentifier<Node> vppNodeIid = (InstanceIdentifier<Node>) epLoc.getExternalNodeMountPoint();
555         String interfacePath = epLoc.getExternalNodeConnector();
556
557         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
558                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
559         if (!optInterfaceIid.isPresent()) {
560             return Futures.immediateFailedFuture(
561                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
562         }
563         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
564         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
565         if (!potentialVppDataProvider.isPresent()) {
566             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
567         }
568         final Optional<Interface> optInterface = GbpNetconfTransaction.read(vppNodeIid,
569                 LogicalDatastoreType.CONFIGURATION, interfaceIid, GbpNetconfTransaction.RETRY_COUNT);
570         if (!optInterface.isPresent()) {
571             // interface does not exist so we consider job done
572             return Futures.immediateFuture(null);
573         }
574         String existingBridgeDomain = resolveBridgeDomain(optInterface.get());
575         if (Strings.isNullOrEmpty(existingBridgeDomain)) {
576             LOG.debug("Bridge domain does not exist therefore it is considered as deleted for interface {}",
577                     interfacePath);
578             // bridge domain does not exist on interface so we consider job done
579             return vppEndpointLocationProvider.replaceLocationForEndpoint(
580                     new ExternalLocationCaseBuilder().setExternalNode(null)
581                         .setExternalNodeMountPoint(vppNodeIid)
582                         .setExternalNodeConnector(interfacePath)
583                         .build(),
584                     addrEpWithLoc.getKey());
585         }
586         InstanceIdentifier<L2> l2Iid =
587                 interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
588         LOG.debug("Deleting bridge domain from interface {}", interfacePath);
589         final boolean transactionState =
590                 GbpNetconfTransaction.netconfSyncedDelete(vppNodeIid, l2Iid, GbpNetconfTransaction.RETRY_COUNT);
591         if (transactionState) {
592             AccessListWrapper.removeAclRefFromIface(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
593             AccessListWrapper.removeAclsForInterface(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
594             return vppEndpointLocationProvider.replaceLocationForEndpoint(
595                     new ExternalLocationCaseBuilder().setExternalNode(null)
596                         .setExternalNodeMountPoint(vppNodeIid)
597                         .setExternalNodeConnector(interfacePath)
598                         .build(),
599                     addrEpWithLoc.getKey());
600         } else {
601             final String message = "Failed to delete bridge domain from interface " + interfacePath;
602             LOG.warn(message);
603             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
604         }
605     }
606
607     public static ExternalLocationCase resolveAndValidateLocation(AddressEndpointWithLocation addrEpWithLoc) {
608         LocationType locationType = addrEpWithLoc.getAbsoluteLocation().getLocationType();
609         if (!(locationType instanceof ExternalLocationCase)) {
610             throw new IllegalArgumentException("Endpoint does not have external location " + addrEpWithLoc);
611         }
612         ExternalLocationCase result = (ExternalLocationCase) locationType;
613         if (result.getExternalNodeMountPoint() == null || result.getExternalNodeConnector() == null) {
614             throw new IllegalArgumentException(
615                     "Endpoint does not have external-node-mount-point or external-node-connector " + addrEpWithLoc);
616         }
617         return result;
618     }
619
620     private static @Nullable String resolveBridgeDomain(@Nonnull Interface iface) {
621         VppInterfaceAugmentation vppInterfaceAugmentation = iface.getAugmentation(VppInterfaceAugmentation.class);
622         L2 existingL2 = vppInterfaceAugmentation.getL2();
623         if (existingL2 != null) {
624             Interconnection interconnection = existingL2.getInterconnection();
625             if (interconnection instanceof BridgeBased) {
626                 return ((BridgeBased) interconnection).getBridgeDomain();
627             }
628         }
629         return null;
630     }
631
632     private static boolean hasNodeAndInterface(VppEndpoint vppEp) {
633         if (vppEp.getVppNodeId() == null) {
634             LOG.debug("vpp-node is missing. {}", vppEp);
635             return false;
636         }
637         if (Strings.isNullOrEmpty(vppEp.getVppInterfaceName())) {
638             LOG.debug("vpp-interface-name is missing. {}", vppEp);
639             return false;
640         }
641         return true;
642     }
643
644     @Override
645     public void close() throws Exception {
646         vppEndpointLocationProvider.close();
647     }
648 }