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