X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=blobdiff_plain;f=netconf%2Fsal-netconf-connector%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fnetconf%2Fsal%2Fconnect%2Fnetconf%2FNetconfDevice.java;h=a6865ba6dd07465b75c91fafb3dffe554033cf26;hb=01e6f6d0f907f710db3a1606ee0632cf8eb28476;hp=cc6e666980a1cf34dcfbb0f96735e612327ec379;hpb=5bbd9ee74e63dc809a764825fd4f14f5ae83925b;p=netconf.git diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java index cc6e666980..a6865ba6dd 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java @@ -7,31 +7,41 @@ */ package org.opendaylight.netconf.sal.connect.netconf; -import com.google.common.base.Function; -import com.google.common.base.Optional; +import static java.util.Objects.requireNonNull; + import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.util.concurrent.FluentFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import io.netty.util.concurrent.EventExecutor; +import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.LinkedList; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import org.opendaylight.controller.md.sal.dom.api.DOMNotification; -import org.opendaylight.controller.md.sal.dom.api.DOMRpcException; -import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; -import org.opendaylight.controller.md.sal.dom.api.DOMRpcService; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import javax.annotation.concurrent.GuardedBy; +import org.opendaylight.mdsal.dom.api.DOMNotification; +import org.opendaylight.mdsal.dom.api.DOMRpcResult; +import org.opendaylight.mdsal.dom.api.DOMRpcService; import org.opendaylight.netconf.api.NetconfMessage; +import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory; import org.opendaylight.netconf.sal.connect.api.MessageTransformer; +import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas; +import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver; import org.opendaylight.netconf.sal.connect.api.RemoteDevice; import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator; import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler; @@ -40,73 +50,102 @@ import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommun import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences; import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc; import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider; +import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider; +import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema; import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer; import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException; +import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory; +import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource; +import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade + * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade. */ -public class NetconfDevice implements RemoteDevice { +public class NetconfDevice + implements RemoteDevice { private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class); - public static final Function QNAME_TO_SOURCE_ID_FUNCTION = new Function() { - @Override - public SourceIdentifier apply(final QName input) { - return new SourceIdentifier(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision())); - } - }; - protected final RemoteDeviceId id; - private final boolean reconnectOnSchemasChange; - protected final SchemaContextFactory schemaContextFactory; + protected final SchemaSourceRegistry schemaRegistry; + protected final SchemaRepository schemaRepository; + + protected final List> sourceRegistrations = new ArrayList<>(); + private final RemoteDeviceHandler salFacade; private final ListeningExecutorService processingExecutor; - protected final SchemaSourceRegistry schemaRegistry; - private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver; + private final DeviceActionFactory deviceActionFactory; + private final NetconfDeviceSchemasResolver stateSchemasResolver; private final NotificationHandler notificationHandler; - protected final List> sourceRegistrations = Lists.newArrayList(); + private final boolean reconnectOnSchemasChange; + private final NetconfNode node; + private final EventExecutor eventExecutor; + private final NetconfNodeAugmentedOptional nodeOptional; + + @GuardedBy("this") + private boolean connected = false; // Message transformer is constructed once the schemas are available private MessageTransformer messageTransformer; /** - * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded + * Create rpc implementation capable of handling RPC for monitoring and notifications + * even before the schemas of remote device are downloaded. */ - static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) { - NetconfMessageTransformer.BaseSchema baseSchema = notificationSupport ? - NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : - NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX; + static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, + final boolean notificationSupport) { + final BaseSchema baseSchema = notificationSupport + ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS + : BaseSchema.BASE_NETCONF_CTX; + + return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, + new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema)); + } - return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema)); + public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, + final RemoteDeviceHandler salFacade, + final ListeningExecutorService globalProcessingExecutor, + final boolean reconnectOnSchemasChange) { + this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null, null, null, + null); } - protected NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler salFacade, - final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) { + public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, + final RemoteDeviceHandler salFacade, + final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange, + final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor, + final NetconfNodeAugmentedOptional nodeOptional) { this.id = id; this.reconnectOnSchemasChange = reconnectOnSchemasChange; + this.deviceActionFactory = deviceActionFactory; + this.node = node; + this.eventExecutor = eventExecutor; + this.nodeOptional = nodeOptional; this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry(); + this.schemaRepository = schemaResourcesDTO.getSchemaRepository(); this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory(); this.salFacade = salFacade; this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver(); - this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor); + this.processingExecutor = requireNonNull(globalProcessingExecutor); this.notificationHandler = new NotificationHandler(salFacade, id); } @@ -118,10 +157,13 @@ public class NetconfDevice implements RemoteDevice sourceResolverFuture = processingExecutor.submit(task); if (shouldListenOnSchemaChange(remoteSessionCapabilities)) { @@ -130,8 +172,8 @@ public class NetconfDevice implements RemoteDevice resolvedSourceCallback = new FutureCallback() { @Override - public void onSuccess(final DeviceSources result) { - addProvidedSourcesToSchemaRegistry(initRpc, result); + public void onSuccess(@Nonnull final DeviceSources result) { + addProvidedSourcesToSchemaRegistry(result); setUpSchema(result); } @@ -140,29 +182,33 @@ public class NetconfDevice implements RemoteDevice rpcResultListenableFuture = - deviceRpc.invokeRpc(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME), NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT); + private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, + final NetconfDeviceCommunicator listener) { + // TODO check whether the model describing create subscription is present in schema + // Perhaps add a default schema context to support create-subscription if the model was not provided + // (same as what we do for base netconf operations in transformer) + final FluentFuture rpcResultListenableFuture = deviceRpc.invokeRpc( + NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME), + NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT); final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() { @Override public Optional filterNotification(final DOMNotification notification) { if (isCapabilityChanged(notification)) { LOG.info("{}: Schemas change detected, reconnecting", id); - // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting + // Only disconnect is enough, + // the reconnecting nature of the connector will take care of reconnecting listener.disconnect(); - return Optional.absent(); + return Optional.empty(); } return Optional.of(notification); } @@ -179,70 +225,88 @@ public class NetconfDevice implements RemoteDevice listener) { + //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing, + //since salFacade.onDeviceDisconnected was already called. + if (connected) { + final BaseSchema baseSchema = + remoteSessionCapabilities.isNotificationsSupported() + ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX; + this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema); + + updateTransformer(this.messageTransformer); + // salFacade.onDeviceConnected has to be called before the notification handler is initialized + this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc, + this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction( + this.messageTransformer, listener, result)); + this.notificationHandler.onRemoteSchemaUp(this.messageTransformer); + + LOG.info("{}: Netconf connector initialized successfully", id); + } else { + LOG.warn("{}: Device communicator was closed before schema setup finished.", id); + } } - protected void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator listener) { - LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t); + private void handleSalInitializationFailure(final Throwable throwable, + final RemoteDeviceCommunicator listener) { + LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable); listener.close(); onRemoteSessionDown(); resetMessageTransformer(); } /** - * Set the transformer to null as is in initial state + * Set the transformer to null as is in initial state. */ private void resetMessageTransformer() { updateTransformer(null); } - private void updateTransformer(final MessageTransformer transformer) { + private synchronized void updateTransformer(final MessageTransformer transformer) { messageTransformer = transformer; } - private void addProvidedSourcesToSchemaRegistry(final NetconfDeviceRpc deviceRpc, final DeviceSources deviceSources) { - final NetconfRemoteSchemaYangSourceProvider yangProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc); + private synchronized void setConnected(final boolean connected) { + this.connected = connected; + } + + private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) { + final SchemaSourceProvider yangProvider = deviceSources.getSourceProvider(); for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) { sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider, - PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue()))); + PotentialSchemaSource.create( + sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue()))); } } @Override public void onRemoteSessionDown() { + setConnected(false); notificationHandler.onRemoteSchemaDown(); salFacade.onDeviceDisconnected(); - for (final SchemaSourceRegistration sourceRegistration : sourceRegistrations) { - sourceRegistration.close(); - } + sourceRegistrations.forEach(SchemaSourceRegistration::close); + sourceRegistrations.clear(); resetMessageTransformer(); } @Override public void onRemoteSessionFailed(final Throwable throwable) { + setConnected(false); salFacade.onDeviceFailed(throwable); } @@ -256,24 +320,33 @@ public class NetconfDevice implements RemoteDevice requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps()); final Set providedSources = availableSchemas.getAvailableYangSchemasQNames(); final Set requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources); if (!requiredSourcesNotProvided.isEmpty()) { - LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}", - id, requiredSourcesNotProvided); + LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities," + + " required but not provided: {}", id, requiredSourcesNotProvided); LOG.warn("{}: Attempting to build schema context from required sources", id); } // Here all the sources reported in netconf monitoring are merged with those reported in hello. // It is necessary to perform this since submodules are not mentioned in hello but still required. - // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector - // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models. + // This clashes with the option of a user to specify supported yang models manually in configuration + // for netconf-connector and as a result one is not able to fully override yang models of a device. + // It is only possible to add additional models. final Set providedSourcesNotRequired = Sets.difference(providedSources, requiredSources); if (!providedSourcesNotRequired.isEmpty()) { - LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}", - id, providedSourcesNotRequired); + LOG.warn("{}: Netconf device provides additional yang models not reported in " + + "hello message capabilities: {}", id, providedSourcesNotRequired); LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id); LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources); requiredSources.addAll(providedSourcesNotRequired); } - return new DeviceSources(requiredSources, providedSources); + final SchemaSourceProvider sourceProvider; + if (availableSchemas instanceof LibraryModulesSchemas) { + sourceProvider = new YangLibrarySchemaYangSourceProvider(id, + ((LibraryModulesSchemas) availableSchemas).getAvailableModels()); + } else { + sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc); + } + + return new DeviceSources(requiredSources, providedSources, sourceProvider); } } @@ -338,10 +425,13 @@ public class NetconfDevice implements RemoteDevice requiredSources; private final Set providedSources; + private final SchemaSourceProvider sourceProvider; - public DeviceSources(final Set requiredSources, final Set providedSources) { + DeviceSources(final Set requiredSources, final Set providedSources, + final SchemaSourceProvider sourceProvider) { this.requiredSources = requiredSources; this.providedSources = providedSources; + this.sourceProvider = sourceProvider; } public Set getRequiredSourcesQName() { @@ -353,13 +443,20 @@ public class NetconfDevice implements RemoteDevice getRequiredSources() { - return Collections2.transform(requiredSources, QNAME_TO_SOURCE_ID_FUNCTION); + return Collections2.transform(requiredSources, DeviceSources::toSourceId); } public Collection getProvidedSources() { - return Collections2.transform(providedSources, QNAME_TO_SOURCE_ID_FUNCTION); + return Collections2.transform(providedSources, DeviceSources::toSourceId); } + public SchemaSourceProvider getSourceProvider() { + return sourceProvider; + } + + private static SourceIdentifier toSourceId(final QName input) { + return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision()); + } } /** @@ -371,7 +468,8 @@ public class NetconfDevice implements RemoteDevice listener; private final NetconfDeviceCapabilities capabilities; - public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator listener) { + SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, + final RemoteDeviceCommunicator listener) { this.deviceSources = deviceSources; this.remoteSessionCapabilities = remoteSessionCapabilities; this.listener = listener; @@ -380,68 +478,141 @@ public class NetconfDevice implements RemoteDevice requiredSources = deviceSources.getRequiredSources(); + final Collection missingSources = filterMissingSources(requiredSources); + + capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources), + UnavailableCapability.FailureReason.MissingSource); + + requiredSources.removeAll(missingSources); + setUpSchema(requiredSources); + } + + private Collection filterMissingSources(final Collection requiredSources) { + return requiredSources.parallelStream().filter(sourceIdentifier -> { + try { + schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get(); + return false; + } catch (InterruptedException | ExecutionException e) { + return true; + } + }).collect(Collectors.toList()); } /** - * Build schema context, in case of success or final failure notify device + * Build schema context, in case of success or final failure notify device. + * + * @param requiredSources required sources */ + @SuppressWarnings("checkstyle:IllegalCatch") private void setUpSchema(Collection requiredSources) { while (!requiredSources.isEmpty()) { LOG.trace("{}: Trying to build schema context from {}", id, requiredSources); try { - final CheckedFuture schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources); - final SchemaContext result = schemaBuilderFuture.checkedGet(); + final ListenableFuture schemaBuilderFuture = schemaContextFactory + .createSchemaContext(requiredSources); + final SchemaContext result = schemaBuilderFuture.get(); LOG.debug("{}: Schema context built successfully from {}", id, requiredSources); - final Collection filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet()); - capabilities.addCapabilities(filteredQNames); - capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps()); - handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result)); + final Collection filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), + capabilities.getUnresolvedCapabilites().keySet()); + capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder() + .setCapability(entry.toString()).setCapabilityOrigin( + remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build()) + .collect(Collectors.toList())); + + capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities + .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder() + .setCapability(entry).setCapabilityOrigin( + remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build()) + .collect(Collectors.toList())); + + handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result), + listener); return; - } catch (Throwable t) { - if (t instanceof MissingSchemaSourceException){ - requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t); - } else if (t instanceof SchemaResolutionException) { - // FIXME do not wrap MissingSchemaSourceException in a - // SchemaResolutionException. Somewhere this exception - // is wrapped thus the instanceod isn't seeing the root - // the cause of the exception. - if (t.getCause() instanceof MissingSchemaSourceException) { - requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause()); - continue; - } - requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t); + } catch (final ExecutionException e) { + // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException + // that might be wrapping a MissingSchemaSourceException so we need to look + // at the cause of the exception to make sure we don't misinterpret it. + final Throwable cause = e.getCause(); + + if (cause instanceof MissingSchemaSourceException) { + requiredSources = handleMissingSchemaSourceException( + requiredSources, (MissingSchemaSourceException) cause); + continue; + } + if (cause instanceof SchemaResolutionException) { + requiredSources = handleSchemaResolutionException(requiredSources, + (SchemaResolutionException) cause); } else { - // unknown error, fail - handleSalInitializationFailure(t, listener); + handleSalInitializationFailure(e, listener); return; } + } catch (final Exception e) { + // unknown error, fail + handleSalInitializationFailure(e, listener); + return; } } - // No more sources, fail - final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context"); - handleSalInitializationFailure(cause, listener); - salFacade.onDeviceFailed(cause); + // No more sources, fail or try to reconnect + if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().isAllowed()) { + eventExecutor.schedule(() -> { + LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime."); + LOG.warn("{} : No more sources for schema context.", id); + LOG.info("{} : Try to remount device.", id); + onRemoteSessionDown(); + salFacade.onDeviceReconnected(remoteSessionCapabilities, node); + }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime(), TimeUnit.MILLISECONDS); + } else { + final IllegalStateException cause = + new IllegalStateException(id + ": No more sources for schema context"); + handleSalInitializationFailure(cause, listener); + salFacade.onDeviceFailed(cause); + } } - private Collection handleMissingSchemaSourceException(Collection requiredSources, final MissingSchemaSourceException t) { + private Collection handleMissingSchemaSourceException( + final Collection requiredSources, final MissingSchemaSourceException exception) { // In case source missing, try without it - final SourceIdentifier missingSource = t.getSourceId(); - LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource); - LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t); - final Collection qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource)); + final SourceIdentifier missingSource = exception.getSourceId(); + LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", + id, missingSource); + LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", + id, missingSource, exception); + final Collection qNameOfMissingSource = + getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource)); if (!qNameOfMissingSource.isEmpty()) { - capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource); + capabilities.addUnresolvedCapabilities( + qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource); } - return stripMissingSource(requiredSources, missingSource); + return stripUnavailableSource(requiredSources, missingSource); } - private Collection handleSchemaResolutionException(Collection requiredSources, final SchemaResolutionException resolutionException) { + private Collection handleSchemaResolutionException( + final Collection requiredSources, final SchemaResolutionException resolutionException) { // In case resolution error, try only with resolved sources + // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model + // FIXME Do we really have assurance that these two cases cannot happen at once? + if (resolutionException.getFailedSource() != null) { + // flawed model - exclude it + final SourceIdentifier failedSourceId = resolutionException.getFailedSource(); + LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", + id, failedSourceId); + LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", + id, failedSourceId, resolutionException); + capabilities.addUnresolvedCapabilities( + getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)), + UnavailableCapability.FailureReason.UnableToResolve); + return stripUnavailableSource(requiredSources, resolutionException.getFailedSource()); + } + // unsatisfied imports final Set unresolvedSources = resolutionException.getUnsatisfiedImports().keySet(); - capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve); - LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports()); - LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException); + capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), + UnavailableCapability.FailureReason.UnableToResolve); + LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", + id, resolutionException.getUnsatisfiedImports()); + LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", + id, resolutionException.getUnsatisfiedImports(), resolutionException); return resolutionException.getResolvedSources(); } @@ -449,23 +620,21 @@ public class NetconfDevice implements RemoteDevice stripMissingSource(final Collection requiredSources, final SourceIdentifier sIdToRemove) { + private Collection stripUnavailableSource(final Collection requiredSources, + final SourceIdentifier sourceIdToRemove) { final LinkedList sourceIdentifiers = Lists.newLinkedList(requiredSources); - final boolean removed = sourceIdentifiers.remove(sIdToRemove); - Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources); + final boolean removed = sourceIdentifiers.remove(sourceIdToRemove); + Preconditions.checkState( + removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources); return sourceIdentifiers; } private Collection getQNameFromSourceIdentifiers(final Collection identifiers) { - final Collection qNames = Collections2.transform(identifiers, new Function() { - @Override - public QName apply(final SourceIdentifier sourceIdentifier) { - return getQNameFromSourceIdentifier(sourceIdentifier); - } - }); + final Collection qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier); if (qNames.isEmpty()) { - LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers); + LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, + identifiers); } return Collections2.filter(qNames, Predicates.notNull()); } @@ -473,21 +642,18 @@ public class NetconfDevice implements RemoteDevice