blob: 677049075763bf6ff7e7bff8ddba2dccd23f3388 [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;
Jonathan Hartc7840bd2016-01-21 23:26:29 -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;
Mark4c964522016-03-08 11:26:07 -080048import java.util.stream.Collectors;
Jonathan Hartc7840bd2016-01-21 23:26:29 -080049
50import static com.google.common.collect.Lists.newArrayList;
toma6897792014-10-08 22:21:05 -070051
Mark4c964522016-03-08 11:26:07 -080052
alshabib9290eea2014-09-22 11:58:17 -070053/**
jccf988bf52015-05-05 19:02:50 +080054 * Lists all currently-known flows.
alshabib9290eea2014-09-22 11:58:17 -070055 */
56@Command(scope = "onos", name = "flows",
toma6897792014-10-08 22:21:05 -070057 description = "Lists all currently-known flows.")
alshabib9290eea2014-09-22 11:58:17 -070058public class FlowsListCommand extends AbstractShellCommand {
59
Jonathan Hartc7840bd2016-01-21 23:26:29 -080060 private static final Predicate<FlowEntry> TRUE_PREDICATE = f -> true;
61
alshabib144a2942014-09-25 18:44:02 -070062 public static final String ANY = "any";
63
Jonathan Hartc7840bd2016-01-21 23:26:29 -080064 private static final String LONG_FORMAT = " id=%s, state=%s, bytes=%s, "
Sangsik Yoonb1b823f2016-05-16 18:55:39 +090065 + "packets=%s, duration=%s, liveType=%s, priority=%s, tableId=%s, appId=%s, "
Jonathan Hartc7840bd2016-01-21 23:26:29 -080066 + "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 = "state", description = "Flow Rule state",
72 required = false, multiValued = false)
73 String state = null;
alshabib99b8fdc2014-09-25 14:30:22 -070074
alshabib144a2942014-09-25 18:44:02 -070075 @Argument(index = 1, name = "uri", description = "Device ID",
toma6897792014-10-08 22:21:05 -070076 required = false, multiValued = false)
alshabib99b8fdc2014-09-25 14:30:22 -070077 String uri = null;
alshabib9290eea2014-09-22 11:58:17 -070078
Jonathan Hartc7840bd2016-01-21 23:26:29 -080079 @Argument(index = 2, name = "table", description = "Table ID",
80 required = false, multiValued = false)
81 String table = null;
82
83 @Option(name = "-s", aliases = "--short",
84 description = "Print more succinct output for each flow",
85 required = false, multiValued = false)
86 private boolean shortOutput = false;
87
Mark4c964522016-03-08 11:26:07 -080088 @Option(name = "-n", aliases = "--no-core-flows",
89 description = "Suppress core flows from output",
90 required = false, multiValued = false)
91 private boolean suppressCoreOutput = false;
92
Charles Chanf9b94ab2016-02-23 19:31:41 -080093 @Option(name = "-c", aliases = "--count",
94 description = "Print flow count only",
95 required = false, multiValued = false)
96 private boolean countOnly = false;
97
Carolina Fernandezfa56d142016-11-14 01:13:26 +010098 @Option(name = "-f", aliases = "--filter",
Carolina Fernandez0b1449d2016-12-04 13:30:36 +010099 description = "Filter flows by specific keyword",
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100100 required = false, multiValued = true)
101 private List<String> filter = new ArrayList<>();
102
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100103 @Option(name = "-r", aliases = "--remove",
104 description = "Remove flows by specific keyword",
105 required = false, multiValued = false)
106 private String remove = null;
107
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800108 private Predicate<FlowEntry> predicate = TRUE_PREDICATE;
alshabib64231d82014-09-25 18:25:31 -0700109
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100110 private StringFilter contentFilter;
111
alshabib9290eea2014-09-22 11:58:17 -0700112 @Override
tom0872a172014-09-23 11:24:26 -0700113 protected void execute() {
toma6897792014-10-08 22:21:05 -0700114 CoreService coreService = get(CoreService.class);
tomcaf3bf72014-09-23 13:20:53 -0700115 DeviceService deviceService = get(DeviceService.class);
116 FlowRuleService service = get(FlowRuleService.class);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100117 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800118
119 compilePredicate();
120
Mark4c964522016-03-08 11:26:07 -0800121 SortedMap<Device, List<FlowEntry>> flows = getSortedFlows(deviceService, service, coreService);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700122
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100123 // Remove flows
124 if (remove != null) {
125 flows.values().forEach(flowList -> {
126 if (!remove.isEmpty()) {
127 filter.add(remove);
128 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
129 }
130 if (!filter.isEmpty() || (remove != null && !remove.isEmpty())) {
131 flowList = filterFlows(flowList);
132 this.removeFlowsInteractive(flowList, service, coreService);
133 }
134 });
135 return;
136 }
137
138 // Show flows
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700139 if (outputJson()) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700140 print("%s", json(flows.keySet(), flows));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700141 } else {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800142 flows.forEach((device, flow) -> printFlows(device, flow, coreService));
alshabib9290eea2014-09-22 11:58:17 -0700143 }
alshabib9290eea2014-09-22 11:58:17 -0700144 }
145
alshabib9290eea2014-09-22 11:58:17 -0700146 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100147 * Removes the flows passed as argument after confirmation is provided
148 * for each of them.
149 * If no explicit confirmation is provided, the flow is not removed.
150 *
151 * @param flows list of flows to remove
152 * @param flowService FlowRuleService object
153 * @param coreService CoreService object
154 */
155 public void removeFlowsInteractive(Iterable<FlowEntry> flows,
156 FlowRuleService flowService, CoreService coreService) {
157 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
158 flows.forEach(flow -> {
159 ApplicationId appId = coreService.getAppId(flow.appId());
160 System.out.print(String.format("Id=%s, AppId=%s. Remove? [y/N]: ",
161 flow.id(), appId != null ? appId.name() : "<none>"));
162 String response;
163 try {
164 response = br.readLine();
165 response = response.trim().replace("\n", "");
Jon Halla3fcf672017-03-28 16:53:22 -0700166 if ("y".equals(response)) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100167 flowService.removeFlowRules(flow);
168 }
169 } catch (IOException e) {
170 response = "";
171 }
172 print(response);
173 });
174 }
175
176 /**
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700177 * Produces a JSON array of flows grouped by the each device.
178 *
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700179 * @param devices collection of devices to group flow by
180 * @param flows collection of flows per each device
181 * @return JSON array
182 */
Ray Milkey3078fc02015-05-06 16:14:14 -0700183 private JsonNode json(Iterable<Device> devices,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700184 Map<Device, List<FlowEntry>> flows) {
185 ObjectMapper mapper = new ObjectMapper();
186 ArrayNode result = mapper.createArrayNode();
187 for (Device device : devices) {
Ray Milkey3078fc02015-05-06 16:14:14 -0700188 result.add(json(mapper, device, flows.get(device)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700189 }
190 return result;
191 }
192
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800193 /**
194 * Compiles a predicate to find matching flows based on the command
195 * arguments.
196 */
197 private void compilePredicate() {
198 if (state != null && !state.equals(ANY)) {
199 final FlowEntryState feState = FlowEntryState.valueOf(state.toUpperCase());
200 predicate = predicate.and(f -> f.state().equals(feState));
201 }
202
203 if (table != null) {
204 final int tableId = Integer.parseInt(table);
205 predicate = predicate.and(f -> f.tableId() == tableId);
206 }
207 }
208
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700209 // Produces JSON object with the flows of the given device.
Ray Milkey3078fc02015-05-06 16:14:14 -0700210 private ObjectNode json(ObjectMapper mapper,
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700211 Device device, List<FlowEntry> flows) {
212 ObjectNode result = mapper.createObjectNode();
213 ArrayNode array = mapper.createArrayNode();
214
Ray Milkey3078fc02015-05-06 16:14:14 -0700215 flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700216
217 result.put("device", device.id().toString())
218 .put("flowCount", flows.size())
Thomas Vachuskadfe48a72014-10-16 10:32:08 -0700219 .set("flows", array);
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700220 return result;
221 }
222
Thomas Vachuskabb0272e2014-10-16 09:32:04 -0700223 /**
alshabib9290eea2014-09-22 11:58:17 -0700224 * Returns the list of devices sorted using the device ID URIs.
225 *
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800226 * @param deviceService device service
227 * @param service flow rule service
Ray Milkeyd4334db2016-04-05 17:39:44 -0700228 * @param coreService core service
alshabib9290eea2014-09-22 11:58:17 -0700229 * @return sorted device list
230 */
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800231 protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
Mark4c964522016-03-08 11:26:07 -0800232 FlowRuleService service, CoreService coreService) {
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800233 SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
alshabib1c319ff2014-10-04 20:29:09 -0700234 List<FlowEntry> rules;
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800235
Saurav Das554f5e72015-10-27 10:28:19 -0700236 Iterable<Device> devices = null;
237 if (uri == null) {
238 devices = deviceService.getDevices();
239 } else {
240 Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
241 devices = (dev == null) ? deviceService.getDevices()
242 : Collections.singletonList(dev);
243 }
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800244
alshabib99b8fdc2014-09-25 14:30:22 -0700245 for (Device d : devices) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800246 if (predicate.equals(TRUE_PREDICATE)) {
alshabib144a2942014-09-25 18:44:02 -0700247 rules = newArrayList(service.getFlowEntries(d.id()));
248 } else {
249 rules = newArrayList();
alshabib1c319ff2014-10-04 20:29:09 -0700250 for (FlowEntry f : service.getFlowEntries(d.id())) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800251 if (predicate.test(f)) {
alshabib144a2942014-09-25 18:44:02 -0700252 rules.add(f);
253 }
254 }
255 }
Yuta HIGUCHI8791a812015-02-10 09:43:52 -0800256 rules.sort(Comparators.FLOW_RULE_COMPARATOR);
Mark4c964522016-03-08 11:26:07 -0800257
258 if (suppressCoreOutput) {
259 short coreAppId = coreService.getAppId("org.onosproject.core").id();
260 rules = rules.stream()
261 .filter(f -> f.appId() != coreAppId)
262 .collect(Collectors.toList());
263 }
alshabib9290eea2014-09-22 11:58:17 -0700264 flows.put(d, rules);
265 }
266 return flows;
267 }
268
269 /**
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100270 * Filter a given list of flows based on the existing content filter.
271 *
272 * @param flows list of flows to filter
273 * @return further filtered list of flows
274 */
275 private List<FlowEntry> filterFlows(List<FlowEntry> flows) {
276 return flows.stream().
277 filter(f -> contentFilter.filter(f)).collect(Collectors.toList());
278 }
279
280 /**
alshabib9290eea2014-09-22 11:58:17 -0700281 * Prints flows.
toma6897792014-10-08 22:21:05 -0700282 *
283 * @param d the device
Yuta HIGUCHI5c947272014-11-03 21:39:21 -0800284 * @param flows the set of flows for that device
285 * @param coreService core system service
alshabib9290eea2014-09-22 11:58:17 -0700286 */
toma6897792014-10-08 22:21:05 -0700287 protected void printFlows(Device d, List<FlowEntry> flows,
288 CoreService coreService) {
Carolina Fernandez0b1449d2016-12-04 13:30:36 +0100289 List<FlowEntry> filteredFlows = filterFlows(flows);
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100290 boolean empty = filteredFlows == null || filteredFlows.isEmpty();
291 print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
Charles Chanf9b94ab2016-02-23 19:31:41 -0800292 if (empty || countOnly) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800293 return;
294 }
295
Carolina Fernandezfa56d142016-11-14 01:13:26 +0100296 for (FlowEntry f : filteredFlows) {
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800297 if (shortOutput) {
298 print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
299 f.tableId(), f.priority(), f.selector().criteria(),
300 printTreatment(f.treatment()));
301 } else {
Brian O'Connor9cc799c2015-06-04 19:35:41 -0700302 ApplicationId appId = coreService.getAppId(f.appId());
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800303 print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900304 f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.tableId(),
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800305 appId != null ? appId.name() : "<none>",
306 f.payLoad() == null ? null : f.payLoad().payLoad().toString(),
307 f.selector().criteria(), f.treatment());
tom1dd08e42014-10-07 11:40:00 -0700308 }
alshabib99b8fdc2014-09-25 14:30:22 -0700309 }
alshabib9290eea2014-09-22 11:58:17 -0700310 }
311
Jonathan Hartc7840bd2016-01-21 23:26:29 -0800312 private String printTreatment(TrafficTreatment treatment) {
313 final String delimiter = ", ";
314 StringBuilder builder = new StringBuilder("[");
315 if (!treatment.immediate().isEmpty()) {
316 builder.append("immediate=" + treatment.immediate() + delimiter);
317 }
318 if (!treatment.deferred().isEmpty()) {
319 builder.append("deferred=" + treatment.deferred() + delimiter);
320 }
321 if (treatment.clearedDeferred()) {
322 builder.append("clearDeferred" + delimiter);
323 }
324 if (treatment.tableTransition() != null) {
325 builder.append("transition=" + treatment.tableTransition() + delimiter);
326 }
327 if (treatment.metered() != null) {
328 builder.append("meter=" + treatment.metered() + delimiter);
329 }
330 if (treatment.writeMetadata() != null) {
331 builder.append("metadata=" + treatment.writeMetadata() + delimiter);
332 }
333 // Chop off last delimiter
334 builder.replace(builder.length() - delimiter.length(), builder.length(), "");
335 builder.append("]");
336 return builder.toString();
337 }
Yuta HIGUCHIe76a24d2014-09-27 00:48:34 -0700338}