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