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.NetconfMessageTransformer;
44 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
45 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
51 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
52 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
53 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
54 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
55 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
56 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
57 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
58 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
65 public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
67 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
69 public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION = new Function<QName, SourceIdentifier>() {
71 public SourceIdentifier apply(final QName input) {
72 return new SourceIdentifier(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision()));
76 protected final RemoteDeviceId id;
77 private final boolean reconnectOnSchemasChange;
79 protected final SchemaContextFactory schemaContextFactory;
80 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
81 private final ListeningExecutorService processingExecutor;
82 protected final SchemaSourceRegistry schemaRegistry;
83 private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
84 private final NotificationHandler notificationHandler;
85 protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
87 // Message transformer is constructed once the schemas are available
88 private MessageTransformer<NetconfMessage> messageTransformer;
91 * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
93 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
94 NetconfMessageTransformer.BaseSchema baseSchema = notificationSupport ?
95 NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
96 NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX;
98 return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
101 protected NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
102 final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
104 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
105 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
106 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
107 this.salFacade = salFacade;
108 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
109 this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
110 this.notificationHandler = new NotificationHandler(salFacade, id);
114 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
115 final NetconfDeviceCommunicator listener) {
116 // SchemaContext setup has to be performed in a dedicated thread since
117 // we are in a netty thread in this method
118 // Yang models are being downloaded in this method and it would cause a
119 // deadlock if we used the netty thread
120 // http://netty.io/wiki/thread-model.html
121 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
123 final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
124 final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
125 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
127 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
128 registerToBaseNetconfStream(initRpc, listener);
131 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
133 public void onSuccess(final DeviceSources result) {
134 addProvidedSourcesToSchemaRegistry(initRpc, result);
138 private void setUpSchema(final DeviceSources result) {
139 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
143 public void onFailure(final Throwable t) {
144 LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
145 handleSalInitializationFailure(t, listener);
149 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
152 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
153 // TODO check whether the model describing create subscription is present in schema
154 // 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)
155 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture =
156 deviceRpc.invokeRpc(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME), NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
158 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
160 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
161 if (isCapabilityChanged(notification)) {
162 LOG.info("{}: Schemas change detected, reconnecting", id);
163 // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
164 listener.disconnect();
165 return Optional.absent();
167 return Optional.of(notification);
170 private boolean isCapabilityChanged(final DOMNotification notification) {
171 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
175 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
177 public void onSuccess(final DOMRpcResult domRpcResult) {
178 notificationHandler.addNotificationFilter(filter);
182 public void onFailure(final Throwable t) {
183 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
188 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
189 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
192 protected void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc) {
193 NetconfMessageTransformer.BaseSchema baseSchema =
194 remoteSessionCapabilities.isNotificationsSupported() ?
195 NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
196 NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX;
197 messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
199 updateTransformer(messageTransformer);
200 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
201 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
202 notificationHandler.onRemoteSchemaUp(messageTransformer);
204 LOG.info("{}: Netconf connector initialized successfully", id);
207 protected void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
208 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
210 onRemoteSessionDown();
211 resetMessageTransformer();
215 * Set the transformer to null as is in initial state
217 private void resetMessageTransformer() {
218 updateTransformer(null);
221 private void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
222 messageTransformer = transformer;
225 private void addProvidedSourcesToSchemaRegistry(final NetconfDeviceRpc deviceRpc, final DeviceSources deviceSources) {
226 final NetconfRemoteSchemaYangSourceProvider yangProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
227 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
228 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
229 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
234 public void onRemoteSessionDown() {
235 notificationHandler.onRemoteSchemaDown();
237 salFacade.onDeviceDisconnected();
238 for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
239 sourceRegistration.close();
241 resetMessageTransformer();
245 public void onRemoteSessionFailed(final Throwable throwable) {
246 salFacade.onDeviceFailed(throwable);
250 public void onNotification(final NetconfMessage notification) {
251 notificationHandler.handleNotification(notification);
255 * Just a transfer object containing schema related dependencies. Injected in constructor.
257 public static class SchemaResourcesDTO {
258 private final SchemaSourceRegistry schemaRegistry;
259 private final SchemaContextFactory schemaContextFactory;
260 private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
262 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry, final SchemaContextFactory schemaContextFactory, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
263 this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
264 this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
265 this.stateSchemasResolver = Preconditions.checkNotNull(stateSchemasResolver);
268 public SchemaSourceRegistry getSchemaRegistry() {
269 return schemaRegistry;
272 public SchemaContextFactory getSchemaContextFactory() {
273 return schemaContextFactory;
276 public NetconfStateSchemas.NetconfStateSchemasResolver getStateSchemasResolver() {
277 return stateSchemasResolver;
282 * Schema building callable.
284 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
286 private final NetconfDeviceRpc deviceRpc;
287 private final NetconfSessionPreferences remoteSessionCapabilities;
288 private final RemoteDeviceId id;
289 private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
291 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
292 final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
293 this.deviceRpc = deviceRpc;
294 this.remoteSessionCapabilities = remoteSessionCapabilities;
296 this.stateSchemasResolver = stateSchemasResolver;
299 public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
300 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
304 public DeviceSources call() throws Exception {
305 final NetconfStateSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
306 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
308 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
309 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
311 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
312 if (!requiredSourcesNotProvided.isEmpty()) {
313 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
314 id, requiredSourcesNotProvided);
315 LOG.warn("{}: Attempting to build schema context from required sources", id);
318 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
319 // It is necessary to perform this since submodules are not mentioned in hello but still required.
320 // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
321 // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
322 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
323 if (!providedSourcesNotRequired.isEmpty()) {
324 LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
325 id, providedSourcesNotRequired);
326 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
327 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
328 requiredSources.addAll(providedSourcesNotRequired);
331 return new DeviceSources(requiredSources, providedSources);
336 * Contains RequiredSources - sources from capabilities.
338 private static final class DeviceSources {
339 private final Set<QName> requiredSources;
340 private final Set<QName> providedSources;
342 public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources) {
343 this.requiredSources = requiredSources;
344 this.providedSources = providedSources;
347 public Set<QName> getRequiredSourcesQName() {
348 return requiredSources;
351 public Set<QName> getProvidedSourcesQName() {
352 return providedSources;
355 public Collection<SourceIdentifier> getRequiredSources() {
356 return Collections2.transform(requiredSources, QNAME_TO_SOURCE_ID_FUNCTION);
359 public Collection<SourceIdentifier> getProvidedSources() {
360 return Collections2.transform(providedSources, QNAME_TO_SOURCE_ID_FUNCTION);
366 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
368 private final class SchemaSetup implements Runnable {
369 private final DeviceSources deviceSources;
370 private final NetconfSessionPreferences remoteSessionCapabilities;
371 private final RemoteDeviceCommunicator<NetconfMessage> listener;
372 private final NetconfDeviceCapabilities capabilities;
374 public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
375 this.deviceSources = deviceSources;
376 this.remoteSessionCapabilities = remoteSessionCapabilities;
377 this.listener = listener;
378 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
383 setUpSchema(deviceSources.getRequiredSources());
387 * Build schema context, in case of success or final failure notify device
389 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
390 while (!requiredSources.isEmpty()) {
391 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
393 final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
394 final SchemaContext result = schemaBuilderFuture.checkedGet();
395 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
396 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
397 capabilities.addCapabilities(filteredQNames);
398 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps());
399 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
401 } catch (Throwable t) {
402 if (t instanceof MissingSchemaSourceException){
403 requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
404 } else if (t instanceof SchemaResolutionException) {
405 // FIXME do not wrap MissingSchemaSourceException in a
406 // SchemaResolutionException. Somewhere this exception
407 // is wrapped thus the instanceod isn't seeing the root
408 // the cause of the exception.
409 if (t.getCause() instanceof MissingSchemaSourceException) {
410 requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
413 requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
415 // unknown error, fail
416 handleSalInitializationFailure(t, listener);
421 // No more sources, fail
422 final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
423 handleSalInitializationFailure(cause, listener);
424 salFacade.onDeviceFailed(cause);
427 private Collection<SourceIdentifier> handleMissingSchemaSourceException(Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
428 // In case source missing, try without it
429 final SourceIdentifier missingSource = t.getSourceId();
430 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
431 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
432 final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
433 if (!qNameOfMissingSource.isEmpty()) {
434 capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
436 return stripMissingSource(requiredSources, missingSource);
439 private Collection<SourceIdentifier> handleSchemaResolutionException(Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
440 // In case resolution error, try only with resolved sources
441 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
442 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
443 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
444 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
445 return resolutionException.getResolvedSources();
448 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
449 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
452 private Collection<SourceIdentifier> stripMissingSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
453 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
454 final boolean removed = sourceIdentifiers.remove(sIdToRemove);
455 Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
456 return sourceIdentifiers;
459 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
460 final Collection<QName> qNames = Collections2.transform(identifiers, new Function<SourceIdentifier, QName>() {
462 public QName apply(final SourceIdentifier sourceIdentifier) {
463 return getQNameFromSourceIdentifier(sourceIdentifier);
467 if (qNames.isEmpty()) {
468 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
470 return Collections2.filter(qNames, Predicates.notNull());
473 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
474 // Required sources are all required and provided merged in DeviceSourcesResolver
475 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
476 if(qname.getLocalName().equals(identifier.getName()) == false) {
480 if(identifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) &&
481 qname.getRevision() == null) {
485 if (qname.getFormattedRevision().equals(identifier.getRevision())) {
489 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
490 // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability