BUG-997 Use shared schema context factory in netconf-connector
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / listener / NetconfDeviceCommunicator.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.listener;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Strings;
12 import com.google.common.collect.Lists;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import io.netty.util.concurrent.Future;
16 import io.netty.util.concurrent.FutureListener;
17 import java.util.ArrayDeque;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Queue;
21 import java.util.concurrent.locks.Lock;
22 import java.util.concurrent.locks.ReentrantLock;
23 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
24 import org.opendaylight.controller.netconf.api.NetconfMessage;
25 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
26 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
27 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
28 import org.opendaylight.controller.netconf.client.NetconfClientSession;
29 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
30 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
31 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
32 import org.opendaylight.controller.netconf.util.xml.XmlElement;
33 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
34 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
35 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
36 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
37 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.RpcError;
40 import org.opendaylight.yangtools.yang.common.RpcResult;
41 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
46
47     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
48
49     private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
50     private final Optional<NetconfSessionCapabilities> overrideNetconfCapabilities;
51     private final RemoteDeviceId id;
52     private final Lock sessionLock = new ReentrantLock();
53
54     // TODO implement concurrent message limit
55     private final Queue<Request> requests = new ArrayDeque<>();
56     private NetconfClientSession session;
57     private Future<?> initFuture;
58
59     public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
60             final NetconfSessionCapabilities netconfSessionCapabilities) {
61         this(id, remoteDevice, Optional.of(netconfSessionCapabilities));
62     }
63
64     public NetconfDeviceCommunicator(final RemoteDeviceId id,
65                                      final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
66         this(id, remoteDevice, Optional.<NetconfSessionCapabilities>absent());
67     }
68
69     private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
70             final Optional<NetconfSessionCapabilities> overrideNetconfCapabilities) {
71         this.id = id;
72         this.remoteDevice = remoteDevice;
73         this.overrideNetconfCapabilities = overrideNetconfCapabilities;
74     }
75
76     @Override
77     public void onSessionUp(final NetconfClientSession session) {
78         sessionLock.lock();
79         try {
80             logger.debug("{}: Session established", id);
81             this.session = session;
82
83             NetconfSessionCapabilities netconfSessionCapabilities =
84                                              NetconfSessionCapabilities.fromNetconfSession(session);
85             logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
86
87             if(overrideNetconfCapabilities.isPresent()) {
88                 netconfSessionCapabilities = netconfSessionCapabilities.replaceModuleCaps(overrideNetconfCapabilities.get());
89                 logger.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id, netconfSessionCapabilities);
90             }
91
92             remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
93         }
94         finally {
95             sessionLock.unlock();
96         }
97     }
98
99     public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
100                                            final NetconfClientConfiguration config) {
101         if(config instanceof NetconfReconnectingClientConfiguration) {
102             initFuture = dispatch.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
103         } else {
104             initFuture = dispatch.createClient(config);
105         }
106     }
107
108     private void tearDown( String reason ) {
109         List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
110         sessionLock.lock();
111         try {
112             if( session != null ) {
113                 session = null;
114
115                 /*
116                  * Walk all requests, check if they have been executing
117                  * or cancelled and remove them from the queue.
118                  */
119                 final Iterator<Request> it = requests.iterator();
120                 while (it.hasNext()) {
121                     final Request r = it.next();
122                     if (r.future.isUncancellable()) {
123                         futuresToCancel.add( r.future );
124                         it.remove();
125                     } else if (r.future.isCancelled()) {
126                         // This just does some house-cleaning
127                         it.remove();
128                     }
129                 }
130
131                 remoteDevice.onRemoteSessionDown();
132             }
133         }
134         finally {
135             sessionLock.unlock();
136         }
137
138         // Notify pending request futures outside of the sessionLock to avoid unnecessarily
139         // blocking the caller.
140         for( UncancellableFuture<RpcResult<NetconfMessage>> future: futuresToCancel ) {
141             if( Strings.isNullOrEmpty( reason ) ) {
142                 future.set( createSessionDownRpcResult() );
143             } else {
144                 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
145             }
146         }
147     }
148
149     private RpcResult<NetconfMessage> createSessionDownRpcResult()
150     {
151         return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
152                              String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
153     }
154
155     private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message )
156     {
157         return RpcResultBuilder.<NetconfMessage>failed()
158                 .withError( errorType, NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(),
159                             message )
160                 .build();
161     }
162
163     @Override
164     public void onSessionDown(final NetconfClientSession session, final Exception e) {
165         logger.warn("{}: Session went down", id, e);
166         tearDown( null );
167     }
168
169     @Override
170     public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
171         logger.warn("{}: Session terminated {}", id, reason);
172         tearDown( reason.getErrorMessage() );
173     }
174
175     @Override
176     public void close() {
177         // Cancel reconnect if in progress
178         if(initFuture != null) {
179             initFuture.cancel(false);
180         }
181         // Disconnect from device
182         if(session != null) {
183             session.close();
184         }
185         tearDown(id + ": Netconf session closed");
186     }
187
188     @Override
189     public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
190         /*
191          * Dispatch between notifications and messages. Messages need to be processed
192          * with lock held, notifications do not.
193          */
194         if (isNotification(message)) {
195             processNotification(message);
196         } else {
197             processMessage(message);
198         }
199     }
200
201     private void processMessage(final NetconfMessage message) {
202         Request request = null;
203         sessionLock.lock();
204
205         try {
206             request = requests.peek();
207             if (request != null && request.future.isUncancellable()) {
208                 requests.poll();
209             } else {
210                 request = null;
211                 logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
212             }
213         }
214         finally {
215             sessionLock.unlock();
216         }
217
218         if( request != null ) {
219
220             logger.debug("{}: Message received {}", id, message);
221
222             if(logger.isTraceEnabled()) {
223                 logger.trace( "{}: Matched request: {} to response: {}", id,
224                               msgToS( request.request ), msgToS( message ) );
225             }
226
227             try {
228                 NetconfMessageTransformUtil.checkValidReply( request.request, message );
229             }
230             catch (final NetconfDocumentedException e) {
231                 logger.warn( "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
232                              id, msgToS( request.request ), msgToS( message ), e );
233
234                 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
235                         .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
236                 return;
237             }
238
239             try {
240                 NetconfMessageTransformUtil.checkSuccessReply(message);
241             }
242             catch(final NetconfDocumentedException e) {
243                 logger.warn( "{}: Error reply from remote device, request: {}, response: {}", id,
244                              msgToS( request.request ), msgToS( message ), e );
245
246                 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
247                         .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
248                 return;
249             }
250
251             request.future.set( RpcResultBuilder.success( message ).build() );
252         }
253     }
254
255     private static String msgToS(final NetconfMessage msg) {
256         return XmlUtil.toString(msg.getDocument());
257     }
258
259     @Override
260     public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(
261                                                final NetconfMessage message, final QName rpc) {
262         sessionLock.lock();
263         try {
264             return sendRequestWithLock( message, rpc );
265         }
266         finally {
267             sessionLock.unlock();
268         }
269     }
270
271     private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
272                                                final NetconfMessage message, final QName rpc) {
273         if(logger.isTraceEnabled()) {
274             logger.trace("{}: Sending message {}", id, msgToS(message));
275         }
276
277         if (session == null) {
278             logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
279             return Futures.immediateFuture( createSessionDownRpcResult() );
280         }
281
282         final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
283                                          message );
284         requests.add(req);
285
286         session.sendMessage(req.request).addListener(new FutureListener<Void>() {
287             @Override
288             public void operationComplete(final Future<Void> future) throws Exception {
289                 if( !future.isSuccess() ) {
290                     // We expect that a session down will occur at this point
291                     logger.debug( "{}: Failed to send request {}", id,
292                                   XmlUtil.toString(req.request.getDocument()), future.cause() );
293
294                     if( future.cause() != null ) {
295                         req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
296                                                               future.cause().getLocalizedMessage() ) );
297                     } else {
298                         req.future.set( createSessionDownRpcResult() ); // assume session is down
299                     }
300                     req.future.setException( future.cause() );
301                 }
302                 else {
303                     logger.trace( "Finished sending request {}", req.request );
304                 }
305             }
306         });
307
308         return req.future;
309     }
310
311     private void processNotification(final NetconfMessage notification) {
312         logger.debug("{}: Notification received: {}", id, notification);
313
314         if(logger.isTraceEnabled()) {
315             logger.trace("{}: Notification received: {}", id, msgToS(notification));
316         }
317
318         remoteDevice.onNotification(notification);
319     }
320
321     private static boolean isNotification(final NetconfMessage message) {
322         final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
323         return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
324     }
325
326     private static final class Request {
327         final UncancellableFuture<RpcResult<NetconfMessage>> future;
328         final NetconfMessage request;
329
330         private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
331                         final NetconfMessage request) {
332             this.future = future;
333             this.request = request;
334         }
335     }
336 }