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.controller.sal.connect.netconf.listener;
10 import java.util.ArrayDeque;
11 import java.util.Collections;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Queue;
15 import java.util.concurrent.locks.Lock;
16 import java.util.concurrent.locks.ReentrantLock;
18 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
19 import org.opendaylight.controller.netconf.api.NetconfMessage;
20 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
21 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
22 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
23 import org.opendaylight.controller.netconf.client.NetconfClientSession;
24 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
25 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
26 import org.opendaylight.controller.netconf.util.xml.XmlElement;
27 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
28 import org.opendaylight.controller.sal.common.util.RpcErrors;
29 import org.opendaylight.controller.sal.common.util.Rpcs;
30 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
31 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
32 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
33 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
34 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.RpcError;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 import com.google.common.base.Strings;
42 import com.google.common.collect.Lists;
43 import com.google.common.util.concurrent.Futures;
44 import com.google.common.util.concurrent.ListenableFuture;
46 import io.netty.util.concurrent.Future;
47 import io.netty.util.concurrent.FutureListener;
49 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
51 private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
53 private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
54 private final RemoteDeviceId id;
55 private final Lock sessionLock = new ReentrantLock();
57 public NetconfDeviceCommunicator(final RemoteDeviceId id,
58 final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
60 this.remoteDevice = remoteDevice;
63 private final Queue<Request> requests = new ArrayDeque<>();
64 private NetconfClientSession session;
67 public void onSessionUp(final NetconfClientSession session) {
70 logger.debug("{}: Session established", id);
71 this.session = session;
73 final NetconfSessionCapabilities netconfSessionCapabilities =
74 NetconfSessionCapabilities.fromNetconfSession(session);
75 logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
77 remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
84 public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
85 final NetconfReconnectingClientConfiguration config) {
86 dispatch.createReconnectingClient(config);
89 private void tearDown( String reason ) {
90 List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
93 if( session != null ) {
97 * Walk all requests, check if they have been executing
98 * or cancelled and remove them from the queue.
100 final Iterator<Request> it = requests.iterator();
101 while (it.hasNext()) {
102 final Request r = it.next();
103 if (r.future.isUncancellable()) {
104 futuresToCancel.add( r.future );
106 } else if (r.future.isCancelled()) {
107 // This just does some house-cleaning
112 remoteDevice.onRemoteSessionDown();
116 sessionLock.unlock();
119 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
120 // blocking the caller.
121 for( UncancellableFuture<RpcResult<NetconfMessage>> future: futuresToCancel ) {
122 if( Strings.isNullOrEmpty( reason ) ) {
123 future.set( createSessionDownRpcResult() );
125 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
130 private RpcResult<NetconfMessage> createSessionDownRpcResult()
132 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
133 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
136 private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message )
138 return new FailedRpcResult<NetconfMessage>( RpcErrors.getRpcError( null,
139 NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(),
140 null, RpcError.ErrorSeverity.ERROR, message, errorType, null ) );
144 public void onSessionDown(final NetconfClientSession session, final Exception e) {
145 logger.warn("{}: Session went down", id, e);
150 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
151 logger.warn("{}: Session terminated {}", id, reason);
152 tearDown( reason.getErrorMessage() );
156 public void close() {
157 tearDown( String.format( "The netconf session to %1$s has been closed", id.getName() ) );
161 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
163 * Dispatch between notifications and messages. Messages need to be processed
164 * with lock held, notifications do not.
166 if (isNotification(message)) {
167 processNotification(message);
169 processMessage(message);
173 private void processMessage(final NetconfMessage message) {
174 Request request = null;
177 request = requests.peek();
178 if (request.future.isUncancellable()) {
183 logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
187 sessionLock.unlock();
190 if( request != null ) {
192 logger.debug("{}: Message received {}", id, message);
194 if(logger.isTraceEnabled()) {
195 logger.trace( "{}: Matched request: {} to response: {}", id,
196 msgToS( request.request ), msgToS( message ) );
200 NetconfMessageTransformUtil.checkValidReply( request.request, message );
202 catch (final NetconfDocumentedException e) {
203 logger.warn( "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
204 id, msgToS( request.request ), msgToS( message ), e );
206 request.future.set( new FailedRpcResult<NetconfMessage>(
207 NetconfMessageTransformUtil.toRpcError( e ) ) );
212 NetconfMessageTransformUtil.checkSuccessReply(message);
214 catch( NetconfDocumentedException e ) {
215 logger.warn( "{}: Error reply from remote device, request: {}, response: {}", id,
216 msgToS( request.request ), msgToS( message ), e );
218 request.future.set( new FailedRpcResult<NetconfMessage>(
219 NetconfMessageTransformUtil.toRpcError( e ) ) );
223 request.future.set(Rpcs.getRpcResult( true, message, Collections.<RpcError>emptySet() ) );
227 private static String msgToS(final NetconfMessage msg) {
228 return XmlUtil.toString(msg.getDocument());
232 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(
233 final NetconfMessage message, final QName rpc) {
236 return sendRequestWithLock( message, rpc );
239 sessionLock.unlock();
243 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
244 final NetconfMessage message, final QName rpc) {
245 if(logger.isTraceEnabled()) {
246 logger.trace("{}: Sending message {}", id, msgToS(message));
249 if (session == null) {
250 logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
251 return Futures.immediateFuture( createSessionDownRpcResult() );
254 final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
258 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
260 public void operationComplete(final Future<Void> future) throws Exception {
261 if( !future.isSuccess() ) {
262 // We expect that a session down will occur at this point
263 logger.debug( "{}: Failed to send request {}", id,
264 XmlUtil.toString(req.request.getDocument()), future.cause() );
266 if( future.cause() != null ) {
267 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
268 future.cause().getLocalizedMessage() ) );
270 req.future.set( createSessionDownRpcResult() ); // assume session is down
272 req.future.setException( future.cause() );
275 logger.trace( "Finished sending request {}", req.request );
283 private void processNotification(final NetconfMessage notification) {
284 logger.debug("{}: Notification received: {}", id, notification);
286 if(logger.isTraceEnabled()) {
287 logger.trace("{}: Notification received: {}", id, msgToS(notification));
290 remoteDevice.onNotification(notification);
293 private static boolean isNotification(final NetconfMessage message) {
294 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
295 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
298 private static final class Request {
299 final UncancellableFuture<RpcResult<NetconfMessage>> future;
300 final NetconfMessage request;
302 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
303 final NetconfMessage request) {
304 this.future = future;
305 this.request = request;