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 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 volatile 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 netconfSessionPreferences = overrideNetconfCapabilities.get().isOverride() ?
113 netconfSessionPreferences.replaceModuleCaps(overrideNetconfCapabilities.get().getSessionPreferences()) :
114 netconfSessionPreferences.addModuleCaps(overrideNetconfCapabilities.get().getSessionPreferences());
116 "{}: Session capabilities overridden, capabilities that will be used: {}",
117 id, netconfSessionPreferences);
121 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
122 if (!firstConnectionFuture.isDone()) {
123 firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
127 sessionLock.unlock();
135 * @return future that returns succes on first succesfull connection and failure when the underlying
136 * reconnecting strategy runs out of reconnection attempts
138 public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
139 if(config instanceof NetconfReconnectingClientConfiguration) {
140 initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
142 initFuture = dispatcher.createClient(config);
146 initFuture.addListener(new GenericFutureListener<Future<Object>>(){
149 public void operationComplete(Future<Object> future) throws Exception {
150 if (!future.isSuccess() && !future.isCancelled()) {
151 LOG.debug("{}: Connection failed", id, future.cause());
152 NetconfDeviceCommunicator.this.remoteDevice.onRemoteSessionFailed(future.cause());
153 if (firstConnectionFuture.isDone()) {
154 firstConnectionFuture.setException(future.cause());
159 return firstConnectionFuture;
162 public void disconnect() {
163 // If session is already in closing, no need to close it again
164 if(session != null && isSessionClosing.compareAndSet(false, true)) {
169 private void tearDown( String reason ) {
170 if (!isSessionClosing()) {
171 LOG.warn("It's curious that no one to close the session but tearDown is called!");
173 LOG.debug("Tearing down {}", reason);
174 List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
177 if( session != null ) {
181 * Walk all requests, check if they have been executing
182 * or cancelled and remove them from the queue.
184 final Iterator<Request> it = requests.iterator();
185 while (it.hasNext()) {
186 final Request r = it.next();
187 if (r.future.isUncancellable()) {
188 futuresToCancel.add( r.future );
190 } else if (r.future.isCancelled()) {
191 // This just does some house-cleaning
196 remoteDevice.onRemoteSessionDown();
200 sessionLock.unlock();
203 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
204 // blocking the caller.
205 for( UncancellableFuture<RpcResult<NetconfMessage>> future: futuresToCancel ) {
206 if( Strings.isNullOrEmpty( reason ) ) {
207 future.set( createSessionDownRpcResult() );
209 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
213 isSessionClosing.set(false);
216 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
217 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
218 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
221 private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message ) {
222 return RpcResultBuilder.<NetconfMessage>failed()
223 .withError(errorType, NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(), message).build();
227 public void onSessionDown(final NetconfClientSession session, final Exception e) {
228 // If session is already in closing, no need to call tearDown again.
229 if (isSessionClosing.compareAndSet(false, true)) {
230 LOG.warn("{}: Session went down", id, e);
236 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
237 // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
238 LOG.warn("{}: Session terminated {}", id, reason);
239 tearDown( reason.getErrorMessage() );
243 public void close() {
244 // Cancel reconnect if in progress
245 if(initFuture != null) {
246 initFuture.cancel(false);
248 // Disconnect from device
249 if(session != null) {
251 // tear down not necessary, called indirectly by above close
256 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
258 * Dispatch between notifications and messages. Messages need to be processed
259 * with lock held, notifications do not.
261 if (isNotification(message)) {
262 processNotification(message);
264 processMessage(message);
268 private void processMessage(final NetconfMessage message) {
269 Request request = null;
273 request = requests.peek();
274 if (request != null && request.future.isUncancellable()) {
276 // we have just removed one request from the queue
277 // we can also release one permit
278 if(semaphore != null) {
283 LOG.warn("{}: Ignoring unsolicited message {}", id,
288 sessionLock.unlock();
291 if( request != null ) {
293 LOG.debug("{}: Message received {}", id, message);
295 if(LOG.isTraceEnabled()) {
296 LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
300 NetconfMessageTransformUtil.checkValidReply( request.request, message );
301 } catch (final NetconfDocumentedException e) {
303 "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
304 id, msgToS(request.request), msgToS(message), e);
306 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
307 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
309 //recursively processing message to eventually find matching request
310 processMessage(message);
316 NetconfMessageTransformUtil.checkSuccessReply(message);
317 } catch(final NetconfDocumentedException e) {
319 "{}: Error reply from remote device, request: {}, response: {}",
320 id, msgToS(request.request), msgToS(message), e);
322 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
323 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
327 request.future.set( RpcResultBuilder.success( message ).build() );
331 private static String msgToS(final NetconfMessage msg) {
332 return XmlUtil.toString(msg.getDocument());
336 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
339 if (semaphore != null && !semaphore.tryAcquire()) {
340 LOG.warn("Limit of concurrent rpc messages was reached (limit :" +
341 concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName());
342 sessionLock.unlock();
343 return Futures.immediateFailedFuture(new NetconfDocumentedException("Limit of rpc messages was reached (Limit :" +
344 concurentRpcMsgs + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
348 return sendRequestWithLock(message, rpc);
350 sessionLock.unlock();
354 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
355 final NetconfMessage message, final QName rpc) {
356 if(LOG.isTraceEnabled()) {
357 LOG.trace("{}: Sending message {}", id, msgToS(message));
360 if (session == null) {
361 LOG.warn("{}: Session is disconnected, failing RPC request {}",
363 return Futures.immediateFuture( createSessionDownRpcResult() );
366 final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
370 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
372 public void operationComplete(final Future<Void> future) throws Exception {
373 if( !future.isSuccess() ) {
374 // We expect that a session down will occur at this point
375 LOG.debug("{}: Failed to send request {}", id,
376 XmlUtil.toString(req.request.getDocument()),
379 if( future.cause() != null ) {
380 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
381 future.cause().getLocalizedMessage() ) );
383 req.future.set( createSessionDownRpcResult() ); // assume session is down
385 req.future.setException( future.cause() );
388 LOG.trace("Finished sending request {}", req.request);
396 private void processNotification(final NetconfMessage notification) {
397 if(LOG.isTraceEnabled()) {
398 LOG.trace("{}: Notification received: {}", id, notification);
401 remoteDevice.onNotification(notification);
404 private static boolean isNotification(final NetconfMessage message) {
405 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
406 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
409 private static final class Request {
410 final UncancellableFuture<RpcResult<NetconfMessage>> future;
411 final NetconfMessage request;
413 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
414 final NetconfMessage request) {
415 this.future = future;
416 this.request = request;