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