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.Queue;
15 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
16 import org.opendaylight.controller.netconf.api.NetconfMessage;
17 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
18 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
19 import org.opendaylight.controller.netconf.client.NetconfClientSession;
20 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
21 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
22 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
23 import org.opendaylight.controller.netconf.util.xml.XmlElement;
24 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
25 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
26 import org.opendaylight.controller.sal.common.util.RpcErrors;
27 import org.opendaylight.controller.sal.common.util.Rpcs;
28 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
29 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
30 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
31 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
32 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.RpcError;
35 import org.opendaylight.yangtools.yang.common.RpcResult;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 import com.google.common.util.concurrent.Futures;
40 import com.google.common.util.concurrent.ListenableFuture;
42 import io.netty.util.concurrent.Future;
43 import io.netty.util.concurrent.FutureListener;
45 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
47 private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
49 private static final RpcResult<NetconfMessage> FAILED_RPC_RESULT = new FailedRpcResult<>(RpcErrors.getRpcError(
50 null, null, null, RpcError.ErrorSeverity.ERROR, "Netconf session disconnected",
51 RpcError.ErrorType.PROTOCOL, null));
53 private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
54 private final RemoteDeviceId id;
56 public NetconfDeviceCommunicator(final RemoteDeviceId id,
57 final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
59 this.remoteDevice = remoteDevice;
62 private final Queue<Request> requests = new ArrayDeque<>();
63 private NetconfClientSession session;
66 public synchronized void onSessionUp(final NetconfClientSession session) {
67 logger.debug("{}: Session established", id);
68 this.session = session;
70 final NetconfSessionCapabilities netconfSessionCapabilities = NetconfSessionCapabilities.fromNetconfSession(session);
71 logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
73 remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
76 public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
77 final NetconfReconnectingClientConfiguration config) {
78 dispatch.createReconnectingClient(config);
81 private synchronized void tearDown(final Exception e) {
82 remoteDevice.onRemoteSessionDown();
86 * Walk all requests, check if they have been executing
87 * or cancelled and remove them from the queue.
89 final Iterator<Request> it = requests.iterator();
90 while (it.hasNext()) {
91 final Request r = it.next();
92 if (r.future.isUncancellable()) {
93 r.future.setException(e);
95 } else if (r.future.isCancelled()) {
96 // This just does some house-cleaning
103 public void onSessionDown(final NetconfClientSession session, final Exception e) {
104 logger.warn("{}: Session went down", id, e);
109 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
110 logger.warn("{}: Session terminated {}", id, reason);
111 tearDown(new RuntimeException(reason.getErrorMessage()));
115 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
117 * Dispatch between notifications and messages. Messages need to be processed
118 * with lock held, notifications do not.
120 if (isNotification(message)) {
121 processNotification(message);
123 processMessage(message);
127 private synchronized void processMessage(final NetconfMessage message) {
128 final Request r = requests.peek();
129 if (r.future.isUncancellable()) {
132 logger.debug("{}: Message received {}", id, message);
134 if(logger.isTraceEnabled()) {
135 logger.trace("{}: Matched request: {} to response: {}", id, msgToS(r.request), msgToS(message));
139 NetconfMessageTransformUtil.checkValidReply(r.request, message);
140 } catch (final IllegalStateException e) {
141 logger.warn("{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}", id,
142 msgToS(r.request), msgToS(message), e);
143 r.future.setException(e);
148 NetconfMessageTransformUtil.checkSuccessReply(message);
149 } catch (NetconfDocumentedException | IllegalStateException e) {
150 logger.warn("{}: Error reply from remote device, request: {}, response: {}", id,
151 msgToS(r.request), msgToS(message), e);
152 r.future.setException(e);
156 r.future.set(Rpcs.getRpcResult(true, message, Collections.<RpcError>emptySet()));
158 logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
163 public void close() {
164 tearDown(new RuntimeException("Closed"));
167 private static String msgToS(final NetconfMessage msg) {
168 return XmlUtil.toString(msg.getDocument());
172 public synchronized ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
173 if(logger.isTraceEnabled()) {
174 logger.trace("{}: Sending message {}", id, msgToS(message));
177 if (session == null) {
178 logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
179 return Futures.immediateFuture(FAILED_RPC_RESULT);
182 final Request req = new Request(new UncancellableFuture<RpcResult<NetconfMessage>>(true), message, rpc);
185 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
187 public void operationComplete(final Future<Void> future) throws Exception {
188 if (!future.isSuccess()) {
189 // We expect that a session down will occur at this point
190 logger.debug("{}: Failed to send request {}", id, XmlUtil.toString(req.request.getDocument()), future.cause());
191 req.future.setException(future.cause());
193 logger.trace("{}: Finished sending request {}", id, req.request);
201 private void processNotification(final NetconfMessage notification) {
202 logger.debug("{}: Notification received: {}", id, notification);
204 if(logger.isTraceEnabled()) {
205 logger.trace("{}: Notification received: {}", id, msgToS(notification));
208 remoteDevice.onNotification(notification);
211 private static boolean isNotification(final NetconfMessage message) {
212 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
213 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
216 private static final class Request {
217 final UncancellableFuture<RpcResult<NetconfMessage>> future;
218 final NetconfMessage request;
221 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future, final NetconfMessage request, final QName rpc) {
222 this.future = future;
223 this.request = request;