blob: ff0cf7d33d1baf8db1b88e1206dcda420a519dc0 [file] [log] [blame]
yoonseonbc0d76f2017-01-05 14:52:05 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
yoonseonbc0d76f2017-01-05 14:52:05 -08003 *
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.cli.net.vnet;
17
18import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.ObjectMapper;
20import com.fasterxml.jackson.databind.node.ArrayNode;
21import com.fasterxml.jackson.databind.node.ObjectNode;
22import org.apache.karaf.shell.commands.Argument;
23import org.apache.karaf.shell.commands.Command;
24import org.apache.karaf.shell.commands.Option;
25import org.onlab.util.StringFilter;
26import org.onosproject.cli.AbstractShellCommand;
27import org.onosproject.core.ApplicationId;
28import org.onosproject.core.CoreService;
29import org.onosproject.incubator.net.virtual.NetworkId;
30import org.onosproject.incubator.net.virtual.VirtualNetworkService;
31import org.onosproject.net.Device;
32import org.onosproject.net.DeviceId;
33import org.onosproject.net.device.DeviceService;
34import org.onosproject.net.flow.FlowEntry;
35import org.onosproject.net.flow.FlowEntry.FlowEntryState;
36import org.onosproject.net.flow.FlowRuleService;
37import org.onosproject.net.flow.TrafficTreatment;
38import org.onosproject.utils.Comparators;
39
40import java.util.ArrayList;
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -080041import java.util.Arrays;
yoonseonbc0d76f2017-01-05 14:52:05 -080042import java.util.Collections;
43import java.util.List;
44import java.util.Map;
45import java.util.SortedMap;
46import java.util.TreeMap;
47import java.util.function.Predicate;
48import java.util.stream.Collectors;
49
50import static com.google.common.collect.Lists.newArrayList;
51
52
53/**
54 * Lists all currently-known flows.
55 */
56@Command(scope = "onos", name = "vnet-flows",
57 description = "Lists all currently-known flows for a virtual network.")
58public class VirtualFlowsListCommand extends AbstractShellCommand {
59
60 private static final Predicate<FlowEntry> TRUE_PREDICATE = f -> true;
61
62 public static final String ANY = "any";
63
64 private static final String LONG_FORMAT = " id=%s, state=%s, bytes=%s, "
65 + "packets=%s, duration=%s, liveType=%s, priority=%s, tableId=%s, appId=%s, "
66 + "payLoad=%s, selector=%s, treatment=%s";
67
68 private static final String SHORT_FORMAT = " %s, bytes=%s, packets=%s, "
69 + "table=%s, priority=%s, selector=%s, treatment=%s";
70
71 @Argument(index = 0, name = "networkId", description = "Network ID",
72 required = true, multiValued = false)
73 Long networkId = null;
74
75 @Argument(index = 1, name = "state", description = "Flow Rule state",
76 required = false, multiValued = false)
77 String state = null;
78
79 @Argument(index = 2, name = "uri", description = "Device ID",
80 required = false, multiValued = false)
81 String uri = null;
82
83 @Argument(index = 3, name = "table", description = "Table ID",
84 required = false, multiValued = false)
85 String table = null;
86
87 @Option(name = "-s", aliases = "--short",
88 description = "Print more succinct output for each flow",
89 required = false, multiValued = false)
90 private boolean shortOutput = false;
91
92 @Option(name = "-c", aliases = "--count",
93 description = "Print flow count only",
94 required = false, multiValued = false)
95 private boolean countOnly = false;
96
97 @Option(name = "-f", aliases = "--filter",
98 description = "Filter flows by specific key",
99 required = false, multiValued = true)
100 private List<String> filter = new ArrayList<>();
101
102 private Predicate<FlowEntry> predicate = TRUE_PREDICATE;
103
104 private StringFilter contentFilter;
105
106 @Override
107 protected void execute() {
108 CoreService coreService = get(CoreService.class);
109
110 VirtualNetworkService vnetservice = get(VirtualNetworkService.class);
111 DeviceService deviceService = vnetservice.get(NetworkId.networkId(networkId),
112 DeviceService.class);
113 FlowRuleService service = vnetservice.get(NetworkId.networkId(networkId),
114 FlowRuleService.class);
115 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
116
117 compilePredicate();
118
119 SortedMap<Device, List<FlowEntry>> flows = getSortedFlows(deviceService, service);
120
121 if (outputJson()) {
122 print("%s", json(flows.keySet(), flows));
123 } else {
124 flows.forEach((device, flow) -> printFlows(device, flow, coreService));
125 }
126 }
127
128 /**
129 * Produces a JSON array of flows grouped by the each device.
130 *
131 * @param devices collection of devices to group flow by
132 * @param flows collection of flows per each device
133 * @return JSON array
134 */
135 private JsonNode json(Iterable<Device> devices,
136 Map<Device, List<FlowEntry>> flows) {
137 ObjectMapper mapper = new ObjectMapper();
138 ArrayNode result = mapper.createArrayNode();
139 for (Device device : devices) {
140 result.add(json(mapper, device, flows.get(device)));
141 }
142 return result;
143 }
144
145 /**
146 * Compiles a predicate to find matching flows based on the command
147 * arguments.
148 */
149 private void compilePredicate() {
150 if (state != null && !state.equals(ANY)) {
151 final FlowEntryState feState = FlowEntryState.valueOf(state.toUpperCase());
152 predicate = predicate.and(f -> f.state().equals(feState));
153 }
154
155 if (table != null) {
156 final int tableId = Integer.parseInt(table);
157 predicate = predicate.and(f -> f.tableId() == tableId);
158 }
159 }
160
161 // Produces JSON object with the flows of the given device.
162 private ObjectNode json(ObjectMapper mapper,
163 Device device, List<FlowEntry> flows) {
164 ObjectNode result = mapper.createObjectNode();
165 ArrayNode array = mapper.createArrayNode();
166
167 flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));
168
169 result.put("device", device.id().toString())
170 .put("flowCount", flows.size())
171 .set("flows", array);
172 return result;
173 }
174
175 /**
176 * Returns the list of devices sorted using the device ID URIs.
177 *
178 * @param deviceService device service
179 * @param service flow rule service
180 * @return sorted device list
181 */
182 protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
183 FlowRuleService service) {
184 SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
185 List<FlowEntry> rules;
186
187 Iterable<Device> devices = null;
188 if (uri == null) {
189 devices = deviceService.getDevices();
190 } else {
191 Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
192 devices = (dev == null) ? deviceService.getDevices()
193 : Collections.singletonList(dev);
194 }
195
196 for (Device d : devices) {
197 if (predicate.equals(TRUE_PREDICATE)) {
198 rules = newArrayList(service.getFlowEntries(d.id()));
199 } else {
200 rules = newArrayList();
201 for (FlowEntry f : service.getFlowEntries(d.id())) {
202 if (predicate.test(f)) {
203 rules.add(f);
204 }
205 }
206 }
207 rules.sort(Comparators.FLOW_RULE_COMPARATOR);
208
209 flows.put(d, rules);
210 }
211 return flows;
212 }
213
214 /**
215 * Prints flows.
216 *
217 * @param d the device
218 * @param flows the set of flows for that device
219 * @param coreService core system service
220 */
221 protected void printFlows(Device d, List<FlowEntry> flows,
222 CoreService coreService) {
223 List<FlowEntry> filteredFlows = flows.stream().
224 filter(f -> contentFilter.filter(f)).collect(Collectors.toList());
225 boolean empty = filteredFlows == null || filteredFlows.isEmpty();
226 print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
227 if (empty || countOnly) {
228 return;
229 }
230
231 for (FlowEntry f : filteredFlows) {
232 if (shortOutput) {
233 print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
234 f.tableId(), f.priority(), f.selector().criteria(),
235 printTreatment(f.treatment()));
236 } else {
237 ApplicationId appId = coreService.getAppId(f.appId());
238 print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
239 f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.tableId(),
240 appId != null ? appId.name() : "<none>",
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800241 f.payLoad() == null ? null : Arrays.toString(f.payLoad().payLoad()),
yoonseonbc0d76f2017-01-05 14:52:05 -0800242 f.selector().criteria(), f.treatment());
243 }
244 }
245 }
246
247 private String printTreatment(TrafficTreatment treatment) {
248 final String delimiter = ", ";
249 StringBuilder builder = new StringBuilder("[");
250 if (!treatment.immediate().isEmpty()) {
251 builder.append("immediate=" + treatment.immediate() + delimiter);
252 }
253 if (!treatment.deferred().isEmpty()) {
254 builder.append("deferred=" + treatment.deferred() + delimiter);
255 }
256 if (treatment.clearedDeferred()) {
257 builder.append("clearDeferred" + delimiter);
258 }
259 if (treatment.tableTransition() != null) {
260 builder.append("transition=" + treatment.tableTransition() + delimiter);
261 }
262 if (treatment.metered() != null) {
263 builder.append("meter=" + treatment.metered() + delimiter);
264 }
265 if (treatment.writeMetadata() != null) {
266 builder.append("metadata=" + treatment.writeMetadata() + delimiter);
267 }
268 // Chop off last delimiter
269 builder.replace(builder.length() - delimiter.length(), builder.length(), "");
270 builder.append("]");
271 return builder.toString();
272 }
273
274}