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