blob: 75c139d5f8e6dcaa8a3914a61ff9e9e4b23d7a1a [file] [log] [blame]
tom7ef8ff92014-09-17 13:08:06 -07001//CHECKSTYLE:OFF
tom9c94c5b2014-09-17 13:14:42 -07002package org.onlab.onos.openflow.controller.impl;
tom7ef8ff92014-09-17 13:08:06 -07003
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;
tom9c94c5b2014-09-17 13:14:42 -070020import org.onlab.onos.openflow.controller.driver.OpenFlowSwitchDriver;
21import org.onlab.onos.openflow.controller.driver.SwitchStateException;
tom7ef8ff92014-09-17 13:08:06 -070022import 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
alshabib339a3d92014-09-26 17:54:32 -0700524
tom7ef8ff92014-09-17 13:08:06 -0700525 h.sw.reassertRole();
526 } else if (m.getErrType() == OFErrorType.FLOW_MOD_FAILED &&
527 ((OFFlowModFailedErrorMsg) m).getCode() ==
528 OFFlowModFailedCode.ALL_TABLES_FULL) {
529 h.sw.setTableFull(true);
530 } else {
531 logError(h, m);
532 }
533 h.dispatchMessage(m);
534 }
535
536 @Override
537 void processOFStatisticsReply(OFChannelHandler h,
538 OFStatsReply m) {
539 h.dispatchMessage(m);
540 }
541
542 @Override
543 void processOFExperimenter(OFChannelHandler h, OFExperimenter m)
544 throws SwitchStateException {
545 h.sw.handleNiciraRole(m);
546 }
547
548 @Override
549 void processOFRoleReply(OFChannelHandler h, OFRoleReply m)
550 throws SwitchStateException {
551 h.sw.handleRole(m);
552 }
553
554 @Override
555 void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
556 throws SwitchStateException {
557 handlePortStatusMessage(h, m, true);
558 h.dispatchMessage(m);
559 }
560
561 @Override
562 void processOFPacketIn(OFChannelHandler h, OFPacketIn m) {
563 h.dispatchMessage(m);
564 }
565
566 @Override
567 void processOFFlowRemoved(OFChannelHandler h,
568 OFFlowRemoved m) {
569 h.dispatchMessage(m);
570 }
571
572 @Override
573 void processOFBarrierReply(OFChannelHandler h, OFBarrierReply m) {
574 h.dispatchMessage(m);
575 }
576
577 };
578
579 private final boolean handshakeComplete;
580 ChannelState(boolean handshakeComplete) {
581 this.handshakeComplete = handshakeComplete;
582 }
583
584 /**
585 * Is this a state in which the handshake has completed?
586 * @return true if the handshake is complete
587 */
588 public boolean isHandshakeComplete() {
589 return handshakeComplete;
590 }
591
592 /**
593 * Get a string specifying the switch connection, state, and
594 * message received. To be used as message for SwitchStateException
595 * or log messages
596 * @param h The channel handler (to get switch information_
597 * @param m The OFMessage that has just been received
598 * @param details A string giving more details about the exact nature
599 * of the problem.
600 * @return display string
601 */
602 // needs to be protected because enum members are actually subclasses
603 protected String getSwitchStateMessage(OFChannelHandler h,
604 OFMessage m,
605 String details) {
606 return String.format("Switch: [%s], State: [%s], received: [%s]"
607 + ", details: %s",
608 h.getSwitchInfoString(),
609 this.toString(),
610 m.getType().toString(),
611 details);
612 }
613
614 /**
615 * We have an OFMessage we didn't expect given the current state and
616 * we want to treat this as an error.
617 * We currently throw an exception that will terminate the connection
618 * However, we could be more forgiving
619 * @param h the channel handler that received the message
620 * @param m the message
621 * @throws SwitchStateException
622 * @throws SwitchStateExeption we always through the execption
623 */
624 // needs to be protected because enum members are acutally subclasses
625 protected void illegalMessageReceived(OFChannelHandler h, OFMessage m)
626 throws SwitchStateException {
627 String msg = getSwitchStateMessage(h, m,
628 "Switch should never send this message in the current state");
629 throw new SwitchStateException(msg);
630
631 }
632
633 /**
634 * We have an OFMessage we didn't expect given the current state and
635 * we want to ignore the message.
636 * @param h the channel handler the received the message
637 * @param m the message
638 */
639 protected void unhandledMessageReceived(OFChannelHandler h,
640 OFMessage m) {
641 if (log.isDebugEnabled()) {
642 String msg = getSwitchStateMessage(h, m,
643 "Ignoring unexpected message");
644 log.debug(msg);
645 }
646 }
647
648 /**
649 * Log an OpenFlow error message from a switch.
650 * @param h The switch that sent the error
651 * @param error The error message
652 */
653 protected void logError(OFChannelHandler h, OFErrorMsg error) {
654 log.error("{} from switch {} in state {}",
655 new Object[] {
656 error,
657 h.getSwitchInfoString(),
658 this.toString()});
659 }
660
661 /**
662 * Log an OpenFlow error message from a switch and disconnect the
663 * channel.
664 *
665 * @param h the IO channel for this switch.
666 * @param error The error message
667 */
668 protected void logErrorDisconnect(OFChannelHandler h, OFErrorMsg error) {
669 logError(h, error);
670 h.channel.disconnect();
671 }
672
673 /**
674 * log an error message for a duplicate dpid and disconnect this channel.
675 * @param h the IO channel for this switch.
676 */
677 protected void disconnectDuplicate(OFChannelHandler h) {
678 log.error("Duplicated dpid or incompleted cleanup - "
679 + "disconnecting channel {}", h.getSwitchInfoString());
680 h.duplicateDpidFound = Boolean.TRUE;
681 h.channel.disconnect();
682 }
683
684
685
686 /**
687 * Handles all pending port status messages before a switch is declared
688 * activated in MASTER or EQUAL role. Note that since this handling
689 * precedes the activation (and therefore notification to IOFSwitchListerners)
690 * the changes to ports will already be visible once the switch is
691 * activated. As a result, no notifications are sent out for these
692 * pending portStatus messages.
693 * @param h
694 * @throws SwitchStateException
695 */
696 protected void handlePendingPortStatusMessages(OFChannelHandler h) {
697 try {
698 handlePendingPortStatusMessages(h, 0);
699 } catch (SwitchStateException e) {
700 log.error(e.getMessage());
701 }
702 }
703
704 private void handlePendingPortStatusMessages(OFChannelHandler h, int index)
705 throws SwitchStateException {
706 if (h.sw == null) {
707 String msg = "State machine error: switch is null. Should never " +
708 "happen";
709 throw new SwitchStateException(msg);
710 }
711 ArrayList<OFPortStatus> temp = new ArrayList<OFPortStatus>();
712 for (OFPortStatus ps: h.pendingPortStatusMsg) {
713 temp.add(ps);
714 handlePortStatusMessage(h, ps, false);
715 }
716 temp.clear();
717 // expensive but ok - we don't expect too many port-status messages
718 // note that we cannot use clear(), because of the reasons below
719 h.pendingPortStatusMsg.removeAll(temp);
720 // the iterator above takes a snapshot of the list - so while we were
721 // dealing with the pending port-status messages, we could have received
722 // newer ones. Handle them recursively, but break the recursion after
723 // five steps to avoid an attack.
724 if (!h.pendingPortStatusMsg.isEmpty() && ++index < 5) {
725 handlePendingPortStatusMessages(h, index);
726 }
727 }
728
729 /**
730 * Handle a port status message.
731 *
732 * Handle a port status message by updating the port maps in the
733 * IOFSwitch instance and notifying Controller about the change so
734 * it can dispatch a switch update.
735 *
736 * @param h The OFChannelHhandler that received the message
737 * @param m The PortStatus message we received
738 * @param doNotify if true switch port changed events will be
739 * dispatched
740 * @throws SwitchStateException
741 *
742 */
743 protected void handlePortStatusMessage(OFChannelHandler h, OFPortStatus m,
744 boolean doNotify) throws SwitchStateException {
745 if (h.sw == null) {
746 String msg = getSwitchStateMessage(h, m,
747 "State machine error: switch is null. Should never " +
748 "happen");
749 throw new SwitchStateException(msg);
750 }
751
752 h.sw.handleMessage(m);
753 }
754
755
756 /**
757 * Process an OF message received on the channel and
758 * update state accordingly.
759 *
760 * The main "event" of the state machine. Process the received message,
761 * send follow up message if required and update state if required.
762 *
763 * Switches on the message type and calls more specific event handlers
764 * for each individual OF message type. If we receive a message that
765 * is supposed to be sent from a controller to a switch we throw
766 * a SwitchStateExeption.
767 *
768 * The more specific handlers can also throw SwitchStateExceptions
769 *
770 * @param h The OFChannelHandler that received the message
771 * @param m The message we received.
772 * @throws SwitchStateException
773 * @throws IOException
774 */
775 void processOFMessage(OFChannelHandler h, OFMessage m)
776 throws IOException, SwitchStateException {
777 switch(m.getType()) {
778 case HELLO:
779 processOFHello(h, (OFHello) m);
780 break;
781 case BARRIER_REPLY:
782 processOFBarrierReply(h, (OFBarrierReply) m);
783 break;
784 case ECHO_REPLY:
785 processOFEchoReply(h, (OFEchoReply) m);
786 break;
787 case ECHO_REQUEST:
788 processOFEchoRequest(h, (OFEchoRequest) m);
789 break;
790 case ERROR:
791 processOFError(h, (OFErrorMsg) m);
792 break;
793 case FEATURES_REPLY:
794 processOFFeaturesReply(h, (OFFeaturesReply) m);
795 break;
796 case FLOW_REMOVED:
797 processOFFlowRemoved(h, (OFFlowRemoved) m);
798 break;
799 case GET_CONFIG_REPLY:
800 processOFGetConfigReply(h, (OFGetConfigReply) m);
801 break;
802 case PACKET_IN:
803 processOFPacketIn(h, (OFPacketIn) m);
804 break;
805 case PORT_STATUS:
806 processOFPortStatus(h, (OFPortStatus) m);
807 break;
808 case QUEUE_GET_CONFIG_REPLY:
809 processOFQueueGetConfigReply(h, (OFQueueGetConfigReply) m);
810 break;
811 case STATS_REPLY: // multipart_reply in 1.3
812 processOFStatisticsReply(h, (OFStatsReply) m);
813 break;
814 case EXPERIMENTER:
815 processOFExperimenter(h, (OFExperimenter) m);
816 break;
817 case ROLE_REPLY:
818 processOFRoleReply(h, (OFRoleReply) m);
819 break;
820 case GET_ASYNC_REPLY:
821 processOFGetAsyncReply(h, (OFAsyncGetReply) m);
822 break;
823
824 // The following messages are sent to switches. The controller
825 // should never receive them
826 case SET_CONFIG:
827 case GET_CONFIG_REQUEST:
828 case PACKET_OUT:
829 case PORT_MOD:
830 case QUEUE_GET_CONFIG_REQUEST:
831 case BARRIER_REQUEST:
832 case STATS_REQUEST: // multipart request in 1.3
833 case FEATURES_REQUEST:
834 case FLOW_MOD:
835 case GROUP_MOD:
836 case TABLE_MOD:
837 case GET_ASYNC_REQUEST:
838 case SET_ASYNC:
839 case METER_MOD:
840 default:
841 illegalMessageReceived(h, m);
842 break;
843 }
844 }
845
846 /*-----------------------------------------------------------------
847 * Default implementation for message handlers in any state.
848 *
849 * Individual states must override these if they want a behavior
850 * that differs from the default.
851 *
852 * In general, these handlers simply ignore the message and do
853 * nothing.
854 *
855 * There are some exceptions though, since some messages really
856 * are handled the same way in every state (e.g., ECHO_REQUST) or
857 * that are only valid in a single state (e.g., HELLO, GET_CONFIG_REPLY
858 -----------------------------------------------------------------*/
859
860 void processOFHello(OFChannelHandler h, OFHello m)
861 throws IOException, SwitchStateException {
862 // we only expect hello in the WAIT_HELLO state
863 illegalMessageReceived(h, m);
864 }
865
866 void processOFBarrierReply(OFChannelHandler h, OFBarrierReply m)
867 throws IOException {
868 // Silently ignore.
869 }
870
871 void processOFEchoRequest(OFChannelHandler h, OFEchoRequest m)
872 throws IOException {
873 if (h.ofVersion == null) {
874 log.error("No OF version set for {}. Not sending Echo REPLY",
875 h.channel.getRemoteAddress());
876 return;
877 }
878 OFFactory factory = (h.ofVersion == OFVersion.OF_13) ?
879 h.controller.getOFMessageFactory13() : h.controller.getOFMessageFactory10();
880 OFEchoReply reply = factory
881 .buildEchoReply()
882 .setXid(m.getXid())
883 .setData(m.getData())
884 .build();
885 h.channel.write(Collections.singletonList(reply));
886 }
887
888 void processOFEchoReply(OFChannelHandler h, OFEchoReply m)
889 throws IOException {
890 // Do nothing with EchoReplies !!
891 }
892
893 // no default implementation for OFError
894 // every state must override it
895 abstract void processOFError(OFChannelHandler h, OFErrorMsg m)
896 throws IOException, SwitchStateException;
897
898
899 void processOFFeaturesReply(OFChannelHandler h, OFFeaturesReply m)
900 throws IOException, SwitchStateException {
901 unhandledMessageReceived(h, m);
902 }
903
904 void processOFFlowRemoved(OFChannelHandler h, OFFlowRemoved m)
905 throws IOException {
906 unhandledMessageReceived(h, m);
907 }
908
909 void processOFGetConfigReply(OFChannelHandler h, OFGetConfigReply m)
910 throws IOException, SwitchStateException {
911 // we only expect config replies in the WAIT_CONFIG_REPLY state
912 illegalMessageReceived(h, m);
913 }
914
915 void processOFPacketIn(OFChannelHandler h, OFPacketIn m)
916 throws IOException {
917 unhandledMessageReceived(h, m);
918 }
919
920 // no default implementation. Every state needs to handle it.
921 abstract void processOFPortStatus(OFChannelHandler h, OFPortStatus m)
922 throws IOException, SwitchStateException;
923
924 void processOFQueueGetConfigReply(OFChannelHandler h,
925 OFQueueGetConfigReply m)
926 throws IOException {
927 unhandledMessageReceived(h, m);
928 }
929
930 void processOFStatisticsReply(OFChannelHandler h, OFStatsReply m)
931 throws IOException, SwitchStateException {
932 unhandledMessageReceived(h, m);
933 }
934
935 void processOFExperimenter(OFChannelHandler h, OFExperimenter m)
936 throws IOException, SwitchStateException {
937 // TODO: it might make sense to parse the vendor message here
938 // into the known vendor messages we support and then call more
939 // specific event handlers
940 unhandledMessageReceived(h, m);
941 }
942
943 void processOFRoleReply(OFChannelHandler h, OFRoleReply m)
944 throws SwitchStateException, IOException {
945 unhandledMessageReceived(h, m);
946 }
947
948 void processOFGetAsyncReply(OFChannelHandler h,
949 OFAsyncGetReply m) {
950 unhandledMessageReceived(h, m);
951 }
952
953 }
954
955
956
957 //*************************
958 // Channel handler methods
959 //*************************
960
961 @Override
962 public void channelConnected(ChannelHandlerContext ctx,
963 ChannelStateEvent e) throws Exception {
964 channel = e.getChannel();
965 log.info("New switch connection from {}",
966 channel.getRemoteAddress());
967 sendHandshakeHelloMessage();
968 setState(ChannelState.WAIT_HELLO);
969 }
970
971 @Override
972 public void channelDisconnected(ChannelHandlerContext ctx,
973 ChannelStateEvent e) throws Exception {
974 log.info("Switch disconnected callback for sw:{}. Cleaning up ...",
975 getSwitchInfoString());
976 if (thisdpid != 0) {
977 if (!duplicateDpidFound) {
978 // if the disconnected switch (on this ChannelHandler)
979 // was not one with a duplicate-dpid, it is safe to remove all
980 // state for it at the controller. Notice that if the disconnected
981 // switch was a duplicate-dpid, calling the method below would clear
982 // all state for the original switch (with the same dpid),
983 // which we obviously don't want.
984 sw.removeConnectedSwitch();
985 } else {
986 // A duplicate was disconnected on this ChannelHandler,
987 // this is the same switch reconnecting, but the original state was
988 // not cleaned up - XXX check liveness of original ChannelHandler
989 duplicateDpidFound = Boolean.FALSE;
990 }
991 } else {
992 log.warn("no dpid in channelHandler registered for "
993 + "disconnected switch {}", getSwitchInfoString());
994 }
995 }
996
997 @Override
998 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
999 throws Exception {
1000 if (e.getCause() instanceof ReadTimeoutException) {
1001 // switch timeout
1002 log.error("Disconnecting switch {} due to read timeout",
1003 getSwitchInfoString());
1004 ctx.getChannel().close();
1005 } else if (e.getCause() instanceof HandshakeTimeoutException) {
1006 log.error("Disconnecting switch {}: failed to complete handshake",
1007 getSwitchInfoString());
1008 ctx.getChannel().close();
1009 } else if (e.getCause() instanceof ClosedChannelException) {
1010 log.debug("Channel for sw {} already closed", getSwitchInfoString());
1011 } else if (e.getCause() instanceof IOException) {
1012 log.error("Disconnecting switch {} due to IO Error: {}",
1013 getSwitchInfoString(), e.getCause().getMessage());
1014 if (log.isDebugEnabled()) {
1015 // still print stack trace if debug is enabled
1016 log.debug("StackTrace for previous Exception: ", e.getCause());
1017 }
1018 ctx.getChannel().close();
1019 } else if (e.getCause() instanceof SwitchStateException) {
1020 log.error("Disconnecting switch {} due to switch state error: {}",
1021 getSwitchInfoString(), e.getCause().getMessage());
1022 if (log.isDebugEnabled()) {
1023 // still print stack trace if debug is enabled
1024 log.debug("StackTrace for previous Exception: ", e.getCause());
1025 }
1026 ctx.getChannel().close();
1027 } else if (e.getCause() instanceof OFParseError) {
1028 log.error("Disconnecting switch "
1029 + getSwitchInfoString() +
1030 " due to message parse failure",
1031 e.getCause());
1032 ctx.getChannel().close();
1033 } else if (e.getCause() instanceof RejectedExecutionException) {
1034 log.warn("Could not process message: queue full");
1035 } else {
1036 log.error("Error while processing message from switch "
1037 + getSwitchInfoString()
1038 + "state " + this.state, e.getCause());
1039 ctx.getChannel().close();
1040 }
1041 }
1042
1043 @Override
1044 public String toString() {
1045 return getSwitchInfoString();
1046 }
1047
1048 @Override
1049 public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
1050 throws Exception {
1051 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1052 OFMessage m = factory.buildEchoRequest().build();
1053 log.info("Sending Echo Request on idle channel: {}",
1054 e.getChannel().getPipeline().getLast().toString());
1055 e.getChannel().write(Collections.singletonList(m));
1056 // XXX S some problems here -- echo request has no transaction id, and
1057 // echo reply is not correlated to the echo request.
1058 }
1059
1060 @Override
1061 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
1062 throws Exception {
1063 if (e.getMessage() instanceof List) {
1064 @SuppressWarnings("unchecked")
1065 List<OFMessage> msglist = (List<OFMessage>) e.getMessage();
1066
1067
1068 for (OFMessage ofm : msglist) {
1069 // Do the actual packet processing
1070 state.processOFMessage(this, ofm);
1071 }
1072 } else {
1073 state.processOFMessage(this, (OFMessage) e.getMessage());
1074 }
1075 }
1076
1077
1078
1079 //*************************
1080 // Channel utility methods
1081 //*************************
1082
1083 /**
1084 * Is this a state in which the handshake has completed?
1085 * @return true if the handshake is complete
1086 */
1087 public boolean isHandshakeComplete() {
1088 return this.state.isHandshakeComplete();
1089 }
1090
1091 private void dispatchMessage(OFMessage m) {
1092 sw.handleMessage(m);
1093 }
1094
1095 /**
1096 * Return a string describing this switch based on the already available
1097 * information (DPID and/or remote socket).
1098 * @return display string
1099 */
1100 private String getSwitchInfoString() {
1101 if (sw != null) {
1102 return sw.toString();
1103 }
1104 String channelString;
1105 if (channel == null || channel.getRemoteAddress() == null) {
1106 channelString = "?";
1107 } else {
1108 channelString = channel.getRemoteAddress().toString();
1109 }
1110 String dpidString;
1111 if (featuresReply == null) {
1112 dpidString = "?";
1113 } else {
1114 dpidString = featuresReply.getDatapathId().toString();
1115 }
1116 return String.format("[%s DPID[%s]]", channelString, dpidString);
1117 }
1118
1119 /**
1120 * Update the channels state. Only called from the state machine.
1121 * TODO: enforce restricted state transitions
1122 * @param state
1123 */
1124 private void setState(ChannelState state) {
1125 this.state = state;
1126 }
1127
1128 /**
1129 * Send hello message to the switch using the handshake transactions ids.
1130 * @throws IOException
1131 */
1132 private void sendHandshakeHelloMessage() throws IOException {
1133 // The OF protocol requires us to start things off by sending the highest
1134 // version of the protocol supported.
1135
1136 // bitmap represents OF1.0 (ofp_version=0x01) and OF1.3 (ofp_version=0x04)
1137 // see Sec. 7.5.1 of the OF1.3.4 spec
1138 U32 bitmap = U32.ofRaw(0x00000012);
1139 OFHelloElem hem = factory13.buildHelloElemVersionbitmap()
1140 .setBitmaps(Collections.singletonList(bitmap))
1141 .build();
1142 OFMessage.Builder mb = factory13.buildHello()
1143 .setXid(this.handshakeTransactionIds--)
1144 .setElements(Collections.singletonList(hem));
1145 log.info("Sending OF_13 Hello to {}", channel.getRemoteAddress());
1146 channel.write(Collections.singletonList(mb.build()));
1147 }
1148
1149 /**
1150 * Send featuresRequest msg to the switch using the handshake transactions ids.
1151 * @throws IOException
1152 */
1153 private void sendHandshakeFeaturesRequestMessage() throws IOException {
1154 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1155 OFMessage m = factory.buildFeaturesRequest()
1156 .setXid(this.handshakeTransactionIds--)
1157 .build();
1158 channel.write(Collections.singletonList(m));
1159 }
1160
1161 /**
1162 * Send the configuration requests to tell the switch we want full
1163 * packets.
1164 * @throws IOException
1165 */
1166 private void sendHandshakeSetConfig() throws IOException {
1167 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1168 //log.debug("Sending CONFIG_REQUEST to {}", channel.getRemoteAddress());
1169 List<OFMessage> msglist = new ArrayList<OFMessage>(3);
1170
1171 // Ensure we receive the full packet via PacketIn
1172 // FIXME: We don't set the reassembly flags.
1173 OFSetConfig sc = factory
1174 .buildSetConfig()
1175 .setMissSendLen((short) 0xffff)
1176 .setXid(this.handshakeTransactionIds--)
1177 .build();
1178 msglist.add(sc);
1179
1180 // Barrier
1181 OFBarrierRequest br = factory
1182 .buildBarrierRequest()
1183 .setXid(this.handshakeTransactionIds--)
1184 .build();
1185 msglist.add(br);
1186
1187 // Verify (need barrier?)
1188 OFGetConfigRequest gcr = factory
1189 .buildGetConfigRequest()
1190 .setXid(this.handshakeTransactionIds--)
1191 .build();
1192 msglist.add(gcr);
1193 channel.write(msglist);
1194 }
1195
1196 /**
1197 * send a description state request.
1198 * @throws IOException
1199 */
1200 private void sendHandshakeDescriptionStatsRequest() throws IOException {
1201 // Get Description to set switch-specific flags
1202 OFFactory factory = (ofVersion == OFVersion.OF_13) ? factory13 : factory10;
1203 OFDescStatsRequest dreq = factory
1204 .buildDescStatsRequest()
1205 .setXid(handshakeTransactionIds--)
1206 .build();
1207 channel.write(Collections.singletonList(dreq));
1208 }
1209
1210 private void sendHandshakeOFPortDescRequest() throws IOException {
1211 // Get port description for 1.3 switch
1212 OFPortDescStatsRequest preq = factory13
1213 .buildPortDescStatsRequest()
1214 .setXid(handshakeTransactionIds--)
1215 .build();
1216 channel.write(Collections.singletonList(preq));
1217 }
1218
1219 ChannelState getStateForTesting() {
1220 return state;
1221 }
1222
1223}