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