ONOS-5908 exclude removed Devices

- MastershipService#getDevicesOf is created based on Leadership topic,
  which can contain removed Device.

Change-Id: I2760d2af5cd766f5eb48fb1cba964300476bd64e
diff --git a/cli/src/main/java/org/onosproject/cli/MastersListCommand.java b/cli/src/main/java/org/onosproject/cli/MastersListCommand.java
index abda027..1357d64 100644
--- a/cli/src/main/java/org/onosproject/cli/MastersListCommand.java
+++ b/cli/src/main/java/org/onosproject/cli/MastersListCommand.java
@@ -24,11 +24,11 @@
 import org.onosproject.cluster.ControllerNode;
 import org.onosproject.mastership.MastershipService;
 import org.onosproject.net.DeviceId;
+import org.onosproject.net.device.DeviceService;
 import org.onosproject.utils.Comparators;
 
 import java.util.Collections;
 import java.util.List;
-
 import static com.google.common.collect.Lists.newArrayList;
 
 /**
@@ -42,6 +42,7 @@
     protected void execute() {
         ClusterService service = get(ClusterService.class);
         MastershipService mastershipService = get(MastershipService.class);
+        DeviceService deviceService = get(DeviceService.class);
         List<ControllerNode> nodes = newArrayList(service.getNodes());
         Collections.sort(nodes, Comparators.NODE_COMPARATOR);
 
@@ -50,6 +51,7 @@
         } else {
             for (ControllerNode node : nodes) {
                 List<DeviceId> ids = Lists.newArrayList(mastershipService.getDevicesOf(node.id()));
+                ids.removeIf(did -> deviceService.getDevice(did) == null);
                 Collections.sort(ids, Comparators.ELEMENT_ID_COMPARATOR);
                 print("%s: %d devices", node.id(), ids.size());
                 for (DeviceId deviceId : ids) {