blob: 4d6908220f1f80a1485abe74b1cede0680c3ff2e [file] [log] [blame]
Jian Li324d6dc2019-07-10 10:55:15 +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.fasterxml.jackson.databind.node.ObjectNode;
21import com.google.common.collect.Lists;
22import io.fabric8.kubernetes.api.model.Namespace;
23import io.fabric8.kubernetes.client.utils.Serialization;
24import org.apache.karaf.shell.api.action.Command;
25import org.onosproject.cli.AbstractShellCommand;
26import org.onosproject.k8snetworking.api.K8sNamespaceService;
27
28import java.io.IOException;
29import java.util.Comparator;
30import java.util.List;
31
32import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.prettyJson;
33
34/**
35 * Lists kubernetes namespaces.
36 */
37@Command(scope = "onos", name = "k8s-namespaces",
38 description = "Lists all kubernetes namespaces")
39public class K8sNamespaceListCommand extends AbstractShellCommand {
40
41 private static final String FORMAT = "%-50s%-15s%-30s";
42
43 @Override
44 protected void doExecute() {
45 K8sNamespaceService service = get(K8sNamespaceService.class);
46 List<Namespace> namespaces = Lists.newArrayList(service.namespaces());
47 namespaces.sort(Comparator.comparing(n -> n.getMetadata().getName()));
48
49 if (outputJson()) {
50 print("%s", json(namespaces));
51 } else {
52 print(FORMAT, "Name", "Phase", "Labels");
53
54 for (Namespace namespace : namespaces) {
55
56 print(FORMAT,
57 namespace.getMetadata().getName(),
58 namespace.getStatus().getPhase(),
59 namespace.getMetadata() != null &&
60 namespace.getMetadata().getLabels() != null &&
61 !namespace.getMetadata().getLabels().isEmpty() ?
62 namespace.getMetadata().getLabels() : "");
63 }
64 }
65 }
66
67 private String json(List<Namespace> namespaces) {
68 ObjectMapper mapper = new ObjectMapper();
69 ArrayNode result = mapper.createArrayNode();
70
71 try {
72 for (Namespace namespace : namespaces) {
73 ObjectNode json = (ObjectNode) new ObjectMapper()
74 .readTree(Serialization.asJson(namespace));
75 result.add(json);
76 }
77 return prettyJson(mapper, result.toString());
78 } catch (IOException e) {
79 log.warn("Failed to parse Namespace's JSON string.");
80 return "";
81 }
82 }
83}