Merge "BUG-1511 - Datastore: cleanup ListenerTreeAPI"
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / NetconfDevice.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.controller.sal.connect.netconf;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Sets;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.ListeningExecutorService;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.util.Collection;
23 import java.util.HashSet;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Set;
27 import java.util.concurrent.Callable;
28 import java.util.concurrent.ExecutorService;
29 import org.opendaylight.controller.netconf.api.NetconfMessage;
30 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
31 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
32 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
33 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
34 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCapabilities;
35 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
36 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
37 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc;
38 import org.opendaylight.controller.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
39 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
40 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.unavailable.capabilities.UnavailableCapability;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.common.RpcResult;
45 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
48 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
49 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
50 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
51 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
52 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
53 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
54 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
55 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
61  */
62 public final class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
63
64     private static final Logger logger = LoggerFactory.getLogger(NetconfDevice.class);
65
66     public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION = new Function<QName, SourceIdentifier>() {
67         @Override
68         public SourceIdentifier apply(final QName input) {
69             return new SourceIdentifier(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision()));
70         }
71     };
72
73     private final RemoteDeviceId id;
74     private final boolean reconnectOnSchemasChange;
75
76     private final SchemaContextFactory schemaContextFactory;
77     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
78     private final ListeningExecutorService processingExecutor;
79     private final SchemaSourceRegistry schemaRegistry;
80     private final MessageTransformer<NetconfMessage> messageTransformer;
81     private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
82     private final NotificationHandler notificationHandler;
83     private final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
84
85     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
86                          final ExecutorService globalProcessingExecutor, final MessageTransformer<NetconfMessage> messageTransformer) {
87         this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, messageTransformer, false);
88     }
89
90     // FIXME reduce parameters
91     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
92                          final ExecutorService globalProcessingExecutor, final MessageTransformer<NetconfMessage> messageTransformer, final boolean reconnectOnSchemasChange) {
93         this.id = id;
94         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
95         this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
96         this.messageTransformer = messageTransformer;
97         this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
98         this.salFacade = salFacade;
99         this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
100         this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
101         this.notificationHandler = new NotificationHandler(salFacade, messageTransformer, id);
102     }
103
104     @Override
105     public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
106                                   final NetconfDeviceCommunicator listener) {
107         // SchemaContext setup has to be performed in a dedicated thread since
108         // we are in a netty thread in this method
109         // Yang models are being downloaded in this method and it would cause a
110         // deadlock if we used the netty thread
111         // http://netty.io/wiki/thread-model.html
112         logger.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
113
114         final NetconfDeviceRpc deviceRpc = setUpDeviceRpc(listener);
115
116         final DeviceSourcesResolver task = new DeviceSourcesResolver(deviceRpc, remoteSessionCapabilities, id, stateSchemasResolver);
117         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
118
119         if(shouldListenOnSchemaChange(remoteSessionCapabilities)) {
120            registerToBaseNetconfStream(deviceRpc, listener);
121         }
122
123         final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
124             @Override
125             public void onSuccess(final DeviceSources result) {
126                 addProvidedSourcesToSchemaRegistry(deviceRpc, result);
127                 setUpSchema(result);
128             }
129
130             private void setUpSchema(final DeviceSources result) {
131                 processingExecutor.submit(new RecursiveSchemaSetup(result, remoteSessionCapabilities, deviceRpc, listener));
132             }
133
134             @Override
135             public void onFailure(final Throwable t) {
136                 logger.warn("{}: Unexpected error resolving device sources: {}", id, t);
137                 handleSalInitializationFailure(t, listener);
138             }
139         };
140
141         Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
142
143     }
144
145     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
146        final ListenableFuture<RpcResult<CompositeNode>> rpcResultListenableFuture =
147                 deviceRpc.invokeRpc(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME, NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
148
149         final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
150             @Override
151             public Optional<CompositeNode> filterNotification(final CompositeNode notification) {
152                 if (isCapabilityChanged(notification)) {
153                     logger.info("{}: Schemas change detected, reconnecting", id);
154                     // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
155                     listener.disconnect();
156                     return Optional.absent();
157                 }
158                 return Optional.of(notification);
159             }
160
161             private boolean isCapabilityChanged(final CompositeNode notification) {
162                 return notification.getNodeType().equals(NetconfCapabilityChange.QNAME);
163             }
164         };
165
166         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<RpcResult<CompositeNode>>() {
167             @Override
168             public void onSuccess(final RpcResult<CompositeNode> result) {
169                 notificationHandler.addNotificationFilter(filter);
170             }
171
172             @Override
173             public void onFailure(final Throwable t) {
174                 logger.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
175             }
176         });
177     }
178
179     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
180         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
181     }
182
183     private void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionPreferences remoteSessionCapabilities, final NetconfDeviceRpc deviceRpc) {
184         updateMessageTransformer(result);
185         salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
186         notificationHandler.onRemoteSchemaUp();
187
188         logger.info("{}: Netconf connector initialized successfully", id);
189     }
190
191     private void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
192         logger.error("{}: Initialization in sal failed, disconnecting from device", id, t);
193         listener.close();
194         onRemoteSessionDown();
195         resetMessageTransformer();
196     }
197
198     /**
199      * Set the schema context inside transformer to null as is in initial state
200      */
201     private void resetMessageTransformer() {
202         updateMessageTransformer(null);
203     }
204
205     /**
206      * Update initial message transformer to use retrieved schema
207      */
208     private void updateMessageTransformer(final SchemaContext currentSchemaContext) {
209         messageTransformer.onGlobalContextUpdated(currentSchemaContext);
210     }
211
212     private void addProvidedSourcesToSchemaRegistry(final NetconfDeviceRpc deviceRpc, final DeviceSources deviceSources) {
213         final NetconfRemoteSchemaYangSourceProvider yangProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
214         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
215             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
216                     PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
217         }
218     }
219
220     private NetconfDeviceRpc setUpDeviceRpc(final RemoteDeviceCommunicator<NetconfMessage> listener) {
221        return new NetconfDeviceRpc(listener, messageTransformer);
222     }
223
224     @Override
225     public void onRemoteSessionDown() {
226         salFacade.onDeviceDisconnected();
227         for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
228             sourceRegistration.close();
229         }
230         resetMessageTransformer();
231     }
232
233     @Override
234     public void onRemoteSessionFailed(Throwable throwable) {
235         salFacade.onDeviceFailed(throwable);
236     }
237
238     @Override
239     public void onNotification(final NetconfMessage notification) {
240         notificationHandler.handleNotification(notification);
241     }
242
243     /**
244      * Just a transfer object containing schema related dependencies. Injected in constructor.
245      */
246     public static class SchemaResourcesDTO {
247         private final SchemaSourceRegistry schemaRegistry;
248         private final SchemaContextFactory schemaContextFactory;
249         private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
250
251         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry, final SchemaContextFactory schemaContextFactory, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
252             this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
253             this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
254             this.stateSchemasResolver = Preconditions.checkNotNull(stateSchemasResolver);
255         }
256
257         public SchemaSourceRegistry getSchemaRegistry() {
258             return schemaRegistry;
259         }
260
261         public SchemaContextFactory getSchemaContextFactory() {
262             return schemaContextFactory;
263         }
264
265         public NetconfStateSchemas.NetconfStateSchemasResolver getStateSchemasResolver() {
266             return stateSchemasResolver;
267         }
268     }
269
270     /**
271      * Schema building callable.
272      */
273     private static class DeviceSourcesResolver implements Callable<DeviceSources> {
274         private final NetconfDeviceRpc deviceRpc;
275         private final NetconfSessionPreferences remoteSessionCapabilities;
276         private final RemoteDeviceId id;
277         private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
278
279         public DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
280             this.deviceRpc = deviceRpc;
281             this.remoteSessionCapabilities = remoteSessionCapabilities;
282             this.id = id;
283             this.stateSchemasResolver = stateSchemasResolver;
284         }
285
286         @Override
287         public DeviceSources call() throws Exception {
288
289             final Set<SourceIdentifier> requiredSources = Sets.newHashSet(Collections2.transform(
290                     remoteSessionCapabilities.getModuleBasedCaps(), QNAME_TO_SOURCE_ID_FUNCTION));
291
292             // If monitoring is not supported, we will still attempt to create schema, sources might be already provided
293             final NetconfStateSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
294             logger.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
295
296             final Set<SourceIdentifier> providedSources = Sets.newHashSet(Collections2.transform(
297                     availableSchemas.getAvailableYangSchemasQNames(), QNAME_TO_SOURCE_ID_FUNCTION));
298
299             final Set<SourceIdentifier> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
300
301             if (!requiredSourcesNotProvided.isEmpty()) {
302                 logger.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
303                         id, requiredSourcesNotProvided);
304                 logger.warn("{}: Attempting to build schema context from required sources", id);
305             }
306
307
308             // TODO should we perform this ? We have a mechanism to fix initialization of devices not reporting or required modules in hello
309             // That is overriding capabilities in configuration using attribute yang-module-capabilities
310             // This is more user friendly even though it clashes with attribute yang-module-capabilities
311             // Some devices do not report all required models in hello message, but provide them
312             final Set<SourceIdentifier> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
313             if (!providedSourcesNotRequired.isEmpty()) {
314                 logger.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
315                         id, providedSourcesNotRequired);
316                 logger.warn("{}: Adding provided but not required sources as required to prevent failures", id);
317                 requiredSources.addAll(providedSourcesNotRequired);
318             }
319
320             return new DeviceSources(requiredSources, providedSources);
321         }
322     }
323
324     /**
325      * Contains RequiredSources - sources from capabilities.
326      *
327      */
328     private static final class DeviceSources {
329         private final Collection<SourceIdentifier> requiredSources;
330         private final Collection<SourceIdentifier> providedSources;
331
332         public DeviceSources(final Collection<SourceIdentifier> requiredSources, final Collection<SourceIdentifier> providedSources) {
333             this.requiredSources = requiredSources;
334             this.providedSources = providedSources;
335         }
336
337         public Collection<SourceIdentifier> getRequiredSources() {
338             return requiredSources;
339         }
340
341         public Collection<SourceIdentifier> getProvidedSources() {
342             return providedSources;
343         }
344
345     }
346
347     /**
348      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
349      */
350     private final class RecursiveSchemaSetup implements Runnable {
351         private final DeviceSources deviceSources;
352         private final NetconfSessionPreferences remoteSessionCapabilities;
353         private final NetconfDeviceRpc deviceRpc;
354         private final RemoteDeviceCommunicator<NetconfMessage> listener;
355         private NetconfDeviceCapabilities capabilities;
356
357         public RecursiveSchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final NetconfDeviceRpc deviceRpc, final RemoteDeviceCommunicator<NetconfMessage> listener) {
358             this.deviceSources = deviceSources;
359             this.remoteSessionCapabilities = remoteSessionCapabilities;
360             this.deviceRpc = deviceRpc;
361             this.listener = listener;
362             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
363         }
364
365         @Override
366         public void run() {
367             setUpSchema(deviceSources.getRequiredSources());
368         }
369
370         /**
371          * Recursively build schema context, in case of success or final failure notify device
372          */
373         // FIXME reimplement without recursion
374         private void setUpSchema(final Collection<SourceIdentifier> requiredSources) {
375             logger.trace("{}: Trying to build schema context from {}", id, requiredSources);
376
377             // If no more sources, fail
378             if(requiredSources.isEmpty()) {
379                 handleSalInitializationFailure(new IllegalStateException(id + ": No more sources for schema context"), listener);
380                 return;
381             }
382
383             final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
384
385             final FutureCallback<SchemaContext> RecursiveSchemaBuilderCallback = new FutureCallback<SchemaContext>() {
386
387                 @Override
388                 public void onSuccess(final SchemaContext result) {
389                     logger.debug("{}: Schema context built successfully from {}", id, requiredSources);
390                     Collection<QName> filteredQNames = Sets.difference(remoteSessionCapabilities.getModuleBasedCaps(), capabilities.getUnresolvedCapabilites().keySet());
391                     capabilities.addCapabilities(filteredQNames);
392                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps());
393                     handleSalInitializationSuccess(result, remoteSessionCapabilities, deviceRpc);
394                 }
395
396                 @Override
397                 public void onFailure(final Throwable t) {
398                     // In case source missing, try without it
399                     if (t instanceof MissingSchemaSourceException) {
400                         final SourceIdentifier missingSource = ((MissingSchemaSourceException) t).getSourceId();
401                         logger.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
402                         capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource)), UnavailableCapability.FailureReason.MissingSource);
403                         setUpSchema(stripMissingSource(requiredSources, missingSource));
404
405                     // In case resolution error, try only with resolved sources
406                     } else if (t instanceof SchemaResolutionException) {
407                         // TODO check for infinite loop
408                         final SchemaResolutionException resolutionException = (SchemaResolutionException) t;
409                         final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
410                         capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
411                         logger.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
412                         setUpSchema(resolutionException.getResolvedSources());
413                     // unknown error, fail
414                     } else {
415                         handleSalInitializationFailure(t, listener);
416                     }
417                 }
418             };
419
420             Futures.addCallback(schemaBuilderFuture, RecursiveSchemaBuilderCallback);
421         }
422
423         private Collection<SourceIdentifier> stripMissingSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
424             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
425             final boolean removed = sourceIdentifiers.remove(sIdToRemove);
426             Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
427             return sourceIdentifiers;
428         }
429
430         private Collection<QName> getQNameFromSourceIdentifiers(Collection<SourceIdentifier> identifiers) {
431             Collection<QName> qNames = new HashSet<>();
432             for (SourceIdentifier source : identifiers) {
433                 Optional<QName> qname = getQNameFromSourceIdentifier(source);
434                 if (qname.isPresent()) {
435                     qNames.add(qname.get());
436                 }
437             }
438             if (qNames.isEmpty()) {
439                 logger.debug("Unable to map any source identfiers to a capability reported by device : " + identifiers);
440             }
441             return qNames;
442         }
443
444         private Optional<QName> getQNameFromSourceIdentifier(SourceIdentifier identifier) {
445             for (QName qname : remoteSessionCapabilities.getModuleBasedCaps()) {
446                 if (qname.getLocalName().equals(identifier.getName())
447                         && qname.getFormattedRevision().equals(identifier.getRevision())) {
448                     return Optional.of(qname);
449                 }
450             }
451             throw new IllegalArgumentException("Unable to map identifier to a devices reported capability: " + identifier);
452         }
453     }
454 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.