510de677852c6203b7e0c91eba0a1ea0aabbba55
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / 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.netconf.sal.connect.netconf.listener;
9
10 import com.google.common.base.Strings;
11 import com.google.common.util.concurrent.ListenableFuture;
12 import com.google.common.util.concurrent.SettableFuture;
13 import io.netty.util.concurrent.Future;
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.Optional;
20 import java.util.Queue;
21 import java.util.concurrent.Semaphore;
22 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
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.util.concurrent.FluentFutures;
42 import org.opendaylight.yangtools.yang.common.Empty;
43 import org.opendaylight.yangtools.yang.common.ErrorTag;
44 import org.opendaylight.yangtools.yang.common.ErrorType;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.common.RpcResult;
47 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator {
52     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
53
54     protected final RemoteDevice<NetconfDeviceCommunicator> remoteDevice;
55     private final Optional<UserPreferences> overrideNetconfCapabilities;
56     protected final RemoteDeviceId id;
57     private final Lock sessionLock = new ReentrantLock();
58
59     private final Semaphore semaphore;
60     private final int concurentRpcMsgs;
61
62     private final Queue<Request> requests = new ArrayDeque<>();
63     private NetconfClientSession currentSession;
64
65     private final SettableFuture<Empty> firstConnectionFuture = SettableFuture.create();
66     private Future<?> taskFuture;
67
68     // isSessionClosing indicates a close operation on the session is issued and
69     // tearDown will surely be called later to finish the close.
70     // Used to allow only one thread to enter tearDown and other threads should
71     // NOT enter it simultaneously and should end its close operation without
72     // calling tearDown to release the locks they hold to avoid deadlock.
73     private static final AtomicIntegerFieldUpdater<NetconfDeviceCommunicator> CLOSING_UPDATER =
74             AtomicIntegerFieldUpdater.newUpdater(NetconfDeviceCommunicator.class, "closing");
75     private volatile int closing;
76
77     public boolean isSessionClosing() {
78         return closing != 0;
79     }
80
81     public NetconfDeviceCommunicator(final RemoteDeviceId id,
82             final RemoteDevice<NetconfDeviceCommunicator> remoteDevice,
83             final UserPreferences netconfSessionPreferences, final int rpcMessageLimit) {
84         this(id, remoteDevice, Optional.of(netconfSessionPreferences), rpcMessageLimit);
85     }
86
87     public NetconfDeviceCommunicator(final RemoteDeviceId id,
88             final RemoteDevice<NetconfDeviceCommunicator> remoteDevice, final int rpcMessageLimit) {
89         this(id, remoteDevice, Optional.empty(), rpcMessageLimit);
90     }
91
92     private NetconfDeviceCommunicator(final RemoteDeviceId id,
93             final RemoteDevice<NetconfDeviceCommunicator> remoteDevice,
94             final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
95         concurentRpcMsgs = rpcMessageLimit;
96         this.id = id;
97         this.remoteDevice = remoteDevice;
98         this.overrideNetconfCapabilities = overrideNetconfCapabilities;
99         semaphore = rpcMessageLimit > 0 ? new Semaphore(rpcMessageLimit) : null;
100     }
101
102     @Override
103     public void onSessionUp(final NetconfClientSession session) {
104         sessionLock.lock();
105         try {
106             LOG.debug("{}: Session established", id);
107             currentSession = session;
108
109             NetconfSessionPreferences netconfSessionPreferences =
110                                              NetconfSessionPreferences.fromNetconfSession(session);
111             LOG.trace("{}: Session advertised capabilities: {}", id,
112                     netconfSessionPreferences);
113
114             if (overrideNetconfCapabilities.isPresent()) {
115                 final NetconfSessionPreferences sessionPreferences = overrideNetconfCapabilities
116                         .get().getSessionPreferences();
117                 netconfSessionPreferences = overrideNetconfCapabilities.get().moduleBasedCapsOverrided()
118                         ? netconfSessionPreferences.replaceModuleCaps(sessionPreferences)
119                         : netconfSessionPreferences.addModuleCaps(sessionPreferences);
120
121                 netconfSessionPreferences = overrideNetconfCapabilities.get().nonModuleBasedCapsOverrided()
122                         ? netconfSessionPreferences.replaceNonModuleCaps(sessionPreferences)
123                         : netconfSessionPreferences.addNonModuleCaps(sessionPreferences);
124                 LOG.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id,
125                         netconfSessionPreferences);
126             }
127
128             remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
129         } finally {
130             sessionLock.unlock();
131         }
132
133         // FIXME: right, except ... this does not include the device schema setup, so is it really useful?
134         if (!firstConnectionFuture.set(Empty.value())) {
135             LOG.trace("{}: First connection already completed", id);
136         }
137     }
138
139     /**
140      * Initialize remote connection.
141      *
142      * @param dispatcher {@code NetconfCLientDispatcher}
143      * @param config     {@code NetconfClientConfiguration}
144      * @return a ListenableFuture that returns success on first successful connection and failure when the underlying
145      *         reconnecting strategy runs out of reconnection attempts
146      */
147     public ListenableFuture<Empty> initializeRemoteConnection(final NetconfClientDispatcher dispatcher,
148             final NetconfClientConfiguration config) {
149
150         final Future<?> connectFuture;
151         if (config instanceof NetconfReconnectingClientConfiguration) {
152             // FIXME: This is weird. If I understand it correctly we want to know about the first connection so as to
153             //        forward error state. Analyze the call graph to understand what is going on here. We really want
154             //        to move reconnection away from the socket layer, so that it can properly interface with sessions
155             //        and generally has some event-driven state (as all good network glue does). There is a second story
156             //        which is we want to avoid duplicate code, so it depends on other users as well.
157             final var future = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
158             taskFuture = future;
159             connectFuture = future.firstSessionFuture();
160         } else {
161             taskFuture = connectFuture = dispatcher.createClient(config);
162         }
163
164         connectFuture.addListener(future -> {
165             if (!future.isSuccess() && !future.isCancelled()) {
166                 LOG.debug("{}: Connection failed", id, future.cause());
167                 remoteDevice.onRemoteSessionFailed(future.cause());
168                 if (!firstConnectionFuture.isDone()) {
169                     firstConnectionFuture.setException(future.cause());
170                 }
171             }
172         });
173         return firstConnectionFuture;
174     }
175
176     public void disconnect() {
177         // If session is already in closing, no need to close it again
178         if (currentSession != null && startClosing() && currentSession.isUp()) {
179             currentSession.close();
180         }
181     }
182
183     private void tearDown(final String reason) {
184         if (!isSessionClosing()) {
185             LOG.warn("It's curious that no one to close the session but tearDown is called!");
186         }
187         LOG.debug("Tearing down {}", reason);
188         final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = new ArrayList<>();
189         sessionLock.lock();
190         try {
191             if (currentSession != null) {
192                 currentSession = null;
193                 /*
194                  * Walk all requests, check if they have been executing
195                  * or cancelled and remove them from the queue.
196                  */
197                 final Iterator<Request> it = requests.iterator();
198                 while (it.hasNext()) {
199                     final Request r = it.next();
200                     if (r.future.isUncancellable()) {
201                         futuresToCancel.add(r.future);
202                         it.remove();
203                     } else if (r.future.isCancelled()) {
204                         // This just does some house-cleaning
205                         it.remove();
206                     }
207                 }
208
209                 remoteDevice.onRemoteSessionDown();
210             }
211         } finally {
212             sessionLock.unlock();
213         }
214
215         // Notify pending request futures outside of the sessionLock to avoid unnecessarily
216         // blocking the caller.
217         for (final UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) {
218             if (Strings.isNullOrEmpty(reason)) {
219                 future.set(createSessionDownRpcResult());
220             } else {
221                 future.set(createErrorRpcResult(ErrorType.TRANSPORT, reason));
222             }
223         }
224
225         closing = 0;
226     }
227
228     private RpcResult<NetconfMessage> createSessionDownRpcResult() {
229         return createErrorRpcResult(ErrorType.TRANSPORT,
230                 String.format("The netconf session to %1$s is disconnected", id.getName()));
231     }
232
233     private static RpcResult<NetconfMessage> createErrorRpcResult(final ErrorType errorType, final String message) {
234         return RpcResultBuilder.<NetconfMessage>failed()
235             .withError(errorType, ErrorTag.OPERATION_FAILED, message).build();
236     }
237
238     @Override
239     public void onSessionDown(final NetconfClientSession session, final Exception exception) {
240         // If session is already in closing, no need to call tearDown again.
241         if (startClosing()) {
242             if (exception instanceof EOFException) {
243                 LOG.info("{}: Session went down: {}", id, exception.getMessage());
244             } else {
245                 LOG.warn("{}: Session went down", id, exception);
246             }
247             tearDown(null);
248         }
249     }
250
251     @Override
252     public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
253         // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
254         LOG.warn("{}: Session terminated {}", id, reason);
255         tearDown(reason.getErrorMessage());
256     }
257
258     @Override
259     public void close() {
260         // Cancel reconnect if in progress
261         if (taskFuture != null) {
262             taskFuture.cancel(false);
263         }
264         // Disconnect from device
265         // tear down not necessary, called indirectly by the close in disconnect()
266         disconnect();
267     }
268
269     @Override
270     public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
271         /*
272          * Dispatch between notifications and messages. Messages need to be processed
273          * with lock held, notifications do not.
274          */
275         if (isNotification(message)) {
276             processNotification(message);
277         } else {
278             processMessage(message);
279         }
280     }
281
282     private void processMessage(final NetconfMessage message) {
283         Request request = null;
284         sessionLock.lock();
285
286         try {
287             request = requests.peek();
288             if (request != null && request.future.isUncancellable()) {
289                 request = requests.poll();
290                 // we have just removed one request from the queue
291                 // we can also release one permit
292                 if (semaphore != null) {
293                     semaphore.release();
294                 }
295             } else {
296                 request = null;
297                 LOG.warn("{}: Ignoring unsolicited message {}", id,
298                         msgToS(message));
299             }
300         } finally {
301             sessionLock.unlock();
302         }
303
304         if (request == null) {
305             // No matching request, bail out
306             return;
307         }
308
309
310         if (message instanceof FailedNetconfMessage) {
311             request.future.set(NetconfMessageTransformUtil.toRpcResult((FailedNetconfMessage) message));
312             return;
313         }
314
315         LOG.debug("{}: Message received {}", id, message);
316
317         if (LOG.isTraceEnabled()) {
318             LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
319         }
320
321         try {
322             NetconfMessageTransformUtil.checkValidReply(request.request, message);
323         } catch (final NetconfDocumentedException e) {
324             LOG.warn("{}: Invalid request-reply match, reply message contains different message-id, "
325                 + "request: {}, response: {}", id, msgToS(request.request), msgToS(message), e);
326
327             request.future.set(RpcResultBuilder.<NetconfMessage>failed()
328                 .withRpcError(NetconfMessageTransformUtil.toRpcError(e))
329                 .build());
330
331             //recursively processing message to eventually find matching request
332             processMessage(message);
333             return;
334         }
335
336         try {
337             NetconfMessageTransformUtil.checkSuccessReply(message);
338         } catch (final NetconfDocumentedException e) {
339             LOG.warn("{}: Error reply from remote device, request: {}, response: {}",
340                 id, msgToS(request.request), msgToS(message), e);
341
342             request.future.set(RpcResultBuilder.<NetconfMessage>failed()
343                 .withRpcError(NetconfMessageTransformUtil.toRpcError(e))
344                 .build());
345             return;
346         }
347
348         request.future.set(RpcResultBuilder.success(message).build());
349     }
350
351     private static String msgToS(final NetconfMessage msg) {
352         return XmlUtil.toString(msg.getDocument());
353     }
354
355     @Override
356     public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
357         sessionLock.lock();
358         try {
359             if (semaphore != null && !semaphore.tryAcquire()) {
360                 LOG.warn("Limit of concurrent rpc messages was reached (limit: {}). Rpc reply message is needed. "
361                     + "Discarding request of Netconf device with id: {}", concurentRpcMsgs, id.getName());
362                 return FluentFutures.immediateFailedFluentFuture(new NetconfDocumentedException(
363                         "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
364                         + ") waiting for emptying the queue of Netconf device with id: " + id.getName()));
365             }
366
367             return sendRequestWithLock(message, rpc);
368         } finally {
369             sessionLock.unlock();
370         }
371     }
372
373     private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
374                                                                             final QName rpc) {
375         if (LOG.isTraceEnabled()) {
376             LOG.trace("{}: Sending message {}", id, msgToS(message));
377         }
378
379         if (currentSession == null) {
380             LOG.warn("{}: Session is disconnected, failing RPC request {}",
381                     id, message);
382             return FluentFutures.immediateFluentFuture(createSessionDownRpcResult());
383         }
384
385         final Request req = new Request(new UncancellableFuture<>(true), message);
386         requests.add(req);
387
388         currentSession.sendMessage(req.request).addListener(future -> {
389             if (!future.isSuccess()) {
390                 // We expect that a session down will occur at this point
391                 LOG.debug("{}: Failed to send request {}", id,
392                         XmlUtil.toString(req.request.getDocument()),
393                         future.cause());
394
395                 if (future.cause() != null) {
396                     req.future.set(createErrorRpcResult(ErrorType.TRANSPORT, future.cause().getLocalizedMessage()));
397                 } else {
398                     req.future.set(createSessionDownRpcResult()); // assume session is down
399                 }
400                 req.future.setException(future.cause());
401             } else {
402                 LOG.trace("Finished sending request {}", req.request);
403             }
404         });
405
406         return req.future;
407     }
408
409     private void processNotification(final NetconfMessage notification) {
410         if (LOG.isTraceEnabled()) {
411             LOG.trace("{}: Notification received: {}", id, notification);
412         }
413
414         remoteDevice.onNotification(notification);
415     }
416
417     private static boolean isNotification(final NetconfMessage message) {
418         if (message.getDocument() == null) {
419             // We have no message, which mean we have a FailedNetconfMessage
420             return false;
421         }
422         final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
423         return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
424     }
425
426     private static final class Request {
427         final UncancellableFuture<RpcResult<NetconfMessage>> future;
428         final NetconfMessage request;
429
430         private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
431                         final NetconfMessage request) {
432             this.future = future;
433             this.request = request;
434         }
435     }
436
437     private boolean startClosing() {
438         return CLOSING_UPDATER.compareAndSet(this, 0, 1);
439     }
440 }