Ayaka Koshibe | e8e4535 | 2014-10-16 00:37:19 -0700 | [diff] [blame^] | 1 | package org.onlab.onos.cli; |
| 2 | |
| 3 | import static com.google.common.collect.Lists.newArrayList; |
| 4 | |
| 5 | import java.util.Collections; |
| 6 | import java.util.List; |
| 7 | |
| 8 | import org.apache.karaf.shell.commands.Command; |
| 9 | import org.onlab.onos.cluster.NodeId; |
| 10 | import org.onlab.onos.mastership.MastershipService; |
| 11 | import org.onlab.onos.net.Device; |
| 12 | import org.onlab.onos.net.DeviceId; |
| 13 | import org.onlab.onos.net.device.DeviceService; |
| 14 | |
| 15 | |
| 16 | /** |
| 17 | * Lists mastership roles of nodes for each device. |
| 18 | */ |
| 19 | @Command(scope = "onos", name = "roles", |
| 20 | description = "Lists mastership roles of nodes for each device.") |
| 21 | public class RolesCommand extends AbstractShellCommand { |
| 22 | |
| 23 | private static final String FMT_HDR = "%s: master=%s\nstandbys: %s nodes"; |
| 24 | private static final String FMT_SB = "\t%s"; |
| 25 | |
| 26 | @Override |
| 27 | protected void execute() { |
| 28 | DeviceService deviceService = get(DeviceService.class); |
| 29 | MastershipService roleService = get(MastershipService.class); |
| 30 | |
| 31 | for (Device d : getSortedDevices(deviceService)) { |
| 32 | DeviceId did = d.id(); |
| 33 | printRoles(roleService, did); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Returns the list of devices sorted using the device ID URIs. |
| 39 | * |
| 40 | * @param service device service |
| 41 | * @return sorted device list |
| 42 | */ |
| 43 | protected static List<Device> getSortedDevices(DeviceService service) { |
| 44 | List<Device> devices = newArrayList(service.getDevices()); |
| 45 | Collections.sort(devices, Comparators.ELEMENT_COMPARATOR); |
| 46 | return devices; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Prints the role information for a device. |
| 51 | * |
| 52 | * @param deviceId the ID of the device |
| 53 | * @param master the current master |
| 54 | */ |
| 55 | protected void printRoles(MastershipService service, DeviceId deviceId) { |
| 56 | List<NodeId> nodes = service.getNodesFor(deviceId); |
| 57 | NodeId first = null; |
| 58 | NodeId master = null; |
| 59 | |
| 60 | if (!nodes.isEmpty()) { |
| 61 | first = nodes.get(0); |
| 62 | } |
| 63 | if (first != null && |
| 64 | first.equals(service.getMasterFor(deviceId))) { |
| 65 | master = nodes.get(0); |
| 66 | nodes.remove(master); |
| 67 | } |
| 68 | print(FMT_HDR, deviceId, master == null ? "NONE" : master, nodes.size()); |
| 69 | |
| 70 | for (NodeId nid : nodes) { |
| 71 | print(FMT_SB, nid); |
| 72 | } |
| 73 | } |
| 74 | } |