31779a78172b5fa5e2b5706f35e4857c3e40edb3
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / NetconfDevice.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.sal.connect.netconf;
9
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.collect.Collections2;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Sets;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.ListeningExecutorService;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.util.Collection;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.concurrent.Callable;
27 import java.util.concurrent.ExecutorService;
28 import org.opendaylight.controller.netconf.api.NetconfMessage;
29 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
30 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
31 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
32 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
33 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
34 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc;
35 import org.opendaylight.controller.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
36 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
41 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
42 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
43 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
44 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
45 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
46 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
47 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
53  */
54 public final class NetconfDevice implements RemoteDevice<NetconfSessionCapabilities, NetconfMessage> {
55
56     private static final Logger logger = LoggerFactory.getLogger(NetconfDevice.class);
57
58     public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION = new Function<QName, SourceIdentifier>() {
59         @Override
60         public SourceIdentifier apply(final QName input) {
61             return new SourceIdentifier(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision()));
62         }
63     };
64
65     private final RemoteDeviceId id;
66
67     private final SchemaContextFactory schemaContextFactory;
68     private final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade;
69     private final ListeningExecutorService processingExecutor;
70     private final SchemaSourceRegistry schemaRegistry;
71     private final MessageTransformer<NetconfMessage> messageTransformer;
72     private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
73     private final NotificationHandler notificationHandler;
74     private final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
75
76     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade,
77                          final ExecutorService globalProcessingExecutor, final MessageTransformer<NetconfMessage> messageTransformer) {
78         this.id = id;
79         this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
80         this.messageTransformer = messageTransformer;
81         this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
82         this.salFacade = salFacade;
83         this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
84         this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
85         this.notificationHandler = new NotificationHandler(salFacade, messageTransformer, id);
86     }
87
88     @Override
89     public void onRemoteSessionUp(final NetconfSessionCapabilities remoteSessionCapabilities,
90                                   final RemoteDeviceCommunicator<NetconfMessage> listener) {
91         // SchemaContext setup has to be performed in a dedicated thread since
92         // we are in a netty thread in this method
93         // Yang models are being downloaded in this method and it would cause a
94         // deadlock if we used the netty thread
95         // http://netty.io/wiki/thread-model.html
96         logger.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
97
98         final NetconfDeviceRpc deviceRpc = setUpDeviceRpc(listener);
99
100         final DeviceSourcesResolver task = new DeviceSourcesResolver(deviceRpc, remoteSessionCapabilities, id, stateSchemasResolver);
101         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
102
103         final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
104             @Override
105             public void onSuccess(final DeviceSources result) {
106                 addProvidedSourcesToSchemaRegistry(deviceRpc, result);
107                 setUpSchema(result);
108             }
109
110             private void setUpSchema(final DeviceSources result) {
111                 processingExecutor.submit(new RecursiveSchemaSetup(result, remoteSessionCapabilities, deviceRpc, listener));
112             }
113
114             @Override
115             public void onFailure(final Throwable t) {
116                 logger.warn("{}: Unexpected error resolving device sources: {}", id, t);
117                 handleSalInitializationFailure(t, listener);
118             }
119         };
120
121         Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
122     }
123
124     private void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionCapabilities remoteSessionCapabilities, final NetconfDeviceRpc deviceRpc) {
125         updateMessageTransformer(result);
126         salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
127         notificationHandler.onRemoteSchemaUp();
128
129         logger.debug("{}: Initialization in sal successful", id);
130         logger.info("{}: Netconf connector initialized successfully", id);
131     }
132
133     private void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
134         logger.error("{}: Initialization in sal failed, disconnecting from device", id, t);
135         listener.close();
136         onRemoteSessionDown();
137         resetMessageTransformer();
138     }
139
140     /**
141      * Set the schema context inside transformer to null as is in initial state
142      */
143     private void resetMessageTransformer() {
144         updateMessageTransformer(null);
145     }
146
147     /**
148      * Update initial message transformer to use retrieved schema
149      * @param currentSchemaContext
150      */
151     private void updateMessageTransformer(final SchemaContext currentSchemaContext) {
152         messageTransformer.onGlobalContextUpdated(currentSchemaContext);
153     }
154
155     private void addProvidedSourcesToSchemaRegistry(final NetconfDeviceRpc deviceRpc, final DeviceSources deviceSources) {
156         final NetconfRemoteSchemaYangSourceProvider yangProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
157         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
158             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
159                     PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
160         }
161     }
162
163     private NetconfDeviceRpc setUpDeviceRpc(final RemoteDeviceCommunicator<NetconfMessage> listener) {
164        return new NetconfDeviceRpc(listener, messageTransformer);
165     }
166
167     @Override
168     public void onRemoteSessionDown() {
169         salFacade.onDeviceDisconnected();
170         for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
171             sourceRegistration.close();
172         }
173         resetMessageTransformer();
174     }
175
176     @Override
177     public void onNotification(final NetconfMessage notification) {
178         notificationHandler.handleNotification(notification);
179     }
180
181     /**
182      * Just a transfer object containing schema related dependencies. Injected in constructor.
183      */
184     public static class SchemaResourcesDTO {
185         private final SchemaSourceRegistry schemaRegistry;
186         private final SchemaContextFactory schemaContextFactory;
187         private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
188
189         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry, final SchemaContextFactory schemaContextFactory, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
190             this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
191             this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
192             this.stateSchemasResolver = Preconditions.checkNotNull(stateSchemasResolver);
193         }
194
195         public SchemaSourceRegistry getSchemaRegistry() {
196             return schemaRegistry;
197         }
198
199         public SchemaContextFactory getSchemaContextFactory() {
200             return schemaContextFactory;
201         }
202
203         public NetconfStateSchemas.NetconfStateSchemasResolver getStateSchemasResolver() {
204             return stateSchemasResolver;
205         }
206     }
207
208     /**
209      * Schema building callable.
210      */
211     private static class DeviceSourcesResolver implements Callable<DeviceSources> {
212         private final NetconfDeviceRpc deviceRpc;
213         private final NetconfSessionCapabilities remoteSessionCapabilities;
214         private final RemoteDeviceId id;
215         private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
216
217         public DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionCapabilities remoteSessionCapabilities, final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
218             this.deviceRpc = deviceRpc;
219             this.remoteSessionCapabilities = remoteSessionCapabilities;
220             this.id = id;
221             this.stateSchemasResolver = stateSchemasResolver;
222         }
223
224         @Override
225         public DeviceSources call() throws Exception {
226
227             final Set<SourceIdentifier> requiredSources = Sets.newHashSet(Collections2.transform(
228                     remoteSessionCapabilities.getModuleBasedCaps(), QNAME_TO_SOURCE_ID_FUNCTION));
229
230             // If monitoring is not supported, we will still attempt to create schema, sources might be already provided
231             final NetconfStateSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
232             logger.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
233
234             final Set<SourceIdentifier> providedSources = Sets.newHashSet(Collections2.transform(
235                     availableSchemas.getAvailableYangSchemasQNames(), QNAME_TO_SOURCE_ID_FUNCTION));
236
237             final Set<SourceIdentifier> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
238
239             if (!requiredSourcesNotProvided.isEmpty()) {
240                 logger.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
241                         id, requiredSourcesNotProvided);
242                 logger.warn("{}: Attempting to build schema context from required sources", id);
243             }
244
245
246             // TODO should we perform this ? We have a mechanism to fix initialization of devices not reporting or required modules in hello
247             // That is overriding capabilities in configuration using attribute yang-module-capabilities
248             // This is more user friendly even though it clashes with attribute yang-module-capabilities
249             // Some devices do not report all required models in hello message, but provide them
250             final Set<SourceIdentifier> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
251             if (!providedSourcesNotRequired.isEmpty()) {
252                 logger.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
253                         id, providedSourcesNotRequired);
254                 logger.warn("{}: Adding provided but not required sources as required to prevent failures", id);
255                 requiredSources.addAll(providedSourcesNotRequired);
256             }
257
258             return new DeviceSources(requiredSources, providedSources);
259         }
260     }
261
262     /**
263      * Contains RequiredSources - sources from capabilities.
264      *
265      */
266     private static final class DeviceSources {
267         private final Collection<SourceIdentifier> requiredSources;
268         private final Collection<SourceIdentifier> providedSources;
269
270         public DeviceSources(final Collection<SourceIdentifier> requiredSources, final Collection<SourceIdentifier> providedSources) {
271             this.requiredSources = requiredSources;
272             this.providedSources = providedSources;
273         }
274
275         public Collection<SourceIdentifier> getRequiredSources() {
276             return requiredSources;
277         }
278
279         public Collection<SourceIdentifier> getProvidedSources() {
280             return providedSources;
281         }
282
283     }
284
285     /**
286      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
287      */
288     private final class RecursiveSchemaSetup implements Runnable {
289         private final DeviceSources deviceSources;
290         private final NetconfSessionCapabilities remoteSessionCapabilities;
291         private final NetconfDeviceRpc deviceRpc;
292         private final RemoteDeviceCommunicator<NetconfMessage> listener;
293
294         public RecursiveSchemaSetup(final DeviceSources deviceSources, final NetconfSessionCapabilities remoteSessionCapabilities, final NetconfDeviceRpc deviceRpc, final RemoteDeviceCommunicator<NetconfMessage> listener) {
295             this.deviceSources = deviceSources;
296             this.remoteSessionCapabilities = remoteSessionCapabilities;
297             this.deviceRpc = deviceRpc;
298             this.listener = listener;
299         }
300
301         @Override
302         public void run() {
303             setUpSchema(deviceSources.getRequiredSources());
304         }
305
306         /**
307          * Recursively build schema context, in case of success or final failure notify device
308          */
309         private void setUpSchema(final Collection<SourceIdentifier> requiredSources) {
310             logger.trace("{}: Trying to build schema context from {}", id, requiredSources);
311
312             // If no more sources, fail
313             if(requiredSources.isEmpty()) {
314                 handleSalInitializationFailure(new IllegalStateException(id + ": No more sources for schema context"), listener);
315                 return;
316             }
317
318             final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
319
320             final FutureCallback<SchemaContext> RecursiveSchemaBuilderCallback = new FutureCallback<SchemaContext>() {
321
322                 @Override
323                 public void onSuccess(final SchemaContext result) {
324                     logger.debug("{}: Schema context built successfully from {}", id, requiredSources);
325                     handleSalInitializationSuccess(result, remoteSessionCapabilities, deviceRpc);
326                 }
327
328                 @Override
329                 public void onFailure(final Throwable t) {
330                     // In case source missing, try without it
331                     if (t instanceof MissingSchemaSourceException) {
332                         final SourceIdentifier missingSource = ((MissingSchemaSourceException) t).getSourceId();
333                         logger.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
334                         setUpSchema(stripMissingSource(requiredSources, missingSource));
335
336                     // In case resolution error, try only with resolved sources
337                     } else if (t instanceof SchemaResolutionException) {
338                         // TODO check for infinite loop
339                         final SchemaResolutionException resolutionException = (SchemaResolutionException) t;
340                         logger.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
341                         setUpSchema(resolutionException.getResolvedSources());
342                     // unknown error, fail
343                     } else {
344                         handleSalInitializationFailure(t, listener);
345                     }
346                 }
347             };
348
349             Futures.addCallback(schemaBuilderFuture, RecursiveSchemaBuilderCallback);
350         }
351
352         private Collection<SourceIdentifier> stripMissingSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
353             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
354             final boolean removed = sourceIdentifiers.remove(sIdToRemove);
355             Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
356             return sourceIdentifiers;
357         }
358     }
359 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.