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.client.mdsal;
10 import com.google.common.base.Strings;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import java.io.EOFException;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Queue;
20 import java.util.concurrent.Semaphore;
21 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
22 import java.util.concurrent.locks.Lock;
23 import java.util.concurrent.locks.ReentrantLock;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.netconf.api.DocumentedException;
26 import org.opendaylight.netconf.api.NetconfTerminationReason;
27 import org.opendaylight.netconf.api.messages.NetconfMessage;
28 import org.opendaylight.netconf.api.xml.XmlElement;
29 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
30 import org.opendaylight.netconf.api.xml.XmlUtil;
31 import org.opendaylight.netconf.client.NetconfClientSession;
32 import org.opendaylight.netconf.client.NetconfClientSessionListener;
33 import org.opendaylight.netconf.client.NetconfMessageUtil;
34 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
35 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
36 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceCommunicator;
37 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
38 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
39 import org.opendaylight.yangtools.yang.common.ErrorTag;
40 import org.opendaylight.yangtools.yang.common.ErrorType;
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 implements NetconfClientSessionListener, RemoteDeviceCommunicator {
49 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
51 protected final RemoteDevice<NetconfDeviceCommunicator> remoteDevice;
52 private final @Nullable UserPreferences overrideNetconfCapabilities;
53 protected final RemoteDeviceId id;
54 private final Lock sessionLock = new ReentrantLock();
56 private final Semaphore semaphore;
57 private final int concurentRpcMsgs;
59 private final Queue<Request> requests = new ArrayDeque<>();
60 private NetconfClientSession currentSession;
62 // isSessionClosing indicates a close operation on the session is issued and
63 // tearDown will surely be called later to finish the close.
64 // Used to allow only one thread to enter tearDown and other threads should
65 // NOT enter it simultaneously and should end its close operation without
66 // calling tearDown to release the locks they hold to avoid deadlock.
67 private static final AtomicIntegerFieldUpdater<NetconfDeviceCommunicator> CLOSING_UPDATER =
68 AtomicIntegerFieldUpdater.newUpdater(NetconfDeviceCommunicator.class, "closing");
69 private volatile int closing;
71 public boolean isSessionClosing() {
75 public NetconfDeviceCommunicator(final RemoteDeviceId id,
76 final RemoteDevice<NetconfDeviceCommunicator> remoteDevice, final int rpcMessageLimit) {
77 this(id, remoteDevice, rpcMessageLimit, null);
80 public NetconfDeviceCommunicator(final RemoteDeviceId id,
81 final RemoteDevice<NetconfDeviceCommunicator> remoteDevice, final int rpcMessageLimit,
82 final @Nullable UserPreferences overrideNetconfCapabilities) {
83 concurentRpcMsgs = rpcMessageLimit;
85 this.remoteDevice = remoteDevice;
86 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
87 semaphore = rpcMessageLimit > 0 ? new Semaphore(rpcMessageLimit) : null;
91 public void onSessionUp(final NetconfClientSession session) {
94 LOG.debug("{}: Session established", id);
95 currentSession = session;
97 var netconfSessionPreferences = NetconfSessionPreferences.fromNetconfSession(session);
98 LOG.trace("{}: Session advertised capabilities: {}", id, netconfSessionPreferences);
100 final var localOverride = overrideNetconfCapabilities;
101 if (localOverride != null) {
102 final var sessionPreferences = localOverride.sessionPreferences();
103 netconfSessionPreferences = localOverride.overrideModuleCapabilities()
104 ? netconfSessionPreferences.replaceModuleCaps(sessionPreferences)
105 : netconfSessionPreferences.addModuleCaps(sessionPreferences);
107 netconfSessionPreferences = localOverride.overrideNonModuleCapabilities()
108 ? netconfSessionPreferences.replaceNonModuleCaps(sessionPreferences)
109 : netconfSessionPreferences.addNonModuleCaps(sessionPreferences);
110 LOG.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id,
111 netconfSessionPreferences);
114 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
116 sessionLock.unlock();
120 public void disconnect() {
121 // If session is already in closing, no need to close it again
122 if (currentSession != null && startClosing() && currentSession.isUp()) {
123 currentSession.close();
127 private void tearDown(final String reason) {
128 if (!isSessionClosing()) {
129 LOG.warn("It's curious that no one to close the session but tearDown is called!");
131 LOG.debug("Tearing down {}", reason);
132 final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = new ArrayList<>();
135 if (currentSession != null) {
136 currentSession = null;
138 * Walk all requests, check if they have been executing
139 * or cancelled and remove them from the queue.
141 final Iterator<Request> it = requests.iterator();
142 while (it.hasNext()) {
143 final Request r = it.next();
144 if (r.future.isUncancellable()) {
145 futuresToCancel.add(r.future);
147 } else if (r.future.isCancelled()) {
148 // This just does some house-cleaning
153 remoteDevice.onRemoteSessionDown();
156 sessionLock.unlock();
159 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
160 // blocking the caller.
161 for (final UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) {
162 if (Strings.isNullOrEmpty(reason)) {
163 future.set(createSessionDownRpcResult());
165 future.set(createErrorRpcResult(ErrorType.TRANSPORT, reason));
172 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
173 return createErrorRpcResult(ErrorType.TRANSPORT,
174 String.format("The netconf session to %1$s is disconnected", id.name()));
177 private static RpcResult<NetconfMessage> createErrorRpcResult(final ErrorType errorType, final String message) {
178 return RpcResultBuilder.<NetconfMessage>failed()
179 .withError(errorType, ErrorTag.OPERATION_FAILED, message).build();
183 public void onSessionDown(final NetconfClientSession session, final Exception exception) {
184 // If session is already in closing, no need to call tearDown again.
185 if (startClosing()) {
186 if (exception instanceof EOFException) {
187 LOG.info("{}: Session went down: {}", id, exception.getMessage());
189 LOG.warn("{}: Session went down", id, exception);
196 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
197 // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
198 LOG.warn("{}: Session terminated {}", id, reason);
199 tearDown(reason.getErrorMessage());
203 public void close() {
204 // Disconnect from device
205 // tear down not necessary, called indirectly by the close in disconnect()
210 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
212 * Dispatch between notifications and messages. Messages need to be processed
213 * with lock held, notifications do not.
215 if (isNotification(message)) {
216 processNotification(message);
218 processMessage(message);
223 public void onError(final NetconfClientSession session, final Exception failure) {
224 final Request request = pollRequest();
225 if (request != null) {
226 request.future.set(RpcResultBuilder.<NetconfMessage>failed()
227 .withRpcError(toRpcError(new DocumentedException(failure.getMessage(),
228 ErrorType.APPLICATION, ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR)))
231 LOG.warn("{}: Ignoring unsolicited failure {}", id, failure.toString());
235 private @Nullable Request pollRequest() {
240 request = requests.peek();
241 if (request != null && request.future.isUncancellable()) {
242 request = requests.poll();
243 // we have just removed one request from the queue
244 // we can also release one permit
245 if (semaphore != null) {
252 sessionLock.unlock();
257 private void processMessage(final NetconfMessage message) {
258 final Request request = pollRequest();
259 if (request == null) {
260 // No matching request, bail out
261 LOG.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
265 LOG.debug("{}: Message received {}", id, message);
267 if (LOG.isTraceEnabled()) {
268 LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
271 final String inputMsgId = request.request.getDocument().getDocumentElement()
272 .getAttribute(XmlNetconfConstants.MESSAGE_ID);
273 final String outputMsgId = message.getDocument().getDocumentElement()
274 .getAttribute(XmlNetconfConstants.MESSAGE_ID);
275 if (!inputMsgId.equals(outputMsgId)) {
276 // FIXME: we should be able to transform directly to RpcError without an intermediate exception
277 final var ex = new DocumentedException("Response message contained unknown \"message-id\"", null,
278 ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, ErrorSeverity.ERROR,
279 ImmutableMap.of("actual-message-id", outputMsgId, "expected-message-id", inputMsgId));
280 LOG.warn("{}: Invalid request-reply match, reply message contains different message-id, "
281 + "request: {}, response: {}", id, msgToS(request.request), msgToS(message));
283 request.future.set(RpcResultBuilder.<NetconfMessage>failed().withRpcError(toRpcError(ex)).build());
285 // recursively processing message to eventually find matching request
286 processMessage(message);
290 if (NetconfMessageUtil.isErrorMessage(message)) {
291 // FIXME: we should be able to transform directly to RpcError without an intermediate exception
292 final var ex = DocumentedException.fromXMLDocument(message.getDocument());
293 LOG.warn("{}: Error reply from remote device, request: {}, response: {}",
294 id, msgToS(request.request), msgToS(message));
295 request.future.set(RpcResultBuilder.<NetconfMessage>failed().withRpcError(toRpcError(ex)).build());
299 request.future.set(RpcResultBuilder.success(message).build());
302 private static String msgToS(final NetconfMessage msg) {
303 return XmlUtil.toString(msg.getDocument());
306 private static RpcError toRpcError(final DocumentedException ex) {
307 final var errorInfo = ex.getErrorInfo();
308 final String infoString;
309 if (errorInfo != null) {
310 final var sb = new StringBuilder();
311 for (var e : errorInfo.entrySet()) {
312 final var tag = e.getKey();
313 sb.append('<').append(tag).append('>').append(e.getValue()).append("</").append(tag).append('>');
315 infoString = sb.toString();
320 return ex.getErrorSeverity() == ErrorSeverity.ERROR
321 ? RpcResultBuilder.newError(ex.getErrorType(), ex.getErrorTag(), ex.getLocalizedMessage(), null,
322 infoString, ex.getCause())
323 : RpcResultBuilder.newWarning(ex.getErrorType(), ex.getErrorTag(), ex.getLocalizedMessage(), null,
324 infoString, ex.getCause());
328 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
331 if (semaphore != null && !semaphore.tryAcquire()) {
332 LOG.warn("Limit of concurrent rpc messages was reached (limit: {}). Rpc reply message is needed. "
333 + "Discarding request of Netconf device with id: {}", concurentRpcMsgs, id.name());
334 return Futures.immediateFailedFuture(new DocumentedException(
335 "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
336 + ") waiting for emptying the queue of Netconf device with id: " + id.name()));
339 return sendRequestWithLock(message, rpc);
341 sessionLock.unlock();
345 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
347 if (LOG.isTraceEnabled()) {
348 LOG.trace("{}: Sending message {}", id, msgToS(message));
351 if (currentSession == null) {
352 LOG.warn("{}: Session is disconnected, failing RPC request {}",
354 return Futures.immediateFuture(createSessionDownRpcResult());
357 final Request req = new Request(new UncancellableFuture<>(true), message);
360 currentSession.sendMessage(req.request).addListener(future -> {
361 if (!future.isSuccess()) {
362 // We expect that a session down will occur at this point
363 LOG.debug("{}: Failed to send request {}", id,
364 XmlUtil.toString(req.request.getDocument()),
367 if (future.cause() != null) {
368 req.future.set(createErrorRpcResult(ErrorType.TRANSPORT, future.cause().getLocalizedMessage()));
370 req.future.set(createSessionDownRpcResult()); // assume session is down
372 req.future.setException(future.cause());
374 LOG.trace("Finished sending request {}", req.request);
381 private void processNotification(final NetconfMessage notification) {
382 if (LOG.isTraceEnabled()) {
383 LOG.trace("{}: Notification received: {}", id, notification);
386 remoteDevice.onNotification(notification);
389 private static boolean isNotification(final NetconfMessage message) {
390 if (message.getDocument() == null) {
391 // We have no message, which mean we have a FailedNetconfMessage
394 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
395 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
398 private static final class Request {
399 final UncancellableFuture<RpcResult<NetconfMessage>> future;
400 final NetconfMessage request;
402 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
403 final NetconfMessage request) {
404 this.future = future;
405 this.request = request;
409 private boolean startClosing() {
410 return CLOSING_UPDATER.compareAndSet(this, 0, 1);