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.NetconfClientConfiguration;
26 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
27 import org.opendaylight.controller.netconf.util.xml.XmlElement;
28 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
29 import org.opendaylight.controller.sal.common.util.RpcErrors;
30 import org.opendaylight.controller.sal.common.util.Rpcs;
31 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
32 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
33 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
34 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
35 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.RpcError;
38 import org.opendaylight.yangtools.yang.common.RpcResult;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import com.google.common.base.Strings;
43 import com.google.common.collect.Lists;
44 import com.google.common.util.concurrent.Futures;
45 import com.google.common.util.concurrent.ListenableFuture;
47 import io.netty.util.concurrent.Future;
48 import io.netty.util.concurrent.FutureListener;
50 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
52 private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
54 private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
55 private final RemoteDeviceId id;
56 private final Lock sessionLock = new ReentrantLock();
58 public NetconfDeviceCommunicator(final RemoteDeviceId id,
59 final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
61 this.remoteDevice = remoteDevice;
64 private final Queue<Request> requests = new ArrayDeque<>();
65 private NetconfClientSession session;
68 public void onSessionUp(final NetconfClientSession session) {
71 logger.debug("{}: Session established", id);
72 this.session = session;
74 final NetconfSessionCapabilities netconfSessionCapabilities =
75 NetconfSessionCapabilities.fromNetconfSession(session);
76 logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
78 remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
85 public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
86 final NetconfClientConfiguration config) {
87 if(config instanceof NetconfReconnectingClientConfiguration) {
88 dispatch.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
90 dispatch.createClient(config);
94 private void tearDown( String reason ) {
95 List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
98 if( session != null ) {
102 * Walk all requests, check if they have been executing
103 * or cancelled and remove them from the queue.
105 final Iterator<Request> it = requests.iterator();
106 while (it.hasNext()) {
107 final Request r = it.next();
108 if (r.future.isUncancellable()) {
109 futuresToCancel.add( r.future );
111 } else if (r.future.isCancelled()) {
112 // This just does some house-cleaning
117 remoteDevice.onRemoteSessionDown();
121 sessionLock.unlock();
124 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
125 // blocking the caller.
126 for( UncancellableFuture<RpcResult<NetconfMessage>> future: futuresToCancel ) {
127 if( Strings.isNullOrEmpty( reason ) ) {
128 future.set( createSessionDownRpcResult() );
130 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
135 private RpcResult<NetconfMessage> createSessionDownRpcResult()
137 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
138 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
141 private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message )
143 return new FailedRpcResult<NetconfMessage>( RpcErrors.getRpcError( null,
144 NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(),
145 null, RpcError.ErrorSeverity.ERROR, message, errorType, null ) );
149 public void onSessionDown(final NetconfClientSession session, final Exception e) {
150 logger.warn("{}: Session went down", id, e);
155 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
156 logger.warn("{}: Session terminated {}", id, reason);
157 tearDown( reason.getErrorMessage() );
161 public void close() {
162 tearDown( String.format( "The netconf session to %1$s has been closed", id.getName() ) );
166 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
168 * Dispatch between notifications and messages. Messages need to be processed
169 * with lock held, notifications do not.
171 if (isNotification(message)) {
172 processNotification(message);
174 processMessage(message);
178 private void processMessage(final NetconfMessage message) {
179 Request request = null;
182 request = requests.peek();
183 if (request.future.isUncancellable()) {
188 logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
192 sessionLock.unlock();
195 if( request != null ) {
197 logger.debug("{}: Message received {}", id, message);
199 if(logger.isTraceEnabled()) {
200 logger.trace( "{}: Matched request: {} to response: {}", id,
201 msgToS( request.request ), msgToS( message ) );
205 NetconfMessageTransformUtil.checkValidReply( request.request, message );
207 catch (final NetconfDocumentedException e) {
208 logger.warn( "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
209 id, msgToS( request.request ), msgToS( message ), e );
211 request.future.set( new FailedRpcResult<NetconfMessage>(
212 NetconfMessageTransformUtil.toRpcError( e ) ) );
217 NetconfMessageTransformUtil.checkSuccessReply(message);
219 catch( NetconfDocumentedException e ) {
220 logger.warn( "{}: Error reply from remote device, request: {}, response: {}", id,
221 msgToS( request.request ), msgToS( message ), e );
223 request.future.set( new FailedRpcResult<NetconfMessage>(
224 NetconfMessageTransformUtil.toRpcError( e ) ) );
228 request.future.set(Rpcs.getRpcResult( true, message, Collections.<RpcError>emptySet() ) );
232 private static String msgToS(final NetconfMessage msg) {
233 return XmlUtil.toString(msg.getDocument());
237 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(
238 final NetconfMessage message, final QName rpc) {
241 return sendRequestWithLock( message, rpc );
244 sessionLock.unlock();
248 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
249 final NetconfMessage message, final QName rpc) {
250 if(logger.isTraceEnabled()) {
251 logger.trace("{}: Sending message {}", id, msgToS(message));
254 if (session == null) {
255 logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
256 return Futures.immediateFuture( createSessionDownRpcResult() );
259 final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
263 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
265 public void operationComplete(final Future<Void> future) throws Exception {
266 if( !future.isSuccess() ) {
267 // We expect that a session down will occur at this point
268 logger.debug( "{}: Failed to send request {}", id,
269 XmlUtil.toString(req.request.getDocument()), future.cause() );
271 if( future.cause() != null ) {
272 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
273 future.cause().getLocalizedMessage() ) );
275 req.future.set( createSessionDownRpcResult() ); // assume session is down
277 req.future.setException( future.cause() );
280 logger.trace( "Finished sending request {}", req.request );
288 private void processNotification(final NetconfMessage notification) {
289 logger.debug("{}: Notification received: {}", id, notification);
291 if(logger.isTraceEnabled()) {
292 logger.trace("{}: Notification received: {}", id, msgToS(notification));
295 remoteDevice.onNotification(notification);
298 private static boolean isNotification(final NetconfMessage message) {
299 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
300 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
303 private static final class Request {
304 final UncancellableFuture<RpcResult<NetconfMessage>> future;
305 final NetconfMessage request;
307 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
308 final NetconfMessage request) {
309 this.future = future;
310 this.request = request;