blob: 8e70bd54b283b01a9c6c93bb065afa773d2f86ff [file] [log] [blame]
Ray Milkey4f5de002014-12-17 19:26:11 -08001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Ray Milkey4f5de002014-12-17 19:26:11 -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.rest;
17
18import java.util.HashMap;
19import java.util.HashSet;
20import java.util.Set;
21
22import org.hamcrest.Description;
23import org.hamcrest.TypeSafeMatcher;
24import org.junit.After;
25import org.junit.Before;
26import org.junit.Test;
27import org.onlab.osgi.ServiceDirectory;
28import org.onlab.osgi.TestServiceDirectory;
29import org.onlab.packet.MacAddress;
30import org.onlab.rest.BaseResource;
31import org.onosproject.codec.CodecService;
32import org.onosproject.codec.impl.CodecManager;
33import org.onosproject.core.DefaultGroupId;
34import org.onosproject.core.GroupId;
35import org.onosproject.net.DefaultDevice;
36import org.onosproject.net.Device;
37import org.onosproject.net.DeviceId;
38import org.onosproject.net.device.DeviceService;
39import org.onosproject.net.flow.DefaultTrafficSelector;
40import org.onosproject.net.flow.DefaultTrafficTreatment;
41import org.onosproject.net.flow.FlowEntry;
42import org.onosproject.net.flow.FlowId;
43import org.onosproject.net.flow.FlowRuleService;
44import org.onosproject.net.flow.TrafficSelector;
45import org.onosproject.net.flow.TrafficTreatment;
46import org.onosproject.net.flow.criteria.Criterion;
47import org.onosproject.net.flow.instructions.Instruction;
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -080048import org.onosproject.net.flow.instructions.Instructions;
Ray Milkey4f5de002014-12-17 19:26:11 -080049import com.eclipsesource.json.JsonArray;
50import com.eclipsesource.json.JsonObject;
Ray Milkey4f5de002014-12-17 19:26:11 -080051import com.google.common.collect.ImmutableSet;
52import com.sun.jersey.api.client.UniformInterfaceException;
53import com.sun.jersey.api.client.WebResource;
Ray Milkey4f5de002014-12-17 19:26:11 -080054
55import static org.easymock.EasyMock.anyObject;
56import static org.easymock.EasyMock.createMock;
57import static org.easymock.EasyMock.expect;
58import static org.easymock.EasyMock.replay;
59import static org.easymock.EasyMock.verify;
60import static org.hamcrest.Matchers.containsString;
61import static org.hamcrest.Matchers.hasSize;
62import static org.hamcrest.Matchers.is;
63import static org.hamcrest.Matchers.not;
64import static org.hamcrest.Matchers.notNullValue;
65import static org.junit.Assert.assertThat;
66import static org.junit.Assert.fail;
67
68/**
69 * Unit tests for Flows REST APIs.
70 */
Ray Milkey9c3d3362015-01-28 10:39:56 -080071public class FlowsResourceTest extends ResourceTest {
Ray Milkey4f5de002014-12-17 19:26:11 -080072 final FlowRuleService mockFlowService = createMock(FlowRuleService.class);
73 final HashMap<DeviceId, Set<FlowEntry>> rules = new HashMap<>();
74
75 final DeviceService mockDeviceService = createMock(DeviceService.class);
76
77 final DeviceId deviceId1 = DeviceId.deviceId("1");
78 final DeviceId deviceId2 = DeviceId.deviceId("2");
79 final DeviceId deviceId3 = DeviceId.deviceId("3");
80 final Device device1 = new DefaultDevice(null, deviceId1, Device.Type.OTHER,
81 "", "", "", "", null);
82 final Device device2 = new DefaultDevice(null, deviceId2, Device.Type.OTHER,
83 "", "", "", "", null);
84
85 final MockFlowEntry flow1 = new MockFlowEntry(deviceId1, 1);
86 final MockFlowEntry flow2 = new MockFlowEntry(deviceId1, 2);
87
88 final MockFlowEntry flow3 = new MockFlowEntry(deviceId2, 3);
89 final MockFlowEntry flow4 = new MockFlowEntry(deviceId2, 4);
90
91 final MockFlowEntry flow5 = new MockFlowEntry(deviceId2, 5);
92 final MockFlowEntry flow6 = new MockFlowEntry(deviceId2, 6);
93
94 /**
95 * Mock class for a flow entry.
96 */
97 private static class MockFlowEntry implements FlowEntry {
98 final DeviceId deviceId;
99 final long baseValue;
100 TrafficTreatment treatment;
101 TrafficSelector selector;
102
103 public MockFlowEntry(DeviceId deviceId, long id) {
104 this.deviceId = deviceId;
105 this.baseValue = id * 100;
106 }
107
108 @Override
109 public FlowEntryState state() {
110 return FlowEntryState.ADDED;
111 }
112
113 @Override
114 public long life() {
115 return baseValue + 11;
116 }
117
118 @Override
119 public long packets() {
120 return baseValue + 22;
121 }
122
123 @Override
124 public long bytes() {
125 return baseValue + 33;
126 }
127
128 @Override
129 public long lastSeen() {
130 return baseValue + 44;
131 }
132
133 @Override
134 public int errType() {
135 return 0;
136 }
137
138 @Override
139 public int errCode() {
140 return 0;
141 }
142
143 @Override
144 public FlowId id() {
145 final long id = baseValue + 55;
146 return FlowId.valueOf(id);
147 }
148
149 @Override
150 public short appId() {
151 return 2;
152 }
153
154 @Override
155 public GroupId groupId() {
156 return new DefaultGroupId(3);
157 }
158
159 @Override
160 public int priority() {
161 return (int) (baseValue + 66);
162 }
163
164 @Override
165 public DeviceId deviceId() {
166 return deviceId;
167 }
168
169 @Override
170 public TrafficSelector selector() {
171 return selector;
172 }
173
174 @Override
175 public TrafficTreatment treatment() {
176 return treatment;
177 }
178
179 @Override
180 public int timeout() {
181 return (int) (baseValue + 77);
182 }
183
184 @Override
185 public boolean isPermanent() {
186 return false;
187 }
sangho11c30ac2015-01-22 14:30:55 -0800188
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -0800189 @Override
sangho11c30ac2015-01-22 14:30:55 -0800190 public Type type() {
191 return Type.DEFAULT;
192 }
alshabibdb774072015-04-20 13:13:51 -0700193
194 @Override
195 public int tableId() {
196 return 0;
197 }
Ray Milkey4f5de002014-12-17 19:26:11 -0800198 }
199
Ray Milkey4f5de002014-12-17 19:26:11 -0800200 /**
201 * Populates some flows used as testing data.
202 */
203 private void setupMockFlows() {
204 flow2.treatment = DefaultTrafficTreatment.builder()
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -0800205 .add(Instructions.modL0Lambda((short) 4))
206 .add(Instructions.modL0Lambda((short) 5))
Ray Milkey4f5de002014-12-17 19:26:11 -0800207 .setEthDst(MacAddress.BROADCAST)
208 .build();
209 flow2.selector = DefaultTrafficSelector.builder()
210 .matchEthType((short) 3)
211 .matchIPProtocol((byte) 9)
212 .build();
213 flow4.treatment = DefaultTrafficTreatment.builder()
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -0800214 .add(Instructions.modL0Lambda((short) 6))
Ray Milkey4f5de002014-12-17 19:26:11 -0800215 .build();
216 final Set<FlowEntry> flows1 = new HashSet<>();
217 flows1.add(flow1);
218 flows1.add(flow2);
219
220 final Set<FlowEntry> flows2 = new HashSet<>();
221 flows1.add(flow3);
222 flows1.add(flow4);
223
224 rules.put(deviceId1, flows1);
225 rules.put(deviceId2, flows2);
226
227 expect(mockFlowService.getFlowEntries(deviceId1))
228 .andReturn(rules.get(deviceId1)).anyTimes();
229 expect(mockFlowService.getFlowEntries(deviceId2))
230 .andReturn(rules.get(deviceId2)).anyTimes();
231 }
232
233 /**
234 * Sets up the global values for all the tests.
235 */
236 @Before
Ray Milkeyed0b1662015-02-05 09:34:29 -0800237 public void setUpTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800238 // Mock device service
239 expect(mockDeviceService.getDevice(deviceId1))
240 .andReturn(device1);
241 expect(mockDeviceService.getDevice(deviceId2))
242 .andReturn(device2);
243 expect(mockDeviceService.getDevices())
244 .andReturn(ImmutableSet.of(device1, device2));
245
246 // Register the services needed for the test
247 final CodecManager codecService = new CodecManager();
248 codecService.activate();
249 ServiceDirectory testDirectory =
250 new TestServiceDirectory()
251 .add(FlowRuleService.class, mockFlowService)
252 .add(DeviceService.class, mockDeviceService)
253 .add(CodecService.class, codecService);
254
255 BaseResource.setServiceDirectory(testDirectory);
256 }
257
258 /**
259 * Cleans up and verifies the mocks.
Ray Milkey4f5de002014-12-17 19:26:11 -0800260 */
261 @After
Ray Milkeyed0b1662015-02-05 09:34:29 -0800262 public void tearDownTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800263 verify(mockFlowService);
264 }
265
266 /**
267 * Hamcrest matcher to check that a flow representation in JSON matches
268 * the actual flow entry.
269 */
270 public static class FlowJsonMatcher extends TypeSafeMatcher<JsonObject> {
271 private final FlowEntry flow;
272 private String reason = "";
273
274 public FlowJsonMatcher(FlowEntry flowValue) {
275 flow = flowValue;
276 }
277
278 @Override
279 public boolean matchesSafely(JsonObject jsonFlow) {
280 // check id
281 final String jsonId = jsonFlow.get("id").asString();
282 final String flowId = Long.toString(flow.id().value());
283 if (!jsonId.equals(flowId)) {
284 reason = "id " + flow.id().toString();
285 return false;
286 }
287
288 // check application id
289 final int jsonAppId = jsonFlow.get("appId").asInt();
290 if (jsonAppId != flow.appId()) {
291 reason = "appId " + Short.toString(flow.appId());
292 return false;
293 }
294
295 // check device id
296 final String jsonDeviceId = jsonFlow.get("deviceId").asString();
297 if (!jsonDeviceId.equals(flow.deviceId().toString())) {
298 reason = "deviceId " + flow.deviceId();
299 return false;
300 }
301
302 // check treatment and instructions array
303 if (flow.treatment() != null) {
304 final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
305 final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
Ray Milkey42507352015-03-20 15:16:10 -0700306 if (flow.treatment().immediate().size() != jsonInstructions.size()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800307 reason = "instructions array size of " +
Ray Milkey42507352015-03-20 15:16:10 -0700308 Integer.toString(flow.treatment().immediate().size());
Ray Milkey4f5de002014-12-17 19:26:11 -0800309 return false;
310 }
Ray Milkey42507352015-03-20 15:16:10 -0700311 for (final Instruction instruction : flow.treatment().immediate()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800312 boolean instructionFound = false;
Ray Milkey4f5de002014-12-17 19:26:11 -0800313 for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800314 final String jsonType =
315 jsonInstructions.get(instructionIndex)
316 .asObject().get("type").asString();
317 final String instructionType = instruction.type().name();
318 if (jsonType.equals(instructionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800319 instructionFound = true;
320 }
321 }
322 if (!instructionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800323 reason = "instruction " + instruction.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800324 return false;
325 }
326 }
327 }
328
329 // check selector and criteria array
330 if (flow.selector() != null) {
331 final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
332 final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
333 if (flow.selector().criteria().size() != jsonCriteria.size()) {
334 reason = "criteria array size of " +
335 Integer.toString(flow.selector().criteria().size());
336 return false;
337 }
338 for (final Criterion criterion : flow.selector().criteria()) {
339 boolean criterionFound = false;
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800340
Ray Milkey4f5de002014-12-17 19:26:11 -0800341 for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800342 final String jsonType =
343 jsonCriteria.get(criterionIndex)
344 .asObject().get("type").asString();
345 final String criterionType = criterion.type().name();
346 if (jsonType.equals(criterionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800347 criterionFound = true;
348 }
349 }
350 if (!criterionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800351 reason = "criterion " + criterion.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800352 return false;
353 }
354 }
355 }
356
357 return true;
358 }
359
360 @Override
361 public void describeTo(Description description) {
362 description.appendText(reason);
363 }
364 }
365
366 /**
367 * Factory to allocate a flow matcher.
368 *
369 * @param flow flow object we are looking for
370 * @return matcher
371 */
372 private static FlowJsonMatcher matchesFlow(FlowEntry flow) {
373 return new FlowJsonMatcher(flow);
374 }
375
376 /**
377 * Hamcrest matcher to check that a flow is represented properly in a JSON
378 * array of flows.
379 */
380 public static class FlowJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
381 private final FlowEntry flow;
382 private String reason = "";
383
384 public FlowJsonArrayMatcher(FlowEntry flowValue) {
385 flow = flowValue;
386 }
387
388 @Override
389 public boolean matchesSafely(JsonArray json) {
390 boolean flowFound = false;
391
392 for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
393 jsonFlowIndex++) {
394
395 final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
396
397 final String flowId = Long.toString(flow.id().value());
398 final String jsonFlowId = jsonFlow.get("id").asString();
399 if (jsonFlowId.equals(flowId)) {
400 flowFound = true;
401
402 // We found the correct flow, check attribute values
403 assertThat(jsonFlow, matchesFlow(flow));
404 }
405 }
406 if (!flowFound) {
407 reason = "Flow with id " + flow.id().toString() + " not found";
408 return false;
409 } else {
410 return true;
411 }
412 }
413
414 @Override
415 public void describeTo(Description description) {
416 description.appendText(reason);
417 }
418 }
419
420 /**
421 * Factory to allocate a flow array matcher.
422 *
423 * @param flow flow object we are looking for
424 * @return matcher
425 */
426 private static FlowJsonArrayMatcher hasFlow(FlowEntry flow) {
427 return new FlowJsonArrayMatcher(flow);
428 }
429
430 /**
431 * Tests the result of the rest api GET when there are no flows.
432 */
433 @Test
434 public void testFlowsEmptyArray() {
435 expect(mockFlowService.getFlowEntries(deviceId1))
436 .andReturn(null).anyTimes();
437 expect(mockFlowService.getFlowEntries(deviceId2))
438 .andReturn(null).anyTimes();
439 replay(mockFlowService);
440 replay(mockDeviceService);
441 final WebResource rs = resource();
442 final String response = rs.path("flows").get(String.class);
443 assertThat(response, is("{\"flows\":[]}"));
444 }
445
446 /**
447 * Tests the result of the rest api GET when there are active flows.
448 */
449 @Test
450 public void testFlowsPopulatedArray() {
451 setupMockFlows();
452 replay(mockFlowService);
453 replay(mockDeviceService);
454 final WebResource rs = resource();
455 final String response = rs.path("flows").get(String.class);
456 final JsonObject result = JsonObject.readFrom(response);
457 assertThat(result, notNullValue());
458
459 assertThat(result.names(), hasSize(1));
460 assertThat(result.names().get(0), is("flows"));
461 final JsonArray jsonFlows = result.get("flows").asArray();
462 assertThat(jsonFlows, notNullValue());
463 assertThat(jsonFlows, hasFlow(flow1));
464 assertThat(jsonFlows, hasFlow(flow2));
465 assertThat(jsonFlows, hasFlow(flow3));
466 assertThat(jsonFlows, hasFlow(flow4));
467 }
468
469 /**
470 * Tests the result of a rest api GET for a device.
471 */
472 @Test
473 public void testFlowsSingleDevice() {
474 setupMockFlows();
475 final Set<FlowEntry> flows = new HashSet<>();
476 flows.add(flow5);
477 flows.add(flow6);
478 expect(mockFlowService.getFlowEntries(anyObject()))
479 .andReturn(flows).anyTimes();
480 replay(mockFlowService);
481 replay(mockDeviceService);
482 final WebResource rs = resource();
483 final String response = rs.path("flows/" + deviceId3).get(String.class);
484 final JsonObject result = JsonObject.readFrom(response);
485 assertThat(result, notNullValue());
486
487 assertThat(result.names(), hasSize(1));
488 assertThat(result.names().get(0), is("flows"));
489 final JsonArray jsonFlows = result.get("flows").asArray();
490 assertThat(jsonFlows, notNullValue());
491 assertThat(jsonFlows, hasFlow(flow5));
492 assertThat(jsonFlows, hasFlow(flow6));
493 }
494
495 /**
496 * Tests the result of a rest api GET for a device.
497 */
498 @Test
499 public void testFlowsSingleDeviceWithFlowId() {
500 setupMockFlows();
501 final Set<FlowEntry> flows = new HashSet<>();
502 flows.add(flow5);
503 flows.add(flow6);
504 expect(mockFlowService.getFlowEntries(anyObject()))
505 .andReturn(flows).anyTimes();
506 replay(mockFlowService);
507 replay(mockDeviceService);
508 final WebResource rs = resource();
509 final String response = rs.path("flows/" + deviceId3 + "/"
510 + Long.toString(flow5.id().value())).get(String.class);
511 final JsonObject result = JsonObject.readFrom(response);
512 assertThat(result, notNullValue());
513
514 assertThat(result.names(), hasSize(1));
515 assertThat(result.names().get(0), is("flows"));
516 final JsonArray jsonFlows = result.get("flows").asArray();
517 assertThat(jsonFlows, notNullValue());
518 assertThat(jsonFlows, hasFlow(flow5));
519 assertThat(jsonFlows, not(hasFlow(flow6)));
520 }
521
522 /**
523 * Tests that a fetch of a non-existent device object throws an exception.
524 */
525 @Test
526 public void testBadGet() {
527 expect(mockFlowService.getFlowEntries(deviceId1))
528 .andReturn(null).anyTimes();
529 expect(mockFlowService.getFlowEntries(deviceId2))
530 .andReturn(null).anyTimes();
531 replay(mockFlowService);
532 replay(mockDeviceService);
533
534 WebResource rs = resource();
535 try {
536 rs.path("flows/0").get(String.class);
537 fail("Fetch of non-existent device did not throw an exception");
538 } catch (UniformInterfaceException ex) {
539 assertThat(ex.getMessage(),
540 containsString("returned a response status of"));
541 }
542 }
543}