blob: 7cbf61930e2725760dc38a8a741db07c49cc67b8 [file] [log] [blame]
Jordan Haltermand07f6722018-10-11 15:25:07 -07001/*
2 * Copyright 2014-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.cli;
17
18import java.util.Collections;
19import java.util.Comparator;
20import java.util.List;
21
22import com.fasterxml.jackson.databind.JsonNode;
23import com.fasterxml.jackson.databind.ObjectMapper;
24import com.fasterxml.jackson.databind.node.ArrayNode;
25import com.fasterxml.jackson.databind.node.ObjectNode;
Ray Milkey0b18b722018-10-16 13:19:15 -070026import org.apache.karaf.shell.api.action.Command;
27import org.apache.karaf.shell.api.action.lifecycle.Service;
Jordan Haltermand07f6722018-10-11 15:25:07 -070028import org.onosproject.cluster.ClusterAdminService;
29import org.onosproject.cluster.Node;
30
31import static com.google.common.collect.Lists.newArrayList;
32
33/**
34 * Lists all storage nodes.
35 */
Ray Milkey0b18b722018-10-16 13:19:15 -070036@Service
Jordan Haltermand07f6722018-10-11 15:25:07 -070037@Command(scope = "onos", name = "storage-nodes", description = "Lists all storage nodes")
38public class StorageNodesListCommand extends AbstractShellCommand {
39
40 private static final String FMT = "id=%s, address=%s:%s";
41
42 @Override
Ray Milkey0b18b722018-10-16 13:19:15 -070043 protected void doExecute() {
Jordan Haltermand07f6722018-10-11 15:25:07 -070044 ClusterAdminService service = get(ClusterAdminService.class);
45 List<Node> nodes = newArrayList(service.getConsensusNodes());
46 Collections.sort(nodes, Comparator.comparing(Node::id));
47 if (outputJson()) {
48 print("%s", json(nodes));
49 } else {
50 for (Node node : nodes) {
51 print(FMT, node.id(), node.host(), node.tcpPort());
52 }
53 }
54 }
55
56 // Produces JSON structure.
57 private JsonNode json(List<Node> nodes) {
58 ObjectMapper mapper = new ObjectMapper();
59 ArrayNode result = mapper.createArrayNode();
60 for (Node node : nodes) {
61 ObjectNode newNode = mapper.createObjectNode()
62 .put("id", node.id().toString())
63 .put("ip", node.ip().toString())
64 .put("host", node.host())
65 .put("tcpPort", node.tcpPort());
66 result.add(newNode);
67 }
68 return result;
69 }
70
71}