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