blob: aea21308e33b6dea1ac8695ec98aa2e29db08b37 [file] [log] [blame]
Jian Lif16e8852019-01-22 22:55:31 +09001/*
2 * Copyright 2019-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.k8snode.cli;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ArrayNode;
20import com.google.common.collect.Lists;
21import org.apache.karaf.shell.api.action.Command;
22import org.apache.karaf.shell.api.action.lifecycle.Service;
23import org.onosproject.cli.AbstractShellCommand;
24import org.onosproject.k8snode.api.K8sNode;
25import org.onosproject.k8snode.api.K8sNodeService;
26
27import java.util.Comparator;
28import java.util.List;
29
30import static org.onosproject.k8snode.util.K8sNodeUtil.prettyJson;
31
32/**
33 * Lists all nodes registered to the service.
34 */
35@Service
36@Command(scope = "onos", name = "k8s-nodes",
37 description = "Lists all nodes registered in kubernetes node service")
38public class K8sNodeListCommand extends AbstractShellCommand {
39
Jian Li8a988042019-05-03 23:41:19 +090040 private static final String FORMAT = "%-28s%-15s%-24s%-20s%-15s";
Jian Lif16e8852019-01-22 22:55:31 +090041
42 @Override
43 protected void doExecute() {
44 K8sNodeService nodeService = get(K8sNodeService.class);
45 List<K8sNode> nodes = Lists.newArrayList(nodeService.nodes());
46 nodes.sort(Comparator.comparing(K8sNode::hostname));
47
48 if (outputJson()) {
49 print("%s", json(nodes));
50 } else {
Jian Li8a988042019-05-03 23:41:19 +090051 print(FORMAT, "Hostname", "Type", "Management IP", "Data IP", "State");
Jian Lif16e8852019-01-22 22:55:31 +090052 for (K8sNode node : nodes) {
53 print(FORMAT,
54 node.hostname(),
55 node.type(),
Jian Lif16e8852019-01-22 22:55:31 +090056 node.managementIp(),
57 node.dataIp() != null ? node.dataIp() : "",
58 node.state());
59 }
60 print("Total %s nodes", nodeService.nodes().size());
61 }
62 }
63
64 private String json(List<K8sNode> nodes) {
65 ObjectMapper mapper = new ObjectMapper();
66 ArrayNode result = mapper.createArrayNode();
67 for (K8sNode node : nodes) {
68 result.add(jsonForEntity(node, K8sNode.class));
69 }
70 return prettyJson(mapper, result.toString());
71 }
72}