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