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