blob: f7adc0a9f662cc38a40f0031ce42f13aa3fc01fe [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;
Ray Milkey0068fd02018-10-11 15:45:39 -070024import org.apache.karaf.shell.api.action.Completion;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070025import org.apache.karaf.shell.api.action.lifecycle.Service;
26import org.apache.karaf.shell.api.action.Option;
Carolina Fernandezfa56d142016-11-14 01:13:26 +010027import org.onlab.util.StringFilter;
Brian O'Connorabafb502014-12-02 22:26:20 -080028import org.onosproject.cli.AbstractShellCommand;
Ray Milkey0068fd02018-10-11 15:45:39 -070029import org.onosproject.cli.PlaceholderCompleter;
Brian O'Connor9cc799c2015-06-04 19:35:41 -070030import org.onosproject.core.ApplicationId;
Ray Milkey3078fc02015-05-06 16:14:14 -070031import org.onosproject.core.CoreService;
Brian O'Connorabafb502014-12-02 22:26:20 -080032import org.onosproject.net.Device;
33import org.onosproject.net.DeviceId;
34import org.onosproject.net.device.DeviceService;
35import org.onosproject.net.flow.FlowEntry;
36import org.onosproject.net.flow.FlowEntry.FlowEntryState;
37import org.onosproject.net.flow.FlowRuleService;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080038import org.onosproject.net.flow.TrafficTreatment;
Carolina Fernandez0b1449d2016-12-04 13:30:36 +010039import org.onosproject.utils.Comparators;
alshabib99b8fdc2014-09-25 14:30:22 -070040
Carolina Fernandez0b1449d2016-12-04 13:30:36 +010041import java.io.BufferedReader;
42import java.io.IOException;
43import java.io.InputStreamReader;
Carolina Fernandezfa56d142016-11-14 01:13:26 +010044import java.util.ArrayList;
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -080045import java.util.Arrays;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080046import java.util.Collections;
47import java.util.List;
48import java.util.Map;
49import java.util.SortedMap;
50import java.util.TreeMap;
51import java.util.function.Predicate;
Mark4c964522016-03-08 11:26:07 -080052import java.util.stream.Collectors;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080053
54import static com.google.common.collect.Lists.newArrayList;
toma6897792014-10-08 22:21:05 -070055
Mark4c964522016-03-08 11:26:07 -080056
alshabib9290eea2014-09-22 11:58:17 -070057/**
jccf988bf52015-05-05 19:02:50 +080058 * Lists all currently-known flows.
alshabib9290eea2014-09-22 11:58:17 -070059 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -070060@Service
alshabib9290eea2014-09-22 11:58:17 -070061@Command(scope = "onos", name = "flows",
toma6897792014-10-08 22:21:05 -070062 description = "Lists all currently-known flows.")
alshabib9290eea2014-09-22 11:58:17 -070063public class FlowsListCommand extends AbstractShellCommand {
64
Jonathan Hartc7840bd2016-01-21 23:26:29 -080065 private static final Predicate<FlowEntry> TRUE_PREDICATE = f -> true;
66
alshabib144a2942014-09-25 18:44:02 -070067 public static final String ANY = "any";
68
Jonathan Hartc7840bd2016-01-21 23:26:29 -080069 private static final String LONG_FORMAT = " id=%s, state=%s, bytes=%s, "
Sangsik Yoonb1b823f2016-05-16 18:55:39 +090070 + "packets=%s, duration=%s, liveType=%s, priority=%s, tableId=%s, appId=%s, "
Jonathan Hartc7840bd2016-01-21 23:26:29 -080071 + "payLoad=%s, selector=%s, treatment=%s";
72
73 private static final String SHORT_FORMAT = " %s, bytes=%s, packets=%s, "
74 + "table=%s, priority=%s, selector=%s, treatment=%s";
75
76 @Argument(index = 0, name = "state", description = "Flow Rule state",
77 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070078 @Completion(FlowRuleStatusCompleter.class)
Jonathan Hartc7840bd2016-01-21 23:26:29 -080079 String state = null;
alshabib99b8fdc2014-09-25 14:30:22 -070080
alshabib144a2942014-09-25 18:44:02 -070081 @Argument(index = 1, name = "uri", description = "Device ID",
toma6897792014-10-08 22:21:05 -070082 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070083 @Completion(DeviceIdCompleter.class)
alshabib99b8fdc2014-09-25 14:30:22 -070084 String uri = null;
alshabib9290eea2014-09-22 11:58:17 -070085
Jonathan Hartc7840bd2016-01-21 23:26:29 -080086 @Argument(index = 2, name = "table", description = "Table ID",
87 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070088 @Completion(PlaceholderCompleter.class)
Jonathan Hartc7840bd2016-01-21 23:26:29 -080089 String table = null;
90
91 @Option(name = "-s", aliases = "--short",
92 description = "Print more succinct output for each flow",
93 required = false, multiValued = false)
94 private boolean shortOutput = false;
95
Mark4c964522016-03-08 11:26:07 -080096 @Option(name = "-n", aliases = "--no-core-flows",
97 description = "Suppress core flows from output",
98 required = false, multiValued = false)
99 private boolean suppressCoreOutput = false;
100
Charles Chanf9b94ab2016-02-23 19:31:41 -0800101 @Option(name = "-c", aliases = "--count",
102 description = "Print flow count only",
103 required = false, multiValued = false)
104 private boolean countOnly = false;
105
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100106 @Option(name = "-f", aliases = "--filter",
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100107 description = "Filter flows by specific keyword",
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100108 required = false, multiValued = true)
109 private List<String> filter = new ArrayList<>();
110
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100111 @Option(name = "-r", aliases = "--remove",
112 description = "Remove flows by specific keyword",
113 required = false, multiValued = false)
114 private String remove = null;
115
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800116 private Predicate<FlowEntry> predicate = TRUE_PREDICATE;
alshabib64231d82014-09-25 18:25:31 -0700117
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100118 private StringFilter contentFilter;
119
alshabib9290eea2014-09-22 11:58:17 -0700120 @Override
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700121 protected void doExecute() {
toma6897792014-10-08 22:21:05 -0700122 CoreService coreService = get(CoreService.class);
tomcaf3bf72014-09-23 13:20:53 -0700123 DeviceService deviceService = get(DeviceService.class);
124 FlowRuleService service = get(FlowRuleService.class);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100125 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800126
127 compilePredicate();
128
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700129 if (countOnly && !suppressCoreOutput && filter.isEmpty() && remove == null) {
130 if (uri == null) {
131 deviceService.getDevices().forEach(device -> printCount(device, service));
132 } else {
133 Device device = deviceService.getDevice(DeviceId.deviceId(uri));
134 if (device != null) {
135 printCount(device, service);
136 }
137 }
138 return;
139 }
140
Mark4c964522016-03-08 11:26:07 -0800141 SortedMap<Device, List<FlowEntry>> flows = getSortedFlows(deviceService, service, coreService);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700142
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100143 // Remove flows
144 if (remove != null) {
145 flows.values().forEach(flowList -> {
146 if (!remove.isEmpty()) {
147 filter.add(remove);
148 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
149 }
150 if (!filter.isEmpty() || (remove != null && !remove.isEmpty())) {
151 flowList = filterFlows(flowList);
152 this.removeFlowsInteractive(flowList, service, coreService);
153 }
154 });
155 return;
156 }
157
158 // Show flows
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700159 if (outputJson()) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700160 print("%s", json(flows.keySet(), flows));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700161 } else {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800162 flows.forEach((device, flow) -> printFlows(device, flow, coreService));
alshabib9290eea2014-09-22 11:58:17 -0700163 }
alshabib9290eea2014-09-22 11:58:17 -0700164 }
165
alshabib9290eea2014-09-22 11:58:17 -0700166 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100167 * Removes the flows passed as argument after confirmation is provided
168 * for each of them.
169 * If no explicit confirmation is provided, the flow is not removed.
170 *
171 * @param flows list of flows to remove
172 * @param flowService FlowRuleService object
173 * @param coreService CoreService object
174 */
175 public void removeFlowsInteractive(Iterable<FlowEntry> flows,
176 FlowRuleService flowService, CoreService coreService) {
177 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
178 flows.forEach(flow -> {
179 ApplicationId appId = coreService.getAppId(flow.appId());
180 System.out.print(String.format("Id=%s, AppId=%s. Remove? [y/N]: ",
181 flow.id(), appId != null ? appId.name() : "<none>"));
182 String response;
183 try {
184 response = br.readLine();
185 response = response.trim().replace("\n", "");
Jon Halla3fcf672017-03-28 16:53:22 -0700186 if ("y".equals(response)) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100187 flowService.removeFlowRules(flow);
188 }
189 } catch (IOException e) {
190 response = "";
191 }
192 print(response);
193 });
194 }
195
196 /**
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700197 * Produces a JSON array of flows grouped by the each device.
198 *
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700199 * @param devices collection of devices to group flow by
200 * @param flows collection of flows per each device
201 * @return JSON array
202 */
Ray Milkey3078fc02015-05-06 16:14:14 -0700203 private JsonNode json(Iterable<Device> devices,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700204 Map<Device, List<FlowEntry>> flows) {
205 ObjectMapper mapper = new ObjectMapper();
206 ArrayNode result = mapper.createArrayNode();
207 for (Device device : devices) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700208 result.add(json(mapper, device, flows.get(device)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700209 }
210 return result;
211 }
212
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800213 /**
214 * Compiles a predicate to find matching flows based on the command
215 * arguments.
216 */
217 private void compilePredicate() {
218 if (state != null && !state.equals(ANY)) {
219 final FlowEntryState feState = FlowEntryState.valueOf(state.toUpperCase());
220 predicate = predicate.and(f -> f.state().equals(feState));
221 }
222
223 if (table != null) {
224 final int tableId = Integer.parseInt(table);
225 predicate = predicate.and(f -> f.tableId() == tableId);
226 }
227 }
228
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700229 // Produces JSON object with the flows of the given device.
Ray Milkey3078fc02015-05-06 16:14:14 -0700230 private ObjectNode json(ObjectMapper mapper,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700231 Device device, List<FlowEntry> flows) {
232 ObjectNode result = mapper.createObjectNode();
233 ArrayNode array = mapper.createArrayNode();
234
Ray Milkey3078fc02015-05-06 16:14:14 -0700235 flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700236
237 result.put("device", device.id().toString())
238 .put("flowCount", flows.size())
Thomas Vachuskadfe48a72014-10-16 10:32:08 -0700239 .set("flows", array);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700240 return result;
241 }
242
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700243 /**
alshabib9290eea2014-09-22 11:58:17 -0700244 * Returns the list of devices sorted using the device ID URIs.
245 *
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800246 * @param deviceService device service
247 * @param service flow rule service
Ray Milkeyd4334db2016-04-05 17:39:44 -0700248 * @param coreService core service
alshabib9290eea2014-09-22 11:58:17 -0700249 * @return sorted device list
250 */
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800251 protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
Mark4c964522016-03-08 11:26:07 -0800252 FlowRuleService service, CoreService coreService) {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800253 SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
alshabib1c319ff2014-10-04 20:29:09 -0700254 List<FlowEntry> rules;
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800255
Saurav Das554f5e72015-10-27 10:28:19 -0700256 Iterable<Device> devices = null;
257 if (uri == null) {
258 devices = deviceService.getDevices();
259 } else {
260 Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
261 devices = (dev == null) ? deviceService.getDevices()
262 : Collections.singletonList(dev);
263 }
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800264
alshabib99b8fdc2014-09-25 14:30:22 -0700265 for (Device d : devices) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800266 if (predicate.equals(TRUE_PREDICATE)) {
alshabib144a2942014-09-25 18:44:02 -0700267 rules = newArrayList(service.getFlowEntries(d.id()));
268 } else {
269 rules = newArrayList();
alshabib1c319ff2014-10-04 20:29:09 -0700270 for (FlowEntry f : service.getFlowEntries(d.id())) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800271 if (predicate.test(f)) {
alshabib144a2942014-09-25 18:44:02 -0700272 rules.add(f);
273 }
274 }
275 }
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800276 rules.sort(Comparators.FLOW_RULE_COMPARATOR);
Mark4c964522016-03-08 11:26:07 -0800277
278 if (suppressCoreOutput) {
279 short coreAppId = coreService.getAppId("org.onosproject.core").id();
280 rules = rules.stream()
281 .filter(f -> f.appId() != coreAppId)
282 .collect(Collectors.toList());
283 }
alshabib9290eea2014-09-22 11:58:17 -0700284 flows.put(d, rules);
285 }
286 return flows;
287 }
288
289 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100290 * Filter a given list of flows based on the existing content filter.
291 *
292 * @param flows list of flows to filter
293 * @return further filtered list of flows
294 */
295 private List<FlowEntry> filterFlows(List<FlowEntry> flows) {
296 return flows.stream().
297 filter(f -> contentFilter.filter(f)).collect(Collectors.toList());
298 }
299
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700300 private void printCount(Device device, FlowRuleService flowRuleService) {
301 print("deviceId=%s, flowRuleCount=%d", device.id(), flowRuleService.getFlowRuleCount(device.id()));
302 }
303
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100304 /**
alshabib9290eea2014-09-22 11:58:17 -0700305 * Prints flows.
toma6897792014-10-08 22:21:05 -0700306 *
307 * @param d the device
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800308 * @param flows the set of flows for that device
309 * @param coreService core system service
alshabib9290eea2014-09-22 11:58:17 -0700310 */
toma6897792014-10-08 22:21:05 -0700311 protected void printFlows(Device d, List<FlowEntry> flows,
312 CoreService coreService) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100313 List<FlowEntry> filteredFlows = filterFlows(flows);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100314 boolean empty = filteredFlows == null || filteredFlows.isEmpty();
315 print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
Charles Chanf9b94ab2016-02-23 19:31:41 -0800316 if (empty || countOnly) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800317 return;
318 }
319
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100320 for (FlowEntry f : filteredFlows) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800321 if (shortOutput) {
322 print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800323 f.table(), f.priority(), f.selector().criteria(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800324 printTreatment(f.treatment()));
325 } else {
Brian O'Connor9cc799c2015-06-04 19:35:41 -0700326 ApplicationId appId = coreService.getAppId(f.appId());
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800327 print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800328 f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.table(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800329 appId != null ? appId.name() : "<none>",
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800330 f.payLoad() == null ? null : Arrays.toString(f.payLoad().payLoad()),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800331 f.selector().criteria(), f.treatment());
tom1dd08e42014-10-07 11:40:00 -0700332 }
alshabib99b8fdc2014-09-25 14:30:22 -0700333 }
alshabib9290eea2014-09-22 11:58:17 -0700334 }
335
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800336 private String printTreatment(TrafficTreatment treatment) {
337 final String delimiter = ", ";
338 StringBuilder builder = new StringBuilder("[");
339 if (!treatment.immediate().isEmpty()) {
340 builder.append("immediate=" + treatment.immediate() + delimiter);
341 }
342 if (!treatment.deferred().isEmpty()) {
343 builder.append("deferred=" + treatment.deferred() + delimiter);
344 }
345 if (treatment.clearedDeferred()) {
346 builder.append("clearDeferred" + delimiter);
347 }
348 if (treatment.tableTransition() != null) {
349 builder.append("transition=" + treatment.tableTransition() + delimiter);
350 }
351 if (treatment.metered() != null) {
352 builder.append("meter=" + treatment.metered() + delimiter);
353 }
354 if (treatment.writeMetadata() != null) {
355 builder.append("metadata=" + treatment.writeMetadata() + delimiter);
356 }
357 // Chop off last delimiter
358 builder.replace(builder.length() - delimiter.length(), builder.length(), "");
359 builder.append("]");
360 return builder.toString();
361 }
Yuta HIGUCHIe76a24d2014-09-27 00:48:34 -0700362}