blob: cc6d24fb1b2afb04a1679031d07b3221ddc6eab0 [file] [log] [blame]
Jian Lif4523d82019-07-07 01:06:09 +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.networking.NetworkPolicy;
23import io.fabric8.kubernetes.client.utils.Serialization;
24import org.apache.karaf.shell.api.action.Command;
25import org.apache.karaf.shell.api.action.lifecycle.Service;
26import org.onosproject.cli.AbstractShellCommand;
27import org.onosproject.k8snetworking.api.K8sNetworkPolicyService;
28
29import java.io.IOException;
30import java.util.Comparator;
31import java.util.List;
32
33import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.prettyJson;
34
35/**
36 * Lists kubernetes network policies.
37 */
38@Service
39@Command(scope = "onos", name = "k8s-network-policies",
40 description = "Lists all kubernetes network policies")
41public class K8sNetworkPolicyListCommand extends AbstractShellCommand {
42
43 private static final String FORMAT = "%-50s%-15s%-30s";
44
45 @Override
46 protected void doExecute() {
47 K8sNetworkPolicyService service = get(K8sNetworkPolicyService.class);
48 List<NetworkPolicy> policies = Lists.newArrayList(service.networkPolicies());
49 policies.sort(Comparator.comparing(p -> p.getMetadata().getName()));
50
51 if (outputJson()) {
52 print("%s", json(policies));
53 } else {
54 print(FORMAT, "Name", "Namespace", "Types");
55
56 for (NetworkPolicy policy : policies) {
57
58 print(FORMAT,
59 policy.getMetadata().getName(),
60 policy.getMetadata().getNamespace(),
61 policy.getSpec().getPolicyTypes().isEmpty() ?
62 "" : policy.getSpec().getPolicyTypes());
63 }
64 }
65 }
66
67 private String json(List<NetworkPolicy> policies) {
68 ObjectMapper mapper = new ObjectMapper();
69 ArrayNode result = mapper.createArrayNode();
70
71 try {
72 for (NetworkPolicy policy : policies) {
73 ObjectNode json = (ObjectNode) new ObjectMapper()
74 .readTree(Serialization.asJson(policy));
75 result.add(json);
76 }
77 return prettyJson(mapper, result.toString());
78 } catch (IOException e) {
79 log.warn("Failed to parse Network Policy's JSON string.");
80 return "";
81 }
82 }
83}