blob: 307736be377f6cc86b0f29a63670c78743737858 [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.base.Strings;
21import com.google.common.collect.Lists;
22import org.apache.karaf.shell.api.action.Argument;
23import org.apache.karaf.shell.api.action.Command;
24import org.apache.karaf.shell.api.action.lifecycle.Service;
25import org.onosproject.cli.AbstractShellCommand;
26import org.onosproject.k8snetworking.api.K8sNetwork;
27import org.onosproject.k8snetworking.api.K8sNetworkService;
28import org.onosproject.k8snetworking.api.K8sPort;
29
30import java.util.Comparator;
31import java.util.List;
32
33import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.prettyJson;
34
35/**
36 * Lists kubernetes ports.
37 */
38@Service
39@Command(scope = "onos", name = "k8s-ports",
40 description = "Lists all kubernetes ports")
41public class K8sPortListCommand extends AbstractShellCommand {
42
43 private static final String FORMAT = "%-40s%-20s%-20s%-8s";
44
45 @Argument(name = "networkId", description = "Network ID")
46 private String networkId = null;
47
48 @Override
49 protected void doExecute() {
50 K8sNetworkService service = get(K8sNetworkService.class);
51
52 List<K8sPort> ports = Lists.newArrayList(service.ports());
53 ports.sort(Comparator.comparing(K8sPort::networkId));
54
55 if (!Strings.isNullOrEmpty(networkId)) {
56 ports.removeIf(port -> !port.networkId().equals(networkId));
57 }
58
59 if (outputJson()) {
60 print("%s", json(ports));
61 } else {
62 print(FORMAT, "ID", "Network", "MAC", "Fixed IPs");
63 for (K8sPort port: ports) {
64 K8sNetwork k8sNet = service.network(port.networkId());
65 print(FORMAT, port.portId(),
66 k8sNet.name(),
67 port.macAddress(),
68 port.ipAddress() == null ? "" : port.ipAddress().toString());
69 }
70 }
71 }
72
73 private String json(List<K8sPort> ports) {
74 ObjectMapper mapper = new ObjectMapper();
75 ArrayNode result = mapper.createArrayNode();
76
77 for (K8sPort port : ports) {
78 result.add(jsonForEntity(port, K8sPort.class));
79 }
80 return prettyJson(mapper, result.toString());
81 }
82}