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