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.NetconfReconnectingClientConfiguration;
22 import org.opendaylight.controller.netconf.util.xml.XmlElement;
23 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
24 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
25 import org.opendaylight.controller.sal.common.util.RpcErrors;
26 import org.opendaylight.controller.sal.common.util.Rpcs;
27 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
28 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
29 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
30 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
31 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.RpcError;
34 import org.opendaylight.yangtools.yang.common.RpcResult;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import com.google.common.util.concurrent.Futures;
39 import com.google.common.util.concurrent.ListenableFuture;
41 import io.netty.util.concurrent.Future;
42 import io.netty.util.concurrent.FutureListener;
44 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
46 private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
48 private static final RpcResult<NetconfMessage> FAILED_RPC_RESULT = new FailedRpcResult<>(RpcErrors.getRpcError(
49 null, null, null, RpcError.ErrorSeverity.ERROR, "Netconf session disconnected",
50 RpcError.ErrorType.PROTOCOL, null));
52 private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
53 private final RemoteDeviceId id;
55 public NetconfDeviceCommunicator(final RemoteDeviceId id,
56 final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
58 this.remoteDevice = remoteDevice;
61 private final Queue<Request> requests = new ArrayDeque<>();
62 private NetconfClientSession session;
65 public synchronized void onSessionUp(final NetconfClientSession session) {
66 logger.debug("{}: Session established", id);
67 this.session = session;
69 final NetconfSessionCapabilities netconfSessionCapabilities = NetconfSessionCapabilities.fromNetconfSession(session);
70 logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
72 remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
75 public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
76 final NetconfReconnectingClientConfiguration config) {
77 dispatch.createReconnectingClient(config);
80 private synchronized void tearDown(final Exception e) {
81 remoteDevice.onRemoteSessionDown();
85 * Walk all requests, check if they have been executing
86 * or cancelled and remove them from the queue.
88 final Iterator<Request> it = requests.iterator();
89 while (it.hasNext()) {
90 final Request r = it.next();
91 if (r.future.isUncancellable()) {
92 r.future.setException(e);
94 } else if (r.future.isCancelled()) {
95 // This just does some house-cleaning
102 public void onSessionDown(final NetconfClientSession session, final Exception e) {
103 logger.warn("{}: Session went down", id, e);
108 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
109 logger.warn("{}: Session terminated {}", id, reason);
110 tearDown(new RuntimeException(reason.getErrorMessage()));
114 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
116 * Dispatch between notifications and messages. Messages need to be processed
117 * with lock held, notifications do not.
119 if (isNotification(message)) {
120 processNotification(message);
122 processMessage(message);
126 private synchronized void processMessage(final NetconfMessage message) {
127 final Request r = requests.peek();
128 if (r.future.isUncancellable()) {
131 logger.debug("{}: Message received {}", id, message);
133 if(logger.isTraceEnabled()) {
134 logger.trace("{}: Matched request: {} to response: {}", id, msgToS(r.request), msgToS(message));
138 NetconfMessageTransformUtil.checkValidReply(r.request, message);
139 } catch (final IllegalStateException e) {
140 logger.warn("{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}", id,
141 msgToS(r.request), msgToS(message), e);
142 r.future.setException(e);
147 NetconfMessageTransformUtil.checkSuccessReply(message);
148 } catch (NetconfDocumentedException | IllegalStateException e) {
149 logger.warn("{}: Error reply from remote device, request: {}, response: {}", id,
150 msgToS(r.request), msgToS(message), e);
151 r.future.setException(e);
155 r.future.set(Rpcs.getRpcResult(true, message, Collections.<RpcError>emptySet()));
157 logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
162 public void close() {
163 tearDown(new RuntimeException("Closed"));
166 private static String msgToS(final NetconfMessage msg) {
167 return XmlUtil.toString(msg.getDocument());
171 public synchronized ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
172 if(logger.isTraceEnabled()) {
173 logger.trace("{}: Sending message {}", id, msgToS(message));
176 if (session == null) {
177 logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
178 return Futures.immediateFuture(FAILED_RPC_RESULT);
181 final Request req = new Request(new UncancellableFuture<RpcResult<NetconfMessage>>(true), message, rpc);
184 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
186 public void operationComplete(final Future<Void> future) throws Exception {
187 if (!future.isSuccess()) {
188 // We expect that a session down will occur at this point
189 logger.debug("{}: Failed to send request {}", id, XmlUtil.toString(req.request.getDocument()), future.cause());
190 req.future.setException(future.cause());
192 logger.trace("{}: Finished sending request {}", id, req.request);
200 private void processNotification(final NetconfMessage notification) {
201 logger.debug("{}: Notification received: {}", id, notification);
203 if(logger.isTraceEnabled()) {
204 logger.trace("{}: Notification received: {}", id, msgToS(notification));
207 remoteDevice.onNotification(notification);
210 private static boolean isNotification(final NetconfMessage message) {
211 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
212 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
215 private static final class Request {
216 final UncancellableFuture<RpcResult<NetconfMessage>> future;
217 final NetconfMessage request;
220 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future, final NetconfMessage request, final QName rpc) {
221 this.future = future;
222 this.request = request;