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