[ONOS-8106][ONOS-8107] Fix for netconf ssh session not initiating when a node goes down in cluster

Change-Id: If9c3208a299d8dfde763115cb873aba00fc35ef6
(cherry picked from commit 01ab40a03a95b009fef69f64a5bfc914b8f1bb14)
diff --git a/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfControllerImpl.java b/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfControllerImpl.java
index d0ee1f0..90f6d14 100644
--- a/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfControllerImpl.java
+++ b/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfControllerImpl.java
@@ -572,7 +572,10 @@
                     Set<String> forReturnValue = new LinkedHashSet<>(replyArguments);
                     return CompletableFuture.completedFuture((T) forReturnValue);
                 default:
-                    String returnValue = Optional.ofNullable(replyArguments.get(0)).orElse(null);
+                    String returnValue = null;
+                    if (!replyArguments.isEmpty()) {
+                        returnValue = Optional.ofNullable(replyArguments.get(0)).orElse(null);
+                    }
                     return CompletableFuture.completedFuture((T) returnValue);
             }
         } catch (InterruptedException e) {
diff --git a/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java b/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java
index 0d94c87..f52e612 100644
--- a/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java
+++ b/providers/netconf/device/src/main/java/org/onosproject/provider/netconf/device/impl/NetconfDeviceProvider.java
@@ -274,7 +274,8 @@
         if (active) {
             switch (newRole) {
                 case MASTER:
-                    if (controller.getNetconfDevice(deviceId) == null) {
+                    if (controller.getNetconfDevice(deviceId) == null ||
+                               !controller.getNetconfDevice(deviceId).isMasterSession()) {
                         connectionExecutor.execute(exceptionSafe(() -> withDeviceLock(
                                 () -> initiateConnection(deviceId), deviceId).run()));
                         log.debug("Accepting mastership role change to {} for device {}", newRole, deviceId);