Use Optional.isEmpty()
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / 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.netconf.sal.connect.netconf;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
13
14 import com.google.common.base.Predicates;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.Sets;
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 com.google.common.util.concurrent.SettableFuture;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import io.netty.util.concurrent.EventExecutor;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.Optional;
32 import java.util.Set;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.TimeUnit;
35 import java.util.stream.Collectors;
36 import org.checkerframework.checker.lock.qual.GuardedBy;
37 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
38 import org.opendaylight.mdsal.dom.api.DOMRpcService;
39 import org.opendaylight.netconf.api.NetconfMessage;
40 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
41 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
42 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
43 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
44 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
54 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
55 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
61 import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
62 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
63 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
64 import org.opendaylight.yangtools.yang.common.QName;
65 import org.opendaylight.yangtools.yang.common.RpcError;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
71 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
72 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
73 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
77 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
78 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84
85 /**
86  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
87  */
88 public class NetconfDevice
89         implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
90
91     @SuppressFBWarnings(value = "SLF4J_LOGGER_SHOULD_BE_PRIVATE",
92             justification = "Needed for common logging of related classes")
93     static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
94
95     private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
96         SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
97     private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
98         NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
99
100     protected final RemoteDeviceId id;
101     protected final EffectiveModelContextFactory schemaContextFactory;
102     protected final SchemaSourceRegistry schemaRegistry;
103     protected final SchemaRepository schemaRepository;
104
105     protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
106
107     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
108     private final ListeningExecutorService processingExecutor;
109     private final DeviceActionFactory deviceActionFactory;
110     private final NetconfDeviceSchemasResolver stateSchemasResolver;
111     private final NotificationHandler notificationHandler;
112     private final boolean reconnectOnSchemasChange;
113     private final BaseNetconfSchemas baseSchemas;
114     private final NetconfNode node;
115     private final EventExecutor eventExecutor;
116     private final NetconfNodeAugmentedOptional nodeOptional;
117
118     @GuardedBy("this")
119     private boolean connected = false;
120
121     // Message transformer is constructed once the schemas are available
122     private MessageTransformer<NetconfMessage> messageTransformer;
123
124     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
125             final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
126             final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
127         this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null,
128             null, null, null);
129     }
130
131     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
132             final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
133             final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
134             final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
135             final NetconfNodeAugmentedOptional nodeOptional) {
136         this.baseSchemas = requireNonNull(baseSchemas);
137         this.id = id;
138         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
139         this.deviceActionFactory = deviceActionFactory;
140         this.node = node;
141         this.eventExecutor = eventExecutor;
142         this.nodeOptional = nodeOptional;
143         this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
144         this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
145         this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
146         this.salFacade = salFacade;
147         this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
148         this.processingExecutor = requireNonNull(globalProcessingExecutor);
149         this.notificationHandler = new NotificationHandler(salFacade, id);
150     }
151
152     @Override
153     public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
154                                   final NetconfDeviceCommunicator listener) {
155         // SchemaContext setup has to be performed in a dedicated thread since
156         // we are in a netty thread in this method
157         // Yang models are being downloaded in this method and it would cause a
158         // deadlock if we used the netty thread
159         // http://netty.io/wiki/thread-model.html
160         setConnected(true);
161         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
162
163         final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
164         final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
165             new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
166         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
167             new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
168
169         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
170             registerToBaseNetconfStream(initRpc, listener);
171         }
172
173         // Set up the SchemaContext for the device
174         final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
175             deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
176
177         // Potentially acquire mount point list and interpret it
178         final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
179             schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
180
181         Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
182             @Override
183             public void onSuccess(final MountPointContext result) {
184                 handleSalInitializationSuccess(result, remoteSessionCapabilities,
185                         getDeviceSpecificRpc(result, listener, baseSchema), listener);
186             }
187
188             @Override
189             public void onFailure(final Throwable cause) {
190                 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
191
192                 // No more sources, fail or try to reconnect
193                 if (cause instanceof EmptySchemaContextException) {
194                     if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().getAllowed()) {
195                         eventExecutor.schedule(() -> {
196                             LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
197                             LOG.warn("{} : No more sources for schema context.", id);
198                             LOG.info("{} : Try to remount device.", id);
199                             onRemoteSessionDown();
200                             salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
201                         }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
202                             TimeUnit.MILLISECONDS);
203                         return;
204                     }
205                 }
206
207                 handleSalInitializationFailure(cause, listener);
208                 salFacade.onDeviceFailed(cause);
209             }
210         }, MoreExecutors.directExecutor());
211     }
212
213     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
214                                              final NetconfDeviceCommunicator listener) {
215         // TODO check whether the model describing create subscription is present in schema
216         // Perhaps add a default schema context to support create-subscription if the model was not provided
217         // (same as what we do for base netconf operations in transformer)
218         final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
219                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
220                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
221
222         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
223             @Override
224             public void onSuccess(final DOMRpcResult domRpcResult) {
225                 notificationHandler.addNotificationFilter(notification -> {
226                     if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getNodeType())) {
227                         LOG.info("{}: Schemas change detected, reconnecting", id);
228                         // Only disconnect is enough,
229                         // the reconnecting nature of the connector will take care of reconnecting
230                         listener.disconnect();
231                         return Optional.empty();
232                     }
233                     return Optional.of(notification);
234                 });
235             }
236
237             @Override
238             public void onFailure(final Throwable throwable) {
239                 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
240                         throwable);
241             }
242         }, MoreExecutors.directExecutor());
243     }
244
245     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
246         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
247     }
248
249     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
250             justification = "https://github.com/spotbugs/spotbugs/issues/811")
251     private synchronized void handleSalInitializationSuccess(final MountPointContext result,
252                                         final NetconfSessionPreferences remoteSessionCapabilities,
253                                         final DOMRpcService deviceRpc,
254                                         final RemoteDeviceCommunicator<NetconfMessage> listener) {
255         //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
256         //since salFacade.onDeviceDisconnected was already called.
257         if (connected) {
258             this.messageTransformer = new NetconfMessageTransformer(result, true,
259                 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
260
261             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
262             this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
263                     this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
264                             this.messageTransformer, listener, result.getEffectiveModelContext()));
265             this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
266
267             LOG.info("{}: Netconf connector initialized successfully", id);
268         } else {
269             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
270         }
271     }
272
273     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
274             justification = "https://github.com/spotbugs/spotbugs/issues/811")
275     private void handleSalInitializationFailure(final Throwable throwable,
276                                                 final RemoteDeviceCommunicator<NetconfMessage> listener) {
277         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
278         listener.close();
279         onRemoteSessionDown();
280         resetMessageTransformer();
281     }
282
283     /**
284      * Set the transformer to null as is in initial state.
285      */
286     private void resetMessageTransformer() {
287         updateTransformer(null);
288     }
289
290     private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
291         messageTransformer = transformer;
292     }
293
294     private synchronized void setConnected(final boolean connected) {
295         this.connected = connected;
296     }
297
298     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
299             justification = "https://github.com/spotbugs/spotbugs/issues/811")
300     private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
301             final NetconfSessionPreferences remoteSessionCapabilities) {
302         LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
303         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
304         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
305             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
306                 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
307                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
308         }
309
310         return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
311     }
312
313     private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
314             final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
315         final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
316         if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
317             return Futures.immediateFuture(emptyContext);
318         }
319
320         // Create a temporary RPC invoker and acquire the mount point tree
321         LOG.debug("{}: Acquiring available mount points", id);
322         final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
323             new NetconfMessageTransformer(emptyContext, false, baseSchema));
324
325         return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
326             Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
327                 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
328                 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
329     }
330
331     private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
332         final Collection<? extends RpcError> errors = rpcResult.getErrors();
333         if (!errors.isEmpty()) {
334             LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
335         }
336         final NormalizedNode<?, ?> schemaMounts = rpcResult.getResult();
337         if (schemaMounts == null) {
338             LOG.debug("{}: device does not define any schema mounts", id);
339             return emptyContext;
340         }
341         if (!(schemaMounts instanceof ContainerNode)) {
342             LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
343             return emptyContext;
344         }
345
346         return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
347     }
348
349     @Override
350     public void onRemoteSessionDown() {
351         setConnected(false);
352         notificationHandler.onRemoteSchemaDown();
353
354         salFacade.onDeviceDisconnected();
355         sourceRegistrations.forEach(SchemaSourceRegistration::close);
356         sourceRegistrations.clear();
357         resetMessageTransformer();
358     }
359
360     @Override
361     public void onRemoteSessionFailed(final Throwable throwable) {
362         setConnected(false);
363         salFacade.onDeviceFailed(throwable);
364     }
365
366     @Override
367     public void onNotification(final NetconfMessage notification) {
368         notificationHandler.handleNotification(notification);
369     }
370
371     private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
372         return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
373     }
374
375     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
376             final RemoteDeviceCommunicator<NetconfMessage> listener, final BaseSchema schema) {
377         return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
378             new NetconfMessageTransformer(result, true, schema));
379     }
380
381     /**
382      * Just a transfer object containing schema related dependencies. Injected in constructor.
383      */
384     public static class SchemaResourcesDTO {
385         private final SchemaSourceRegistry schemaRegistry;
386         private final SchemaRepository schemaRepository;
387         private final EffectiveModelContextFactory schemaContextFactory;
388         private final NetconfDeviceSchemasResolver stateSchemasResolver;
389
390         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
391                                   final SchemaRepository schemaRepository,
392                                   final EffectiveModelContextFactory schemaContextFactory,
393                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
394             this.schemaRegistry = requireNonNull(schemaRegistry);
395             this.schemaRepository = requireNonNull(schemaRepository);
396             this.schemaContextFactory = requireNonNull(schemaContextFactory);
397             this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
398         }
399
400         public SchemaSourceRegistry getSchemaRegistry() {
401             return schemaRegistry;
402         }
403
404         public SchemaRepository getSchemaRepository() {
405             return schemaRepository;
406         }
407
408         public EffectiveModelContextFactory getSchemaContextFactory() {
409             return schemaContextFactory;
410         }
411
412         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
413             return stateSchemasResolver;
414         }
415     }
416
417     /**
418      * A dedicated exception to indicate when we fail to setup a SchemaContext.
419      *
420      * @author Robert Varga
421      */
422     private static final class EmptySchemaContextException extends Exception {
423         private static final long serialVersionUID = 1L;
424
425         EmptySchemaContextException(final String message) {
426             super(message);
427         }
428     }
429
430     /**
431      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
432      */
433     private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
434         private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
435
436         private final DeviceSources deviceSources;
437         private final NetconfSessionPreferences remoteSessionCapabilities;
438         private final NetconfDeviceCapabilities capabilities;
439
440         private Collection<SourceIdentifier> requiredSources;
441
442         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
443             this.deviceSources = deviceSources;
444             this.remoteSessionCapabilities = remoteSessionCapabilities;
445             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
446
447             // If device supports notifications and does not contain necessary modules, add them automatically
448             if (remoteSessionCapabilities.containsNonModuleCapability(
449                     XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
450                 deviceSources.getRequiredSourcesQName().addAll(
451                         Arrays.asList(
452                                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
453                                         .$YangModuleInfoImpl.getInstance().getName(),
454                                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
455                                         .$YangModuleInfoImpl.getInstance().getName()
456                         )
457                 );
458             }
459
460             requiredSources = deviceSources.getRequiredSources();
461             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
462
463             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
464                     UnavailableCapability.FailureReason.MissingSource);
465             requiredSources.removeAll(missingSources);
466         }
467
468         ListenableFuture<EffectiveModelContext> startResolution() {
469             trySetupSchema();
470             return resultFuture;
471         }
472
473         @Override
474         public void onSuccess(final EffectiveModelContext result) {
475             LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
476
477             final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
478                     capabilities.getUnresolvedCapabilites().keySet());
479             capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
480                     .setCapability(entry.toString()).setCapabilityOrigin(
481                             remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
482                     .collect(Collectors.toList()));
483
484             capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
485                     .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
486                             .setCapability(entry).setCapabilityOrigin(
487                                     remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
488                     .collect(Collectors.toList()));
489
490             resultFuture.set(result);
491         }
492
493         @Override
494         public void onFailure(final Throwable cause) {
495             // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
496             // that might be wrapping a MissingSchemaSourceException so we need to look
497             // at the cause of the exception to make sure we don't misinterpret it.
498             if (cause instanceof MissingSchemaSourceException) {
499                 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
500             } else if (cause instanceof SchemaResolutionException) {
501                 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
502             } else {
503                 LOG.debug("Unhandled failure", cause);
504                 resultFuture.setException(cause);
505                 // No more trying...
506                 return;
507             }
508
509             trySetupSchema();
510         }
511
512         private void trySetupSchema() {
513             if (!requiredSources.isEmpty()) {
514                 // Initiate async resolution, drive it back based on the result
515                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
516                 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
517                     MoreExecutors.directExecutor());
518             } else {
519                 LOG.debug("{}: no more sources for schema context", id);
520                 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
521             }
522         }
523
524         private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
525             return origSources.parallelStream().filter(sourceIdentifier -> {
526                 try {
527                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
528                     return false;
529                 } catch (InterruptedException | ExecutionException e) {
530                     return true;
531                 }
532             }).collect(Collectors.toList());
533         }
534
535         private Collection<SourceIdentifier> handleMissingSchemaSourceException(
536                 final MissingSchemaSourceException exception) {
537             // In case source missing, try without it
538             final SourceIdentifier missingSource = exception.getSourceId();
539             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
540                 id, missingSource);
541             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
542                 id, missingSource, exception);
543             final Collection<QName> qNameOfMissingSource =
544                 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
545             if (!qNameOfMissingSource.isEmpty()) {
546                 capabilities.addUnresolvedCapabilities(
547                         qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
548             }
549             return stripUnavailableSource(missingSource);
550         }
551
552         private Collection<SourceIdentifier> handleSchemaResolutionException(
553                 final SchemaResolutionException resolutionException) {
554             // In case resolution error, try only with resolved sources
555             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
556             // FIXME Do we really have assurance that these two cases cannot happen at once?
557             if (resolutionException.getFailedSource() != null) {
558                 // flawed model - exclude it
559                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
560                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
561                     id, failedSourceId);
562                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
563                     id, failedSourceId, resolutionException);
564                 capabilities.addUnresolvedCapabilities(
565                         getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
566                         UnavailableCapability.FailureReason.UnableToResolve);
567                 return stripUnavailableSource(resolutionException.getFailedSource());
568             }
569             // unsatisfied imports
570             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
571             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
572                 UnavailableCapability.FailureReason.UnableToResolve);
573             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
574                 id, resolutionException.getUnsatisfiedImports());
575             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
576                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
577             return resolutionException.getResolvedSources();
578         }
579
580         private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
581             final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
582             checkState(sourceIdentifiers.remove(sourceIdToRemove),
583                     "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
584             return sourceIdentifiers;
585         }
586
587         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
588             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
589
590             if (qNames.isEmpty()) {
591                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
592                         identifiers);
593             }
594             return Collections2.filter(qNames, Predicates.notNull());
595         }
596
597         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
598             // Required sources are all required and provided merged in DeviceSourcesResolver
599             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
600                 if (!qname.getLocalName().equals(identifier.getName())) {
601                     continue;
602                 }
603
604                 if (identifier.getRevision().equals(qname.getRevision())) {
605                     return qname;
606                 }
607             }
608             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
609                     deviceSources.getRequiredSourcesQName());
610             // return null since we cannot find the QName,
611             // this capability will be removed from required sources and not reported as unresolved-capability
612             return null;
613         }
614     }
615 }