Merge "add partial match for non-module capabilities - to enable deviations in base...
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / KeepaliveSalFacade.java
1 /*
2  * Copyright (c) 2015 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.sal;
9
10 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps.getSourceNode;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
14
15 import com.google.common.base.Preconditions;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
25 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
26 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
27 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
28 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
29 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
30 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
31 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
32 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
33 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
34 import org.opendaylight.yangtools.concepts.ListenerRegistration;
35 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * SalFacade proxy that invokes keepalive RPCs to prevent session shutdown from remote device
44  * and to detect incorrect session drops (netconf session is inactive, but TCP/SSH connection is still present).
45  * The keepalive RPC is a get-config with empty filter.
46  */
47 public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSessionPreferences> {
48
49     private static final Logger LOG = LoggerFactory.getLogger(KeepaliveSalFacade.class);
50
51     // 2 minutes keepalive delay by default
52     private static final long DEFAULT_DELAY = TimeUnit.MINUTES.toSeconds(2);
53
54     // 1 minute transaction timeout by default
55     private static final long DEFAULT_TRANSACTION_TIMEOUT_MILLI = TimeUnit.MILLISECONDS.toMillis(60000);
56
57     private final RemoteDeviceId id;
58     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
59     private final ScheduledExecutorService executor;
60     private final long keepaliveDelaySeconds;
61     private final ResetKeepalive resetKeepaliveTask;
62     private final long defaultRequestTimeoutMillis;
63
64     private volatile NetconfDeviceCommunicator listener;
65     private volatile ScheduledFuture<?> currentKeepalive;
66     private volatile DOMRpcService currentDeviceRpc;
67
68     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
69                               final ScheduledExecutorService executor, final long keepaliveDelaySeconds, final long defaultRequestTimeoutMillis) {
70         this.id = id;
71         this.salFacade = salFacade;
72         this.executor = executor;
73         this.keepaliveDelaySeconds = keepaliveDelaySeconds;
74         this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
75         this.resetKeepaliveTask = new ResetKeepalive();
76     }
77
78     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
79                               final ScheduledExecutorService executor) {
80         this(id, salFacade, executor, DEFAULT_DELAY, DEFAULT_TRANSACTION_TIMEOUT_MILLI);
81     }
82
83     /**
84      * Set the netconf session listener whenever ready
85      *
86      * @param listener netconf session listener
87      */
88     public void setListener(final NetconfDeviceCommunicator listener) {
89         this.listener = listener;
90     }
91
92     /**
93      * Just cancel current keepalive task.
94      * If its already started, let it finish ... not such a big deal.
95      *
96      * Then schedule next keepalive.
97      */
98     private void resetKeepalive() {
99         LOG.trace("{}: Resetting netconf keepalive timer", id);
100         if(currentKeepalive != null) {
101             currentKeepalive.cancel(false);
102         }
103         scheduleKeepalive();
104     }
105
106     /**
107      * Cancel current keepalive and also reset current deviceRpc
108      */
109     private void stopKeepalives() {
110         if(currentKeepalive != null) {
111             currentKeepalive.cancel(false);
112         }
113         currentDeviceRpc = null;
114     }
115
116     private void reconnect() {
117         Preconditions.checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
118         stopKeepalives();
119         LOG.info("{}: Reconnecting inactive netconf session", id);
120         listener.disconnect();
121     }
122
123     @Override
124     public void onDeviceConnected(final SchemaContext remoteSchemaContext, final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
125         this.currentDeviceRpc = deviceRpc;
126         final DOMRpcService deviceRpc1 = new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
127         salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
128
129         LOG.debug("{}: Netconf session initiated, starting keepalives", id);
130         scheduleKeepalive();
131     }
132
133     private void scheduleKeepalive() {
134         Preconditions.checkState(currentDeviceRpc != null);
135         LOG.trace("{}: Scheduling next keepalive in {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
136         currentKeepalive = executor.schedule(new Keepalive(currentKeepalive), keepaliveDelaySeconds, TimeUnit.SECONDS);
137     }
138
139     @Override
140     public void onDeviceDisconnected() {
141         stopKeepalives();
142         salFacade.onDeviceDisconnected();
143     }
144
145     @Override
146     public void onDeviceFailed(final Throwable throwable) {
147         stopKeepalives();
148         salFacade.onDeviceFailed(throwable);
149     }
150
151     @Override
152     public void onNotification(final DOMNotification domNotification) {
153         resetKeepalive();
154         salFacade.onNotification(domNotification);
155     }
156
157     @Override
158     public void close() {
159         stopKeepalives();
160         salFacade.close();
161     }
162
163     // Keepalive RPC static resources
164     private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
165     private static final ContainerNode KEEPALIVE_PAYLOAD =
166             NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
167
168     /**
169      * Invoke keepalive RPC and check the response. In case of any received response the keepalive
170      * is considered successful and schedules next keepalive with a fixed delay. If the response is unsuccessful (no
171      * response received, or the rcp could not even be sent) immediate reconnect is triggered as netconf session
172      * is considered inactive/failed.
173      */
174     private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
175
176         private final ScheduledFuture<?> previousKeepalive;
177
178         public Keepalive(final ScheduledFuture<?> previousKeepalive) {
179             this.previousKeepalive = previousKeepalive;
180         }
181
182         @Override
183         public void run() {
184             LOG.trace("{}: Invoking keepalive RPC", id);
185
186             try {
187                 if(previousKeepalive != null && !previousKeepalive.isDone()) {
188                     onFailure(new IllegalStateException("Previous keepalive timed out"));
189                 } else {
190                     Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this);
191                 }
192             } catch (NullPointerException e) {
193                 LOG.debug("{}: Skipping keepalive while reconnecting", id);
194                 // Empty catch block intentional
195                 // Do nothing. The currentDeviceRpc was null and it means we hit the reconnect window and
196                 // attempted to send keepalive while we were reconnecting. Next keepalive will be scheduled
197                 // after reconnect so no action necessary here.
198             }
199         }
200
201         @Override
202         public void onSuccess(final DOMRpcResult result) {
203             if (result != null && result.getResult() != null) {
204                 LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
205                 scheduleKeepalive();
206             } else {
207                 LOG.warn("{} Keepalive RPC returned null with response: {}. Reconnecting netconf session", id, result);
208                 reconnect();
209             }
210         }
211
212         @Override
213         public void onFailure(@Nonnull final Throwable t) {
214             LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, t);
215             reconnect();
216         }
217     }
218
219     /**
220      * Reset keepalive after each RPC response received
221      */
222     private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
223         @Override
224         public void onSuccess(@Nullable final DOMRpcResult result) {
225             // No matter what response we got, rpc-reply or rpc-error, we got it from device so the netconf session is OK
226             resetKeepalive();
227         }
228
229         @Override
230         public void onFailure(@Nonnull final Throwable t) {
231             // User/Application RPC failed (The RPC did not reach the remote device or .. TODO what other reasons could cause this ?)
232             // There is no point in keeping this session. Reconnect.
233             LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, t);
234             reconnect();
235         }
236     }
237
238     /*
239      * Request timeout task is called once the defaultRequestTimeoutMillis is
240      * reached. At this moment, if the request is not yet finished, we cancel
241      * it.
242      */
243     private static final class RequestTimeoutTask implements Runnable {
244
245         private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
246
247         public RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
248             this.rpcResultFuture = rpcResultFuture;
249         }
250
251         @Override
252         public void run() {
253             if (!rpcResultFuture.isDone()) {
254                 rpcResultFuture.cancel(true);
255             }
256         }
257     }
258
259     /**
260      * DOMRpcService proxy that attaches reset-keepalive-task and schedule
261      * request-timeout-task to each RPC invocation.
262      */
263     private static final class KeepaliveDOMRpcService implements DOMRpcService {
264
265         private final DOMRpcService deviceRpc;
266         private ResetKeepalive resetKeepaliveTask;
267         private final long defaultRequestTimeoutMillis;
268         private final ScheduledExecutorService executor;
269
270         public KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
271                 final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
272             this.deviceRpc = deviceRpc;
273             this.resetKeepaliveTask = resetKeepaliveTask;
274             this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
275             this.executor = executor;
276         }
277
278         @Nonnull
279         @Override
280         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, final NormalizedNode<?, ?> input) {
281             final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture = deviceRpc.invokeRpc(type, input);
282             Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask);
283
284             final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
285             executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
286
287             return domRpcResultDOMRpcExceptionCheckedFuture;
288         }
289
290         @Override
291         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
292             // There is no real communication with the device (yet), no reset here
293             return deviceRpc.registerRpcListener(listener);
294         }
295     }
296 }