blob: 098c9f0d5e863a3db333705c687fc4d6648eefa1 [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;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080045import java.util.Collections;
46import java.util.List;
47import java.util.Map;
48import java.util.SortedMap;
49import java.util.TreeMap;
50import java.util.function.Predicate;
Mark4c964522016-03-08 11:26:07 -080051import java.util.stream.Collectors;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080052
53import static com.google.common.collect.Lists.newArrayList;
toma6897792014-10-08 22:21:05 -070054
Mark4c964522016-03-08 11:26:07 -080055
alshabib9290eea2014-09-22 11:58:17 -070056/**
jccf988bf52015-05-05 19:02:50 +080057 * Lists all currently-known flows.
alshabib9290eea2014-09-22 11:58:17 -070058 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -070059@Service
alshabib9290eea2014-09-22 11:58:17 -070060@Command(scope = "onos", name = "flows",
toma6897792014-10-08 22:21:05 -070061 description = "Lists all currently-known flows.")
alshabib9290eea2014-09-22 11:58:17 -070062public class FlowsListCommand extends AbstractShellCommand {
63
Jonathan Hartc7840bd2016-01-21 23:26:29 -080064 private static final Predicate<FlowEntry> TRUE_PREDICATE = f -> true;
65
alshabib144a2942014-09-25 18:44:02 -070066 public static final String ANY = "any";
67
Jonathan Hartc7840bd2016-01-21 23:26:29 -080068 private static final String LONG_FORMAT = " id=%s, state=%s, bytes=%s, "
Sangsik Yoonb1b823f2016-05-16 18:55:39 +090069 + "packets=%s, duration=%s, liveType=%s, priority=%s, tableId=%s, appId=%s, "
Ray Milkey47f09c52019-02-08 18:51:34 -080070 + "selector=%s, treatment=%s";
Jonathan Hartc7840bd2016-01-21 23:26:29 -080071
72 private static final String SHORT_FORMAT = " %s, bytes=%s, packets=%s, "
73 + "table=%s, priority=%s, selector=%s, treatment=%s";
74
75 @Argument(index = 0, name = "state", description = "Flow Rule state",
76 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070077 @Completion(FlowRuleStatusCompleter.class)
Jonathan Hartc7840bd2016-01-21 23:26:29 -080078 String state = null;
alshabib99b8fdc2014-09-25 14:30:22 -070079
alshabib144a2942014-09-25 18:44:02 -070080 @Argument(index = 1, name = "uri", description = "Device ID",
toma6897792014-10-08 22:21:05 -070081 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070082 @Completion(DeviceIdCompleter.class)
alshabib99b8fdc2014-09-25 14:30:22 -070083 String uri = null;
alshabib9290eea2014-09-22 11:58:17 -070084
Jonathan Hartc7840bd2016-01-21 23:26:29 -080085 @Argument(index = 2, name = "table", description = "Table ID",
86 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070087 @Completion(PlaceholderCompleter.class)
Jonathan Hartc7840bd2016-01-21 23:26:29 -080088 String table = null;
89
90 @Option(name = "-s", aliases = "--short",
91 description = "Print more succinct output for each flow",
92 required = false, multiValued = false)
93 private boolean shortOutput = false;
94
Mark4c964522016-03-08 11:26:07 -080095 @Option(name = "-n", aliases = "--no-core-flows",
96 description = "Suppress core flows from output",
97 required = false, multiValued = false)
98 private boolean suppressCoreOutput = false;
99
Charles Chanf9b94ab2016-02-23 19:31:41 -0800100 @Option(name = "-c", aliases = "--count",
101 description = "Print flow count only",
102 required = false, multiValued = false)
103 private boolean countOnly = false;
104
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100105 @Option(name = "-f", aliases = "--filter",
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100106 description = "Filter flows by specific keyword",
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100107 required = false, multiValued = true)
108 private List<String> filter = new ArrayList<>();
109
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100110 @Option(name = "-r", aliases = "--remove",
111 description = "Remove flows by specific keyword",
112 required = false, multiValued = false)
113 private String remove = null;
114
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800115 private Predicate<FlowEntry> predicate = TRUE_PREDICATE;
alshabib64231d82014-09-25 18:25:31 -0700116
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100117 private StringFilter contentFilter;
118
alshabib9290eea2014-09-22 11:58:17 -0700119 @Override
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700120 protected void doExecute() {
toma6897792014-10-08 22:21:05 -0700121 CoreService coreService = get(CoreService.class);
tomcaf3bf72014-09-23 13:20:53 -0700122 DeviceService deviceService = get(DeviceService.class);
123 FlowRuleService service = get(FlowRuleService.class);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100124 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800125
126 compilePredicate();
127
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700128 if (countOnly && !suppressCoreOutput && filter.isEmpty() && remove == null) {
129 if (uri == null) {
130 deviceService.getDevices().forEach(device -> printCount(device, service));
131 } else {
132 Device device = deviceService.getDevice(DeviceId.deviceId(uri));
133 if (device != null) {
134 printCount(device, service);
135 }
136 }
137 return;
138 }
139
Mark4c964522016-03-08 11:26:07 -0800140 SortedMap<Device, List<FlowEntry>> flows = getSortedFlows(deviceService, service, coreService);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700141
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100142 // Remove flows
143 if (remove != null) {
144 flows.values().forEach(flowList -> {
145 if (!remove.isEmpty()) {
146 filter.add(remove);
147 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
148 }
149 if (!filter.isEmpty() || (remove != null && !remove.isEmpty())) {
150 flowList = filterFlows(flowList);
151 this.removeFlowsInteractive(flowList, service, coreService);
152 }
153 });
154 return;
155 }
156
157 // Show flows
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700158 if (outputJson()) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700159 print("%s", json(flows.keySet(), flows));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700160 } else {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800161 flows.forEach((device, flow) -> printFlows(device, flow, coreService));
alshabib9290eea2014-09-22 11:58:17 -0700162 }
alshabib9290eea2014-09-22 11:58:17 -0700163 }
164
alshabib9290eea2014-09-22 11:58:17 -0700165 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100166 * Removes the flows passed as argument after confirmation is provided
167 * for each of them.
168 * If no explicit confirmation is provided, the flow is not removed.
169 *
170 * @param flows list of flows to remove
171 * @param flowService FlowRuleService object
172 * @param coreService CoreService object
173 */
174 public void removeFlowsInteractive(Iterable<FlowEntry> flows,
175 FlowRuleService flowService, CoreService coreService) {
176 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
177 flows.forEach(flow -> {
178 ApplicationId appId = coreService.getAppId(flow.appId());
179 System.out.print(String.format("Id=%s, AppId=%s. Remove? [y/N]: ",
180 flow.id(), appId != null ? appId.name() : "<none>"));
181 String response;
182 try {
183 response = br.readLine();
184 response = response.trim().replace("\n", "");
Jon Halla3fcf672017-03-28 16:53:22 -0700185 if ("y".equals(response)) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100186 flowService.removeFlowRules(flow);
187 }
188 } catch (IOException e) {
189 response = "";
190 }
191 print(response);
192 });
193 }
194
195 /**
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700196 * Produces a JSON array of flows grouped by the each device.
197 *
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700198 * @param devices collection of devices to group flow by
199 * @param flows collection of flows per each device
200 * @return JSON array
201 */
Ray Milkey3078fc02015-05-06 16:14:14 -0700202 private JsonNode json(Iterable<Device> devices,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700203 Map<Device, List<FlowEntry>> flows) {
204 ObjectMapper mapper = new ObjectMapper();
205 ArrayNode result = mapper.createArrayNode();
206 for (Device device : devices) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700207 result.add(json(mapper, device, flows.get(device)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700208 }
209 return result;
210 }
211
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800212 /**
213 * Compiles a predicate to find matching flows based on the command
214 * arguments.
215 */
216 private void compilePredicate() {
217 if (state != null && !state.equals(ANY)) {
218 final FlowEntryState feState = FlowEntryState.valueOf(state.toUpperCase());
219 predicate = predicate.and(f -> f.state().equals(feState));
220 }
221
222 if (table != null) {
223 final int tableId = Integer.parseInt(table);
224 predicate = predicate.and(f -> f.tableId() == tableId);
225 }
226 }
227
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700228 // Produces JSON object with the flows of the given device.
Ray Milkey3078fc02015-05-06 16:14:14 -0700229 private ObjectNode json(ObjectMapper mapper,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700230 Device device, List<FlowEntry> flows) {
231 ObjectNode result = mapper.createObjectNode();
232 ArrayNode array = mapper.createArrayNode();
233
Ray Milkey3078fc02015-05-06 16:14:14 -0700234 flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700235
236 result.put("device", device.id().toString())
237 .put("flowCount", flows.size())
Thomas Vachuskadfe48a72014-10-16 10:32:08 -0700238 .set("flows", array);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700239 return result;
240 }
241
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700242 /**
alshabib9290eea2014-09-22 11:58:17 -0700243 * Returns the list of devices sorted using the device ID URIs.
244 *
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800245 * @param deviceService device service
246 * @param service flow rule service
Ray Milkeyd4334db2016-04-05 17:39:44 -0700247 * @param coreService core service
alshabib9290eea2014-09-22 11:58:17 -0700248 * @return sorted device list
249 */
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800250 protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
Mark4c964522016-03-08 11:26:07 -0800251 FlowRuleService service, CoreService coreService) {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800252 SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
alshabib1c319ff2014-10-04 20:29:09 -0700253 List<FlowEntry> rules;
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800254
Saurav Das554f5e72015-10-27 10:28:19 -0700255 Iterable<Device> devices = null;
256 if (uri == null) {
257 devices = deviceService.getDevices();
258 } else {
259 Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
260 devices = (dev == null) ? deviceService.getDevices()
261 : Collections.singletonList(dev);
262 }
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800263
alshabib99b8fdc2014-09-25 14:30:22 -0700264 for (Device d : devices) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800265 if (predicate.equals(TRUE_PREDICATE)) {
alshabib144a2942014-09-25 18:44:02 -0700266 rules = newArrayList(service.getFlowEntries(d.id()));
267 } else {
268 rules = newArrayList();
alshabib1c319ff2014-10-04 20:29:09 -0700269 for (FlowEntry f : service.getFlowEntries(d.id())) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800270 if (predicate.test(f)) {
alshabib144a2942014-09-25 18:44:02 -0700271 rules.add(f);
272 }
273 }
274 }
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800275 rules.sort(Comparators.FLOW_RULE_COMPARATOR);
Mark4c964522016-03-08 11:26:07 -0800276
277 if (suppressCoreOutput) {
278 short coreAppId = coreService.getAppId("org.onosproject.core").id();
279 rules = rules.stream()
280 .filter(f -> f.appId() != coreAppId)
281 .collect(Collectors.toList());
282 }
alshabib9290eea2014-09-22 11:58:17 -0700283 flows.put(d, rules);
284 }
285 return flows;
286 }
287
288 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100289 * Filter a given list of flows based on the existing content filter.
290 *
291 * @param flows list of flows to filter
292 * @return further filtered list of flows
293 */
294 private List<FlowEntry> filterFlows(List<FlowEntry> flows) {
295 return flows.stream().
296 filter(f -> contentFilter.filter(f)).collect(Collectors.toList());
297 }
298
Jordan Haltermana49c60a2018-05-15 23:01:44 -0700299 private void printCount(Device device, FlowRuleService flowRuleService) {
300 print("deviceId=%s, flowRuleCount=%d", device.id(), flowRuleService.getFlowRuleCount(device.id()));
301 }
302
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100303 /**
alshabib9290eea2014-09-22 11:58:17 -0700304 * Prints flows.
toma6897792014-10-08 22:21:05 -0700305 *
306 * @param d the device
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800307 * @param flows the set of flows for that device
308 * @param coreService core system service
alshabib9290eea2014-09-22 11:58:17 -0700309 */
toma6897792014-10-08 22:21:05 -0700310 protected void printFlows(Device d, List<FlowEntry> flows,
311 CoreService coreService) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100312 List<FlowEntry> filteredFlows = filterFlows(flows);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100313 boolean empty = filteredFlows == null || filteredFlows.isEmpty();
314 print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
Charles Chanf9b94ab2016-02-23 19:31:41 -0800315 if (empty || countOnly) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800316 return;
317 }
318
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100319 for (FlowEntry f : filteredFlows) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800320 if (shortOutput) {
321 print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800322 f.table(), f.priority(), f.selector().criteria(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800323 printTreatment(f.treatment()));
324 } else {
Brian O'Connor9cc799c2015-06-04 19:35:41 -0700325 ApplicationId appId = coreService.getAppId(f.appId());
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800326 print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
Yi Tsengac81f5f2017-11-14 00:35:43 -0800327 f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.table(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800328 appId != null ? appId.name() : "<none>",
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800329 f.selector().criteria(), f.treatment());
tom1dd08e42014-10-07 11:40:00 -0700330 }
alshabib99b8fdc2014-09-25 14:30:22 -0700331 }
alshabib9290eea2014-09-22 11:58:17 -0700332 }
333
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800334 private String printTreatment(TrafficTreatment treatment) {
335 final String delimiter = ", ";
336 StringBuilder builder = new StringBuilder("[");
337 if (!treatment.immediate().isEmpty()) {
338 builder.append("immediate=" + treatment.immediate() + delimiter);
339 }
340 if (!treatment.deferred().isEmpty()) {
341 builder.append("deferred=" + treatment.deferred() + delimiter);
342 }
343 if (treatment.clearedDeferred()) {
344 builder.append("clearDeferred" + delimiter);
345 }
346 if (treatment.tableTransition() != null) {
347 builder.append("transition=" + treatment.tableTransition() + delimiter);
348 }
349 if (treatment.metered() != null) {
350 builder.append("meter=" + treatment.metered() + delimiter);
351 }
352 if (treatment.writeMetadata() != null) {
353 builder.append("metadata=" + treatment.writeMetadata() + delimiter);
354 }
355 // Chop off last delimiter
356 builder.replace(builder.length() - delimiter.length(), builder.length(), "");
357 builder.append("]");
358 return builder.toString();
359 }
Yuta HIGUCHIe76a24d2014-09-27 00:48:34 -0700360}