Optimize port status and hello message handling
[openflowplugin.git] / openflowplugin / src / test / java / org / opendaylight / openflowplugin / openflow / md / core / ConnectionConductorImplTest.java
1 /**
2  * Copyright (c) 2013, 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowplugin.openflow.md.core;
10
11 import static org.junit.Assert.assertNotNull;
12
13 import java.math.BigInteger;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Stack;
20 import java.util.concurrent.CountDownLatch;
21 import java.util.concurrent.ScheduledThreadPoolExecutor;
22 import java.util.concurrent.TimeUnit;
23 import org.junit.After;
24 import org.junit.Assert;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28 import org.mockito.ArgumentCaptor;
29 import org.mockito.Matchers;
30 import org.mockito.Mock;
31 import org.mockito.Mockito;
32 import org.mockito.runners.MockitoJUnitRunner;
33 import org.opendaylight.openflowplugin.api.OFConstants;
34 import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
35 import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
36 import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
37 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
38 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
39 import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
40 import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
41 import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
42 import org.opendaylight.openflowplugin.openflow.md.core.plan.ConnectionAdapterStackImpl;
43 import org.opendaylight.openflowplugin.openflow.md.core.plan.EventFactory;
44 import org.opendaylight.openflowplugin.openflow.md.core.plan.SwitchTestEvent;
45 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
46 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
47 import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessorLightImpl;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeaturesV10;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessageBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessageBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessageBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessageBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessageBuilder;
66 import org.opendaylight.yangtools.yang.binding.DataContainer;
67 import org.opendaylight.yangtools.yang.binding.DataObject;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 @RunWith(MockitoJUnitRunner.class)
72 public class ConnectionConductorImplTest {
73
74     protected static final Logger LOG = LoggerFactory
75             .getLogger(ConnectionConductorImplTest.class);
76
77     /**
78      * in [ms]
79      */
80     private final int maxProcessingTimeout = 500;
81
82     protected ConnectionAdapterStackImpl adapter;
83     private ConnectionConductorImpl connectionConductor;
84     private MDController controller;
85     private Stack<SwitchTestEvent> eventPlan;
86
87     private Thread libSimulation;
88     private final ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(
89             8);
90
91     protected QueueProcessorLightImpl queueProcessor;
92
93     private PopListenerCountingImpl<DataObject> popListener;
94
95     private int experimenterMessageCounter;
96     private int packetinMessageCounter;
97     private int flowremovedMessageCounter;
98     private int portstatusAddMessageCounter;
99     private int portstatusDeleteMessageCounter;
100     private int portstatusModifyMessageCounter;
101     private int errorMessageCounter;
102
103     @Mock
104     private ErrorHandlerSimpleImpl errorHandler;
105
106     private final int expectedErrors = 0;
107     @Mock
108     private MessageSpy<DataContainer> messageSpy;
109     @Mock
110     HandshakeContext handshakeContext;
111     private ErrorMessageService objErms;
112
113     public void incrExperimenterMessageCounter() {
114         this.experimenterMessageCounter++;
115     }
116
117     public void incrPacketinMessageCounter() {
118         this.packetinMessageCounter++;
119     }
120
121     public void incrFlowremovedMessageCounter() {
122         this.flowremovedMessageCounter++;
123     }
124
125     public void incrPortstatusAddMessageCounter() {
126         this.portstatusAddMessageCounter++;
127     }
128
129     public void incrPortstatusDeleteMessageCounter() {
130         this.portstatusDeleteMessageCounter++;
131     }
132
133     public void incrPortstatusModifyMessageCounter() {
134         this.portstatusModifyMessageCounter++;
135     }
136
137     public void incrErrorMessageCounter() {
138         this.errorMessageCounter++;
139     }
140
141     @Test
142     /**
143      * Test for ConnectionConductorFactory#createConductor
144      */
145     public void testCreateConductor() {
146         ConnectionConductor connectionConductor = ConnectionConductorFactory.createConductor(adapter, queueProcessor);
147         assertNotNull(connectionConductor);
148     }
149
150     /**
151      * @throws java.lang.Exception
152      */
153     @Before
154     public void setUp() throws Exception {
155         adapter = new ConnectionAdapterStackImpl();
156
157         popListener = new PopListenerCountingImpl<>();
158
159         final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
160         controller = new MDController(convertorManager);
161         controller.init();
162         controller.getMessageTranslators().putAll(assembleTranslatorMapping());
163
164         queueProcessor = new QueueProcessorLightImpl();
165         queueProcessor.setMessageSpy(messageSpy);
166         queueProcessor.setPopListenersMapping(assemblePopListenerMapping());
167         queueProcessor.setTranslatorMapping(controller.getMessageTranslators());
168         queueProcessor.init();
169
170         connectionConductor = new ConnectionConductorImpl(adapter);
171         connectionConductor.setQueueProcessor(queueProcessor);
172         connectionConductor.setErrorHandler(errorHandler);
173         connectionConductor.init();
174         connectionConductor.setHandshakeContext(handshakeContext);
175         eventPlan = new Stack<>();
176         adapter.setEventPlan(eventPlan);
177         adapter.setProceedTimeout(5000L);
178         adapter.checkListeners();
179     }
180
181     /**
182      * @return
183      */
184     private Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> assemblePopListenerMapping() {
185         Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> mapping = new HashMap<>();
186         Collection<PopListener<DataObject>> popListenerBag = new ArrayList<>();
187         popListenerBag.add(popListener);
188         //TODO: add testing registered types
189         mapping.put(DataObject.class, popListenerBag);
190         return mapping;
191     }
192
193     /**
194      * @throws java.lang.Exception
195      */
196     @After
197     public void tearDown() throws Exception {
198         if (libSimulation != null) {
199             libSimulation.join();
200         }
201         queueProcessor.shutdown();
202
203         for (Exception problem : adapter.getOccuredExceptions()) {
204             LOG.error("during simulation on adapter side: "
205                     + problem.getMessage());
206         }
207         Assert.assertEquals(0, adapter.getOccuredExceptions().size());
208         adapter = null;
209         if (LOG.isDebugEnabled()) {
210             if (eventPlan.size() > 0) {
211                 LOG.debug("eventPlan size: " + eventPlan.size());
212                 for (SwitchTestEvent event : eventPlan) {
213                     LOG.debug(" # EVENT:: " + event);
214                 }
215             }
216         }
217         Assert.assertTrue("plan is not finished", eventPlan.isEmpty());
218         eventPlan = null;
219         controller = null;
220
221         // logging errors if occurred
222         ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
223         Mockito.verify(errorHandler, Mockito.atMost(1)).handleException(
224                 errorCaptor.capture(), Matchers.any(SessionContext.class));
225         for (Throwable problem : errorCaptor.getAllValues()) {
226             LOG.warn(problem.getMessage(), problem);
227         }
228
229         Mockito.verify(errorHandler, Mockito.times(expectedErrors)).handleException(
230                 Matchers.any(Throwable.class), Matchers.any(SessionContext.class));
231     }
232
233     /**
234      * Test method for
235      * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onEchoRequestMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage)}
236      * .
237      *
238      * @throws Exception
239      */
240     @Test
241     public void testOnEchoRequestMessage() throws Exception {
242         simulateV13PostHandshakeState(connectionConductor);
243
244         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
245                 EventFactory.DEFAULT_VERSION, new EchoRequestMessageBuilder()));
246         eventPlan.add(0,
247                 EventFactory.createDefaultWaitForRpcEvent(42, "echoReply"));
248         executeNow();
249     }
250
251     /**
252      * Test of handshake, covering version negotiation and features.
253      * Switch delivers first helloMessage with default version.
254      *
255      * @throws Exception
256      */
257     @Test
258     public void testHandshake1() throws Exception {
259         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
260                 EventFactory.DEFAULT_VERSION, new HelloMessageBuilder()));
261         eventPlan.add(0, EventFactory.createDefaultWaitForAllEvent(
262                 EventFactory.createDefaultWaitForRpcEvent(43, "helloReply"),
263                 EventFactory.createDefaultWaitForRpcEvent(44, "getFeatures")));
264         eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(44,
265                 EventFactory.DEFAULT_VERSION, getFeatureResponseMsg()));
266
267         int i = 1;
268         executeNow();
269
270         Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
271                 connectionConductor.getConductorState());
272         Assert.assertEquals((short) 0x04, connectionConductor.getVersion()
273                 .shortValue());
274     }
275
276     /**
277      * Test of handshake, covering version negotiation and features.
278      * Controller sends first helloMessage with default version
279      *
280      * @throws Exception
281      */
282     @Test
283     public void testHandshake1SwitchStarts() throws Exception {
284         eventPlan.add(0, EventFactory.createConnectionReadyCallback(connectionConductor));
285         eventPlan.add(0, EventFactory.createDefaultWaitForRpcEvent(21, "helloReply"));
286         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
287                 EventFactory.DEFAULT_VERSION, new HelloMessageBuilder()));
288         eventPlan.add(0, EventFactory.createDefaultWaitForRpcEvent(43, "getFeatures"));
289         eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(43,
290                 EventFactory.DEFAULT_VERSION, getFeatureResponseMsg()));
291
292         executeNow();
293
294         Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
295                 connectionConductor.getConductorState());
296         Assert.assertEquals((short) 0x04, connectionConductor.getVersion()
297                 .shortValue());
298     }
299
300     /**
301      * Test of handshake, covering version negotiation and features.
302      * Switch delivers first helloMessage with version 0x05
303      * and negotiates following versions: 0x03, 0x01
304      *
305      * @throws Exception
306      */
307     @Test
308     public void testHandshake2() throws Exception {
309         connectionConductor.setBitmapNegotiationEnable(false);
310         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
311                 (short) 0x05, new HelloMessageBuilder()));
312         eventPlan.add(0,
313                 EventFactory.createDefaultWaitForRpcEvent(43, "helloReply"));
314         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(43L,
315                 (short) 0x03, new HelloMessageBuilder()));
316         eventPlan.add(0,
317                 EventFactory.createDefaultWaitForRpcEvent(44, "helloReply"));
318         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(44L,
319                 (short) 0x01, new HelloMessageBuilder()));
320         eventPlan.add(0,
321                 EventFactory.createDefaultWaitForRpcEvent(45, "getFeatures"));
322
323         eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(45,
324                 (short) 0x01, getFeatureResponseMsg()));
325
326         executeNow();
327
328         Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
329                 connectionConductor.getConductorState());
330         Assert.assertEquals((short) 0x01, connectionConductor.getVersion()
331                 .shortValue());
332     }
333
334     /**
335      * Test of handshake, covering version negotiation and features.
336      * Controller sends first helloMessage with default version
337      * and switch negotiates following versions: 0x05, 0x03, 0x01
338      *
339      * @throws Exception
340      */
341     @Test
342     public void testHandshake2SwitchStarts() throws Exception {
343         connectionConductor.setBitmapNegotiationEnable(false);
344         eventPlan.add(0, EventFactory.createConnectionReadyCallback(connectionConductor));
345         eventPlan.add(0,
346                 EventFactory.createDefaultWaitForRpcEvent(21, "helloReply"));
347         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
348                 (short) 0x05, new HelloMessageBuilder()));
349         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(43L,
350                 (short) 0x03, new HelloMessageBuilder()));
351         eventPlan.add(0,
352                 EventFactory.createDefaultWaitForRpcEvent(44, "helloReply"));
353         eventPlan.add(0, EventFactory.createDefaultNotificationEvent(44L,
354                 (short) 0x01, new HelloMessageBuilder()));
355         eventPlan.add(0,
356                 EventFactory.createDefaultWaitForRpcEvent(45, "getFeatures"));
357
358         eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(45,
359                 (short) 0x01, getFeatureResponseMsg()));
360
361         executeNow();
362
363         Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
364                 connectionConductor.getConductorState());
365         Assert.assertEquals((short) 0x01, connectionConductor.getVersion()
366                 .shortValue());
367     }
368
369     /**
370      * Test method for
371      * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onFlowRemovedMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage)}
372      * .
373      *
374      * @throws InterruptedException
375      */
376     @Test
377     public void testOnFlowRemovedMessage() throws InterruptedException {
378         FlowRemovedMessageService objFms = new FlowRemovedMessageService();
379         controller.addMessageTranslator(FlowRemovedMessage.class, 4, objFms);
380
381         simulateV13PostHandshakeState(connectionConductor);
382         objFms.resetLatch(2);
383
384         // Now send Flow Removed messages
385         FlowRemovedMessageBuilder builder1 = new FlowRemovedMessageBuilder();
386         builder1.setVersion((short) 4);
387         builder1.setXid(1L);
388         connectionConductor.onFlowRemovedMessage(builder1.build());
389             LOG.debug("about to wait for popListener");
390         builder1.setXid(2L);
391         connectionConductor.onFlowRemovedMessage(builder1.build());
392
393         flushMessageProcessing();
394         Assert.assertTrue(objFms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
395         Assert.assertEquals(2, flowremovedMessageCounter);
396     }
397
398     /**
399      * Test method for
400      * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onMultipartReplyMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage)}
401      * .
402      */
403     @Test
404     public void testOnMultipartReplyMessage() {
405         // fail("Not yet implemented");
406         // TODO:: add test
407     }
408
409     /**
410      * Test method for
411      * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onPacketInMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage)}
412      * .
413      *
414      * @throws InterruptedException
415      */
416     @Test
417     public void testOnPacketInMessage() throws InterruptedException {
418         PacketInMessageService objPms = new PacketInMessageService();
419         controller.addMessageTranslator(PacketInMessage.class, 4, objPms);
420
421         simulateV13PostHandshakeState(connectionConductor);
422
423         // Now send PacketIn
424         PacketInMessageBuilder builder1 = new PacketInMessageBuilder();
425         builder1.setVersion((short) 4);
426         builder1.setBufferId((long) 1);
427         connectionConductor.onPacketInMessage(builder1.build());
428         builder1.setBufferId((long) 2);
429         connectionConductor.onPacketInMessage(builder1.build());
430
431         flushMessageProcessing();
432         Assert.assertTrue(objPms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
433         Assert.assertEquals(2, packetinMessageCounter);
434     }
435
436     /**
437      * Test method for
438      * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onPortStatusMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage)}
439      * .
440      *
441      * @throws InterruptedException
442      */
443     @Test
444     public void testOnPortStatusMessage() throws InterruptedException {
445         PortStatusMessageService objPSms = new PortStatusMessageService();
446         controller.addMessageTranslator(PortStatusMessage.class, 4, objPSms);
447
448         simulateV13PostHandshakeState(connectionConductor);
449
450         // Send Port Status messages
451         PortStatusMessageBuilder builder1 = new PortStatusMessageBuilder();
452         builder1.setVersion((short) 4);
453         PortFeatures features = new PortFeatures(true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false);
454         builder1.setPortNo(90L).setReason(PortReason.OFPPRADD).setCurrentFeatures(features);
455         objPSms.resetLatch(3);
456         LOG.debug("sending port message");
457         connectionConductor.onPortStatusMessage(builder1.build());
458         builder1.setPortNo(90L).setReason(PortReason.OFPPRMODIFY).setCurrentFeatures(features);
459         connectionConductor.onPortStatusMessage(builder1.build());
460         builder1.setPortNo(90L).setReason(PortReason.OFPPRDELETE).setCurrentFeatures(features);
461         connectionConductor.onPortStatusMessage(builder1.build());
462
463         flushMessageProcessing();
464         Assert.assertTrue(objPSms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
465         Assert.assertEquals(1, portstatusModifyMessageCounter);
466         Assert.assertEquals(1, portstatusAddMessageCounter);
467         Assert.assertEquals(1, portstatusDeleteMessageCounter);
468     }
469
470     private void flushMessageProcessing() throws InterruptedException {
471         // make sure that harvester sleeps deeply
472         Thread.sleep(maxProcessingTimeout);
473         // flushing messages
474         queueProcessor.getHarvesterHandle().ping();
475     }
476
477     /**
478      * @throws InterruptedException
479      */
480     private void executeLater() throws InterruptedException {
481         execute(false);
482     }
483
484     /**
485      * @throws InterruptedException
486      */
487     private void executeNow() throws InterruptedException {
488         execute(true);
489     }
490
491     /**
492      * @throws InterruptedException
493      */
494     private void execute(final boolean join) throws InterruptedException {
495         libSimulation = new Thread(adapter, "junit-adapter");
496         libSimulation.start();
497         if (join) {
498             libSimulation.join();
499         }
500     }
501
502     private static GetFeaturesOutputBuilder getFeatureResponseMsg() {
503         GetFeaturesOutputBuilder getFeaturesOutputBuilder = new GetFeaturesOutputBuilder();
504         getFeaturesOutputBuilder.setDatapathId(new BigInteger("102030405060"));
505         getFeaturesOutputBuilder.setAuxiliaryId((short) 0);
506         getFeaturesOutputBuilder.setBuffers(4L);
507         getFeaturesOutputBuilder.setReserved(0L);
508         getFeaturesOutputBuilder.setTables((short) 2);
509         getFeaturesOutputBuilder.setCapabilities(createCapabilities(84));
510
511         return getFeaturesOutputBuilder;
512     }
513
514     /**
515      * @return
516      */
517     private static Capabilities createCapabilities(final long input) {
518         final Boolean FLOW_STATS = (input & (1 << 0)) != 0;
519         final Boolean TABLE_STATS = (input & (1 << 1)) != 0;
520         final Boolean PORT_STATS = (input & (1 << 2)) != 0;
521         final Boolean GROUP_STATS = (input & (1 << 3)) != 0;
522         final Boolean IP_REASM = (input & (1 << 5)) != 0;
523         final Boolean QUEUE_STATS = (input & (1 << 6)) != 0;
524         final Boolean PORT_BLOCKED = (input & (1 << 8)) != 0;
525         Capabilities capabilities = new Capabilities(FLOW_STATS, GROUP_STATS, IP_REASM,
526                 PORT_BLOCKED, PORT_STATS, QUEUE_STATS, TABLE_STATS);
527         return capabilities;
528     }
529
530     public abstract class ProcessingLatchService {
531         private CountDownLatch processingLatch = new CountDownLatch(0);
532
533         public void resetLatch(int passAmount) {
534             processingLatch = new CountDownLatch(passAmount);
535         }
536
537         protected void countDown() {
538             processingLatch.countDown();
539         }
540
541         public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
542             return processingLatch.await(timeout, unit);
543         }
544     }
545
546     public class ExperimenterMessageService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
547         @Override
548         public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
549             LOG.debug("Received a packet in Experimenter Service");
550             ConnectionConductorImplTest.this.incrExperimenterMessageCounter();
551             return null;
552         }
553     }
554
555     public class PacketInMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
556         @Override
557         public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
558             LOG.debug("Received a packet in PacketIn Service");
559             ConnectionConductorImplTest.this.incrPacketinMessageCounter();
560             countDown();
561             return null;
562         }
563     }
564
565     public class FlowRemovedMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
566         @Override
567         public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
568             LOG.debug("Received a packet in FlowRemoved Service");
569             ConnectionConductorImplTest.this.incrFlowremovedMessageCounter();
570             countDown();
571             return null;
572         }
573     }
574
575     public class PortStatusMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
576         @Override
577         public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
578             LOG.debug("Received a packet in PortStatus Service");
579             if ((((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRADD))) {
580                 ConnectionConductorImplTest.this.incrPortstatusAddMessageCounter();
581             } else if (((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRDELETE)) {
582                 ConnectionConductorImplTest.this.incrPortstatusDeleteMessageCounter();
583             } else if (((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRMODIFY)) {
584                 ConnectionConductorImplTest.this.incrPortstatusModifyMessageCounter();
585             }
586             countDown();
587             return null;
588         }
589     }
590
591     public class ErrorMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
592         @Override
593         public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
594             LOG.debug("Received a packet in Experimenter Service");
595             ConnectionConductorImplTest.this.incrErrorMessageCounter();
596             countDown();
597             return null;
598         }
599     }
600
601     /**
602      * Test method for
603      * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onExperimenterMessage(ExperimenterMessage)}
604      * .
605      *
606      * @throws InterruptedException
607      */
608     @Test
609     public void testOnErrorMessage() throws InterruptedException {
610         simulateV13PostHandshakeState(connectionConductor);
611         final int messageAmount = 2;
612
613         objErms.resetLatch(messageAmount);
614         ErrorMessageBuilder builder1 = new ErrorMessageBuilder();
615         builder1.setVersion((short) 4);
616         builder1.setCode(100);
617         connectionConductor.onErrorMessage(builder1.build());
618         builder1.setCode(200);
619         connectionConductor.onErrorMessage(builder1.build());
620
621         flushMessageProcessing();
622         Assert.assertTrue(objErms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
623         Assert.assertEquals(messageAmount, errorMessageCounter);
624     }
625
626     /**
627      * @return listener mapping for:
628      * <ul>
629      * <li>experimenter</li>
630      * <li>error</li>
631      * </ul>
632      */
633     private Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> assembleTranslatorMapping() {
634         Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping = new HashMap<>();
635         TranslatorKey tKey;
636
637         IMDMessageTranslator<OfHeader, List<DataObject>> objEms = new ExperimenterMessageService();
638         Collection<IMDMessageTranslator<OfHeader, List<DataObject>>> existingValues = new ArrayList<>();
639         existingValues.add(objEms);
640         tKey = new TranslatorKey(4, ExperimenterMessage.class.getName());
641         translatorMapping.put(tKey, existingValues);
642         objErms = new ErrorMessageService();
643         existingValues.add(objErms);
644         tKey = new TranslatorKey(4, ErrorMessage.class.getName());
645         translatorMapping.put(tKey, existingValues);
646         return translatorMapping;
647     }
648
649     /**
650      * Test method for
651      * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#processPortStatusMsg(PortStatus)}
652      * <br><br>
653      * Tests for getting features from port status message by port version
654      * <ul>
655      * <li>features are malformed - one of them is null</li>
656      * <li>mismatch between port version and port features</li>
657      * <li>mismatch between port version and port features</li>
658      * <li>non-existing port version</li>
659      * <li>port version OF 1.0</li>
660      * <li>port version OF 1.3</li>
661      * </ul>
662      */
663     @Test
664     public void testProcessPortStatusMsg() {
665         simulateV13PostHandshakeState(connectionConductor);
666
667         long portNumber = 90L;
668         long portNumberV10 = 91L;
669         PortStatusMessage msg;
670
671         PortStatusMessageBuilder builder = new PortStatusMessageBuilder();
672         PortFeatures features = new PortFeatures(true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false);
673         PortFeatures featuresMal = new PortFeatures(true, false, false, false, null, false, false, false, false, false, false, false, false, false, false, false);
674         PortFeaturesV10 featuresV10 = new PortFeaturesV10(true, false, false, false, false, false, false, false, false, false, false, false);
675
676         //Malformed features
677         builder.setVersion((short) 1).setPortNo(portNumber).setReason(PortReason.OFPPRADD).setCurrentFeatures(featuresMal);
678         connectionConductor.processPortStatusMsg(builder.build());
679         Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty());
680         Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty());
681
682         //Version-features mismatch
683         builder.setCurrentFeatures(features);
684         connectionConductor.processPortStatusMsg(builder.build());
685         Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty());
686         Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty());
687
688         //Non existing version
689         builder.setVersion((short) 0);
690         connectionConductor.processPortStatusMsg(builder.build());
691         Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty());
692         Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty());
693
694         //Version OF 1.3
695         builder.setVersion((short) 4);
696         msg = builder.build();
697         connectionConductor.processPortStatusMsg(builder.build());
698         Assert.assertTrue(connectionConductor.getSessionContext().getPortBandwidth(portNumber));
699         Assert.assertEquals(connectionConductor.getSessionContext().getPhysicalPort(portNumber), msg);
700
701         //Version OF 1.0
702         builder.setVersion((short) 1).setPortNo(portNumberV10).setCurrentFeatures(null).setCurrentFeaturesV10(featuresV10);
703         msg = builder.build();
704         connectionConductor.processPortStatusMsg(builder.build());
705         Assert.assertTrue(connectionConductor.getSessionContext().getPortBandwidth(portNumberV10));
706         Assert.assertEquals(connectionConductor.getSessionContext().getPhysicalPort(portNumberV10), msg);
707     }
708
709
710     @Test
711     public void testHandshakeFailOperations(){
712         connectionConductor.onHandshakeFailure();
713         connectionConductor.checkState(ConnectionConductor.CONDUCTOR_STATE.RIP);
714     }
715     private static void simulateV13PostHandshakeState(final ConnectionConductorImpl conductor) {
716         GetFeaturesOutputBuilder featureOutput = getFeatureResponseMsg();
717         conductor.postHandshakeBasic(featureOutput.build(), OFConstants.OFP_VERSION_1_3);
718         LOG.debug("simulating post handshake event done");
719     }
720 }