[ONOS-7243] Check for existing device master before attempting to acquire mastership to mark device offline

Change-Id: I11c1b173d2bb7d866889d0d6d42b9e7e702c2e79
diff --git a/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java b/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java
index c9b4154..e348dd7 100644
--- a/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java
+++ b/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java
@@ -447,17 +447,20 @@
                 } else {
                     // check if the device has master, if not, mark it offline
                     // only the nodes which has mastership role can mark any device offline.
-                    CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
-                    roleFuture.thenAccept(role -> {
-                        MastershipTerm term = termService.getMastershipTerm(deviceId);
-                        if (term != null && localNodeId.equals(term.master())) {
-                            log.info("Marking unreachable device {} offline", deviceId);
-                            post(store.markOffline(deviceId));
-                        } else {
-                            log.info("Failed marking {} offline. {}", deviceId, role);
-                        }
-                        mastershipService.relinquishMastership(deviceId);
-                    });
+                    NodeId master = mastershipService.getMasterFor(deviceId);
+                    if (master == null) {
+                        CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
+                        roleFuture.thenAccept(role -> {
+                            MastershipTerm term = termService.getMastershipTerm(deviceId);
+                            if (term != null && localNodeId.equals(term.master())) {
+                                log.info("Marking unreachable device {} offline", deviceId);
+                                post(store.markOffline(deviceId));
+                            } else {
+                                log.info("Failed marking {} offline. {}", deviceId, role);
+                            }
+                            mastershipService.relinquishMastership(deviceId);
+                        });
+                    }
                 }
                 continue;
             }