Bump odlparent to 5.0.0
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / KeepaliveSalFacade.java
index 59ce05edca3198cfe39b067dbe202e36cc4ac796..825cd380996b90a61ad7cb9e01e9b87b6b78ff29 100644 (file)
@@ -7,24 +7,20 @@
  */
 package org.opendaylight.netconf.sal.connect.netconf.sal;
 
+import static com.google.common.base.Preconditions.checkState;
 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps.getSourceNode;
 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_CONFIG_NODEID;
 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_CONFIG_PATH;
 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME;
 
-import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.FluentFuture;
 import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.MoreExecutors;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.mdsal.dom.api.DOMActionService;
 import org.opendaylight.mdsal.dom.api.DOMNotification;
 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
@@ -121,7 +117,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
     }
 
     void reconnect() {
-        Preconditions.checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
+        checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
         stopKeepalives();
         LOG.info("{}: Reconnecting inactive netconf session", id);
         listener.disconnect();
@@ -139,7 +135,8 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
             final DOMActionService deviceAction) {
         this.currentDeviceRpc = deviceRpc;
         final DOMRpcService deviceRpc1 =
-                new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
+                new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor,
+                        new ResponseWaitingScheduler());
 
         salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1, deviceAction);
 
@@ -149,7 +146,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
 
     private void scheduleKeepalives() {
         lastKeepAliveSucceeded.set(true);
-        Preconditions.checkState(currentDeviceRpc != null);
+        checkState(currentDeviceRpc != null);
         LOG.trace("{}: Scheduling keepalives every  {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
         currentKeepalive = executor.scheduleWithFixedDelay(new Keepalive(),
           keepaliveDelaySeconds, keepaliveDelaySeconds, TimeUnit.SECONDS);
@@ -196,14 +193,14 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
             LOG.trace("{}: Invoking keepalive RPC", id);
 
             try {
-                boolean lastJobSucceeded = lastKeepAliveSucceeded.getAndSet(false);
+                final boolean lastJobSucceeded = lastKeepAliveSucceeded.getAndSet(false);
                 if (!lastJobSucceeded) {
                     onFailure(new IllegalStateException("Previous keepalive timed out"));
                 } else {
-                    Futures.addCallback(currentDeviceRpc.invokeRpc(NETCONF_GET_CONFIG_PATH, KEEPALIVE_PAYLOAD), this,
+                    currentDeviceRpc.invokeRpc(NETCONF_GET_CONFIG_PATH, KEEPALIVE_PAYLOAD).addCallback(this,
                                         MoreExecutors.directExecutor());
                 }
-            } catch (NullPointerException e) {
+            } catch (final NullPointerException e) {
                 LOG.debug("{}: Skipping keepalive while reconnecting", id);
                 // Empty catch block intentional
                 // Do nothing. The currentDeviceRpc was null and it means we hit the reconnect window and
@@ -218,9 +215,15 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
         public void onSuccess(final DOMRpcResult result) {
             // No matter what response we got, rpc-reply or rpc-error,
             // we got it from device so the netconf session is OK
-            if (result != null && result.getResult() != null) {
+            if (result == null) {
+                LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
+                reconnect();
+                return;
+            }
+
+            if (result.getResult() != null) {
                 lastKeepAliveSucceeded.set(true);
-            }  else if (result != null && result.getErrors() != null) {
+            }  else if (result.getErrors() != null) {
                 LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
                 lastKeepAliveSucceeded.set(true);
             } else {
@@ -230,7 +233,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
         }
 
         @Override
-        public void onFailure(@Nonnull final Throwable throwable) {
+        public void onFailure(final Throwable throwable) {
             LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
             reconnect();
         }
@@ -241,14 +244,14 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
      */
     private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
         @Override
-        public void onSuccess(@Nullable final DOMRpcResult result) {
+        public void onSuccess(final DOMRpcResult result) {
             // No matter what response we got,
             // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
             resetKeepalive();
         }
 
         @Override
-        public void onFailure(@Nonnull final Throwable throwable) {
+        public void onFailure(final Throwable throwable) {
             // User/Application RPC failed (The RPC did not reach the remote device or ..
             // TODO what other reasons could cause this ?)
             // There is no point in keeping this session. Reconnect.
@@ -257,6 +260,63 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
         }
     }
 
+    private final class ResponseWaitingScheduler {
+
+        private ScheduledFuture<?> schedule;
+
+        public void initScheduler(final Runnable runnable) {
+            if (currentKeepalive != null) {
+                currentKeepalive.cancel(true);
+            } else {
+                LOG.trace("Keepalive does not exist.");
+            }
+            scheduleKeepalives();
+            //Listening on the result should be done before the keepalive rpc will be send
+            final long delay = (keepaliveDelaySeconds * 1000) - 500;
+            schedule = executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
+        }
+
+        public void stopScheduler() {
+            if (schedule != null) {
+                schedule.cancel(true);
+            } else {
+                LOG.trace("Scheduler does not exist.");
+            }
+        }
+    }
+
+    private static final class ResponseWaiting implements Runnable {
+
+        private final FluentFuture<DOMRpcResult> rpcResultFuture;
+        private final ResponseWaitingScheduler responseWaitingScheduler;
+
+        ResponseWaiting(final ResponseWaitingScheduler responseWaitingScheduler,
+                final FluentFuture<DOMRpcResult> rpcResultFuture) {
+            this.responseWaitingScheduler = responseWaitingScheduler;
+            this.rpcResultFuture = rpcResultFuture;
+        }
+
+        public void start() {
+            LOG.trace("Start to waiting for result.");
+            responseWaitingScheduler.initScheduler(this);
+        }
+
+        public void stop() {
+            LOG.info("Stop to waiting for result.");
+            responseWaitingScheduler.stopScheduler();
+        }
+
+        @Override
+        public void run() {
+            if (!rpcResultFuture.isCancelled() && !rpcResultFuture.isDone()) {
+                LOG.trace("Waiting for result");
+                responseWaitingScheduler.initScheduler(this);
+            } else {
+                LOG.trace("Result has been cancelled or done.");
+            }
+        }
+    }
+
     /*
      * Request timeout task is called once the defaultRequestTimeoutMillis is
      * reached. At this moment, if the request is not yet finished, we cancel
@@ -265,9 +325,11 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
     private static final class RequestTimeoutTask implements Runnable {
 
         private final FluentFuture<DOMRpcResult> rpcResultFuture;
+        private final ResponseWaiting responseWaiting;
 
-        RequestTimeoutTask(final FluentFuture<DOMRpcResult> rpcResultFuture) {
+        RequestTimeoutTask(final FluentFuture<DOMRpcResult> rpcResultFuture, final ResponseWaiting responseWaiting) {
             this.rpcResultFuture = rpcResultFuture;
+            this.responseWaiting = responseWaiting;
         }
 
         @Override
@@ -275,6 +337,9 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
             if (!rpcResultFuture.isDone()) {
                 rpcResultFuture.cancel(true);
             }
+            if (responseWaiting != null) {
+                responseWaiting.stop();
+            }
         }
     }
 
@@ -288,35 +353,37 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
         private final ResetKeepalive resetKeepaliveTask;
         private final long defaultRequestTimeoutMillis;
         private final ScheduledExecutorService executor;
+        private final ResponseWaitingScheduler responseWaitingScheduler;
 
         KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
-                final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
+                final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor,
+                final ResponseWaitingScheduler responseWaitingScheduler) {
             this.deviceRpc = deviceRpc;
             this.resetKeepaliveTask = resetKeepaliveTask;
             this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
             this.executor = executor;
+            this.responseWaitingScheduler = responseWaitingScheduler;
         }
 
         public DOMRpcService getDeviceRpc() {
             return deviceRpc;
         }
 
-        @Nonnull
         @Override
-        public @NonNull FluentFuture<DOMRpcResult> invokeRpc(@Nonnull final SchemaPath type,
-                                                                      final NormalizedNode<?, ?> input) {
+        public FluentFuture<DOMRpcResult> invokeRpc(final SchemaPath type, final NormalizedNode<?, ?> input) {
             final FluentFuture<DOMRpcResult> rpcResultFuture = deviceRpc.invokeRpc(type, input);
-            Futures.addCallback(rpcResultFuture, resetKeepaliveTask, MoreExecutors.directExecutor());
+            final ResponseWaiting responseWaiting = new ResponseWaiting(responseWaitingScheduler, rpcResultFuture);
+            responseWaiting.start();
+            rpcResultFuture.addCallback(resetKeepaliveTask, MoreExecutors.directExecutor());
 
-            final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(rpcResultFuture);
+            final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(rpcResultFuture, responseWaiting);
             executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
 
             return rpcResultFuture;
         }
 
         @Override
-        public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
-                @Nonnull final T listener) {
+        public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) {
             // There is no real communication with the device (yet), no reset here
             return deviceRpc.registerRpcListener(listener);
         }