fa6e2522938cf40bbce4c759ea9c43871317c1f1
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / listener / NetconfDeviceCommunicator.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sal.connect.netconf.listener;
9
10 import java.util.ArrayDeque;
11 import java.util.Collections;
12 import java.util.Iterator;
13 import java.util.Queue;
14
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;
38
39 import com.google.common.util.concurrent.Futures;
40 import com.google.common.util.concurrent.ListenableFuture;
41
42 import io.netty.util.concurrent.Future;
43 import io.netty.util.concurrent.FutureListener;
44
45 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
46
47     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
48
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));
52
53     private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
54     private final RemoteDeviceId id;
55
56     public NetconfDeviceCommunicator(final RemoteDeviceId id,
57             final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
58         this.id = id;
59         this.remoteDevice = remoteDevice;
60     }
61
62     private final Queue<Request> requests = new ArrayDeque<>();
63     private NetconfClientSession session;
64
65     @Override
66     public synchronized void onSessionUp(final NetconfClientSession session) {
67         logger.debug("{}: Session established", id);
68         this.session = session;
69
70         final NetconfSessionCapabilities netconfSessionCapabilities = NetconfSessionCapabilities.fromNetconfSession(session);
71         logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
72
73         remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
74     }
75
76     public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
77                                            final NetconfReconnectingClientConfiguration config) {
78         dispatch.createReconnectingClient(config);
79     }
80
81     private synchronized void tearDown(final Exception e) {
82         remoteDevice.onRemoteSessionDown();
83         session = null;
84
85         /*
86          * Walk all requests, check if they have been executing
87          * or cancelled and remove them from the queue.
88          */
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);
94                 it.remove();
95             } else if (r.future.isCancelled()) {
96                 // This just does some house-cleaning
97                 it.remove();
98             }
99         }
100     }
101
102     @Override
103     public void onSessionDown(final NetconfClientSession session, final Exception e) {
104         logger.warn("{}: Session went down", id, e);
105         tearDown(e);
106     }
107
108     @Override
109     public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
110         logger.warn("{}: Session terminated {}", id, reason);
111         tearDown(new RuntimeException(reason.getErrorMessage()));
112     }
113
114     @Override
115     public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
116         /*
117          * Dispatch between notifications and messages. Messages need to be processed
118          * with lock held, notifications do not.
119          */
120         if (isNotification(message)) {
121             processNotification(message);
122         } else {
123             processMessage(message);
124         }
125     }
126
127     private synchronized void processMessage(final NetconfMessage message) {
128         final Request r = requests.peek();
129         if (r.future.isUncancellable()) {
130             requests.poll();
131
132             logger.debug("{}: Message received {}", id, message);
133
134             if(logger.isTraceEnabled()) {
135                 logger.trace("{}: Matched request: {} to response: {}", id, msgToS(r.request), msgToS(message));
136             }
137
138             try {
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);
144                 return;
145             }
146
147             try {
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);
153                 return;
154             }
155
156             r.future.set(Rpcs.getRpcResult(true, message, Collections.<RpcError>emptySet()));
157         } else {
158             logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
159         }
160     }
161
162     @Override
163     public void close() {
164         tearDown(new RuntimeException("Closed"));
165     }
166
167     private static String msgToS(final NetconfMessage msg) {
168         return XmlUtil.toString(msg.getDocument());
169     }
170
171     @Override
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));
175         }
176
177         if (session == null) {
178             logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
179             return Futures.immediateFuture(FAILED_RPC_RESULT);
180         }
181
182         final Request req = new Request(new UncancellableFuture<RpcResult<NetconfMessage>>(true), message, rpc);
183         requests.add(req);
184
185         session.sendMessage(req.request).addListener(new FutureListener<Void>() {
186             @Override
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());
192                 } else {
193                     logger.trace("{}: Finished sending request {}", id, req.request);
194                 }
195             }
196         });
197
198         return req.future;
199     }
200
201     private void processNotification(final NetconfMessage notification) {
202         logger.debug("{}: Notification received: {}", id, notification);
203
204         if(logger.isTraceEnabled()) {
205             logger.trace("{}: Notification received: {}", id, msgToS(notification));
206         }
207
208         remoteDevice.onNotification(notification);
209     }
210
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()) ;
214     }
215
216     private static final class Request {
217         final UncancellableFuture<RpcResult<NetconfMessage>> future;
218         final NetconfMessage request;
219         final QName rpc;
220
221         private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future, final NetconfMessage request, final QName rpc) {
222             this.future = future;
223             this.request = request;
224             this.rpc = rpc;
225         }
226     }
227 }