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