blob: 3f74ff1e0e01c9f1d14924ed02232301f11f702c [file] [log] [blame]
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -08001package net.floodlightcontroller.flowcache;
2
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -08003import java.io.IOException;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -08004import java.util.ArrayList;
5import java.util.Collection;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -08006import java.util.EnumSet;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -08007import java.util.HashMap;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -08008import java.util.List;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -08009import java.util.Map;
Pavlin Radoslavov01391c92013-03-14 17:13:21 -070010import java.util.TreeMap;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080011import java.util.concurrent.Executors;
12import java.util.concurrent.ScheduledExecutorService;
13import java.util.concurrent.ScheduledFuture;
14import java.util.concurrent.TimeUnit;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080015
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080016import net.floodlightcontroller.core.IFloodlightProviderService;
17import net.floodlightcontroller.core.INetMapStorage;
18import net.floodlightcontroller.core.INetMapTopologyObjects.IFlowEntry;
19import net.floodlightcontroller.core.INetMapTopologyObjects.IFlowPath;
20import net.floodlightcontroller.core.IOFSwitch;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080021import net.floodlightcontroller.core.module.FloodlightModuleContext;
22import net.floodlightcontroller.core.module.FloodlightModuleException;
23import net.floodlightcontroller.core.module.IFloodlightModule;
24import net.floodlightcontroller.core.module.IFloodlightService;
25import net.floodlightcontroller.flowcache.IFlowService;
26import net.floodlightcontroller.flowcache.web.FlowWebRoutable;
27import net.floodlightcontroller.restserver.IRestApiService;
28import net.floodlightcontroller.util.CallerId;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080029import net.floodlightcontroller.util.DataPath;
30import net.floodlightcontroller.util.Dpid;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080031import net.floodlightcontroller.util.DataPathEndpoints;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080032import net.floodlightcontroller.util.FlowEntry;
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -070033import net.floodlightcontroller.util.FlowEntryAction;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080034import net.floodlightcontroller.util.FlowEntryId;
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -070035import net.floodlightcontroller.util.FlowEntryMatch;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080036import net.floodlightcontroller.util.FlowEntrySwitchState;
37import net.floodlightcontroller.util.FlowEntryUserState;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080038import net.floodlightcontroller.util.FlowId;
39import net.floodlightcontroller.util.FlowPath;
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -070040import net.floodlightcontroller.util.IPv4Net;
41import net.floodlightcontroller.util.MACAddress;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080042import net.floodlightcontroller.util.OFMessageDamper;
43import net.floodlightcontroller.util.Port;
44import net.onrc.onos.util.GraphDBConnection;
45import net.onrc.onos.util.GraphDBConnection.Transaction;
46
47import org.openflow.protocol.OFFlowMod;
48import org.openflow.protocol.OFMatch;
49import org.openflow.protocol.OFPacketOut;
Pavlin Radoslavov78c4e492013-03-12 17:17:48 -070050import org.openflow.protocol.OFPort;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080051import org.openflow.protocol.OFType;
52import org.openflow.protocol.action.OFAction;
53import org.openflow.protocol.action.OFActionOutput;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080054
55import org.slf4j.Logger;
56import org.slf4j.LoggerFactory;
57
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080058public class FlowManager implements IFloodlightModule, IFlowService, INetMapStorage {
59
60 public GraphDBConnection conn;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080061
62 protected IRestApiService restApi;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080063 protected IFloodlightProviderService floodlightProvider;
64
65 protected OFMessageDamper messageDamper;
66
Pavlin Radoslavov78c4e492013-03-12 17:17:48 -070067 //
68 // TODO: Values copied from elsewhere (class LearningSwitch).
69 // The local copy should go away!
70 //
71 protected static final int OFMESSAGE_DAMPER_CAPACITY = 50000; // TODO: find sweet spot
72 protected static final int OFMESSAGE_DAMPER_TIMEOUT = 250; // ms
73 public static final short FLOWMOD_DEFAULT_IDLE_TIMEOUT = 0; // infinity
74 public static final short FLOWMOD_DEFAULT_HARD_TIMEOUT = 0; // infinite
75 public static final short PRIORITY_DEFAULT = 100;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080076
Pavlin Radoslavov01391c92013-03-14 17:13:21 -070077 private static long nextFlowEntryId = 1;
78
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -080079 /** The logger. */
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -080080 private static Logger log = LoggerFactory.getLogger(FlowManager.class);
81
82 // The periodic task(s)
83 private final ScheduledExecutorService scheduler =
84 Executors.newScheduledThreadPool(1);
85 final Runnable reader = new Runnable() {
86 public void run() {
87 // log.debug("Reading Flow Entries from the Network Map...");
88 if (floodlightProvider == null) {
89 log.debug("FloodlightProvider service not found!");
90 return;
91 }
92
93 Map<Long, IOFSwitch> mySwitches = floodlightProvider.getSwitches();
94
Pavlin Radoslavov01391c92013-03-14 17:13:21 -070095 Map<Long, IFlowEntry> myFlowEntries = new TreeMap<Long, IFlowEntry>();
96
97 //
98 // Fetch all Flow Entries and select only my Flow Entries
99 //
100 Iterable<IFlowEntry> allFlowEntries = conn.utils().getAllFlowEntries(conn);
101 for (IFlowEntry flowEntryObj : allFlowEntries) {
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800102 FlowEntryId flowEntryId =
103 new FlowEntryId(flowEntryObj.getFlowEntryId());
104 String userState = flowEntryObj.getUserState();
105 String switchState = flowEntryObj.getSwitchState();
106
107 log.debug("Found Flow Entry {}: ", flowEntryId.toString());
108 log.debug("User State {}:", userState);
109 log.debug("Switch State {}:", switchState);
110
111 if (! switchState.equals("FE_SWITCH_NOT_UPDATED")) {
112 // Ignore the entry: nothing to do
113 continue;
114 }
115
116 Dpid dpid = new Dpid(flowEntryObj.getSwitchDpid());
117 IOFSwitch mySwitch = mySwitches.get(dpid.value());
118 if (mySwitch == null) {
119 log.debug("Flow Entry ignored: not my switch");
120 continue;
121 }
Pavlin Radoslavov01391c92013-03-14 17:13:21 -0700122 myFlowEntries.put(flowEntryId.value(), flowEntryObj);
123 }
124
125 //
126 // Process my Flow Entries
127 //
128 for (Map.Entry<Long, IFlowEntry> entry : myFlowEntries.entrySet()) {
129 IFlowEntry flowEntryObj = entry.getValue();
130
131 //
132 // TODO: Eliminate the re-fetching of flowEntryId,
133 // userState, switchState, and dpid from the flowEntryObj.
134 //
135 FlowEntryId flowEntryId =
136 new FlowEntryId(flowEntryObj.getFlowEntryId());
137 Dpid dpid = new Dpid(flowEntryObj.getSwitchDpid());
138 String userState = flowEntryObj.getUserState();
139 String switchState = flowEntryObj.getSwitchState();
140 IOFSwitch mySwitch = mySwitches.get(dpid.value());
141 if (mySwitch == null) {
142 log.debug("Flow Entry ignored: not my switch");
143 continue;
144 }
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800145
146 //
147 // Create the Open Flow Flow Modification Entry to push
148 //
149 OFFlowMod fm =
150 (OFFlowMod) floodlightProvider.getOFMessageFactory()
151 .getMessage(OFType.FLOW_MOD);
152 long cookie = flowEntryId.value();
153
154 short flowModCommand = OFFlowMod.OFPFC_ADD;
155 if (userState.equals("FE_USER_ADD")) {
156 flowModCommand = OFFlowMod.OFPFC_ADD;
157 } else if (userState.equals("FE_USER_MODIFY")) {
158 flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT;
159 } else if (userState.equals("FE_USER_DELETE")) {
160 flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT;
161 } else {
162 // Unknown user state. Ignore the entry
163 continue;
164 }
165
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700166 //
167 // Fetch the match conditions
168 //
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800169 OFMatch match = new OFMatch();
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700170 match.setWildcards(OFMatch.OFPFW_ALL);
171 Short matchInPort = flowEntryObj.getMatchInPort();
172 if (matchInPort != null) {
173 match.setInputPort(matchInPort);
174 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT);
175 }
176 Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
177 if (matchEthernetFrameType != null) {
178 match.setDataLayerType(matchEthernetFrameType);
179 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE);
180 }
181 String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
182 if (matchSrcIPv4Net != null) {
183 match.setFromCIDR(matchSrcIPv4Net, OFMatch.STR_NW_SRC);
184 }
185 String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
186 if (matchDstIPv4Net != null) {
187 match.setFromCIDR(matchDstIPv4Net, OFMatch.STR_NW_DST);
188 }
189 String matchSrcMac = flowEntryObj.getMatchSrcMac();
190 if (matchSrcMac != null) {
191 match.setDataLayerSource(matchSrcMac);
192 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC);
193 }
194 String matchDstMac = flowEntryObj.getMatchDstMac();
195 if (matchDstMac != null) {
196 match.setDataLayerDestination(matchDstMac);
197 match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST);
198 }
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700199
200 //
201 // Fetch the actions
202 //
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800203 List<OFAction> actions = new ArrayList<OFAction>();
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700204 Short actionOutputPort = flowEntryObj.getActionOutput();
205 if (actionOutputPort != null) {
206 OFActionOutput action = new OFActionOutput();
207 // XXX: The max length is hard-coded for now
208 action.setMaxLength((short)0xffff);
209 action.setPort(actionOutputPort);
210 actions.add(action);
211 }
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800212
213 fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
214 .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
Pavlin Radoslavov78c4e492013-03-12 17:17:48 -0700215 .setPriority(PRIORITY_DEFAULT)
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800216 .setBufferId(OFPacketOut.BUFFER_ID_NONE)
217 .setCookie(cookie)
218 .setCommand(flowModCommand)
219 .setMatch(match)
220 .setActions(actions)
221 .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
Pavlin Radoslavov78c4e492013-03-12 17:17:48 -0700222 fm.setOutPort(OFPort.OFPP_NONE.getValue());
223 if ((flowModCommand == OFFlowMod.OFPFC_DELETE) ||
224 (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) {
225 if (actionOutputPort != null)
226 fm.setOutPort(actionOutputPort);
227 }
228
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800229 //
230 // TODO: Set the following flag
231 // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
232 // See method ForwardingBase::pushRoute()
233 //
234 try {
235 messageDamper.write(mySwitch, fm, null);
236 mySwitch.flush();
237 flowEntryObj.setSwitchState("FE_SWITCH_UPDATED");
238 if (userState.equals("FE_USER_DELETE")) {
239 // Delete the entry
240 IFlowPath flowObj = null;
241 flowObj = conn.utils().getFlowPathByFlowEntry(conn,
242 flowEntryObj);
243 if (flowObj != null)
244 log.debug("Found FlowPath to be deleted");
245 else
246 log.debug("Did not find FlowPath to be deleted");
247 flowObj.removeFlowEntry(flowEntryObj);
248 conn.utils().removeFlowEntry(conn, flowEntryObj);
249
250 // Test whether the last flow entry
251 Iterable<IFlowEntry> tmpflowEntries =
252 flowObj.getFlowEntries();
253 boolean found = false;
254 for (IFlowEntry tmpflowEntryObj : tmpflowEntries) {
255 found = true;
256 break;
257 }
258 if (! found) {
259 // Remove the Flow Path as well
260 conn.utils().removeFlowPath(conn, flowObj);
261 }
262 }
263 } catch (IOException e) {
264 log.error("Failure writing flow mod from network map", e);
265 }
266 }
267 conn.endTx(Transaction.COMMIT);
268 }
269 };
270 final ScheduledFuture<?> readerHandle =
271 scheduler.scheduleAtFixedRate(reader, 3, 3, TimeUnit.SECONDS);
272
273 @Override
274 public void init(String conf) {
275 conn = GraphDBConnection.getInstance(conf);
276 }
277
278 public void finalize() {
279 close();
280 }
281
282 @Override
283 public void close() {
284 conn.close();
285 }
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800286
287 @Override
288 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
289 Collection<Class<? extends IFloodlightService>> l =
290 new ArrayList<Class<? extends IFloodlightService>>();
291 l.add(IFlowService.class);
292 return l;
293 }
294
295 @Override
296 public Map<Class<? extends IFloodlightService>, IFloodlightService>
297 getServiceImpls() {
298 Map<Class<? extends IFloodlightService>,
299 IFloodlightService> m =
300 new HashMap<Class<? extends IFloodlightService>,
301 IFloodlightService>();
302 m.put(IFlowService.class, this);
303 return m;
304 }
305
306 @Override
307 public Collection<Class<? extends IFloodlightService>>
308 getModuleDependencies() {
309 Collection<Class<? extends IFloodlightService>> l =
310 new ArrayList<Class<? extends IFloodlightService>>();
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800311 l.add(IFloodlightProviderService.class);
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800312 l.add(IRestApiService.class);
313 return l;
314 }
315
316 @Override
317 public void init(FloodlightModuleContext context)
318 throws FloodlightModuleException {
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800319 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800320 restApi = context.getServiceImpl(IRestApiService.class);
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800321 messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY,
322 EnumSet.of(OFType.FLOW_MOD),
323 OFMESSAGE_DAMPER_TIMEOUT);
324 // TODO: An ugly hack!
325 String conf = "/tmp/cassandra.titan";
326 this.init(conf);
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800327 }
328
329 @Override
330 public void startUp(FloodlightModuleContext context) {
331 restApi.addRestletRoutable(new FlowWebRoutable());
332 }
333
334 /**
335 * Add a flow.
336 *
337 * Internally, ONOS will automatically register the installer for
338 * receiving Flow Path Notifications for that path.
339 *
340 * @param flowPath the Flow Path to install.
341 * @param flowId the return-by-reference Flow ID as assigned internally.
342 * @return true on success, otherwise false.
343 */
344 @Override
345 public boolean addFlow(FlowPath flowPath, FlowId flowId) {
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800346
347 //
348 // Assign the FlowEntry IDs
Pavlin Radoslavov01391c92013-03-14 17:13:21 -0700349 // Right now every new flow entry gets a new flow entry ID
350 // TODO: This needs to be redesigned!
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800351 //
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800352 for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) {
Pavlin Radoslavov01391c92013-03-14 17:13:21 -0700353 long id = nextFlowEntryId++;
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800354 flowEntry.setFlowEntryId(new FlowEntryId(id));
355 }
356
357 IFlowPath flowObj = null;
358 try {
359 if ((flowObj = conn.utils().searchFlowPath(conn, flowPath.flowId()))
360 != null) {
361 log.debug("Adding FlowPath with FlowId {}: found existing FlowPath",
362 flowPath.flowId().toString());
363 } else {
364 flowObj = conn.utils().newFlowPath(conn);
365 log.debug("Adding FlowPath with FlowId {}: creating new FlowPath",
366 flowPath.flowId().toString());
367 }
368 } catch (Exception e) {
369 // TODO: handle exceptions
370 conn.endTx(Transaction.ROLLBACK);
371 log.error(":addFlow FlowId:{} failed",
372 flowPath.flowId().toString());
373 }
374 if (flowObj == null)
375 return false;
376
377 //
378 // Set the Flow key:
379 // - flowId
380 //
381 flowObj.setFlowId(flowPath.flowId().toString());
382 flowObj.setType("flow");
383
384 //
385 // Set the Flow attributes:
386 // - flowPath.installerId()
387 // - flowPath.dataPath().srcPort()
388 // - flowPath.dataPath().dstPort()
389 //
390 flowObj.setInstallerId(flowPath.installerId().toString());
391 flowObj.setSrcSwitch(flowPath.dataPath().srcPort().dpid().toString());
392 flowObj.setSrcPort(flowPath.dataPath().srcPort().port().value());
393 flowObj.setDstSwitch(flowPath.dataPath().dstPort().dpid().toString());
394 flowObj.setDstPort(flowPath.dataPath().dstPort().port().value());
395
396 // Flow edges:
397 // HeadFE
398
399
400 //
401 // Flow Entries:
402 // flowPath.dataPath().flowEntries()
403 //
404 for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) {
405 IFlowEntry flowEntryObj = null;
406 boolean found = false;
407 try {
408 if ((flowEntryObj = conn.utils().searchFlowEntry(conn, flowEntry.flowEntryId())) != null) {
409 log.debug("Adding FlowEntry with FlowEntryId {}: found existing FlowEntry",
410 flowEntry.flowEntryId().toString());
411 found = true;
412 } else {
413 flowEntryObj = conn.utils().newFlowEntry(conn);
414 log.debug("Adding FlowEntry with FlowEntryId {}: creating new FlowEntry",
415 flowEntry.flowEntryId().toString());
416 }
417 } catch (Exception e) {
418 // TODO: handle exceptions
419 conn.endTx(Transaction.ROLLBACK);
420 log.error(":addFlow FlowEntryId:{} failed",
421 flowEntry.flowEntryId().toString());
422 }
423 if (flowEntryObj == null)
424 return false;
425
426 //
427 // Set the Flow Entry key:
428 // - flowEntry.flowEntryId()
429 //
430 flowEntryObj.setFlowEntryId(flowEntry.flowEntryId().toString());
431 flowEntryObj.setType("flow_entry");
432
433 //
434 // Set the Flow Entry attributes:
435 // - flowEntry.flowEntryMatch()
436 // - flowEntry.flowEntryActions()
437 // - flowEntry.dpid()
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800438 // - flowEntry.flowEntryUserState()
439 // - flowEntry.flowEntrySwitchState()
440 // - flowEntry.flowEntryErrorState()
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700441 // - flowEntry.matchInPort()
442 // - flowEntry.matchEthernetFrameType()
443 // - flowEntry.matchSrcIPv4Net()
444 // - flowEntry.matchDstIPv4Net()
445 // - flowEntry.matchSrcMac()
446 // - flowEntry.matchDstMac()
447 // - flowEntry.actionOutput()
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800448 //
449 flowEntryObj.setSwitchDpid(flowEntry.dpid().toString());
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700450 if (flowEntry.flowEntryMatch().matchInPort())
451 flowEntryObj.setMatchInPort(flowEntry.flowEntryMatch().inPort().value());
452 if (flowEntry.flowEntryMatch().matchEthernetFrameType())
453 flowEntryObj.setMatchEthernetFrameType(flowEntry.flowEntryMatch().ethernetFrameType());
454 if (flowEntry.flowEntryMatch().matchSrcIPv4Net())
455 flowEntryObj.setMatchSrcIPv4Net(flowEntry.flowEntryMatch().srcIPv4Net().toString());
456 if (flowEntry.flowEntryMatch().matchDstIPv4Net())
457 flowEntryObj.setMatchDstIPv4Net(flowEntry.flowEntryMatch().dstIPv4Net().toString());
458 if (flowEntry.flowEntryMatch().matchSrcMac())
459 flowEntryObj.setMatchSrcMac(flowEntry.flowEntryMatch().srcMac().toString());
460 if (flowEntry.flowEntryMatch().matchDstMac())
461 flowEntryObj.setMatchDstMac(flowEntry.flowEntryMatch().dstMac().toString());
462
463 for (FlowEntryAction fa : flowEntry.flowEntryActions()) {
464 if (fa.actionOutput() != null)
465 flowEntryObj.setActionOutput(fa.actionOutput().port().value());
466 }
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800467 // TODO: Hacks with hard-coded state names!
468 if (found)
469 flowEntryObj.setUserState("FE_USER_MODIFY");
470 else
471 flowEntryObj.setUserState("FE_USER_ADD");
472 flowEntryObj.setSwitchState("FE_SWITCH_NOT_UPDATED");
473 //
Pavlin Radoslavovede97582013-03-08 18:57:28 -0800474 // TODO: Take care of the FlowEntryMatch, FlowEntryAction set,
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800475 // and FlowEntryErrorState.
476 //
477
478 // Flow Entries edges:
479 // Flow
480 // NextFE
481 // InPort
482 // OutPort
483 // Switch
484 if (! found)
485 flowObj.addFlowEntry(flowEntryObj);
486 }
487 conn.endTx(Transaction.COMMIT);
488
489 //
490 // TODO: We need a proper Flow ID allocation mechanism.
491 //
492 flowId.setValue(flowPath.flowId().value());
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800493 return true;
494 }
495
496 /**
497 * Delete a previously added flow.
498 *
499 * @param flowId the Flow ID of the flow to delete.
500 * @return true on success, otherwise false.
501 */
502 @Override
503 public boolean deleteFlow(FlowId flowId) {
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800504 IFlowPath flowObj = null;
505 //
506 // We just mark the entries for deletion,
507 // and let the switches remove each individual entry after
508 // it has been removed from the switches.
509 //
510 try {
511 if ((flowObj = conn.utils().searchFlowPath(conn, flowId))
512 != null) {
513 log.debug("Deleting FlowPath with FlowId {}: found existing FlowPath",
514 flowId.toString());
515 } else {
516 log.debug("Deleting FlowPath with FlowId {}: FlowPath not found",
517 flowId.toString());
518 }
519 } catch (Exception e) {
520 // TODO: handle exceptions
521 conn.endTx(Transaction.ROLLBACK);
522 log.error(":deleteFlow FlowId:{} failed", flowId.toString());
523 }
524 if (flowObj == null)
525 return true; // OK: No such flow
526
527 //
528 // Find and mark for deletion all Flow Entries
529 //
530 Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
531 boolean empty = true; // TODO: an ugly hack
532 for (IFlowEntry flowEntryObj : flowEntries) {
533 empty = false;
534 // flowObj.removeFlowEntry(flowEntryObj);
535 // conn.utils().removeFlowEntry(conn, flowEntryObj);
536 flowEntryObj.setUserState("FE_USER_DELETE");
537 flowEntryObj.setSwitchState("FE_SWITCH_NOT_UPDATED");
538 }
539 // Remove from the database empty flows
540 if (empty)
541 conn.utils().removeFlowPath(conn, flowObj);
542 conn.endTx(Transaction.COMMIT);
543
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800544 return true;
545 }
546
547 /**
Pavlin Radoslavov916832f2013-03-14 17:48:41 -0700548 * Clear the state for a previously added flow.
549 *
550 * @param flowId the Flow ID of the flow to clear.
551 * @return true on success, otherwise false.
552 */
553 @Override
554 public boolean clearFlow(FlowId flowId) {
555 IFlowPath flowObj = null;
556 try {
557 if ((flowObj = conn.utils().searchFlowPath(conn, flowId))
558 != null) {
559 log.debug("Clearing FlowPath with FlowId {}: found existing FlowPath",
560 flowId.toString());
561 } else {
562 log.debug("Clearing FlowPath with FlowId {}: FlowPath not found",
563 flowId.toString());
564 }
565 } catch (Exception e) {
566 // TODO: handle exceptions
567 conn.endTx(Transaction.ROLLBACK);
568 log.error(":clearFlow FlowId:{} failed", flowId.toString());
569 }
570 if (flowObj == null)
571 return true; // OK: No such flow
572
573 //
574 // Remove all Flow Entries
575 //
576 Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
577 for (IFlowEntry flowEntryObj : flowEntries) {
578 flowObj.removeFlowEntry(flowEntryObj);
579 conn.utils().removeFlowEntry(conn, flowEntryObj);
580 }
581 // Remove the Flow itself
582 conn.utils().removeFlowPath(conn, flowObj);
583 conn.endTx(Transaction.COMMIT);
584
585 return true;
586 }
587
588 /**
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800589 * Get a previously added flow.
590 *
591 * @param flowId the Flow ID of the flow to get.
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800592 * @return the Flow Path if found, otherwise null.
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800593 */
594 @Override
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800595 public FlowPath getFlow(FlowId flowId) {
596 IFlowPath flowObj = null;
597 try {
598 if ((flowObj = conn.utils().searchFlowPath(conn, flowId))
599 != null) {
600 log.debug("Get FlowPath with FlowId {}: found existing FlowPath",
601 flowId.toString());
602 } else {
603 log.debug("Get FlowPath with FlowId {}: FlowPath not found",
604 flowId.toString());
605 }
606 } catch (Exception e) {
607 // TODO: handle exceptions
608 conn.endTx(Transaction.ROLLBACK);
609 log.error(":getFlow FlowId:{} failed", flowId.toString());
610 }
611 if (flowObj == null)
612 return null; // Flow not found
613
614 //
615 // Extract the Flow state
616 //
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800617 FlowPath flowPath = extractFlowPath(flowObj);
618 conn.endTx(Transaction.COMMIT);
619
620 return flowPath;
621 }
622
623 /**
624 * Get all previously added flows by a specific installer for a given
625 * data path endpoints.
626 *
627 * @param installerId the Caller ID of the installer of the flow to get.
628 * @param dataPathEndpoints the data path endpoints of the flow to get.
629 * @return the Flow Paths if found, otherwise null.
630 */
631 @Override
632 public ArrayList<FlowPath> getAllFlows(CallerId installerId,
633 DataPathEndpoints dataPathEndpoints) {
634 //
635 // TODO: The implementation below is not optimal:
636 // We fetch all flows, and then return only the subset that match
637 // the query conditions.
638 // We should use the appropriate Titan/Gremlin query to filter-out
639 // the flows as appropriate.
640 //
641 ArrayList<FlowPath> allFlows = getAllFlows();
642
643 if (allFlows == null) {
644 log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints);
645 return null;
646 }
647
648 ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
649 for (FlowPath flow : allFlows) {
650 //
651 // TODO: String-based comparison is sub-optimal.
652 // We are using it for now to save us the extra work of
Pavlin Radoslavovc4e76a62013-03-06 10:52:41 -0800653 // implementing the "equals()" and "hashCode()" methods.
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800654 //
655 if (! flow.installerId().toString().equals(installerId.toString()))
656 continue;
657 if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
658 continue;
659 }
660 if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
661 continue;
662 }
663 flowPaths.add(flow);
664 }
665
666 if (flowPaths.isEmpty()) {
667 log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints);
668 flowPaths = null;
669 } else {
670 log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: FlowPaths are found", installerId, dataPathEndpoints);
671 }
672
673 return flowPaths;
674 }
675
676 /**
677 * Get all installed flows by all installers for given data path endpoints.
678 *
679 * @param dataPathEndpoints the data path endpoints of the flows to get.
680 * @return the Flow Paths if found, otherwise null.
681 */
682 @Override
683 public ArrayList<FlowPath> getAllFlows(DataPathEndpoints dataPathEndpoints) {
684 //
685 // TODO: The implementation below is not optimal:
686 // We fetch all flows, and then return only the subset that match
687 // the query conditions.
688 // We should use the appropriate Titan/Gremlin query to filter-out
689 // the flows as appropriate.
690 //
691 ArrayList<FlowPath> allFlows = getAllFlows();
692
693 if (allFlows == null) {
694 log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints);
695 return null;
696 }
697
698 ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
699 for (FlowPath flow : allFlows) {
700 //
701 // TODO: String-based comparison is sub-optimal.
702 // We are using it for now to save us the extra work of
Pavlin Radoslavovc4e76a62013-03-06 10:52:41 -0800703 // implementing the "equals()" and "hashCode()" methods.
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800704 //
705 if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
706 continue;
707 }
708 if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
709 continue;
710 }
711 flowPaths.add(flow);
712 }
713
714 if (flowPaths.isEmpty()) {
715 log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints);
716 flowPaths = null;
717 } else {
718 log.debug("Get FlowPaths for dataPathEndpoints{}: FlowPaths are found", dataPathEndpoints);
719 }
720
721 return flowPaths;
722 }
723
724 /**
725 * Get all installed flows by all installers.
726 *
727 * @return the Flow Paths if found, otherwise null.
728 */
729 @Override
730 public ArrayList<FlowPath> getAllFlows() {
731 Iterable<IFlowPath> flowPathsObj = null;
732
733 try {
734 if ((flowPathsObj = conn.utils().getAllFlowPaths(conn)) != null) {
735 log.debug("Get all FlowPaths: found FlowPaths");
736 } else {
737 log.debug("Get all FlowPaths: no FlowPaths found");
738 }
739 } catch (Exception e) {
740 // TODO: handle exceptions
741 conn.endTx(Transaction.ROLLBACK);
742 log.error(":getAllFlowPaths failed");
743 }
744 if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false))
745 return null; // No Flows found
746
747 ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
748 for (IFlowPath flowObj : flowPathsObj) {
749 //
750 // Extract the Flow state
751 //
752 FlowPath flowPath = extractFlowPath(flowObj);
753 flowPaths.add(flowPath);
754 }
755
756 conn.endTx(Transaction.COMMIT);
757
758 return flowPaths;
759 }
760
761 /**
762 * Extract Flow Path State from a Titan Database Object @ref IFlowPath.
763 *
764 * @param flowObj the object to extract the Flow Path State from.
765 * @return the extracted Flow Path State.
766 */
767 private FlowPath extractFlowPath(IFlowPath flowObj) {
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800768 FlowPath flowPath = new FlowPath();
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800769
770 //
771 // Extract the Flow state
772 //
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800773 flowPath.setFlowId(new FlowId(flowObj.getFlowId()));
774 flowPath.setInstallerId(new CallerId(flowObj.getInstallerId()));
775 flowPath.dataPath().srcPort().setDpid(new Dpid(flowObj.getSrcSwitch()));
776 flowPath.dataPath().srcPort().setPort(new Port(flowObj.getSrcPort()));
777 flowPath.dataPath().dstPort().setDpid(new Dpid(flowObj.getDstSwitch()));
778 flowPath.dataPath().dstPort().setPort(new Port(flowObj.getDstPort()));
779
780 //
781 // Extract all Flow Entries
782 //
783 Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
784 for (IFlowEntry flowEntryObj : flowEntries) {
785 FlowEntry flowEntry = new FlowEntry();
786 flowEntry.setFlowEntryId(new FlowEntryId(flowEntryObj.getFlowEntryId()));
787 flowEntry.setDpid(new Dpid(flowEntryObj.getSwitchDpid()));
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700788
789 //
790 // Extract the match conditions
791 //
792 FlowEntryMatch match = new FlowEntryMatch();
793 Short matchInPort = flowEntryObj.getMatchInPort();
794 if (matchInPort != null)
795 match.enableInPort(new Port(matchInPort));
796 Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
797 if (matchEthernetFrameType != null)
798 match.enableEthernetFrameType(matchEthernetFrameType);
799 String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
800 if (matchSrcIPv4Net != null)
801 match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
802 String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
803 if (matchDstIPv4Net != null)
804 match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
805 String matchSrcMac = flowEntryObj.getMatchSrcMac();
806 if (matchSrcMac != null)
807 match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
808 String matchDstMac = flowEntryObj.getMatchDstMac();
809 if (matchDstMac != null)
810 match.enableDstMac(MACAddress.valueOf(matchDstMac));
811 flowEntry.setFlowEntryMatch(match);
812
813 //
814 // Extract the actions
815 //
816 ArrayList<FlowEntryAction> actions = new ArrayList<FlowEntryAction>();
817 Short actionOutputPort = flowEntryObj.getActionOutput();
818 if (actionOutputPort != null) {
819 FlowEntryAction action = new FlowEntryAction();
820 action.setActionOutput(new Port(actionOutputPort));
821 actions.add(action);
822 }
823 flowEntry.setFlowEntryActions(actions);
824
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800825 String userState = flowEntryObj.getUserState();
826 flowEntry.setFlowEntryUserState(FlowEntryUserState.valueOf(userState));
827 String switchState = flowEntryObj.getSwitchState();
828 flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.valueOf(switchState));
829 //
Pavlin Radoslavovede97582013-03-08 18:57:28 -0800830 // TODO: Take care of the FlowEntryMatch, FlowEntryAction set,
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800831 // and FlowEntryErrorState.
832 //
833 flowPath.dataPath().flowEntries().add(flowEntry);
834 }
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800835
836 return flowPath;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800837 }
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800838}