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