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