blob: ddac49ee4569ae0df16c01fe591bc0fa76055d33 [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;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070022import org.apache.karaf.shell.api.action.Argument;
23import org.apache.karaf.shell.api.action.Command;
24import org.apache.karaf.shell.api.action.lifecycle.Service;
25import org.apache.karaf.shell.api.action.Option;
Carolina Fernandezfa56d142016-11-14 01:13:26 +010026import org.onlab.util.StringFilter;
Brian O'Connorabafb502014-12-02 22:26:20 -080027import org.onosproject.cli.AbstractShellCommand;
Brian O'Connor9cc799c2015-06-04 19:35:41 -070028import org.onosproject.core.ApplicationId;
Ray Milkey3078fc02015-05-06 16:14:14 -070029import org.onosproject.core.CoreService;
Brian O'Connorabafb502014-12-02 22:26:20 -080030import org.onosproject.net.Device;
31import org.onosproject.net.DeviceId;
32import org.onosproject.net.device.DeviceService;
33import org.onosproject.net.flow.FlowEntry;
34import org.onosproject.net.flow.FlowEntry.FlowEntryState;
35import org.onosproject.net.flow.FlowRuleService;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080036import org.onosproject.net.flow.TrafficTreatment;
Carolina Fernandez0b1449d2016-12-04 13:30:36 +010037import org.onosproject.utils.Comparators;
alshabib99b8fdc2014-09-25 14:30:22 -070038
Carolina Fernandez0b1449d2016-12-04 13:30:36 +010039import java.io.BufferedReader;
40import java.io.IOException;
41import java.io.InputStreamReader;
Carolina Fernandezfa56d142016-11-14 01:13:26 +010042import java.util.ArrayList;
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -080043import java.util.Arrays;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080044import java.util.Collections;
45import java.util.List;
46import java.util.Map;
47import java.util.SortedMap;
48import java.util.TreeMap;
49import java.util.function.Predicate;
Mark4c964522016-03-08 11:26:07 -080050import java.util.stream.Collectors;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080051
52import static com.google.common.collect.Lists.newArrayList;
toma6897792014-10-08 22:21:05 -070053
Mark4c964522016-03-08 11:26:07 -080054
alshabib9290eea2014-09-22 11:58:17 -070055/**
jccf988bf52015-05-05 19:02:50 +080056 * Lists all currently-known flows.
alshabib9290eea2014-09-22 11:58:17 -070057 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -070058@Service
alshabib9290eea2014-09-22 11:58:17 -070059@Command(scope = "onos", name = "flows",
toma6897792014-10-08 22:21:05 -070060 description = "Lists all currently-known flows.")
alshabib9290eea2014-09-22 11:58:17 -070061public class FlowsListCommand extends AbstractShellCommand {
62
Jonathan Hartc7840bd2016-01-21 23:26:29 -080063 private static final Predicate<FlowEntry> TRUE_PREDICATE = f -> true;
64
alshabib144a2942014-09-25 18:44:02 -070065 public static final String ANY = "any";
66
Jonathan Hartc7840bd2016-01-21 23:26:29 -080067 private static final String LONG_FORMAT = " id=%s, state=%s, bytes=%s, "
Sangsik Yoonb1b823f2016-05-16 18:55:39 +090068 + "packets=%s, duration=%s, liveType=%s, priority=%s, tableId=%s, appId=%s, "
Jonathan Hartc7840bd2016-01-21 23:26:29 -080069 + "payLoad=%s, selector=%s, treatment=%s";
70
71 private static final String SHORT_FORMAT = " %s, bytes=%s, packets=%s, "
72 + "table=%s, priority=%s, selector=%s, treatment=%s";
73
74 @Argument(index = 0, name = "state", description = "Flow Rule state",
75 required = false, multiValued = false)
76 String state = null;
alshabib99b8fdc2014-09-25 14:30:22 -070077
alshabib144a2942014-09-25 18:44:02 -070078 @Argument(index = 1, name = "uri", description = "Device ID",
toma6897792014-10-08 22:21:05 -070079 required = false, multiValued = false)
alshabib99b8fdc2014-09-25 14:30:22 -070080 String uri = null;
alshabib9290eea2014-09-22 11:58:17 -070081
Jonathan Hartc7840bd2016-01-21 23:26:29 -080082 @Argument(index = 2, name = "table", description = "Table ID",
83 required = false, multiValued = false)
84 String table = null;
85
86 @Option(name = "-s", aliases = "--short",
87 description = "Print more succinct output for each flow",
88 required = false, multiValued = false)
89 private boolean shortOutput = false;
90
Mark4c964522016-03-08 11:26:07 -080091 @Option(name = "-n", aliases = "--no-core-flows",
92 description = "Suppress core flows from output",
93 required = false, multiValued = false)
94 private boolean suppressCoreOutput = false;
95
Charles Chanf9b94ab2016-02-23 19:31:41 -080096 @Option(name = "-c", aliases = "--count",
97 description = "Print flow count only",
98 required = false, multiValued = false)
99 private boolean countOnly = false;
100
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100101 @Option(name = "-f", aliases = "--filter",
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100102 description = "Filter flows by specific keyword",
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100103 required = false, multiValued = true)
104 private List<String> filter = new ArrayList<>();
105
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100106 @Option(name = "-r", aliases = "--remove",
107 description = "Remove flows by specific keyword",
108 required = false, multiValued = false)
109 private String remove = null;
110
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800111 private Predicate<FlowEntry> predicate = TRUE_PREDICATE;
alshabib64231d82014-09-25 18:25:31 -0700112
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100113 private StringFilter contentFilter;
114
alshabib9290eea2014-09-22 11:58:17 -0700115 @Override
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700116 protected void doExecute() {
toma6897792014-10-08 22:21:05 -0700117 CoreService coreService = get(CoreService.class);
tomcaf3bf72014-09-23 13:20:53 -0700118 DeviceService deviceService = get(DeviceService.class);
119 FlowRuleService service = get(FlowRuleService.class);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100120 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800121
122 compilePredicate();
123
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700124 if (countOnly && !suppressCoreOutput && filter.isEmpty() && remove == null) {
125 if (uri == null) {
126 deviceService.getDevices().forEach(device -> printCount(device, service));
127 } else {
128 Device device = deviceService.getDevice(DeviceId.deviceId(uri));
129 if (device != null) {
130 printCount(device, service);
131 }
132 }
133 return;
134 }
135
Mark4c964522016-03-08 11:26:07 -0800136 SortedMap<Device, List<FlowEntry>> flows = getSortedFlows(deviceService, service, coreService);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700137
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100138 // Remove flows
139 if (remove != null) {
140 flows.values().forEach(flowList -> {
141 if (!remove.isEmpty()) {
142 filter.add(remove);
143 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
144 }
145 if (!filter.isEmpty() || (remove != null && !remove.isEmpty())) {
146 flowList = filterFlows(flowList);
147 this.removeFlowsInteractive(flowList, service, coreService);
148 }
149 });
150 return;
151 }
152
153 // Show flows
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700154 if (outputJson()) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700155 print("%s", json(flows.keySet(), flows));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700156 } else {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800157 flows.forEach((device, flow) -> printFlows(device, flow, coreService));
alshabib9290eea2014-09-22 11:58:17 -0700158 }
alshabib9290eea2014-09-22 11:58:17 -0700159 }
160
alshabib9290eea2014-09-22 11:58:17 -0700161 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100162 * Removes the flows passed as argument after confirmation is provided
163 * for each of them.
164 * If no explicit confirmation is provided, the flow is not removed.
165 *
166 * @param flows list of flows to remove
167 * @param flowService FlowRuleService object
168 * @param coreService CoreService object
169 */
170 public void removeFlowsInteractive(Iterable<FlowEntry> flows,
171 FlowRuleService flowService, CoreService coreService) {
172 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
173 flows.forEach(flow -> {
174 ApplicationId appId = coreService.getAppId(flow.appId());
175 System.out.print(String.format("Id=%s, AppId=%s. Remove? [y/N]: ",
176 flow.id(), appId != null ? appId.name() : "<none>"));
177 String response;
178 try {
179 response = br.readLine();
180 response = response.trim().replace("\n", "");
Jon Halla3fcf672017-03-28 16:53:22 -0700181 if ("y".equals(response)) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100182 flowService.removeFlowRules(flow);
183 }
184 } catch (IOException e) {
185 response = "";
186 }
187 print(response);
188 });
189 }
190
191 /**
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700192 * Produces a JSON array of flows grouped by the each device.
193 *
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700194 * @param devices collection of devices to group flow by
195 * @param flows collection of flows per each device
196 * @return JSON array
197 */
Ray Milkey3078fc02015-05-06 16:14:14 -0700198 private JsonNode json(Iterable<Device> devices,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700199 Map<Device, List<FlowEntry>> flows) {
200 ObjectMapper mapper = new ObjectMapper();
201 ArrayNode result = mapper.createArrayNode();
202 for (Device device : devices) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700203 result.add(json(mapper, device, flows.get(device)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700204 }
205 return result;
206 }
207
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800208 /**
209 * Compiles a predicate to find matching flows based on the command
210 * arguments.
211 */
212 private void compilePredicate() {
213 if (state != null && !state.equals(ANY)) {
214 final FlowEntryState feState = FlowEntryState.valueOf(state.toUpperCase());
215 predicate = predicate.and(f -> f.state().equals(feState));
216 }
217
218 if (table != null) {
219 final int tableId = Integer.parseInt(table);
220 predicate = predicate.and(f -> f.tableId() == tableId);
221 }
222 }
223
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700224 // Produces JSON object with the flows of the given device.
Ray Milkey3078fc02015-05-06 16:14:14 -0700225 private ObjectNode json(ObjectMapper mapper,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700226 Device device, List<FlowEntry> flows) {
227 ObjectNode result = mapper.createObjectNode();
228 ArrayNode array = mapper.createArrayNode();
229
Ray Milkey3078fc02015-05-06 16:14:14 -0700230 flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700231
232 result.put("device", device.id().toString())
233 .put("flowCount", flows.size())
Thomas Vachuskadfe48a72014-10-16 10:32:08 -0700234 .set("flows", array);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700235 return result;
236 }
237
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700238 /**
alshabib9290eea2014-09-22 11:58:17 -0700239 * Returns the list of devices sorted using the device ID URIs.
240 *
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800241 * @param deviceService device service
242 * @param service flow rule service
Ray Milkeyd4334db2016-04-05 17:39:44 -0700243 * @param coreService core service
alshabib9290eea2014-09-22 11:58:17 -0700244 * @return sorted device list
245 */
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800246 protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
Mark4c964522016-03-08 11:26:07 -0800247 FlowRuleService service, CoreService coreService) {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800248 SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
alshabib1c319ff2014-10-04 20:29:09 -0700249 List<FlowEntry> rules;
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800250
Saurav Das554f5e72015-10-27 10:28:19 -0700251 Iterable<Device> devices = null;
252 if (uri == null) {
253 devices = deviceService.getDevices();
254 } else {
255 Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
256 devices = (dev == null) ? deviceService.getDevices()
257 : Collections.singletonList(dev);
258 }
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800259
alshabib99b8fdc2014-09-25 14:30:22 -0700260 for (Device d : devices) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800261 if (predicate.equals(TRUE_PREDICATE)) {
alshabib144a2942014-09-25 18:44:02 -0700262 rules = newArrayList(service.getFlowEntries(d.id()));
263 } else {
264 rules = newArrayList();
alshabib1c319ff2014-10-04 20:29:09 -0700265 for (FlowEntry f : service.getFlowEntries(d.id())) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800266 if (predicate.test(f)) {
alshabib144a2942014-09-25 18:44:02 -0700267 rules.add(f);
268 }
269 }
270 }
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800271 rules.sort(Comparators.FLOW_RULE_COMPARATOR);
Mark4c964522016-03-08 11:26:07 -0800272
273 if (suppressCoreOutput) {
274 short coreAppId = coreService.getAppId("org.onosproject.core").id();
275 rules = rules.stream()
276 .filter(f -> f.appId() != coreAppId)
277 .collect(Collectors.toList());
278 }
alshabib9290eea2014-09-22 11:58:17 -0700279 flows.put(d, rules);
280 }
281 return flows;
282 }
283
284 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100285 * Filter a given list of flows based on the existing content filter.
286 *
287 * @param flows list of flows to filter
288 * @return further filtered list of flows
289 */
290 private List<FlowEntry> filterFlows(List<FlowEntry> flows) {
291 return flows.stream().
292 filter(f -> contentFilter.filter(f)).collect(Collectors.toList());
293 }
294
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700295 private void printCount(Device device, FlowRuleService flowRuleService) {
296 print("deviceId=%s, flowRuleCount=%d", device.id(), flowRuleService.getFlowRuleCount(device.id()));
297 }
298
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100299 /**
alshabib9290eea2014-09-22 11:58:17 -0700300 * Prints flows.
toma6897792014-10-08 22:21:05 -0700301 *
302 * @param d the device
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800303 * @param flows the set of flows for that device
304 * @param coreService core system service
alshabib9290eea2014-09-22 11:58:17 -0700305 */
toma6897792014-10-08 22:21:05 -0700306 protected void printFlows(Device d, List<FlowEntry> flows,
307 CoreService coreService) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100308 List<FlowEntry> filteredFlows = filterFlows(flows);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100309 boolean empty = filteredFlows == null || filteredFlows.isEmpty();
310 print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
Charles Chanf9b94ab2016-02-23 19:31:41 -0800311 if (empty || countOnly) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800312 return;
313 }
314
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100315 for (FlowEntry f : filteredFlows) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800316 if (shortOutput) {
317 print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800318 f.table(), f.priority(), f.selector().criteria(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800319 printTreatment(f.treatment()));
320 } else {
Brian O'Connor9cc799c2015-06-04 19:35:41 -0700321 ApplicationId appId = coreService.getAppId(f.appId());
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800322 print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800323 f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.table(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800324 appId != null ? appId.name() : "<none>",
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800325 f.payLoad() == null ? null : Arrays.toString(f.payLoad().payLoad()),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800326 f.selector().criteria(), f.treatment());
tom1dd08e42014-10-07 11:40:00 -0700327 }
alshabib99b8fdc2014-09-25 14:30:22 -0700328 }
alshabib9290eea2014-09-22 11:58:17 -0700329 }
330
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800331 private String printTreatment(TrafficTreatment treatment) {
332 final String delimiter = ", ";
333 StringBuilder builder = new StringBuilder("[");
334 if (!treatment.immediate().isEmpty()) {
335 builder.append("immediate=" + treatment.immediate() + delimiter);
336 }
337 if (!treatment.deferred().isEmpty()) {
338 builder.append("deferred=" + treatment.deferred() + delimiter);
339 }
340 if (treatment.clearedDeferred()) {
341 builder.append("clearDeferred" + delimiter);
342 }
343 if (treatment.tableTransition() != null) {
344 builder.append("transition=" + treatment.tableTransition() + delimiter);
345 }
346 if (treatment.metered() != null) {
347 builder.append("meter=" + treatment.metered() + delimiter);
348 }
349 if (treatment.writeMetadata() != null) {
350 builder.append("metadata=" + treatment.writeMetadata() + delimiter);
351 }
352 // Chop off last delimiter
353 builder.replace(builder.length() - delimiter.length(), builder.length(), "");
354 builder.append("]");
355 return builder.toString();
356 }
Yuta HIGUCHIe76a24d2014-09-27 00:48:34 -0700357}