blob: 5aea937391a87ac005efc20149728e29cc6b7070 [file] [log] [blame]
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001/**
2* Copyright 2011, Big Switch Networks, Inc.
3* Originally created by David Erickson, Stanford University
4*
5* Licensed under the Apache License, Version 2.0 (the "License"); you may
6* not use this file except in compliance with the License. You may obtain
7* a copy of the License at
8*
9* http://www.apache.org/licenses/LICENSE-2.0
10*
11* Unless required by applicable law or agreed to in writing, software
12* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14* License for the specific language governing permissions and limitations
15* under the License.
16**/
17
18package net.floodlightcontroller.core.internal;
19
20import static org.easymock.EasyMock.*;
21
22import java.util.ArrayList;
23import java.util.Collection;
24import java.util.Date;
25import java.util.HashMap;
26import java.util.HashSet;
27import java.util.List;
28import java.util.Map;
29import java.util.concurrent.ConcurrentHashMap;
30import java.util.concurrent.Future;
31import java.util.concurrent.TimeUnit;
32
33import net.floodlightcontroller.core.FloodlightProvider;
34import net.floodlightcontroller.core.FloodlightContext;
35import net.floodlightcontroller.core.IFloodlightProviderService;
36import net.floodlightcontroller.core.IHAListener;
37import net.floodlightcontroller.core.IFloodlightProviderService.Role;
38import net.floodlightcontroller.core.IOFMessageFilterManagerService;
39import net.floodlightcontroller.core.IOFMessageListener;
40import net.floodlightcontroller.core.IListener.Command;
41import net.floodlightcontroller.core.IOFSwitch;
42import net.floodlightcontroller.core.IOFSwitchListener;
43import net.floodlightcontroller.core.OFMessageFilterManager;
44import net.floodlightcontroller.core.internal.Controller.IUpdate;
45import net.floodlightcontroller.core.internal.Controller.SwitchUpdate;
46import net.floodlightcontroller.core.internal.Controller.SwitchUpdateType;
47import net.floodlightcontroller.core.internal.OFChannelState.HandshakeState;
48import net.floodlightcontroller.core.module.FloodlightModuleContext;
49import net.floodlightcontroller.core.test.MockFloodlightProvider;
50import net.floodlightcontroller.core.test.MockThreadPoolService;
51import net.floodlightcontroller.counter.CounterStore;
52import net.floodlightcontroller.counter.ICounterStoreService;
53import net.floodlightcontroller.packet.ARP;
54import net.floodlightcontroller.packet.Ethernet;
55import net.floodlightcontroller.packet.IPacket;
56import net.floodlightcontroller.packet.IPv4;
57import net.floodlightcontroller.perfmon.IPktInProcessingTimeService;
58import net.floodlightcontroller.perfmon.PktInProcessingTime;
59import net.floodlightcontroller.restserver.IRestApiService;
60import net.floodlightcontroller.restserver.RestApiServer;
61import net.floodlightcontroller.storage.IStorageSourceService;
62import net.floodlightcontroller.storage.memory.MemoryStorageSource;
63import net.floodlightcontroller.test.FloodlightTestCase;
64import net.floodlightcontroller.threadpool.IThreadPoolService;
65
66import org.easymock.Capture;
67import org.easymock.EasyMock;
68import org.jboss.netty.channel.Channel;
69import org.junit.Test;
70import org.openflow.protocol.OFError;
71import org.openflow.protocol.OFError.OFBadRequestCode;
72import org.openflow.protocol.OFError.OFErrorType;
73import org.openflow.protocol.OFFeaturesReply;
74import org.openflow.protocol.OFPacketIn;
75import org.openflow.protocol.OFPacketOut;
76import org.openflow.protocol.OFPhysicalPort;
77import org.openflow.protocol.OFPort;
78import org.openflow.protocol.OFPortStatus;
79import org.openflow.protocol.OFStatisticsReply;
80import org.openflow.protocol.OFType;
81import org.openflow.protocol.OFPacketIn.OFPacketInReason;
82import org.openflow.protocol.OFPortStatus.OFPortReason;
83import org.openflow.protocol.OFVendor;
84import org.openflow.protocol.action.OFAction;
85import org.openflow.protocol.action.OFActionOutput;
86import org.openflow.protocol.factory.BasicFactory;
87import org.openflow.protocol.statistics.OFFlowStatisticsReply;
88import org.openflow.protocol.statistics.OFStatistics;
89import org.openflow.protocol.statistics.OFStatisticsType;
90import org.openflow.util.HexString;
91import org.openflow.vendor.nicira.OFNiciraVendorData;
92import org.openflow.vendor.nicira.OFRoleReplyVendorData;
93
94/**
95 *
96 * @author David Erickson (daviderickson@cs.stanford.edu)
97 */
98public class ControllerTest extends FloodlightTestCase {
99
100 private Controller controller;
101 private MockThreadPoolService tp;
102
103 @Override
104 public void setUp() throws Exception {
105 super.setUp();
106 FloodlightModuleContext fmc = new FloodlightModuleContext();
107
108 FloodlightProvider cm = new FloodlightProvider();
109 controller = (Controller)cm.getServiceImpls().get(IFloodlightProviderService.class);
110 fmc.addService(IFloodlightProviderService.class, controller);
111
112 MemoryStorageSource memstorage = new MemoryStorageSource();
113 fmc.addService(IStorageSourceService.class, memstorage);
114
115 RestApiServer restApi = new RestApiServer();
116 fmc.addService(IRestApiService.class, restApi);
117
118 CounterStore cs = new CounterStore();
119 fmc.addService(ICounterStoreService.class, cs);
120
121 PktInProcessingTime ppt = new PktInProcessingTime();
122 fmc.addService(IPktInProcessingTimeService.class, ppt);
123
124 tp = new MockThreadPoolService();
125 fmc.addService(IThreadPoolService.class, tp);
126
127 ppt.init(fmc);
128 restApi.init(fmc);
129 memstorage.init(fmc);
130 cm.init(fmc);
131 tp.init(fmc);
132 ppt.startUp(fmc);
133 restApi.startUp(fmc);
134 memstorage.startUp(fmc);
135 cm.startUp(fmc);
136 tp.startUp(fmc);
137 }
138
139 public Controller getController() {
140 return controller;
141 }
142
143 protected OFStatisticsReply getStatisticsReply(int transactionId,
144 int count, boolean moreReplies) {
145 OFStatisticsReply sr = new OFStatisticsReply();
146 sr.setXid(transactionId);
147 sr.setStatisticType(OFStatisticsType.FLOW);
148 List<OFStatistics> statistics = new ArrayList<OFStatistics>();
149 for (int i = 0; i < count; ++i) {
150 statistics.add(new OFFlowStatisticsReply());
151 }
152 sr.setStatistics(statistics);
153 if (moreReplies)
154 sr.setFlags((short) 1);
155 return sr;
156 }
157
158 /* Set the mock expectations for sw when sw is passed to addSwitch */
159 protected void setupSwitchForAddSwitch(IOFSwitch sw, long dpid) {
160 String dpidString = HexString.toHexString(dpid);
161
162 expect(sw.getId()).andReturn(dpid).anyTimes();
163 expect(sw.getStringId()).andReturn(dpidString).anyTimes();
164 expect(sw.getConnectedSince()).andReturn(new Date());
165 Channel channel = createMock(Channel.class);
166 expect(sw.getChannel()).andReturn(channel);
167 expect(channel.getRemoteAddress()).andReturn(null);
168
169 expect(sw.getCapabilities()).andReturn(0).anyTimes();
170 expect(sw.getBuffers()).andReturn(0).anyTimes();
171 expect(sw.getTables()).andReturn((byte)0).anyTimes();
172 expect(sw.getActions()).andReturn(0).anyTimes();
173 expect(sw.getPorts()).andReturn(new ArrayList<OFPhysicalPort>()).anyTimes();
174 }
175
176 /**
177 * Run the controller's main loop so that updates are processed
178 */
179 protected class ControllerRunThread extends Thread {
180 public void run() {
181 controller.openFlowPort = 0; // Don't listen
182 controller.run();
183 }
184 }
185
186 /**
187 * Verify that a listener that throws an exception halts further
188 * execution, and verify that the Commands STOP and CONTINUE are honored.
189 * @throws Exception
190 */
191 @Test
192 public void testHandleMessages() throws Exception {
193 Controller controller = getController();
194 controller.removeOFMessageListeners(OFType.PACKET_IN);
195
196 IOFSwitch sw = createMock(IOFSwitch.class);
197 expect(sw.getStringId()).andReturn("00:00:00:00:00:00:00").anyTimes();
198
199 // Build our test packet
200 IPacket testPacket = new Ethernet()
201 .setSourceMACAddress("00:44:33:22:11:00")
202 .setDestinationMACAddress("00:11:22:33:44:55")
203 .setEtherType(Ethernet.TYPE_ARP)
204 .setPayload(
205 new ARP()
206 .setHardwareType(ARP.HW_TYPE_ETHERNET)
207 .setProtocolType(ARP.PROTO_TYPE_IP)
208 .setHardwareAddressLength((byte) 6)
209 .setProtocolAddressLength((byte) 4)
210 .setOpCode(ARP.OP_REPLY)
211 .setSenderHardwareAddress(Ethernet.toMACAddress("00:44:33:22:11:00"))
212 .setSenderProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.1"))
213 .setTargetHardwareAddress(Ethernet.toMACAddress("00:11:22:33:44:55"))
214 .setTargetProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.2")));
215 byte[] testPacketSerialized = testPacket.serialize();
216
217 // Build the PacketIn
218 OFPacketIn pi = ((OFPacketIn) new BasicFactory().getMessage(OFType.PACKET_IN))
219 .setBufferId(-1)
220 .setInPort((short) 1)
221 .setPacketData(testPacketSerialized)
222 .setReason(OFPacketInReason.NO_MATCH)
223 .setTotalLength((short) testPacketSerialized.length);
224
225 IOFMessageListener test1 = createMock(IOFMessageListener.class);
226 expect(test1.getName()).andReturn("test1").anyTimes();
227 expect(test1.isCallbackOrderingPrereq((OFType)anyObject(), (String)anyObject())).andReturn(false).anyTimes();
228 expect(test1.isCallbackOrderingPostreq((OFType)anyObject(), (String)anyObject())).andReturn(false).anyTimes();
229 expect(test1.receive(eq(sw), eq(pi), isA(FloodlightContext.class))).andThrow(new RuntimeException("This is NOT an error! We are testing exception catching."));
230 IOFMessageListener test2 = createMock(IOFMessageListener.class);
231 expect(test2.getName()).andReturn("test2").anyTimes();
232 expect(test2.isCallbackOrderingPrereq((OFType)anyObject(), (String)anyObject())).andReturn(false).anyTimes();
233 expect(test2.isCallbackOrderingPostreq((OFType)anyObject(), (String)anyObject())).andReturn(false).anyTimes();
234 // expect no calls to test2.receive() since test1.receive() threw an exception
235
236 replay(test1, test2, sw);
237 controller.addOFMessageListener(OFType.PACKET_IN, test1);
238 controller.addOFMessageListener(OFType.PACKET_IN, test2);
239 try {
240 controller.handleMessage(sw, pi, null);
241 } catch (RuntimeException e) {
242 assertEquals(e.getMessage().startsWith("This is NOT an error!"), true);
243 }
244 verify(test1, test2, sw);
245
246 // verify STOP works
247 reset(test1, test2, sw);
248 expect(test1.receive(eq(sw), eq(pi), isA(FloodlightContext.class))).andReturn(Command.STOP);
249 //expect(test1.getId()).andReturn(0).anyTimes();
250 expect(sw.getStringId()).andReturn("00:00:00:00:00:00:00").anyTimes();
251 replay(test1, test2, sw);
252 controller.handleMessage(sw, pi, null);
253 verify(test1, test2, sw);
254 }
255
256 public class FutureFetcher<E> implements Runnable {
257 public E value;
258 public Future<E> future;
259
260 public FutureFetcher(Future<E> future) {
261 this.future = future;
262 }
263
264 @Override
265 public void run() {
266 try {
267 value = future.get();
268 } catch (Exception e) {
269 throw new RuntimeException(e);
270 }
271 }
272
273 /**
274 * @return the value
275 */
276 public E getValue() {
277 return value;
278 }
279
280 /**
281 * @return the future
282 */
283 public Future<E> getFuture() {
284 return future;
285 }
286 }
287
288 /**
289 *
290 * @throws Exception
291 */
292 @Test
293 public void testOFStatisticsFuture() throws Exception {
294 // Test for a single stats reply
295 IOFSwitch sw = createMock(IOFSwitch.class);
296 sw.cancelStatisticsReply(1);
297 OFStatisticsFuture sf = new OFStatisticsFuture(tp, sw, 1);
298
299 replay(sw);
300 List<OFStatistics> stats;
301 FutureFetcher<List<OFStatistics>> ff = new FutureFetcher<List<OFStatistics>>(sf);
302 Thread t = new Thread(ff);
303 t.start();
304 sf.deliverFuture(sw, getStatisticsReply(1, 10, false));
305
306 t.join();
307 stats = ff.getValue();
308 verify(sw);
309 assertEquals(10, stats.size());
310
311 // Test multiple stats replies
312 reset(sw);
313 sw.cancelStatisticsReply(1);
314
315 sf = new OFStatisticsFuture(tp, sw, 1);
316
317 replay(sw);
318 ff = new FutureFetcher<List<OFStatistics>>(sf);
319 t = new Thread(ff);
320 t.start();
321 sf.deliverFuture(sw, getStatisticsReply(1, 10, true));
322 sf.deliverFuture(sw, getStatisticsReply(1, 5, false));
323 t.join();
324
325 stats = sf.get();
326 verify(sw);
327 assertEquals(15, stats.size());
328
329 // Test cancellation
330 reset(sw);
331 sw.cancelStatisticsReply(1);
332 sf = new OFStatisticsFuture(tp, sw, 1);
333
334 replay(sw);
335 ff = new FutureFetcher<List<OFStatistics>>(sf);
336 t = new Thread(ff);
337 t.start();
338 sf.cancel(true);
339 t.join();
340
341 stats = sf.get();
342 verify(sw);
343 assertEquals(0, stats.size());
344
345 // Test self timeout
346 reset(sw);
347 sw.cancelStatisticsReply(1);
348 sf = new OFStatisticsFuture(tp, sw, 1, 75, TimeUnit.MILLISECONDS);
349
350 replay(sw);
351 ff = new FutureFetcher<List<OFStatistics>>(sf);
352 t = new Thread(ff);
353 t.start();
354 t.join(2000);
355
356 stats = sf.get();
357 verify(sw);
358 assertEquals(0, stats.size());
359 }
360
361 @Test
362 public void testMessageFilterManager() throws Exception {
363 class MyOFMessageFilterManager extends OFMessageFilterManager {
364 public MyOFMessageFilterManager(int timer_interval) {
365 super();
366 TIMER_INTERVAL = timer_interval;
367 }
368 }
369 FloodlightModuleContext fmCntx = new FloodlightModuleContext();
370 MockFloodlightProvider mfp = new MockFloodlightProvider();
371 OFMessageFilterManager mfm = new MyOFMessageFilterManager(100);
372 MockThreadPoolService mtp = new MockThreadPoolService();
373 fmCntx.addService(IOFMessageFilterManagerService.class, mfm);
374 fmCntx.addService(IFloodlightProviderService.class, mfp);
375 fmCntx.addService(IThreadPoolService.class, mtp);
376 String sid = null;
377
378 mfm.init(fmCntx);
379 mfm.startUp(fmCntx);
380
381 ConcurrentHashMap <String, String> filter;
382 int i;
383
384 //Adding the filter works -- adds up to the maximum filter size.
385 for(i=mfm.getMaxFilterSize(); i > 0; --i) {
386 filter = new ConcurrentHashMap<String,String>();
387 filter.put("mac", String.format("00:11:22:33:44:%d%d", i,i));
388 sid = mfm.setupFilter(null, filter, 60);
389 assertTrue(mfm.getNumberOfFilters() == mfm.getMaxFilterSize() - i +1);
390 }
391
392 // Add one more to see if you can't
393 filter = new ConcurrentHashMap<String,String>();
394 filter.put("mac", "mac2");
395 mfm.setupFilter(null, filter, 10*1000);
396
397 assertTrue(mfm.getNumberOfFilters() == mfm.getMaxFilterSize());
398
399 // Deleting the filter works.
400 mfm.setupFilter(sid, null, -1);
401 assertTrue(mfm.getNumberOfFilters() == mfm.getMaxFilterSize()-1);
402
403 // Creating mock switch to which we will send packet out and
404 IOFSwitch sw = createMock(IOFSwitch.class);
405 expect(sw.getId()).andReturn(new Long(0));
406
407 // Mock Packet-in
408 IPacket testPacket = new Ethernet()
409 .setSourceMACAddress("00:44:33:22:11:00")
410 .setDestinationMACAddress("00:11:22:33:44:55")
411 .setEtherType(Ethernet.TYPE_ARP)
412 .setPayload(
413 new ARP()
414 .setHardwareType(ARP.HW_TYPE_ETHERNET)
415 .setProtocolType(ARP.PROTO_TYPE_IP)
416 .setHardwareAddressLength((byte) 6)
417 .setProtocolAddressLength((byte) 4)
418 .setOpCode(ARP.OP_REPLY)
419 .setSenderHardwareAddress(Ethernet.toMACAddress("00:44:33:22:11:00"))
420 .setSenderProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.1"))
421 .setTargetHardwareAddress(Ethernet.toMACAddress("00:11:22:33:44:55"))
422 .setTargetProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.2")));
423 byte[] testPacketSerialized = testPacket.serialize();
424
425 // Build the PacketIn
426 OFPacketIn pi = ((OFPacketIn) new BasicFactory().getMessage(OFType.PACKET_IN))
427 .setBufferId(-1)
428 .setInPort((short) 1)
429 .setPacketData(testPacketSerialized)
430 .setReason(OFPacketInReason.NO_MATCH)
431 .setTotalLength((short) testPacketSerialized.length);
432
433 // Mock Packet-out
434 OFPacketOut packetOut =
435 (OFPacketOut) mockFloodlightProvider.getOFMessageFactory().getMessage(OFType.PACKET_OUT);
436 packetOut.setBufferId(pi.getBufferId())
437 .setInPort(pi.getInPort());
438 List<OFAction> poactions = new ArrayList<OFAction>();
439 poactions.add(new OFActionOutput(OFPort.OFPP_TABLE.getValue(), (short) 0));
440 packetOut.setActions(poactions)
441 .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH)
442 .setPacketData(testPacketSerialized)
443 .setLengthU(OFPacketOut.MINIMUM_LENGTH+packetOut.getActionsLength()+testPacketSerialized.length);
444
445 FloodlightContext cntx = new FloodlightContext();
446 IFloodlightProviderService.bcStore.put(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD, (Ethernet) testPacket);
447
448
449 // Let's check the listeners.
450 List <IOFMessageListener> lm;
451
452 // Check to see if all the listeners are active.
453 lm = mfp.getListeners().get(OFType.PACKET_OUT);
454 assertTrue(lm.size() == 1);
455 assertTrue(lm.get(0).equals(mfm));
456
457 lm = mfp.getListeners().get(OFType.FLOW_MOD);
458 assertTrue(lm.size() == 1);
459 assertTrue(lm.get(0).equals(mfm));
460
461 lm = mfp.getListeners().get(OFType.PACKET_IN);
462 assertTrue(lm.size() == 1);
463 assertTrue(lm.get(0).equals(mfm));
464
465 HashSet<String> matchedFilters;
466
467 // Send a packet in and check if it matches a filter.
468 matchedFilters = mfm.getMatchedFilters(pi, cntx);
469 assertTrue(matchedFilters.size() == 1);
470
471 // Send a packet out and check if it matches a filter
472 matchedFilters = mfm.getMatchedFilters(packetOut, cntx);
473 assertTrue(matchedFilters.size() == 1);
474
475 // Wait for all filters to be timed out.
476 Thread.sleep(150);
477 assertEquals(0, mfm.getNumberOfFilters());
478 }
479
480 @Test
481 public void testAddSwitch() throws Exception {
482 controller.activeSwitches = new ConcurrentHashMap<Long, IOFSwitch>();
483
484 //OFSwitchImpl oldsw = createMock(OFSwitchImpl.class);
485 OFSwitchImpl oldsw = new OFSwitchImpl();
486 OFFeaturesReply featuresReply = new OFFeaturesReply();
487 featuresReply.setDatapathId(0L);
488 featuresReply.setPorts(new ArrayList<OFPhysicalPort>());
489 oldsw.setFeaturesReply(featuresReply);
490 //expect(oldsw.getId()).andReturn(0L).anyTimes();
491 //expect(oldsw.asyncRemoveSwitchLock()).andReturn(rwlock.writeLock()).anyTimes();
492 //oldsw.setConnected(false);
493 //expect(oldsw.getStringId()).andReturn("00:00:00:00:00:00:00").anyTimes();
494
495 Channel channel = createNiceMock(Channel.class);
496 //expect(oldsw.getChannel()).andReturn(channel);
497 oldsw.setChannel(channel);
498 expect(channel.close()).andReturn(null);
499
500 IOFSwitch newsw = createMock(IOFSwitch.class);
501 expect(newsw.getId()).andReturn(0L).anyTimes();
502 expect(newsw.getStringId()).andReturn("00:00:00:00:00:00:00").anyTimes();
503 expect(newsw.getConnectedSince()).andReturn(new Date());
504 Channel channel2 = createMock(Channel.class);
505 expect(newsw.getChannel()).andReturn(channel2);
506 expect(channel2.getRemoteAddress()).andReturn(null);
507 expect(newsw.getPorts()).andReturn(new ArrayList<OFPhysicalPort>());
508 expect(newsw.getCapabilities()).andReturn(0).anyTimes();
509 expect(newsw.getBuffers()).andReturn(0).anyTimes();
510 expect(newsw.getTables()).andReturn((byte)0).anyTimes();
511 expect(newsw.getActions()).andReturn(0).anyTimes();
Jonathan Hartfe990382013-02-06 15:22:32 -0800512 expect(newsw.getPorts()).andReturn(new ArrayList<OFPhysicalPort>());
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800513 controller.activeSwitches.put(0L, oldsw);
514 replay(newsw, channel, channel2);
515
516 controller.addSwitch(newsw);
517
518 verify(newsw, channel, channel2);
519 }
520
521 @Test
522 public void testUpdateQueue() throws Exception {
523 class DummySwitchListener implements IOFSwitchListener {
524 public int nAdded;
525 public int nRemoved;
526 public int nPortChanged;
527 public DummySwitchListener() {
528 nAdded = 0;
529 nRemoved = 0;
530 nPortChanged = 0;
531 }
532 public synchronized void addedSwitch(IOFSwitch sw) {
533 nAdded++;
534 notifyAll();
535 }
536 public synchronized void removedSwitch(IOFSwitch sw) {
537 nRemoved++;
538 notifyAll();
539 }
540 public String getName() {
541 return "dummy";
542 }
543 @Override
544 public void switchPortChanged(Long switchId) {
545 nPortChanged++;
546 notifyAll();
547 }
mininet99670862013-06-04 10:58:44 -0700548
549 @Override
550 public void switchPortAdded(Long switchId, OFPhysicalPort port) {};
551 @Override
552 public void switchPortRemoved(Long switchId, OFPhysicalPort port) {};
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800553 }
554 DummySwitchListener switchListener = new DummySwitchListener();
555 IOFSwitch sw = createMock(IOFSwitch.class);
556 ControllerRunThread t = new ControllerRunThread();
557 t.start();
558
559 controller.addOFSwitchListener(switchListener);
560 synchronized(switchListener) {
561 controller.updates.put(controller.new SwitchUpdate(sw,
562 Controller.SwitchUpdateType.ADDED));
563 switchListener.wait(500);
564 assertTrue("IOFSwitchListener.addedSwitch() was not called",
565 switchListener.nAdded == 1);
566 controller.updates.put(controller.new SwitchUpdate(sw,
567 Controller.SwitchUpdateType.REMOVED));
568 switchListener.wait(500);
569 assertTrue("IOFSwitchListener.removedSwitch() was not called",
570 switchListener.nRemoved == 1);
571 controller.updates.put(controller.new SwitchUpdate(sw,
572 Controller.SwitchUpdateType.PORTCHANGED));
573 switchListener.wait(500);
574 assertTrue("IOFSwitchListener.switchPortChanged() was not called",
575 switchListener.nPortChanged == 1);
576 }
577 }
578
579
580 private Map<String,Object> getFakeControllerIPRow(String id, String controllerId,
581 String type, int number, String discoveredIP ) {
582 HashMap<String, Object> row = new HashMap<String,Object>();
583 row.put(Controller.CONTROLLER_INTERFACE_ID, id);
584 row.put(Controller.CONTROLLER_INTERFACE_CONTROLLER_ID, controllerId);
585 row.put(Controller.CONTROLLER_INTERFACE_TYPE, type);
586 row.put(Controller.CONTROLLER_INTERFACE_NUMBER, number);
587 row.put(Controller.CONTROLLER_INTERFACE_DISCOVERED_IP, discoveredIP);
588 return row;
589 }
590
591 /**
592 * Test notifications for controller node IP changes. This requires
593 * synchronization between the main test thread and another thread
594 * that runs Controller's main loop and takes / handles updates. We
595 * synchronize with wait(timeout) / notifyAll(). We check for the
596 * expected condition after the wait returns. However, if wait returns
597 * due to the timeout (or due to spurious awaking) and the check fails we
598 * might just not have waited long enough. Using a long enough timeout
599 * mitigates this but we cannot get rid of the fundamental "issue".
600 *
601 * @throws Exception
602 */
603 @Test
604 public void testControllerNodeIPChanges() throws Exception {
605 class DummyHAListener implements IHAListener {
606 public Map<String, String> curControllerNodeIPs;
607 public Map<String, String> addedControllerNodeIPs;
608 public Map<String, String> removedControllerNodeIPs;
609 public int nCalled;
610
611 public DummyHAListener() {
612 this.nCalled = 0;
613 }
614
615 @Override
616 public void roleChanged(Role oldRole, Role newRole) {
617 // ignore
618 }
619
620 @Override
621 public synchronized void controllerNodeIPsChanged(
622 Map<String, String> curControllerNodeIPs,
623 Map<String, String> addedControllerNodeIPs,
624 Map<String, String> removedControllerNodeIPs) {
625 this.curControllerNodeIPs = curControllerNodeIPs;
626 this.addedControllerNodeIPs = addedControllerNodeIPs;
627 this.removedControllerNodeIPs = removedControllerNodeIPs;
628 this.nCalled++;
629 notifyAll();
630 }
631
632 public void do_assert(int nCalled,
633 Map<String, String> curControllerNodeIPs,
634 Map<String, String> addedControllerNodeIPs,
635 Map<String, String> removedControllerNodeIPs) {
636 assertEquals("nCalled is not as expected", nCalled, this.nCalled);
637 assertEquals("curControllerNodeIPs is not as expected",
638 curControllerNodeIPs, this.curControllerNodeIPs);
639 assertEquals("addedControllerNodeIPs is not as expected",
640 addedControllerNodeIPs, this.addedControllerNodeIPs);
641 assertEquals("removedControllerNodeIPs is not as expected",
642 removedControllerNodeIPs, this.removedControllerNodeIPs);
643
644 }
645 }
646 long waitTimeout = 250; // ms
647 DummyHAListener listener = new DummyHAListener();
648 HashMap<String,String> expectedCurMap = new HashMap<String, String>();
649 HashMap<String,String> expectedAddedMap = new HashMap<String, String>();
650 HashMap<String,String> expectedRemovedMap = new HashMap<String, String>();
651
652 controller.addHAListener(listener);
653 ControllerRunThread t = new ControllerRunThread();
654 t.start();
655
656 synchronized(listener) {
657 // Insert a first entry
658 controller.storageSource.insertRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
659 getFakeControllerIPRow("row1", "c1", "Ethernet", 0, "1.1.1.1"));
660 expectedCurMap.clear();
661 expectedAddedMap.clear();
662 expectedRemovedMap.clear();
663 expectedCurMap.put("c1", "1.1.1.1");
664 expectedAddedMap.put("c1", "1.1.1.1");
665 listener.wait(waitTimeout);
666 listener.do_assert(1, expectedCurMap, expectedAddedMap, expectedRemovedMap);
667
668 // Add an interface that we want to ignore.
669 controller.storageSource.insertRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
670 getFakeControllerIPRow("row2", "c1", "Ethernet", 1, "1.1.1.2"));
671 listener.wait(waitTimeout); // TODO: do a different check. This call will have to wait for the timeout
672 assertTrue("controllerNodeIPsChanged() should not have been called here",
673 listener.nCalled == 1);
674
675 // Add another entry
676 controller.storageSource.insertRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
677 getFakeControllerIPRow("row3", "c2", "Ethernet", 0, "2.2.2.2"));
678 expectedCurMap.clear();
679 expectedAddedMap.clear();
680 expectedRemovedMap.clear();
681 expectedCurMap.put("c1", "1.1.1.1");
682 expectedCurMap.put("c2", "2.2.2.2");
683 expectedAddedMap.put("c2", "2.2.2.2");
684 listener.wait(waitTimeout);
685 listener.do_assert(2, expectedCurMap, expectedAddedMap, expectedRemovedMap);
686
687
688 // Update an entry
689 controller.storageSource.updateRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
690 "row3", getFakeControllerIPRow("row3", "c2", "Ethernet", 0, "2.2.2.3"));
691 expectedCurMap.clear();
692 expectedAddedMap.clear();
693 expectedRemovedMap.clear();
694 expectedCurMap.put("c1", "1.1.1.1");
695 expectedCurMap.put("c2", "2.2.2.3");
696 expectedAddedMap.put("c2", "2.2.2.3");
697 expectedRemovedMap.put("c2", "2.2.2.2");
698 listener.wait(waitTimeout);
699 listener.do_assert(3, expectedCurMap, expectedAddedMap, expectedRemovedMap);
700
701 // Delete an entry
702 controller.storageSource.deleteRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
703 "row3");
704 expectedCurMap.clear();
705 expectedAddedMap.clear();
706 expectedRemovedMap.clear();
707 expectedCurMap.put("c1", "1.1.1.1");
708 expectedRemovedMap.put("c2", "2.2.2.3");
709 listener.wait(waitTimeout);
710 listener.do_assert(4, expectedCurMap, expectedAddedMap, expectedRemovedMap);
711 }
712 }
713
714 @Test
715 public void testGetControllerNodeIPs() {
716 HashMap<String,String> expectedCurMap = new HashMap<String, String>();
717
718 controller.storageSource.insertRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
719 getFakeControllerIPRow("row1", "c1", "Ethernet", 0, "1.1.1.1"));
720 controller.storageSource.insertRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
721 getFakeControllerIPRow("row2", "c1", "Ethernet", 1, "1.1.1.2"));
722 controller.storageSource.insertRow(Controller.CONTROLLER_INTERFACE_TABLE_NAME,
723 getFakeControllerIPRow("row3", "c2", "Ethernet", 0, "2.2.2.2"));
724 expectedCurMap.put("c1", "1.1.1.1");
725 expectedCurMap.put("c2", "2.2.2.2");
726 assertEquals("expectedControllerNodeIPs is not as expected",
727 expectedCurMap, controller.getControllerNodeIPs());
728 }
729
730 @Test
731 public void testSetRoleNull() {
732 try {
733 controller.setRole(null);
734 fail("Should have thrown an Exception");
735 }
736 catch (NullPointerException e) {
737 //exptected
738 }
739 }
740
741 @Test
742 public void testSetRole() {
743 controller.connectedSwitches.add(new OFSwitchImpl());
744 RoleChanger roleChanger = createMock(RoleChanger.class);
745 roleChanger.submitRequest(controller.connectedSwitches, Role.SLAVE);
746 controller.roleChanger = roleChanger;
747
748 assertEquals("Check that update queue is empty", 0,
749 controller.updates.size());
750
751 replay(roleChanger);
752 controller.setRole(Role.SLAVE);
753 verify(roleChanger);
754
755 Controller.IUpdate upd = controller.updates.poll();
756 assertNotNull("Check that update queue has an update", upd);
757 assertTrue("Check that update is HARoleUpdate",
758 upd instanceof Controller.HARoleUpdate);
759 Controller.HARoleUpdate roleUpd = (Controller.HARoleUpdate)upd;
760 assertSame(null, roleUpd.oldRole);
761 assertSame(Role.SLAVE, roleUpd.newRole);
762 }
763
764 @Test
765 public void testCheckSwitchReady() {
766 OFChannelState state = new OFChannelState();
767 Controller.OFChannelHandler chdlr = controller.new OFChannelHandler(state);
768 chdlr.sw = createMock(OFSwitchImpl.class);
769
770 // Wrong current state
771 // Should not go to READY
772 state.hsState = OFChannelState.HandshakeState.HELLO;
773 state.hasDescription = true;
774 state.hasGetConfigReply = true;
775 replay(chdlr.sw); // nothing called on sw
776 chdlr.checkSwitchReady();
777 verify(chdlr.sw);
778 assertSame(OFChannelState.HandshakeState.HELLO, state.hsState);
779 reset(chdlr.sw);
780
781 // Have only config reply
782 state.hsState = OFChannelState.HandshakeState.FEATURES_REPLY;
783 state.hasDescription = false;
784 state.hasGetConfigReply = true;
785 replay(chdlr.sw);
786 chdlr.checkSwitchReady();
787 verify(chdlr.sw);
788 assertSame(OFChannelState.HandshakeState.FEATURES_REPLY, state.hsState);
789 assertTrue(controller.connectedSwitches.isEmpty());
790 assertTrue(controller.activeSwitches.isEmpty());
791 reset(chdlr.sw);
792
793 // Have only desc reply
794 state.hsState = OFChannelState.HandshakeState.FEATURES_REPLY;
795 state.hasDescription = true;
796 state.hasGetConfigReply = false;
797 replay(chdlr.sw);
798 chdlr.checkSwitchReady();
799 verify(chdlr.sw);
800 assertSame(OFChannelState.HandshakeState.FEATURES_REPLY, state.hsState);
801 assertTrue(controller.connectedSwitches.isEmpty());
802 assertTrue(controller.activeSwitches.isEmpty());
803 reset(chdlr.sw);
804
805 //////////////////////////////////////////
806 // Finally, everything is right. Should advance to READY
807 //////////////////////////////////////////
808 controller.roleChanger = createMock(RoleChanger.class);
809 state.hsState = OFChannelState.HandshakeState.FEATURES_REPLY;
810 state.hasDescription = true;
811 state.hasGetConfigReply = true;
812 // Role support disabled. Switch should be promoted to active switch
813 // list.
814 setupSwitchForAddSwitch(chdlr.sw, 0L);
815 chdlr.sw.clearAllFlowMods();
816 replay(controller.roleChanger, chdlr.sw);
817 chdlr.checkSwitchReady();
818 verify(controller.roleChanger, chdlr.sw);
819 assertSame(OFChannelState.HandshakeState.READY, state.hsState);
820 assertSame(chdlr.sw, controller.activeSwitches.get(0L));
821 assertTrue(controller.connectedSwitches.contains(chdlr.sw));
822 assertTrue(state.firstRoleReplyReceived);
823 reset(chdlr.sw);
824 reset(controller.roleChanger);
825 controller.connectedSwitches.clear();
826 controller.activeSwitches.clear();
827
828
829 // Role support enabled.
830 state.hsState = OFChannelState.HandshakeState.FEATURES_REPLY;
831 controller.role = Role.MASTER;
832 Capture<Collection<OFSwitchImpl>> swListCapture =
833 new Capture<Collection<OFSwitchImpl>>();
834 controller.roleChanger.submitRequest(capture(swListCapture),
835 same(Role.MASTER));
836 replay(controller.roleChanger, chdlr.sw);
837 chdlr.checkSwitchReady();
838 verify(controller.roleChanger, chdlr.sw);
839 assertSame(OFChannelState.HandshakeState.READY, state.hsState);
840 assertTrue(controller.activeSwitches.isEmpty());
841 assertTrue(controller.connectedSwitches.contains(chdlr.sw));
842 assertTrue(state.firstRoleReplyReceived);
843 Collection<OFSwitchImpl> swList = swListCapture.getValue();
844 assertEquals(1, swList.size());
845 assertTrue("swList must contain this switch", swList.contains(chdlr.sw));
846 }
847
848
849 @Test
850 public void testChannelDisconnected() throws Exception {
851 OFChannelState state = new OFChannelState();
852 state.hsState = OFChannelState.HandshakeState.READY;
853 Controller.OFChannelHandler chdlr = controller.new OFChannelHandler(state);
854 chdlr.sw = createMock(OFSwitchImpl.class);
855
856 // Switch is active
857 expect(chdlr.sw.getId()).andReturn(0L).anyTimes();
858 expect(chdlr.sw.getStringId()).andReturn("00:00:00:00:00:00:00:00")
859 .anyTimes();
860 chdlr.sw.cancelAllStatisticsReplies();
861 chdlr.sw.setConnected(false);
862 expect(chdlr.sw.isConnected()).andReturn(true);
863
864 controller.connectedSwitches.add(chdlr.sw);
865 controller.activeSwitches.put(0L, chdlr.sw);
866
867 replay(chdlr.sw);
868 chdlr.channelDisconnected(null, null);
869 verify(chdlr.sw);
870
871 // Switch is connected but not active
872 reset(chdlr.sw);
873 expect(chdlr.sw.getId()).andReturn(0L).anyTimes();
874 chdlr.sw.setConnected(false);
875 replay(chdlr.sw);
876 chdlr.channelDisconnected(null, null);
877 verify(chdlr.sw);
878
879 // Not in ready state
880 state.hsState = HandshakeState.START;
881 reset(chdlr.sw);
882 replay(chdlr.sw);
883 chdlr.channelDisconnected(null, null);
884 verify(chdlr.sw);
885
886 // Switch is null
887 state.hsState = HandshakeState.READY;
888 chdlr.sw = null;
889 chdlr.channelDisconnected(null, null);
890 }
891
892 /*
893 @Test
894 public void testRoleChangeForSerialFailoverSwitch() throws Exception {
895 OFSwitchImpl newsw = createMock(OFSwitchImpl.class);
896 expect(newsw.getId()).andReturn(0L).anyTimes();
897 expect(newsw.getStringId()).andReturn("00:00:00:00:00:00:00").anyTimes();
898 Channel channel2 = createMock(Channel.class);
899 expect(newsw.getChannel()).andReturn(channel2);
900
901 // newsw.role is null because the switch does not support
902 // role request messages
903 expect(newsw.getAttribute(IOFSwitch.SWITCH_SUPPORTS_NX_ROLE))
904 .andReturn(false);
905 // switch is connected
906 controller.connectedSwitches.add(newsw);
907
908 // the switch should get disconnected when role is changed to SLAVE
909 expect(channel2.close()).andReturn(null);
910
911 replay(newsw, channel2);
912 controller.setRole(Role.SLAVE);
913 verify(newsw, channel2);
914 }
915 */
916
917 @Test
918 public void testRoleNotSupportedError() throws Exception {
919 int xid = 424242;
920 OFChannelState state = new OFChannelState();
921 state.hsState = HandshakeState.READY;
922 Controller.OFChannelHandler chdlr = controller.new OFChannelHandler(state);
923 chdlr.sw = createMock(OFSwitchImpl.class);
924 Channel ch = createMock(Channel.class);
925
926 // the error returned when role request message is not supported by sw
927 OFError msg = new OFError();
928 msg.setType(OFType.ERROR);
929 msg.setXid(xid);
930 msg.setErrorType(OFErrorType.OFPET_BAD_REQUEST);
931 msg.setErrorCode(OFBadRequestCode.OFPBRC_BAD_VENDOR);
932
933 // the switch connection should get disconnected when the controller is
934 // in SLAVE mode and the switch does not support role-request messages
935 state.firstRoleReplyReceived = false;
936 controller.role = Role.SLAVE;
937 expect(chdlr.sw.checkFirstPendingRoleRequestXid(xid)).andReturn(true);
938 chdlr.sw.deliverRoleRequestNotSupported(xid);
939 expect(chdlr.sw.getChannel()).andReturn(ch).anyTimes();
940 expect(ch.close()).andReturn(null);
941
942 replay(ch, chdlr.sw);
943 chdlr.processOFMessage(msg);
944 verify(ch, chdlr.sw);
945 assertTrue("state.firstRoleReplyReceived must be true",
946 state.firstRoleReplyReceived);
947 assertTrue("activeSwitches must be empty",
948 controller.activeSwitches.isEmpty());
949 reset(ch, chdlr.sw);
950
951
952 // a different error message - should also reject role request
953 msg.setErrorType(OFErrorType.OFPET_BAD_REQUEST);
954 msg.setErrorCode(OFBadRequestCode.OFPBRC_EPERM);
955 state.firstRoleReplyReceived = false;
956 controller.role = Role.SLAVE;
957 expect(chdlr.sw.checkFirstPendingRoleRequestXid(xid)).andReturn(true);
958 chdlr.sw.deliverRoleRequestNotSupported(xid);
959 expect(chdlr.sw.getChannel()).andReturn(ch).anyTimes();
960 expect(ch.close()).andReturn(null);
961 replay(ch, chdlr.sw);
962
963 chdlr.processOFMessage(msg);
964 verify(ch, chdlr.sw);
965 assertTrue("state.firstRoleReplyReceived must be True even with EPERM",
966 state.firstRoleReplyReceived);
967 assertTrue("activeSwitches must be empty",
968 controller.activeSwitches.isEmpty());
969 reset(ch, chdlr.sw);
970
971
972 // We are MASTER, the switch should be added to the list of active
973 // switches.
974 state.firstRoleReplyReceived = false;
975 controller.role = Role.MASTER;
976 expect(chdlr.sw.checkFirstPendingRoleRequestXid(xid)).andReturn(true);
977 chdlr.sw.deliverRoleRequestNotSupported(xid);
978 setupSwitchForAddSwitch(chdlr.sw, 0L);
979 chdlr.sw.clearAllFlowMods();
980 replay(ch, chdlr.sw);
981
982 chdlr.processOFMessage(msg);
983 verify(ch, chdlr.sw);
984 assertTrue("state.firstRoleReplyReceived must be true",
985 state.firstRoleReplyReceived);
986 assertSame("activeSwitches must contain this switch",
987 chdlr.sw, controller.activeSwitches.get(0L));
988 reset(ch, chdlr.sw);
989
990 }
991
992
993 @Test
994 public void testVendorMessageUnknown() throws Exception {
995 // Check behavior with an unknown vendor id
996 OFChannelState state = new OFChannelState();
997 state.hsState = HandshakeState.READY;
998 Controller.OFChannelHandler chdlr = controller.new OFChannelHandler(state);
999 OFVendor msg = new OFVendor();
1000 msg.setVendor(0);
1001 chdlr.processOFMessage(msg);
1002 }
1003
1004
1005 // Helper function.
1006 protected Controller.OFChannelHandler getChannelHandlerForRoleReplyTest() {
1007 OFChannelState state = new OFChannelState();
1008 state.hsState = HandshakeState.READY;
1009 Controller.OFChannelHandler chdlr = controller.new OFChannelHandler(state);
1010 chdlr.sw = createMock(OFSwitchImpl.class);
1011 return chdlr;
1012 }
1013
1014 // Helper function
1015 protected OFVendor getRoleReplyMsgForRoleReplyTest(int xid, int nicira_role) {
1016 OFVendor msg = new OFVendor();
1017 msg.setXid(xid);
1018 msg.setVendor(OFNiciraVendorData.NX_VENDOR_ID);
1019 OFRoleReplyVendorData roleReplyVendorData =
1020 new OFRoleReplyVendorData(OFRoleReplyVendorData.NXT_ROLE_REPLY);
1021 msg.setVendorData(roleReplyVendorData);
1022 roleReplyVendorData.setRole(nicira_role);
1023 return msg;
1024 }
1025
1026 /** invalid role in role reply */
1027 @Test
1028 public void testNiciraRoleReplyInvalidRole()
1029 throws Exception {
1030 int xid = 424242;
1031 Controller.OFChannelHandler chdlr = getChannelHandlerForRoleReplyTest();
1032 Channel ch = createMock(Channel.class);
1033 expect(chdlr.sw.getChannel()).andReturn(ch);
1034 expect(ch.close()).andReturn(null);
1035 OFVendor msg = getRoleReplyMsgForRoleReplyTest(xid, 232323);
1036 replay(chdlr.sw, ch);
1037 chdlr.processOFMessage(msg);
1038 verify(chdlr.sw, ch);
1039 }
1040
1041 /** First role reply message received: transition from slave to master */
1042 @Test
1043 public void testNiciraRoleReplySlave2MasterFristTime()
1044 throws Exception {
1045 int xid = 424242;
1046 Controller.OFChannelHandler chdlr = getChannelHandlerForRoleReplyTest();
1047 OFVendor msg = getRoleReplyMsgForRoleReplyTest(xid,
1048 OFRoleReplyVendorData.NX_ROLE_MASTER);
1049
1050 chdlr.sw.deliverRoleReply(xid, Role.MASTER);
1051 expect(chdlr.sw.isActive()).andReturn(true);
1052 setupSwitchForAddSwitch(chdlr.sw, 1L);
1053 chdlr.sw.clearAllFlowMods();
1054 chdlr.state.firstRoleReplyReceived = false;
1055 replay(chdlr.sw);
1056 chdlr.processOFMessage(msg);
1057 verify(chdlr.sw);
1058 assertTrue("state.firstRoleReplyReceived must be true",
1059 chdlr.state.firstRoleReplyReceived);
1060 assertSame("activeSwitches must contain this switch",
1061 chdlr.sw, controller.activeSwitches.get(1L));
1062 }
1063
1064
1065 /** Not first role reply message received: transition from slave to master */
1066 @Test
1067 public void testNiciraRoleReplySlave2MasterNotFristTime()
1068 throws Exception {
1069 int xid = 424242;
1070 Controller.OFChannelHandler chdlr = getChannelHandlerForRoleReplyTest();
1071 OFVendor msg = getRoleReplyMsgForRoleReplyTest(xid,
1072 OFRoleReplyVendorData.NX_ROLE_MASTER);
1073
1074 chdlr.sw.deliverRoleReply(xid, Role.MASTER);
1075 expect(chdlr.sw.isActive()).andReturn(true);
1076 setupSwitchForAddSwitch(chdlr.sw, 1L);
1077 chdlr.state.firstRoleReplyReceived = true;
1078 // Flow table shouldn't be wipe
1079 replay(chdlr.sw);
1080 chdlr.processOFMessage(msg);
1081 verify(chdlr.sw);
1082 assertTrue("state.firstRoleReplyReceived must be true",
1083 chdlr.state.firstRoleReplyReceived);
1084 assertSame("activeSwitches must contain this switch",
1085 chdlr.sw, controller.activeSwitches.get(1L));
1086 }
1087
1088 /** transition from slave to equal */
1089 @Test
1090 public void testNiciraRoleReplySlave2Equal()
1091 throws Exception {
1092 int xid = 424242;
1093 Controller.OFChannelHandler chdlr = getChannelHandlerForRoleReplyTest();
1094 OFVendor msg = getRoleReplyMsgForRoleReplyTest(xid,
1095 OFRoleReplyVendorData.NX_ROLE_OTHER);
1096
1097 chdlr.sw.deliverRoleReply(xid, Role.EQUAL);
1098 expect(chdlr.sw.isActive()).andReturn(true);
1099 setupSwitchForAddSwitch(chdlr.sw, 1L);
1100 chdlr.sw.clearAllFlowMods();
1101 chdlr.state.firstRoleReplyReceived = false;
1102 replay(chdlr.sw);
1103 chdlr.processOFMessage(msg);
1104 verify(chdlr.sw);
1105 assertTrue("state.firstRoleReplyReceived must be true",
1106 chdlr.state.firstRoleReplyReceived);
1107 assertSame("activeSwitches must contain this switch",
1108 chdlr.sw, controller.activeSwitches.get(1L));
1109 };
1110
1111 @Test
1112 /** Slave2Slave transition ==> no change */
1113 public void testNiciraRoleReplySlave2Slave() throws Exception{
1114 int xid = 424242;
1115 Controller.OFChannelHandler chdlr = getChannelHandlerForRoleReplyTest();
1116 OFVendor msg = getRoleReplyMsgForRoleReplyTest(xid,
1117 OFRoleReplyVendorData.NX_ROLE_SLAVE);
1118
1119 chdlr.sw.deliverRoleReply(xid, Role.SLAVE);
1120 expect(chdlr.sw.getId()).andReturn(1L).anyTimes();
1121 expect(chdlr.sw.getStringId()).andReturn("00:00:00:00:00:00:00:01")
1122 .anyTimes();
1123 expect(chdlr.sw.isActive()).andReturn(false);
1124 // don't add switch to activeSwitches ==> slave2slave
1125 chdlr.state.firstRoleReplyReceived = false;
1126 replay(chdlr.sw);
1127 chdlr.processOFMessage(msg);
1128 verify(chdlr.sw);
1129 assertTrue("state.firstRoleReplyReceived must be true",
1130 chdlr.state.firstRoleReplyReceived);
1131 assertTrue("activeSwitches must be empty",
1132 controller.activeSwitches.isEmpty());
1133 }
1134
1135 @Test
1136 /** Equal2Master transition ==> no change */
1137 public void testNiciraRoleReplyEqual2Master() throws Exception{
1138 int xid = 424242;
1139 Controller.OFChannelHandler chdlr = getChannelHandlerForRoleReplyTest();
1140 OFVendor msg = getRoleReplyMsgForRoleReplyTest(xid,
1141 OFRoleReplyVendorData.NX_ROLE_MASTER);
1142
1143 chdlr.sw.deliverRoleReply(xid, Role.MASTER);
1144 expect(chdlr.sw.getId()).andReturn(1L).anyTimes();
1145 expect(chdlr.sw.getStringId()).andReturn("00:00:00:00:00:00:00:01")
1146 .anyTimes();
1147 expect(chdlr.sw.isActive()).andReturn(true);
1148 controller.activeSwitches.put(1L, chdlr.sw);
1149 chdlr.state.firstRoleReplyReceived = false;
1150 replay(chdlr.sw);
1151 chdlr.processOFMessage(msg);
1152 verify(chdlr.sw);
1153 assertTrue("state.firstRoleReplyReceived must be true",
1154 chdlr.state.firstRoleReplyReceived);
1155 assertSame("activeSwitches must contain this switch",
1156 chdlr.sw, controller.activeSwitches.get(1L));
1157 }
1158
1159 @Test
1160 public void testNiciraRoleReplyMaster2Slave()
1161 throws Exception {
1162 int xid = 424242;
1163 Controller.OFChannelHandler chdlr = getChannelHandlerForRoleReplyTest();
1164 OFVendor msg = getRoleReplyMsgForRoleReplyTest(xid,
1165 OFRoleReplyVendorData.NX_ROLE_SLAVE);
1166
1167 chdlr.sw.deliverRoleReply(xid, Role.SLAVE);
1168 expect(chdlr.sw.getId()).andReturn(1L).anyTimes();
1169 expect(chdlr.sw.getStringId()).andReturn("00:00:00:00:00:00:00:01")
1170 .anyTimes();
1171 controller.activeSwitches.put(1L, chdlr.sw);
1172 expect(chdlr.sw.isActive()).andReturn(false);
1173 expect(chdlr.sw.isConnected()).andReturn(true);
1174 chdlr.sw.cancelAllStatisticsReplies();
1175 chdlr.state.firstRoleReplyReceived = false;
1176 replay(chdlr.sw);
1177 chdlr.processOFMessage(msg);
1178 verify(chdlr.sw);
1179 assertTrue("state.firstRoleReplyReceived must be true",
1180 chdlr.state.firstRoleReplyReceived);
1181 assertTrue("activeSwitches must be empty",
1182 controller.activeSwitches.isEmpty());
1183 }
1184
1185 /**
1186 * Tests that you can't remove a switch from the active
1187 * switch list.
1188 * @throws Exception
1189 */
1190 @Test
1191 public void testRemoveActiveSwitch() {
1192 IOFSwitch sw = EasyMock.createNiceMock(IOFSwitch.class);
1193 boolean exceptionThrown = false;
1194 expect(sw.getId()).andReturn(1L).anyTimes();
1195 replay(sw);
1196 getController().activeSwitches.put(sw.getId(), sw);
1197 try {
1198 getController().getSwitches().remove(1L);
1199 } catch (UnsupportedOperationException e) {
1200 exceptionThrown = true;
1201 }
1202 assertTrue(exceptionThrown);
1203 verify(sw);
1204 }
1205
1206 public void verifyPortChangedUpdateInQueue(IOFSwitch sw) throws Exception {
1207 assertEquals(1, controller.updates.size());
1208 IUpdate update = controller.updates.take();
1209 assertEquals(true, update instanceof SwitchUpdate);
1210 SwitchUpdate swUpdate = (SwitchUpdate)update;
1211 assertEquals(sw, swUpdate.sw);
1212 assertEquals(SwitchUpdateType.PORTCHANGED, swUpdate.switchUpdateType);
1213 }
1214
1215 /*
1216 * Test handlePortStatus()
1217 * TODO: test correct updateStorage behavior!
1218 */
1219 @Test
1220 public void testHandlePortStatus() throws Exception {
1221 IOFSwitch sw = createMock(IOFSwitch.class);
1222 OFPhysicalPort port = new OFPhysicalPort();
1223 port.setName("myPortName1");
1224 port.setPortNumber((short)42);
1225
1226 OFPortStatus ofps = new OFPortStatus();
1227 ofps.setDesc(port);
1228
1229 ofps.setReason((byte)OFPortReason.OFPPR_ADD.ordinal());
1230 sw.setPort(port);
1231 expectLastCall().once();
1232 replay(sw);
1233 controller.handlePortStatusMessage(sw, ofps, false);
1234 verify(sw);
1235 verifyPortChangedUpdateInQueue(sw);
1236 reset(sw);
1237
1238 ofps.setReason((byte)OFPortReason.OFPPR_MODIFY.ordinal());
1239 sw.setPort(port);
1240 expectLastCall().once();
1241 replay(sw);
1242 controller.handlePortStatusMessage(sw, ofps, false);
1243 verify(sw);
1244 verifyPortChangedUpdateInQueue(sw);
1245 reset(sw);
1246
1247 ofps.setReason((byte)OFPortReason.OFPPR_DELETE.ordinal());
1248 sw.deletePort(port.getPortNumber());
1249 expectLastCall().once();
1250 replay(sw);
1251 controller.handlePortStatusMessage(sw, ofps, false);
1252 verify(sw);
1253 verifyPortChangedUpdateInQueue(sw);
1254 reset(sw);
1255 }
1256}