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