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