Upgrading ACL implementation
[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.InterfaceKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.LocationType;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.location.type.ExternalLocationCase;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.location.type.ExternalLocationCaseBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.renderers.renderer.renderer.policy.configuration.endpoints.AddressEndpointWithLocation;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425.ExcludeFromPolicy;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes.InterfaceTypeChoice;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes._interface.type.choice.LoopbackCase;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes._interface.type.choice.TapCase;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425._interface.attributes._interface.type.choice.VhostUserCase;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425.config.VppEndpoint;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.VhostUserRole;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.VppInterfaceAugmentation;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.interfaces._interface.L2;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.interfaces._interface.L2Builder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.l2.config.attributes.Interconnection;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.l2.config.attributes.interconnection.BridgeBased;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev170607.l2.config.attributes.interconnection.BridgeBasedBuilder;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
60 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 import com.google.common.base.Optional;
65 import com.google.common.base.Preconditions;
66 import com.google.common.base.Strings;
67 import com.google.common.collect.HashMultimap;
68 import com.google.common.collect.SetMultimap;
69 import com.google.common.eventbus.Subscribe;
70 import com.google.common.util.concurrent.Futures;
71 import com.google.common.util.concurrent.ListenableFuture;
72 import com.google.common.util.concurrent.MoreExecutors;
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: 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         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
322             builder.setEnableProxyArp(true);
323             builder.setSnatEnabled(true);
324         }
325         VhostUserCommand vhostUserCommand =
326                 builder.setOperation(operations).setDescription(vppEp.getDescription()).build();
327         return Optional.of(vhostUserCommand);
328     }
329
330     private Optional<AbstractInterfaceCommand> createTapInterfaceWithoutBdCommand(@Nonnull VppEndpoint vppEp,
331             @Nonnull Operations operation) {
332         if (!hasNodeAndInterface(vppEp)) {
333             LOG.debug("Interface command is not created for {}", vppEp);
334             return Optional.absent();
335         }
336         TapPortCommand.TapPortCommandBuilder builder = TapPortCommand.builder();
337         InterfaceTypeChoice interfaceTypeChoice = vppEp.getInterfaceTypeChoice();
338         if (interfaceTypeChoice instanceof TapCase) {
339             TapCase tapIface = (TapCase) interfaceTypeChoice;
340             String name = tapIface.getName();
341             if (Strings.isNullOrEmpty(name)) {
342                 LOG.debug("Tap interface command is not created because name is missing. {}", vppEp);
343                 return Optional.absent();
344             }
345             builder.setTapName(name);
346         }
347
348         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
349             builder.setEnableProxyArp(true);
350         }
351
352         TapPortCommand tapPortCommand = builder
353                 .setOperation(operation)
354                 .setDescription(vppEp.getDescription())
355                 .setInterfaceName(vppEp.getVppInterfaceName())
356                 .build();
357         return Optional.of(tapPortCommand);
358     }
359
360     private Optional<AbstractInterfaceCommand> createLoopbackWithoutBdCommand(@Nonnull VppEndpoint vppEp,
361         @Nonnull Operations operation) {
362         if (!hasNodeAndInterface(vppEp)) {
363             LOG.debug("Interface command is not created for {}", vppEp);
364             return Optional.absent();
365         }
366         LoopbackCommand.LoopbackCommandBuilder builder = LoopbackCommand.builder();
367         LoopbackCase loopIface = (LoopbackCase) vppEp.getInterfaceTypeChoice();
368
369         builder.setPhysAddress(loopIface.getPhysAddress());
370         builder.setBvi(loopIface.isBvi());
371         builder.setIpAddress(loopIface.getIpAddress());
372         builder.setIpPrefix(loopIface.getIpPrefix());
373
374         LoopbackCommand loopbackCommand = builder
375             .setOperation(operation)
376             .setDescription(vppEp.getDescription())
377             .setInterfaceName(vppEp.getVppInterfaceName())
378             .build();
379
380         return Optional.of(loopbackCommand);
381     }
382
383     /**
384      * Adds bridge domain to an interface if the interface exist.<br>
385      * It rewrites bridge domain in case it already exist.<br>
386      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update location
387      * when the interface is created successfully.<br>
388      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
389      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
390      * containing message in {@link Exception#getMessage()}
391      *
392      * @param bridgeDomainName bridge domain
393      * @param addrEpWithLoc    {@link AddressEndpointWithLocation} containing
394      *                         {@link ExternalLocationCase} where
395      *                         {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
396      *                         and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
397      * @param aclWrappers wrappers for ACLs
398      * @param enableBvi BVI enabled/disabled
399      * @return {@link ListenableFuture}
400      */
401     public synchronized ListenableFuture<Void> addBridgeDomainToInterface(@Nonnull String bridgeDomainName,
402                                                                           @Nonnull AddressEndpointWithLocation addrEpWithLoc,
403                                                                           @Nonnull List<AccessListWrapper> aclWrappers,
404                                                                           boolean enableBvi) {
405         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
406         InstanceIdentifier<Node> vppNodeIid = (InstanceIdentifier<Node>) epLoc.getExternalNodeMountPoint();
407         String interfacePath = epLoc.getExternalNodeConnector();
408
409         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
410                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
411         if (!optInterfaceIid.isPresent()) {
412             return Futures.immediateFailedFuture(
413                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
414         }
415         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
416         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
417         if (!potentialVppDataProvider.isPresent()) {
418             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
419         }
420         Optional<Interface> optInterface = GbpNetconfTransaction.read(vppNodeIid, LogicalDatastoreType.CONFIGURATION,
421                 interfaceIid, GbpNetconfTransaction.RETRY_COUNT);
422
423         if (!optInterface.isPresent()) {
424             return Futures.immediateFailedFuture(new Exception("Interface "
425                     + interfaceIid.firstKeyOf(Interface.class) + " does not exist on node " + vppNodeIid));
426         }
427         String existingBridgeDomain = resolveBridgeDomain(optInterface.get());
428         if (bridgeDomainName.equals(existingBridgeDomain)) {
429             LOG.debug("Bridge domain {} already exists on interface {}", bridgeDomainName, interfacePath);
430             String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
431             if (!bridgeDomainPath.equals(epLoc.getExternalNode())) {
432                 return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
433                         .setExternalNode(bridgeDomainPath)
434                         .setExternalNodeMountPoint(vppNodeIid)
435                         .setExternalNodeConnector(interfacePath)
436                         .build(), addrEpWithLoc.getKey());
437             }
438             return Futures.immediateFuture(null);
439         }
440         InstanceIdentifier<L2> l2Iid =
441                 interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
442         Optional<L2> optL2 = GbpNetconfTransaction.read(vppNodeIid, LogicalDatastoreType.CONFIGURATION,
443                 l2Iid, GbpNetconfTransaction.RETRY_COUNT);
444         L2Builder l2Builder = (optL2.isPresent()) ? new L2Builder(optL2.get()) : new L2Builder();
445         L2 l2 = l2Builder.setInterconnection(new BridgeBasedBuilder()
446                 .setBridgeDomain(bridgeDomainName)
447                 .setBridgedVirtualInterface(enableBvi)
448                 .build()).build();
449         LOG.debug("Adding bridge domain {} to interface {}", bridgeDomainName, interfacePath);
450         LOG.info("Debugging L2: iid={}, data={}", l2Iid, l2);
451         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppNodeIid, l2Iid, l2,
452                 GbpNetconfTransaction.RETRY_COUNT);
453         if (transactionState) {
454             LOG.debug("Adding bridge domain {} to interface {} successful", bridgeDomainName, interfacePath);
455             Set<String> excludedIfaces = excludedFromPolicy.get(vppNodeIid.firstKeyOf(Node.class).getNodeId());
456             if (!isExcludedFromPolicy(vppNodeIid.firstKeyOf(Node.class).getNodeId(),
457                     interfaceIid.firstKeyOf(Interface.class).getName())) {
458                 // can apply ACLs on interfaces in bridge domains
459                 aclWrappers.forEach(aclWrapper -> {
460                     LOG.debug("Writing access list for interface {} on a node {}.", interfaceIid, vppNodeIid);
461                     aclWrapper.writeAcl(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
462                     aclWrapper.writeAclRefOnIface(vppNodeIid, interfaceIid);
463                 });
464             }
465             String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
466             return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
467                     .setExternalNode(bridgeDomainPath)
468                     .setExternalNodeMountPoint(vppNodeIid)
469                     .setExternalNodeConnector(interfacePath)
470                     .build(), addrEpWithLoc.getKey());
471         } else {
472             final String message = "Adding bridge domain " + bridgeDomainName + " to interface " + interfacePath + " failed";
473             LOG.warn(message);
474             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
475         }
476     }
477
478     public boolean isExcludedFromPolicy(@Nonnull NodeId nodeId,@Nonnull String interfaceName) {
479         Set<String> excludedIfaces = excludedFromPolicy.get(nodeId);
480         if(excludedIfaces != null && excludedIfaces.contains(interfaceName)) {
481             return true;
482         }
483         return false;
484     }
485
486     public ListenableFuture<Void> configureInterface(InstanceIdentifier<Node> vppIid, InterfaceKey ifaceKey, @Nullable String bridgeDomainName,
487                                                      @Nullable Boolean enableBvi) {
488         L2Builder l2Builder = readL2ForInterface(vppIid, ifaceKey);
489         L2 l2 = l2Builder.setInterconnection(new BridgeBasedBuilder()
490             .setBridgeDomain(bridgeDomainName)
491             .setBridgedVirtualInterface(enableBvi)
492             .build()).build();
493         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppIid,
494             VppIidFactory.getL2ForInterfaceIid(ifaceKey), l2, GbpNetconfTransaction.RETRY_COUNT);
495         if (transactionState) {
496             LOG.debug("Adding bridge domain {} to interface {}", bridgeDomainName, 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, InterfaceKey ifaceKey) {
507         L2Builder l2Builder = readL2ForInterface(vppIid, ifaceKey);
508         if (l2Builder.getInterconnection() == null || !(l2Builder.getInterconnection() instanceof BridgeBased)) {
509             LOG.warn("Interface already not in bridge domain {} ", ifaceKey);
510             return Futures.immediateFuture(null);
511         }
512         final boolean transactionState = GbpNetconfTransaction.netconfSyncedDelete(vppIid,
513                 VppIidFactory.getL2ForInterfaceIid(ifaceKey), GbpNetconfTransaction.RETRY_COUNT);
514         if (transactionState) {
515             LOG.debug("Removing bridge domain from interface {}", VppIidFactory.getInterfaceIID(ifaceKey));
516             return Futures.immediateFuture(null);
517         } else {
518             final String message = "Failed to remove bridge domain from interface "
519                     + VppIidFactory.getInterfaceIID(ifaceKey);
520             LOG.warn(message);
521             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
522         }
523     }
524
525     private L2Builder readL2ForInterface(InstanceIdentifier<Node> vppIid, InterfaceKey ifaceKey) {
526         InstanceIdentifier<L2> l2Iid = VppIidFactory.getL2ForInterfaceIid(ifaceKey);
527         final ReadOnlyTransaction rwTxRead = VbdNetconfTransaction.NODE_DATA_BROKER_MAP.get(vppIid).getKey().newReadOnlyTransaction();
528         Optional<L2> optL2 = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, l2Iid, rwTxRead);
529         rwTxRead.close();
530         return  (optL2.isPresent()) ? new L2Builder(optL2.get()) : new L2Builder();
531     }
532
533     /**
534      * Removes bridge domain (if exist) from an interface (if exist).<br>
535      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update endpoint
536      * location.
537      * <p>
538      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
539      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
540      * containing message in {@link Exception#getMessage()}
541      *
542      * @param addrEpWithLoc {@link AddressEndpointWithLocation} containing
543      *                      {@link ExternalLocationCase} where
544      *                      {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
545      *                      and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
546      * @return {@link ListenableFuture}
547      */
548     public synchronized @Nonnull ListenableFuture<Void> deleteBridgeDomainFromInterface(
549             @Nonnull AddressEndpointWithLocation addrEpWithLoc) {
550         // TODO update ACLs for peers
551         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
552         InstanceIdentifier<Node> vppNodeIid = (InstanceIdentifier<Node>) epLoc.getExternalNodeMountPoint();
553         String interfacePath = epLoc.getExternalNodeConnector();
554
555         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
556                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
557         if (!optInterfaceIid.isPresent()) {
558             return Futures.immediateFailedFuture(
559                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
560         }
561         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
562         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
563         if (!potentialVppDataProvider.isPresent()) {
564             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
565         }
566         final Optional<Interface> optInterface = GbpNetconfTransaction.read(vppNodeIid,
567                 LogicalDatastoreType.CONFIGURATION, interfaceIid, GbpNetconfTransaction.RETRY_COUNT);
568         if (!optInterface.isPresent()) {
569             // interface does not exist so we consider job done
570             return Futures.immediateFuture(null);
571         }
572         String existingBridgeDomain = resolveBridgeDomain(optInterface.get());
573         if (Strings.isNullOrEmpty(existingBridgeDomain)) {
574             LOG.debug("Bridge domain does not exist therefore it is considered as deleted for interface {}",
575                     interfacePath);
576             // bridge domain does not exist on interface so we consider job done
577             return vppEndpointLocationProvider.replaceLocationForEndpoint(
578                     new ExternalLocationCaseBuilder().setExternalNode(null)
579                         .setExternalNodeMountPoint(vppNodeIid)
580                         .setExternalNodeConnector(interfacePath)
581                         .build(),
582                     addrEpWithLoc.getKey());
583         }
584         InstanceIdentifier<L2> l2Iid =
585                 interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
586         LOG.debug("Deleting bridge domain from interface {}", interfacePath);
587         final boolean transactionState =
588                 GbpNetconfTransaction.netconfSyncedDelete(vppNodeIid, l2Iid, GbpNetconfTransaction.RETRY_COUNT);
589         if (transactionState) {
590             AccessListWrapper.removeAclRefFromIface(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
591             AccessListWrapper.removeAclsForInterface(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
592             return vppEndpointLocationProvider.replaceLocationForEndpoint(
593                     new ExternalLocationCaseBuilder().setExternalNode(null)
594                         .setExternalNodeMountPoint(vppNodeIid)
595                         .setExternalNodeConnector(interfacePath)
596                         .build(),
597                     addrEpWithLoc.getKey());
598         } else {
599             final String message = "Failed to delete bridge domain from interface " + interfacePath;
600             LOG.warn(message);
601             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
602         }
603     }
604
605     public static ExternalLocationCase resolveAndValidateLocation(AddressEndpointWithLocation addrEpWithLoc) {
606         LocationType locationType = addrEpWithLoc.getAbsoluteLocation().getLocationType();
607         if (!(locationType instanceof ExternalLocationCase)) {
608             throw new IllegalArgumentException("Endpoint does not have external location " + addrEpWithLoc);
609         }
610         ExternalLocationCase result = (ExternalLocationCase) locationType;
611         if (result.getExternalNodeMountPoint() == null || result.getExternalNodeConnector() == null) {
612             throw new IllegalArgumentException(
613                     "Endpoint does not have external-node-mount-point or external-node-connector " + addrEpWithLoc);
614         }
615         return result;
616     }
617
618     private static @Nullable String resolveBridgeDomain(@Nonnull Interface iface) {
619         VppInterfaceAugmentation vppInterfaceAugmentation = iface.getAugmentation(VppInterfaceAugmentation.class);
620         L2 existingL2 = vppInterfaceAugmentation.getL2();
621         if (existingL2 != null) {
622             Interconnection interconnection = existingL2.getInterconnection();
623             if (interconnection instanceof BridgeBased) {
624                 return ((BridgeBased) interconnection).getBridgeDomain();
625             }
626         }
627         return null;
628     }
629
630     private static boolean hasNodeAndInterface(VppEndpoint vppEp) {
631         if (vppEp.getVppNodeId() == null) {
632             LOG.debug("vpp-node is missing. {}", vppEp);
633             return false;
634         }
635         if (Strings.isNullOrEmpty(vppEp.getVppInterfaceName())) {
636             LOG.debug("vpp-interface-name is missing. {}", vppEp);
637             return false;
638         }
639         return true;
640     }
641
642     @Override
643     public void close() throws Exception {
644         vppEndpointLocationProvider.close();
645     }
646 }