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