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