Bump odlparent to 6.0.0
[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(), TimeUnit.MILLISECONDS);
190                         return;
191                     }
192                 }
193
194                 handleSalInitializationFailure(cause, listener);
195                 salFacade.onDeviceFailed(cause);
196             }
197         }, MoreExecutors.directExecutor());
198     }
199
200     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
201                                              final NetconfDeviceCommunicator listener) {
202         // TODO check whether the model describing create subscription is present in schema
203         // Perhaps add a default schema context to support create-subscription if the model was not provided
204         // (same as what we do for base netconf operations in transformer)
205         final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
206                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_PATH,
207                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
208
209         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
210             @Override
211             public void onSuccess(final DOMRpcResult domRpcResult) {
212                 notificationHandler.addNotificationFilter(notification -> {
213                     if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getNodeType())) {
214                         LOG.info("{}: Schemas change detected, reconnecting", id);
215                         // Only disconnect is enough,
216                         // the reconnecting nature of the connector will take care of reconnecting
217                         listener.disconnect();
218                         return Optional.empty();
219                     }
220                     return Optional.of(notification);
221                 });
222             }
223
224             @Override
225             public void onFailure(final Throwable throwable) {
226                 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
227                         throwable);
228             }
229         }, MoreExecutors.directExecutor());
230     }
231
232     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
233         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
234     }
235
236     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
237             justification = "https://github.com/spotbugs/spotbugs/issues/811")
238     private synchronized void handleSalInitializationSuccess(final MountPointContext result,
239                                         final NetconfSessionPreferences remoteSessionCapabilities,
240                                         final DOMRpcService deviceRpc,
241                                         final RemoteDeviceCommunicator<NetconfMessage> listener) {
242         //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
243         //since salFacade.onDeviceDisconnected was already called.
244         if (connected) {
245             final BaseSchema baseSchema =
246                 remoteSessionCapabilities.isNotificationsSupported()
247                         ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
248             this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
249
250             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
251             this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
252                     this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
253                             this.messageTransformer, listener, result.getSchemaContext()));
254             this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
255
256             LOG.info("{}: Netconf connector initialized successfully", id);
257         } else {
258             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
259         }
260     }
261
262     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
263             justification = "https://github.com/spotbugs/spotbugs/issues/811")
264     private void handleSalInitializationFailure(final Throwable throwable,
265                                                 final RemoteDeviceCommunicator<NetconfMessage> listener) {
266         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
267         listener.close();
268         onRemoteSessionDown();
269         resetMessageTransformer();
270     }
271
272     /**
273      * Set the transformer to null as is in initial state.
274      */
275     private void resetMessageTransformer() {
276         updateTransformer(null);
277     }
278
279     private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
280         messageTransformer = transformer;
281     }
282
283     private synchronized void setConnected(final boolean connected) {
284         this.connected = connected;
285     }
286
287     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
288             justification = "https://github.com/spotbugs/spotbugs/issues/811")
289     private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
290         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
291         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
292             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
293                     PotentialSchemaSource.create(
294                             sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
295         }
296     }
297
298     @Override
299     public void onRemoteSessionDown() {
300         setConnected(false);
301         notificationHandler.onRemoteSchemaDown();
302
303         salFacade.onDeviceDisconnected();
304         sourceRegistrations.forEach(SchemaSourceRegistration::close);
305         sourceRegistrations.clear();
306         resetMessageTransformer();
307     }
308
309     @Override
310     public void onRemoteSessionFailed(final Throwable throwable) {
311         setConnected(false);
312         salFacade.onDeviceFailed(throwable);
313     }
314
315     @Override
316     public void onNotification(final NetconfMessage notification) {
317         notificationHandler.handleNotification(notification);
318     }
319
320     private static BaseSchema resolveBaseSchema(final boolean notificationSupport) {
321         return notificationSupport ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
322     }
323
324     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
325             final RemoteDeviceCommunicator<NetconfMessage> listener) {
326         return new NetconfDeviceRpc(result.getSchemaContext(), listener, new NetconfMessageTransformer(result, true));
327     }
328
329     /**
330      * Just a transfer object containing schema related dependencies. Injected in constructor.
331      */
332     public static class SchemaResourcesDTO {
333         private final SchemaSourceRegistry schemaRegistry;
334         private final SchemaRepository schemaRepository;
335         private final SchemaContextFactory schemaContextFactory;
336         private final NetconfDeviceSchemasResolver stateSchemasResolver;
337
338         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
339                                   final SchemaRepository schemaRepository,
340                                   final SchemaContextFactory schemaContextFactory,
341                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
342             this.schemaRegistry = requireNonNull(schemaRegistry);
343             this.schemaRepository = requireNonNull(schemaRepository);
344             this.schemaContextFactory = requireNonNull(schemaContextFactory);
345             this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
346         }
347
348         public SchemaSourceRegistry getSchemaRegistry() {
349             return schemaRegistry;
350         }
351
352         public SchemaRepository getSchemaRepository() {
353             return schemaRepository;
354         }
355
356         public SchemaContextFactory getSchemaContextFactory() {
357             return schemaContextFactory;
358         }
359
360         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
361             return stateSchemasResolver;
362         }
363     }
364
365     /**
366      * A dedicated exception to indicate when we fail to setup a SchemaContext.
367      *
368      * @author Robert Varga
369      */
370     private static final class EmptySchemaContextException extends Exception {
371         private static final long serialVersionUID = 1L;
372
373         EmptySchemaContextException(final String message) {
374             super(message);
375         }
376     }
377
378     /**
379      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
380      */
381     private final class SchemaSetup implements FutureCallback<SchemaContext> {
382         private final SettableFuture<SchemaContext> resultFuture = SettableFuture.create();
383
384         private final DeviceSources deviceSources;
385         private final NetconfSessionPreferences remoteSessionCapabilities;
386         private final NetconfDeviceCapabilities capabilities;
387
388         private Collection<SourceIdentifier> requiredSources;
389
390         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
391             this.deviceSources = deviceSources;
392             this.remoteSessionCapabilities = remoteSessionCapabilities;
393             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
394
395             requiredSources = deviceSources.getRequiredSources();
396             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
397
398             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
399                     UnavailableCapability.FailureReason.MissingSource);
400             requiredSources.removeAll(missingSources);
401         }
402
403         ListenableFuture<SchemaContext> startResolution() {
404             trySetupSchema();
405             return resultFuture;
406         }
407
408         @Override
409         public void onSuccess(final SchemaContext result) {
410             LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
411
412             final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
413                     capabilities.getUnresolvedCapabilites().keySet());
414             capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
415                     .setCapability(entry.toString()).setCapabilityOrigin(
416                             remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
417                     .collect(Collectors.toList()));
418
419             capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
420                     .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
421                             .setCapability(entry).setCapabilityOrigin(
422                                     remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
423                     .collect(Collectors.toList()));
424
425             resultFuture.set(result);
426         }
427
428         @Override
429         public void onFailure(final Throwable cause) {
430             // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
431             // that might be wrapping a MissingSchemaSourceException so we need to look
432             // at the cause of the exception to make sure we don't misinterpret it.
433             if (cause instanceof MissingSchemaSourceException) {
434                 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
435             } else if (cause instanceof SchemaResolutionException) {
436                 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
437             } else {
438                 LOG.debug("Unhandled failure", cause);
439                 resultFuture.setException(cause);
440                 // No more trying...
441                 return;
442             }
443
444             trySetupSchema();
445         }
446
447         private void trySetupSchema() {
448             if (!requiredSources.isEmpty()) {
449                 // Initiate async resolution, drive it back based on the result
450                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
451                 Futures.addCallback(schemaContextFactory.createSchemaContext(requiredSources), this,
452                     MoreExecutors.directExecutor());
453             } else {
454                 LOG.debug("{}: no more sources for schema context", id);
455                 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
456             }
457         }
458
459         private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
460             return origSources.parallelStream().filter(sourceIdentifier -> {
461                 try {
462                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
463                     return false;
464                 } catch (InterruptedException | ExecutionException e) {
465                     return true;
466                 }
467             }).collect(Collectors.toList());
468         }
469
470         private Collection<SourceIdentifier> handleMissingSchemaSourceException(
471                 final MissingSchemaSourceException exception) {
472             // In case source missing, try without it
473             final SourceIdentifier missingSource = exception.getSourceId();
474             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
475                 id, missingSource);
476             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
477                 id, missingSource, exception);
478             final Collection<QName> qNameOfMissingSource =
479                 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
480             if (!qNameOfMissingSource.isEmpty()) {
481                 capabilities.addUnresolvedCapabilities(
482                         qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
483             }
484             return stripUnavailableSource(missingSource);
485         }
486
487         private Collection<SourceIdentifier> handleSchemaResolutionException(
488                 final SchemaResolutionException resolutionException) {
489             // In case resolution error, try only with resolved sources
490             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
491             // FIXME Do we really have assurance that these two cases cannot happen at once?
492             if (resolutionException.getFailedSource() != null) {
493                 // flawed model - exclude it
494                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
495                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
496                     id, failedSourceId);
497                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
498                     id, failedSourceId, resolutionException);
499                 capabilities.addUnresolvedCapabilities(
500                         getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
501                         UnavailableCapability.FailureReason.UnableToResolve);
502                 return stripUnavailableSource(resolutionException.getFailedSource());
503             }
504             // unsatisfied imports
505             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
506             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
507                 UnavailableCapability.FailureReason.UnableToResolve);
508             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
509                 id, resolutionException.getUnsatisfiedImports());
510             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
511                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
512             return resolutionException.getResolvedSources();
513         }
514
515         private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
516             final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
517             checkState(sourceIdentifiers.remove(sourceIdToRemove),
518                     "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
519             return sourceIdentifiers;
520         }
521
522         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
523             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
524
525             if (qNames.isEmpty()) {
526                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
527                         identifiers);
528             }
529             return Collections2.filter(qNames, Predicates.notNull());
530         }
531
532         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
533             // Required sources are all required and provided merged in DeviceSourcesResolver
534             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
535                 if (!qname.getLocalName().equals(identifier.getName())) {
536                     continue;
537                 }
538
539                 if (identifier.getRevision().equals(qname.getRevision())) {
540                     return qname;
541                 }
542             }
543             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
544                     deviceSources.getRequiredSourcesQName());
545             // return null since we cannot find the QName,
546             // this capability will be removed from required sources and not reported as unresolved-capability
547             return null;
548         }
549     }
550 }