2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.forwardingrulesmanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.UnknownHostException;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.Date;
19 import java.util.EnumSet;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
25 import java.util.Map.Entry;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
30 import org.eclipse.osgi.framework.console.CommandInterpreter;
31 import org.eclipse.osgi.framework.console.CommandProvider;
32 import org.opendaylight.controller.clustering.services.CacheConfigException;
33 import org.opendaylight.controller.clustering.services.CacheExistException;
34 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
35 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
36 import org.opendaylight.controller.clustering.services.IClusterServices;
37 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
38 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
39 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
40 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
41 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
42 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
43 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
44 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
45 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
46 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
47 import org.opendaylight.controller.hosttracker.IfIptoHost;
48 import org.opendaylight.controller.sal.action.Action;
49 import org.opendaylight.controller.sal.action.ActionType;
50 import org.opendaylight.controller.sal.action.Controller;
51 import org.opendaylight.controller.sal.action.Flood;
52 import org.opendaylight.controller.sal.action.Output;
53 import org.opendaylight.controller.sal.action.PopVlan;
54 import org.opendaylight.controller.sal.core.ContainerFlow;
55 import org.opendaylight.controller.sal.core.IContainer;
56 import org.opendaylight.controller.sal.core.IContainerListener;
57 import org.opendaylight.controller.sal.core.Node;
58 import org.opendaylight.controller.sal.core.NodeConnector;
59 import org.opendaylight.controller.sal.core.Property;
60 import org.opendaylight.controller.sal.core.UpdateType;
61 import org.opendaylight.controller.sal.flowprogrammer.Flow;
62 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
63 import org.opendaylight.controller.sal.match.Match;
64 import org.opendaylight.controller.sal.match.MatchType;
65 import org.opendaylight.controller.sal.utils.StatusCode;
66 import org.opendaylight.controller.sal.utils.EtherTypes;
67 import org.opendaylight.controller.sal.utils.GlobalConstants;
68 import org.opendaylight.controller.sal.utils.HexEncode;
69 import org.opendaylight.controller.sal.utils.IObjectReader;
70 import org.opendaylight.controller.sal.utils.IPProtocols;
71 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
72 import org.opendaylight.controller.sal.utils.NodeCreator;
73 import org.opendaylight.controller.sal.utils.ObjectReader;
74 import org.opendaylight.controller.sal.utils.ObjectWriter;
75 import org.opendaylight.controller.sal.utils.Status;
76 import org.opendaylight.controller.switchmanager.IInventoryListener;
77 import org.opendaylight.controller.switchmanager.ISwitchManager;
78 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
79 import org.opendaylight.controller.switchmanager.Subnet;
80 import org.osgi.framework.BundleContext;
81 import org.osgi.framework.FrameworkUtil;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
86 * Class that manages forwarding rule installation and removal per container of
87 * the network. It also maintains the central repository of all the forwarding
88 * rules installed on the network nodes.
90 public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
91 PortGroupChangeListener, IContainerListener, ISwitchManagerAware,
92 IConfigurationContainerAware, IInventoryListener, IObjectReader,
93 ICacheUpdateAware<Long, String>, CommandProvider {
94 private static final String SAVE = "Save";
95 private static final String NODEDOWN = "Node is Down";
96 private static final Logger log = LoggerFactory
97 .getLogger(ForwardingRulesManagerImpl.class);
98 private Map<Long, String> flowsSaveEvent;
99 private String frmFileName;
100 private String portGroupFileName;
101 private ConcurrentMap<Integer, FlowConfig> staticFlows;
102 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
103 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
104 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
105 private ConcurrentMap<String, Object> TSPolicies;
106 private boolean inContainerMode; // being used by default instance only
108 * Flow database. It's the software view of what was installed on the
109 * switch. It is indexed by node. For convenience a version indexed by group
110 * name is also maintained. The core element is a class which contains the
111 * flow entry pushed by the functional modules and the respective container
112 * flow merged version. In absence of container flows, the two flow entries
115 private ConcurrentMap<Node, Set<FlowEntryInstall>> nodeFlows;
116 private ConcurrentMap<String, Set<FlowEntryInstall>> groupFlows;
118 * Inactive flow list. This is for the global instance of FRM It will
119 * contain all the flow entries which were installed on the global container
120 * when the first container is created.
122 private List<FlowEntry> inactiveFlows;
124 private IfIptoHost hostFinder;
125 private IContainer container;
126 private Set<IForwardingRulesManagerAware> frmAware;
127 private PortGroupProvider portGroupProvider;
128 private IFlowProgrammerService programmer;
129 private IClusterContainerServices clusterContainerService = null;
130 private ISwitchManager switchManager;
133 * Adds a flow entry onto the network node It runs various validity checks
134 * and derive the final container flows merged entries that will be
135 * attempted to be installed
138 * the original flow entry application requested to add
141 private Status addEntry(FlowEntry flowEntry) {
143 if (flowEntry == null || flowEntry.getNode() == null) {
144 String msg = "Invalid FlowEntry";
145 log.warn(msg + ": " + flowEntry);
146 return new Status(StatusCode.NOTACCEPTABLE, msg);
150 * Derive the container flow merged entries to install In presence of N
151 * container flows, we may end up with N different entries to install...
153 List<FlowEntryInstall> toInstallList = deriveInstallEntries(
154 flowEntry.clone(), container.getContainerFlows());
156 // Container Flow conflict Check
157 if (toInstallList.isEmpty()) {
158 String msg = "Flow Entry conflicts with all Container Flows";
160 return new Status(StatusCode.CONFLICT, msg);
163 // Derive the list of entries good to be installed
164 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
165 for (FlowEntryInstall entry : toInstallList) {
166 // Conflict Check: Verify new entry would not overwrite existing
168 if (findMatch(entry.getInstall(), false) != null) {
169 log.warn("Operation Rejected: A flow with same match "
170 + "and priority exists on the target node");
171 log.trace("Aborting to install " + entry);
174 toInstallSafe.add(entry);
177 // Declare failure if all the container flow merged entries clash with
179 if (toInstallSafe.size() == 0) {
180 String msg = "A flow with same match and priority exists "
181 + "on the target node";
183 return new Status(StatusCode.CONFLICT, msg);
186 // Try to install an entry at the time
187 Status error = new Status(null, null);
188 boolean oneSucceded = false;
189 for (FlowEntryInstall installEntry : toInstallList) {
191 // Install and update database
192 Status ret = addEntriesInternal(installEntry);
194 if (ret.isSuccess()) {
198 log.warn("Failed to install the entry: " + ret.getDescription());
202 return (oneSucceded) ? new Status(StatusCode.SUCCESS, null) : error;
206 * Given a flow entry and the list of container flows, it returns the list
207 * of container flow merged flow entries good to be installed on this
208 * container. If the list of container flows is null or empty, the install
209 * entry list will contain only one entry, the original flow entry. If the
210 * flow entry is congruent with all the N container flows, then the output
211 * install entry list will contain N entries. If the output list is empty,
212 * it means the passed flow entry conflicts with all the container flows.
215 * The list of container flows
216 * @return the list of container flow merged entries good to be installed on
219 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request,
220 List<ContainerFlow> cFlowList) {
221 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(
224 if (container.getContainerFlows() == null
225 || container.getContainerFlows().isEmpty()) {
226 // No container flows => entry good to be installed unchanged
227 toInstallList.add(new FlowEntryInstall(request.clone(), null));
229 // Create the list of entries to be installed. If the flow entry is
230 // not congruent with any container flow, no install entries will be
232 for (ContainerFlow cFlow : container.getContainerFlows()) {
233 if (cFlow.allowsFlow(request.getFlow())) {
234 toInstallList.add(new FlowEntryInstall(request.clone(),
239 return toInstallList;
243 * Modify a flow entry with a new one It runs various validity check and
244 * derive the final container flows merged flow entries to work with
246 * @param currentFlowEntry
247 * @param newFlowEntry
248 * @return Success or error string
250 private Status modifyEntry(FlowEntry currentFlowEntry,
251 FlowEntry newFlowEntry) {
255 if (currentFlowEntry == null || currentFlowEntry.getNode() == null
256 || newFlowEntry == null || newFlowEntry.getNode() == null) {
257 String msg = "Modify: Invalid FlowEntry";
258 log.warn(msg + ": {} or {} ", currentFlowEntry, newFlowEntry);
259 return new Status(StatusCode.NOTACCEPTABLE, msg);
261 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
262 || !currentFlowEntry.getFlowName().equals(
263 newFlowEntry.getFlowName())) {
264 String msg = "Modify: Incompatible Flow Entries";
265 log.warn(msg + ": {} and {}", currentFlowEntry, newFlowEntry);
266 return new Status(StatusCode.NOTACCEPTABLE, msg);
270 if (currentFlowEntry.equals(newFlowEntry)) {
271 String msg = "Modify skipped as flows are the same";
272 log.debug(msg + ": " + currentFlowEntry + " and " + newFlowEntry);
273 return new Status(StatusCode.SUCCESS, msg);
276 // Conflict Check: Verify the new entry would not conflict with another
278 // This is a loose check on the previous original flow entry requests.
280 // on the container flow merged flow entries (if any) yet
281 FlowEntryInstall sameMatchOriginalEntry = findMatch(newFlowEntry, true);
282 if (sameMatchOriginalEntry != null
283 && !sameMatchOriginalEntry.getOriginal().equals(
285 String msg = "Operation Rejected: Another flow with same match "
286 + "and priority exists on the target node";
288 return new Status(StatusCode.CONFLICT, msg);
291 // Derive the installed and toInstall entries
292 List<FlowEntryInstall> installedList = deriveInstallEntries(
293 currentFlowEntry.clone(), container.getContainerFlows());
294 List<FlowEntryInstall> toInstallList = deriveInstallEntries(
295 newFlowEntry.clone(), container.getContainerFlows());
297 if (toInstallList.isEmpty()) {
298 String msg = "Modify Operation Rejected: The new entry "
299 + "conflicts with all the container flows";
301 return new Status(StatusCode.CONFLICT, msg);
305 * If the two list sizes differ, it means the new flow entry does not
306 * satisfy the same number of container flows the current entry does.
307 * This is only possible when the new entry and current entry have
308 * different match. In this scenario the modification would ultimately
309 * be handled as a remove and add operations in the protocol plugin.
311 * Also, if any of the new flow entries would clash with an existing
312 * one, we cannot proceed with the modify operation, because it would
313 * fail for some entries and leave stale entries on the network node.
314 * Modify path can be taken only if it can be performed completely, for
317 * So, for the above two cases, to simplify, let's decouple the modify
318 * in: 1) remove current entries 2) install new entries
320 boolean decouple = false;
321 if (installedList.size() != toInstallList.size()) {
322 log.info("Modify: New flow entry does not satisfy the same "
323 + "number of container flows as the original entry does");
326 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
327 for (FlowEntryInstall installEntry : toInstallList) {
328 // Conflict Check: Verify the new entry would not overwrite another
330 FlowEntryInstall sameMatchEntry = findMatch(
331 installEntry.getInstall(), false);
332 if (sameMatchEntry != null
333 && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
334 log.info("Modify: new container flow merged flow entry "
335 + "clashes with existing flow");
338 toInstallSafe.add(installEntry);
343 // Remove current entries
344 for (FlowEntryInstall currEntry : installedList) {
345 this.removeEntryInternal(currEntry);
347 // Install new entries
348 for (FlowEntryInstall newEntry : toInstallSafe) {
349 this.addEntriesInternal(newEntry);
353 * The two list have the same size and the entries to install do not
354 * clash with any existing flow on the network node. We assume here
355 * (and might be wrong) that the same container flows that were
356 * satisfied by the current entries are the same that are satisfied
357 * by the new entries. Let's take the risk for now.
359 * Note: modification has to be complete. If any entry modification
360 * fails, we need to stop, restore the already modified entries, and
365 int size = toInstallList.size();
367 // Modify and update database
368 retModify = modifyEntryInternal(installedList.get(i),
369 toInstallList.get(i));
370 if (retModify.isSuccess()) {
376 // Check if uncompleted modify
378 log.warn("Unable to perform a complete modify for all "
379 + "the container flows merged entries");
380 // Restore original entries
383 log.info("Attempting to restore initial entries");
384 retExt = modifyEntryInternal(toInstallList.get(i),
385 installedList.get(i));
386 if (retExt.isSuccess()) {
392 // Fatal error, recovery failed
394 String msg = "Flow recovery failed ! Unrecoverable Error";
396 return new Status(StatusCode.INTERNALERROR, msg);
400 return new Status(StatusCode.SUCCESS, null);
404 * This is the function that modifies the final container flows merged
405 * entries on the network node and update the database. It expects that all
406 * the validity checks are passed
408 * @param currentEntries
412 private Status modifyEntryInternal(FlowEntryInstall currentEntries,
413 FlowEntryInstall newEntries) {
414 // Modify the flow on the network node
415 Status status = programmer.modifyFlow(currentEntries.getNode(),
416 currentEntries.getInstall().getFlow(), newEntries.getInstall()
419 if (!status.isSuccess()) {
420 log.warn("SDN Plugin failed to program the flow: "
421 + status.getDescription());
425 log.trace("Modified {} => {}", currentEntries.getInstall(),
426 newEntries.getInstall());
429 updateLocalDatabase(currentEntries, false);
430 updateLocalDatabase(newEntries, true);
436 * Remove a flow entry. If the entry is not present in the software view
437 * (entry or node not present), it return successfully
442 private Status removeEntry(FlowEntry flowEntry) {
443 Status error = new Status(null, null);
446 if (flowEntry == null || flowEntry.getNode() == null) {
447 String msg = "Invalid FlowEntry";
448 log.warn(msg + ": " + flowEntry);
449 return new Status(StatusCode.NOTACCEPTABLE, msg);
452 // Derive the container flows merged installed entries
453 List<FlowEntryInstall> installedList = deriveInstallEntries(
454 flowEntry.clone(), container.getContainerFlows());
456 Set<FlowEntryInstall> flowsOnNode = nodeFlows.get(flowEntry.getNode());
457 boolean atLeastOneRemoved = false;
458 for (FlowEntryInstall entry : installedList) {
459 if (flowsOnNode == null) {
460 String msg = "Removal skipped (Node down)";
461 log.debug(msg + " for flow entry " + flowEntry);
462 return new Status(StatusCode.SUCCESS, msg);
464 if (!flowsOnNode.contains(entry)) {
465 log.debug("Removal skipped (not present in software view) "
466 + "for flow entry " + flowEntry);
468 if (installedList.size() == 1) {
469 // If we had only one entry to remove, we are done
470 return new Status(StatusCode.SUCCESS, null);
476 // Remove and update DB
477 Status ret = removeEntryInternal(entry);
479 if (!ret.isSuccess()) {
481 log.warn("Failed to remove the entry: " + ret.getDescription());
482 if (installedList.size() == 1) {
483 // If we had only one entry to remove, this is fatal failure
487 atLeastOneRemoved = true;
492 * No worries if full removal failed. Consistency checker will take care
493 * of removing the stale entries later, or adjusting the software
494 * database if not in sync with hardware
496 return (atLeastOneRemoved) ? new Status(StatusCode.SUCCESS, null)
501 * This is the function that removes the final container flows merged entry
502 * from the network node and update the database. It expects that all the
503 * validity checks are passed
506 * the FlowEntryInstall
507 * @return "Success" or error string
509 private Status removeEntryInternal(FlowEntryInstall entry) {
510 // Mark the entry to be deleted (for CC just in case we fail)
514 Status status = programmer.removeFlow(entry.getNode(), entry
515 .getInstall().getFlow());
517 if (!status.isSuccess()) {
518 log.warn("SDN Plugin failed to remove the flow: "
519 + status.getDescription());
522 log.trace("Removed {}", entry.getInstall());
525 updateLocalDatabase(entry, false);
531 * This is the function that installs the final container flow merged entry
532 * on the network node and updates the database. It expects that all the
533 * validity and conflict checks are passed. That means it does not check
534 * whether this flow would conflict or overwrite an existing one.
537 * the FlowEntryInstall
538 * @return "Success" or error string
540 private Status addEntriesInternal(FlowEntryInstall entry) {
541 // Install the flow on the network node
542 Status status = programmer.addFlow(entry.getNode(), entry.getInstall()
545 if (!status.isSuccess()) {
546 log.warn("SDN Plugin failed to program the flow: "
547 + status.getDescription());
551 log.trace("Added {}", entry.getInstall());
554 updateLocalDatabase(entry, true);
560 * Returns true if the flow conflicts with all the container's flows. This
561 * means that if the function returns true, the passed flow entry is
562 * congruent with at least one container flow, hence it is good to be
563 * installed on this container.
566 * @return true if flow conflicts with all the container flows, false
569 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
570 List<ContainerFlow> cFlowList = container.getContainerFlows();
572 // Validity check and avoid unnecessary computation
573 // Also takes care of default container where no container flows are
575 if (cFlowList == null || cFlowList.isEmpty()) {
579 for (ContainerFlow cFlow : cFlowList) {
580 if (cFlow.allowsFlow(flowEntry.getFlow())) {
581 // Entry is allowed by at least one container flow: good to go
588 private synchronized void updateLocalDatabase(FlowEntryInstall entry,
590 // Update node indexed flow database
591 updateNodeFlowsDB(entry, add);
593 // Update group indexed flow database
594 updateGroupFlowsDB(entry, add);
598 * Update the node mapped flows database
600 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
601 Node node = flowEntries.getNode();
603 Set<FlowEntryInstall> flowEntrylist = this.nodeFlows.get(node);
604 if (flowEntrylist == null) {
608 flowEntrylist = new HashSet<FlowEntryInstall>();
613 flowEntrylist.add(flowEntries);
615 flowEntrylist.remove(flowEntries);
618 if (flowEntrylist.isEmpty()) {
619 this.nodeFlows.remove(node);
621 this.nodeFlows.put(node, flowEntrylist);
626 * Update the group name mapped flows database
628 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
629 Set<FlowEntryInstall> flowList;
630 FlowEntryInstall exists = null;
631 String flowName = flowEntries.getFlowName();
632 String groupName = flowEntries.getGroupName();
634 if (this.groupFlows == null) {
638 // Flow may not be part of a group
639 if (groupName == null) {
643 if (this.groupFlows.containsKey(groupName)) {
644 flowList = this.groupFlows.get(groupName);
649 flowList = new HashSet<FlowEntryInstall>();
653 for (FlowEntryInstall flow : flowList) {
654 if (flow.equalsByNodeAndName(flowEntries.getNode(), flowName)) {
660 if (exists == null && add == false) {
664 if (exists != null) {
665 flowList.remove(exists);
669 flowList.add(flowEntries);
672 if (flowList.isEmpty()) {
673 this.groupFlows.remove(groupName);
675 this.groupFlows.put(groupName, flowList);
680 * Remove a flow entry that has been added previously First checks if the
681 * entry is effectively present in the local database
683 @SuppressWarnings("unused")
684 private Status removeEntry(Node node, String flowName) {
685 FlowEntryInstall target = null;
688 for (FlowEntryInstall entry : this.nodeFlows.get(node)) {
689 if (entry.equalsByNodeAndName(node, flowName)) {
695 // If it is not there, stop any further processing
696 if (target == null) {
697 return new Status(StatusCode.SUCCESS, "Entry is not present");
701 Status status = programmer.removeFlow(target.getNode(), target
702 .getInstall().getFlow());
705 if (status.isSuccess()) {
706 updateLocalDatabase(target, false);
713 public Status installFlowEntry(FlowEntry flowEntry) {
715 if (inContainerMode) {
716 String msg = "Controller in container mode: Install Refused";
717 status = new Status(StatusCode.NOTACCEPTABLE, msg);
720 status = addEntry(flowEntry);
726 public Status uninstallFlowEntry(FlowEntry entry) {
728 if (inContainerMode) {
729 String msg = "Controller in container mode: Uninstall Refused";
730 status = new Status(StatusCode.NOTACCEPTABLE, msg);
733 status = removeEntry(entry);
739 public Status modifyFlowEntry(FlowEntry currentFlowEntry,
740 FlowEntry newFlowEntry) {
741 Status status = null;
742 if (inContainerMode) {
743 String msg = "Controller in container mode: Modify Refused";
744 status = new Status(StatusCode.NOTACCEPTABLE, msg);
747 status = modifyEntry(currentFlowEntry, newFlowEntry);
753 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
755 * Run a loose check on the installed entries to decide whether to go
756 * with a add or modify method. A loose check means only check against
757 * the original flow entry requests and not against the installed flow
758 * entries which are the result of the original entry merged with the
759 * container flow(s) (if any). The modifyFlowEntry method in presence of
760 * conflicts with the Container flows (if any) would revert back to a
761 * delete + add pattern
763 FlowEntryInstall currentFlowEntries = findMatch(newFlowEntry, true);
765 if (currentFlowEntries != null) {
766 return modifyFlowEntry(currentFlowEntries.getOriginal(),
769 return installFlowEntry(newFlowEntry);
774 * Try to find in the database if a Flow with the same Match and priority of
775 * the passed one already exists for the specified network node. Flow,
776 * priority and network node are all specified in the FlowEntry If found,
777 * the respective FlowEntryInstall Object is returned
780 * the FlowEntry to be tested against the ones installed
782 * if true, the function will run the check against the original
783 * flow entry portion of the installed entries
784 * @return null if not found, otherwise the FlowEntryInstall which contains
785 * the existing flow entry
787 private FlowEntryInstall findMatch(FlowEntry flowEntry, boolean looseCheck) {
788 Flow flow = flowEntry.getFlow();
789 Match match = flow.getMatch();
790 short priority = flow.getPriority();
791 Set<FlowEntryInstall> thisNodeList = nodeFlows.get(flowEntry.getNode());
793 if (thisNodeList != null) {
794 for (FlowEntryInstall flowEntries : thisNodeList) {
795 flow = (looseCheck == false) ? flowEntries.getInstall()
796 .getFlow() : flowEntries.getOriginal().getFlow();
797 if (flow.getMatch().equals(match)
798 && flow.getPriority() == priority) {
806 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
807 return entryConflictsWithContainerFlows(flowEntry);
811 * Updates all installed flows because the container flow got updated This
812 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
813 * Reinstall of all flows This is needed because a new container flows
814 * merged flow may conflict with an existing old container flows merged flow
815 * on the network node
817 private void updateFlowsContainerFlow() {
818 List<FlowEntryInstall> oldCouples = new ArrayList<FlowEntryInstall>();
819 List<FlowEntry> toReinstall = new ArrayList<FlowEntry>();
820 for (Entry<Node, Set<FlowEntryInstall>> entry : this.nodeFlows
824 if (entry.getValue() == null) {
827 // Create a set of old entries and one of original entries to be
829 for (FlowEntryInstall oldCouple : entry.getValue()) {
830 oldCouples.add(oldCouple);
831 toReinstall.add(oldCouple.getOriginal());
833 // Remove the old couples. No validity checks to be run, use the
835 for (FlowEntryInstall oldCouple : oldCouples) {
836 this.removeEntryInternal(oldCouple);
838 // Reinstall the original flow entries, via the regular path: new
839 // cFlow merge + validations
840 for (FlowEntry flowEntry : toReinstall) {
841 this.installFlowEntry(flowEntry);
846 public void nonClusterObjectCreate() {
847 nodeFlows = new ConcurrentHashMap<Node, Set<FlowEntryInstall>>();
848 TSPolicies = new ConcurrentHashMap<String, Object>();
849 groupFlows = new ConcurrentHashMap<String, Set<FlowEntryInstall>>();
850 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
851 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
852 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
853 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
854 flowsSaveEvent = new HashMap<Long, String>();
855 inactiveFlows = new ArrayList<FlowEntry>(1);
858 private void registerWithOSGIConsole() {
859 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
861 bundleContext.registerService(CommandProvider.class.getName(), this,
866 public void setTSPolicyData(String policyname, Object o, boolean add) {
869 /* Check if this policy already exists */
870 if (!(TSPolicies.containsKey(policyname))) {
871 TSPolicies.put(policyname, o);
874 TSPolicies.remove(policyname);
876 if (frmAware != null) {
877 synchronized (frmAware) {
878 for (IForwardingRulesManagerAware frma : frmAware) {
880 frma.policyUpdate(policyname, add);
881 } catch (Exception e) {
882 log.error("Exception on callback", e);
890 public Map<String, Object> getTSPolicyData() {
895 public Object getTSPolicyData(String policyName) {
896 if (TSPolicies.containsKey(policyName)) {
897 return TSPolicies.get(policyName);
904 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
905 List<FlowEntry> list = null;
906 if (this.groupFlows != null && this.groupFlows.containsKey(policyName)) {
907 list = new ArrayList<FlowEntry>();
908 for (FlowEntryInstall entries : groupFlows.get(policyName)) {
909 list.add(entries.getOriginal());
911 return new ArrayList<FlowEntry>();
917 public void addOutputPort(Node node, String flowName,
918 List<NodeConnector> portList) {
920 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
922 for (FlowEntryInstall flow : flowEntryList) {
923 if (flow.getFlowName().equals(flowName)) {
924 FlowEntry currentFlowEntry = flow.getOriginal();
925 FlowEntry newFlowEntry = currentFlowEntry.clone();
926 for (NodeConnector dstPort : portList) {
927 newFlowEntry.getFlow().addAction(new Output(dstPort));
929 Status error = modifyEntry(currentFlowEntry, newFlowEntry);
930 if (error.isSuccess()) {
931 log.info("Ports {} added to FlowEntry {}", portList,
934 log.warn("Failed to add ports {} to Flow entry {}: "
935 + error.getDescription(), portList,
936 currentFlowEntry.toString());
941 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found",
946 public void removeOutputPort(Node node, String flowName,
947 List<NodeConnector> portList) {
949 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
951 for (FlowEntryInstall flow : flowEntryList) {
952 if (flow.getFlowName().equals(flowName)) {
953 FlowEntry currentFlowEntry = flow.getOriginal();
954 FlowEntry newFlowEntry = currentFlowEntry.clone();
955 for (NodeConnector dstPort : portList) {
956 Action action = new Output(dstPort);
957 newFlowEntry.getFlow().removeAction(action);
959 Status status = modifyEntry(currentFlowEntry, newFlowEntry);
960 if (status.isSuccess()) {
961 log.info("Ports {} removed from FlowEntry {}", portList,
964 log.warn("Failed to remove ports {} from Flow entry {}: "
965 + status.getDescription(), portList,
966 currentFlowEntry.toString());
972 "Failed to remove ports from Flow {} on Node {}: Entry Not Found",
977 * This function assumes the target flow has only one output port
980 public void replaceOutputPort(Node node, String flowName,
981 NodeConnector outPort) {
982 FlowEntry currentFlowEntry = null;
983 FlowEntry newFlowEntry = null;
984 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
987 for (FlowEntryInstall flow : flowEntryList) {
988 if (flow.getFlowName().equals(flowName)) {
989 currentFlowEntry = flow.getOriginal();
993 if (currentFlowEntry == null) {
995 "Failed to replace output port for flow {} on node {}: Entry Not Found",
1000 // Create a flow copy with the new output port
1001 newFlowEntry = currentFlowEntry.clone();
1002 Action target = null;
1003 for (Action action : newFlowEntry.getFlow().getActions()) {
1004 if (action.getType() == ActionType.OUTPUT) {
1009 newFlowEntry.getFlow().removeAction(target);
1010 newFlowEntry.getFlow().addAction(new Output(outPort));
1012 // Modify on network node
1013 Status status = modifyEntry(currentFlowEntry, newFlowEntry);
1015 if (status.isSuccess()) {
1016 log.info("Output port replaced with " + outPort
1017 + " for flow {} on node {}", flowName, node);
1019 log.warn("Failed to replace output port for flow {} on node {}: ",
1020 status.getDescription(), flowName, node);
1026 public NodeConnector getOutputPort(Node node, String flowName) {
1027 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
1029 for (FlowEntryInstall flow : flowEntryList) {
1030 if (flow.getFlowName().equals(flowName)) {
1031 for (Action action : flow.getOriginal().getFlow().getActions()) {
1032 if (action.getType() == ActionType.OUTPUT) {
1033 return ((Output) action).getPort();
1042 private void cacheStartup() {
1047 @SuppressWarnings("deprecation")
1048 private void allocateCaches() {
1049 if (this.clusterContainerService == null) {
1050 log.warn("Un-initialized clusterContainerService, can't create cache");
1054 log.debug("FRM allocateCaches for Container {}", container);
1057 clusterContainerService.createCache("frm.nodeFlows",
1058 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1060 clusterContainerService.createCache("frm.groupFlows",
1061 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1063 clusterContainerService.createCache("frm.staticFlows",
1064 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1066 clusterContainerService.createCache("frm.flowsSaveEvent",
1067 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1069 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1070 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1072 clusterContainerService.createCache("frm.portGroupConfigs",
1073 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1075 clusterContainerService.createCache("frm.portGroupData",
1076 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1078 clusterContainerService.createCache("frm.TSPolicies",
1079 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1081 } catch (CacheConfigException cce) {
1082 log.error("FRM CacheConfigException");
1083 } catch (CacheExistException cce) {
1084 log.error("FRM CacheExistException");
1088 @SuppressWarnings({ "unchecked", "deprecation" })
1089 private void retrieveCaches() {
1090 ConcurrentMap<?, ?> map;
1092 if (this.clusterContainerService == null) {
1093 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1097 log.debug("FRM retrieveCaches for Container {}", container);
1099 map = clusterContainerService.getCache("frm.nodeFlows");
1101 nodeFlows = (ConcurrentMap<Node, Set<FlowEntryInstall>>) map;
1104 "FRM Cache frm.nodeFlows allocation failed for Container {}",
1108 map = clusterContainerService.getCache("frm.groupFlows");
1110 groupFlows = (ConcurrentMap<String, Set<FlowEntryInstall>>) map;
1113 "FRM Cache frm.groupFlows allocation failed for Container {}",
1117 map = clusterContainerService.getCache("frm.staticFlows");
1119 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1122 "FRM Cache frm.staticFlows allocation failed for Container {}",
1126 map = clusterContainerService.getCache("frm.flowsSaveEvent");
1128 flowsSaveEvent = (ConcurrentMap<Long, String>) map;
1131 "FRM Cache frm.flowsSaveEvent allocation failed for Container {}",
1135 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1137 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1140 "FRM Cache frm.staticFlowsOrdinal allocation failed for Container {}",
1144 map = clusterContainerService.getCache("frm.portGroupConfigs");
1146 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1149 "FRM Cache frm.portGroupConfigs allocation failed for Container {}",
1153 map = clusterContainerService.getCache("frm.portGroupData");
1155 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1158 "FRM Cache frm.portGroupData allocation failed for Container {}",
1162 map = clusterContainerService.getCache("frm.TSPolicies");
1164 TSPolicies = (ConcurrentMap<String, Object>) map;
1167 "FRM Cache frm.TSPolicies allocation failed for Container {}",
1173 @SuppressWarnings("deprecation")
1174 private void destroyCaches() {
1175 if (this.clusterContainerService == null) {
1176 log.warn("Un-initialized clusterContainerService, can't destroy cache");
1180 log.debug("FRM destroyCaches for Container {}", container);
1181 clusterContainerService.destroyCache("frm.nodeFlows");
1182 clusterContainerService.destroyCache("frm.TSPolicies");
1183 clusterContainerService.destroyCache("frm.groupFlows");
1184 clusterContainerService.destroyCache("frm.staticFlows");
1185 clusterContainerService.destroyCache("frm.flowsSaveEvent");
1186 clusterContainerService.destroyCache("frm.staticFlowsOrdinal");
1187 clusterContainerService.destroyCache("frm.portGroupData");
1188 clusterContainerService.destroyCache("frm.portGroupConfigs");
1189 nonClusterObjectCreate();
1192 private boolean flowConfigExists(FlowConfig config) {
1193 // As per customer requirement, flow name has to be unique on per node
1195 for (FlowConfig fc : staticFlows.values()) {
1196 if (fc.isByNameAndNodeIdEqual(config)) {
1204 public Status addStaticFlow(FlowConfig config, boolean restore) {
1205 StringBuffer resultStr = new StringBuffer();
1206 boolean multipleFlowPush = false;
1209 config.setStatus(StatusCode.SUCCESS.toString());
1212 if (flowConfigExists(config)) {
1213 error = "Entry with this name on specified switch already exists";
1214 config.setStatus(error);
1215 return new Status(StatusCode.CONFLICT, error);
1218 // Skip validation check if we are trying to restore a saved config
1219 if (!restore && !config.isValid(container, resultStr)) {
1220 log.debug(resultStr.toString());
1221 error = "Invalid Configuration (" + resultStr.toString() + ")";
1222 config.setStatus(error);
1223 return new Status(StatusCode.BADREQUEST, error);
1226 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1227 for (String portGroupName : portGroupConfigs.keySet()) {
1228 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1229 multipleFlowPush = true;
1233 if (!multipleFlowPush) {
1234 log.debug(resultStr.toString());
1235 error = "Invalid Configuration (Invalid PortGroup Name)";
1236 config.setStatus(error);
1237 return new Status(StatusCode.BADREQUEST, error);
1242 * If requested program the entry in hardware first before updating the
1245 if (!multipleFlowPush) {
1247 if (config.installInHw()) {
1248 FlowEntry entry = config.getFlowEntry();
1249 status = this.addEntry(entry);
1250 if (!status.isSuccess()) {
1251 config.setStatus(status.getDescription());
1260 * When the control reaches this point, either of the following
1261 * conditions is true 1. This is a single entry configuration (non
1262 * PortGroup) and the hardware installation is successful 2. This is a
1263 * multiple entry configuration (PortGroup) and hardware installation is
1264 * NOT done directly on this event. 3. The User prefers to retain the
1265 * configuration in Controller and skip hardware installation.
1267 * Hence it is safe to update the StaticFlow DB at this point.
1269 * Note : For the case of PortGrouping, it is essential to have this DB
1270 * populated before the PortGroupListeners can query for the DB
1271 * triggered using portGroupChanged event...
1273 Integer ordinal = staticFlowsOrdinal.get(0);
1274 staticFlowsOrdinal.put(0, ++ordinal);
1275 staticFlows.put(ordinal, config);
1277 if (multipleFlowPush) {
1278 PortGroupConfig pgconfig = portGroupConfigs.get(config
1280 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1281 if (existingData != null) {
1282 portGroupChanged(pgconfig, existingData, true);
1285 return new Status(StatusCode.SUCCESS, null);
1288 private void addStaticFlowsToSwitch(Node node) {
1289 for (FlowConfig config : staticFlows.values()) {
1290 if (config.isPortGroupEnabled()) {
1293 if (config.getNode().equals(node)) {
1294 if (config.installInHw()
1295 && !config.getStatus().equals(
1296 StatusCode.SUCCESS.toString())) {
1297 Status status = this.addEntry(config.getFlowEntry());
1298 config.setStatus(status.getDescription());
1304 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1305 log.trace("Updating Static Flow configs on node down: " + node);
1307 List<Integer> toRemove = new ArrayList<Integer>();
1308 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1310 FlowConfig config = entry.getValue();
1312 if (config.isPortGroupEnabled()) {
1316 if (config.installInHw() && config.getNode().equals(node)) {
1317 if (config.isInternalFlow()) {
1318 // Take note of this controller generated static flow
1319 toRemove.add(entry.getKey());
1321 config.setStatus(NODEDOWN);
1325 // Remove controller generated static flows for this node
1326 for (Integer index : toRemove) {
1327 staticFlows.remove(index);
1331 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1332 log.trace("Updating Static Flow configs on container mode change: "
1335 for (FlowConfig config : staticFlows.values()) {
1336 if (config.isPortGroupEnabled()) {
1339 if (config.installInHw()) {
1342 config.setStatus("Removed from node because in container mode");
1345 config.setStatus(StatusCode.SUCCESS.toString());
1353 public Status removeStaticFlow(FlowConfig config) {
1355 * No config.isInternal() check as NB does not take this path and GUI
1356 * cannot issue a delete on an internal generated flow. We need this
1357 * path to be accessible when switch mode is changed from proactive to
1358 * reactive, so that we can remove the internal generated LLDP and ARP
1361 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1362 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1363 // Program the network node
1364 Status status = this.removeEntry(config.getFlowEntry());
1365 // Update configuration database if programming was successful
1366 if (status.isSuccess()) {
1367 staticFlows.remove(entry.getKey());
1370 entry.getValue().setStatus(status.getDescription());
1375 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1379 public Status removeStaticFlow(String name, Node node) {
1380 for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1381 FlowConfig entry = mapEntry.getValue();
1382 Status status = new Status(null, null);
1383 if (entry.isByNameAndNodeIdEqual(name, node)) {
1384 // Validity check for api3 entry point
1385 if (entry.isInternalFlow()) {
1386 String msg = "Invalid operation: Controller generated "
1387 + "flow cannot be deleted";
1389 return new Status(StatusCode.NOTACCEPTABLE, msg);
1391 if (!entry.isPortGroupEnabled()) {
1392 // Program the network node
1393 status = this.removeEntry(entry.getFlowEntry());
1395 // Update configuration database if programming was successful
1396 if (status.isSuccess()) {
1397 staticFlows.remove(mapEntry.getKey());
1400 entry.setStatus(status.getDescription());
1405 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1408 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1409 // Validity check for api3 entry point
1410 if (newFlowConfig.isInternalFlow()) {
1411 String msg = "Invalid operation: Controller generated flow "
1412 + "cannot be modified";
1414 return new Status(StatusCode.NOTACCEPTABLE, msg);
1418 StringBuffer resultStr = new StringBuffer();
1419 if (!newFlowConfig.isValid(container, resultStr)) {
1420 String msg = "Invalid Configuration (" + resultStr.toString() + ")";
1421 newFlowConfig.setStatus(msg);
1423 return new Status(StatusCode.BADREQUEST, msg);
1426 FlowConfig oldFlowConfig = null;
1427 Integer index = null;
1428 for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1429 FlowConfig entry = mapEntry.getValue();
1430 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(),
1431 newFlowConfig.getNode())) {
1432 oldFlowConfig = entry;
1433 index = mapEntry.getKey();
1438 if (oldFlowConfig == null) {
1439 String msg = "Attempt to modify a non existing static flow";
1441 return new Status(StatusCode.NOTFOUND, msg);
1444 // Do not attempt to reinstall the flow, warn user
1445 if (newFlowConfig.equals(oldFlowConfig)) {
1446 String msg = "No modification detected";
1447 log.info("Static flow modification skipped: " + msg);
1448 return new Status(StatusCode.SUCCESS, msg);
1451 // If flow is installed, program the network node
1452 Status status = new Status(StatusCode.SUCCESS, "Saved in config");
1453 if (oldFlowConfig.installInHw()) {
1454 status = this.modifyEntry(oldFlowConfig.getFlowEntry(),
1455 newFlowConfig.getFlowEntry());
1458 // Update configuration database if programming was successful
1459 if (status.isSuccess()) {
1460 newFlowConfig.setStatus(status.getDescription());
1461 staticFlows.put(index, newFlowConfig);
1468 public Status toggleStaticFlowStatus(String name, Node node) {
1469 return toggleStaticFlowStatus(getStaticFlow(name, node));
1473 public Status toggleStaticFlowStatus(FlowConfig config) {
1474 if (config == null) {
1475 String msg = "Invalid request: null flow config";
1477 return new Status(StatusCode.BADREQUEST, msg);
1479 // Validity check for api3 entry point
1480 if (config.isInternalFlow()) {
1481 String msg = "Invalid operation: Controller generated flow "
1482 + "cannot be modified";
1484 return new Status(StatusCode.NOTACCEPTABLE, msg);
1487 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1488 FlowConfig conf = entry.getValue();
1489 if (conf.isByNameAndNodeIdEqual(config)) {
1490 // Program the network node
1491 Status status = new Status(StatusCode.SUCCESS, null);
1492 if (conf.installInHw()) {
1493 status = this.removeEntry(conf.getFlowEntry());
1495 status = this.addEntry(conf.getFlowEntry());
1497 if (!status.isSuccess()) {
1498 conf.setStatus(status.getDescription());
1502 // Update Configuration database
1503 conf.setStatus(StatusCode.SUCCESS.toString());
1504 conf.toggleStatus();
1508 return new Status(StatusCode.NOTFOUND,
1509 "Unable to locate the entry. Failed to toggle status");
1513 * Uninstall all the Flow Entries present in the software view A copy of
1514 * each entry is stored in the inactive list so that it can be re-applied
1515 * when needed This function is called on the default container instance of
1516 * FRM only when the first container is created
1518 private void uninstallAllFlowEntries() {
1519 log.info("Uninstalling all flows");
1521 // Store entries / create target list
1522 for (ConcurrentMap.Entry<Node, Set<FlowEntryInstall>> mapEntry : nodeFlows
1524 for (FlowEntryInstall flowEntries : mapEntry.getValue()) {
1525 inactiveFlows.add(flowEntries.getOriginal());
1529 // Now remove the entries
1530 for (FlowEntry flowEntry : inactiveFlows) {
1531 Status status = this.removeEntry(flowEntry);
1532 if (!status.isSuccess()) {
1534 "Failed to remove entry: {}: "
1535 + status.getDescription(), flowEntry);
1541 * Re-install all the Flow Entries present in the inactive list The inactive
1542 * list will be empty at the end of this call This function is called on the
1543 * default container instance of FRM only when the last container is deleted
1545 private void reinstallAllFlowEntries() {
1546 log.info("Reinstalling all inactive flows");
1548 for (FlowEntry flowEntry : this.inactiveFlows) {
1549 Status status = this.addEntry(flowEntry);
1550 if (!status.isSuccess()) {
1552 "Failed to install entry: {}: "
1553 + status.getDescription(), flowEntry);
1557 // Empty inactive list in any case
1558 inactiveFlows.clear();
1561 public List<FlowConfig> getStaticFlows() {
1562 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0)
1566 // TODO: need to come out with a better algorithm for mantaining the order
1567 // of the configuration entries
1568 // with actual one, index associated to deleted entries cannot be reused and
1570 private List<FlowConfig> getStaticFlowsOrderedList(
1571 ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1572 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1573 for (int i = 0; i <= maxKey; i++) {
1574 FlowConfig entry = flowMap.get(i);
1575 if (entry != null) {
1576 orderedList.add(entry);
1583 public FlowConfig getStaticFlow(String name, Node node) {
1584 for (FlowConfig config : staticFlows.values()) {
1585 if (config.isByNameAndNodeIdEqual(name, node)) {
1593 public List<FlowConfig> getStaticFlows(Node node) {
1594 List<FlowConfig> list = new ArrayList<FlowConfig>();
1595 for (FlowConfig config : staticFlows.values()) {
1596 if (config.onNode(node)) {
1604 public List<String> getStaticFlowNamesForNode(Node node) {
1605 List<String> list = new ArrayList<String>();
1606 for (FlowConfig config : staticFlows.values()) {
1607 if (config.onNode(node)) {
1608 list.add(config.getName());
1615 public List<Node> getListNodeWithConfiguredFlows() {
1616 Set<Node> set = new HashSet<Node>();
1617 for (FlowConfig config : staticFlows.values()) {
1618 set.add(config.getNode());
1620 return new ArrayList<Node>(set);
1623 @SuppressWarnings("unchecked")
1624 private void loadFlowConfiguration() {
1625 ObjectReader objReader = new ObjectReader();
1626 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader
1627 .read(this, frmFileName);
1629 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader
1630 .read(this, portGroupFileName);
1632 if (pgConfig != null) {
1633 for (Map.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
1634 addPortGroupConfig(entry.getKey(), entry.getValue()
1635 .getMatchString(), true);
1639 if (confList == null) {
1644 for (Integer key : confList.keySet()) {
1645 if (key.intValue() > maxKey)
1646 maxKey = key.intValue();
1649 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
1650 addStaticFlow(conf, true);
1655 public Object readObject(ObjectInputStream ois)
1656 throws FileNotFoundException, IOException, ClassNotFoundException {
1657 return ois.readObject();
1660 public Status saveConfig() {
1661 // Publish the save config event to the cluster nodes
1662 flowsSaveEvent.put(new Date().getTime(), SAVE);
1663 return saveConfigInternal();
1666 private Status saveConfigInternal() {
1667 ObjectWriter objWriter = new ObjectWriter();
1668 ConcurrentHashMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1669 for (Integer ordinal : staticFlows.keySet()) {
1670 FlowConfig config = staticFlows.get(ordinal);
1671 // Do not save dynamic and controller generated static flows
1672 if (config.isDynamic() || config.isInternalFlow()) {
1675 nonDynamicFlows.put(ordinal, config);
1677 objWriter.write(nonDynamicFlows, frmFileName);
1678 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(
1679 portGroupConfigs), portGroupFileName);
1680 return new Status(StatusCode.SUCCESS, null);
1684 public void entryCreated(Long key, String cacheName, boolean local) {
1688 public void entryUpdated(Long key, String new_value, String cacheName,
1689 boolean originLocal) {
1690 saveConfigInternal();
1694 public void entryDeleted(Long key, String cacheName, boolean originLocal) {
1698 public void subnetNotify(Subnet sub, boolean add) {
1701 private void installImplicitARPReplyPunt(Node node) {
1707 List<String> puntAction = new ArrayList<String>();
1708 puntAction.add(ActionType.CONTROLLER.toString());
1710 FlowConfig allowARP = new FlowConfig();
1711 allowARP.setInstallInHw(true);
1712 allowARP.setName("**Punt ARP Reply");
1713 allowARP.setPriority("500");
1714 allowARP.setNode(node);
1715 allowARP.setEtherType("0x"
1716 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1717 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager
1718 .getControllerMAC()));
1719 allowARP.setActions(puntAction);
1720 addStaticFlow(allowARP, false);
1724 public void modeChangeNotify(Node node, boolean proactive) {
1725 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
1727 List<String> puntAction = new ArrayList<String>();
1728 puntAction.add(ActionType.CONTROLLER.toString());
1730 FlowConfig allowARP = new FlowConfig();
1731 allowARP.setInstallInHw(true);
1732 allowARP.setName("**Punt ARP");
1733 allowARP.setPriority("1");
1734 allowARP.setNode(node);
1735 allowARP.setEtherType("0x"
1736 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1737 allowARP.setActions(puntAction);
1738 defaultConfigs.add(allowARP);
1740 FlowConfig allowLLDP = new FlowConfig();
1741 allowLLDP.setInstallInHw(true);
1742 allowLLDP.setName("**Punt LLDP");
1743 allowLLDP.setPriority("1");
1744 allowLLDP.setNode(node);
1747 + Integer.toHexString(EtherTypes.LLDP.intValue())
1749 allowLLDP.setActions(puntAction);
1750 defaultConfigs.add(allowLLDP);
1752 List<String> dropAction = new ArrayList<String>();
1753 dropAction.add(ActionType.DROP.toString());
1755 FlowConfig dropAllConfig = new FlowConfig();
1756 dropAllConfig.setInstallInHw(true);
1757 dropAllConfig.setName("**Catch-All Drop");
1758 dropAllConfig.setPriority("0");
1759 dropAllConfig.setNode(node);
1760 dropAllConfig.setActions(dropAction);
1761 defaultConfigs.add(dropAllConfig);
1763 for (FlowConfig fc : defaultConfigs) {
1765 addStaticFlow(fc, false);
1767 removeStaticFlow(fc);
1771 log.info("Set Switch {} Mode to {}", node, proactive);
1775 * Remove from the databases all the flows installed on the node
1779 private synchronized void cleanDatabaseForNode(Node node) {
1780 log.info("Cleaning Flow database for Node " + node.toString());
1782 // Find out which groups the node's flows are part of
1783 Set<String> affectedGroups = new HashSet<String>();
1784 Set<FlowEntryInstall> flowEntryList = nodeFlows.get(node);
1785 if (flowEntryList != null) {
1786 for (FlowEntryInstall entry : flowEntryList) {
1787 String groupName = entry.getGroupName();
1788 if (groupName != null) {
1789 affectedGroups.add(groupName);
1794 // Remove the node's flows from the group indexed flow database
1795 if (!affectedGroups.isEmpty()) {
1796 for (String group : affectedGroups) {
1797 Set<FlowEntryInstall> flowList = groupFlows.get(group);
1798 Set<FlowEntryInstall> toRemove = new HashSet<FlowEntryInstall>();
1799 for (FlowEntryInstall entry : flowList) {
1800 if (node.equals(entry.getNode())) {
1801 toRemove.add(entry);
1804 flowList.removeAll(toRemove);
1805 if (flowList.isEmpty()) {
1806 groupFlows.remove(group);
1811 // Remove the node's flows from the node indexed flow database
1812 nodeFlows.remove(node);
1816 public void notifyNode(Node node, UpdateType type,
1817 Map<String, Property> propMap) {
1820 addStaticFlowsToSwitch(node);
1823 cleanDatabaseForNode(node);
1824 updateStaticFlowConfigsOnNodeDown(node);
1832 public void notifyNodeConnector(NodeConnector nodeConnector,
1833 UpdateType type, Map<String, Property> propMap) {
1836 private FlowConfig getDerivedFlowConfig(FlowConfig original,
1837 String configName, Short port) {
1838 FlowConfig derivedFlow = new FlowConfig(original);
1839 derivedFlow.setDynamic(true);
1840 derivedFlow.setPortGroup(null);
1841 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
1842 derivedFlow.setIngressPort(port + "");
1846 private void addPortGroupFlows(PortGroupConfig config, Node node,
1848 for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
1850 FlowConfig staticFlow = it.next();
1851 if (staticFlow.getPortGroup() == null) {
1854 if ((staticFlow.getNode().equals(node))
1855 && (staticFlow.getPortGroup().equals(config.getName()))) {
1856 for (Short port : data.getPorts()) {
1857 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
1858 config.getName(), port);
1859 addStaticFlow(derivedFlow, false);
1865 private void removePortGroupFlows(PortGroupConfig config, Node node,
1867 for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
1869 FlowConfig staticFlow = it.next();
1870 if (staticFlow.getPortGroup() == null) {
1873 if ((staticFlow.getNode().equals(node))
1874 && (staticFlow.getPortGroup().equals(config.getName()))) {
1875 for (Short port : data.getPorts()) {
1876 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
1877 config.getName(), port);
1878 removeStaticFlow(derivedFlow);
1885 public void portGroupChanged(PortGroupConfig config,
1886 Map<Node, PortGroup> data, boolean add) {
1887 log.info("PortGroup Changed for :" + config + " Data: " + portGroupData);
1888 Map<Node, PortGroup> existingData = portGroupData.get(config);
1889 if (existingData != null) {
1890 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
1891 PortGroup existingPortGroup = existingData.get(entry.getKey());
1892 if (existingPortGroup == null) {
1894 existingData.put(entry.getKey(), entry.getValue());
1895 addPortGroupFlows(config, entry.getKey(),
1900 existingPortGroup.getPorts().addAll(
1901 entry.getValue().getPorts());
1902 addPortGroupFlows(config, entry.getKey(),
1905 existingPortGroup.getPorts().removeAll(
1906 entry.getValue().getPorts());
1907 removePortGroupFlows(config, entry.getKey(),
1914 portGroupData.put(config, data);
1915 for (Node swid : data.keySet()) {
1916 addPortGroupFlows(config, swid, data.get(swid));
1922 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
1923 PortGroupConfig config = portGroupConfigs.get(name);
1927 if ((portGroupProvider == null) && !restore) {
1930 if ((portGroupProvider != null)
1931 && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
1935 config = new PortGroupConfig(name, regex);
1936 portGroupConfigs.put(name, config);
1937 if (portGroupProvider != null) {
1938 portGroupProvider.createPortGroupConfig(config);
1943 public boolean delPortGroupConfig(String name) {
1944 PortGroupConfig config = portGroupConfigs.get(name);
1945 if (config == null) {
1949 if (portGroupProvider != null) {
1950 portGroupProvider.deletePortGroupConfig(config);
1952 portGroupConfigs.remove(name);
1956 private void usePortGroupConfig(String name) {
1957 PortGroupConfig config = portGroupConfigs.get(name);
1958 if (config == null) {
1961 if (portGroupProvider != null) {
1962 Map<Node, PortGroup> data = portGroupProvider
1963 .getPortGroupData(config);
1964 portGroupData.put(config, data);
1969 public Map<String, PortGroupConfig> getPortGroupConfigs() {
1970 return portGroupConfigs;
1973 public boolean isPortGroupSupported() {
1974 if (portGroupProvider == null) {
1980 // Fir PortGroupProvider to use regular Dependency Manager
1981 /* @SuppressWarnings("rawtypes") */
1982 /* public void bind(Object arg0, Map arg1) throws Exception { */
1983 /* if (arg0 instanceof PortGroupProvider) { */
1984 /* setPortGroupProvider((PortGroupProvider)arg0); */
1988 /* @SuppressWarnings("rawtypes") */
1990 /* public void unbind(Object arg0, Map arg1) throws Exception { */
1991 /* if (arg0 instanceof PortGroupProvider) { */
1992 /* portGroupProvider = null; */
1996 public void setIContainer(IContainer s) {
2000 public void unsetIContainer(IContainer s) {
2001 if (this.container == s) {
2002 this.container = null;
2006 public PortGroupProvider getPortGroupProvider() {
2007 return portGroupProvider;
2010 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2011 this.portGroupProvider = null;
2014 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2015 this.portGroupProvider = portGroupProvider;
2016 portGroupProvider.registerPortGroupChange(this);
2017 for (PortGroupConfig config : portGroupConfigs.values()) {
2018 portGroupProvider.createPortGroupConfig(config);
2022 public void setHostFinder(IfIptoHost hostFinder) {
2023 this.hostFinder = hostFinder;
2026 public void unsetHostFinder(IfIptoHost hostFinder) {
2027 if (this.hostFinder == hostFinder) {
2028 this.hostFinder = null;
2032 public void setFrmAware(IForwardingRulesManagerAware obj) {
2033 this.frmAware.add(obj);
2036 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2037 this.frmAware.remove(obj);
2040 void setClusterContainerService(IClusterContainerServices s) {
2041 log.debug("Cluster Service set");
2042 this.clusterContainerService = s;
2045 void unsetClusterContainerService(IClusterContainerServices s) {
2046 if (this.clusterContainerService == s) {
2047 log.debug("Cluster Service removed!");
2048 this.clusterContainerService = null;
2052 private String getContainerName() {
2053 if (container == null) {
2054 return GlobalConstants.DEFAULT.toString();
2056 return container.getName();
2060 * Function called by the dependency manager when all the required
2061 * dependencies are satisfied
2065 frmAware = Collections
2066 .synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
2067 frmFileName = GlobalConstants.STARTUPHOME.toString()
2068 + "frm_staticflows_" + this.getContainerName() + ".conf";
2069 portGroupFileName = GlobalConstants.STARTUPHOME.toString()
2070 + "portgroup_" + this.getContainerName() + ".conf";
2072 inContainerMode = false;
2074 if (portGroupProvider != null) {
2075 portGroupProvider.registerPortGroupChange(this);
2078 nonClusterObjectCreate();
2082 registerWithOSGIConsole();
2085 * If we are not the first cluster node to come up, do not initialize
2086 * the static flow entries ordinal
2088 if (staticFlowsOrdinal.size() == 0) {
2089 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2094 * Function called by the dependency manager when at least one dependency
2095 * become unsatisfied or when the component is shutting down because for
2096 * example bundle is being stopped.
2104 * Function called by dependency manager after "init ()" is called and after
2105 * the services provided by the class are registered in the service registry
2110 * Read startup and build database if we have not already gotten the
2111 * configurations synced from another node
2113 if (staticFlows.isEmpty()) {
2114 loadFlowConfiguration();
2119 * Function called by the dependency manager before the services exported by
2120 * the component are unregistered, this will be followed by a "destroy ()"
2127 public void setFlowProgrammerService(IFlowProgrammerService service) {
2128 this.programmer = service;
2131 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2132 if (this.programmer == service) {
2133 this.programmer = null;
2137 public void setSwitchManager(ISwitchManager switchManager) {
2138 this.switchManager = switchManager;
2141 public void unsetSwitchManager(ISwitchManager switchManager) {
2142 if (this.switchManager == switchManager) {
2143 this.switchManager = null;
2148 public void tagUpdated(String containerName, Node n, short oldTag,
2149 short newTag, UpdateType t) {
2154 public void containerFlowUpdated(String containerName,
2155 ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
2157 * Whether it is an addition or removal, we have to recompute the merged
2158 * flows entries taking into account all the current container flows
2159 * because flow merging is not an injective function
2161 updateFlowsContainerFlow();
2165 public void nodeConnectorUpdated(String containerName, NodeConnector p,
2171 public void containerModeUpdated(UpdateType update) {
2174 this.inContainerMode = true;
2175 this.uninstallAllFlowEntries();
2178 this.inContainerMode = false;
2179 this.reinstallAllFlowEntries();
2184 // Update our configuration DB
2185 updateStaticFlowConfigsOnContainerModeChange(update);
2192 public String getHelp() {
2193 StringBuffer help = new StringBuffer();
2194 help.append("---FRM Matrix Application---\n");
2195 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2196 help.append("\t addMatrixConfig <name> <regex>\n");
2197 help.append("\t delMatrixConfig <name>\n");
2198 help.append("\t useMatrixConfig <name>\n");
2199 return help.toString();
2202 public void _printMatrixData(CommandInterpreter ci) {
2203 ci.println("Configs : ");
2204 ci.println("---------");
2205 ci.println(portGroupConfigs);
2207 ci.println("Data : ");
2208 ci.println("------");
2209 ci.println(portGroupData);
2212 public void _addMatrixConfig(CommandInterpreter ci) {
2213 String name = ci.nextArgument();
2214 String regex = ci.nextArgument();
2215 addPortGroupConfig(name, regex, false);
2218 public void _delMatrixConfig(CommandInterpreter ci) {
2219 String name = ci.nextArgument();
2220 delPortGroupConfig(name);
2223 public void _useMatrixConfig(CommandInterpreter ci) {
2224 String name = ci.nextArgument();
2225 usePortGroupConfig(name);
2228 public void _arpPunt(CommandInterpreter ci) {
2229 String switchId = ci.nextArgument();
2230 long swid = HexEncode.stringToLong(switchId);
2231 Node node = NodeCreator.createOFNode(swid);
2232 installImplicitARPReplyPunt(node);
2235 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2237 String nodeId = ci.nextArgument();
2238 if (nodeId == null) {
2239 ci.print("Node id not specified");
2243 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2244 } catch (NumberFormatException e) {
2245 e.printStackTrace();
2247 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2250 public void _frmremoveflow(CommandInterpreter ci)
2251 throws UnknownHostException {
2253 String nodeId = ci.nextArgument();
2254 if (nodeId == null) {
2255 ci.print("Node id not specified");
2259 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2260 } catch (NumberFormatException e) {
2261 e.printStackTrace();
2263 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2266 private Flow getSampleFlow(Node node) throws UnknownHostException {
2267 NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
2269 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector(
2271 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,
2272 (byte) 0x9a, (byte) 0xbc };
2273 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d,
2274 (byte) 0x5e, (byte) 0x6f };
2275 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2276 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2277 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2278 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2279 short ethertype = EtherTypes.IPv4.shortValue();
2280 short vlan = (short) 27;
2283 byte proto = IPProtocols.TCP.byteValue();
2284 short src = (short) 55000;
2288 * Create a SAL Flow aFlow
2290 Match match = new Match();
2291 match.setField(MatchType.IN_PORT, port);
2292 match.setField(MatchType.DL_SRC, srcMac);
2293 match.setField(MatchType.DL_DST, dstMac);
2294 match.setField(MatchType.DL_TYPE, ethertype);
2295 match.setField(MatchType.DL_VLAN, vlan);
2296 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2297 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2298 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2299 match.setField(MatchType.NW_TOS, tos);
2300 match.setField(MatchType.NW_PROTO, proto);
2301 match.setField(MatchType.TP_SRC, src);
2302 match.setField(MatchType.TP_DST, dst);
2304 List<Action> actions = new ArrayList<Action>();
2305 actions.add(new Output(oport));
2306 actions.add(new PopVlan());
2307 actions.add(new Flood());
2308 actions.add(new Controller());
2309 return new Flow(match, actions);
2313 public Status saveConfiguration() {
2314 return saveConfig();
2317 public void _frmNodeFlows(CommandInterpreter ci) {
2318 boolean verbose = false;
2319 String verboseCheck = ci.nextArgument();
2320 if (verboseCheck != null) {
2321 verbose = verboseCheck.equals("true");
2324 // Dump per node database
2325 for (Entry<Node, Set<FlowEntryInstall>> entry : this.nodeFlows
2327 Node node = entry.getKey();
2328 for (FlowEntryInstall flow : entry.getValue()) {
2330 ci.println(node + " " + flow.getFlowName());
2332 ci.println(node + " " + flow.toString());
2338 public void _frmGroupFlows(CommandInterpreter ci) {
2339 boolean verbose = false;
2340 String verboseCheck = ci.nextArgument();
2341 if (verboseCheck != null) {
2342 verbose = verboseCheck.equalsIgnoreCase("true");
2345 // Dump per node database
2346 for (Entry<String, Set<FlowEntryInstall>> entry : this.groupFlows
2348 String group = entry.getKey();
2349 ci.println("Group " + group + ":");
2350 for (FlowEntryInstall flow : entry.getValue()) {
2352 ci.println(flow.getNode() + " " + flow.getFlowName());
2354 ci.println(flow.getNode() + " " + flow.toString());