5340f929865337cc066ffb7c5e022fb1a4b2718a
[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.concurrent.ExecutionException;
12 import java.util.concurrent.ExecutorService;
13
14 import javax.annotation.Nonnull;
15 import javax.annotation.Nullable;
16
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
21 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.ConfigCommand;
22 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.VhostUserCommand;
23 import org.opendaylight.groupbasedpolicy.renderer.vpp.commands.VhostUserCommand.VhostUserCommandBuilder;
24 import org.opendaylight.groupbasedpolicy.renderer.vpp.event.NodeOperEvent;
25 import org.opendaylight.groupbasedpolicy.renderer.vpp.event.VppEndpointConfEvent;
26 import org.opendaylight.groupbasedpolicy.renderer.vpp.util.General.Operations;
27 import org.opendaylight.groupbasedpolicy.renderer.vpp.util.MountedDataBrokerProvider;
28 import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.LocationType;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.location.type.ExternalLocationCase;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.base_endpoint.rev160427.has.absolute.location.absolute.location.location.type.ExternalLocationCaseBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.renderer.rev151103.renderers.renderer.renderer.policy.configuration.endpoints.AddressEndpointWithLocation;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425.config.VppEndpoint;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425.config.vpp.endpoint.InterfaceTypeChoice;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.vpp_renderer.rev160425.config.vpp.endpoint._interface.type.choice.VhostUserCase;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VhostUserRole;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceAugmentation;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.L2;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.L2Builder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.base.attributes.Interconnection;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.base.attributes.interconnection.BridgeBased;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.base.attributes.interconnection.BridgeBasedBuilder;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.common.base.Optional;
49 import com.google.common.base.Preconditions;
50 import com.google.common.base.Strings;
51 import com.google.common.eventbus.Subscribe;
52 import com.google.common.util.concurrent.AsyncFunction;
53 import com.google.common.util.concurrent.CheckedFuture;
54 import com.google.common.util.concurrent.Futures;
55 import com.google.common.util.concurrent.ListenableFuture;
56
57 public class InterfaceManager implements AutoCloseable {
58
59     private static final Logger LOG = LoggerFactory.getLogger(InterfaceManager.class);
60     private final MountedDataBrokerProvider mountDataProvider;
61     private final VppEndpointLocationProvider vppEndpointLocationProvider;
62     private final ExecutorService netconfWorker;
63
64     public InterfaceManager(@Nonnull MountedDataBrokerProvider mountDataProvider, @Nonnull DataBroker dataProvider, @Nonnull ExecutorService netconfWorker) {
65         this.mountDataProvider = Preconditions.checkNotNull(mountDataProvider);
66         this.netconfWorker = Preconditions.checkNotNull(netconfWorker);
67         this.vppEndpointLocationProvider = new VppEndpointLocationProvider(dataProvider);
68     }
69
70     @Subscribe
71     public synchronized void vppEndpointChanged(VppEndpointConfEvent event) {
72         try {
73             switch (event.getDtoModificationType()) {
74                 case CREATED:
75                     vppEndpointCreated(event.getAfter().get()).get();
76                     break;
77                 case UPDATED:
78                     vppEndpointDeleted(event.getBefore().get()).get();
79                     vppEndpointCreated(event.getAfter().get()).get();
80                     break;
81                 case DELETED:
82                     vppEndpointDeleted(event.getBefore().get()).get();
83                     break;
84             }
85         } catch (InterruptedException | ExecutionException e) {
86             LOG.error("Failed to update Vpp Endpoint. {}", e);
87             e.printStackTrace();
88         }
89     }
90
91     private ListenableFuture<Void> vppEndpointCreated(VppEndpoint vppEndpoint) {
92         Optional<ConfigCommand> potentialIfaceCommand = createInterfaceWithoutBdCommand(vppEndpoint, Operations.PUT);
93         if (!potentialIfaceCommand.isPresent()) {
94             return Futures.immediateFuture(null);
95         }
96         ConfigCommand ifaceWithoutBdCommand = potentialIfaceCommand.get();
97         InstanceIdentifier<?> vppNodeIid = vppEndpoint.getVppNodePath();
98         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.getDataBrokerForMountPoint(vppNodeIid);
99         if (!potentialVppDataProvider.isPresent()) {
100             LOG.debug("Cannot get data broker for mount point {}", vppNodeIid);
101             Futures.immediateFuture(null);
102         }
103         DataBroker vppDataBroker = potentialVppDataProvider.get();
104         return createIfaceOnVpp(ifaceWithoutBdCommand, vppDataBroker, vppEndpoint, vppNodeIid);
105     }
106
107     private ListenableFuture<Void> createIfaceOnVpp(ConfigCommand createIfaceWithoutBdCommand,
108             DataBroker vppDataBroker, VppEndpoint vppEndpoint, InstanceIdentifier<?> vppNodeIid) {
109         ReadWriteTransaction rwTx = vppDataBroker.newReadWriteTransaction();
110         createIfaceWithoutBdCommand.execute(rwTx);
111         return Futures.transform(rwTx.submit(), new AsyncFunction<Void, Void>() {
112
113             @Override
114             public ListenableFuture<Void> apply(Void input) {
115                 LOG.debug("Create interface on VPP command was successful:\nVPP: {}\nCommand: {}", vppNodeIid,
116                         createIfaceWithoutBdCommand);
117                 return vppEndpointLocationProvider.createLocationForVppEndpoint(vppEndpoint);
118             }
119         }, netconfWorker);
120     }
121
122     private ListenableFuture<Void> vppEndpointDeleted(VppEndpoint vppEndpoint) {
123         Optional<ConfigCommand> potentialIfaceCommand = createInterfaceWithoutBdCommand(vppEndpoint, Operations.DELETE);
124         if (!potentialIfaceCommand.isPresent()) {
125             return Futures.immediateFuture(null);
126         }
127         ConfigCommand ifaceWithoutBdCommand = potentialIfaceCommand.get();
128         InstanceIdentifier<?> vppNodeIid = vppEndpoint.getVppNodePath();
129         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.getDataBrokerForMountPoint(vppNodeIid);
130         if (!potentialVppDataProvider.isPresent()) {
131             LOG.debug("Cannot get data broker for mount point {}", vppNodeIid);
132             return Futures.immediateFuture(null);
133         }
134         DataBroker vppDataBroker = potentialVppDataProvider.get();
135         return deleteIfaceOnVpp(ifaceWithoutBdCommand, vppDataBroker, vppEndpoint, vppNodeIid);
136     }
137
138     private ListenableFuture<Void> deleteIfaceOnVpp(ConfigCommand deleteIfaceWithoutBdCommand,
139             DataBroker vppDataBroker, VppEndpoint vppEndpoint, InstanceIdentifier<?> vppNodeIid) {
140         ReadWriteTransaction rwTx = vppDataBroker.newReadWriteTransaction();
141         deleteIfaceWithoutBdCommand.execute(rwTx);
142
143         return Futures.transform(rwTx.submit(), new AsyncFunction<Void, Void>() {
144
145             @Override
146             public ListenableFuture<Void> apply(Void input) {
147                 LOG.debug("Delete interface on VPP command was successful:\nVPP: {}\nCommand: {}", vppNodeIid,
148                         deleteIfaceWithoutBdCommand);
149                 return vppEndpointLocationProvider.deleteLocationForVppEndpoint(vppEndpoint);
150             }
151         }, netconfWorker);
152     }
153
154     @Subscribe
155     public synchronized void vppNodeChanged(NodeOperEvent event) {
156         switch (event.getDtoModificationType()) {
157             case CREATED:
158                 if (event.isAfterConnected()) {
159                     // TODO read VppEndpoints or cache them during vppEndpointChanged()
160                 }
161                 break;
162             case UPDATED:
163                 if (!event.isBeforeConnected() && event.isAfterConnected()) {
164                     // TODO reconciliation - diff between disconnected snapshot and current snapshot
165                 }
166                 break;
167             case DELETED:
168                 if (event.isBeforeConnected()) {
169                     // TODO we could do snapshot of VppEndpoints 
170                     // which can be used for reconciliation
171                 }
172                 break;
173         }
174     }
175
176     private static Optional<ConfigCommand> createInterfaceWithoutBdCommand(@Nonnull VppEndpoint vppEp,
177             @Nonnull Operations operations) {
178         if (!hasNodeAndInterface(vppEp)) {
179             LOG.debug("Interface command is not created for {}", vppEp);
180             return Optional.absent();
181         }
182         VhostUserCommandBuilder builder = VhostUserCommand.builder();
183         builder.setName(vppEp.getVppInterfaceName());
184         InterfaceTypeChoice interfaceTypeChoice = vppEp.getInterfaceTypeChoice();
185         if (interfaceTypeChoice instanceof VhostUserCase) {
186             VhostUserCase vhostUserIface = (VhostUserCase) interfaceTypeChoice;
187             String socket = vhostUserIface.getSocket();
188             if (Strings.isNullOrEmpty(socket)) {
189                 LOG.debug("Vhost user interface command is not created because socket is missing. {}", vppEp);
190                 return Optional.absent();
191             }
192             builder.setSocket(socket);
193             builder.setRole(VhostUserRole.Client);
194         }
195         VhostUserCommand vhostUserCommand =
196                 builder.setOperation(operations).setDescription(vppEp.getDescription()).build();
197         return Optional.of(vhostUserCommand);
198     }
199
200     /**
201      * Adds bridge domain to an interface if the interface exist.<br>
202      * It rewrites bridge domain in case it already exist.<br>
203      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update location
204      * when the interface is created successfully.<br>
205      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
206      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
207      * containing message in {@link Exception#getMessage()}
208      * 
209      * @param bridgeDomainName bridge domain
210      * @param addrEpWithLoc {@link AddressEndpointWithLocation} containing
211      *        {@link ExternalLocationCase} where
212      *        {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
213      *        and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
214      * @return {@link ListenableFuture}
215      */
216     public synchronized @Nonnull ListenableFuture<Void> addBridgeDomainToInterface(@Nonnull String bridgeDomainName,
217             @Nonnull AddressEndpointWithLocation addrEpWithLoc) {
218         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
219         InstanceIdentifier<?> vppNodeIid = epLoc.getExternalNodeMountPoint();
220         String interfacePath = epLoc.getExternalNodeConnector();
221
222         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
223                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
224         if (!optInterfaceIid.isPresent()) {
225             return Futures.immediateFailedFuture(
226                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
227         }
228         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
229
230         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.getDataBrokerForMountPoint(vppNodeIid);
231         if (!potentialVppDataProvider.isPresent()) {
232             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
233         }
234
235         ReadWriteTransaction rwTx = potentialVppDataProvider.get().newReadWriteTransaction();
236         CheckedFuture<Optional<Interface>, ReadFailedException> futureIface =
237                 rwTx.read(LogicalDatastoreType.CONFIGURATION, interfaceIid);
238         return Futures.transform(futureIface, new AsyncFunction<Optional<Interface>, Void>() {
239
240             @Override
241             public ListenableFuture<Void> apply(Optional<Interface> optIface) throws Exception {
242                 if (!optIface.isPresent()) {
243                     return Futures.immediateFailedFuture(new Exception("Iterface "
244                             + interfaceIid.firstKeyOf(Interface.class) + " does not exist on node " + vppNodeIid));
245                 }
246
247                 String existingBridgeDomain = resolveBridgeDomain(optIface.get());
248                 if (bridgeDomainName.equals(existingBridgeDomain)) {
249                     LOG.debug("Bridge domain {} already exists on interface {}", bridgeDomainName, interfacePath);
250                     String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
251                     if (!bridgeDomainPath.equals(epLoc.getExternalNode())) {
252                         return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
253                             .setExternalNode(bridgeDomainPath)
254                             .setExternalNodeMountPoint(vppNodeIid)
255                             .setExternalNodeConnector(interfacePath)
256                             .build(), addrEpWithLoc.getKey());
257                     }
258                     return Futures.immediateFuture(null);
259                 }
260
261                 InstanceIdentifier<L2> l2Iid =
262                         interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
263                 Optional<L2> optL2 = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, l2Iid, rwTx);
264                 L2Builder l2Builder = (optL2.isPresent()) ? new L2Builder(optL2.get()) : new L2Builder();
265                 L2 l2 = l2Builder.setInterconnection(new BridgeBasedBuilder().setBridgeDomain(bridgeDomainName).build()).build();
266                 rwTx.put(LogicalDatastoreType.CONFIGURATION, l2Iid, l2);
267                 LOG.debug("Adding bridge domain {} to interface {}", bridgeDomainName, interfacePath);
268                 return Futures.transform(rwTx.submit(), new AsyncFunction<Void, Void>() {
269
270                     @Override
271                     public ListenableFuture<Void> apply(Void input) {
272                         String bridgeDomainPath = VppPathMapper.bridgeDomainToRestPath(bridgeDomainName);
273                         return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
274                                 .setExternalNode(bridgeDomainPath)
275                                 .setExternalNodeMountPoint(vppNodeIid)
276                                 .setExternalNodeConnector(interfacePath)
277                                 .build(), addrEpWithLoc.getKey());
278                     }
279                 }, netconfWorker);
280             }
281         }, netconfWorker);
282     }
283
284     /**
285      * <p>
286      * Removes bridge domain (if exist) from an interface (if exist).<br>
287      * {@link VppEndpointLocationProvider#VPP_ENDPOINT_LOCATION_PROVIDER} will update endpoint
288      * location.
289      * <p>
290      * If the interface does not exist or other problems occur {@link ListenableFuture} will fail
291      * as {@link Futures#immediateFailedFuture(Throwable)} with {@link Exception}
292      * containing message in {@link Exception#getMessage()}
293      * 
294      * @param addrEpWithLoc {@link AddressEndpointWithLocation} containing
295      *        {@link ExternalLocationCase} where
296      *        {@link ExternalLocationCase#getExternalNodeMountPoint()} MUST NOT be {@code null}
297      *        and {@link ExternalLocationCase#getExternalNodeConnector()} MUST NOT be {@code null}
298      * @return {@link ListenableFuture}
299      */
300     public synchronized @Nonnull ListenableFuture<Void> deleteBridgeDomainFromInterface(
301             @Nonnull AddressEndpointWithLocation addrEpWithLoc) {
302         ExternalLocationCase epLoc = resolveAndValidateLocation(addrEpWithLoc);
303         InstanceIdentifier<?> vppNodeIid = epLoc.getExternalNodeMountPoint();
304         String interfacePath = epLoc.getExternalNodeConnector();
305
306         Optional<InstanceIdentifier<Interface>> optInterfaceIid =
307                 VppPathMapper.interfaceToInstanceIdentifier(interfacePath);
308         if (!optInterfaceIid.isPresent()) {
309             return Futures.immediateFailedFuture(
310                     new Exception("Cannot resolve interface instance-identifier for interface path" + interfacePath));
311         }
312         InstanceIdentifier<Interface> interfaceIid = optInterfaceIid.get();
313
314         Optional<DataBroker> potentialVppDataProvider = mountDataProvider.getDataBrokerForMountPoint(vppNodeIid);
315         if (!potentialVppDataProvider.isPresent()) {
316             return Futures.immediateFailedFuture(new Exception("Cannot get data broker for mount point " + vppNodeIid));
317         }
318
319         ReadWriteTransaction rwTx = potentialVppDataProvider.get().newReadWriteTransaction();
320         CheckedFuture<Optional<Interface>, ReadFailedException> futureIface =
321                 rwTx.read(LogicalDatastoreType.CONFIGURATION, interfaceIid);
322         return Futures.transform(futureIface, new AsyncFunction<Optional<Interface>, Void>() {
323
324             @Override
325             public ListenableFuture<Void> apply(Optional<Interface> optIface) throws Exception {
326                 if (!optIface.isPresent()) {
327                     // interface does not exist so we consider job done
328                     return Futures.immediateFuture(null);
329                 }
330
331                 String existingBridgeDomain = resolveBridgeDomain(optIface.get());
332                 if (Strings.isNullOrEmpty(existingBridgeDomain)) {
333                     LOG.debug("Bridge domain does not exist therefore it is cosidered as"
334                             + "deleted for interface {}", interfacePath);
335                     // bridge domain does not exist on interface so we consider job done
336                     return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
337                             .setExternalNode(null)
338                             .setExternalNodeMountPoint(vppNodeIid)
339                             .setExternalNodeConnector(interfacePath)
340                             .build(), addrEpWithLoc.getKey());
341                 }
342
343                 InstanceIdentifier<L2> l2Iid =
344                         interfaceIid.builder().augmentation(VppInterfaceAugmentation.class).child(L2.class).build();
345                 rwTx.delete(LogicalDatastoreType.CONFIGURATION, l2Iid);
346                 LOG.debug("Deleting bridge domain from interface {}", interfacePath);
347                 return Futures.transform(rwTx.submit(), new AsyncFunction<Void, Void>() {
348
349                     @Override
350                     public ListenableFuture<Void> apply(Void input) {
351                         return vppEndpointLocationProvider.replaceLocationForEndpoint(new ExternalLocationCaseBuilder()
352                                 .setExternalNode(null)
353                                 .setExternalNodeMountPoint(vppNodeIid)
354                                 .setExternalNodeConnector(interfacePath)
355                                 .build(), addrEpWithLoc.getKey());
356                     }
357                 }, netconfWorker);
358             }
359         }, netconfWorker);
360     }
361
362     private static ExternalLocationCase resolveAndValidateLocation(AddressEndpointWithLocation addrEpWithLoc) {
363         LocationType locationType = addrEpWithLoc.getAbsoluteLocation().getLocationType();
364         if (!(locationType instanceof ExternalLocationCase)) {
365             throw new IllegalArgumentException("Endpoint does not have external location " + addrEpWithLoc);
366         }
367         ExternalLocationCase result = (ExternalLocationCase) locationType;
368         if (result.getExternalNodeMountPoint() == null || result.getExternalNodeConnector() == null) {
369             throw new IllegalArgumentException(
370                     "Endpoint does not have external-node-mount-point or external-node-connector " + addrEpWithLoc);
371         }
372         return result;
373     }
374
375     private static @Nullable String resolveBridgeDomain(@Nonnull Interface iface) {
376         VppInterfaceAugmentation vppInterfaceAugmentation = iface.getAugmentation(VppInterfaceAugmentation.class);
377         L2 existingL2 = vppInterfaceAugmentation.getL2();
378         if (existingL2 != null) {
379             Interconnection interconnection = existingL2.getInterconnection();
380             if (interconnection instanceof BridgeBased) {
381                 return ((BridgeBased) interconnection).getBridgeDomain();
382             }
383         }
384         return null;
385     }
386
387     private static boolean hasNodeAndInterface(VppEndpoint vppEp) {
388         if (vppEp.getVppNodePath() == null) {
389             LOG.debug("vpp-node is missing. {}", vppEp);
390             return false;
391         }
392         if (Strings.isNullOrEmpty(vppEp.getVppInterfaceName())) {
393             LOG.debug("vpp-interface-name is missing. {}", vppEp);
394             return false;
395         }
396         return true;
397     }
398
399     @Override
400     public void close() throws Exception {
401         vppEndpointLocationProvider.close();
402     }
403
404 }