2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.connect.netconf;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicates;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Sets;
18 import com.google.common.util.concurrent.CheckedFuture;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.ListeningExecutorService;
23 import com.google.common.util.concurrent.MoreExecutors;
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;
30 import java.util.concurrent.Callable;
31 import java.util.concurrent.ExecutionException;
32 import java.util.stream.Collectors;
33 import javax.annotation.Nonnull;
34 import javax.annotation.concurrent.GuardedBy;
35 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
36 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
38 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
39 import org.opendaylight.netconf.api.NetconfMessage;
40 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
41 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
42 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
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.NetconfRemoteSchemaYangSourceProvider;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
54 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
55 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
56 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
68 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
69 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
70 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
80 public class NetconfDevice
81 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
83 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
85 protected final RemoteDeviceId id;
86 protected final SchemaContextFactory schemaContextFactory;
87 protected final SchemaSourceRegistry schemaRegistry;
88 protected final SchemaRepository schemaRepository;
90 protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
93 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
94 private final ListeningExecutorService processingExecutor;
95 private final DeviceActionFactory deviceActionFactory;
96 private final NetconfDeviceSchemasResolver stateSchemasResolver;
97 private final NotificationHandler notificationHandler;
98 private final boolean reconnectOnSchemasChange;
101 private boolean connected = false;
103 // Message transformer is constructed once the schemas are available
104 private MessageTransformer<NetconfMessage> messageTransformer;
107 * Create rpc implementation capable of handling RPC for monitoring and notifications
108 * even before the schemas of remote device are downloaded.
110 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
111 final boolean notificationSupport) {
112 final BaseSchema baseSchema = notificationSupport
113 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS
114 : BaseSchema.BASE_NETCONF_CTX;
116 return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
117 new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
120 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
121 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
122 final ListeningExecutorService globalProcessingExecutor,
123 final boolean reconnectOnSchemasChange) {
124 this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
127 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
128 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
129 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
130 final DeviceActionFactory deviceActionFactory) {
132 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
133 this.deviceActionFactory = deviceActionFactory;
134 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
135 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
136 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
137 this.salFacade = salFacade;
138 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
139 this.processingExecutor = requireNonNull(globalProcessingExecutor);
140 this.notificationHandler = new NotificationHandler(salFacade, id);
144 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
145 final NetconfDeviceCommunicator listener) {
146 // SchemaContext setup has to be performed in a dedicated thread since
147 // we are in a netty thread in this method
148 // Yang models are being downloaded in this method and it would cause a
149 // deadlock if we used the netty thread
150 // http://netty.io/wiki/thread-model.html
152 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
154 final NetconfDeviceRpc initRpc =
155 getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
156 final DeviceSourcesResolver task =
157 new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
158 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
160 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
161 registerToBaseNetconfStream(initRpc, listener);
164 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
166 public void onSuccess(@Nonnull final DeviceSources result) {
167 addProvidedSourcesToSchemaRegistry(result);
171 private void setUpSchema(final DeviceSources result) {
172 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
176 public void onFailure(final Throwable throwable) {
177 LOG.warn("{}: Unexpected error resolving device sources", id, throwable);
178 handleSalInitializationFailure(throwable, listener);
182 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback, MoreExecutors.directExecutor());
185 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
186 final NetconfDeviceCommunicator listener) {
187 // TODO check whether the model describing create subscription is present in schema
188 // Perhaps add a default schema context to support create-subscription if the model was not provided
189 // (same as what we do for base netconf operations in transformer)
190 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture = deviceRpc.invokeRpc(
191 NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
192 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
194 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
196 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
197 if (isCapabilityChanged(notification)) {
198 LOG.info("{}: Schemas change detected, reconnecting", id);
199 // Only disconnect is enough,
200 // the reconnecting nature of the connector will take care of reconnecting
201 listener.disconnect();
202 return Optional.absent();
204 return Optional.of(notification);
207 private boolean isCapabilityChanged(final DOMNotification notification) {
208 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
212 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
214 public void onSuccess(final DOMRpcResult domRpcResult) {
215 notificationHandler.addNotificationFilter(filter);
219 public void onFailure(final Throwable throwable) {
220 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
223 }, MoreExecutors.directExecutor());
226 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
227 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
230 private synchronized void handleSalInitializationSuccess(final SchemaContext result,
231 final NetconfSessionPreferences remoteSessionCapabilities,
232 final DOMRpcService deviceRpc,
233 final RemoteDeviceCommunicator<NetconfMessage> listener) {
234 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
235 //since salFacade.onDeviceDisconnected was already called.
237 final BaseSchema baseSchema =
238 remoteSessionCapabilities.isNotificationsSupported()
239 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
240 this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
242 updateTransformer(this.messageTransformer);
243 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
244 this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
245 this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
246 this.messageTransformer, listener, result));
247 this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
249 LOG.info("{}: Netconf connector initialized successfully", id);
251 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
255 private void handleSalInitializationFailure(final Throwable throwable,
256 final RemoteDeviceCommunicator<NetconfMessage> listener) {
257 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
259 onRemoteSessionDown();
260 resetMessageTransformer();
264 * Set the transformer to null as is in initial state.
266 private void resetMessageTransformer() {
267 updateTransformer(null);
270 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
271 messageTransformer = transformer;
274 private synchronized void setConnected(final boolean connected) {
275 this.connected = connected;
278 private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
279 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
280 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
281 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
282 PotentialSchemaSource.create(
283 sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
288 public void onRemoteSessionDown() {
290 notificationHandler.onRemoteSchemaDown();
292 salFacade.onDeviceDisconnected();
293 for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
294 : sourceRegistrations) {
295 sourceRegistration.close();
297 resetMessageTransformer();
301 public void onRemoteSessionFailed(final Throwable throwable) {
303 salFacade.onDeviceFailed(throwable);
307 public void onNotification(final NetconfMessage notification) {
308 notificationHandler.handleNotification(notification);
312 * Just a transfer object containing schema related dependencies. Injected in constructor.
314 public static class SchemaResourcesDTO {
315 private final SchemaSourceRegistry schemaRegistry;
316 private final SchemaRepository schemaRepository;
317 private final SchemaContextFactory schemaContextFactory;
318 private final NetconfDeviceSchemasResolver stateSchemasResolver;
320 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
321 final SchemaRepository schemaRepository,
322 final SchemaContextFactory schemaContextFactory,
323 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
324 this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
325 this.schemaRepository = Preconditions.checkNotNull(schemaRepository);
326 this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
327 this.stateSchemasResolver = Preconditions.checkNotNull(deviceSchemasResolver);
330 public SchemaSourceRegistry getSchemaRegistry() {
331 return schemaRegistry;
334 public SchemaRepository getSchemaRepository() {
335 return schemaRepository;
338 public SchemaContextFactory getSchemaContextFactory() {
339 return schemaContextFactory;
342 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
343 return stateSchemasResolver;
348 * Schema building callable.
350 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
352 private final NetconfDeviceRpc deviceRpc;
353 private final NetconfSessionPreferences remoteSessionCapabilities;
354 private final RemoteDeviceId id;
355 private final NetconfDeviceSchemasResolver stateSchemasResolver;
357 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
358 final NetconfSessionPreferences remoteSessionCapabilities,
359 final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
360 this.deviceRpc = deviceRpc;
361 this.remoteSessionCapabilities = remoteSessionCapabilities;
363 this.stateSchemasResolver = stateSchemasResolver;
366 DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
367 final NetconfDeviceSchemasResolver stateSchemasResolver,
368 final NetconfDeviceRpc rpcForMonitoring) {
369 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
373 public DeviceSources call() {
374 final NetconfDeviceSchemas availableSchemas =
375 stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
376 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
377 availableSchemas.getAvailableYangSchemasQNames());
379 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
380 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
382 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
383 if (!requiredSourcesNotProvided.isEmpty()) {
384 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
385 + " required but not provided: {}", id, requiredSourcesNotProvided);
386 LOG.warn("{}: Attempting to build schema context from required sources", id);
389 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
390 // It is necessary to perform this since submodules are not mentioned in hello but still required.
391 // This clashes with the option of a user to specify supported yang models manually in configuration
392 // for netconf-connector and as a result one is not able to fully override yang models of a device.
393 // It is only possible to add additional models.
394 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
395 if (!providedSourcesNotRequired.isEmpty()) {
396 LOG.warn("{}: Netconf device provides additional yang models not reported in "
397 + "hello message capabilities: {}", id, providedSourcesNotRequired);
398 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
399 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
400 requiredSources.addAll(providedSourcesNotRequired);
403 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
404 if (availableSchemas instanceof LibraryModulesSchemas) {
405 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
406 ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
408 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
411 return new DeviceSources(requiredSources, providedSources, sourceProvider);
416 * Contains RequiredSources - sources from capabilities.
418 private static final class DeviceSources {
419 private final Set<QName> requiredSources;
420 private final Set<QName> providedSources;
421 private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
423 DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
424 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
425 this.requiredSources = requiredSources;
426 this.providedSources = providedSources;
427 this.sourceProvider = sourceProvider;
430 public Set<QName> getRequiredSourcesQName() {
431 return requiredSources;
434 public Set<QName> getProvidedSourcesQName() {
435 return providedSources;
438 public Collection<SourceIdentifier> getRequiredSources() {
439 return Collections2.transform(requiredSources, DeviceSources::toSourceId);
442 public Collection<SourceIdentifier> getProvidedSources() {
443 return Collections2.transform(providedSources, DeviceSources::toSourceId);
446 public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
447 return sourceProvider;
450 private static SourceIdentifier toSourceId(final QName input) {
451 return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
456 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
458 private final class SchemaSetup implements Runnable {
459 private final DeviceSources deviceSources;
460 private final NetconfSessionPreferences remoteSessionCapabilities;
461 private final RemoteDeviceCommunicator<NetconfMessage> listener;
462 private final NetconfDeviceCapabilities capabilities;
464 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
465 final RemoteDeviceCommunicator<NetconfMessage> listener) {
466 this.deviceSources = deviceSources;
467 this.remoteSessionCapabilities = remoteSessionCapabilities;
468 this.listener = listener;
469 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
475 final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
476 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
478 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
479 UnavailableCapability.FailureReason.MissingSource);
481 requiredSources.removeAll(missingSources);
482 setUpSchema(requiredSources);
485 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
486 return requiredSources.parallelStream().filter(sourceIdentifier -> {
488 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
490 } catch (InterruptedException | ExecutionException e) {
493 }).collect(Collectors.toList());
497 * Build schema context, in case of success or final failure notify device.
499 * @param requiredSources required sources
501 @SuppressWarnings("checkstyle:IllegalCatch")
502 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
503 while (!requiredSources.isEmpty()) {
504 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
506 final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
507 .createSchemaContext(requiredSources);
508 final SchemaContext result = schemaBuilderFuture.get();
509 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
510 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
511 capabilities.getUnresolvedCapabilites().keySet());
512 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
513 .setCapability(entry.toString()).setCapabilityOrigin(
514 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
515 .collect(Collectors.toList()));
517 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
518 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
519 .setCapability(entry).setCapabilityOrigin(
520 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
521 .collect(Collectors.toList()));
523 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result),
526 } catch (final ExecutionException e) {
527 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
528 // that might be wrapping a MissingSchemaSourceException so we need to look
529 // at the cause of the exception to make sure we don't misinterpret it.
530 final Throwable cause = e.getCause();
532 if (cause instanceof MissingSchemaSourceException) {
533 requiredSources = handleMissingSchemaSourceException(
534 requiredSources, (MissingSchemaSourceException) cause);
537 if (cause instanceof SchemaResolutionException) {
538 requiredSources = handleSchemaResolutionException(requiredSources,
539 (SchemaResolutionException) cause);
541 handleSalInitializationFailure(e, listener);
544 } catch (final Exception e) {
545 // unknown error, fail
546 handleSalInitializationFailure(e, listener);
550 // No more sources, fail
551 final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
552 handleSalInitializationFailure(cause, listener);
553 salFacade.onDeviceFailed(cause);
556 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
557 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
558 // In case source missing, try without it
559 final SourceIdentifier missingSource = exception.getSourceId();
560 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
562 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
563 id, missingSource, exception);
564 final Collection<QName> qNameOfMissingSource =
565 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
566 if (!qNameOfMissingSource.isEmpty()) {
567 capabilities.addUnresolvedCapabilities(
568 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
570 return stripUnavailableSource(requiredSources, missingSource);
573 private Collection<SourceIdentifier> handleSchemaResolutionException(
574 final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
575 // In case resolution error, try only with resolved sources
576 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
577 // FIXME Do we really have assurance that these two cases cannot happen at once?
578 if (resolutionException.getFailedSource() != null) {
579 // flawed model - exclude it
580 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
581 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
583 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
584 id, failedSourceId, resolutionException);
585 capabilities.addUnresolvedCapabilities(
586 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
587 UnavailableCapability.FailureReason.UnableToResolve);
588 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
590 // unsatisfied imports
591 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
592 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
593 UnavailableCapability.FailureReason.UnableToResolve);
594 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
595 id, resolutionException.getUnsatisfiedImports());
596 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
597 id, resolutionException.getUnsatisfiedImports(), resolutionException);
598 return resolutionException.getResolvedSources();
601 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
602 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
605 private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
606 final SourceIdentifier sourceIdToRemove) {
607 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
608 final boolean removed = sourceIdentifiers.remove(sourceIdToRemove);
609 Preconditions.checkState(
610 removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources);
611 return sourceIdentifiers;
614 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
615 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
617 if (qNames.isEmpty()) {
618 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
621 return Collections2.filter(qNames, Predicates.notNull());
624 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
625 // Required sources are all required and provided merged in DeviceSourcesResolver
626 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
627 if (!qname.getLocalName().equals(identifier.getName())) {
631 if (identifier.getRevision().equals(qname.getRevision())) {
635 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
636 deviceSources.getRequiredSourcesQName());
637 // return null since we cannot find the QName,
638 // this capability will be removed from required sources and not reported as unresolved-capability