blob: 04601cf2ab66d299004c7b5d0830d337ee3fade5 [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
40 private static final String FORMAT = "%-20s%-15s%-24s%-24s%-20s%-15s";
41
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 {
51 print(FORMAT, "Hostname", "Type", "Integration Bridge",
52 "Management IP", "Data IP", "State");
53 for (K8sNode node : nodes) {
54 print(FORMAT,
55 node.hostname(),
56 node.type(),
57 node.intgBridge(),
58 node.managementIp(),
59 node.dataIp() != null ? node.dataIp() : "",
60 node.state());
61 }
62 print("Total %s nodes", nodeService.nodes().size());
63 }
64 }
65
66 private String json(List<K8sNode> nodes) {
67 ObjectMapper mapper = new ObjectMapper();
68 ArrayNode result = mapper.createArrayNode();
69 for (K8sNode node : nodes) {
70 result.add(jsonForEntity(node, K8sNode.class));
71 }
72 return prettyJson(mapper, result.toString());
73 }
74}