blob: 57c9fb1a80d3f9dfc7e2f772db992dd0dc0ea27c [file] [log] [blame]
yoonseonbc0d76f2017-01-05 14:52:05 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
yoonseonbc0d76f2017-01-05 14:52:05 -08003 *
4 * 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
7 *
8 * 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.
15 */
16package org.onosproject.cli.net.vnet;
17
18import 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;
yoonseonbc0d76f2017-01-05 14:52:05 -080027import org.onlab.util.StringFilter;
28import org.onosproject.cli.AbstractShellCommand;
Ray Milkey0068fd02018-10-11 15:45:39 -070029import org.onosproject.cli.PlaceholderCompleter;
30import org.onosproject.cli.net.FlowRuleStatusCompleter;
yoonseonbc0d76f2017-01-05 14:52:05 -080031import org.onosproject.core.ApplicationId;
32import org.onosproject.core.CoreService;
33import org.onosproject.incubator.net.virtual.NetworkId;
34import org.onosproject.incubator.net.virtual.VirtualNetworkService;
35import org.onosproject.net.Device;
36import org.onosproject.net.DeviceId;
37import org.onosproject.net.device.DeviceService;
38import org.onosproject.net.flow.FlowEntry;
39import org.onosproject.net.flow.FlowEntry.FlowEntryState;
40import org.onosproject.net.flow.FlowRuleService;
41import org.onosproject.net.flow.TrafficTreatment;
42import org.onosproject.utils.Comparators;
43
44import java.util.ArrayList;
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -080045import java.util.Arrays;
yoonseonbc0d76f2017-01-05 14:52:05 -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;
52import java.util.stream.Collectors;
53
54import static com.google.common.collect.Lists.newArrayList;
55
56
57/**
58 * Lists all currently-known flows.
59 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -070060@Service
yoonseonbc0d76f2017-01-05 14:52:05 -080061@Command(scope = "onos", name = "vnet-flows",
62 description = "Lists all currently-known flows for a virtual network.")
63public class VirtualFlowsListCommand extends AbstractShellCommand {
64
65 private static final Predicate<FlowEntry> TRUE_PREDICATE = f -> true;
66
67 public static final String ANY = "any";
68
69 private static final String LONG_FORMAT = " id=%s, state=%s, bytes=%s, "
70 + "packets=%s, duration=%s, liveType=%s, priority=%s, tableId=%s, appId=%s, "
71 + "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 = "networkId", description = "Network ID",
77 required = true, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070078 @Completion(VirtualNetworkCompleter.class)
yoonseonbc0d76f2017-01-05 14:52:05 -080079 Long networkId = null;
80
81 @Argument(index = 1, name = "state", description = "Flow Rule state",
82 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070083 @Completion(FlowRuleStatusCompleter.class)
yoonseonbc0d76f2017-01-05 14:52:05 -080084 String state = null;
85
86 @Argument(index = 2, name = "uri", description = "Device ID",
87 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070088 @Completion(VirtualDeviceCompleter.class)
yoonseonbc0d76f2017-01-05 14:52:05 -080089 String uri = null;
90
91 @Argument(index = 3, name = "table", description = "Table ID",
92 required = false, multiValued = false)
Ray Milkey0068fd02018-10-11 15:45:39 -070093 @Completion(PlaceholderCompleter.class)
yoonseonbc0d76f2017-01-05 14:52:05 -080094 String table = null;
95
96 @Option(name = "-s", aliases = "--short",
97 description = "Print more succinct output for each flow",
98 required = false, multiValued = false)
99 private boolean shortOutput = false;
100
101 @Option(name = "-c", aliases = "--count",
102 description = "Print flow count only",
103 required = false, multiValued = false)
104 private boolean countOnly = false;
105
106 @Option(name = "-f", aliases = "--filter",
107 description = "Filter flows by specific key",
108 required = false, multiValued = true)
109 private List<String> filter = new ArrayList<>();
110
111 private Predicate<FlowEntry> predicate = TRUE_PREDICATE;
112
113 private StringFilter contentFilter;
114
115 @Override
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700116 protected void doExecute() {
yoonseonbc0d76f2017-01-05 14:52:05 -0800117 CoreService coreService = get(CoreService.class);
118
119 VirtualNetworkService vnetservice = get(VirtualNetworkService.class);
120 DeviceService deviceService = vnetservice.get(NetworkId.networkId(networkId),
121 DeviceService.class);
122 FlowRuleService service = vnetservice.get(NetworkId.networkId(networkId),
123 FlowRuleService.class);
124 contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
125
126 compilePredicate();
127
128 SortedMap<Device, List<FlowEntry>> flows = getSortedFlows(deviceService, service);
129
130 if (outputJson()) {
131 print("%s", json(flows.keySet(), flows));
132 } else {
133 flows.forEach((device, flow) -> printFlows(device, flow, coreService));
134 }
135 }
136
137 /**
138 * Produces a JSON array of flows grouped by the each device.
139 *
140 * @param devices collection of devices to group flow by
141 * @param flows collection of flows per each device
142 * @return JSON array
143 */
144 private JsonNode json(Iterable<Device> devices,
145 Map<Device, List<FlowEntry>> flows) {
146 ObjectMapper mapper = new ObjectMapper();
147 ArrayNode result = mapper.createArrayNode();
148 for (Device device : devices) {
149 result.add(json(mapper, device, flows.get(device)));
150 }
151 return result;
152 }
153
154 /**
155 * Compiles a predicate to find matching flows based on the command
156 * arguments.
157 */
158 private void compilePredicate() {
159 if (state != null && !state.equals(ANY)) {
160 final FlowEntryState feState = FlowEntryState.valueOf(state.toUpperCase());
161 predicate = predicate.and(f -> f.state().equals(feState));
162 }
163
164 if (table != null) {
165 final int tableId = Integer.parseInt(table);
166 predicate = predicate.and(f -> f.tableId() == tableId);
167 }
168 }
169
170 // Produces JSON object with the flows of the given device.
171 private ObjectNode json(ObjectMapper mapper,
172 Device device, List<FlowEntry> flows) {
173 ObjectNode result = mapper.createObjectNode();
174 ArrayNode array = mapper.createArrayNode();
175
176 flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));
177
178 result.put("device", device.id().toString())
179 .put("flowCount", flows.size())
180 .set("flows", array);
181 return result;
182 }
183
184 /**
185 * Returns the list of devices sorted using the device ID URIs.
186 *
187 * @param deviceService device service
188 * @param service flow rule service
189 * @return sorted device list
190 */
191 protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
192 FlowRuleService service) {
193 SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
194 List<FlowEntry> rules;
195
196 Iterable<Device> devices = null;
197 if (uri == null) {
198 devices = deviceService.getDevices();
199 } else {
200 Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
201 devices = (dev == null) ? deviceService.getDevices()
202 : Collections.singletonList(dev);
203 }
204
205 for (Device d : devices) {
206 if (predicate.equals(TRUE_PREDICATE)) {
207 rules = newArrayList(service.getFlowEntries(d.id()));
208 } else {
209 rules = newArrayList();
210 for (FlowEntry f : service.getFlowEntries(d.id())) {
211 if (predicate.test(f)) {
212 rules.add(f);
213 }
214 }
215 }
216 rules.sort(Comparators.FLOW_RULE_COMPARATOR);
217
218 flows.put(d, rules);
219 }
220 return flows;
221 }
222
223 /**
224 * Prints flows.
225 *
226 * @param d the device
227 * @param flows the set of flows for that device
228 * @param coreService core system service
229 */
230 protected void printFlows(Device d, List<FlowEntry> flows,
231 CoreService coreService) {
232 List<FlowEntry> filteredFlows = flows.stream().
233 filter(f -> contentFilter.filter(f)).collect(Collectors.toList());
234 boolean empty = filteredFlows == null || filteredFlows.isEmpty();
235 print("deviceId=%s, flowRuleCount=%d", d.id(), empty ? 0 : filteredFlows.size());
236 if (empty || countOnly) {
237 return;
238 }
239
240 for (FlowEntry f : filteredFlows) {
241 if (shortOutput) {
242 print(SHORT_FORMAT, f.state(), f.bytes(), f.packets(),
243 f.tableId(), f.priority(), f.selector().criteria(),
244 printTreatment(f.treatment()));
245 } else {
246 ApplicationId appId = coreService.getAppId(f.appId());
247 print(LONG_FORMAT, Long.toHexString(f.id().value()), f.state(),
248 f.bytes(), f.packets(), f.life(), f.liveType(), f.priority(), f.tableId(),
249 appId != null ? appId.name() : "<none>",
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800250 f.payLoad() == null ? null : Arrays.toString(f.payLoad().payLoad()),
yoonseonbc0d76f2017-01-05 14:52:05 -0800251 f.selector().criteria(), f.treatment());
252 }
253 }
254 }
255
256 private String printTreatment(TrafficTreatment treatment) {
257 final String delimiter = ", ";
258 StringBuilder builder = new StringBuilder("[");
259 if (!treatment.immediate().isEmpty()) {
260 builder.append("immediate=" + treatment.immediate() + delimiter);
261 }
262 if (!treatment.deferred().isEmpty()) {
263 builder.append("deferred=" + treatment.deferred() + delimiter);
264 }
265 if (treatment.clearedDeferred()) {
266 builder.append("clearDeferred" + delimiter);
267 }
268 if (treatment.tableTransition() != null) {
269 builder.append("transition=" + treatment.tableTransition() + delimiter);
270 }
271 if (treatment.metered() != null) {
272 builder.append("meter=" + treatment.metered() + delimiter);
273 }
274 if (treatment.writeMetadata() != null) {
275 builder.append("metadata=" + treatment.writeMetadata() + delimiter);
276 }
277 // Chop off last delimiter
278 builder.replace(builder.length() - delimiter.length(), builder.length(), "");
279 builder.append("]");
280 return builder.toString();
281 }
282
283}