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