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