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 com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicates;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Sets;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.ListeningExecutorService;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import java.util.Collection;
24 import java.util.LinkedList;
25 import java.util.List;
27 import java.util.concurrent.Callable;
28 import java.util.concurrent.ExecutorService;
29 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
30 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
33 import org.opendaylight.netconf.api.NetconfMessage;
34 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
35 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
36 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
37 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
38 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
39 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
40 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
41 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
42 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
43 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
44 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
45 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
46 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
52 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
53 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
54 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
55 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
56 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
57 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
58 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
59 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
60 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
65 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
67 public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
69 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
71 public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION = new Function<QName, SourceIdentifier>() {
73 public SourceIdentifier apply(final QName input) {
74 return RevisionSourceIdentifier
75 .create(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision()));
79 protected final RemoteDeviceId id;
80 private final boolean reconnectOnSchemasChange;
82 protected final SchemaContextFactory schemaContextFactory;
83 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
84 private final ListeningExecutorService processingExecutor;
85 protected final SchemaSourceRegistry schemaRegistry;
86 private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
87 private final NotificationHandler notificationHandler;
88 protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
90 // Message transformer is constructed once the schemas are available
91 private MessageTransformer<NetconfMessage> messageTransformer;
94 * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
96 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
97 BaseSchema baseSchema = notificationSupport ?
98 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
99 BaseSchema.BASE_NETCONF_CTX;
101 return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
104 protected NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
105 final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
107 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
108 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
109 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
110 this.salFacade = salFacade;
111 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
112 this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
113 this.notificationHandler = new NotificationHandler(salFacade, id);
117 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
118 final NetconfDeviceCommunicator listener) {
119 // SchemaContext setup has to be performed in a dedicated thread since
120 // we are in a netty thread in this method
121 // Yang models are being downloaded in this method and it would cause a
122 // deadlock if we used the netty thread
123 // http://netty.io/wiki/thread-model.html
124 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
126 final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
127 final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
128 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
130 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
131 registerToBaseNetconfStream(initRpc, listener);
134 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
136 public void onSuccess(final DeviceSources result) {
137 addProvidedSourcesToSchemaRegistry(initRpc, result);
141 private void setUpSchema(final DeviceSources result) {
142 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
146 public void onFailure(final Throwable t) {
147 LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
148 handleSalInitializationFailure(t, listener);
152 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
155 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
156 // TODO check whether the model describing create subscription is present in schema
157 // 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)
158 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture =
159 deviceRpc.invokeRpc(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME), NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
161 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
163 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
164 if (isCapabilityChanged(notification)) {
165 LOG.info("{}: Schemas change detected, reconnecting", id);
166 // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
167 listener.disconnect();
168 return Optional.absent();
170 return Optional.of(notification);
173 private boolean isCapabilityChanged(final DOMNotification notification) {
174 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
178 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
180 public void onSuccess(final DOMRpcResult domRpcResult) {
181 notificationHandler.addNotificationFilter(filter);
185 public void onFailure(final Throwable t) {
186 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
191 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
192 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
195 protected void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc) {
196 BaseSchema baseSchema =
197 remoteSessionCapabilities.isNotificationsSupported() ?
198 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
199 BaseSchema.BASE_NETCONF_CTX;
200 messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
202 updateTransformer(messageTransformer);
203 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
204 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
205 notificationHandler.onRemoteSchemaUp(messageTransformer);
207 LOG.info("{}: Netconf connector initialized successfully", id);
210 protected void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
211 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
213 onRemoteSessionDown();
214 resetMessageTransformer();
218 * Set the transformer to null as is in initial state
220 private void resetMessageTransformer() {
221 updateTransformer(null);
224 private void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
225 messageTransformer = transformer;
228 private void addProvidedSourcesToSchemaRegistry(final NetconfDeviceRpc deviceRpc, final DeviceSources deviceSources) {
229 final NetconfRemoteSchemaYangSourceProvider yangProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
230 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
231 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
232 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
237 public void onRemoteSessionDown() {
238 notificationHandler.onRemoteSchemaDown();
240 salFacade.onDeviceDisconnected();
241 for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
242 sourceRegistration.close();
244 resetMessageTransformer();
248 public void onRemoteSessionFailed(final Throwable throwable) {
249 salFacade.onDeviceFailed(throwable);
253 public void onNotification(final NetconfMessage notification) {
254 notificationHandler.handleNotification(notification);
258 * Just a transfer object containing schema related dependencies. Injected in constructor.
260 public static class SchemaResourcesDTO {
261 private final SchemaSourceRegistry schemaRegistry;
262 private final SchemaContextFactory schemaContextFactory;
263 private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
265 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry, final SchemaContextFactory schemaContextFactory, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
266 this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
267 this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
268 this.stateSchemasResolver = Preconditions.checkNotNull(stateSchemasResolver);
271 public SchemaSourceRegistry getSchemaRegistry() {
272 return schemaRegistry;
275 public SchemaContextFactory getSchemaContextFactory() {
276 return schemaContextFactory;
279 public NetconfStateSchemas.NetconfStateSchemasResolver getStateSchemasResolver() {
280 return stateSchemasResolver;
285 * Schema building callable.
287 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
289 private final NetconfDeviceRpc deviceRpc;
290 private final NetconfSessionPreferences remoteSessionCapabilities;
291 private final RemoteDeviceId id;
292 private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
294 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
295 final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
296 this.deviceRpc = deviceRpc;
297 this.remoteSessionCapabilities = remoteSessionCapabilities;
299 this.stateSchemasResolver = stateSchemasResolver;
302 public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
303 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
307 public DeviceSources call() throws Exception {
308 final NetconfStateSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
309 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
311 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
312 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
314 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
315 if (!requiredSourcesNotProvided.isEmpty()) {
316 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
317 id, requiredSourcesNotProvided);
318 LOG.warn("{}: Attempting to build schema context from required sources", id);
321 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
322 // It is necessary to perform this since submodules are not mentioned in hello but still required.
323 // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
324 // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
325 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
326 if (!providedSourcesNotRequired.isEmpty()) {
327 LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
328 id, providedSourcesNotRequired);
329 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
330 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
331 requiredSources.addAll(providedSourcesNotRequired);
334 return new DeviceSources(requiredSources, providedSources);
339 * Contains RequiredSources - sources from capabilities.
341 private static final class DeviceSources {
342 private final Set<QName> requiredSources;
343 private final Set<QName> providedSources;
345 public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources) {
346 this.requiredSources = requiredSources;
347 this.providedSources = providedSources;
350 public Set<QName> getRequiredSourcesQName() {
351 return requiredSources;
354 public Set<QName> getProvidedSourcesQName() {
355 return providedSources;
358 public Collection<SourceIdentifier> getRequiredSources() {
359 return Collections2.transform(requiredSources, QNAME_TO_SOURCE_ID_FUNCTION);
362 public Collection<SourceIdentifier> getProvidedSources() {
363 return Collections2.transform(providedSources, QNAME_TO_SOURCE_ID_FUNCTION);
369 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
371 private final class SchemaSetup implements Runnable {
372 private final DeviceSources deviceSources;
373 private final NetconfSessionPreferences remoteSessionCapabilities;
374 private final RemoteDeviceCommunicator<NetconfMessage> listener;
375 private final NetconfDeviceCapabilities capabilities;
377 public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
378 this.deviceSources = deviceSources;
379 this.remoteSessionCapabilities = remoteSessionCapabilities;
380 this.listener = listener;
381 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
386 setUpSchema(deviceSources.getRequiredSources());
390 * Build schema context, in case of success or final failure notify device
392 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
393 while (!requiredSources.isEmpty()) {
394 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
396 final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
397 final SchemaContext result = schemaBuilderFuture.checkedGet();
398 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
399 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
400 capabilities.addCapabilities(filteredQNames);
401 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps());
402 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
404 } catch (Throwable t) {
405 if (t instanceof MissingSchemaSourceException){
406 requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
407 } else if (t instanceof SchemaResolutionException) {
408 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
409 // that might be wrapping a MissingSchemaSourceException so we need to look
410 // at the cause of the exception to make sure we don't misinterpret it.
411 if (t.getCause() instanceof MissingSchemaSourceException) {
412 requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
415 requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
417 // unknown error, fail
418 handleSalInitializationFailure(t, listener);
423 // No more sources, fail
424 final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
425 handleSalInitializationFailure(cause, listener);
426 salFacade.onDeviceFailed(cause);
429 private Collection<SourceIdentifier> handleMissingSchemaSourceException(Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
430 // In case source missing, try without it
431 final SourceIdentifier missingSource = t.getSourceId();
432 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
433 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
434 final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
435 if (!qNameOfMissingSource.isEmpty()) {
436 capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
438 return stripMissingSource(requiredSources, missingSource);
441 private Collection<SourceIdentifier> handleSchemaResolutionException(Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
442 // In case resolution error, try only with resolved sources
443 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
444 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
445 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
446 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
447 return resolutionException.getResolvedSources();
450 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
451 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
454 private Collection<SourceIdentifier> stripMissingSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
455 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
456 final boolean removed = sourceIdentifiers.remove(sIdToRemove);
457 Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
458 return sourceIdentifiers;
461 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
462 final Collection<QName> qNames = Collections2.transform(identifiers, new Function<SourceIdentifier, QName>() {
464 public QName apply(final SourceIdentifier sourceIdentifier) {
465 return getQNameFromSourceIdentifier(sourceIdentifier);
469 if (qNames.isEmpty()) {
470 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
472 return Collections2.filter(qNames, Predicates.notNull());
475 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
476 // Required sources are all required and provided merged in DeviceSourcesResolver
477 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
478 if(qname.getLocalName().equals(identifier.getName()) == false) {
482 if(identifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) &&
483 qname.getRevision() == null) {
487 if (qname.getFormattedRevision().equals(identifier.getRevision())) {
491 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
492 // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability