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 java.util.ArrayDeque;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Queue;
21 import java.util.concurrent.Semaphore;
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.concurrent.locks.Lock;
24 import java.util.concurrent.locks.ReentrantLock;
25 import org.opendaylight.netconf.api.FailedNetconfMessage;
26 import org.opendaylight.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.netconf.api.NetconfMessage;
28 import org.opendaylight.netconf.api.NetconfTerminationReason;
29 import org.opendaylight.netconf.api.xml.XmlElement;
30 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
31 import org.opendaylight.netconf.api.xml.XmlUtil;
32 import org.opendaylight.netconf.client.NetconfClientDispatcher;
33 import org.opendaylight.netconf.client.NetconfClientSession;
34 import org.opendaylight.netconf.client.NetconfClientSessionListener;
35 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
36 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
37 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
38 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
39 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
40 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.RpcError;
43 import org.opendaylight.yangtools.yang.common.RpcResult;
44 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public class NetconfDeviceCommunicator
49 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 currentSession;
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(
79 final RemoteDeviceId id,
80 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
81 final UserPreferences netconfSessionPreferences, final int rpcMessageLimit) {
82 this(id, remoteDevice, Optional.of(netconfSessionPreferences), rpcMessageLimit);
85 public NetconfDeviceCommunicator(
86 final RemoteDeviceId id,
87 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
88 final int rpcMessageLimit) {
89 this(id, remoteDevice, Optional.<UserPreferences>absent(), rpcMessageLimit);
92 private NetconfDeviceCommunicator(
93 final RemoteDeviceId id,
94 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
95 final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
96 this.concurentRpcMsgs = rpcMessageLimit;
98 this.remoteDevice = remoteDevice;
99 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
100 this.firstConnectionFuture = SettableFuture.create();
101 this.semaphore = rpcMessageLimit > 0 ? new Semaphore(rpcMessageLimit) : null;
105 public void onSessionUp(final NetconfClientSession session) {
108 LOG.debug("{}: Session established", id);
109 currentSession = session;
111 NetconfSessionPreferences netconfSessionPreferences =
112 NetconfSessionPreferences.fromNetconfSession(session);
113 LOG.trace("{}: Session advertised capabilities: {}", id,
114 netconfSessionPreferences);
116 if (overrideNetconfCapabilities.isPresent()) {
117 final NetconfSessionPreferences sessionPreferences = overrideNetconfCapabilities
118 .get().getSessionPreferences();
119 netconfSessionPreferences = overrideNetconfCapabilities.get().moduleBasedCapsOverrided()
120 ? netconfSessionPreferences.replaceModuleCaps(sessionPreferences)
121 : netconfSessionPreferences.addModuleCaps(sessionPreferences);
123 netconfSessionPreferences = overrideNetconfCapabilities.get().nonModuleBasedCapsOverrided()
124 ? netconfSessionPreferences.replaceNonModuleCaps(sessionPreferences)
125 : netconfSessionPreferences.addNonModuleCaps(sessionPreferences);
126 LOG.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id,
127 netconfSessionPreferences);
130 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
131 if (!firstConnectionFuture.isDone()) {
132 firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
135 sessionLock.unlock();
140 * Initialize remote connection.
142 * @param dispatcher {@code NetconfCLientDispatcher}
143 * @param config {@code NetconfClientConfiguration}
144 * @return future that returns succes on first succesfull connection and failure when the underlying
145 * reconnecting strategy runs out of reconnection attempts
147 public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(
148 final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
149 if (config instanceof NetconfReconnectingClientConfiguration) {
150 initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
152 initFuture = dispatcher.createClient(config);
156 initFuture.addListener(future -> {
157 if (!future.isSuccess() && !future.isCancelled()) {
158 LOG.debug("{}: Connection failed", id, future.cause());
159 NetconfDeviceCommunicator.this.remoteDevice.onRemoteSessionFailed(future.cause());
160 if (firstConnectionFuture.isDone()) {
161 firstConnectionFuture.setException(future.cause());
165 return firstConnectionFuture;
168 public void disconnect() {
169 // If session is already in closing, no need to close it again
170 if (currentSession != null && isSessionClosing.compareAndSet(false, true)) {
171 currentSession.close();
175 private void tearDown(final String reason) {
176 if (!isSessionClosing()) {
177 LOG.warn("It's curious that no one to close the session but tearDown is called!");
179 LOG.debug("Tearing down {}", reason);
180 final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
183 if (currentSession != null) {
184 currentSession = null;
186 * Walk all requests, check if they have been executing
187 * or cancelled and remove them from the queue.
189 final Iterator<Request> it = requests.iterator();
190 while (it.hasNext()) {
191 final Request r = it.next();
192 if (r.future.isUncancellable()) {
193 futuresToCancel.add(r.future);
195 } else if (r.future.isCancelled()) {
196 // This just does some house-cleaning
201 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 static RpcResult<NetconfMessage> createErrorRpcResult(final RpcError.ErrorType errorType,
226 final String message) {
227 return RpcResultBuilder.<NetconfMessage>failed()
228 .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build();
232 public void onSessionDown(final NetconfClientSession session, final Exception exception) {
233 // If session is already in closing, no need to call tearDown again.
234 if (isSessionClosing.compareAndSet(false, true)) {
235 LOG.warn("{}: Session went down", id, exception);
241 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
242 // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
243 LOG.warn("{}: Session terminated {}", id, reason);
244 tearDown(reason.getErrorMessage());
248 public void close() {
249 // Cancel reconnect if in progress
250 if (initFuture != null) {
251 initFuture.cancel(false);
253 // Disconnect from device
254 // tear down not necessary, called indirectly by the close in disconnect()
259 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
261 * Dispatch between notifications and messages. Messages need to be processed
262 * with lock held, notifications do not.
264 if (isNotification(message)) {
265 processNotification(message);
267 processMessage(message);
271 private void processMessage(final NetconfMessage message) {
272 Request request = null;
276 request = requests.peek();
277 if (request != null && request.future.isUncancellable()) {
278 request = requests.poll();
279 // we have just removed one request from the queue
280 // we can also release one permit
281 if (semaphore != null) {
286 LOG.warn("{}: Ignoring unsolicited message {}", id,
290 sessionLock.unlock();
293 if (request != null) {
295 if (FailedNetconfMessage.class.isInstance(message)) {
296 request.future.set(NetconfMessageTransformUtil.toRpcResult((FailedNetconfMessage) message));
300 LOG.debug("{}: Message received {}", id, message);
302 if (LOG.isTraceEnabled()) {
303 LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
307 NetconfMessageTransformUtil.checkValidReply(request.request, message);
308 } catch (final NetconfDocumentedException e) {
310 "{}: Invalid request-reply match,"
311 + "reply message contains different message-id, request: {}, response: {}",
312 id, msgToS(request.request), msgToS(message), e);
314 request.future.set(RpcResultBuilder.<NetconfMessage>failed()
315 .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
317 //recursively processing message to eventually find matching request
318 processMessage(message);
324 NetconfMessageTransformUtil.checkSuccessReply(message);
325 } catch (final NetconfDocumentedException e) {
327 "{}: Error reply from remote device, request: {}, response: {}",
328 id, msgToS(request.request), msgToS(message), e);
330 request.future.set(RpcResultBuilder.<NetconfMessage>failed()
331 .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
335 request.future.set(RpcResultBuilder.success(message).build());
339 private static String msgToS(final NetconfMessage msg) {
340 return XmlUtil.toString(msg.getDocument());
344 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
347 if (semaphore != null && !semaphore.tryAcquire()) {
348 LOG.warn("Limit of concurrent rpc messages was reached (limit :" + concurentRpcMsgs
349 + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName());
350 return Futures.immediateFailedFuture(new NetconfDocumentedException(
351 "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
352 + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
355 return sendRequestWithLock(message, rpc);
357 sessionLock.unlock();
361 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
363 if (LOG.isTraceEnabled()) {
364 LOG.trace("{}: Sending message {}", id, msgToS(message));
367 if (currentSession == null) {
368 LOG.warn("{}: Session is disconnected, failing RPC request {}",
370 return Futures.immediateFuture(createSessionDownRpcResult());
373 final Request req = new Request(new UncancellableFuture<>(true), message);
376 currentSession.sendMessage(req.request).addListener(future -> {
377 if (!future.isSuccess()) {
378 // We expect that a session down will occur at this point
379 LOG.debug("{}: Failed to send request {}", id,
380 XmlUtil.toString(req.request.getDocument()),
383 if (future.cause() != null) {
384 req.future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
385 future.cause().getLocalizedMessage()));
387 req.future.set(createSessionDownRpcResult()); // assume session is down
389 req.future.setException(future.cause());
391 LOG.trace("Finished sending request {}", req.request);
398 private void processNotification(final NetconfMessage notification) {
399 if (LOG.isTraceEnabled()) {
400 LOG.trace("{}: Notification received: {}", id, notification);
403 remoteDevice.onNotification(notification);
406 private static boolean isNotification(final NetconfMessage message) {
407 if (message.getDocument() == null) {
408 // We have no message, which mean we have a FailedNetconfMessage
411 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
412 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
415 private static final class Request {
416 final UncancellableFuture<RpcResult<NetconfMessage>> future;
417 final NetconfMessage request;
419 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
420 final NetconfMessage request) {
421 this.future = future;
422 this.request = request;