[VOL-4065] Fix race condition between mastership and local leadership

Change-Id: I62251bfa97074c886af4e325993f87916749d624
diff --git a/app/src/main/java/org/opencord/cordmcast/impl/CordMcast.java b/app/src/main/java/org/opencord/cordmcast/impl/CordMcast.java
index 674121d..e1fed34 100644
--- a/app/src/main/java/org/opencord/cordmcast/impl/CordMcast.java
+++ b/app/src/main/java/org/opencord/cordmcast/impl/CordMcast.java
@@ -811,20 +811,24 @@
         return fwdBuilder;
     }
 
-    // Custom-built function, when the device is not available we need a fallback mechanism
+    /**
+     * Checks for mastership or falls back to leadership on deviceId.
+     * If the device is available use mastership,
+     * otherwise fallback on leadership.
+     * Leadership on the device topic is needed because the master can be NONE
+     * in case the device went away, we still need to handle events
+     * consistently
+     */
     private boolean isLocalLeader(DeviceId deviceId) {
-        if (!mastershipService.isLocalMaster(deviceId)) {
-            // When the device is available we just check the mastership
-            if (deviceService.isAvailable(deviceId)) {
-                return false;
-            }
+        if (deviceService.isAvailable(deviceId)) {
+            return mastershipService.isLocalMaster(deviceId);
+        } else {
             // Fallback with Leadership service - device id is used as topic
             NodeId leader = leadershipService.runForLeadership(
                     deviceId.toString()).leaderNodeId();
             // Verify if this node is the leader
             return clusterService.getLocalNode().id().equals(leader);
         }
-        return true;
     }
 
     private class InternalDeviceListener implements DeviceListener {
diff --git a/app/src/test/java/org/opencord/cordmcast/impl/McastTestBase.java b/app/src/test/java/org/opencord/cordmcast/impl/McastTestBase.java
index 1d6b815..214a283 100644
--- a/app/src/test/java/org/opencord/cordmcast/impl/McastTestBase.java
+++ b/app/src/test/java/org/opencord/cordmcast/impl/McastTestBase.java
@@ -306,6 +306,11 @@
             }
             return null;
         }
+
+        @Override
+        public boolean isAvailable(DeviceId deviceId) {
+            return true;
+        }
     }
 
      public OutputInstruction outputPort(TrafficTreatment trafficTreatment) {