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.IFlowProgrammerListener;
63 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
64 import org.opendaylight.controller.sal.match.Match;
65 import org.opendaylight.controller.sal.match.MatchType;
66 import org.opendaylight.controller.sal.utils.StatusCode;
67 import org.opendaylight.controller.sal.utils.EtherTypes;
68 import org.opendaylight.controller.sal.utils.GlobalConstants;
69 import org.opendaylight.controller.sal.utils.HexEncode;
70 import org.opendaylight.controller.sal.utils.IObjectReader;
71 import org.opendaylight.controller.sal.utils.IPProtocols;
72 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
73 import org.opendaylight.controller.sal.utils.NodeCreator;
74 import org.opendaylight.controller.sal.utils.ObjectReader;
75 import org.opendaylight.controller.sal.utils.ObjectWriter;
76 import org.opendaylight.controller.sal.utils.Status;
77 import org.opendaylight.controller.switchmanager.IInventoryListener;
78 import org.opendaylight.controller.switchmanager.ISwitchManager;
79 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
80 import org.opendaylight.controller.switchmanager.Subnet;
81 import org.osgi.framework.BundleContext;
82 import org.osgi.framework.FrameworkUtil;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 * Class that manages forwarding rule installation and removal per container of
88 * the network. It also maintains the central repository of all the forwarding
89 * rules installed on the network nodes.
91 public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
92 PortGroupChangeListener, IContainerListener, ISwitchManagerAware,
93 IConfigurationContainerAware, IInventoryListener, IObjectReader,
94 ICacheUpdateAware<Long, String>, CommandProvider,
95 IFlowProgrammerListener {
96 private static final String SAVE = "Save";
97 private static final String NODEDOWN = "Node is Down";
98 private static final Logger log = LoggerFactory
99 .getLogger(ForwardingRulesManagerImpl.class);
100 private Map<Long, String> flowsSaveEvent;
101 private String frmFileName;
102 private String portGroupFileName;
103 private ConcurrentMap<Integer, FlowConfig> staticFlows;
104 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
105 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
106 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
107 private ConcurrentMap<String, Object> TSPolicies;
108 private boolean inContainerMode; // being used by default instance only
110 * Flow database. It's the software view of what was installed on the
111 * switch. It is indexed by node. For convenience a version indexed by group
112 * name is also maintained. The core element is a class which contains the
113 * flow entry pushed by the functional modules and the respective container
114 * flow merged version. In absence of container flows, the two flow entries
117 private ConcurrentMap<Node, Set<FlowEntryInstall>> nodeFlows;
118 private ConcurrentMap<String, Set<FlowEntryInstall>> groupFlows;
120 * Inactive flow list. This is for the global instance of FRM It will
121 * contain all the flow entries which were installed on the global container
122 * when the first container is created.
124 private List<FlowEntry> inactiveFlows;
126 private IfIptoHost hostFinder;
127 private IContainer container;
128 private Set<IForwardingRulesManagerAware> frmAware;
129 private PortGroupProvider portGroupProvider;
130 private IFlowProgrammerService programmer;
131 private IClusterContainerServices clusterContainerService = null;
132 private ISwitchManager switchManager;
135 * Adds a flow entry onto the network node It runs various validity checks
136 * and derive the final container flows merged entries that will be
137 * attempted to be installed
140 * the original flow entry application requested to add
143 private Status addEntry(FlowEntry flowEntry) {
145 if (flowEntry == null || flowEntry.getNode() == null) {
146 String msg = "Invalid FlowEntry";
147 log.warn(msg + ": " + flowEntry);
148 return new Status(StatusCode.NOTACCEPTABLE, msg);
152 * Derive the container flow merged entries to install In presence of N
153 * container flows, we may end up with N different entries to install...
155 List<FlowEntryInstall> toInstallList = deriveInstallEntries(
156 flowEntry.clone(), container.getContainerFlows());
158 // Container Flow conflict Check
159 if (toInstallList.isEmpty()) {
160 String msg = "Flow Entry conflicts with all Container Flows";
162 return new Status(StatusCode.CONFLICT, msg);
165 // Derive the list of entries good to be installed
166 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
167 for (FlowEntryInstall entry : toInstallList) {
168 // Conflict Check: Verify new entry would not overwrite existing
170 if (findMatch(entry.getInstall(), false) != null) {
171 log.warn("Operation Rejected: A flow with same match "
172 + "and priority exists on the target node");
173 log.trace("Aborting to install " + entry);
176 toInstallSafe.add(entry);
179 // Declare failure if all the container flow merged entries clash with
181 if (toInstallSafe.size() == 0) {
182 String msg = "A flow with same match and priority exists "
183 + "on the target node";
185 return new Status(StatusCode.CONFLICT, msg);
188 // Try to install an entry at the time
189 Status error = new Status(null, null);
190 boolean oneSucceded = false;
191 for (FlowEntryInstall installEntry : toInstallList) {
193 // Install and update database
194 Status ret = addEntriesInternal(installEntry);
196 if (ret.isSuccess()) {
200 log.warn("Failed to install the entry: " + ret.getDescription());
204 return (oneSucceded) ? new Status(StatusCode.SUCCESS, null) : error;
208 * Given a flow entry and the list of container flows, it returns the list
209 * of container flow merged flow entries good to be installed on this
210 * container. If the list of container flows is null or empty, the install
211 * entry list will contain only one entry, the original flow entry. If the
212 * flow entry is congruent with all the N container flows, then the output
213 * install entry list will contain N entries. If the output list is empty,
214 * it means the passed flow entry conflicts with all the container flows.
217 * The list of container flows
218 * @return the list of container flow merged entries good to be installed on
221 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request,
222 List<ContainerFlow> cFlowList) {
223 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(
226 if (container.getContainerFlows() == null
227 || container.getContainerFlows().isEmpty()) {
228 // No container flows => entry good to be installed unchanged
229 toInstallList.add(new FlowEntryInstall(request.clone(), null));
231 // Create the list of entries to be installed. If the flow entry is
232 // not congruent with any container flow, no install entries will be
234 for (ContainerFlow cFlow : container.getContainerFlows()) {
235 if (cFlow.allowsFlow(request.getFlow())) {
236 toInstallList.add(new FlowEntryInstall(request.clone(),
241 return toInstallList;
245 * Modify a flow entry with a new one It runs various validity check and
246 * derive the final container flows merged flow entries to work with
248 * @param currentFlowEntry
249 * @param newFlowEntry
250 * @return Success or error string
252 private Status modifyEntry(FlowEntry currentFlowEntry,
253 FlowEntry newFlowEntry) {
257 if (currentFlowEntry == null || currentFlowEntry.getNode() == null
258 || newFlowEntry == null || newFlowEntry.getNode() == null) {
259 String msg = "Modify: Invalid FlowEntry";
260 log.warn(msg + ": {} or {} ", currentFlowEntry, newFlowEntry);
261 return new Status(StatusCode.NOTACCEPTABLE, msg);
263 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
264 || !currentFlowEntry.getFlowName().equals(
265 newFlowEntry.getFlowName())) {
266 String msg = "Modify: Incompatible Flow Entries";
267 log.warn(msg + ": {} and {}", currentFlowEntry, newFlowEntry);
268 return new Status(StatusCode.NOTACCEPTABLE, msg);
272 if (currentFlowEntry.equals(newFlowEntry)) {
273 String msg = "Modify skipped as flows are the same";
274 log.debug(msg + ": " + currentFlowEntry + " and " + newFlowEntry);
275 return new Status(StatusCode.SUCCESS, msg);
278 // Conflict Check: Verify the new entry would not conflict with another
280 // This is a loose check on the previous original flow entry requests.
282 // on the container flow merged flow entries (if any) yet
283 FlowEntryInstall sameMatchOriginalEntry = findMatch(newFlowEntry, true);
284 if (sameMatchOriginalEntry != null
285 && !sameMatchOriginalEntry.getOriginal().equals(
287 String msg = "Operation Rejected: Another flow with same match "
288 + "and priority exists on the target node";
290 return new Status(StatusCode.CONFLICT, msg);
293 // Derive the installed and toInstall entries
294 List<FlowEntryInstall> installedList = deriveInstallEntries(
295 currentFlowEntry.clone(), container.getContainerFlows());
296 List<FlowEntryInstall> toInstallList = deriveInstallEntries(
297 newFlowEntry.clone(), container.getContainerFlows());
299 if (toInstallList.isEmpty()) {
300 String msg = "Modify Operation Rejected: The new entry "
301 + "conflicts with all the container flows";
303 return new Status(StatusCode.CONFLICT, msg);
307 * If the two list sizes differ, it means the new flow entry does not
308 * satisfy the same number of container flows the current entry does.
309 * This is only possible when the new entry and current entry have
310 * different match. In this scenario the modification would ultimately
311 * be handled as a remove and add operations in the protocol plugin.
313 * Also, if any of the new flow entries would clash with an existing
314 * one, we cannot proceed with the modify operation, because it would
315 * fail for some entries and leave stale entries on the network node.
316 * Modify path can be taken only if it can be performed completely, for
319 * So, for the above two cases, to simplify, let's decouple the modify
320 * in: 1) remove current entries 2) install new entries
322 boolean decouple = false;
323 if (installedList.size() != toInstallList.size()) {
324 log.info("Modify: New flow entry does not satisfy the same "
325 + "number of container flows as the original entry does");
328 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
329 for (FlowEntryInstall installEntry : toInstallList) {
330 // Conflict Check: Verify the new entry would not overwrite another
332 FlowEntryInstall sameMatchEntry = findMatch(
333 installEntry.getInstall(), false);
334 if (sameMatchEntry != null
335 && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
336 log.info("Modify: new container flow merged flow entry "
337 + "clashes with existing flow");
340 toInstallSafe.add(installEntry);
345 // Remove current entries
346 for (FlowEntryInstall currEntry : installedList) {
347 this.removeEntryInternal(currEntry);
349 // Install new entries
350 for (FlowEntryInstall newEntry : toInstallSafe) {
351 this.addEntriesInternal(newEntry);
355 * The two list have the same size and the entries to install do not
356 * clash with any existing flow on the network node. We assume here
357 * (and might be wrong) that the same container flows that were
358 * satisfied by the current entries are the same that are satisfied
359 * by the new entries. Let's take the risk for now.
361 * Note: modification has to be complete. If any entry modification
362 * fails, we need to stop, restore the already modified entries, and
367 int size = toInstallList.size();
369 // Modify and update database
370 retModify = modifyEntryInternal(installedList.get(i),
371 toInstallList.get(i));
372 if (retModify.isSuccess()) {
378 // Check if uncompleted modify
380 log.warn("Unable to perform a complete modify for all "
381 + "the container flows merged entries");
382 // Restore original entries
385 log.info("Attempting to restore initial entries");
386 retExt = modifyEntryInternal(toInstallList.get(i),
387 installedList.get(i));
388 if (retExt.isSuccess()) {
394 // Fatal error, recovery failed
396 String msg = "Flow recovery failed ! Unrecoverable Error";
398 return new Status(StatusCode.INTERNALERROR, msg);
402 return new Status(StatusCode.SUCCESS, null);
406 * This is the function that modifies the final container flows merged
407 * entries on the network node and update the database. It expects that all
408 * the validity checks are passed
410 * @param currentEntries
414 private Status modifyEntryInternal(FlowEntryInstall currentEntries,
415 FlowEntryInstall newEntries) {
416 // Modify the flow on the network node
417 Status status = programmer.modifyFlow(currentEntries.getNode(),
418 currentEntries.getInstall().getFlow(), newEntries.getInstall()
421 if (!status.isSuccess()) {
422 log.warn("SDN Plugin failed to program the flow: "
423 + status.getDescription());
427 log.trace("Modified {} => {}", currentEntries.getInstall(),
428 newEntries.getInstall());
431 updateLocalDatabase(currentEntries, false);
432 updateLocalDatabase(newEntries, true);
438 * Remove a flow entry. If the entry is not present in the software view
439 * (entry or node not present), it return successfully
444 private Status removeEntry(FlowEntry flowEntry) {
445 Status error = new Status(null, null);
448 if (flowEntry == null || flowEntry.getNode() == null) {
449 String msg = "Invalid FlowEntry";
450 log.warn(msg + ": " + flowEntry);
451 return new Status(StatusCode.NOTACCEPTABLE, msg);
454 // Derive the container flows merged installed entries
455 List<FlowEntryInstall> installedList = deriveInstallEntries(
456 flowEntry.clone(), container.getContainerFlows());
458 Set<FlowEntryInstall> flowsOnNode = nodeFlows.get(flowEntry.getNode());
459 boolean atLeastOneRemoved = false;
460 for (FlowEntryInstall entry : installedList) {
461 if (flowsOnNode == null) {
462 String msg = "Removal skipped (Node down or Flow not on Node)";
463 log.debug(msg + " for flow entry " + flowEntry);
464 return new Status(StatusCode.SUCCESS, msg);
466 if (!flowsOnNode.contains(entry)) {
467 log.debug("Removal skipped (not present in software view) "
468 + "for flow entry " + flowEntry);
470 if (installedList.size() == 1) {
471 // If we had only one entry to remove, we are done
472 return new Status(StatusCode.SUCCESS, null);
478 // Remove and update DB
479 Status ret = removeEntryInternal(entry);
481 if (!ret.isSuccess()) {
483 log.warn("Failed to remove the entry: " + ret.getDescription());
484 if (installedList.size() == 1) {
485 // If we had only one entry to remove, this is fatal failure
489 atLeastOneRemoved = true;
494 * No worries if full removal failed. Consistency checker will take care
495 * of removing the stale entries later, or adjusting the software
496 * database if not in sync with hardware
498 return (atLeastOneRemoved) ? new Status(StatusCode.SUCCESS, null)
503 * This is the function that removes the final container flows merged entry
504 * from the network node and update the database. It expects that all the
505 * validity checks are passed
508 * the FlowEntryInstall
509 * @return "Success" or error string
511 private Status removeEntryInternal(FlowEntryInstall entry) {
512 // Mark the entry to be deleted (for CC just in case we fail)
516 Status status = programmer.removeFlow(entry.getNode(), entry
517 .getInstall().getFlow());
519 if (!status.isSuccess()) {
520 log.warn("SDN Plugin failed to remove the flow: "
521 + status.getDescription());
524 log.trace("Removed {}", entry.getInstall());
527 updateLocalDatabase(entry, false);
533 * This is the function that installs the final container flow merged entry
534 * on the network node and updates the database. It expects that all the
535 * validity and conflict checks are passed. That means it does not check
536 * whether this flow would conflict or overwrite an existing one.
539 * the FlowEntryInstall
540 * @return "Success" or error string
542 private Status addEntriesInternal(FlowEntryInstall entry) {
543 // Install the flow on the network node
544 Status status = programmer.addFlow(entry.getNode(), entry.getInstall()
547 if (!status.isSuccess()) {
548 log.warn("SDN Plugin failed to program the flow: "
549 + status.getDescription());
553 log.trace("Added {}", entry.getInstall());
556 updateLocalDatabase(entry, true);
562 * Returns true if the flow conflicts with all the container's flows. This
563 * means that if the function returns true, the passed flow entry is
564 * congruent with at least one container flow, hence it is good to be
565 * installed on this container.
568 * @return true if flow conflicts with all the container flows, false
571 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
572 List<ContainerFlow> cFlowList = container.getContainerFlows();
574 // Validity check and avoid unnecessary computation
575 // Also takes care of default container where no container flows are
577 if (cFlowList == null || cFlowList.isEmpty()) {
581 for (ContainerFlow cFlow : cFlowList) {
582 if (cFlow.allowsFlow(flowEntry.getFlow())) {
583 // Entry is allowed by at least one container flow: good to go
590 private synchronized void updateLocalDatabase(FlowEntryInstall entry,
592 // Update node indexed flow database
593 updateNodeFlowsDB(entry, add);
595 // Update group indexed flow database
596 updateGroupFlowsDB(entry, add);
600 * Update the node mapped flows database
602 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
603 Node node = flowEntries.getNode();
605 Set<FlowEntryInstall> flowEntrylist = this.nodeFlows.get(node);
606 if (flowEntrylist == null) {
610 flowEntrylist = new HashSet<FlowEntryInstall>();
615 flowEntrylist.add(flowEntries);
617 flowEntrylist.remove(flowEntries);
620 if (flowEntrylist.isEmpty()) {
621 this.nodeFlows.remove(node);
623 this.nodeFlows.put(node, flowEntrylist);
628 * Update the group name mapped flows database
630 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
631 Set<FlowEntryInstall> flowList;
632 FlowEntryInstall exists = null;
633 String flowName = flowEntries.getFlowName();
634 String groupName = flowEntries.getGroupName();
636 if (this.groupFlows == null) {
640 // Flow may not be part of a group
641 if (groupName == null) {
645 if (this.groupFlows.containsKey(groupName)) {
646 flowList = this.groupFlows.get(groupName);
651 flowList = new HashSet<FlowEntryInstall>();
655 for (FlowEntryInstall flow : flowList) {
656 if (flow.equalsByNodeAndName(flowEntries.getNode(), flowName)) {
662 if (exists == null && add == false) {
666 if (exists != null) {
667 flowList.remove(exists);
671 flowList.add(flowEntries);
674 if (flowList.isEmpty()) {
675 this.groupFlows.remove(groupName);
677 this.groupFlows.put(groupName, flowList);
682 * Remove a flow entry that has been added previously First checks if the
683 * entry is effectively present in the local database
685 @SuppressWarnings("unused")
686 private Status removeEntry(Node node, String flowName) {
687 FlowEntryInstall target = null;
690 for (FlowEntryInstall entry : this.nodeFlows.get(node)) {
691 if (entry.equalsByNodeAndName(node, flowName)) {
697 // If it is not there, stop any further processing
698 if (target == null) {
699 return new Status(StatusCode.SUCCESS, "Entry is not present");
703 Status status = programmer.removeFlow(target.getNode(), target
704 .getInstall().getFlow());
707 if (status.isSuccess()) {
708 updateLocalDatabase(target, false);
715 public Status installFlowEntry(FlowEntry flowEntry) {
717 if (inContainerMode) {
718 String msg = "Controller in container mode: Install Refused";
719 status = new Status(StatusCode.NOTACCEPTABLE, msg);
722 status = addEntry(flowEntry);
728 public Status uninstallFlowEntry(FlowEntry entry) {
730 if (inContainerMode) {
731 String msg = "Controller in container mode: Uninstall Refused";
732 status = new Status(StatusCode.NOTACCEPTABLE, msg);
735 status = removeEntry(entry);
741 public Status modifyFlowEntry(FlowEntry currentFlowEntry,
742 FlowEntry newFlowEntry) {
743 Status status = null;
744 if (inContainerMode) {
745 String msg = "Controller in container mode: Modify Refused";
746 status = new Status(StatusCode.NOTACCEPTABLE, msg);
749 status = modifyEntry(currentFlowEntry, newFlowEntry);
755 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
757 * Run a loose check on the installed entries to decide whether to go
758 * with a add or modify method. A loose check means only check against
759 * the original flow entry requests and not against the installed flow
760 * entries which are the result of the original entry merged with the
761 * container flow(s) (if any). The modifyFlowEntry method in presence of
762 * conflicts with the Container flows (if any) would revert back to a
763 * delete + add pattern
765 FlowEntryInstall currentFlowEntries = findMatch(newFlowEntry, true);
767 if (currentFlowEntries != null) {
768 return modifyFlowEntry(currentFlowEntries.getOriginal(),
771 return installFlowEntry(newFlowEntry);
776 * Try to find in the database if a Flow with the same Match and priority of
777 * the passed one already exists for the specified network node. Flow,
778 * priority and network node are all specified in the FlowEntry If found,
779 * the respective FlowEntryInstall Object is returned
782 * the FlowEntry to be tested against the ones installed
784 * if true, the function will run the check against the original
785 * flow entry portion of the installed entries
786 * @return null if not found, otherwise the FlowEntryInstall which contains
787 * the existing flow entry
789 private FlowEntryInstall findMatch(FlowEntry flowEntry, boolean looseCheck) {
790 Flow flow = flowEntry.getFlow();
791 Match match = flow.getMatch();
792 short priority = flow.getPriority();
793 Set<FlowEntryInstall> thisNodeList = nodeFlows.get(flowEntry.getNode());
795 if (thisNodeList != null) {
796 for (FlowEntryInstall flowEntries : thisNodeList) {
797 flow = (looseCheck == false) ? flowEntries.getInstall()
798 .getFlow() : flowEntries.getOriginal().getFlow();
799 if (flow.getMatch().equals(match)
800 && flow.getPriority() == priority) {
808 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
809 return entryConflictsWithContainerFlows(flowEntry);
813 * Updates all installed flows because the container flow got updated This
814 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
815 * Reinstall of all flows This is needed because a new container flows
816 * merged flow may conflict with an existing old container flows merged flow
817 * on the network node
819 private void updateFlowsContainerFlow() {
820 List<FlowEntryInstall> oldCouples = new ArrayList<FlowEntryInstall>();
821 List<FlowEntry> toReinstall = new ArrayList<FlowEntry>();
822 for (Entry<Node, Set<FlowEntryInstall>> entry : this.nodeFlows
826 if (entry.getValue() == null) {
829 // Create a set of old entries and one of original entries to be
831 for (FlowEntryInstall oldCouple : entry.getValue()) {
832 oldCouples.add(oldCouple);
833 toReinstall.add(oldCouple.getOriginal());
835 // Remove the old couples. No validity checks to be run, use the
837 for (FlowEntryInstall oldCouple : oldCouples) {
838 this.removeEntryInternal(oldCouple);
840 // Reinstall the original flow entries, via the regular path: new
841 // cFlow merge + validations
842 for (FlowEntry flowEntry : toReinstall) {
843 this.installFlowEntry(flowEntry);
848 public void nonClusterObjectCreate() {
849 nodeFlows = new ConcurrentHashMap<Node, Set<FlowEntryInstall>>();
850 TSPolicies = new ConcurrentHashMap<String, Object>();
851 groupFlows = new ConcurrentHashMap<String, Set<FlowEntryInstall>>();
852 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
853 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
854 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
855 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
856 flowsSaveEvent = new HashMap<Long, String>();
857 inactiveFlows = new ArrayList<FlowEntry>(1);
860 private void registerWithOSGIConsole() {
861 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
863 bundleContext.registerService(CommandProvider.class.getName(), this,
868 public void setTSPolicyData(String policyname, Object o, boolean add) {
871 /* Check if this policy already exists */
872 if (!(TSPolicies.containsKey(policyname))) {
873 TSPolicies.put(policyname, o);
876 TSPolicies.remove(policyname);
878 if (frmAware != null) {
879 synchronized (frmAware) {
880 for (IForwardingRulesManagerAware frma : frmAware) {
882 frma.policyUpdate(policyname, add);
883 } catch (Exception e) {
884 log.error("Exception on callback", e);
892 public Map<String, Object> getTSPolicyData() {
897 public Object getTSPolicyData(String policyName) {
898 if (TSPolicies.containsKey(policyName)) {
899 return TSPolicies.get(policyName);
906 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
907 List<FlowEntry> list = null;
908 if (this.groupFlows != null && this.groupFlows.containsKey(policyName)) {
909 list = new ArrayList<FlowEntry>();
910 for (FlowEntryInstall entries : groupFlows.get(policyName)) {
911 list.add(entries.getOriginal());
913 return new ArrayList<FlowEntry>();
919 public void addOutputPort(Node node, String flowName,
920 List<NodeConnector> portList) {
922 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
924 for (FlowEntryInstall flow : flowEntryList) {
925 if (flow.getFlowName().equals(flowName)) {
926 FlowEntry currentFlowEntry = flow.getOriginal();
927 FlowEntry newFlowEntry = currentFlowEntry.clone();
928 for (NodeConnector dstPort : portList) {
929 newFlowEntry.getFlow().addAction(new Output(dstPort));
931 Status error = modifyEntry(currentFlowEntry, newFlowEntry);
932 if (error.isSuccess()) {
933 log.info("Ports {} added to FlowEntry {}", portList,
936 log.warn("Failed to add ports {} to Flow entry {}: "
937 + error.getDescription(), portList,
938 currentFlowEntry.toString());
943 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found",
948 public void removeOutputPort(Node node, String flowName,
949 List<NodeConnector> portList) {
951 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
953 for (FlowEntryInstall flow : flowEntryList) {
954 if (flow.getFlowName().equals(flowName)) {
955 FlowEntry currentFlowEntry = flow.getOriginal();
956 FlowEntry newFlowEntry = currentFlowEntry.clone();
957 for (NodeConnector dstPort : portList) {
958 Action action = new Output(dstPort);
959 newFlowEntry.getFlow().removeAction(action);
961 Status status = modifyEntry(currentFlowEntry, newFlowEntry);
962 if (status.isSuccess()) {
963 log.info("Ports {} removed from FlowEntry {}", portList,
966 log.warn("Failed to remove ports {} from Flow entry {}: "
967 + status.getDescription(), portList,
968 currentFlowEntry.toString());
974 "Failed to remove ports from Flow {} on Node {}: Entry Not Found",
979 * This function assumes the target flow has only one output port
982 public void replaceOutputPort(Node node, String flowName,
983 NodeConnector outPort) {
984 FlowEntry currentFlowEntry = null;
985 FlowEntry newFlowEntry = null;
986 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
989 for (FlowEntryInstall flow : flowEntryList) {
990 if (flow.getFlowName().equals(flowName)) {
991 currentFlowEntry = flow.getOriginal();
995 if (currentFlowEntry == null) {
997 "Failed to replace output port for flow {} on node {}: Entry Not Found",
1002 // Create a flow copy with the new output port
1003 newFlowEntry = currentFlowEntry.clone();
1004 Action target = null;
1005 for (Action action : newFlowEntry.getFlow().getActions()) {
1006 if (action.getType() == ActionType.OUTPUT) {
1011 newFlowEntry.getFlow().removeAction(target);
1012 newFlowEntry.getFlow().addAction(new Output(outPort));
1014 // Modify on network node
1015 Status status = modifyEntry(currentFlowEntry, newFlowEntry);
1017 if (status.isSuccess()) {
1018 log.info("Output port replaced with " + outPort
1019 + " for flow {} on node {}", flowName, node);
1021 log.warn("Failed to replace output port for flow {} on node {}: ",
1022 status.getDescription(), flowName, node);
1028 public NodeConnector getOutputPort(Node node, String flowName) {
1029 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
1031 for (FlowEntryInstall flow : flowEntryList) {
1032 if (flow.getFlowName().equals(flowName)) {
1033 for (Action action : flow.getOriginal().getFlow().getActions()) {
1034 if (action.getType() == ActionType.OUTPUT) {
1035 return ((Output) action).getPort();
1044 private void cacheStartup() {
1049 @SuppressWarnings("deprecation")
1050 private void allocateCaches() {
1051 if (this.clusterContainerService == null) {
1052 log.warn("Un-initialized clusterContainerService, can't create cache");
1056 log.debug("FRM allocateCaches for Container {}", container);
1059 clusterContainerService.createCache("frm.nodeFlows",
1060 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1062 clusterContainerService.createCache("frm.groupFlows",
1063 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1065 clusterContainerService.createCache("frm.staticFlows",
1066 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1068 clusterContainerService.createCache("frm.flowsSaveEvent",
1069 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1071 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1072 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1074 clusterContainerService.createCache("frm.portGroupConfigs",
1075 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1077 clusterContainerService.createCache("frm.portGroupData",
1078 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1080 clusterContainerService.createCache("frm.TSPolicies",
1081 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1083 } catch (CacheConfigException cce) {
1084 log.error("FRM CacheConfigException");
1085 } catch (CacheExistException cce) {
1086 log.error("FRM CacheExistException");
1090 @SuppressWarnings({ "unchecked", "deprecation" })
1091 private void retrieveCaches() {
1092 ConcurrentMap<?, ?> map;
1094 if (this.clusterContainerService == null) {
1095 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1099 log.debug("FRM retrieveCaches for Container {}", container);
1101 map = clusterContainerService.getCache("frm.nodeFlows");
1103 nodeFlows = (ConcurrentMap<Node, Set<FlowEntryInstall>>) map;
1106 "FRM Cache frm.nodeFlows allocation failed for Container {}",
1110 map = clusterContainerService.getCache("frm.groupFlows");
1112 groupFlows = (ConcurrentMap<String, Set<FlowEntryInstall>>) map;
1115 "FRM Cache frm.groupFlows allocation failed for Container {}",
1119 map = clusterContainerService.getCache("frm.staticFlows");
1121 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1124 "FRM Cache frm.staticFlows allocation failed for Container {}",
1128 map = clusterContainerService.getCache("frm.flowsSaveEvent");
1130 flowsSaveEvent = (ConcurrentMap<Long, String>) map;
1133 "FRM Cache frm.flowsSaveEvent allocation failed for Container {}",
1137 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1139 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1142 "FRM Cache frm.staticFlowsOrdinal allocation failed for Container {}",
1146 map = clusterContainerService.getCache("frm.portGroupConfigs");
1148 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1151 "FRM Cache frm.portGroupConfigs allocation failed for Container {}",
1155 map = clusterContainerService.getCache("frm.portGroupData");
1157 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1160 "FRM Cache frm.portGroupData allocation failed for Container {}",
1164 map = clusterContainerService.getCache("frm.TSPolicies");
1166 TSPolicies = (ConcurrentMap<String, Object>) map;
1169 "FRM Cache frm.TSPolicies allocation failed for Container {}",
1175 @SuppressWarnings("deprecation")
1176 private void destroyCaches() {
1177 if (this.clusterContainerService == null) {
1178 log.warn("Un-initialized clusterContainerService, can't destroy cache");
1182 log.debug("FRM destroyCaches for Container {}", container);
1183 clusterContainerService.destroyCache("frm.nodeFlows");
1184 clusterContainerService.destroyCache("frm.TSPolicies");
1185 clusterContainerService.destroyCache("frm.groupFlows");
1186 clusterContainerService.destroyCache("frm.staticFlows");
1187 clusterContainerService.destroyCache("frm.flowsSaveEvent");
1188 clusterContainerService.destroyCache("frm.staticFlowsOrdinal");
1189 clusterContainerService.destroyCache("frm.portGroupData");
1190 clusterContainerService.destroyCache("frm.portGroupConfigs");
1191 nonClusterObjectCreate();
1194 private boolean flowConfigExists(FlowConfig config) {
1195 // As per customer requirement, flow name has to be unique on per node
1197 for (FlowConfig fc : staticFlows.values()) {
1198 if (fc.isByNameAndNodeIdEqual(config)) {
1206 public Status addStaticFlow(FlowConfig config, boolean restore) {
1207 StringBuffer resultStr = new StringBuffer();
1208 boolean multipleFlowPush = false;
1211 config.setStatus(StatusCode.SUCCESS.toString());
1214 if (flowConfigExists(config)) {
1215 error = "Entry with this name on specified switch already exists";
1216 config.setStatus(error);
1217 return new Status(StatusCode.CONFLICT, error);
1220 // Skip validation check if we are trying to restore a saved config
1221 if (!restore && !config.isValid(container, resultStr)) {
1222 log.debug(resultStr.toString());
1223 error = "Invalid Configuration (" + resultStr.toString() + ")";
1224 config.setStatus(error);
1225 return new Status(StatusCode.BADREQUEST, error);
1228 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1229 for (String portGroupName : portGroupConfigs.keySet()) {
1230 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1231 multipleFlowPush = true;
1235 if (!multipleFlowPush) {
1236 log.debug(resultStr.toString());
1237 error = "Invalid Configuration (Invalid PortGroup Name)";
1238 config.setStatus(error);
1239 return new Status(StatusCode.BADREQUEST, error);
1244 * If requested program the entry in hardware first before updating the
1247 if (!multipleFlowPush) {
1249 if (config.installInHw()) {
1250 FlowEntry entry = config.getFlowEntry();
1251 status = this.addEntry(entry);
1252 if (!status.isSuccess()) {
1253 config.setStatus(status.getDescription());
1262 * When the control reaches this point, either of the following
1263 * conditions is true 1. This is a single entry configuration (non
1264 * PortGroup) and the hardware installation is successful 2. This is a
1265 * multiple entry configuration (PortGroup) and hardware installation is
1266 * NOT done directly on this event. 3. The User prefers to retain the
1267 * configuration in Controller and skip hardware installation.
1269 * Hence it is safe to update the StaticFlow DB at this point.
1271 * Note : For the case of PortGrouping, it is essential to have this DB
1272 * populated before the PortGroupListeners can query for the DB
1273 * triggered using portGroupChanged event...
1275 Integer ordinal = staticFlowsOrdinal.get(0);
1276 staticFlowsOrdinal.put(0, ++ordinal);
1277 staticFlows.put(ordinal, config);
1279 if (multipleFlowPush) {
1280 PortGroupConfig pgconfig = portGroupConfigs.get(config
1282 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1283 if (existingData != null) {
1284 portGroupChanged(pgconfig, existingData, true);
1287 return new Status(StatusCode.SUCCESS, null);
1290 private void addStaticFlowsToSwitch(Node node) {
1291 for (FlowConfig config : staticFlows.values()) {
1292 if (config.isPortGroupEnabled()) {
1295 if (config.getNode().equals(node)) {
1296 if (config.installInHw()
1297 && !config.getStatus().equals(
1298 StatusCode.SUCCESS.toString())) {
1299 Status status = this.addEntry(config.getFlowEntry());
1300 config.setStatus(status.getDescription());
1306 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1307 log.trace("Updating Static Flow configs on node down: " + node);
1309 List<Integer> toRemove = new ArrayList<Integer>();
1310 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1312 FlowConfig config = entry.getValue();
1314 if (config.isPortGroupEnabled()) {
1318 if (config.installInHw() && config.getNode().equals(node)) {
1319 if (config.isInternalFlow()) {
1320 // Take note of this controller generated static flow
1321 toRemove.add(entry.getKey());
1323 config.setStatus(NODEDOWN);
1327 // Remove controller generated static flows for this node
1328 for (Integer index : toRemove) {
1329 staticFlows.remove(index);
1333 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1334 log.trace("Updating Static Flow configs on container mode change: "
1337 for (FlowConfig config : staticFlows.values()) {
1338 if (config.isPortGroupEnabled()) {
1341 if (config.installInHw()) {
1344 config.setStatus("Removed from node because in container mode");
1347 config.setStatus(StatusCode.SUCCESS.toString());
1355 public Status removeStaticFlow(FlowConfig config) {
1357 * No config.isInternal() check as NB does not take this path and GUI
1358 * cannot issue a delete on an internal generated flow. We need this
1359 * path to be accessible when switch mode is changed from proactive to
1360 * reactive, so that we can remove the internal generated LLDP and ARP
1363 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1364 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1365 // Program the network node
1366 Status status = this.removeEntry(config.getFlowEntry());
1367 // Update configuration database if programming was successful
1368 if (status.isSuccess()) {
1369 staticFlows.remove(entry.getKey());
1372 entry.getValue().setStatus(status.getDescription());
1377 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1381 public Status removeStaticFlow(String name, Node node) {
1382 for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1383 FlowConfig entry = mapEntry.getValue();
1384 Status status = new Status(null, null);
1385 if (entry.isByNameAndNodeIdEqual(name, node)) {
1386 // Validity check for api3 entry point
1387 if (entry.isInternalFlow()) {
1388 String msg = "Invalid operation: Controller generated "
1389 + "flow cannot be deleted";
1391 return new Status(StatusCode.NOTACCEPTABLE, msg);
1393 if (!entry.isPortGroupEnabled()) {
1394 // Program the network node
1395 status = this.removeEntry(entry.getFlowEntry());
1397 // Update configuration database if programming was successful
1398 if (status.isSuccess()) {
1399 staticFlows.remove(mapEntry.getKey());
1402 entry.setStatus(status.getDescription());
1407 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1410 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1411 // Validity check for api3 entry point
1412 if (newFlowConfig.isInternalFlow()) {
1413 String msg = "Invalid operation: Controller generated flow "
1414 + "cannot be modified";
1416 return new Status(StatusCode.NOTACCEPTABLE, msg);
1420 StringBuffer resultStr = new StringBuffer();
1421 if (!newFlowConfig.isValid(container, resultStr)) {
1422 String msg = "Invalid Configuration (" + resultStr.toString() + ")";
1423 newFlowConfig.setStatus(msg);
1425 return new Status(StatusCode.BADREQUEST, msg);
1428 FlowConfig oldFlowConfig = null;
1429 Integer index = null;
1430 for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1431 FlowConfig entry = mapEntry.getValue();
1432 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(),
1433 newFlowConfig.getNode())) {
1434 oldFlowConfig = entry;
1435 index = mapEntry.getKey();
1440 if (oldFlowConfig == null) {
1441 String msg = "Attempt to modify a non existing static flow";
1443 return new Status(StatusCode.NOTFOUND, msg);
1446 // Do not attempt to reinstall the flow, warn user
1447 if (newFlowConfig.equals(oldFlowConfig)) {
1448 String msg = "No modification detected";
1449 log.info("Static flow modification skipped: " + msg);
1450 return new Status(StatusCode.SUCCESS, msg);
1453 // If flow is installed, program the network node
1454 Status status = new Status(StatusCode.SUCCESS, "Saved in config");
1455 if (oldFlowConfig.installInHw()) {
1456 status = this.modifyEntry(oldFlowConfig.getFlowEntry(),
1457 newFlowConfig.getFlowEntry());
1460 // Update configuration database if programming was successful
1461 if (status.isSuccess()) {
1462 newFlowConfig.setStatus(status.getDescription());
1463 staticFlows.put(index, newFlowConfig);
1470 public Status toggleStaticFlowStatus(String name, Node node) {
1471 return toggleStaticFlowStatus(getStaticFlow(name, node));
1475 public Status toggleStaticFlowStatus(FlowConfig config) {
1476 if (config == null) {
1477 String msg = "Invalid request: null flow config";
1479 return new Status(StatusCode.BADREQUEST, msg);
1481 // Validity check for api3 entry point
1482 if (config.isInternalFlow()) {
1483 String msg = "Invalid operation: Controller generated flow "
1484 + "cannot be modified";
1486 return new Status(StatusCode.NOTACCEPTABLE, msg);
1489 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1490 FlowConfig conf = entry.getValue();
1491 if (conf.isByNameAndNodeIdEqual(config)) {
1492 // Program the network node
1493 Status status = new Status(StatusCode.SUCCESS, null);
1494 if (conf.installInHw()) {
1495 status = this.removeEntry(conf.getFlowEntry());
1497 status = this.addEntry(conf.getFlowEntry());
1499 if (!status.isSuccess()) {
1500 conf.setStatus(status.getDescription());
1504 // Update Configuration database
1505 conf.setStatus(StatusCode.SUCCESS.toString());
1506 conf.toggleStatus();
1510 return new Status(StatusCode.NOTFOUND,
1511 "Unable to locate the entry. Failed to toggle status");
1515 * Uninstall all the Flow Entries present in the software view A copy of
1516 * each entry is stored in the inactive list so that it can be re-applied
1517 * when needed This function is called on the default container instance of
1518 * FRM only when the first container is created
1520 private void uninstallAllFlowEntries() {
1521 log.info("Uninstalling all flows");
1523 // Store entries / create target list
1524 for (ConcurrentMap.Entry<Node, Set<FlowEntryInstall>> mapEntry : nodeFlows
1526 for (FlowEntryInstall flowEntries : mapEntry.getValue()) {
1527 inactiveFlows.add(flowEntries.getOriginal());
1531 // Now remove the entries
1532 for (FlowEntry flowEntry : inactiveFlows) {
1533 Status status = this.removeEntry(flowEntry);
1534 if (!status.isSuccess()) {
1536 "Failed to remove entry: {}: "
1537 + status.getDescription(), flowEntry);
1543 * Re-install all the Flow Entries present in the inactive list The inactive
1544 * list will be empty at the end of this call This function is called on the
1545 * default container instance of FRM only when the last container is deleted
1547 private void reinstallAllFlowEntries() {
1548 log.info("Reinstalling all inactive flows");
1550 for (FlowEntry flowEntry : this.inactiveFlows) {
1551 Status status = this.addEntry(flowEntry);
1552 if (!status.isSuccess()) {
1554 "Failed to install entry: {}: "
1555 + status.getDescription(), flowEntry);
1559 // Empty inactive list in any case
1560 inactiveFlows.clear();
1563 public List<FlowConfig> getStaticFlows() {
1564 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0)
1568 // TODO: need to come out with a better algorithm for mantaining the order
1569 // of the configuration entries
1570 // with actual one, index associated to deleted entries cannot be reused and
1572 private List<FlowConfig> getStaticFlowsOrderedList(
1573 ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1574 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1575 for (int i = 0; i <= maxKey; i++) {
1576 FlowConfig entry = flowMap.get(i);
1577 if (entry != null) {
1578 orderedList.add(entry);
1585 public FlowConfig getStaticFlow(String name, Node node) {
1586 for (FlowConfig config : staticFlows.values()) {
1587 if (config.isByNameAndNodeIdEqual(name, node)) {
1595 public List<FlowConfig> getStaticFlows(Node node) {
1596 List<FlowConfig> list = new ArrayList<FlowConfig>();
1597 for (FlowConfig config : staticFlows.values()) {
1598 if (config.onNode(node)) {
1606 public List<String> getStaticFlowNamesForNode(Node node) {
1607 List<String> list = new ArrayList<String>();
1608 for (FlowConfig config : staticFlows.values()) {
1609 if (config.onNode(node)) {
1610 list.add(config.getName());
1617 public List<Node> getListNodeWithConfiguredFlows() {
1618 Set<Node> set = new HashSet<Node>();
1619 for (FlowConfig config : staticFlows.values()) {
1620 set.add(config.getNode());
1622 return new ArrayList<Node>(set);
1625 @SuppressWarnings("unchecked")
1626 private void loadFlowConfiguration() {
1627 ObjectReader objReader = new ObjectReader();
1628 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader
1629 .read(this, frmFileName);
1631 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader
1632 .read(this, portGroupFileName);
1634 if (pgConfig != null) {
1635 for (Map.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
1636 addPortGroupConfig(entry.getKey(), entry.getValue()
1637 .getMatchString(), true);
1641 if (confList == null) {
1646 for (Integer key : confList.keySet()) {
1647 if (key.intValue() > maxKey)
1648 maxKey = key.intValue();
1651 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
1652 addStaticFlow(conf, true);
1657 public Object readObject(ObjectInputStream ois)
1658 throws FileNotFoundException, IOException, ClassNotFoundException {
1659 return ois.readObject();
1662 public Status saveConfig() {
1663 // Publish the save config event to the cluster nodes
1664 flowsSaveEvent.put(new Date().getTime(), SAVE);
1665 return saveConfigInternal();
1668 private Status saveConfigInternal() {
1669 ObjectWriter objWriter = new ObjectWriter();
1670 ConcurrentHashMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1671 for (Integer ordinal : staticFlows.keySet()) {
1672 FlowConfig config = staticFlows.get(ordinal);
1673 // Do not save dynamic and controller generated static flows
1674 if (config.isDynamic() || config.isInternalFlow()) {
1677 nonDynamicFlows.put(ordinal, config);
1679 objWriter.write(nonDynamicFlows, frmFileName);
1680 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(
1681 portGroupConfigs), portGroupFileName);
1682 return new Status(StatusCode.SUCCESS, null);
1686 public void entryCreated(Long key, String cacheName, boolean local) {
1690 public void entryUpdated(Long key, String new_value, String cacheName,
1691 boolean originLocal) {
1692 saveConfigInternal();
1696 public void entryDeleted(Long key, String cacheName, boolean originLocal) {
1700 public void subnetNotify(Subnet sub, boolean add) {
1703 private void installImplicitARPReplyPunt(Node node) {
1709 List<String> puntAction = new ArrayList<String>();
1710 puntAction.add(ActionType.CONTROLLER.toString());
1712 FlowConfig allowARP = new FlowConfig();
1713 allowARP.setInstallInHw(true);
1714 allowARP.setName("**Punt ARP Reply");
1715 allowARP.setPriority("500");
1716 allowARP.setNode(node);
1717 allowARP.setEtherType("0x"
1718 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1719 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager
1720 .getControllerMAC()));
1721 allowARP.setActions(puntAction);
1722 addStaticFlow(allowARP, false);
1726 public void modeChangeNotify(Node node, boolean proactive) {
1727 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
1729 List<String> puntAction = new ArrayList<String>();
1730 puntAction.add(ActionType.CONTROLLER.toString());
1732 FlowConfig allowARP = new FlowConfig();
1733 allowARP.setInstallInHw(true);
1734 allowARP.setName("**Punt ARP");
1735 allowARP.setPriority("1");
1736 allowARP.setNode(node);
1737 allowARP.setEtherType("0x"
1738 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1739 allowARP.setActions(puntAction);
1740 defaultConfigs.add(allowARP);
1742 FlowConfig allowLLDP = new FlowConfig();
1743 allowLLDP.setInstallInHw(true);
1744 allowLLDP.setName("**Punt LLDP");
1745 allowLLDP.setPriority("1");
1746 allowLLDP.setNode(node);
1749 + Integer.toHexString(EtherTypes.LLDP.intValue())
1751 allowLLDP.setActions(puntAction);
1752 defaultConfigs.add(allowLLDP);
1754 List<String> dropAction = new ArrayList<String>();
1755 dropAction.add(ActionType.DROP.toString());
1757 FlowConfig dropAllConfig = new FlowConfig();
1758 dropAllConfig.setInstallInHw(true);
1759 dropAllConfig.setName("**Catch-All Drop");
1760 dropAllConfig.setPriority("0");
1761 dropAllConfig.setNode(node);
1762 dropAllConfig.setActions(dropAction);
1763 defaultConfigs.add(dropAllConfig);
1765 for (FlowConfig fc : defaultConfigs) {
1767 addStaticFlow(fc, false);
1769 removeStaticFlow(fc);
1773 log.info("Set Switch {} Mode to {}", node, proactive);
1777 * Remove from the databases all the flows installed on the node
1781 private synchronized void cleanDatabaseForNode(Node node) {
1782 log.info("Cleaning Flow database for Node " + node.toString());
1784 // Find out which groups the node's flows are part of
1785 Set<String> affectedGroups = new HashSet<String>();
1786 Set<FlowEntryInstall> flowEntryList = nodeFlows.get(node);
1787 if (flowEntryList != null) {
1788 for (FlowEntryInstall entry : flowEntryList) {
1789 String groupName = entry.getGroupName();
1790 if (groupName != null) {
1791 affectedGroups.add(groupName);
1796 // Remove the node's flows from the group indexed flow database
1797 if (!affectedGroups.isEmpty()) {
1798 for (String group : affectedGroups) {
1799 Set<FlowEntryInstall> flowList = groupFlows.get(group);
1800 Set<FlowEntryInstall> toRemove = new HashSet<FlowEntryInstall>();
1801 for (FlowEntryInstall entry : flowList) {
1802 if (node.equals(entry.getNode())) {
1803 toRemove.add(entry);
1806 flowList.removeAll(toRemove);
1807 if (flowList.isEmpty()) {
1808 groupFlows.remove(group);
1813 // Remove the node's flows from the node indexed flow database
1814 nodeFlows.remove(node);
1818 public void notifyNode(Node node, UpdateType type,
1819 Map<String, Property> propMap) {
1822 addStaticFlowsToSwitch(node);
1825 cleanDatabaseForNode(node);
1826 updateStaticFlowConfigsOnNodeDown(node);
1834 public void notifyNodeConnector(NodeConnector nodeConnector,
1835 UpdateType type, Map<String, Property> propMap) {
1838 private FlowConfig getDerivedFlowConfig(FlowConfig original,
1839 String configName, Short port) {
1840 FlowConfig derivedFlow = new FlowConfig(original);
1841 derivedFlow.setDynamic(true);
1842 derivedFlow.setPortGroup(null);
1843 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
1844 derivedFlow.setIngressPort(port + "");
1848 private void addPortGroupFlows(PortGroupConfig config, Node node,
1850 for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
1852 FlowConfig staticFlow = it.next();
1853 if (staticFlow.getPortGroup() == null) {
1856 if ((staticFlow.getNode().equals(node))
1857 && (staticFlow.getPortGroup().equals(config.getName()))) {
1858 for (Short port : data.getPorts()) {
1859 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
1860 config.getName(), port);
1861 addStaticFlow(derivedFlow, false);
1867 private void removePortGroupFlows(PortGroupConfig config, Node node,
1869 for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
1871 FlowConfig staticFlow = it.next();
1872 if (staticFlow.getPortGroup() == null) {
1875 if ((staticFlow.getNode().equals(node))
1876 && (staticFlow.getPortGroup().equals(config.getName()))) {
1877 for (Short port : data.getPorts()) {
1878 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
1879 config.getName(), port);
1880 removeStaticFlow(derivedFlow);
1887 public void portGroupChanged(PortGroupConfig config,
1888 Map<Node, PortGroup> data, boolean add) {
1889 log.info("PortGroup Changed for :" + config + " Data: " + portGroupData);
1890 Map<Node, PortGroup> existingData = portGroupData.get(config);
1891 if (existingData != null) {
1892 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
1893 PortGroup existingPortGroup = existingData.get(entry.getKey());
1894 if (existingPortGroup == null) {
1896 existingData.put(entry.getKey(), entry.getValue());
1897 addPortGroupFlows(config, entry.getKey(),
1902 existingPortGroup.getPorts().addAll(
1903 entry.getValue().getPorts());
1904 addPortGroupFlows(config, entry.getKey(),
1907 existingPortGroup.getPorts().removeAll(
1908 entry.getValue().getPorts());
1909 removePortGroupFlows(config, entry.getKey(),
1916 portGroupData.put(config, data);
1917 for (Node swid : data.keySet()) {
1918 addPortGroupFlows(config, swid, data.get(swid));
1924 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
1925 PortGroupConfig config = portGroupConfigs.get(name);
1929 if ((portGroupProvider == null) && !restore) {
1932 if ((portGroupProvider != null)
1933 && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
1937 config = new PortGroupConfig(name, regex);
1938 portGroupConfigs.put(name, config);
1939 if (portGroupProvider != null) {
1940 portGroupProvider.createPortGroupConfig(config);
1945 public boolean delPortGroupConfig(String name) {
1946 PortGroupConfig config = portGroupConfigs.get(name);
1947 if (config == null) {
1951 if (portGroupProvider != null) {
1952 portGroupProvider.deletePortGroupConfig(config);
1954 portGroupConfigs.remove(name);
1958 private void usePortGroupConfig(String name) {
1959 PortGroupConfig config = portGroupConfigs.get(name);
1960 if (config == null) {
1963 if (portGroupProvider != null) {
1964 Map<Node, PortGroup> data = portGroupProvider
1965 .getPortGroupData(config);
1966 portGroupData.put(config, data);
1971 public Map<String, PortGroupConfig> getPortGroupConfigs() {
1972 return portGroupConfigs;
1975 public boolean isPortGroupSupported() {
1976 if (portGroupProvider == null) {
1982 // Fir PortGroupProvider to use regular Dependency Manager
1983 /* @SuppressWarnings("rawtypes") */
1984 /* public void bind(Object arg0, Map arg1) throws Exception { */
1985 /* if (arg0 instanceof PortGroupProvider) { */
1986 /* setPortGroupProvider((PortGroupProvider)arg0); */
1990 /* @SuppressWarnings("rawtypes") */
1992 /* public void unbind(Object arg0, Map arg1) throws Exception { */
1993 /* if (arg0 instanceof PortGroupProvider) { */
1994 /* portGroupProvider = null; */
1998 public void setIContainer(IContainer s) {
2002 public void unsetIContainer(IContainer s) {
2003 if (this.container == s) {
2004 this.container = null;
2008 public PortGroupProvider getPortGroupProvider() {
2009 return portGroupProvider;
2012 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2013 this.portGroupProvider = null;
2016 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2017 this.portGroupProvider = portGroupProvider;
2018 portGroupProvider.registerPortGroupChange(this);
2019 for (PortGroupConfig config : portGroupConfigs.values()) {
2020 portGroupProvider.createPortGroupConfig(config);
2024 public void setHostFinder(IfIptoHost hostFinder) {
2025 this.hostFinder = hostFinder;
2028 public void unsetHostFinder(IfIptoHost hostFinder) {
2029 if (this.hostFinder == hostFinder) {
2030 this.hostFinder = null;
2034 public void setFrmAware(IForwardingRulesManagerAware obj) {
2035 this.frmAware.add(obj);
2038 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2039 this.frmAware.remove(obj);
2042 void setClusterContainerService(IClusterContainerServices s) {
2043 log.debug("Cluster Service set");
2044 this.clusterContainerService = s;
2047 void unsetClusterContainerService(IClusterContainerServices s) {
2048 if (this.clusterContainerService == s) {
2049 log.debug("Cluster Service removed!");
2050 this.clusterContainerService = null;
2054 private String getContainerName() {
2055 if (container == null) {
2056 return GlobalConstants.DEFAULT.toString();
2058 return container.getName();
2062 * Function called by the dependency manager when all the required
2063 * dependencies are satisfied
2067 frmAware = Collections
2068 .synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
2069 frmFileName = GlobalConstants.STARTUPHOME.toString()
2070 + "frm_staticflows_" + this.getContainerName() + ".conf";
2071 portGroupFileName = GlobalConstants.STARTUPHOME.toString()
2072 + "portgroup_" + this.getContainerName() + ".conf";
2074 inContainerMode = false;
2076 if (portGroupProvider != null) {
2077 portGroupProvider.registerPortGroupChange(this);
2080 nonClusterObjectCreate();
2084 registerWithOSGIConsole();
2087 * If we are not the first cluster node to come up, do not initialize
2088 * the static flow entries ordinal
2090 if (staticFlowsOrdinal.size() == 0) {
2091 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2096 * Function called by the dependency manager when at least one dependency
2097 * become unsatisfied or when the component is shutting down because for
2098 * example bundle is being stopped.
2106 * Function called by dependency manager after "init ()" is called and after
2107 * the services provided by the class are registered in the service registry
2112 * Read startup and build database if we have not already gotten the
2113 * configurations synced from another node
2115 if (staticFlows.isEmpty()) {
2116 loadFlowConfiguration();
2121 * Function called by the dependency manager before the services exported by
2122 * the component are unregistered, this will be followed by a "destroy ()"
2129 public void setFlowProgrammerService(IFlowProgrammerService service) {
2130 this.programmer = service;
2133 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2134 if (this.programmer == service) {
2135 this.programmer = null;
2139 public void setSwitchManager(ISwitchManager switchManager) {
2140 this.switchManager = switchManager;
2143 public void unsetSwitchManager(ISwitchManager switchManager) {
2144 if (this.switchManager == switchManager) {
2145 this.switchManager = null;
2150 public void tagUpdated(String containerName, Node n, short oldTag,
2151 short newTag, UpdateType t) {
2156 public void containerFlowUpdated(String containerName,
2157 ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
2159 * Whether it is an addition or removal, we have to recompute the merged
2160 * flows entries taking into account all the current container flows
2161 * because flow merging is not an injective function
2163 updateFlowsContainerFlow();
2167 public void nodeConnectorUpdated(String containerName, NodeConnector p,
2173 public void containerModeUpdated(UpdateType update) {
2176 this.inContainerMode = true;
2177 this.uninstallAllFlowEntries();
2180 this.inContainerMode = false;
2181 this.reinstallAllFlowEntries();
2186 // Update our configuration DB
2187 updateStaticFlowConfigsOnContainerModeChange(update);
2194 public String getHelp() {
2195 StringBuffer help = new StringBuffer();
2196 help.append("---FRM Matrix Application---\n");
2197 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2198 help.append("\t addMatrixConfig <name> <regex>\n");
2199 help.append("\t delMatrixConfig <name>\n");
2200 help.append("\t useMatrixConfig <name>\n");
2201 return help.toString();
2204 public void _printMatrixData(CommandInterpreter ci) {
2205 ci.println("Configs : ");
2206 ci.println("---------");
2207 ci.println(portGroupConfigs);
2209 ci.println("Data : ");
2210 ci.println("------");
2211 ci.println(portGroupData);
2214 public void _addMatrixConfig(CommandInterpreter ci) {
2215 String name = ci.nextArgument();
2216 String regex = ci.nextArgument();
2217 addPortGroupConfig(name, regex, false);
2220 public void _delMatrixConfig(CommandInterpreter ci) {
2221 String name = ci.nextArgument();
2222 delPortGroupConfig(name);
2225 public void _useMatrixConfig(CommandInterpreter ci) {
2226 String name = ci.nextArgument();
2227 usePortGroupConfig(name);
2230 public void _arpPunt(CommandInterpreter ci) {
2231 String switchId = ci.nextArgument();
2232 long swid = HexEncode.stringToLong(switchId);
2233 Node node = NodeCreator.createOFNode(swid);
2234 installImplicitARPReplyPunt(node);
2237 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2239 String nodeId = ci.nextArgument();
2240 if (nodeId == null) {
2241 ci.print("Node id not specified");
2245 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2246 } catch (NumberFormatException e) {
2249 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2252 public void _frmremoveflow(CommandInterpreter ci)
2253 throws UnknownHostException {
2255 String nodeId = ci.nextArgument();
2256 if (nodeId == null) {
2257 ci.print("Node id not specified");
2261 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2262 } catch (NumberFormatException e) {
2265 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2268 private Flow getSampleFlow(Node node) throws UnknownHostException {
2269 NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
2271 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector(
2273 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,
2274 (byte) 0x9a, (byte) 0xbc };
2275 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d,
2276 (byte) 0x5e, (byte) 0x6f };
2277 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2278 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2279 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2280 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2281 short ethertype = EtherTypes.IPv4.shortValue();
2282 short vlan = (short) 27;
2285 byte proto = IPProtocols.TCP.byteValue();
2286 short src = (short) 55000;
2290 * Create a SAL Flow aFlow
2292 Match match = new Match();
2293 match.setField(MatchType.IN_PORT, port);
2294 match.setField(MatchType.DL_SRC, srcMac);
2295 match.setField(MatchType.DL_DST, dstMac);
2296 match.setField(MatchType.DL_TYPE, ethertype);
2297 match.setField(MatchType.DL_VLAN, vlan);
2298 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2299 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2300 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2301 match.setField(MatchType.NW_TOS, tos);
2302 match.setField(MatchType.NW_PROTO, proto);
2303 match.setField(MatchType.TP_SRC, src);
2304 match.setField(MatchType.TP_DST, dst);
2306 List<Action> actions = new ArrayList<Action>();
2307 actions.add(new Output(oport));
2308 actions.add(new PopVlan());
2309 actions.add(new Flood());
2310 actions.add(new Controller());
2311 return new Flow(match, actions);
2315 public Status saveConfiguration() {
2316 return saveConfig();
2319 public void _frmNodeFlows(CommandInterpreter ci) {
2320 boolean verbose = false;
2321 String verboseCheck = ci.nextArgument();
2322 if (verboseCheck != null) {
2323 verbose = verboseCheck.equals("true");
2326 // Dump per node database
2327 for (Entry<Node, Set<FlowEntryInstall>> entry : this.nodeFlows
2329 Node node = entry.getKey();
2330 for (FlowEntryInstall flow : entry.getValue()) {
2332 ci.println(node + " " + flow.getFlowName());
2334 ci.println(node + " " + flow.toString());
2340 public void _frmGroupFlows(CommandInterpreter ci) {
2341 boolean verbose = false;
2342 String verboseCheck = ci.nextArgument();
2343 if (verboseCheck != null) {
2344 verbose = verboseCheck.equalsIgnoreCase("true");
2347 // Dump per node database
2348 for (Entry<String, Set<FlowEntryInstall>> entry : this.groupFlows
2350 String group = entry.getKey();
2351 ci.println("Group " + group + ":");
2352 for (FlowEntryInstall flow : entry.getValue()) {
2354 ci.println(flow.getNode() + " " + flow.getFlowName());
2356 ci.println(flow.getNode() + " " + flow.toString());
2363 public void flowRemoved(Node node, Flow flow) {
2364 log.trace("Received flow removed notification on {} for {}", node, flow);
2365 // For flow entry identification, only match and priority matter
2366 FlowEntry toFind = new FlowEntry("any", "any", flow, node);
2367 FlowEntryInstall installedEntry = this.findMatch(toFind, false);
2368 if (installedEntry == null) {
2369 log.trace("Entry is not know to us");
2373 // Update Static flow status
2374 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2375 FlowConfig conf = entry.getValue();
2376 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
2377 // Update Configuration database
2378 conf.toggleStatus();
2382 // Update software views
2383 this.updateLocalDatabase(installedEntry, false);