blob: c792b67efce4f89e23e54cb0152d49a3cf9449c9 [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 /**
548 * Get a previously added flow.
549 *
550 * @param flowId the Flow ID of the flow to get.
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800551 * @return the Flow Path if found, otherwise null.
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800552 */
553 @Override
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800554 public FlowPath getFlow(FlowId flowId) {
555 IFlowPath flowObj = null;
556 try {
557 if ((flowObj = conn.utils().searchFlowPath(conn, flowId))
558 != null) {
559 log.debug("Get FlowPath with FlowId {}: found existing FlowPath",
560 flowId.toString());
561 } else {
562 log.debug("Get 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(":getFlow FlowId:{} failed", flowId.toString());
569 }
570 if (flowObj == null)
571 return null; // Flow not found
572
573 //
574 // Extract the Flow state
575 //
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800576 FlowPath flowPath = extractFlowPath(flowObj);
577 conn.endTx(Transaction.COMMIT);
578
579 return flowPath;
580 }
581
582 /**
583 * Get all previously added flows by a specific installer for a given
584 * data path endpoints.
585 *
586 * @param installerId the Caller ID of the installer of the flow to get.
587 * @param dataPathEndpoints the data path endpoints of the flow to get.
588 * @return the Flow Paths if found, otherwise null.
589 */
590 @Override
591 public ArrayList<FlowPath> getAllFlows(CallerId installerId,
592 DataPathEndpoints dataPathEndpoints) {
593 //
594 // TODO: The implementation below is not optimal:
595 // We fetch all flows, and then return only the subset that match
596 // the query conditions.
597 // We should use the appropriate Titan/Gremlin query to filter-out
598 // the flows as appropriate.
599 //
600 ArrayList<FlowPath> allFlows = getAllFlows();
601
602 if (allFlows == null) {
603 log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints);
604 return null;
605 }
606
607 ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
608 for (FlowPath flow : allFlows) {
609 //
610 // TODO: String-based comparison is sub-optimal.
611 // We are using it for now to save us the extra work of
Pavlin Radoslavovc4e76a62013-03-06 10:52:41 -0800612 // implementing the "equals()" and "hashCode()" methods.
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800613 //
614 if (! flow.installerId().toString().equals(installerId.toString()))
615 continue;
616 if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
617 continue;
618 }
619 if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
620 continue;
621 }
622 flowPaths.add(flow);
623 }
624
625 if (flowPaths.isEmpty()) {
626 log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints);
627 flowPaths = null;
628 } else {
629 log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: FlowPaths are found", installerId, dataPathEndpoints);
630 }
631
632 return flowPaths;
633 }
634
635 /**
636 * Get all installed flows by all installers for given data path endpoints.
637 *
638 * @param dataPathEndpoints the data path endpoints of the flows to get.
639 * @return the Flow Paths if found, otherwise null.
640 */
641 @Override
642 public ArrayList<FlowPath> getAllFlows(DataPathEndpoints dataPathEndpoints) {
643 //
644 // TODO: The implementation below is not optimal:
645 // We fetch all flows, and then return only the subset that match
646 // the query conditions.
647 // We should use the appropriate Titan/Gremlin query to filter-out
648 // the flows as appropriate.
649 //
650 ArrayList<FlowPath> allFlows = getAllFlows();
651
652 if (allFlows == null) {
653 log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints);
654 return null;
655 }
656
657 ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
658 for (FlowPath flow : allFlows) {
659 //
660 // TODO: String-based comparison is sub-optimal.
661 // We are using it for now to save us the extra work of
Pavlin Radoslavovc4e76a62013-03-06 10:52:41 -0800662 // implementing the "equals()" and "hashCode()" methods.
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800663 //
664 if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) {
665 continue;
666 }
667 if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) {
668 continue;
669 }
670 flowPaths.add(flow);
671 }
672
673 if (flowPaths.isEmpty()) {
674 log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints);
675 flowPaths = null;
676 } else {
677 log.debug("Get FlowPaths for dataPathEndpoints{}: FlowPaths are found", dataPathEndpoints);
678 }
679
680 return flowPaths;
681 }
682
683 /**
684 * Get all installed flows by all installers.
685 *
686 * @return the Flow Paths if found, otherwise null.
687 */
688 @Override
689 public ArrayList<FlowPath> getAllFlows() {
690 Iterable<IFlowPath> flowPathsObj = null;
691
692 try {
693 if ((flowPathsObj = conn.utils().getAllFlowPaths(conn)) != null) {
694 log.debug("Get all FlowPaths: found FlowPaths");
695 } else {
696 log.debug("Get all FlowPaths: no FlowPaths found");
697 }
698 } catch (Exception e) {
699 // TODO: handle exceptions
700 conn.endTx(Transaction.ROLLBACK);
701 log.error(":getAllFlowPaths failed");
702 }
703 if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false))
704 return null; // No Flows found
705
706 ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>();
707 for (IFlowPath flowObj : flowPathsObj) {
708 //
709 // Extract the Flow state
710 //
711 FlowPath flowPath = extractFlowPath(flowObj);
712 flowPaths.add(flowPath);
713 }
714
715 conn.endTx(Transaction.COMMIT);
716
717 return flowPaths;
718 }
719
720 /**
721 * Extract Flow Path State from a Titan Database Object @ref IFlowPath.
722 *
723 * @param flowObj the object to extract the Flow Path State from.
724 * @return the extracted Flow Path State.
725 */
726 private FlowPath extractFlowPath(IFlowPath flowObj) {
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800727 FlowPath flowPath = new FlowPath();
Pavlin Radoslavov706df052013-03-06 10:49:07 -0800728
729 //
730 // Extract the Flow state
731 //
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800732 flowPath.setFlowId(new FlowId(flowObj.getFlowId()));
733 flowPath.setInstallerId(new CallerId(flowObj.getInstallerId()));
734 flowPath.dataPath().srcPort().setDpid(new Dpid(flowObj.getSrcSwitch()));
735 flowPath.dataPath().srcPort().setPort(new Port(flowObj.getSrcPort()));
736 flowPath.dataPath().dstPort().setDpid(new Dpid(flowObj.getDstSwitch()));
737 flowPath.dataPath().dstPort().setPort(new Port(flowObj.getDstPort()));
738
739 //
740 // Extract all Flow Entries
741 //
742 Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries();
743 for (IFlowEntry flowEntryObj : flowEntries) {
744 FlowEntry flowEntry = new FlowEntry();
745 flowEntry.setFlowEntryId(new FlowEntryId(flowEntryObj.getFlowEntryId()));
746 flowEntry.setDpid(new Dpid(flowEntryObj.getSwitchDpid()));
Pavlin Radoslavove2f0de82013-03-12 01:39:30 -0700747
748 //
749 // Extract the match conditions
750 //
751 FlowEntryMatch match = new FlowEntryMatch();
752 Short matchInPort = flowEntryObj.getMatchInPort();
753 if (matchInPort != null)
754 match.enableInPort(new Port(matchInPort));
755 Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType();
756 if (matchEthernetFrameType != null)
757 match.enableEthernetFrameType(matchEthernetFrameType);
758 String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net();
759 if (matchSrcIPv4Net != null)
760 match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net));
761 String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net();
762 if (matchDstIPv4Net != null)
763 match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net));
764 String matchSrcMac = flowEntryObj.getMatchSrcMac();
765 if (matchSrcMac != null)
766 match.enableSrcMac(MACAddress.valueOf(matchSrcMac));
767 String matchDstMac = flowEntryObj.getMatchDstMac();
768 if (matchDstMac != null)
769 match.enableDstMac(MACAddress.valueOf(matchDstMac));
770 flowEntry.setFlowEntryMatch(match);
771
772 //
773 // Extract the actions
774 //
775 ArrayList<FlowEntryAction> actions = new ArrayList<FlowEntryAction>();
776 Short actionOutputPort = flowEntryObj.getActionOutput();
777 if (actionOutputPort != null) {
778 FlowEntryAction action = new FlowEntryAction();
779 action.setActionOutput(new Port(actionOutputPort));
780 actions.add(action);
781 }
782 flowEntry.setFlowEntryActions(actions);
783
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800784 String userState = flowEntryObj.getUserState();
785 flowEntry.setFlowEntryUserState(FlowEntryUserState.valueOf(userState));
786 String switchState = flowEntryObj.getSwitchState();
787 flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.valueOf(switchState));
788 //
Pavlin Radoslavovede97582013-03-08 18:57:28 -0800789 // TODO: Take care of the FlowEntryMatch, FlowEntryAction set,
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800790 // and FlowEntryErrorState.
791 //
792 flowPath.dataPath().flowEntries().add(flowEntry);
793 }
Pavlin Radoslavovb6f53542013-03-01 16:02:14 -0800794
795 return flowPath;
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800796 }
Pavlin Radoslavov9e5344c2013-02-18 09:58:30 -0800797}