e0e7b42523e0a1c22789c600fa21d71d436cfa03
[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             // TODO Auto-generated catch block
137             LOG.error("Failed to process changed vpp endpoint - before: {}, after {}: ", event.getBefore(),
138                     event.getBefore());
139         }
140     }
141
142     private ListenableFuture<Boolean> updatePolicyExcludedEndpoints(VppEndpoint vppEndpoint, boolean created) {
143         if (vppEndpoint == null || vppEndpoint.getAugmentation(ExcludeFromPolicy.class) == null) {
144             return Futures.immediateFuture(true);
145         }
146         if (created) {
147             excludedFromPolicy.put(vppEndpoint.getVppNodeId(), vppEndpoint.getVppInterfaceName());
148             return Futures.immediateFuture(true);
149         }
150         return Futures.immediateFuture(excludedFromPolicy.remove(vppEndpoint.getVppNodeId(),
151                 vppEndpoint.getVppInterfaceName()));
152     }
153
154     private ListenableFuture<Void> vppEndpointCreated(VppEndpoint vppEndpoint) {
155         InterfaceTypeChoice interfaceTypeChoice = vppEndpoint.getInterfaceTypeChoice();
156         LOG.trace("Creating VPP endpoint {}, type of {}", vppEndpoint, interfaceTypeChoice);
157         Optional<AbstractInterfaceCommand> potentialIfaceCommand = Optional.absent();
158         if (interfaceTypeChoice instanceof VhostUserCase) {
159             potentialIfaceCommand = createVhostInterfaceWithoutBdCommand(vppEndpoint, Operations.PUT);
160         } else if (interfaceTypeChoice instanceof TapCase) {
161             potentialIfaceCommand = createTapInterfaceWithoutBdCommand(vppEndpoint, Operations.PUT);
162         } else if (interfaceTypeChoice instanceof LoopbackCase){
163             if (!ConfigUtil.getInstance().isL3FlatEnabled()) {
164                 potentialIfaceCommand = createLoopbackWithoutBdCommand(vppEndpoint, Operations.PUT);
165             }
166             else {
167                 LOG.trace("L3 flat enabled: Creating of Loopback BVI disabled in InterfaceManager. LISP in VPP renderer will take care of this.");
168             }
169         }
170         if (!potentialIfaceCommand.isPresent()) {
171             LOG.debug("Interface/PUT command was not created for VppEndpoint point {}", vppEndpoint);
172             return Futures.immediateFuture(null);
173         }
174         ConfigCommand ifaceWithoutBdCommand = potentialIfaceCommand.get();
175         InstanceIdentifier<Node> vppNodeIid = VppIidFactory.getNetconfNodeIid(vppEndpoint.getVppNodeId());
176         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
177         if (!potentialVppDataProvider.isPresent()) {
178             final String message = "Cannot get data broker for mount point " + vppNodeIid;
179             LOG.warn(message);
180             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
181         }
182         return createInterfaceWithEndpointLocation(ifaceWithoutBdCommand, vppNodeIid, vppEndpoint);
183     }
184
185     public ListenableFuture<Void> createInterfaceOnVpp(final ConfigCommand createIfaceWithoutBdCommand,
186                                                        final InstanceIdentifier<Node> vppIid) {
187         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppIid, createIfaceWithoutBdCommand,
188                 GbpNetconfTransaction.RETRY_COUNT);
189         if (transactionState) {
190             LOG.trace("Creating Interface on VPP: {}", createIfaceWithoutBdCommand);
191             return Futures.immediateFuture(null);
192         } else {
193             final String message = "Failed to create Interface on VPP: " + createIfaceWithoutBdCommand;
194             LOG.warn(message);
195             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
196         }
197     }
198
199     private ListenableFuture<Void> createInterfaceWithEndpointLocation(final ConfigCommand createIfaceWithoutBdCommand,
200                                                                        final InstanceIdentifier<Node> vppIid,
201                                                                        final VppEndpoint vppEndpoint) {
202         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppIid, createIfaceWithoutBdCommand,
203                 GbpNetconfTransaction.RETRY_COUNT);
204         if (transactionState) {
205             LOG.debug("Create interface on VPP command was successful. VPP: {} Command: {}", vppIid,
206                     createIfaceWithoutBdCommand);
207             return vppEndpointLocationProvider.createLocationForVppEndpoint(vppEndpoint);
208         } else {
209             final String message = "Create interface on VPP command was not successful. VPP: " + vppIid
210             + " Command: " + createIfaceWithoutBdCommand;
211             LOG.warn(message);
212             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
213         }
214     }
215
216     private ListenableFuture<Void> vppEndpointUpdated(@Nonnull final VppEndpoint oldVppEndpoint,
217                                                       @Nonnull final VppEndpoint newVppEndpoint) {
218         if(!oldVppEndpoint.equals(newVppEndpoint)) {
219             LOG.debug("Updating vpp endpoint, old EP: {} new EP: {}", oldVppEndpoint, newVppEndpoint);
220             return Futures.transformAsync(vppEndpointDeleted(oldVppEndpoint),
221                 input -> vppEndpointCreated(newVppEndpoint), MoreExecutors.directExecutor());
222         }
223         LOG.debug("Update skipped, provided before/after vpp endpoints are equal");
224         return Futures.immediateFuture(null);
225     }
226
227     private ListenableFuture<Void> vppEndpointDeleted(@Nonnull VppEndpoint vppEndpoint) {
228         InterfaceTypeChoice interfaceTypeChoice = vppEndpoint.getInterfaceTypeChoice();
229         LOG.trace("Deleting VPP endpoint {}, type of {}", vppEndpoint, interfaceTypeChoice.toString());
230         Optional<AbstractInterfaceCommand> potentialIfaceCommand = Optional.absent();
231         if (interfaceTypeChoice instanceof VhostUserCase) {
232             potentialIfaceCommand = createVhostInterfaceWithoutBdCommand(vppEndpoint, Operations.DELETE);
233         } else if (interfaceTypeChoice instanceof TapCase) {
234             potentialIfaceCommand = createTapInterfaceWithoutBdCommand(vppEndpoint, Operations.DELETE);
235         } else if (interfaceTypeChoice instanceof LoopbackCase){
236             if (!ConfigUtil.getInstance().isL3FlatEnabled()) {
237                 potentialIfaceCommand = createLoopbackWithoutBdCommand(vppEndpoint, Operations.DELETE);
238             }
239             else {
240                 LOG.trace("L3 flat enabled: Deleting of Loopback BVI disabled in InterfaceManager. LISP in VPP renderer will take care of this.");
241             }
242         }
243
244
245         if (!potentialIfaceCommand.isPresent()) {
246             LOG.debug("Interface/DELETE command was not created for VppEndpoint point {}", vppEndpoint);
247             return Futures.immediateFuture(null);
248         }
249         AbstractInterfaceCommand ifaceWithoutBdCommand = potentialIfaceCommand.get();
250         InstanceIdentifier<Node> vppNodeIid = VppIidFactory.getNetconfNodeIid(vppEndpoint.getVppNodeId());
251         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
252         if (!potentialVppDataProvider.isPresent()) {
253             final String message = "Cannot get data broker for mount point " + vppNodeIid;
254             LOG.warn(message);
255             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
256         }
257         DataBroker vppDataBroker = potentialVppDataProvider.get();
258
259         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
260             flatOverlayManager.handleInterfaceDeleteForFlatOverlay(vppDataBroker, vppEndpoint);
261         }
262         return deleteIfaceOnVpp(ifaceWithoutBdCommand, vppNodeIid, vppEndpoint);
263     }
264
265     private ListenableFuture<Void> deleteIfaceOnVpp(AbstractInterfaceCommand deleteIfaceWithoutBdCommand, InstanceIdentifier<Node> vppIid,
266             VppEndpoint vppEndpoint) {
267         InterfaceBuilder intfBuilder = deleteIfaceWithoutBdCommand.getInterfaceBuilder();
268         final boolean transactionState = GbpNetconfTransaction.netconfSyncedDelete(vppIid,
269                 deleteIfaceWithoutBdCommand, GbpNetconfTransaction.RETRY_COUNT);
270         if (transactionState) {
271             LOG.debug("Delete interface on VPP command was successful: VPP: {} Command: {}", vppIid,
272                     deleteIfaceWithoutBdCommand);
273             AccessListWrapper.removeAclsForInterface(vppIid, new InterfaceKey(intfBuilder.getName()));
274             return vppEndpointLocationProvider.deleteLocationForVppEndpoint(vppEndpoint);
275         } else {
276             final String message = "Delete interface on VPP command was not successful: VPP: " + vppIid
277                     + " Command: " + deleteIfaceWithoutBdCommand;
278             LOG.warn(message);
279             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
280         }
281     }
282
283     @Subscribe
284     public synchronized void vppNodeChanged(NodeOperEvent event) {
285         switch (event.getDtoModificationType()) {
286             case CREATED:
287                 if (event.isAfterConnected()) {
288                     // TODO read VppEndpoints or cache them during vppEndpointChanged()
289                 }
290                 break;
291             case UPDATED:
292                 if (!event.isBeforeConnected() && event.isAfterConnected()) {
293                     // TODO reconciliation - diff between disconnected snapshot and current snapshot
294                 }
295                 break;
296             case DELETED:
297                 if (event.isBeforeConnected()) {
298                     // TODO we could do snapshot of VppEndpoints
299                     // which can be used for reconciliation
300                 }
301                 break;
302         }
303     }
304
305     private Optional<AbstractInterfaceCommand> createVhostInterfaceWithoutBdCommand(@Nonnull VppEndpoint vppEp,
306                                                                                     @Nonnull Operations operations) {
307         if (!hasNodeAndInterface(vppEp)) {
308             LOG.debug("Interface command is not created for {}", vppEp);
309             return Optional.absent();
310         }
311         VhostUserCommandBuilder builder = VhostUserCommand.builder();
312         builder.setName(vppEp.getVppInterfaceName());
313         InterfaceTypeChoice interfaceTypeChoice = vppEp.getInterfaceTypeChoice();
314         if (interfaceTypeChoice instanceof VhostUserCase) {
315             VhostUserCase vhostUserIface = (VhostUserCase) interfaceTypeChoice;
316             String socket = vhostUserIface.getSocket();
317             if (Strings.isNullOrEmpty(socket)) {
318                 LOG.debug("Vhost user interface command is not created because socket is missing. {}", vppEp);
319                 return Optional.absent();
320             }
321             builder.setSocket(socket);
322             builder.setRole(VhostUserRole.Client);
323         }
324
325         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
326             builder.setEnableProxyArp(true);
327         }
328
329         VhostUserCommand vhostUserCommand =
330                 builder.setOperation(operations).setDescription(vppEp.getDescription()).build();
331         return Optional.of(vhostUserCommand);
332     }
333
334     private Optional<AbstractInterfaceCommand> createTapInterfaceWithoutBdCommand(@Nonnull VppEndpoint vppEp,
335             @Nonnull Operations operation) {
336         if (!hasNodeAndInterface(vppEp)) {
337             LOG.debug("Interface command is not created for {}", vppEp);
338             return Optional.absent();
339         }
340         TapPortCommand.TapPortCommandBuilder builder = TapPortCommand.builder();
341         InterfaceTypeChoice interfaceTypeChoice = vppEp.getInterfaceTypeChoice();
342         if (interfaceTypeChoice instanceof TapCase) {
343             TapCase tapIface = (TapCase) interfaceTypeChoice;
344             String name = tapIface.getName();
345             if (Strings.isNullOrEmpty(name)) {
346                 LOG.debug("Tap interface command is not created because name is missing. {}", vppEp);
347                 return Optional.absent();
348             }
349             builder.setTapName(name);
350         }
351
352         if (ConfigUtil.getInstance().isL3FlatEnabled()) {
353             builder.setEnableProxyArp(true);
354         }
355
356         TapPortCommand tapPortCommand = builder
357                 .setOperation(operation)
358                 .setDescription(vppEp.getDescription())
359                 .setInterfaceName(vppEp.getVppInterfaceName())
360                 .build();
361         return Optional.of(tapPortCommand);
362     }
363
364     private Optional<AbstractInterfaceCommand> createLoopbackWithoutBdCommand(@Nonnull VppEndpoint vppEp,
365         @Nonnull Operations operation) {
366         if (!hasNodeAndInterface(vppEp)) {
367             LOG.debug("Interface command is not created for {}", vppEp);
368             return Optional.absent();
369         }
370         LoopbackCommand.LoopbackCommandBuilder builder = LoopbackCommand.builder();
371         LoopbackCase loopIface = (LoopbackCase) vppEp.getInterfaceTypeChoice();
372
373         builder.setPhysAddress(loopIface.getPhysAddress());
374         builder.setBvi(loopIface.isBvi());
375         builder.setIpAddress(loopIface.getIpAddress());
376         builder.setIpPrefix(loopIface.getIpPrefix());
377
378         LoopbackCommand loopbackCommand = builder
379             .setOperation(operation)
380             .setDescription(vppEp.getDescription())
381             .setInterfaceName(vppEp.getVppInterfaceName())
382             .build();
383
384         return Optional.of(loopbackCommand);
385     }
386
387     /**
388      * Adds bridge domain to an interface if the interface exist.<br>
389      * It rewrites bridge domain in case it already exist.<br>
390      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update location
391      * when the interface is created successfully.<br>
392      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
393      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
394      * containing message in {@link Exception#getMessage()}
395      *
396      * @param bridgeDomainName bridge domain
397      * @param addrEpWithLoc    {@link AddressEndpointWithLocation} containing
398      *                         {@link ExternalLocationCase} where
399      *                         {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
400      *                         and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
401      * @param aclWrappers wrappers for ACLs
402      * @param enableBvi BVI enabled/disabled
403      * @return {@link ListenableFuture}
404      */
405     public synchronized ListenableFuture<Void> addBridgeDomainToInterface(@Nonnull String bridgeDomainName,
406                                                                           @Nonnull AddressEndpointWithLocation addrEpWithLoc,
407                                                                           @Nonnull List<AccessListWrapper> aclWrappers,
408                                                                           boolean enableBvi) {
409         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
410         InstanceIdentifier<Node> vppNodeIid = (InstanceIdentifier<Node>) epLoc.getExternalNodeMountPoint();
411         String interfacePath = epLoc.getExternalNodeConnector();
412
413         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
414                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
415         if (!optInterfaceIid.isPresent()) {
416             return Futures.immediateFailedFuture(
417                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
418         }
419         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
420         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
421         if (!potentialVppDataProvider.isPresent()) {
422             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
423         }
424         Optional<Interface> optInterface = GbpNetconfTransaction.read(vppNodeIid, LogicalDatastoreType.CONFIGURATION,
425                 interfaceIid, GbpNetconfTransaction.RETRY_COUNT);
426
427         if (!optInterface.isPresent()) {
428             return Futures.immediateFailedFuture(new Exception("Interface "
429                     + interfaceIid.firstKeyOf(Interface.class) + " does not exist on node " + vppNodeIid));
430         }
431         String existingBridgeDomain = resolveBridgeDomain(optInterface.get());
432         if (bridgeDomainName.equals(existingBridgeDomain)) {
433             LOG.debug("Bridge domain {} already exists on interface {}", bridgeDomainName, interfacePath);
434             String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
435             if (!bridgeDomainPath.equals(epLoc.getExternalNode())) {
436                 return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
437                         .setExternalNode(bridgeDomainPath)
438                         .setExternalNodeMountPoint(vppNodeIid)
439                         .setExternalNodeConnector(interfacePath)
440                         .build(), addrEpWithLoc.getKey());
441             }
442             return Futures.immediateFuture(null);
443         }
444         InstanceIdentifier<L2> l2Iid =
445                 interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
446         Optional<L2> optL2 = GbpNetconfTransaction.read(vppNodeIid, LogicalDatastoreType.CONFIGURATION,
447                 l2Iid, GbpNetconfTransaction.RETRY_COUNT);
448         L2Builder l2Builder = (optL2.isPresent()) ? new L2Builder(optL2.get()) : new L2Builder();
449         L2 l2 = l2Builder.setInterconnection(new BridgeBasedBuilder()
450                 .setBridgeDomain(bridgeDomainName)
451                 .setBridgedVirtualInterface(enableBvi)
452                 .build()).build();
453         LOG.debug("Adding bridge domain {} to interface {}", bridgeDomainName, interfacePath);
454         LOG.info("Debugging L2: iid={}, data={}", l2Iid, l2);
455         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppNodeIid, l2Iid, l2,
456                 GbpNetconfTransaction.RETRY_COUNT);
457         if (transactionState) {
458             LOG.debug("Adding bridge domain {} to interface {} successful", bridgeDomainName, interfacePath);
459             Set<String> excludedIfaces = excludedFromPolicy.get(vppNodeIid.firstKeyOf(Node.class).getNodeId());
460             if (!isExcludedFromPolicy(vppNodeIid.firstKeyOf(Node.class).getNodeId(),
461                     interfaceIid.firstKeyOf(Interface.class).getName())) {
462                 // can apply ACLs on interfaces in bridge domains
463                 aclWrappers.forEach(aclWrapper -> {
464                     LOG.debug("Writing access list for interface {} on a node {}.", interfaceIid, vppNodeIid);
465                     aclWrapper.writeAcl(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
466                     aclWrapper.writeAclRefOnIface(vppNodeIid, interfaceIid);
467                 });
468             }
469             String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
470             return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
471                     .setExternalNode(bridgeDomainPath)
472                     .setExternalNodeMountPoint(vppNodeIid)
473                     .setExternalNodeConnector(interfacePath)
474                     .build(), addrEpWithLoc.getKey());
475         } else {
476             final String message = "Adding bridge domain " + bridgeDomainName + " to interface " + interfacePath + " failed";
477             LOG.warn(message);
478             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
479         }
480     }
481
482     public boolean isExcludedFromPolicy(@Nonnull NodeId nodeId,@Nonnull String interfaceName) {
483         Set<String> excludedIfaces = excludedFromPolicy.get(nodeId);
484         if(excludedIfaces != null && excludedIfaces.contains(interfaceName)) {
485             return true;
486         }
487         return false;
488     }
489
490     public ListenableFuture<Void> configureInterface(InstanceIdentifier<Node> vppIid, InterfaceKey ifaceKey, @Nullable String bridgeDomainName,
491                                                      @Nullable Boolean enableBvi) {
492         L2Builder l2Builder = readL2ForInterface(vppIid, ifaceKey);
493         L2 l2 = l2Builder.setInterconnection(new BridgeBasedBuilder()
494             .setBridgeDomain(bridgeDomainName)
495             .setBridgedVirtualInterface(enableBvi)
496             .build()).build();
497         final boolean transactionState = GbpNetconfTransaction.netconfSyncedWrite(vppIid,
498             VppIidFactory.getL2ForInterfaceIid(ifaceKey), l2, GbpNetconfTransaction.RETRY_COUNT);
499         if (transactionState) {
500             LOG.debug("Adding bridge domain {} to interface {}", bridgeDomainName, VppIidFactory.getInterfaceIID(ifaceKey));
501             return Futures.immediateFuture(null);
502         } else {
503             final String message = "Failed to add bridge domain " + bridgeDomainName + " to interface "
504                     + VppIidFactory.getInterfaceIID(ifaceKey);
505             LOG.warn(message);
506             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
507         }
508     }
509
510     public ListenableFuture<Void> removeInterfaceFromBridgeDomain(InstanceIdentifier<Node> vppIid, InterfaceKey ifaceKey) {
511         L2Builder l2Builder = readL2ForInterface(vppIid, ifaceKey);
512         if (l2Builder.getInterconnection() == null || !(l2Builder.getInterconnection() instanceof BridgeBased)) {
513             LOG.warn("Interface already not in bridge domain {} ", ifaceKey);
514             return Futures.immediateFuture(null);
515         }
516         final boolean transactionState = GbpNetconfTransaction.netconfSyncedDelete(vppIid,
517                 VppIidFactory.getL2ForInterfaceIid(ifaceKey), GbpNetconfTransaction.RETRY_COUNT);
518         if (transactionState) {
519             LOG.debug("Removing bridge domain from interface {}", VppIidFactory.getInterfaceIID(ifaceKey));
520             return Futures.immediateFuture(null);
521         } else {
522             final String message = "Failed to remove bridge domain from interface "
523                     + VppIidFactory.getInterfaceIID(ifaceKey);
524             LOG.warn(message);
525             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
526         }
527     }
528
529     private L2Builder readL2ForInterface(InstanceIdentifier<Node> vppIid, InterfaceKey ifaceKey) {
530         InstanceIdentifier<L2> l2Iid = VppIidFactory.getL2ForInterfaceIid(ifaceKey);
531         final ReadOnlyTransaction rwTxRead = VbdNetconfTransaction.NODE_DATA_BROKER_MAP.get(vppIid).getKey().newReadOnlyTransaction();
532         Optional<L2> optL2 = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, l2Iid, rwTxRead);
533         rwTxRead.close();
534         return  (optL2.isPresent()) ? new L2Builder(optL2.get()) : new L2Builder();
535     }
536
537     /**
538      * Removes bridge domain (if exist) from an interface (if exist).<br>
539      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update endpoint
540      * location.
541      * <p>
542      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
543      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
544      * containing message in {@link Exception#getMessage()}
545      *
546      * @param addrEpWithLoc {@link AddressEndpointWithLocation} containing
547      *                      {@link ExternalLocationCase} where
548      *                      {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
549      *                      and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
550      * @return {@link ListenableFuture}
551      */
552     public synchronized @Nonnull ListenableFuture<Void> deleteBridgeDomainFromInterface(
553             @Nonnull AddressEndpointWithLocation addrEpWithLoc) {
554         // TODO update ACLs for peers
555         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
556         InstanceIdentifier<Node> vppNodeIid = (InstanceIdentifier<Node>) epLoc.getExternalNodeMountPoint();
557         String interfacePath = epLoc.getExternalNodeConnector();
558
559         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
560                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
561         if (!optInterfaceIid.isPresent()) {
562             return Futures.immediateFailedFuture(
563                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
564         }
565         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
566         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.resolveDataBrokerForMountPoint(vppNodeIid);
567         if (!potentialVppDataProvider.isPresent()) {
568             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
569         }
570         final Optional<Interface> optInterface = GbpNetconfTransaction.read(vppNodeIid,
571                 LogicalDatastoreType.CONFIGURATION, interfaceIid, GbpNetconfTransaction.RETRY_COUNT);
572         if (!optInterface.isPresent()) {
573             // interface does not exist so we consider job done
574             return Futures.immediateFuture(null);
575         }
576         String existingBridgeDomain = resolveBridgeDomain(optInterface.get());
577         if (Strings.isNullOrEmpty(existingBridgeDomain)) {
578             LOG.debug("Bridge domain does not exist therefore it is considered as deleted for interface {}",
579                     interfacePath);
580             // bridge domain does not exist on interface so we consider job done
581             return vppEndpointLocationProvider.replaceLocationForEndpoint(
582                     new ExternalLocationCaseBuilder().setExternalNode(null)
583                         .setExternalNodeMountPoint(vppNodeIid)
584                         .setExternalNodeConnector(interfacePath)
585                         .build(),
586                     addrEpWithLoc.getKey());
587         }
588         InstanceIdentifier<L2> l2Iid =
589                 interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
590         LOG.debug("Deleting bridge domain from interface {}", interfacePath);
591         final boolean transactionState =
592                 GbpNetconfTransaction.netconfSyncedDelete(vppNodeIid, l2Iid, GbpNetconfTransaction.RETRY_COUNT);
593         if (transactionState) {
594             AccessListWrapper.removeAclRefFromIface(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
595             AccessListWrapper.removeAclsForInterface(vppNodeIid, interfaceIid.firstKeyOf(Interface.class));
596             return vppEndpointLocationProvider.replaceLocationForEndpoint(
597                     new ExternalLocationCaseBuilder().setExternalNode(null)
598                         .setExternalNodeMountPoint(vppNodeIid)
599                         .setExternalNodeConnector(interfacePath)
600                         .build(),
601                     addrEpWithLoc.getKey());
602         } else {
603             final String message = "Failed to delete bridge domain from interface " + interfacePath;
604             LOG.warn(message);
605             return Futures.immediateFailedFuture(new VppRendererProcessingException(message));
606         }
607     }
608
609     public static ExternalLocationCase resolveAndValidateLocation(AddressEndpointWithLocation addrEpWithLoc) {
610         LocationType locationType = addrEpWithLoc.getAbsoluteLocation().getLocationType();
611         if (!(locationType instanceof ExternalLocationCase)) {
612             throw new IllegalArgumentException("Endpoint does not have external location " + addrEpWithLoc);
613         }
614         ExternalLocationCase result = (ExternalLocationCase) locationType;
615         if (result.getExternalNodeMountPoint() == null || result.getExternalNodeConnector() == null) {
616             throw new IllegalArgumentException(
617                     "Endpoint does not have external-node-mount-point or external-node-connector " + addrEpWithLoc);
618         }
619         return result;
620     }
621
622     private static @Nullable String resolveBridgeDomain(@Nonnull Interface iface) {
623         VppInterfaceAugmentation vppInterfaceAugmentation = iface.getAugmentation(VppInterfaceAugmentation.class);
624         L2 existingL2 = vppInterfaceAugmentation.getL2();
625         if (existingL2 != null) {
626             Interconnection interconnection = existingL2.getInterconnection();
627             if (interconnection instanceof BridgeBased) {
628                 return ((BridgeBased) interconnection).getBridgeDomain();
629             }
630         }
631         return null;
632     }
633
634     private static boolean hasNodeAndInterface(VppEndpoint vppEp) {
635         if (vppEp.getVppNodeId() == null) {
636             LOG.debug("vpp-node is missing. {}", vppEp);
637             return false;
638         }
639         if (Strings.isNullOrEmpty(vppEp.getVppInterfaceName())) {
640             LOG.debug("vpp-interface-name is missing. {}", vppEp);
641             return false;
642         }
643         return true;
644     }
645
646     @Override
647     public void close() throws Exception {
648         vppEndpointLocationProvider.close();
649     }
650 }