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