blob: 5c26b0630478079f3d46260124176a2535d89f12 [file] [log] [blame]
Thomas Vachuska7d693f52014-10-21 19:17:57 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska7d693f52014-10-21 19:17:57 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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
Thomas Vachuska7d693f52014-10-21 19:17:57 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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.
Thomas Vachuska7d693f52014-10-21 19:17:57 -070015 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.cli.net;
alshabib9290eea2014-09-22 11:58:17 -070017
Jonathan Hartc7840bd2016-01-21 23:26:29 -080018import 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;
alshabib99b8fdc2014-09-25 14:30:22 -070022import org.apache.karaf.shell.commands.Argument;
23import org.apache.karaf.shell.commands.Command;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080024import org.apache.karaf.shell.commands.Option;
Carolina Fernandezfa56d142016-11-14 01:13:26 +010025import org.onlab.util.StringFilter;
Brian O'Connorabafb502014-12-02 22:26:20 -080026import org.onosproject.cli.AbstractShellCommand;
Brian O'Connor9cc799c2015-06-04 19:35:41 -070027import org.onosproject.core.ApplicationId;
Ray Milkey3078fc02015-05-06 16:14:14 -070028import org.onosproject.core.CoreService;
Brian O'Connorabafb502014-12-02 22:26:20 -080029import org.onosproject.net.Device;
30import org.onosproject.net.DeviceId;
31import org.onosproject.net.device.DeviceService;
32import org.onosproject.net.flow.FlowEntry;
33import org.onosproject.net.flow.FlowEntry.FlowEntryState;
34import org.onosproject.net.flow.FlowRuleService;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080035import org.onosproject.net.flow.TrafficTreatment;
Carolina Fernandez0b1449d2016-12-04 13:30:36 +010036import org.onosproject.utils.Comparators;
alshabib99b8fdc2014-09-25 14:30:22 -070037
Carolina Fernandez0b1449d2016-12-04 13:30:36 +010038import java.io.BufferedReader;
39import java.io.IOException;
40import java.io.InputStreamReader;
Carolina Fernandezfa56d142016-11-14 01:13:26 +010041import java.util.ArrayList;
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -080042import java.util.Arrays;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080043import java.util.Collections;
44import java.util.List;
45import java.util.Map;
46import java.util.SortedMap;
47import java.util.TreeMap;
48import java.util.function.Predicate;
Mark4c964522016-03-08 11:26:07 -080049import java.util.stream.Collectors;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080050
51import static com.google.common.collect.Lists.newArrayList;
toma6897792014-10-08 22:21:05 -070052
Mark4c964522016-03-08 11:26:07 -080053
alshabib9290eea2014-09-22 11:58:17 -070054/**
jccf988bf52015-05-05 19:02:50 +080055 * Lists all currently-known flows.
alshabib9290eea2014-09-22 11:58:17 -070056 */
57@Command(scope = "onos", name = "flows",
toma6897792014-10-08 22:21:05 -070058 description = "Lists all currently-known flows.")
alshabib9290eea2014-09-22 11:58:17 -070059public class FlowsListCommand extends AbstractShellCommand {
60
Jonathan Hartc7840bd2016-01-21 23:26:29 -080061 private static final Predicate<FlowEntry> TRUE_PREDICATE = f -> true;
62
alshabib144a2942014-09-25 18:44:02 -070063 public static final String ANY = "any";
64
Jonathan Hartc7840bd2016-01-21 23:26:29 -080065 private static final String LONG_FORMAT = " id=%s, state=%s, bytes=%s, "
Sangsik Yoonb1b823f2016-05-16 18:55:39 +090066 + "packets=%s, duration=%s, liveType=%s, priority=%s, tableId=%s, appId=%s, "
Jonathan Hartc7840bd2016-01-21 23:26:29 -080067 + "payLoad=%s, selector=%s, treatment=%s";
68
69 private static final String SHORT_FORMAT = " %s, bytes=%s, packets=%s, "
70 + "table=%s, priority=%s, selector=%s, treatment=%s";
71
72 @Argument(index = 0, name = "state", description = "Flow Rule state",
73 required = false, multiValued = false)
74 String state = null;
alshabib99b8fdc2014-09-25 14:30:22 -070075
alshabib144a2942014-09-25 18:44:02 -070076 @Argument(index = 1, name = "uri", description = "Device ID",
toma6897792014-10-08 22:21:05 -070077 required = false, multiValued = false)
alshabib99b8fdc2014-09-25 14:30:22 -070078 String uri = null;
alshabib9290eea2014-09-22 11:58:17 -070079
Jonathan Hartc7840bd2016-01-21 23:26:29 -080080 @Argument(index = 2, name = "table", description = "Table ID",
81 required = false, multiValued = false)
82 String table = null;
83
84 @Option(name = "-s", aliases = "--short",
85 description = "Print more succinct output for each flow",
86 required = false, multiValued = false)
87 private boolean shortOutput = false;
88
Mark4c964522016-03-08 11:26:07 -080089 @Option(name = "-n", aliases = "--no-core-flows",
90 description = "Suppress core flows from output",
91 required = false, multiValued = false)
92 private boolean suppressCoreOutput = false;
93
Charles Chanf9b94ab2016-02-23 19:31:41 -080094 @Option(name = "-c", aliases = "--count",
95 description = "Print flow count only",
96 required = false, multiValued = false)
97 private boolean countOnly = false;
98
Carolina Fernandezfa56d142016-11-14 01:13:26 +010099 @Option(name = "-f", aliases = "--filter",
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100100 description = "Filter flows by specific keyword",
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100101 required = false, multiValued = true)
102 private List<String> filter = new ArrayList<>();
103
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100104 @Option(name = "-r", aliases = "--remove",
105 description = "Remove flows by specific keyword",
106 required = false, multiValued = false)
107 private String remove = null;
108
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800109 private Predicate<FlowEntry> predicate = TRUE_PREDICATE;
alshabib64231d82014-09-25 18:25:31 -0700110
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100111 private StringFilter contentFilter;
112
alshabib9290eea2014-09-22 11:58:17 -0700113 @Override
tom0872a172014-09-23 11:24:26 -0700114 protected void execute() {
toma6897792014-10-08 22:21:05 -0700115 CoreService coreService = get(CoreService.class);
tomcaf3bf72014-09-23 13:20:53 -0700116 DeviceService deviceService = get(DeviceService.class);
117 FlowRuleService service = get(FlowRuleService.class);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100118 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800119
120 compilePredicate();
121
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700122 if (countOnly && !suppressCoreOutput && filter.isEmpty() && remove == null) {
123 if (uri == null) {
124 deviceService.getDevices().forEach(device -> printCount(device, service));
125 } else {
126 Device device = deviceService.getDevice(DeviceId.deviceId(uri));
127 if (device != null) {
128 printCount(device, service);
129 }
130 }
131 return;
132 }
133
Mark4c964522016-03-08 11:26:07 -0800134 SortedMap<Device, List<FlowEntry>> flows = getSortedFlows(deviceService, service, coreService);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700135
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100136 // Remove flows
137 if (remove != null) {
138 flows.values().forEach(flowList -> {
139 if (!remove.isEmpty()) {
140 filter.add(remove);
141 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
142 }
143 if (!filter.isEmpty() || (remove != null && !remove.isEmpty())) {
144 flowList = filterFlows(flowList);
145 this.removeFlowsInteractive(flowList, service, coreService);
146 }
147 });
148 return;
149 }
150
151 // Show flows
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700152 if (outputJson()) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700153 print("%s", json(flows.keySet(), flows));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700154 } else {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800155 flows.forEach((device, flow) -> printFlows(device, flow, coreService));
alshabib9290eea2014-09-22 11:58:17 -0700156 }
alshabib9290eea2014-09-22 11:58:17 -0700157 }
158
alshabib9290eea2014-09-22 11:58:17 -0700159 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100160 * Removes the flows passed as argument after confirmation is provided
161 * for each of them.
162 * If no explicit confirmation is provided, the flow is not removed.
163 *
164 * @param flows list of flows to remove
165 * @param flowService FlowRuleService object
166 * @param coreService CoreService object
167 */
168 public void removeFlowsInteractive(Iterable<FlowEntry> flows,
169 FlowRuleService flowService, CoreService coreService) {
170 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
171 flows.forEach(flow -> {
172 ApplicationId appId = coreService.getAppId(flow.appId());
173 System.out.print(String.format("Id=%s, AppId=%s. Remove? [y/N]: ",
174 flow.id(), appId != null ? appId.name() : "<none>"));
175 String response;
176 try {
177 response = br.readLine();
178 response = response.trim().replace("\n", "");
Jon Halla3fcf672017-03-28 16:53:22 -0700179 if ("y".equals(response)) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100180 flowService.removeFlowRules(flow);
181 }
182 } catch (IOException e) {
183 response = "";
184 }
185 print(response);
186 });
187 }
188
189 /**
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700190 * Produces a JSON array of flows grouped by the each device.
191 *
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700192 * @param devices collection of devices to group flow by
193 * @param flows collection of flows per each device
194 * @return JSON array
195 */
Ray Milkey3078fc02015-05-06 16:14:14 -0700196 private JsonNode json(Iterable<Device> devices,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700197 Map<Device, List<FlowEntry>> flows) {
198 ObjectMapper mapper = new ObjectMapper();
199 ArrayNode result = mapper.createArrayNode();
200 for (Device device : devices) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700201 result.add(json(mapper, device, flows.get(device)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700202 }
203 return result;
204 }
205
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800206 /**
207 * Compiles a predicate to find matching flows based on the command
208 * arguments.
209 */
210 private void compilePredicate() {
211 if (state != null && !state.equals(ANY)) {
212 final FlowEntryState feState = FlowEntryState.valueOf(state.toUpperCase());
213 predicate = predicate.and(f -> f.state().equals(feState));
214 }
215
216 if (table != null) {
217 final int tableId = Integer.parseInt(table);
218 predicate = predicate.and(f -> f.tableId() == tableId);
219 }
220 }
221
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700222 // Produces JSON object with the flows of the given device.
Ray Milkey3078fc02015-05-06 16:14:14 -0700223 private ObjectNode json(ObjectMapper mapper,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700224 Device device, List<FlowEntry> flows) {
225 ObjectNode result = mapper.createObjectNode();
226 ArrayNode array = mapper.createArrayNode();
227
Ray Milkey3078fc02015-05-06 16:14:14 -0700228 flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700229
230 result.put("device", device.id().toString())
231 .put("flowCount", flows.size())
Thomas Vachuskadfe48a72014-10-16 10:32:08 -0700232 .set("flows", array);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700233 return result;
234 }
235
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700236 /**
alshabib9290eea2014-09-22 11:58:17 -0700237 * Returns the list of devices sorted using the device ID URIs.
238 *
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800239 * @param deviceService device service
240 * @param service flow rule service
Ray Milkeyd4334db2016-04-05 17:39:44 -0700241 * @param coreService core service
alshabib9290eea2014-09-22 11:58:17 -0700242 * @return sorted device list
243 */
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800244 protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
Mark4c964522016-03-08 11:26:07 -0800245 FlowRuleService service, CoreService coreService) {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800246 SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
alshabib1c319ff2014-10-04 20:29:09 -0700247 List<FlowEntry> rules;
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800248
Saurav Das554f5e72015-10-27 10:28:19 -0700249 Iterable<Device> devices = null;
250 if (uri == null) {
251 devices = deviceService.getDevices();
252 } else {
253 Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
254 devices = (dev == null) ? deviceService.getDevices()
255 : Collections.singletonList(dev);
256 }
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800257
alshabib99b8fdc2014-09-25 14:30:22 -0700258 for (Device d : devices) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800259 if (predicate.equals(TRUE_PREDICATE)) {
alshabib144a2942014-09-25 18:44:02 -0700260 rules = newArrayList(service.getFlowEntries(d.id()));
261 } else {
262 rules = newArrayList();
alshabib1c319ff2014-10-04 20:29:09 -0700263 for (FlowEntry f : service.getFlowEntries(d.id())) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800264 if (predicate.test(f)) {
alshabib144a2942014-09-25 18:44:02 -0700265 rules.add(f);
266 }
267 }
268 }
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800269 rules.sort(Comparators.FLOW_RULE_COMPARATOR);
Mark4c964522016-03-08 11:26:07 -0800270
271 if (suppressCoreOutput) {
272 short coreAppId = coreService.getAppId("org.onosproject.core").id();
273 rules = rules.stream()
274 .filter(f -> f.appId() != coreAppId)
275 .collect(Collectors.toList());
276 }
alshabib9290eea2014-09-22 11:58:17 -0700277 flows.put(d, rules);
278 }
279 return flows;
280 }
281
282 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100283 * Filter a given list of flows based on the existing content filter.
284 *
285 * @param flows list of flows to filter
286 * @return further filtered list of flows
287 */
288 private List<FlowEntry> filterFlows(List<FlowEntry> flows) {
289 return flows.stream().
290 filter(f -> contentFilter.filter(f)).collect(Collectors.toList());
291 }
292
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700293 private void printCount(Device device, FlowRuleService flowRuleService) {
294 print("deviceId=%s, flowRuleCount=%d", device.id(), flowRuleService.getFlowRuleCount(device.id()));
295 }
296
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100297 /**
alshabib9290eea2014-09-22 11:58:17 -0700298 * Prints flows.
toma6897792014-10-08 22:21:05 -0700299 *
300 * @param d the device
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800301 * @param flows the set of flows for that device
302 * @param coreService core system service
alshabib9290eea2014-09-22 11:58:17 -0700303 */
toma6897792014-10-08 22:21:05 -0700304 protected void printFlows(Device d, List<FlowEntry> flows,
305 CoreService coreService) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100306 List<FlowEntry> filteredFlows = filterFlows(flows);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100307 boolean empty = filteredFlows == null || filteredFlows.isEmpty();
308 print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
Charles Chanf9b94ab2016-02-23 19:31:41 -0800309 if (empty || countOnly) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800310 return;
311 }
312
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100313 for (FlowEntry f : filteredFlows) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800314 if (shortOutput) {
315 print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800316 f.table(), f.priority(), f.selector().criteria(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800317 printTreatment(f.treatment()));
318 } else {
Brian O'Connor9cc799c2015-06-04 19:35:41 -0700319 ApplicationId appId = coreService.getAppId(f.appId());
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800320 print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800321 f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.table(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800322 appId != null ? appId.name() : "<none>",
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800323 f.payLoad() == null ? null : Arrays.toString(f.payLoad().payLoad()),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800324 f.selector().criteria(), f.treatment());
tom1dd08e42014-10-07 11:40:00 -0700325 }
alshabib99b8fdc2014-09-25 14:30:22 -0700326 }
alshabib9290eea2014-09-22 11:58:17 -0700327 }
328
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800329 private String printTreatment(TrafficTreatment treatment) {
330 final String delimiter = ", ";
331 StringBuilder builder = new StringBuilder("[");
332 if (!treatment.immediate().isEmpty()) {
333 builder.append("immediate=" + treatment.immediate() + delimiter);
334 }
335 if (!treatment.deferred().isEmpty()) {
336 builder.append("deferred=" + treatment.deferred() + delimiter);
337 }
338 if (treatment.clearedDeferred()) {
339 builder.append("clearDeferred" + delimiter);
340 }
341 if (treatment.tableTransition() != null) {
342 builder.append("transition=" + treatment.tableTransition() + delimiter);
343 }
344 if (treatment.metered() != null) {
345 builder.append("meter=" + treatment.metered() + delimiter);
346 }
347 if (treatment.writeMetadata() != null) {
348 builder.append("metadata=" + treatment.writeMetadata() + delimiter);
349 }
350 // Chop off last delimiter
351 builder.replace(builder.length() - delimiter.length(), builder.length(), "");
352 builder.append("]");
353 return builder.toString();
354 }
Yuta HIGUCHIe76a24d2014-09-27 00:48:34 -0700355}