blob: b18340a83a1c850a5ea736a216fdb214fad14527 [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
Ray Milkeyd43fe452015-05-29 09:35:12 -070018import java.net.HttpURLConnection;
Ray Milkey4f5de002014-12-17 19:26:11 -080019import java.util.HashMap;
20import java.util.HashSet;
21import java.util.Set;
22
Ray Milkeyd43fe452015-05-29 09:35:12 -070023import javax.ws.rs.core.MediaType;
24
Ray Milkey4f5de002014-12-17 19:26:11 -080025import org.hamcrest.Description;
26import org.hamcrest.TypeSafeMatcher;
27import org.junit.After;
28import org.junit.Before;
29import org.junit.Test;
30import org.onlab.osgi.ServiceDirectory;
31import org.onlab.osgi.TestServiceDirectory;
32import org.onlab.packet.MacAddress;
33import org.onlab.rest.BaseResource;
34import org.onosproject.codec.CodecService;
35import org.onosproject.codec.impl.CodecManager;
Ray Milkeyd43fe452015-05-29 09:35:12 -070036import org.onosproject.core.CoreService;
Ray Milkey4f5de002014-12-17 19:26:11 -080037import org.onosproject.core.DefaultGroupId;
38import org.onosproject.core.GroupId;
39import org.onosproject.net.DefaultDevice;
40import org.onosproject.net.Device;
41import org.onosproject.net.DeviceId;
Ray Milkeyd43fe452015-05-29 09:35:12 -070042import org.onosproject.net.NetTestTools;
Ray Milkey4f5de002014-12-17 19:26:11 -080043import org.onosproject.net.device.DeviceService;
44import org.onosproject.net.flow.DefaultTrafficSelector;
45import org.onosproject.net.flow.DefaultTrafficTreatment;
46import org.onosproject.net.flow.FlowEntry;
47import org.onosproject.net.flow.FlowId;
jcc3d4e14a2015-04-21 11:32:05 +080048import org.onosproject.net.flow.FlowRuleExtPayLoad;
Ray Milkey4f5de002014-12-17 19:26:11 -080049import org.onosproject.net.flow.FlowRuleService;
50import org.onosproject.net.flow.TrafficSelector;
51import org.onosproject.net.flow.TrafficTreatment;
52import org.onosproject.net.flow.criteria.Criterion;
53import org.onosproject.net.flow.instructions.Instruction;
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -080054import org.onosproject.net.flow.instructions.Instructions;
jcc3d4e14a2015-04-21 11:32:05 +080055
Ray Milkey4f5de002014-12-17 19:26:11 -080056import com.eclipsesource.json.JsonArray;
57import com.eclipsesource.json.JsonObject;
Ray Milkey4f5de002014-12-17 19:26:11 -080058import com.google.common.collect.ImmutableSet;
Ray Milkeyd43fe452015-05-29 09:35:12 -070059import com.sun.jersey.api.client.ClientResponse;
Ray Milkey4f5de002014-12-17 19:26:11 -080060import com.sun.jersey.api.client.UniformInterfaceException;
61import com.sun.jersey.api.client.WebResource;
Ray Milkey4f5de002014-12-17 19:26:11 -080062
63import static org.easymock.EasyMock.anyObject;
Ray Milkeyd43fe452015-05-29 09:35:12 -070064import static org.easymock.EasyMock.anyShort;
Ray Milkey4f5de002014-12-17 19:26:11 -080065import static org.easymock.EasyMock.createMock;
66import static org.easymock.EasyMock.expect;
Ray Milkeyd43fe452015-05-29 09:35:12 -070067import static org.easymock.EasyMock.expectLastCall;
Ray Milkey4f5de002014-12-17 19:26:11 -080068import static org.easymock.EasyMock.replay;
69import static org.easymock.EasyMock.verify;
70import static org.hamcrest.Matchers.containsString;
71import static org.hamcrest.Matchers.hasSize;
72import static org.hamcrest.Matchers.is;
73import static org.hamcrest.Matchers.not;
74import static org.hamcrest.Matchers.notNullValue;
75import static org.junit.Assert.assertThat;
76import static org.junit.Assert.fail;
77
78/**
79 * Unit tests for Flows REST APIs.
80 */
Ray Milkey9c3d3362015-01-28 10:39:56 -080081public class FlowsResourceTest extends ResourceTest {
Ray Milkey4f5de002014-12-17 19:26:11 -080082 final FlowRuleService mockFlowService = createMock(FlowRuleService.class);
Ray Milkeyd43fe452015-05-29 09:35:12 -070083 CoreService mockCoreService = createMock(CoreService.class);
84
Ray Milkey4f5de002014-12-17 19:26:11 -080085 final HashMap<DeviceId, Set<FlowEntry>> rules = new HashMap<>();
86
87 final DeviceService mockDeviceService = createMock(DeviceService.class);
88
89 final DeviceId deviceId1 = DeviceId.deviceId("1");
90 final DeviceId deviceId2 = DeviceId.deviceId("2");
91 final DeviceId deviceId3 = DeviceId.deviceId("3");
92 final Device device1 = new DefaultDevice(null, deviceId1, Device.Type.OTHER,
93 "", "", "", "", null);
94 final Device device2 = new DefaultDevice(null, deviceId2, Device.Type.OTHER,
95 "", "", "", "", null);
96
97 final MockFlowEntry flow1 = new MockFlowEntry(deviceId1, 1);
98 final MockFlowEntry flow2 = new MockFlowEntry(deviceId1, 2);
99
100 final MockFlowEntry flow3 = new MockFlowEntry(deviceId2, 3);
101 final MockFlowEntry flow4 = new MockFlowEntry(deviceId2, 4);
102
103 final MockFlowEntry flow5 = new MockFlowEntry(deviceId2, 5);
104 final MockFlowEntry flow6 = new MockFlowEntry(deviceId2, 6);
105
106 /**
107 * Mock class for a flow entry.
108 */
109 private static class MockFlowEntry implements FlowEntry {
110 final DeviceId deviceId;
111 final long baseValue;
112 TrafficTreatment treatment;
113 TrafficSelector selector;
114
115 public MockFlowEntry(DeviceId deviceId, long id) {
116 this.deviceId = deviceId;
117 this.baseValue = id * 100;
118 }
119
120 @Override
121 public FlowEntryState state() {
122 return FlowEntryState.ADDED;
123 }
124
125 @Override
126 public long life() {
127 return baseValue + 11;
128 }
129
130 @Override
131 public long packets() {
132 return baseValue + 22;
133 }
134
135 @Override
136 public long bytes() {
137 return baseValue + 33;
138 }
139
140 @Override
141 public long lastSeen() {
142 return baseValue + 44;
143 }
144
145 @Override
146 public int errType() {
147 return 0;
148 }
149
150 @Override
151 public int errCode() {
152 return 0;
153 }
154
155 @Override
156 public FlowId id() {
157 final long id = baseValue + 55;
158 return FlowId.valueOf(id);
159 }
160
161 @Override
alshabib08d98982015-04-21 16:25:50 -0700162 public GroupId groupId() {
163 return new DefaultGroupId(3);
Ray Milkey4f5de002014-12-17 19:26:11 -0800164 }
165
166 @Override
alshabib08d98982015-04-21 16:25:50 -0700167 public short appId() {
168 return 2;
Ray Milkey4f5de002014-12-17 19:26:11 -0800169 }
170
171 @Override
172 public int priority() {
173 return (int) (baseValue + 66);
174 }
175
176 @Override
177 public DeviceId deviceId() {
178 return deviceId;
179 }
180
181 @Override
182 public TrafficSelector selector() {
183 return selector;
184 }
185
186 @Override
187 public TrafficTreatment treatment() {
188 return treatment;
189 }
190
191 @Override
192 public int timeout() {
193 return (int) (baseValue + 77);
194 }
195
196 @Override
197 public boolean isPermanent() {
198 return false;
199 }
sangho11c30ac2015-01-22 14:30:55 -0800200
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -0800201 @Override
alshabibdb774072015-04-20 13:13:51 -0700202 public int tableId() {
203 return 0;
204 }
jcc3d4e14a2015-04-21 11:32:05 +0800205
206 @Override
207 public FlowRuleExtPayLoad payLoad() {
208 return null;
209 }
Ray Milkey4f5de002014-12-17 19:26:11 -0800210 }
211
Ray Milkey4f5de002014-12-17 19:26:11 -0800212 /**
213 * Populates some flows used as testing data.
214 */
215 private void setupMockFlows() {
216 flow2.treatment = DefaultTrafficTreatment.builder()
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -0800217 .add(Instructions.modL0Lambda((short) 4))
218 .add(Instructions.modL0Lambda((short) 5))
Ray Milkey4f5de002014-12-17 19:26:11 -0800219 .setEthDst(MacAddress.BROADCAST)
220 .build();
221 flow2.selector = DefaultTrafficSelector.builder()
222 .matchEthType((short) 3)
223 .matchIPProtocol((byte) 9)
224 .build();
225 flow4.treatment = DefaultTrafficTreatment.builder()
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -0800226 .add(Instructions.modL0Lambda((short) 6))
Ray Milkey4f5de002014-12-17 19:26:11 -0800227 .build();
228 final Set<FlowEntry> flows1 = new HashSet<>();
229 flows1.add(flow1);
230 flows1.add(flow2);
231
232 final Set<FlowEntry> flows2 = new HashSet<>();
233 flows1.add(flow3);
234 flows1.add(flow4);
235
236 rules.put(deviceId1, flows1);
237 rules.put(deviceId2, flows2);
238
239 expect(mockFlowService.getFlowEntries(deviceId1))
240 .andReturn(rules.get(deviceId1)).anyTimes();
241 expect(mockFlowService.getFlowEntries(deviceId2))
242 .andReturn(rules.get(deviceId2)).anyTimes();
243 }
244
245 /**
246 * Sets up the global values for all the tests.
247 */
248 @Before
Ray Milkeyed0b1662015-02-05 09:34:29 -0800249 public void setUpTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800250 // Mock device service
251 expect(mockDeviceService.getDevice(deviceId1))
252 .andReturn(device1);
253 expect(mockDeviceService.getDevice(deviceId2))
254 .andReturn(device2);
255 expect(mockDeviceService.getDevices())
256 .andReturn(ImmutableSet.of(device1, device2));
257
Ray Milkeyd43fe452015-05-29 09:35:12 -0700258 // Mock Core Service
259 expect(mockCoreService.getAppId(anyShort()))
260 .andReturn(NetTestTools.APP_ID).anyTimes();
261 replay(mockCoreService);
262
Ray Milkey4f5de002014-12-17 19:26:11 -0800263 // Register the services needed for the test
264 final CodecManager codecService = new CodecManager();
265 codecService.activate();
266 ServiceDirectory testDirectory =
267 new TestServiceDirectory()
268 .add(FlowRuleService.class, mockFlowService)
269 .add(DeviceService.class, mockDeviceService)
Ray Milkeyd43fe452015-05-29 09:35:12 -0700270 .add(CodecService.class, codecService)
271 .add(CoreService.class, mockCoreService);
Ray Milkey4f5de002014-12-17 19:26:11 -0800272
273 BaseResource.setServiceDirectory(testDirectory);
274 }
275
276 /**
277 * Cleans up and verifies the mocks.
Ray Milkey4f5de002014-12-17 19:26:11 -0800278 */
279 @After
Ray Milkeyed0b1662015-02-05 09:34:29 -0800280 public void tearDownTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800281 verify(mockFlowService);
Ray Milkeyd43fe452015-05-29 09:35:12 -0700282 verify(mockCoreService);
Ray Milkey4f5de002014-12-17 19:26:11 -0800283 }
284
285 /**
286 * Hamcrest matcher to check that a flow representation in JSON matches
287 * the actual flow entry.
288 */
289 public static class FlowJsonMatcher extends TypeSafeMatcher<JsonObject> {
290 private final FlowEntry flow;
291 private String reason = "";
292
293 public FlowJsonMatcher(FlowEntry flowValue) {
294 flow = flowValue;
295 }
296
297 @Override
298 public boolean matchesSafely(JsonObject jsonFlow) {
299 // check id
300 final String jsonId = jsonFlow.get("id").asString();
301 final String flowId = Long.toString(flow.id().value());
302 if (!jsonId.equals(flowId)) {
303 reason = "id " + flow.id().toString();
304 return false;
305 }
306
307 // check application id
308 final int jsonAppId = jsonFlow.get("appId").asInt();
309 if (jsonAppId != flow.appId()) {
310 reason = "appId " + Short.toString(flow.appId());
311 return false;
312 }
313
314 // check device id
315 final String jsonDeviceId = jsonFlow.get("deviceId").asString();
316 if (!jsonDeviceId.equals(flow.deviceId().toString())) {
317 reason = "deviceId " + flow.deviceId();
318 return false;
319 }
320
321 // check treatment and instructions array
322 if (flow.treatment() != null) {
323 final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
324 final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
Ray Milkey42507352015-03-20 15:16:10 -0700325 if (flow.treatment().immediate().size() != jsonInstructions.size()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800326 reason = "instructions array size of " +
Ray Milkey42507352015-03-20 15:16:10 -0700327 Integer.toString(flow.treatment().immediate().size());
Ray Milkey4f5de002014-12-17 19:26:11 -0800328 return false;
329 }
Ray Milkey42507352015-03-20 15:16:10 -0700330 for (final Instruction instruction : flow.treatment().immediate()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800331 boolean instructionFound = false;
Ray Milkey4f5de002014-12-17 19:26:11 -0800332 for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800333 final String jsonType =
334 jsonInstructions.get(instructionIndex)
335 .asObject().get("type").asString();
336 final String instructionType = instruction.type().name();
337 if (jsonType.equals(instructionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800338 instructionFound = true;
339 }
340 }
341 if (!instructionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800342 reason = "instruction " + instruction.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800343 return false;
344 }
345 }
346 }
347
348 // check selector and criteria array
349 if (flow.selector() != null) {
350 final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
351 final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
352 if (flow.selector().criteria().size() != jsonCriteria.size()) {
353 reason = "criteria array size of " +
354 Integer.toString(flow.selector().criteria().size());
355 return false;
356 }
357 for (final Criterion criterion : flow.selector().criteria()) {
358 boolean criterionFound = false;
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800359
Ray Milkey4f5de002014-12-17 19:26:11 -0800360 for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800361 final String jsonType =
362 jsonCriteria.get(criterionIndex)
363 .asObject().get("type").asString();
364 final String criterionType = criterion.type().name();
365 if (jsonType.equals(criterionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800366 criterionFound = true;
367 }
368 }
369 if (!criterionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800370 reason = "criterion " + criterion.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800371 return false;
372 }
373 }
374 }
375
376 return true;
377 }
378
379 @Override
380 public void describeTo(Description description) {
381 description.appendText(reason);
382 }
383 }
384
385 /**
386 * Factory to allocate a flow matcher.
387 *
388 * @param flow flow object we are looking for
389 * @return matcher
390 */
391 private static FlowJsonMatcher matchesFlow(FlowEntry flow) {
392 return new FlowJsonMatcher(flow);
393 }
394
395 /**
396 * Hamcrest matcher to check that a flow is represented properly in a JSON
397 * array of flows.
398 */
399 public static class FlowJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
400 private final FlowEntry flow;
401 private String reason = "";
402
403 public FlowJsonArrayMatcher(FlowEntry flowValue) {
404 flow = flowValue;
405 }
406
407 @Override
408 public boolean matchesSafely(JsonArray json) {
409 boolean flowFound = false;
410
411 for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
412 jsonFlowIndex++) {
413
414 final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
415
416 final String flowId = Long.toString(flow.id().value());
417 final String jsonFlowId = jsonFlow.get("id").asString();
418 if (jsonFlowId.equals(flowId)) {
419 flowFound = true;
420
421 // We found the correct flow, check attribute values
422 assertThat(jsonFlow, matchesFlow(flow));
423 }
424 }
425 if (!flowFound) {
426 reason = "Flow with id " + flow.id().toString() + " not found";
427 return false;
428 } else {
429 return true;
430 }
431 }
432
433 @Override
434 public void describeTo(Description description) {
435 description.appendText(reason);
436 }
437 }
438
439 /**
440 * Factory to allocate a flow array matcher.
441 *
442 * @param flow flow object we are looking for
443 * @return matcher
444 */
445 private static FlowJsonArrayMatcher hasFlow(FlowEntry flow) {
446 return new FlowJsonArrayMatcher(flow);
447 }
448
449 /**
450 * Tests the result of the rest api GET when there are no flows.
451 */
452 @Test
453 public void testFlowsEmptyArray() {
454 expect(mockFlowService.getFlowEntries(deviceId1))
455 .andReturn(null).anyTimes();
456 expect(mockFlowService.getFlowEntries(deviceId2))
457 .andReturn(null).anyTimes();
458 replay(mockFlowService);
459 replay(mockDeviceService);
460 final WebResource rs = resource();
461 final String response = rs.path("flows").get(String.class);
462 assertThat(response, is("{\"flows\":[]}"));
463 }
464
465 /**
466 * Tests the result of the rest api GET when there are active flows.
467 */
468 @Test
469 public void testFlowsPopulatedArray() {
470 setupMockFlows();
471 replay(mockFlowService);
472 replay(mockDeviceService);
473 final WebResource rs = resource();
474 final String response = rs.path("flows").get(String.class);
475 final JsonObject result = JsonObject.readFrom(response);
476 assertThat(result, notNullValue());
477
478 assertThat(result.names(), hasSize(1));
479 assertThat(result.names().get(0), is("flows"));
480 final JsonArray jsonFlows = result.get("flows").asArray();
481 assertThat(jsonFlows, notNullValue());
482 assertThat(jsonFlows, hasFlow(flow1));
483 assertThat(jsonFlows, hasFlow(flow2));
484 assertThat(jsonFlows, hasFlow(flow3));
485 assertThat(jsonFlows, hasFlow(flow4));
486 }
487
488 /**
489 * Tests the result of a rest api GET for a device.
490 */
491 @Test
492 public void testFlowsSingleDevice() {
493 setupMockFlows();
494 final Set<FlowEntry> flows = new HashSet<>();
495 flows.add(flow5);
496 flows.add(flow6);
497 expect(mockFlowService.getFlowEntries(anyObject()))
498 .andReturn(flows).anyTimes();
499 replay(mockFlowService);
500 replay(mockDeviceService);
501 final WebResource rs = resource();
502 final String response = rs.path("flows/" + deviceId3).get(String.class);
503 final JsonObject result = JsonObject.readFrom(response);
504 assertThat(result, notNullValue());
505
506 assertThat(result.names(), hasSize(1));
507 assertThat(result.names().get(0), is("flows"));
508 final JsonArray jsonFlows = result.get("flows").asArray();
509 assertThat(jsonFlows, notNullValue());
510 assertThat(jsonFlows, hasFlow(flow5));
511 assertThat(jsonFlows, hasFlow(flow6));
512 }
513
514 /**
515 * Tests the result of a rest api GET for a device.
516 */
517 @Test
518 public void testFlowsSingleDeviceWithFlowId() {
519 setupMockFlows();
520 final Set<FlowEntry> flows = new HashSet<>();
521 flows.add(flow5);
522 flows.add(flow6);
523 expect(mockFlowService.getFlowEntries(anyObject()))
524 .andReturn(flows).anyTimes();
525 replay(mockFlowService);
526 replay(mockDeviceService);
527 final WebResource rs = resource();
528 final String response = rs.path("flows/" + deviceId3 + "/"
529 + Long.toString(flow5.id().value())).get(String.class);
530 final JsonObject result = JsonObject.readFrom(response);
531 assertThat(result, notNullValue());
532
533 assertThat(result.names(), hasSize(1));
534 assertThat(result.names().get(0), is("flows"));
535 final JsonArray jsonFlows = result.get("flows").asArray();
536 assertThat(jsonFlows, notNullValue());
537 assertThat(jsonFlows, hasFlow(flow5));
538 assertThat(jsonFlows, not(hasFlow(flow6)));
539 }
540
541 /**
542 * Tests that a fetch of a non-existent device object throws an exception.
543 */
544 @Test
545 public void testBadGet() {
546 expect(mockFlowService.getFlowEntries(deviceId1))
547 .andReturn(null).anyTimes();
548 expect(mockFlowService.getFlowEntries(deviceId2))
549 .andReturn(null).anyTimes();
550 replay(mockFlowService);
551 replay(mockDeviceService);
552
553 WebResource rs = resource();
554 try {
555 rs.path("flows/0").get(String.class);
556 fail("Fetch of non-existent device did not throw an exception");
557 } catch (UniformInterfaceException ex) {
558 assertThat(ex.getMessage(),
559 containsString("returned a response status of"));
560 }
561 }
Ray Milkeyd43fe452015-05-29 09:35:12 -0700562
563 /**
564 * Tests creating a flow with POST.
565 */
566 @Test
567 public void testPost() {
568 String json = "{\"appId\":2,\"priority\":1,\"isPermanent\":true,"
569 + "\"deviceId\":\"of:0000000000000001\","
570 + "\"treatment\":{\"instructions\":[ {\"type\":\"OUTPUT\",\"port\":2}]},"
571 + "\"selector\":{\"criteria\":[ {\"type\":\"ETH_TYPE\",\"ethType\":2054}]}}";
572
573 mockFlowService.applyFlowRules(anyObject());
574 expectLastCall();
575 replay(mockFlowService);
576
577 WebResource rs = resource();
578
579
580 ClientResponse response = rs.path("flows/")
581 .type(MediaType.APPLICATION_JSON_TYPE)
582 .post(ClientResponse.class, json);
583 assertThat(response.getStatus(), is(HttpURLConnection.HTTP_ACCEPTED));
584 }
Ray Milkey4f5de002014-12-17 19:26:11 -0800585}