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