Jian Li | bde20bf | 2019-01-25 17:34:43 +0900 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onosproject.k8snetworking.cli; |
| 17 | |
| 18 | import com.fasterxml.jackson.databind.ObjectMapper; |
| 19 | import com.fasterxml.jackson.databind.node.ArrayNode; |
| 20 | import com.google.common.collect.Lists; |
| 21 | import org.apache.karaf.shell.api.action.Command; |
| 22 | import org.apache.karaf.shell.api.action.lifecycle.Service; |
| 23 | import org.onosproject.cli.AbstractShellCommand; |
| 24 | import org.onosproject.k8snetworking.api.K8sNetwork; |
| 25 | import org.onosproject.k8snetworking.api.K8sNetworkService; |
| 26 | |
| 27 | import java.util.Comparator; |
| 28 | import java.util.List; |
| 29 | |
| 30 | import 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") |
| 38 | public 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 | } |