Merge "API Usability: Introduced type capture for Transaction Factory"
[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.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.ListeningExecutorService;
16 import com.google.common.util.concurrent.MoreExecutors;
17 import java.io.InputStream;
18 import java.util.LinkedList;
19 import java.util.List;
20 import java.util.concurrent.ExecutorService;
21 import org.opendaylight.controller.netconf.api.NetconfMessage;
22 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
23 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
24 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
25 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
26 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
27 import org.opendaylight.controller.sal.connect.api.SchemaContextProviderFactory;
28 import org.opendaylight.controller.sal.connect.api.SchemaSourceProviderFactory;
29 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
30 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc;
31 import org.opendaylight.controller.sal.connect.netconf.schema.NetconfDeviceSchemaProviderFactory;
32 import org.opendaylight.controller.sal.connect.netconf.schema.NetconfRemoteSchemaSourceProvider;
33 import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
34 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
35 import org.opendaylight.controller.sal.core.api.RpcImplementation;
36 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
38 import org.opendaylight.yangtools.yang.model.util.repo.AbstractCachingSchemaSourceProvider;
39 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
45  */
46 public final class NetconfDevice implements RemoteDevice<NetconfSessionCapabilities, NetconfMessage> {
47
48     private static final Logger logger = LoggerFactory.getLogger(NetconfDevice.class);
49
50     private final RemoteDeviceId id;
51
52     private final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade;
53     private final ListeningExecutorService processingExecutor;
54     private final MessageTransformer<NetconfMessage> messageTransformer;
55     private final SchemaContextProviderFactory schemaContextProviderFactory;
56     private final SchemaSourceProviderFactory<InputStream> sourceProviderFactory;
57     private final NotificationHandler notificationHandler;
58
59     public static NetconfDevice createNetconfDevice(final RemoteDeviceId id,
60             final AbstractCachingSchemaSourceProvider<String, InputStream> schemaSourceProvider,
61             final ExecutorService executor, final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade) {
62
63         return new NetconfDevice(id, salFacade, executor, new NetconfMessageTransformer(),
64                 new NetconfDeviceSchemaProviderFactory(id), new SchemaSourceProviderFactory<InputStream>() {
65                     @Override
66                     public SchemaSourceProvider<InputStream> createSourceProvider(final RpcImplementation deviceRpc) {
67                         return schemaSourceProvider.createInstanceFor(new NetconfRemoteSchemaSourceProvider(id,
68                                 deviceRpc));
69                     }
70                 });
71     }
72
73     @VisibleForTesting
74     protected NetconfDevice(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade,
75             final ExecutorService processingExecutor, final MessageTransformer<NetconfMessage> messageTransformer,
76             final SchemaContextProviderFactory schemaContextProviderFactory,
77             final SchemaSourceProviderFactory<InputStream> sourceProviderFactory) {
78         this.id = id;
79         this.messageTransformer = messageTransformer;
80         this.salFacade = salFacade;
81         this.sourceProviderFactory = sourceProviderFactory;
82         this.processingExecutor = MoreExecutors.listeningDecorator(processingExecutor);
83         this.schemaContextProviderFactory = schemaContextProviderFactory;
84         this.notificationHandler = new NotificationHandler(salFacade, messageTransformer, id);
85     }
86
87     @Override
88     public void onRemoteSessionUp(final NetconfSessionCapabilities remoteSessionCapabilities,
89                                   final RemoteDeviceCommunicator<NetconfMessage> listener) {
90         // SchemaContext setup has to be performed in a dedicated thread since
91         // we are in a netty thread in this method
92         // Yang models are being downloaded in this method and it would cause a
93         // deadlock if we used the netty thread
94         // http://netty.io/wiki/thread-model.html
95         logger.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
96
97         final ListenableFuture<?> salInitializationFuture = processingExecutor.submit(new Runnable() {
98             @Override
99             public void run() {
100                 final NetconfDeviceRpc deviceRpc = setUpDeviceRpc(remoteSessionCapabilities, listener);
101                 final SchemaSourceProvider<InputStream> delegate = sourceProviderFactory.createSourceProvider(deviceRpc);
102                 final SchemaContextProvider schemaContextProvider = setUpSchemaContext(delegate, remoteSessionCapabilities);
103                 updateMessageTransformer(schemaContextProvider);
104                 salFacade.onDeviceConnected(schemaContextProvider, remoteSessionCapabilities, deviceRpc);
105                 notificationHandler.onRemoteSchemaUp();
106             }
107         });
108
109         Futures.addCallback(salInitializationFuture, new FutureCallback<Object>() {
110             @Override
111             public void onSuccess(final Object result) {
112                 logger.debug("{}: Initialization in sal successful", id);
113                 logger.info("{}: Netconf connector initialized successfully", id);
114             }
115
116             @Override
117             public void onFailure(final Throwable t) {
118                 // Unable to initialize device, set as disconnected
119                 logger.error("{}: Initialization failed", id, t);
120                 salFacade.onDeviceDisconnected();
121             }
122         });
123     }
124
125     /**
126      * Update initial message transformer to use retrieved schema
127      */
128     private void updateMessageTransformer(final SchemaContextProvider schemaContextProvider) {
129         messageTransformer.onGlobalContextUpdated(schemaContextProvider.getSchemaContext());
130     }
131
132     private SchemaContextProvider setUpSchemaContext(final SchemaSourceProvider<InputStream> sourceProvider, final NetconfSessionCapabilities capabilities) {
133         return schemaContextProviderFactory.createContextProvider(capabilities.getModuleBasedCaps(), sourceProvider);
134     }
135
136     private NetconfDeviceRpc setUpDeviceRpc(final NetconfSessionCapabilities capHolder, final RemoteDeviceCommunicator<NetconfMessage> listener) {
137         Preconditions.checkArgument(capHolder.isMonitoringSupported(),
138                 "%s: Netconf device does not support netconf monitoring, yang schemas cannot be acquired. Netconf device capabilities", capHolder);
139         return new NetconfDeviceRpc(listener, messageTransformer);
140     }
141
142     @Override
143     public void onRemoteSessionDown() {
144         salFacade.onDeviceDisconnected();
145     }
146
147     @Override
148     public void onNotification(final NetconfMessage notification) {
149         notificationHandler.handleNotification(notification);
150     }
151
152     /**
153      * Handles incoming notifications. Either caches them(until onRemoteSchemaUp is called) or passes to sal Facade.
154      */
155     private final static class NotificationHandler {
156
157         private final RemoteDeviceHandler<?> salFacade;
158         private final List<NetconfMessage> cache = new LinkedList<>();
159         private final MessageTransformer<NetconfMessage> messageTransformer;
160         private boolean passNotifications = false;
161         private final RemoteDeviceId id;
162
163         NotificationHandler(final RemoteDeviceHandler<?> salFacade, final MessageTransformer<NetconfMessage> messageTransformer, final RemoteDeviceId id) {
164             this.salFacade = salFacade;
165             this.messageTransformer = messageTransformer;
166             this.id = id;
167         }
168
169         synchronized void handleNotification(final NetconfMessage notification) {
170             if(passNotifications) {
171                 passNotification(messageTransformer.toNotification(notification));
172             } else {
173                 cacheNotification(notification);
174             }
175         }
176
177         /**
178          * Forward all cached notifications and pass all notifications from this point directly to sal facade.
179          */
180         synchronized void onRemoteSchemaUp() {
181             passNotifications = true;
182
183             for (final NetconfMessage cachedNotification : cache) {
184                 passNotification(messageTransformer.toNotification(cachedNotification));
185             }
186
187             cache.clear();
188         }
189
190         private void cacheNotification(final NetconfMessage notification) {
191             Preconditions.checkState(passNotifications == false);
192
193             logger.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification);
194             if(logger.isTraceEnabled()) {
195                 logger.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument()));
196             }
197
198             cache.add(notification);
199         }
200
201         private void passNotification(final CompositeNode parsedNotification) {
202             logger.debug("{}: Forwarding notification {}", id, parsedNotification);
203             Preconditions.checkNotNull(parsedNotification);
204             salFacade.onNotification(parsedNotification);
205         }
206
207     }
208 }