blob: 82904a61f6244c2a0dea8df3f57d16d06bd6f0a7 [file] [log] [blame]
Jian Libde20bf2019-01-25 17:34:43 +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.k8snetworking.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.k8snetworking.api.K8sNetwork;
25import org.onosproject.k8snetworking.api.K8sNetworkService;
26
27import java.util.Comparator;
28import java.util.List;
29
30import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.prettyJson;
31
32/**
33 * Lists kubernetes networks.
34 */
35@Service
36@Command(scope = "onos", name = "k8s-networks",
37 description = "Lists all kubernetes networks")
38public class K8sNetworkListCommand extends AbstractShellCommand {
39
40 private static final String FORMAT = "%-40s%-20s%-20s%-20s%-16s";
41
42 @Override
43 protected void doExecute() {
44 K8sNetworkService service = get(K8sNetworkService.class);
45 List<K8sNetwork> networks = Lists.newArrayList(service.networks());
46 networks.sort(Comparator.comparing(K8sNetwork::name));
47
48 if (outputJson()) {
49 print("%s", json(networks));
50 } else {
51 print(FORMAT, "ID", "Name", "Type", "SegId", "Gateway");
52
53 for (K8sNetwork net: networks) {
54 print(FORMAT, net.networkId(),
55 net.name(),
56 net.type().toString(),
57 net.segmentId(),
58 net.gatewayIp() == null ? "" : net.gatewayIp().toString());
59 }
60 }
61 }
62
63 private String json(List<K8sNetwork> networks) {
64 ObjectMapper mapper = new ObjectMapper();
65 ArrayNode result = mapper.createArrayNode();
66
67 for (K8sNetwork network : networks) {
68 result.add(jsonForEntity(network, K8sNetwork.class));
69 }
70 return prettyJson(mapper, result.toString());
71 }
72}