2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.connect.netconf.listener;
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;
49 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
51 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
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();
58 private final Semaphore semaphore;
59 private final int concurentRpcMsgs;
61 private final Queue<Request> requests = new ArrayDeque<>();
62 private NetconfClientSession session;
64 private Future<?> initFuture;
65 private final SettableFuture<NetconfDeviceCapabilities> firstConnectionFuture;
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);
74 public Boolean isSessionClosing() {
75 return isSessionClosing.get();
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);
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);
89 private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
90 final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
91 this.concurentRpcMsgs = rpcMessageLimit;
93 this.remoteDevice = remoteDevice;
94 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
95 this.firstConnectionFuture = SettableFuture.create();
96 this.semaphore = rpcMessageLimit > 0 ? new Semaphore(rpcMessageLimit) : null;
100 public void onSessionUp(final NetconfClientSession session) {
103 LOG.debug("{}: Session established", id);
104 this.session = session;
106 NetconfSessionPreferences netconfSessionPreferences =
107 NetconfSessionPreferences.fromNetconfSession(session);
108 LOG.trace("{}: Session advertised capabilities: {}", id,
109 netconfSessionPreferences);
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);
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);
125 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
126 if (!firstConnectionFuture.isDone()) {
127 firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
131 sessionLock.unlock();
139 * @return future that returns succes on first succesfull connection and failure when the underlying
140 * reconnecting strategy runs out of reconnection attempts
142 public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
143 if(config instanceof NetconfReconnectingClientConfiguration) {
144 initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
146 initFuture = dispatcher.createClient(config);
150 initFuture.addListener(new GenericFutureListener<Future<Object>>(){
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());
163 return firstConnectionFuture;
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)) {
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!");
177 LOG.debug("Tearing down {}", reason);
178 final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
181 if( session != null ) {
185 * Walk all requests, check if they have been executing
186 * or cancelled and remove them from the queue.
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 );
194 } else if (r.future.isCancelled()) {
195 // This just does some house-cleaning
200 remoteDevice.onRemoteSessionDown();
204 sessionLock.unlock();
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() );
213 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
217 isSessionClosing.set(false);
220 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
221 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
222 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
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();
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);
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() );
247 public void close() {
248 // Cancel reconnect if in progress
249 if(initFuture != null) {
250 initFuture.cancel(false);
252 // Disconnect from device
253 // tear down not necessary, called indirectly by the close in disconnect()
258 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
260 * Dispatch between notifications and messages. Messages need to be processed
261 * with lock held, notifications do not.
263 if (isNotification(message)) {
264 processNotification(message);
266 processMessage(message);
270 private void processMessage(final NetconfMessage message) {
271 Request request = null;
275 request = requests.peek();
276 if (request != null && request.future.isUncancellable()) {
278 // we have just removed one request from the queue
279 // we can also release one permit
280 if(semaphore != null) {
285 LOG.warn("{}: Ignoring unsolicited message {}", id,
290 sessionLock.unlock();
293 if( request != null ) {
295 LOG.debug("{}: Message received {}", id, message);
297 if(LOG.isTraceEnabled()) {
298 LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
302 NetconfMessageTransformUtil.checkValidReply( request.request, message );
303 } catch (final NetconfDocumentedException e) {
305 "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
306 id, msgToS(request.request), msgToS(message), e);
308 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
309 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
311 //recursively processing message to eventually find matching request
312 processMessage(message);
318 NetconfMessageTransformUtil.checkSuccessReply(message);
319 } catch(final NetconfDocumentedException e) {
321 "{}: Error reply from remote device, request: {}, response: {}",
322 id, msgToS(request.request), msgToS(message), e);
324 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
325 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
329 request.future.set( RpcResultBuilder.success( message ).build() );
333 private static String msgToS(final NetconfMessage msg) {
334 return XmlUtil.toString(msg.getDocument());
338 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
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()));
350 return sendRequestWithLock(message, rpc);
352 sessionLock.unlock();
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));
362 if (session == null) {
363 LOG.warn("{}: Session is disconnected, failing RPC request {}",
365 return Futures.immediateFuture( createSessionDownRpcResult() );
368 final Request req = new Request(new UncancellableFuture<>(true), message);
371 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
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()),
380 if( future.cause() != null ) {
381 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
382 future.cause().getLocalizedMessage() ) );
384 req.future.set( createSessionDownRpcResult() ); // assume session is down
386 req.future.setException( future.cause() );
389 LOG.trace("Finished sending request {}", req.request);
397 private void processNotification(final NetconfMessage notification) {
398 if(LOG.isTraceEnabled()) {
399 LOG.trace("{}: Notification received: {}", id, notification);
402 remoteDevice.onNotification(notification);
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()) ;
410 private static final class Request {
411 final UncancellableFuture<RpcResult<NetconfMessage>> future;
412 final NetconfMessage request;
414 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
415 final NetconfMessage request) {
416 this.future = future;
417 this.request = request;