blob: 5f52081a2773c2a190bfc6afcd3f332e5e7e3f89 [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 }
189 }
190
Ray Milkey4f5de002014-12-17 19:26:11 -0800191 /**
192 * Populates some flows used as testing data.
193 */
194 private void setupMockFlows() {
195 flow2.treatment = DefaultTrafficTreatment.builder()
196 .add(new L0ModificationInstruction.ModLambdaInstruction(
197 L0ModificationInstruction.L0SubType.LAMBDA, (short) 4))
198 .add(new L0ModificationInstruction.ModLambdaInstruction(
199 L0ModificationInstruction.L0SubType.LAMBDA, (short) 5))
200 .setEthDst(MacAddress.BROADCAST)
201 .build();
202 flow2.selector = DefaultTrafficSelector.builder()
203 .matchEthType((short) 3)
204 .matchIPProtocol((byte) 9)
205 .build();
206 flow4.treatment = DefaultTrafficTreatment.builder()
207 .add(new L0ModificationInstruction.ModLambdaInstruction(
208 L0ModificationInstruction.L0SubType.LAMBDA, (short) 6))
209 .build();
210 final Set<FlowEntry> flows1 = new HashSet<>();
211 flows1.add(flow1);
212 flows1.add(flow2);
213
214 final Set<FlowEntry> flows2 = new HashSet<>();
215 flows1.add(flow3);
216 flows1.add(flow4);
217
218 rules.put(deviceId1, flows1);
219 rules.put(deviceId2, flows2);
220
221 expect(mockFlowService.getFlowEntries(deviceId1))
222 .andReturn(rules.get(deviceId1)).anyTimes();
223 expect(mockFlowService.getFlowEntries(deviceId2))
224 .andReturn(rules.get(deviceId2)).anyTimes();
225 }
226
227 /**
228 * Sets up the global values for all the tests.
229 */
230 @Before
231 public void setUp() {
232 // Mock device service
233 expect(mockDeviceService.getDevice(deviceId1))
234 .andReturn(device1);
235 expect(mockDeviceService.getDevice(deviceId2))
236 .andReturn(device2);
237 expect(mockDeviceService.getDevices())
238 .andReturn(ImmutableSet.of(device1, device2));
239
240 // Register the services needed for the test
241 final CodecManager codecService = new CodecManager();
242 codecService.activate();
243 ServiceDirectory testDirectory =
244 new TestServiceDirectory()
245 .add(FlowRuleService.class, mockFlowService)
246 .add(DeviceService.class, mockDeviceService)
247 .add(CodecService.class, codecService);
248
249 BaseResource.setServiceDirectory(testDirectory);
250 }
251
252 /**
253 * Cleans up and verifies the mocks.
254 *
255 * @throws Exception if the super teardown fails.
256 */
257 @After
258 public void tearDown() throws Exception {
259 super.tearDown();
260 verify(mockFlowService);
261 }
262
263 /**
264 * Hamcrest matcher to check that a flow representation in JSON matches
265 * the actual flow entry.
266 */
267 public static class FlowJsonMatcher extends TypeSafeMatcher<JsonObject> {
268 private final FlowEntry flow;
269 private String reason = "";
270
271 public FlowJsonMatcher(FlowEntry flowValue) {
272 flow = flowValue;
273 }
274
275 @Override
276 public boolean matchesSafely(JsonObject jsonFlow) {
277 // check id
278 final String jsonId = jsonFlow.get("id").asString();
279 final String flowId = Long.toString(flow.id().value());
280 if (!jsonId.equals(flowId)) {
281 reason = "id " + flow.id().toString();
282 return false;
283 }
284
285 // check application id
286 final int jsonAppId = jsonFlow.get("appId").asInt();
287 if (jsonAppId != flow.appId()) {
288 reason = "appId " + Short.toString(flow.appId());
289 return false;
290 }
291
292 // check device id
293 final String jsonDeviceId = jsonFlow.get("deviceId").asString();
294 if (!jsonDeviceId.equals(flow.deviceId().toString())) {
295 reason = "deviceId " + flow.deviceId();
296 return false;
297 }
298
299 // check treatment and instructions array
300 if (flow.treatment() != null) {
301 final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
302 final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
303 if (flow.treatment().instructions().size() != jsonInstructions.size()) {
304 reason = "instructions array size of " +
305 Integer.toString(flow.treatment().instructions().size());
306 return false;
307 }
308 for (final Instruction instruction : flow.treatment().instructions()) {
309 boolean instructionFound = false;
Ray Milkey4f5de002014-12-17 19:26:11 -0800310 for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800311 final String jsonType =
312 jsonInstructions.get(instructionIndex)
313 .asObject().get("type").asString();
314 final String instructionType = instruction.type().name();
315 if (jsonType.equals(instructionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800316 instructionFound = true;
317 }
318 }
319 if (!instructionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800320 reason = "instruction " + instruction.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800321 return false;
322 }
323 }
324 }
325
326 // check selector and criteria array
327 if (flow.selector() != null) {
328 final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
329 final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
330 if (flow.selector().criteria().size() != jsonCriteria.size()) {
331 reason = "criteria array size of " +
332 Integer.toString(flow.selector().criteria().size());
333 return false;
334 }
335 for (final Criterion criterion : flow.selector().criteria()) {
336 boolean criterionFound = false;
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800337
Ray Milkey4f5de002014-12-17 19:26:11 -0800338 for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800339 final String jsonType =
340 jsonCriteria.get(criterionIndex)
341 .asObject().get("type").asString();
342 final String criterionType = criterion.type().name();
343 if (jsonType.equals(criterionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800344 criterionFound = true;
345 }
346 }
347 if (!criterionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800348 reason = "criterion " + criterion.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800349 return false;
350 }
351 }
352 }
353
354 return true;
355 }
356
357 @Override
358 public void describeTo(Description description) {
359 description.appendText(reason);
360 }
361 }
362
363 /**
364 * Factory to allocate a flow matcher.
365 *
366 * @param flow flow object we are looking for
367 * @return matcher
368 */
369 private static FlowJsonMatcher matchesFlow(FlowEntry flow) {
370 return new FlowJsonMatcher(flow);
371 }
372
373 /**
374 * Hamcrest matcher to check that a flow is represented properly in a JSON
375 * array of flows.
376 */
377 public static class FlowJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
378 private final FlowEntry flow;
379 private String reason = "";
380
381 public FlowJsonArrayMatcher(FlowEntry flowValue) {
382 flow = flowValue;
383 }
384
385 @Override
386 public boolean matchesSafely(JsonArray json) {
387 boolean flowFound = false;
388
389 for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
390 jsonFlowIndex++) {
391
392 final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
393
394 final String flowId = Long.toString(flow.id().value());
395 final String jsonFlowId = jsonFlow.get("id").asString();
396 if (jsonFlowId.equals(flowId)) {
397 flowFound = true;
398
399 // We found the correct flow, check attribute values
400 assertThat(jsonFlow, matchesFlow(flow));
401 }
402 }
403 if (!flowFound) {
404 reason = "Flow with id " + flow.id().toString() + " not found";
405 return false;
406 } else {
407 return true;
408 }
409 }
410
411 @Override
412 public void describeTo(Description description) {
413 description.appendText(reason);
414 }
415 }
416
417 /**
418 * Factory to allocate a flow array matcher.
419 *
420 * @param flow flow object we are looking for
421 * @return matcher
422 */
423 private static FlowJsonArrayMatcher hasFlow(FlowEntry flow) {
424 return new FlowJsonArrayMatcher(flow);
425 }
426
427 /**
428 * Tests the result of the rest api GET when there are no flows.
429 */
430 @Test
431 public void testFlowsEmptyArray() {
432 expect(mockFlowService.getFlowEntries(deviceId1))
433 .andReturn(null).anyTimes();
434 expect(mockFlowService.getFlowEntries(deviceId2))
435 .andReturn(null).anyTimes();
436 replay(mockFlowService);
437 replay(mockDeviceService);
438 final WebResource rs = resource();
439 final String response = rs.path("flows").get(String.class);
440 assertThat(response, is("{\"flows\":[]}"));
441 }
442
443 /**
444 * Tests the result of the rest api GET when there are active flows.
445 */
446 @Test
447 public void testFlowsPopulatedArray() {
448 setupMockFlows();
449 replay(mockFlowService);
450 replay(mockDeviceService);
451 final WebResource rs = resource();
452 final String response = rs.path("flows").get(String.class);
453 final JsonObject result = JsonObject.readFrom(response);
454 assertThat(result, notNullValue());
455
456 assertThat(result.names(), hasSize(1));
457 assertThat(result.names().get(0), is("flows"));
458 final JsonArray jsonFlows = result.get("flows").asArray();
459 assertThat(jsonFlows, notNullValue());
460 assertThat(jsonFlows, hasFlow(flow1));
461 assertThat(jsonFlows, hasFlow(flow2));
462 assertThat(jsonFlows, hasFlow(flow3));
463 assertThat(jsonFlows, hasFlow(flow4));
464 }
465
466 /**
467 * Tests the result of a rest api GET for a device.
468 */
469 @Test
470 public void testFlowsSingleDevice() {
471 setupMockFlows();
472 final Set<FlowEntry> flows = new HashSet<>();
473 flows.add(flow5);
474 flows.add(flow6);
475 expect(mockFlowService.getFlowEntries(anyObject()))
476 .andReturn(flows).anyTimes();
477 replay(mockFlowService);
478 replay(mockDeviceService);
479 final WebResource rs = resource();
480 final String response = rs.path("flows/" + deviceId3).get(String.class);
481 final JsonObject result = JsonObject.readFrom(response);
482 assertThat(result, notNullValue());
483
484 assertThat(result.names(), hasSize(1));
485 assertThat(result.names().get(0), is("flows"));
486 final JsonArray jsonFlows = result.get("flows").asArray();
487 assertThat(jsonFlows, notNullValue());
488 assertThat(jsonFlows, hasFlow(flow5));
489 assertThat(jsonFlows, hasFlow(flow6));
490 }
491
492 /**
493 * Tests the result of a rest api GET for a device.
494 */
495 @Test
496 public void testFlowsSingleDeviceWithFlowId() {
497 setupMockFlows();
498 final Set<FlowEntry> flows = new HashSet<>();
499 flows.add(flow5);
500 flows.add(flow6);
501 expect(mockFlowService.getFlowEntries(anyObject()))
502 .andReturn(flows).anyTimes();
503 replay(mockFlowService);
504 replay(mockDeviceService);
505 final WebResource rs = resource();
506 final String response = rs.path("flows/" + deviceId3 + "/"
507 + Long.toString(flow5.id().value())).get(String.class);
508 final JsonObject result = JsonObject.readFrom(response);
509 assertThat(result, notNullValue());
510
511 assertThat(result.names(), hasSize(1));
512 assertThat(result.names().get(0), is("flows"));
513 final JsonArray jsonFlows = result.get("flows").asArray();
514 assertThat(jsonFlows, notNullValue());
515 assertThat(jsonFlows, hasFlow(flow5));
516 assertThat(jsonFlows, not(hasFlow(flow6)));
517 }
518
519 /**
520 * Tests that a fetch of a non-existent device object throws an exception.
521 */
522 @Test
523 public void testBadGet() {
524 expect(mockFlowService.getFlowEntries(deviceId1))
525 .andReturn(null).anyTimes();
526 expect(mockFlowService.getFlowEntries(deviceId2))
527 .andReturn(null).anyTimes();
528 replay(mockFlowService);
529 replay(mockDeviceService);
530
531 WebResource rs = resource();
532 try {
533 rs.path("flows/0").get(String.class);
534 fail("Fetch of non-existent device did not throw an exception");
535 } catch (UniformInterfaceException ex) {
536 assertThat(ex.getMessage(),
537 containsString("returned a response status of"));
538 }
539 }
540}