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