blob: adcb9904d68e265880efb471c869b955facfcd40 [file] [log] [blame]
tom7ef8ff92014-09-17 13:08:06 -07001//CHECKSTYLE:OFF
2package org.onlab.onos.of.controller.impl;
3
4import java.io.IOException;
5import java.nio.channels.ClosedChannelException;
6import java.util.ArrayList;
7import java.util.Collections;
8import java.util.List;
9import java.util.concurrent.CopyOnWriteArrayList;
10import java.util.concurrent.RejectedExecutionException;
11
12import org.jboss.netty.channel.Channel;
13import org.jboss.netty.channel.ChannelHandlerContext;
14import org.jboss.netty.channel.ChannelStateEvent;
15import org.jboss.netty.channel.ExceptionEvent;
16import org.jboss.netty.channel.MessageEvent;
17import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
18import org.jboss.netty.handler.timeout.IdleStateEvent;
19import org.jboss.netty.handler.timeout.ReadTimeoutException;
20import org.onlab.onos.of.controller.driver.OpenFlowSwitchDriver;
21import org.onlab.onos.of.controller.driver.SwitchStateException;
22import org.projectfloodlight.openflow.exceptions.OFParseError;
23import org.projectfloodlight.openflow.protocol.OFAsyncGetReply;
24import org.projectfloodlight.openflow.protocol.OFBadRequestCode;
25import org.projectfloodlight.openflow.protocol.OFBarrierReply;
26import org.projectfloodlight.openflow.protocol.OFBarrierRequest;
27import org.projectfloodlight.openflow.protocol.OFDescStatsReply;
28import org.projectfloodlight.openflow.protocol.OFDescStatsRequest;
29import org.projectfloodlight.openflow.protocol.OFEchoReply;
30import org.projectfloodlight.openflow.protocol.OFEchoRequest;
31import org.projectfloodlight.openflow.protocol.OFErrorMsg;
32import org.projectfloodlight.openflow.protocol.OFErrorType;
33import org.projectfloodlight.openflow.protocol.OFExperimenter;
34import org.projectfloodlight.openflow.protocol.OFFactory;
35import org.projectfloodlight.openflow.protocol.OFFeaturesReply;
36import org.projectfloodlight.openflow.protocol.OFFlowModFailedCode;
37import org.projectfloodlight.openflow.protocol.OFFlowRemoved;
38import org.projectfloodlight.openflow.protocol.OFGetConfigReply;
39import org.projectfloodlight.openflow.protocol.OFGetConfigRequest;
40import org.projectfloodlight.openflow.protocol.OFHello;
41import org.projectfloodlight.openflow.protocol.OFHelloElem;
42import org.projectfloodlight.openflow.protocol.OFMessage;
43import org.projectfloodlight.openflow.protocol.OFPacketIn;
44import org.projectfloodlight.openflow.protocol.OFPortDescStatsReply;
45import org.projectfloodlight.openflow.protocol.OFPortDescStatsRequest;
46import org.projectfloodlight.openflow.protocol.OFPortStatus;
47import org.projectfloodlight.openflow.protocol.OFQueueGetConfigReply;
48import org.projectfloodlight.openflow.protocol.OFRoleReply;
49import org.projectfloodlight.openflow.protocol.OFSetConfig;
50import org.projectfloodlight.openflow.protocol.OFStatsReply;
51import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
52import org.projectfloodlight.openflow.protocol.OFStatsType;
53import org.projectfloodlight.openflow.protocol.OFType;
54import org.projectfloodlight.openflow.protocol.OFVersion;
55import org.projectfloodlight.openflow.protocol.errormsg.OFBadRequestErrorMsg;
56import org.projectfloodlight.openflow.protocol.errormsg.OFFlowModFailedErrorMsg;
57import org.projectfloodlight.openflow.types.U32;
58import org.slf4j.Logger;
59import org.slf4j.LoggerFactory;
60
61/**
62 * Channel handler deals with the switch connection and dispatches
63 * switch messages to the appropriate locations.
64 */
65class OFChannelHandler extends IdleStateAwareChannelHandler {
66 private static final Logger log = LoggerFactory.getLogger(OFChannelHandler.class);
67 private final Controller controller;
68 private OpenFlowSwitchDriver sw;
69 private long thisdpid; // channelHandler cached value of connected switch id
70 private Channel channel;
71 // State needs to be volatile because the HandshakeTimeoutHandler
72 // needs to check if the handshake is complete
73 private volatile ChannelState state;
74
75 // When a switch with a duplicate dpid is found (i.e we already have a
76 // connected switch with the same dpid), the new switch is immediately
77 // disconnected. At that point netty callsback channelDisconnected() which
78 // proceeds to cleaup switch state - we need to ensure that it does not cleanup
79 // switch state for the older (still connected) switch
80 private volatile Boolean duplicateDpidFound;
81
82 // Temporary storage for switch-features and port-description
83 private OFFeaturesReply featuresReply;
84 private OFPortDescStatsReply portDescReply;
85 // a concurrent ArrayList to temporarily store port status messages
86 // before we are ready to deal with them
87 private final CopyOnWriteArrayList<OFPortStatus> pendingPortStatusMsg;
88
89 //Indicates the openflow version used by this switch
90 protected OFVersion ofVersion;
91 protected OFFactory factory13;
92 protected OFFactory factory10;
93
94 /** transaction Ids to use during handshake. Since only one thread
95 * calls into an OFChannelHandler instance, we don't need atomic.
96 * We will count down
97 */
98 private int handshakeTransactionIds = -1;
99
100 /**
101 * Create a new unconnected OFChannelHandler.
102 * @param controller
103 */
104 OFChannelHandler(Controller controller) {
105 this.controller = controller;
106 this.state = ChannelState.INIT;
107 this.pendingPortStatusMsg = new CopyOnWriteArrayList<OFPortStatus>();
108 factory13 = controller.getOFMessageFactory13();
109 factory10 = controller.getOFMessageFactory10();
110 duplicateDpidFound = Boolean.FALSE;
111 }
112
113
114
115 // XXX S consider if necessary
116 public void disconnectSwitch() {
117 sw.disconnectSwitch();
118 }
119
120
121
122 //*************************
123 // Channel State Machine
124 //*************************
125
126 /**
127 * The state machine for handling the switch/channel state. All state
128 * transitions should happen from within the state machine (and not from other
129 * parts of the code)
130 */
131 enum ChannelState {
132 /**
133 * Initial state before channel is connected.
134 */
135 INIT(false) {
136 @Override
137 void processOFMessage(OFChannelHandler h, OFMessage m)
138 throws IOException, SwitchStateException {
139 illegalMessageReceived(h, m);
140 }
141
142 @Override
143 void processOFError(OFChannelHandler h, OFErrorMsg m)
144 throws IOException {
145 // need to implement since its abstract but it will never
146 // be called
147 }
148
149 @Override
150 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
151 throws IOException {
152 unhandledMessageReceived(h, m);
153 }
154 },
155
156 /**
157 * We send a OF 1.3 HELLO to the switch and wait for a Hello from the switch.
158 * Once we receive the reply, we decide on OF 1.3 or 1.0 switch - no other
159 * protocol version is accepted.
160 * We send an OFFeaturesRequest depending on the protocol version selected
161 * Next state is WAIT_FEATURES_REPLY
162 */
163 WAIT_HELLO(false) {
164 @Override
165 void processOFHello(OFChannelHandler h, OFHello m)
166 throws IOException {
167 // TODO We could check for the optional bitmap, but for now
168 // we are just checking the version number.
169 if (m.getVersion() == OFVersion.OF_13) {
170 log.info("Received {} Hello from {}", m.getVersion(),
171 h.channel.getRemoteAddress());
172 h.ofVersion = OFVersion.OF_13;
173 } else if (m.getVersion() == OFVersion.OF_10) {
174 log.info("Received {} Hello from {} - switching to OF "
175 + "version 1.0", m.getVersion(),
176 h.channel.getRemoteAddress());
177 h.ofVersion = OFVersion.OF_10;
178 } else {
179 log.error("Received Hello of version {} from switch at {}. "
180 + "This controller works with OF1.0 and OF1.3 "
181 + "switches. Disconnecting switch ...",
182 m.getVersion(), h.channel.getRemoteAddress());
183 h.channel.disconnect();
184 return;
185 }
186 h.sendHandshakeFeaturesRequestMessage();
187 h.setState(WAIT_FEATURES_REPLY);
188 }
189 @Override
190 void processOFFeaturesReply(OFChannelHandler h, OFFeaturesReply m)
191 throws IOException, SwitchStateException {
192 illegalMessageReceived(h, m);
193 }
194 @Override
195 void processOFStatisticsReply(OFChannelHandler h,
196 OFStatsReply m)
197 throws IOException, SwitchStateException {
198 illegalMessageReceived(h, m);
199 }
200 @Override
201 void processOFError(OFChannelHandler h, OFErrorMsg m) {
202 logErrorDisconnect(h, m);
203 }
204
205 @Override
206 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
207 throws IOException {
208 unhandledMessageReceived(h, m);
209 }
210 },
211
212
213 /**
214 * We are waiting for a features reply message. Once we receive it, the
215 * behavior depends on whether this is a 1.0 or 1.3 switch. For 1.0,
216 * we send a SetConfig request, barrier, and GetConfig request and the
217 * next state is WAIT_CONFIG_REPLY. For 1.3, we send a Port description
218 * request and the next state is WAIT_PORT_DESC_REPLY.
219 */
220 WAIT_FEATURES_REPLY(false) {
221 @Override
222 void processOFFeaturesReply(OFChannelHandler h, OFFeaturesReply m)
223 throws IOException {
224 h.thisdpid = m.getDatapathId().getLong();
225 log.info("Received features reply for switch at {} with dpid {}",
226 h.getSwitchInfoString(), h.thisdpid);
227
228 h.featuresReply = m; //temp store
229 if (h.ofVersion == OFVersion.OF_10) {
230 h.sendHandshakeSetConfig();
231 h.setState(WAIT_CONFIG_REPLY);
232 } else {
233 //version is 1.3, must get switchport information
234 h.sendHandshakeOFPortDescRequest();
235 h.setState(WAIT_PORT_DESC_REPLY);
236 }
237 }
238 @Override
239 void processOFStatisticsReply(OFChannelHandler h,
240 OFStatsReply m)
241 throws IOException, SwitchStateException {
242 illegalMessageReceived(h, m);
243 }
244 @Override
245 void processOFError(OFChannelHandler h, OFErrorMsg m) {
246 logErrorDisconnect(h, m);
247 }
248
249 @Override
250 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
251 throws IOException {
252 unhandledMessageReceived(h, m);
253 }
254 },
255
256 /**
257 * We are waiting for a description of the 1.3 switch ports.
258 * Once received, we send a SetConfig request
259 * Next State is WAIT_CONFIG_REPLY
260 */
261 WAIT_PORT_DESC_REPLY(false) {
262
263 @Override
264 void processOFStatisticsReply(OFChannelHandler h, OFStatsReply m)
265 throws SwitchStateException {
266 // Read port description
267 if (m.getStatsType() != OFStatsType.PORT_DESC) {
268 log.warn("Expecting port description stats but received stats "
269 + "type {} from {}. Ignoring ...", m.getStatsType(),
270 h.channel.getRemoteAddress());
271 return;
272 }
273 if (m.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
274 log.warn("Stats reply indicates more stats from sw {} for "
275 + "port description - not currently handled",
276 h.getSwitchInfoString());
277 }
278 h.portDescReply = (OFPortDescStatsReply) m; // temp store
279 log.info("Received port desc reply for switch at {}",
280 h.getSwitchInfoString());
281 try {
282 h.sendHandshakeSetConfig();
283 } catch (IOException e) {
284 log.error("Unable to send setConfig after PortDescReply. "
285 + "Error: {}", e.getMessage());
286 }
287 h.setState(WAIT_CONFIG_REPLY);
288 }
289
290 @Override
291 void processOFError(OFChannelHandler h, OFErrorMsg m)
292 throws IOException, SwitchStateException {
293 logErrorDisconnect(h, m);
294
295 }
296
297 @Override
298 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
299 throws IOException, SwitchStateException {
300 unhandledMessageReceived(h, m);
301
302 }
303 },
304
305 /**
306 * We are waiting for a config reply message. Once we receive it
307 * we send a DescriptionStatsRequest to the switch.
308 * Next state: WAIT_DESCRIPTION_STAT_REPLY
309 */
310 WAIT_CONFIG_REPLY(false) {
311 @Override
312 void processOFGetConfigReply(OFChannelHandler h, OFGetConfigReply m)
313 throws IOException {
314 if (m.getMissSendLen() == 0xffff) {
315 log.trace("Config Reply from switch {} confirms "
316 + "miss length set to 0xffff",
317 h.getSwitchInfoString());
318 } else {
319 // FIXME: we can't really deal with switches that don't send
320 // full packets. Shouldn't we drop the connection here?
321 log.warn("Config Reply from switch {} has"
322 + "miss length set to {}",
323 h.getSwitchInfoString(),
324 m.getMissSendLen());
325 }
326 h.sendHandshakeDescriptionStatsRequest();
327 h.setState(WAIT_DESCRIPTION_STAT_REPLY);
328 }
329
330 @Override
331 void processOFBarrierReply(OFChannelHandler h, OFBarrierReply m) {
332 // do nothing;
333 }
334
335 @Override
336 void processOFFeaturesReply(OFChannelHandler h, OFFeaturesReply m)
337 throws IOException, SwitchStateException {
338 illegalMessageReceived(h, m);
339 }
340 @Override
341 void processOFStatisticsReply(OFChannelHandler h,
342 OFStatsReply m)
343 throws IOException, SwitchStateException {
344 log.error("Received multipart(stats) message sub-type {}",
345 m.getStatsType());
346 illegalMessageReceived(h, m);
347 }
348
349 @Override
350 void processOFError(OFChannelHandler h, OFErrorMsg m) {
351 logErrorDisconnect(h, m);
352 }
353
354 @Override
355 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
356 throws IOException {
357 h.pendingPortStatusMsg.add(m);
358 }
359 },
360
361
362 /**
363 * We are waiting for a OFDescriptionStat message from the switch.
364 * Once we receive any stat message we try to parse it. If it's not
365 * a description stats message we disconnect. If its the expected
366 * description stats message, we:
367 * - use the switch driver to bind the switch and get an IOFSwitch instance
368 * - setup the IOFSwitch instance
369 * - add switch controller and send the initial role
370 * request to the switch.
371 * Next state: WAIT_INITIAL_ROLE
372 * In the typical case, where switches support role request messages
373 * the next state is where we expect the role reply message.
374 * In the special case that where the switch does not support any kind
375 * of role request messages, we don't send a role message, but we do
376 * request mastership from the registry service. This controller
377 * should become master once we hear back from the registry service.
378 * All following states will have a h.sw instance!
379 */
380 WAIT_DESCRIPTION_STAT_REPLY(false) {
381 @Override
382 void processOFStatisticsReply(OFChannelHandler h, OFStatsReply m)
383 throws SwitchStateException {
384 // Read description, if it has been updated
385 if (m.getStatsType() != OFStatsType.DESC) {
386 log.warn("Expecting Description stats but received stats "
387 + "type {} from {}. Ignoring ...", m.getStatsType(),
388 h.channel.getRemoteAddress());
389 return;
390 }
391 log.info("Received switch description reply from switch at {}",
392 h.channel.getRemoteAddress());
393 OFDescStatsReply drep = (OFDescStatsReply) m;
394 // Here is where we differentiate between different kinds of switches
395 h.sw = h.controller.getOFSwitchInstance(h.thisdpid, drep, h.ofVersion);
396
397 h.sw.setOFVersion(h.ofVersion);
398 h.sw.setFeaturesReply(h.featuresReply);
399 h.sw.setPortDescReply(h.portDescReply);
400 h.sw.setConnected(true);
401 h.sw.setChannel(h.channel);
402 boolean success = h.sw.connectSwitch();
403
404 if (!success) {
405 disconnectDuplicate(h);
406 return;
407 }
408 // set switch information
409
410
411
412 log.info("Switch {} bound to class {}, description {}",
413 new Object[] {h.sw, h.sw.getClass(), drep });
414 //Put switch in EQUAL mode until we hear back from the global registry
415 //log.debug("Setting new switch {} to EQUAL and sending Role request",
416 // h.sw.getStringId());
417 //h.sw.activateEqualSwitch();
418 //h.setSwitchRole(RoleState.EQUAL);
419
420 h.sw.startDriverHandshake();
421 h.setState(WAIT_SWITCH_DRIVER_SUB_HANDSHAKE);
422
423 }
424
425 @Override
426 void processOFError(OFChannelHandler h, OFErrorMsg m) {
427 logErrorDisconnect(h, m);
428 }
429
430 @Override
431 void processOFFeaturesReply(OFChannelHandler h, OFFeaturesReply m)
432 throws IOException, SwitchStateException {
433 illegalMessageReceived(h, m);
434 }
435
436 @Override
437 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
438 throws IOException {
439 h.pendingPortStatusMsg.add(m);
440 }
441 },
442
443
444 /**
445 * We are waiting for the respective switch driver to complete its
446 * configuration. Notice that we do not consider this to be part of the main
447 * switch-controller handshake. But we do consider it as a step that comes
448 * before we declare the switch as available to the controller.
449 * Next State: depends on the role of this controller for this switch - either
450 * MASTER or EQUAL.
451 */
452 WAIT_SWITCH_DRIVER_SUB_HANDSHAKE(true) {
453
454 @Override
455 void processOFError(OFChannelHandler h, OFErrorMsg m)
456 throws IOException {
457 // will never be called. We override processOFMessage
458 }
459
460 @Override
461 void processOFMessage(OFChannelHandler h, OFMessage m)
462 throws IOException, SwitchStateException {
463 if (m.getType() == OFType.ECHO_REQUEST) {
464 processOFEchoRequest(h, (OFEchoRequest) m);
465 } else if (m.getType() == OFType.ROLE_REPLY) {
466 h.sw.handleRole(m);
467 } else if (m.getType() == OFType.ERROR) {
468 if (!h.sw.handleRoleError((OFErrorMsg)m)) {
469 h.sw.processDriverHandshakeMessage(m);
470 if (h.sw.isDriverHandshakeComplete()) {
471 h.setState(ACTIVE);
472 }
473 }
474 } else {
475 if (m.getType() == OFType.EXPERIMENTER &&
476 ((OFExperimenter) m).getExperimenter() ==
477 RoleManager.NICIRA_EXPERIMENTER) {
478 h.sw.handleNiciraRole(m);
479 } else {
480 h.sw.processDriverHandshakeMessage(m);
481 if (h.sw.isDriverHandshakeComplete()) {
482 h.setState(ACTIVE);
483 }
484 }
485 }
486 }
487
488 @Override
489 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
490 throws IOException, SwitchStateException {
491 h.pendingPortStatusMsg.add(m);
492 }
493 },
494
495
496 /**
497 * This controller is in MASTER role for this switch. We enter this state
498 * after requesting and winning control from the global registry.
499 * The main handshake as well as the switch-driver sub-handshake
500 * is complete at this point.
501 * // XXX S reconsider below
502 * In the (near) future we may deterministically assign controllers to
503 * switches at startup.
504 * We only leave this state if the switch disconnects or
505 * if we send a role request for SLAVE /and/ receive the role reply for
506 * SLAVE.
507 */
508 ACTIVE(true) {
509 @Override
510 void processOFError(OFChannelHandler h, OFErrorMsg m)
511 throws IOException, SwitchStateException {
512 // if we get here, then the error message is for something else
513 if (m.getErrType() == OFErrorType.BAD_REQUEST &&
514 ((OFBadRequestErrorMsg) m).getCode() ==
515 OFBadRequestCode.EPERM) {
516 // We are the master controller and the switch returned
517 // a permission error. This is a likely indicator that
518 // the switch thinks we are slave. Reassert our
519 // role
520 // FIXME: this could be really bad during role transitions
521 // if two controllers are master (even if its only for
522 // a brief period). We might need to see if these errors
523 // persist before we reassert
524 log.warn("Received permission error from switch {} while" +
525 "being master. Reasserting master role.",
526 h.getSwitchInfoString());
527 h.sw.reassertRole();
528 } else if (m.getErrType() == OFErrorType.FLOW_MOD_FAILED &&
529 ((OFFlowModFailedErrorMsg) m).getCode() ==
530 OFFlowModFailedCode.ALL_TABLES_FULL) {
531 h.sw.setTableFull(true);
532 } else {
533 logError(h, m);
534 }
535 h.dispatchMessage(m);
536 }
537
538 @Override
539 void processOFStatisticsReply(OFChannelHandler h,
540 OFStatsReply m) {
541 h.dispatchMessage(m);
542 }
543
544 @Override
545 void processOFExperimenter(OFChannelHandler h, OFExperimenter m)
546 throws SwitchStateException {
547 h.sw.handleNiciraRole(m);
548 }
549
550 @Override
551 void processOFRoleReply(OFChannelHandler h, OFRoleReply m)
552 throws SwitchStateException {
553 h.sw.handleRole(m);
554 }
555
556 @Override
557 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
558 throws SwitchStateException {
559 handlePortStatusMessage(h, m, true);
560 h.dispatchMessage(m);
561 }
562
563 @Override
564 void processOFPacketIn(OFChannelHandler h, OFPacketIn m) {
565 h.dispatchMessage(m);
566 }
567
568 @Override
569 void processOFFlowRemoved(OFChannelHandler h,
570 OFFlowRemoved m) {
571 h.dispatchMessage(m);
572 }
573
574 @Override
575 void processOFBarrierReply(OFChannelHandler h, OFBarrierReply m) {
576 h.dispatchMessage(m);
577 }
578
579 };
580
581 private final boolean handshakeComplete;
582 ChannelState(boolean handshakeComplete) {
583 this.handshakeComplete = handshakeComplete;
584 }
585
586 /**
587 * Is this a state in which the handshake has completed?
588 * @return true if the handshake is complete
589 */
590 public boolean isHandshakeComplete() {
591 return handshakeComplete;
592 }
593
594 /**
595 * Get a string specifying the switch connection, state, and
596 * message received. To be used as message for SwitchStateException
597 * or log messages
598 * @param h The channel handler (to get switch information_
599 * @param m The OFMessage that has just been received
600 * @param details A string giving more details about the exact nature
601 * of the problem.
602 * @return display string
603 */
604 // needs to be protected because enum members are actually subclasses
605 protected String getSwitchStateMessage(OFChannelHandler h,
606 OFMessage m,
607 String details) {
608 return String.format("Switch: [%s], State: [%s], received: [%s]"
609 + ", details: %s",
610 h.getSwitchInfoString(),
611 this.toString(),
612 m.getType().toString(),
613 details);
614 }
615
616 /**
617 * We have an OFMessage we didn't expect given the current state and
618 * we want to treat this as an error.
619 * We currently throw an exception that will terminate the connection
620 * However, we could be more forgiving
621 * @param h the channel handler that received the message
622 * @param m the message
623 * @throws SwitchStateException
624 * @throws SwitchStateExeption we always through the execption
625 */
626 // needs to be protected because enum members are acutally subclasses
627 protected void illegalMessageReceived(OFChannelHandler h, OFMessage m)
628 throws SwitchStateException {
629 String msg = getSwitchStateMessage(h, m,
630 "Switch should never send this message in the current state");
631 throw new SwitchStateException(msg);
632
633 }
634
635 /**
636 * We have an OFMessage we didn't expect given the current state and
637 * we want to ignore the message.
638 * @param h the channel handler the received the message
639 * @param m the message
640 */
641 protected void unhandledMessageReceived(OFChannelHandler h,
642 OFMessage m) {
643 if (log.isDebugEnabled()) {
644 String msg = getSwitchStateMessage(h, m,
645 "Ignoring unexpected message");
646 log.debug(msg);
647 }
648 }
649
650 /**
651 * Log an OpenFlow error message from a switch.
652 * @param h The switch that sent the error
653 * @param error The error message
654 */
655 protected void logError(OFChannelHandler h, OFErrorMsg error) {
656 log.error("{} from switch {} in state {}",
657 new Object[] {
658 error,
659 h.getSwitchInfoString(),
660 this.toString()});
661 }
662
663 /**
664 * Log an OpenFlow error message from a switch and disconnect the
665 * channel.
666 *
667 * @param h the IO channel for this switch.
668 * @param error The error message
669 */
670 protected void logErrorDisconnect(OFChannelHandler h, OFErrorMsg error) {
671 logError(h, error);
672 h.channel.disconnect();
673 }
674
675 /**
676 * log an error message for a duplicate dpid and disconnect this channel.
677 * @param h the IO channel for this switch.
678 */
679 protected void disconnectDuplicate(OFChannelHandler h) {
680 log.error("Duplicated dpid or incompleted cleanup - "
681 + "disconnecting channel {}", h.getSwitchInfoString());
682 h.duplicateDpidFound = Boolean.TRUE;
683 h.channel.disconnect();
684 }
685
686
687
688 /**
689 * Handles all pending port status messages before a switch is declared
690 * activated in MASTER or EQUAL role. Note that since this handling
691 * precedes the activation (and therefore notification to IOFSwitchListerners)
692 * the changes to ports will already be visible once the switch is
693 * activated. As a result, no notifications are sent out for these
694 * pending portStatus messages.
695 * @param h
696 * @throws SwitchStateException
697 */
698 protected void handlePendingPortStatusMessages(OFChannelHandler h) {
699 try {
700 handlePendingPortStatusMessages(h, 0);
701 } catch (SwitchStateException e) {
702 log.error(e.getMessage());
703 }
704 }
705
706 private void handlePendingPortStatusMessages(OFChannelHandler h, int index)
707 throws SwitchStateException {
708 if (h.sw == null) {
709 String msg = "State machine error: switch is null. Should never " +
710 "happen";
711 throw new SwitchStateException(msg);
712 }
713 ArrayList<OFPortStatus> temp = new ArrayList<OFPortStatus>();
714 for (OFPortStatus ps: h.pendingPortStatusMsg) {
715 temp.add(ps);
716 handlePortStatusMessage(h, ps, false);
717 }
718 temp.clear();
719 // expensive but ok - we don't expect too many port-status messages
720 // note that we cannot use clear(), because of the reasons below
721 h.pendingPortStatusMsg.removeAll(temp);
722 // the iterator above takes a snapshot of the list - so while we were
723 // dealing with the pending port-status messages, we could have received
724 // newer ones. Handle them recursively, but break the recursion after
725 // five steps to avoid an attack.
726 if (!h.pendingPortStatusMsg.isEmpty() && ++index < 5) {
727 handlePendingPortStatusMessages(h, index);
728 }
729 }
730
731 /**
732 * Handle a port status message.
733 *
734 * Handle a port status message by updating the port maps in the
735 * IOFSwitch instance and notifying Controller about the change so
736 * it can dispatch a switch update.
737 *
738 * @param h The OFChannelHhandler that received the message
739 * @param m The PortStatus message we received
740 * @param doNotify if true switch port changed events will be
741 * dispatched
742 * @throws SwitchStateException
743 *
744 */
745 protected void handlePortStatusMessage(OFChannelHandler h, OFPortStatus m,
746 boolean doNotify) throws SwitchStateException {
747 if (h.sw == null) {
748 String msg = getSwitchStateMessage(h, m,
749 "State machine error: switch is null. Should never " +
750 "happen");
751 throw new SwitchStateException(msg);
752 }
753
754 h.sw.handleMessage(m);
755 }
756
757
758 /**
759 * Process an OF message received on the channel and
760 * update state accordingly.
761 *
762 * The main "event" of the state machine. Process the received message,
763 * send follow up message if required and update state if required.
764 *
765 * Switches on the message type and calls more specific event handlers
766 * for each individual OF message type. If we receive a message that
767 * is supposed to be sent from a controller to a switch we throw
768 * a SwitchStateExeption.
769 *
770 * The more specific handlers can also throw SwitchStateExceptions
771 *
772 * @param h The OFChannelHandler that received the message
773 * @param m The message we received.
774 * @throws SwitchStateException
775 * @throws IOException
776 */
777 void processOFMessage(OFChannelHandler h, OFMessage m)
778 throws IOException, SwitchStateException {
779 switch(m.getType()) {
780 case HELLO:
781 processOFHello(h, (OFHello) m);
782 break;
783 case BARRIER_REPLY:
784 processOFBarrierReply(h, (OFBarrierReply) m);
785 break;
786 case ECHO_REPLY:
787 processOFEchoReply(h, (OFEchoReply) m);
788 break;
789 case ECHO_REQUEST:
790 processOFEchoRequest(h, (OFEchoRequest) m);
791 break;
792 case ERROR:
793 processOFError(h, (OFErrorMsg) m);
794 break;
795 case FEATURES_REPLY:
796 processOFFeaturesReply(h, (OFFeaturesReply) m);
797 break;
798 case FLOW_REMOVED:
799 processOFFlowRemoved(h, (OFFlowRemoved) m);
800 break;
801 case GET_CONFIG_REPLY:
802 processOFGetConfigReply(h, (OFGetConfigReply) m);
803 break;
804 case PACKET_IN:
805 processOFPacketIn(h, (OFPacketIn) m);
806 break;
807 case PORT_STATUS:
808 processOFPortStatus(h, (OFPortStatus) m);
809 break;
810 case QUEUE_GET_CONFIG_REPLY:
811 processOFQueueGetConfigReply(h, (OFQueueGetConfigReply) m);
812 break;
813 case STATS_REPLY: // multipart_reply in 1.3
814 processOFStatisticsReply(h, (OFStatsReply) m);
815 break;
816 case EXPERIMENTER:
817 processOFExperimenter(h, (OFExperimenter) m);
818 break;
819 case ROLE_REPLY:
820 processOFRoleReply(h, (OFRoleReply) m);
821 break;
822 case GET_ASYNC_REPLY:
823 processOFGetAsyncReply(h, (OFAsyncGetReply) m);
824 break;
825
826 // The following messages are sent to switches. The controller
827 // should never receive them
828 case SET_CONFIG:
829 case GET_CONFIG_REQUEST:
830 case PACKET_OUT:
831 case PORT_MOD:
832 case QUEUE_GET_CONFIG_REQUEST:
833 case BARRIER_REQUEST:
834 case STATS_REQUEST: // multipart request in 1.3
835 case FEATURES_REQUEST:
836 case FLOW_MOD:
837 case GROUP_MOD:
838 case TABLE_MOD:
839 case GET_ASYNC_REQUEST:
840 case SET_ASYNC:
841 case METER_MOD:
842 default:
843 illegalMessageReceived(h, m);
844 break;
845 }
846 }
847
848 /*-----------------------------------------------------------------
849 * Default implementation for message handlers in any state.
850 *
851 * Individual states must override these if they want a behavior
852 * that differs from the default.
853 *
854 * In general, these handlers simply ignore the message and do
855 * nothing.
856 *
857 * There are some exceptions though, since some messages really
858 * are handled the same way in every state (e.g., ECHO_REQUST) or
859 * that are only valid in a single state (e.g., HELLO, GET_CONFIG_REPLY
860 -----------------------------------------------------------------*/
861
862 void processOFHello(OFChannelHandler h, OFHello m)
863 throws IOException, SwitchStateException {
864 // we only expect hello in the WAIT_HELLO state
865 illegalMessageReceived(h, m);
866 }
867
868 void processOFBarrierReply(OFChannelHandler h, OFBarrierReply m)
869 throws IOException {
870 // Silently ignore.
871 }
872
873 void processOFEchoRequest(OFChannelHandler h, OFEchoRequest m)
874 throws IOException {
875 if (h.ofVersion == null) {
876 log.error("No OF version set for {}. Not sending Echo REPLY",
877 h.channel.getRemoteAddress());
878 return;
879 }
880 OFFactory factory = (h.ofVersion == OFVersion.OF_13) ?
881 h.controller.getOFMessageFactory13() : h.controller.getOFMessageFactory10();
882 OFEchoReply reply = factory
883 .buildEchoReply()
884 .setXid(m.getXid())
885 .setData(m.getData())
886 .build();
887 h.channel.write(Collections.singletonList(reply));
888 }
889
890 void processOFEchoReply(OFChannelHandler h, OFEchoReply m)
891 throws IOException {
892 // Do nothing with EchoReplies !!
893 }
894
895 // no default implementation for OFError
896 // every state must override it
897 abstract void processOFError(OFChannelHandler h, OFErrorMsg m)
898 throws IOException, SwitchStateException;
899
900
901 void processOFFeaturesReply(OFChannelHandler h, OFFeaturesReply m)
902 throws IOException, SwitchStateException {
903 unhandledMessageReceived(h, m);
904 }
905
906 void processOFFlowRemoved(OFChannelHandler h, OFFlowRemoved m)
907 throws IOException {
908 unhandledMessageReceived(h, m);
909 }
910
911 void processOFGetConfigReply(OFChannelHandler h, OFGetConfigReply m)
912 throws IOException, SwitchStateException {
913 // we only expect config replies in the WAIT_CONFIG_REPLY state
914 illegalMessageReceived(h, m);
915 }
916
917 void processOFPacketIn(OFChannelHandler h, OFPacketIn m)
918 throws IOException {
919 unhandledMessageReceived(h, m);
920 }
921
922 // no default implementation. Every state needs to handle it.
923 abstract void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
924 throws IOException, SwitchStateException;
925
926 void processOFQueueGetConfigReply(OFChannelHandler h,
927 OFQueueGetConfigReply m)
928 throws IOException {
929 unhandledMessageReceived(h, m);
930 }
931
932 void processOFStatisticsReply(OFChannelHandler h, OFStatsReply m)
933 throws IOException, SwitchStateException {
934 unhandledMessageReceived(h, m);
935 }
936
937 void processOFExperimenter(OFChannelHandler h, OFExperimenter m)
938 throws IOException, SwitchStateException {
939 // TODO: it might make sense to parse the vendor message here
940 // into the known vendor messages we support and then call more
941 // specific event handlers
942 unhandledMessageReceived(h, m);
943 }
944
945 void processOFRoleReply(OFChannelHandler h, OFRoleReply m)
946 throws SwitchStateException, IOException {
947 unhandledMessageReceived(h, m);
948 }
949
950 void processOFGetAsyncReply(OFChannelHandler h,
951 OFAsyncGetReply m) {
952 unhandledMessageReceived(h, m);
953 }
954
955 }
956
957
958
959 //*************************
960 // Channel handler methods
961 //*************************
962
963 @Override
964 public void channelConnected(ChannelHandlerContext ctx,
965 ChannelStateEvent e) throws Exception {
966 channel = e.getChannel();
967 log.info("New switch connection from {}",
968 channel.getRemoteAddress());
969 sendHandshakeHelloMessage();
970 setState(ChannelState.WAIT_HELLO);
971 }
972
973 @Override
974 public void channelDisconnected(ChannelHandlerContext ctx,
975 ChannelStateEvent e) throws Exception {
976 log.info("Switch disconnected callback for sw:{}. Cleaning up ...",
977 getSwitchInfoString());
978 if (thisdpid != 0) {
979 if (!duplicateDpidFound) {
980 // if the disconnected switch (on this ChannelHandler)
981 // was not one with a duplicate-dpid, it is safe to remove all
982 // state for it at the controller. Notice that if the disconnected
983 // switch was a duplicate-dpid, calling the method below would clear
984 // all state for the original switch (with the same dpid),
985 // which we obviously don't want.
986 sw.removeConnectedSwitch();
987 } else {
988 // A duplicate was disconnected on this ChannelHandler,
989 // this is the same switch reconnecting, but the original state was
990 // not cleaned up - XXX check liveness of original ChannelHandler
991 duplicateDpidFound = Boolean.FALSE;
992 }
993 } else {
994 log.warn("no dpid in channelHandler registered for "
995 + "disconnected switch {}", getSwitchInfoString());
996 }
997 }
998
999 @Override
1000 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
1001 throws Exception {
1002 if (e.getCause() instanceof ReadTimeoutException) {
1003 // switch timeout
1004 log.error("Disconnecting switch {} due to read timeout",
1005 getSwitchInfoString());
1006 ctx.getChannel().close();
1007 } else if (e.getCause() instanceof HandshakeTimeoutException) {
1008 log.error("Disconnecting switch {}: failed to complete handshake",
1009 getSwitchInfoString());
1010 ctx.getChannel().close();
1011 } else if (e.getCause() instanceof ClosedChannelException) {
1012 log.debug("Channel for sw {} already closed", getSwitchInfoString());
1013 } else if (e.getCause() instanceof IOException) {
1014 log.error("Disconnecting switch {} due to IO Error: {}",
1015 getSwitchInfoString(), e.getCause().getMessage());
1016 if (log.isDebugEnabled()) {
1017 // still print stack trace if debug is enabled
1018 log.debug("StackTrace for previous Exception: ", e.getCause());
1019 }
1020 ctx.getChannel().close();
1021 } else if (e.getCause() instanceof SwitchStateException) {
1022 log.error("Disconnecting switch {} due to switch state error: {}",
1023 getSwitchInfoString(), e.getCause().getMessage());
1024 if (log.isDebugEnabled()) {
1025 // still print stack trace if debug is enabled
1026 log.debug("StackTrace for previous Exception: ", e.getCause());
1027 }
1028 ctx.getChannel().close();
1029 } else if (e.getCause() instanceof OFParseError) {
1030 log.error("Disconnecting switch "
1031 + getSwitchInfoString() +
1032 " due to message parse failure",
1033 e.getCause());
1034 ctx.getChannel().close();
1035 } else if (e.getCause() instanceof RejectedExecutionException) {
1036 log.warn("Could not process message: queue full");
1037 } else {
1038 log.error("Error while processing message from switch "
1039 + getSwitchInfoString()
1040 + "state " + this.state, e.getCause());
1041 ctx.getChannel().close();
1042 }
1043 }
1044
1045 @Override
1046 public String toString() {
1047 return getSwitchInfoString();
1048 }
1049
1050 @Override
1051 public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
1052 throws Exception {
1053 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1054 OFMessage m = factory.buildEchoRequest().build();
1055 log.info("Sending Echo Request on idle channel: {}",
1056 e.getChannel().getPipeline().getLast().toString());
1057 e.getChannel().write(Collections.singletonList(m));
1058 // XXX S some problems here -- echo request has no transaction id, and
1059 // echo reply is not correlated to the echo request.
1060 }
1061
1062 @Override
1063 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
1064 throws Exception {
1065 if (e.getMessage() instanceof List) {
1066 @SuppressWarnings("unchecked")
1067 List<OFMessage> msglist = (List<OFMessage>) e.getMessage();
1068
1069
1070 for (OFMessage ofm : msglist) {
1071 // Do the actual packet processing
1072 state.processOFMessage(this, ofm);
1073 }
1074 } else {
1075 state.processOFMessage(this, (OFMessage) e.getMessage());
1076 }
1077 }
1078
1079
1080
1081 //*************************
1082 // Channel utility methods
1083 //*************************
1084
1085 /**
1086 * Is this a state in which the handshake has completed?
1087 * @return true if the handshake is complete
1088 */
1089 public boolean isHandshakeComplete() {
1090 return this.state.isHandshakeComplete();
1091 }
1092
1093 private void dispatchMessage(OFMessage m) {
1094 sw.handleMessage(m);
1095 }
1096
1097 /**
1098 * Return a string describing this switch based on the already available
1099 * information (DPID and/or remote socket).
1100 * @return display string
1101 */
1102 private String getSwitchInfoString() {
1103 if (sw != null) {
1104 return sw.toString();
1105 }
1106 String channelString;
1107 if (channel == null || channel.getRemoteAddress() == null) {
1108 channelString = "?";
1109 } else {
1110 channelString = channel.getRemoteAddress().toString();
1111 }
1112 String dpidString;
1113 if (featuresReply == null) {
1114 dpidString = "?";
1115 } else {
1116 dpidString = featuresReply.getDatapathId().toString();
1117 }
1118 return String.format("[%s DPID[%s]]", channelString, dpidString);
1119 }
1120
1121 /**
1122 * Update the channels state. Only called from the state machine.
1123 * TODO: enforce restricted state transitions
1124 * @param state
1125 */
1126 private void setState(ChannelState state) {
1127 this.state = state;
1128 }
1129
1130 /**
1131 * Send hello message to the switch using the handshake transactions ids.
1132 * @throws IOException
1133 */
1134 private void sendHandshakeHelloMessage() throws IOException {
1135 // The OF protocol requires us to start things off by sending the highest
1136 // version of the protocol supported.
1137
1138 // bitmap represents OF1.0 (ofp_version=0x01) and OF1.3 (ofp_version=0x04)
1139 // see Sec. 7.5.1 of the OF1.3.4 spec
1140 U32 bitmap = U32.ofRaw(0x00000012);
1141 OFHelloElem hem = factory13.buildHelloElemVersionbitmap()
1142 .setBitmaps(Collections.singletonList(bitmap))
1143 .build();
1144 OFMessage.Builder mb = factory13.buildHello()
1145 .setXid(this.handshakeTransactionIds--)
1146 .setElements(Collections.singletonList(hem));
1147 log.info("Sending OF_13 Hello to {}", channel.getRemoteAddress());
1148 channel.write(Collections.singletonList(mb.build()));
1149 }
1150
1151 /**
1152 * Send featuresRequest msg to the switch using the handshake transactions ids.
1153 * @throws IOException
1154 */
1155 private void sendHandshakeFeaturesRequestMessage() throws IOException {
1156 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1157 OFMessage m = factory.buildFeaturesRequest()
1158 .setXid(this.handshakeTransactionIds--)
1159 .build();
1160 channel.write(Collections.singletonList(m));
1161 }
1162
1163 /**
1164 * Send the configuration requests to tell the switch we want full
1165 * packets.
1166 * @throws IOException
1167 */
1168 private void sendHandshakeSetConfig() throws IOException {
1169 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1170 //log.debug("Sending CONFIG_REQUEST to {}", channel.getRemoteAddress());
1171 List<OFMessage> msglist = new ArrayList<OFMessage>(3);
1172
1173 // Ensure we receive the full packet via PacketIn
1174 // FIXME: We don't set the reassembly flags.
1175 OFSetConfig sc = factory
1176 .buildSetConfig()
1177 .setMissSendLen((short) 0xffff)
1178 .setXid(this.handshakeTransactionIds--)
1179 .build();
1180 msglist.add(sc);
1181
1182 // Barrier
1183 OFBarrierRequest br = factory
1184 .buildBarrierRequest()
1185 .setXid(this.handshakeTransactionIds--)
1186 .build();
1187 msglist.add(br);
1188
1189 // Verify (need barrier?)
1190 OFGetConfigRequest gcr = factory
1191 .buildGetConfigRequest()
1192 .setXid(this.handshakeTransactionIds--)
1193 .build();
1194 msglist.add(gcr);
1195 channel.write(msglist);
1196 }
1197
1198 /**
1199 * send a description state request.
1200 * @throws IOException
1201 */
1202 private void sendHandshakeDescriptionStatsRequest() throws IOException {
1203 // Get Description to set switch-specific flags
1204 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1205 OFDescStatsRequest dreq = factory
1206 .buildDescStatsRequest()
1207 .setXid(handshakeTransactionIds--)
1208 .build();
1209 channel.write(Collections.singletonList(dreq));
1210 }
1211
1212 private void sendHandshakeOFPortDescRequest() throws IOException {
1213 // Get port description for 1.3 switch
1214 OFPortDescStatsRequest preq = factory13
1215 .buildPortDescStatsRequest()
1216 .setXid(handshakeTransactionIds--)
1217 .build();
1218 channel.write(Collections.singletonList(preq));
1219 }
1220
1221 ChannelState getStateForTesting() {
1222 return state;
1223 }
1224
1225}