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.EnumSet;
19 import java.util.HashSet;
20 import java.util.List;
22 import java.util.Map.Entry;
24 import java.util.concurrent.BlockingQueue;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.LinkedBlockingQueue;
29 import org.eclipse.osgi.framework.console.CommandInterpreter;
30 import org.eclipse.osgi.framework.console.CommandProvider;
31 import org.opendaylight.controller.clustering.services.CacheConfigException;
32 import org.opendaylight.controller.clustering.services.CacheExistException;
33 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
34 import org.opendaylight.controller.clustering.services.IClusterServices;
35 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
36 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
37 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
38 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
39 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
40 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
41 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
42 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
43 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
44 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
45 import org.opendaylight.controller.sal.action.Action;
46 import org.opendaylight.controller.sal.action.ActionType;
47 import org.opendaylight.controller.sal.action.Controller;
48 import org.opendaylight.controller.sal.action.Flood;
49 import org.opendaylight.controller.sal.action.Output;
50 import org.opendaylight.controller.sal.action.PopVlan;
51 import org.opendaylight.controller.sal.core.ContainerFlow;
52 import org.opendaylight.controller.sal.core.IContainer;
53 import org.opendaylight.controller.sal.core.IContainerListener;
54 import org.opendaylight.controller.sal.core.Node;
55 import org.opendaylight.controller.sal.core.NodeConnector;
56 import org.opendaylight.controller.sal.core.Property;
57 import org.opendaylight.controller.sal.core.UpdateType;
58 import org.opendaylight.controller.sal.flowprogrammer.Flow;
59 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
60 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
61 import org.opendaylight.controller.sal.match.Match;
62 import org.opendaylight.controller.sal.match.MatchType;
63 import org.opendaylight.controller.sal.utils.EtherTypes;
64 import org.opendaylight.controller.sal.utils.GlobalConstants;
65 import org.opendaylight.controller.sal.utils.HexEncode;
66 import org.opendaylight.controller.sal.utils.IObjectReader;
67 import org.opendaylight.controller.sal.utils.IPProtocols;
68 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
69 import org.opendaylight.controller.sal.utils.NodeCreator;
70 import org.opendaylight.controller.sal.utils.ObjectReader;
71 import org.opendaylight.controller.sal.utils.ObjectWriter;
72 import org.opendaylight.controller.sal.utils.Status;
73 import org.opendaylight.controller.sal.utils.StatusCode;
74 import org.opendaylight.controller.switchmanager.IInventoryListener;
75 import org.opendaylight.controller.switchmanager.ISwitchManager;
76 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
77 import org.opendaylight.controller.switchmanager.Subnet;
78 import org.osgi.framework.BundleContext;
79 import org.osgi.framework.FrameworkUtil;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 * Class that manages forwarding rule installation and removal per container of
85 * the network. It also maintains the central repository of all the forwarding
86 * rules installed on the network nodes.
88 public class ForwardingRulesManager implements IForwardingRulesManager, PortGroupChangeListener,
89 IContainerListener, ISwitchManagerAware, IConfigurationContainerAware, IInventoryListener, IObjectReader,
90 CommandProvider, IFlowProgrammerListener {
91 private static final String NODEDOWN = "Node is Down";
92 private static final String SUCCESS = StatusCode.SUCCESS.toString();
93 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
94 private String frmFileName;
95 private String portGroupFileName;
96 private ConcurrentMap<Integer, FlowConfig> staticFlows;
97 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
98 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
99 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
100 private ConcurrentMap<String, Object> TSPolicies;
101 private boolean inContainerMode; // being used by global instance only
102 private boolean stopping;
105 * Flow database. It's the software view of what was requested to install
106 * and what is installed on the switch. It is indexed by the entry itself.
107 * The entry's hashcode resumes the network node index, the flow's priority
108 * and the flow's match. The value element is a class which contains the
109 * flow entry pushed by the applications modules and the respective
110 * container flow merged version. In absence of container flows, the two
111 * flow entries are the same.
113 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
114 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
116 * Per node and per group indexing
118 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
119 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
122 * Inactive flow list. This is for the global instance of FRM It will
123 * contain all the flow entries which were installed on the global container
124 * when the first container is created.
126 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
128 private IContainer container;
129 private Set<IForwardingRulesManagerAware> frmAware =
130 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
131 private PortGroupProvider portGroupProvider;
132 private IFlowProgrammerService programmer;
133 private IClusterContainerServices clusterContainerService = null;
134 private ISwitchManager switchManager;
135 private Thread frmEventHandler;
136 protected BlockingQueue<FRMEvent> pendingEvents;
139 * Adds a flow entry onto the network node It runs various validity checks
140 * and derive the final container flows merged entries that will be
141 * attempted to be installed
144 * the original flow entry application requested to add
146 * the flag indicating if this is a asynchronous request
147 * @return the status of this request. In case of asynchronous call, it will
148 * contain the unique id assigned to this request
150 private Status addEntry(FlowEntry flowEntry, boolean async) {
153 if (flowEntry == null || flowEntry.getNode() == null) {
154 String msg = "Invalid FlowEntry";
155 String logMsg = msg + ": {}";
156 log.warn(logMsg, flowEntry);
157 return new Status(StatusCode.NOTACCEPTABLE, msg);
161 * Derive the container flow merged entries to install In presence of N
162 * container flows, we may end up with N different entries to install...
164 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
166 // Container Flow conflict Check
167 if (toInstallList.isEmpty()) {
168 String msg = "Flow Entry conflicts with all Container Flows";
169 String logMsg = msg + ": {}";
170 log.warn(logMsg, flowEntry);
171 return new Status(StatusCode.CONFLICT, msg);
174 // Derive the list of entries good to be installed
175 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
176 for (FlowEntryInstall entry : toInstallList) {
177 // Conflict Check: Verify new entry would not overwrite existing
179 if (this.installedSwView.containsKey(entry)) {
180 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
181 log.trace("Aborting to install {}", entry);
184 toInstallSafe.add(entry);
187 // Declare failure if all the container flow merged entries clash with
189 if (toInstallSafe.size() == 0) {
190 String msg = "A flow with same match and priority exists on the target node";
191 String logMsg = msg + ": {}";
192 log.warn(logMsg, flowEntry);
193 return new Status(StatusCode.CONFLICT, msg);
196 // Try to install an entry at the time
197 Status error = new Status(null, null);
198 Status succeded = null;
199 boolean oneSucceded = false;
200 for (FlowEntryInstall installEntry : toInstallSafe) {
202 // Install and update database
203 Status ret = addEntriesInternal(installEntry, async);
205 if (ret.isSuccess()) {
208 * The first successful status response will be returned For the
209 * asynchronous call, we can discard the container flow
210 * complication for now and assume we will always deal with one
211 * flow only per request
216 log.warn("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
220 return (oneSucceded) ? succeded : error;
224 * Given a flow entry and the list of container flows, it returns the list
225 * of container flow merged flow entries good to be installed on this
226 * container. If the list of container flows is null or empty, the install
227 * entry list will contain only one entry, the original flow entry. If the
228 * flow entry is congruent with all the N container flows, then the output
229 * install entry list will contain N entries. If the output list is empty,
230 * it means the passed flow entry conflicts with all the container flows.
233 * The list of container flows
234 * @return the list of container flow merged entries good to be installed on
237 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
238 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
240 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
241 // No container flows => entry good to be installed unchanged
242 toInstallList.add(new FlowEntryInstall(request.clone(), null));
244 // Create the list of entries to be installed. If the flow entry is
245 // not congruent with any container flow, no install entries will be
247 for (ContainerFlow cFlow : container.getContainerFlows()) {
248 if (cFlow.allowsFlow(request.getFlow())) {
249 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
253 return toInstallList;
257 * Modify a flow entry with a new one It runs various validity check and
258 * derive the final container flows merged flow entries to work with
260 * @param currentFlowEntry
261 * @param newFlowEntry
263 * the flag indicating if this is a asynchronous request
264 * @return the status of this request. In case of asynchronous call, it will
265 * contain the unique id assigned to this request
267 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
271 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
272 || newFlowEntry.getNode() == null) {
273 String msg = "Modify: Invalid FlowEntry";
274 String logMsg = msg + ": {} or {}";
275 log.warn(logMsg, currentFlowEntry, newFlowEntry);
276 return new Status(StatusCode.NOTACCEPTABLE, msg);
278 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
279 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
280 String msg = "Modify: Incompatible Flow Entries";
281 String logMsg = msg + ": {} and {}";
282 log.warn(logMsg, currentFlowEntry, newFlowEntry);
283 return new Status(StatusCode.NOTACCEPTABLE, msg);
287 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
288 String msg = "Modify skipped as flows are the same";
289 String logMsg = msg + ": {} and {}";
290 log.debug(logMsg, currentFlowEntry, newFlowEntry);
291 return new Status(StatusCode.SUCCESS, msg);
295 * Conflict Check: Verify the new entry would not conflict with an
296 * existing one. This is a loose check on the previous original flow
297 * entry requests. No check on the container flow merged flow entries
300 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
301 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
302 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
303 String logMsg = msg + ": {}";
304 log.warn(logMsg, currentFlowEntry);
305 return new Status(StatusCode.CONFLICT, msg);
308 // Derive the installed and toInstall entries
309 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
310 container.getContainerFlows());
311 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
313 if (toInstallList.isEmpty()) {
314 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
315 String logMsg = msg + ": {}";
316 log.warn(logMsg, newFlowEntry);
318 return new Status(StatusCode.CONFLICT, msg);
322 * If the two list sizes differ, it means the new flow entry does not
323 * satisfy the same number of container flows the current entry does.
324 * This is only possible when the new entry and current entry have
325 * different match. In this scenario the modification would ultimately
326 * be handled as a remove and add operations in the protocol plugin.
328 * Also, if any of the new flow entries would clash with an existing
329 * one, we cannot proceed with the modify operation, because it would
330 * fail for some entries and leave stale entries on the network node.
331 * Modify path can be taken only if it can be performed completely, for
334 * So, for the above two cases, to simplify, let's decouple the modify
335 * in: 1) remove current entries 2) install new entries
337 Status succeeded = null;
338 boolean decouple = false;
339 if (installedList.size() != toInstallList.size()) {
340 log.info("Modify: New flow entry does not satisfy the same "
341 + "number of container flows as the original entry does");
344 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
345 for (FlowEntryInstall installEntry : toInstallList) {
347 * Conflict Check: Verify the new entry would not overwrite another
350 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
351 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
352 log.info("Modify: new container flow merged flow entry clashes with existing flow");
355 toInstallSafe.add(installEntry);
360 // Remove current entries
361 for (FlowEntryInstall currEntry : installedList) {
362 this.removeEntryInternal(currEntry, async);
364 // Install new entries
365 for (FlowEntryInstall newEntry : toInstallSafe) {
366 succeeded = this.addEntriesInternal(newEntry, async);
370 * The two list have the same size and the entries to install do not
371 * clash with any existing flow on the network node. We assume here
372 * (and might be wrong) that the same container flows that were
373 * satisfied by the current entries are the same that are satisfied
374 * by the new entries. Let's take the risk for now.
376 * Note: modification has to be complete. If any entry modification
377 * fails, we need to stop, restore the already modified entries, and
380 Status retModify = null;
382 int size = toInstallList.size();
384 // Modify and update database
385 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
386 if (retModify.isSuccess()) {
392 // Check if uncompleted modify
394 log.warn("Unable to perform a complete modify for all the container flows merged entries");
395 // Restore original entries
398 log.info("Attempting to restore initial entries");
399 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
400 if (retExt.isSuccess()) {
406 // Fatal error, recovery failed
408 String msg = "Flow recovery failed ! Unrecoverable Error";
410 return new Status(StatusCode.INTERNALERROR, msg);
413 succeeded = retModify;
416 * The first successful status response will be returned. For the
417 * asynchronous call, we can discard the container flow complication for
418 * now and assume we will always deal with one flow only per request
424 * This is the function that modifies the final container flows merged
425 * entries on the network node and update the database. It expects that all
426 * the validity checks are passed
428 * @param currentEntries
431 * the flag indicating if this is a asynchronous request
432 * @return the status of this request. In case of asynchronous call, it will
433 * contain the unique id assigned to this request
435 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
436 // Modify the flow on the network node
437 Status status = (async) ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
438 .getFlow(), newEntries.getInstall().getFlow()) : programmer.modifyFlow(currentEntries.getNode(),
439 currentEntries.getInstall().getFlow(), newEntries.getInstall().getFlow());
441 if (!status.isSuccess()) {
442 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
443 status.getDescription());
447 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
450 newEntries.setRequestId(status.getRequestId());
451 updateLocalDatabase(currentEntries, false);
452 updateLocalDatabase(newEntries, true);
458 * Remove a flow entry. If the entry is not present in the software view
459 * (entry or node not present), it return successfully
462 * the flow entry to remove
464 * the flag indicating if this is a asynchronous request
465 * @return the status of this request. In case of asynchronous call, it will
466 * contain the unique id assigned to this request
468 private Status removeEntry(FlowEntry flowEntry, boolean async) {
469 Status error = new Status(null, null);
472 if (flowEntry == null || flowEntry.getNode() == null) {
473 String msg = "Invalid FlowEntry";
474 String logMsg = msg + ": {}";
475 log.warn(logMsg, flowEntry);
476 return new Status(StatusCode.NOTACCEPTABLE, msg);
479 // Derive the container flows merged installed entries
480 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
482 Status succeeded = null;
483 boolean atLeastOneRemoved = false;
484 for (FlowEntryInstall entry : installedList) {
485 if (!installedSwView.containsKey(entry)) {
486 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
487 log.debug(logMsg, flowEntry);
488 if (installedList.size() == 1) {
489 // If we had only one entry to remove, we are done
490 return new Status(StatusCode.SUCCESS);
496 // Remove and update DB
497 Status ret = removeEntryInternal(entry, async);
499 if (!ret.isSuccess()) {
501 log.warn("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
502 if (installedList.size() == 1) {
503 // If we had only one entry to remove, this is fatal failure
508 atLeastOneRemoved = true;
513 * No worries if full removal failed. Consistency checker will take care
514 * of removing the stale entries later, or adjusting the software
515 * database if not in sync with hardware
517 return (atLeastOneRemoved) ? succeeded : error;
521 * This is the function that removes the final container flows merged entry
522 * from the network node and update the database. It expects that all the
523 * validity checks are passed
526 * the flow entry to remove
528 * the flag indicating if this is a asynchronous request
529 * @return the status of this request. In case of asynchronous call, it will
530 * contain the unique id assigned to this request
532 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
533 // Mark the entry to be deleted (for CC just in case we fail)
537 Status status = (async) ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall().getFlow())
538 : programmer.removeFlow(entry.getNode(), entry.getInstall().getFlow());
540 if (!status.isSuccess()) {
541 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
542 status.getDescription());
545 log.trace("Removed {}", entry.getInstall());
548 updateLocalDatabase(entry, false);
554 * This is the function that installs the final container flow merged entry
555 * on the network node and updates the database. It expects that all the
556 * validity and conflict checks are passed. That means it does not check
557 * whether this flow would conflict or overwrite an existing one.
560 * the flow entry to install
562 * the flag indicating if this is a asynchronous request
563 * @return the status of this request. In case of asynchronous call, it will
564 * contain the unique id assigned to this request
566 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
567 // Install the flow on the network node
568 Status status = (async) ? programmer.addFlowAsync(entry.getNode(), entry.getInstall().getFlow()) : programmer
569 .addFlow(entry.getNode(), entry.getInstall().getFlow());
571 if (!status.isSuccess()) {
572 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
573 status.getDescription());
577 log.trace("Added {}", entry.getInstall());
580 entry.setRequestId(status.getRequestId());
581 updateLocalDatabase(entry, true);
587 * Returns true if the flow conflicts with all the container's flows. This
588 * means that if the function returns true, the passed flow entry is
589 * congruent with at least one container flow, hence it is good to be
590 * installed on this container.
593 * @return true if flow conflicts with all the container flows, false
596 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
597 List<ContainerFlow> cFlowList = container.getContainerFlows();
599 // Validity check and avoid unnecessary computation
600 // Also takes care of default container where no container flows are
602 if (cFlowList == null || cFlowList.isEmpty()) {
606 for (ContainerFlow cFlow : cFlowList) {
607 if (cFlow.allowsFlow(flowEntry.getFlow())) {
608 // Entry is allowed by at least one container flow: good to go
615 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
616 // Update the software view
617 updateSwViewes(entry, add);
619 // Update node indexed flow database
620 updateNodeFlowsDB(entry, add);
622 // Update group indexed flow database
623 updateGroupFlowsDB(entry, add);
627 * Update the node mapped flows database
629 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
631 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
632 installedSwView.put(flowEntries, flowEntries);
634 originalSwView.remove(flowEntries.getOriginal());
635 installedSwView.remove(flowEntries);
640 * Update the node mapped flows database
642 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
643 Node node = flowEntries.getNode();
645 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
646 if (nodeIndeces == null) {
650 nodeIndeces = new ArrayList<FlowEntryInstall>();
655 nodeIndeces.add(flowEntries);
657 nodeIndeces.remove(flowEntries);
660 // Update cache across cluster
661 if (nodeIndeces.isEmpty()) {
662 this.nodeFlows.remove(node);
664 this.nodeFlows.put(node, nodeIndeces);
669 * Update the group name mapped flows database
671 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
672 String groupName = flowEntries.getGroupName();
674 // Flow may not be part of a group
675 if (groupName == null) {
679 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
680 if (indices == null) {
684 indices = new ArrayList<FlowEntryInstall>();
689 indices.add(flowEntries);
691 indices.remove(flowEntries);
694 // Update cache across cluster
695 if (indices.isEmpty()) {
696 this.groupFlows.remove(groupName);
698 this.groupFlows.put(groupName, indices);
703 * Remove a flow entry that has been added previously First checks if the
704 * entry is effectively present in the local database
706 @SuppressWarnings("unused")
707 private Status removeEntry(Node node, String flowName) {
708 FlowEntryInstall target = null;
711 for (FlowEntryInstall entry : installedSwView.values()) {
712 if (entry.equalsByNodeAndName(node, flowName)) {
718 // If it is not there, stop any further processing
719 if (target == null) {
720 return new Status(StatusCode.SUCCESS, "Entry is not present");
724 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
727 if (status.isSuccess()) {
728 updateLocalDatabase(target, false);
731 log.warn("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
732 status.getDescription());
739 public Status installFlowEntry(FlowEntry flowEntry) {
741 if (isContainerModeAllowed(flowEntry)) {
742 status = addEntry(flowEntry, false);
744 String msg = "Controller in container mode: Install Refused";
745 String logMsg = msg + ": {}";
746 status = new Status(StatusCode.NOTACCEPTABLE, msg);
747 log.warn(logMsg, flowEntry);
753 public Status installFlowEntryAsync(FlowEntry flowEntry) {
755 if (isContainerModeAllowed(flowEntry)) {
756 status = addEntry(flowEntry, true);
758 String msg = "Controller in container mode: Install Refused";
759 status = new Status(StatusCode.NOTACCEPTABLE, msg);
766 public Status uninstallFlowEntry(FlowEntry flowEntry) {
768 if (isContainerModeAllowed(flowEntry)) {
769 status = removeEntry(flowEntry, false);
771 String msg = "Controller in container mode: Uninstall Refused";
772 String logMsg = msg + ": {}";
773 status = new Status(StatusCode.NOTACCEPTABLE, msg);
774 log.warn(logMsg, flowEntry);
780 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
782 if (isContainerModeAllowed(flowEntry)) {
783 status = removeEntry(flowEntry, true);
785 String msg = "Controller in container mode: Uninstall Refused";
786 status = new Status(StatusCode.NOTACCEPTABLE, msg);
793 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
794 Status status = null;
795 if (isContainerModeAllowed(currentFlowEntry)) {
796 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
798 String msg = "Controller in container mode: Modify Refused";
799 String logMsg = msg + ": {}";
800 status = new Status(StatusCode.NOTACCEPTABLE, msg);
801 log.warn(logMsg, newFlowEntry);
807 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
808 Status status = null;
809 if (isContainerModeAllowed(currentFlowEntry)) {
810 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
812 String msg = "Controller in container mode: Modify Refused";
813 status = new Status(StatusCode.NOTACCEPTABLE, msg);
820 * Returns whether the specified flow entry is allowed to be
821 * installed/removed/modified based on the current container mode status.
822 * This call always returns true in the container instance of forwarding
823 * rules manager. It is meant for the global instance only (default
824 * container) of forwarding rules manager. Idea is that for assuring
825 * container isolation of traffic, flow installation in default container is
826 * blocked when in container mode (containers are present). The only flows
827 * that are allowed in container mode in the default container are the
828 * proactive flows, the ones automatically installed on the network node
829 * which forwarding mode has been configured to "proactive". These flows are
830 * needed by controller to discover the nodes topology and to discover the
831 * attached hosts for some SDN switches.
834 * The flow entry to be installed/removed/modified
835 * @return true if not in container mode or if flowEntry is internally
838 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
839 return (!inContainerMode) ? true : flowEntry.isInternal();
843 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
845 * Run a check on the original entries to decide whether to go with a
846 * add or modify method. A loose check means only check against the
847 * original flow entry requests and not against the installed flow
848 * entries which are the result of the original entry merged with the
849 * container flow(s) (if any). The modifyFlowEntry method in presence of
850 * conflicts with the Container flows (if any) would revert back to a
851 * delete + add pattern
853 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
855 if (currentFlowEntry != null) {
856 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
858 return installFlowEntry(newFlowEntry);
863 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
865 * Run a check on the original entries to decide whether to go with a
866 * add or modify method. A loose check means only check against the
867 * original flow entry requests and not against the installed flow
868 * entries which are the result of the original entry merged with the
869 * container flow(s) (if any). The modifyFlowEntry method in presence of
870 * conflicts with the Container flows (if any) would revert back to a
871 * delete + add pattern
873 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
875 if (currentFlowEntry != null) {
876 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
878 return installFlowEntryAsync(newFlowEntry);
883 public Status uninstallFlowEntryGroup(String groupName) {
884 if (groupName == null || groupName.isEmpty()) {
885 return new Status(StatusCode.BADREQUEST, "Invalid group name");
887 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
888 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
890 if (inContainerMode) {
891 String msg = "Controller in container mode: Group Uninstall Refused";
892 String logMsg = msg + ": {}";
893 log.warn(logMsg, groupName);
894 return new Status(StatusCode.NOTACCEPTABLE, msg);
898 if (groupFlows.containsKey(groupName)) {
899 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
900 toBeRemoved = list.size();
901 for (FlowEntryInstall entry : list) {
902 Status status = this.removeEntry(entry.getOriginal(), false);
903 if (status.isSuccess()) {
906 error = status.getDescription();
910 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
911 "Not all the flows were removed: " + error);
915 public Status uninstallFlowEntryGroupAsync(String groupName) {
916 if (groupName == null || groupName.isEmpty()) {
917 return new Status(StatusCode.BADREQUEST, "Invalid group name");
919 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
920 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
922 if (inContainerMode) {
923 String msg = "Controller in container mode: Group Uninstall Refused";
924 String logMsg = msg + ": {}";
925 log.warn(logMsg, groupName);
926 return new Status(StatusCode.NOTACCEPTABLE, msg);
928 if (groupFlows.containsKey(groupName)) {
929 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
930 for (FlowEntryInstall entry : list) {
931 this.removeEntry(entry.getOriginal(), true);
934 return new Status(StatusCode.SUCCESS);
938 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
939 return entryConflictsWithContainerFlows(flowEntry);
943 * Updates all installed flows because the container flow got updated This
944 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
945 * Reinstall of all flows This is needed because a new container flows
946 * merged flow may conflict with an existing old container flows merged flow
947 * on the network node
949 private void updateFlowsContainerFlow() {
950 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
951 // First remove all installed entries
952 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
953 FlowEntryInstall current = entry.getValue();
954 // Store the original entry
955 toReInstall.add(current.getOriginal());
956 // Remove the old couples. No validity checks to be run, use the
958 this.removeEntryInternal(current, false);
960 // Then reinstall the original entries
961 for (FlowEntry entry : toReInstall) {
962 // Reinstall the original flow entries, via the regular path: new
963 // cFlow merge + validations
964 this.installFlowEntry(entry);
968 private void nonClusterObjectCreate() {
969 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
970 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
971 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
972 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
973 TSPolicies = new ConcurrentHashMap<String, Object>();
974 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
975 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
976 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
977 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
978 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
981 private void registerWithOSGIConsole() {
982 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
983 bundleContext.registerService(CommandProvider.class.getName(), this, null);
987 public void setTSPolicyData(String policyname, Object o, boolean add) {
990 /* Check if this policy already exists */
991 if (!(TSPolicies.containsKey(policyname))) {
992 TSPolicies.put(policyname, o);
995 TSPolicies.remove(policyname);
997 if (frmAware != null) {
998 synchronized (frmAware) {
999 for (IForwardingRulesManagerAware frma : frmAware) {
1001 frma.policyUpdate(policyname, add);
1002 } catch (Exception e) {
1003 log.warn("Exception on callback", e);
1011 public Map<String, Object> getTSPolicyData() {
1016 public Object getTSPolicyData(String policyName) {
1017 if (TSPolicies.containsKey(policyName)) {
1018 return TSPolicies.get(policyName);
1025 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1026 List<FlowEntry> list = new ArrayList<FlowEntry>();
1027 if (policyName != null && !policyName.trim().isEmpty()) {
1028 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1029 if (policyName.equals(entry.getKey().getGroupName())) {
1030 list.add(entry.getKey().clone());
1038 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1040 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1041 if (flow.getFlowName().equals(flowName)) {
1042 FlowEntry currentFlowEntry = flow.getOriginal();
1043 FlowEntry newFlowEntry = currentFlowEntry.clone();
1044 for (NodeConnector dstPort : portList) {
1045 newFlowEntry.getFlow().addAction(new Output(dstPort));
1047 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1048 if (error.isSuccess()) {
1049 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1051 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1052 currentFlowEntry.toString(), error.getDescription());
1057 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1061 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1062 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1063 FlowEntryInstall flow = this.installedSwView.get(index);
1064 if (flow.getFlowName().equals(flowName)) {
1065 FlowEntry currentFlowEntry = flow.getOriginal();
1066 FlowEntry newFlowEntry = currentFlowEntry.clone();
1067 for (NodeConnector dstPort : portList) {
1068 Action action = new Output(dstPort);
1069 newFlowEntry.getFlow().removeAction(action);
1071 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1072 if (status.isSuccess()) {
1073 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1075 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1076 currentFlowEntry.toString(), status.getDescription());
1081 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1085 * This function assumes the target flow has only one output port
1088 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1089 FlowEntry currentFlowEntry = null;
1090 FlowEntry newFlowEntry = null;
1093 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1094 FlowEntryInstall flow = this.installedSwView.get(index);
1095 if (flow.getFlowName().equals(flowName)) {
1096 currentFlowEntry = flow.getOriginal();
1100 if (currentFlowEntry == null) {
1101 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1105 // Create a flow copy with the new output port
1106 newFlowEntry = currentFlowEntry.clone();
1107 Action target = null;
1108 for (Action action : newFlowEntry.getFlow().getActions()) {
1109 if (action.getType() == ActionType.OUTPUT) {
1114 newFlowEntry.getFlow().removeAction(target);
1115 newFlowEntry.getFlow().addAction(new Output(outPort));
1117 // Modify on network node
1118 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1120 if (status.isSuccess()) {
1121 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1123 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1124 status.getDescription());
1130 public NodeConnector getOutputPort(Node node, String flowName) {
1131 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1132 FlowEntryInstall flow = this.installedSwView.get(index);
1133 if (flow.getFlowName().equals(flowName)) {
1134 for (Action action : flow.getOriginal().getFlow().getActions()) {
1135 if (action.getType() == ActionType.OUTPUT) {
1136 return ((Output) action).getPort();
1144 private void cacheStartup() {
1149 @SuppressWarnings("deprecation")
1150 private void allocateCaches() {
1151 if (this.clusterContainerService == null) {
1152 log.warn("Un-initialized clusterContainerService, can't create cache");
1156 log.debug("Allocating caches for Container {}", container.getName());
1159 clusterContainerService.createCache("frm.originalSwView",
1160 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1162 clusterContainerService.createCache("frm.installedSwView",
1163 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1165 clusterContainerService.createCache("frm.inactiveFlows",
1166 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1168 clusterContainerService.createCache("frm.nodeFlows",
1169 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1171 clusterContainerService.createCache("frm.groupFlows",
1172 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1174 clusterContainerService.createCache("frm.staticFlows",
1175 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1177 clusterContainerService.createCache("frm.flowsSaveEvent",
1178 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1180 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1181 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1183 clusterContainerService.createCache("frm.portGroupConfigs",
1184 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1186 clusterContainerService.createCache("frm.portGroupData",
1187 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1189 clusterContainerService.createCache("frm.TSPolicies",
1190 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1192 } catch (CacheConfigException cce) {
1193 log.error("CacheConfigException");
1194 } catch (CacheExistException cce) {
1195 log.error("CacheExistException");
1199 @SuppressWarnings({ "unchecked", "deprecation" })
1200 private void retrieveCaches() {
1201 ConcurrentMap<?, ?> map;
1203 if (this.clusterContainerService == null) {
1204 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1205 nonClusterObjectCreate();
1209 log.debug("Retrieving Caches for Container {}", container.getName());
1211 map = clusterContainerService.getCache("frm.originalSwView");
1213 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1215 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1218 map = clusterContainerService.getCache("frm.installedSwView");
1220 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1222 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1225 map = clusterContainerService.getCache("frm.inactiveFlows");
1227 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1229 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1232 map = clusterContainerService.getCache("frm.nodeFlows");
1234 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1236 log.error("Retrieval of cache failed for Container {}", container.getName());
1239 map = clusterContainerService.getCache("frm.groupFlows");
1241 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1243 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1246 map = clusterContainerService.getCache("frm.staticFlows");
1248 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1250 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1253 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1255 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1257 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1260 map = clusterContainerService.getCache("frm.portGroupConfigs");
1262 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1264 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1267 map = clusterContainerService.getCache("frm.portGroupData");
1269 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1271 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1274 map = clusterContainerService.getCache("frm.TSPolicies");
1276 TSPolicies = (ConcurrentMap<String, Object>) map;
1278 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1283 private boolean flowConfigExists(FlowConfig config) {
1284 // Flow name has to be unique on per node id basis
1285 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1286 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1294 public Status addStaticFlow(FlowConfig config) {
1295 // Configuration object validation
1296 Status status = config.validate(container);
1297 if (!status.isSuccess()) {
1298 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1299 String error = "Invalid Configuration (" + status.getDescription() + ")";
1300 config.setStatus(error);
1301 return new Status(StatusCode.BADREQUEST, error);
1303 return addStaticFlowInternal(config, false);
1307 * Private method to add a static flow configuration which does not run any
1308 * validation on the passed FlowConfig object. If restore is set to true,
1309 * configuration is stored in configuration database regardless the
1310 * installation on the network node was successful. This is useful at boot
1311 * when static flows are present in startup configuration and are read
1312 * before the switches connects.
1315 * The static flow configuration
1317 * if true, the configuration is stored regardless the
1318 * installation on the network node was successful
1319 * @return The status of this request
1321 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1322 boolean multipleFlowPush = false;
1325 config.setStatus(SUCCESS);
1328 if (flowConfigExists(config)) {
1329 error = "Entry with this name on specified switch already exists";
1330 log.warn("Entry with this name on specified switch already exists: {}", config);
1331 config.setStatus(error);
1332 return new Status(StatusCode.CONFLICT, error);
1335 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1336 for (String portGroupName : portGroupConfigs.keySet()) {
1337 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1338 multipleFlowPush = true;
1342 if (!multipleFlowPush) {
1343 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1344 error = "Invalid Configuration (Invalid PortGroup Name)";
1345 config.setStatus(error);
1346 return new Status(StatusCode.BADREQUEST, error);
1351 * If requested program the entry in hardware first before updating the
1354 if (!multipleFlowPush) {
1356 if (config.installInHw()) {
1357 FlowEntry entry = config.getFlowEntry();
1358 status = this.installFlowEntry(entry);
1359 if (!status.isSuccess()) {
1360 config.setStatus(status.getDescription());
1369 * When the control reaches this point, either of the following
1370 * conditions is true 1. This is a single entry configuration (non
1371 * PortGroup) and the hardware installation is successful 2. This is a
1372 * multiple entry configuration (PortGroup) and hardware installation is
1373 * NOT done directly on this event. 3. The User prefers to retain the
1374 * configuration in Controller and skip hardware installation.
1376 * Hence it is safe to update the StaticFlow DB at this point.
1378 * Note : For the case of PortGrouping, it is essential to have this DB
1379 * populated before the PortGroupListeners can query for the DB
1380 * triggered using portGroupChanged event...
1382 Integer ordinal = staticFlowsOrdinal.get(0);
1383 staticFlowsOrdinal.put(0, ++ordinal);
1384 staticFlows.put(ordinal, config);
1386 if (multipleFlowPush) {
1387 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1388 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1389 if (existingData != null) {
1390 portGroupChanged(pgconfig, existingData, true);
1393 return new Status(StatusCode.SUCCESS);
1396 private void addStaticFlowsToSwitch(Node node) {
1397 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1398 FlowConfig config = entry.getValue();
1399 if (config.isPortGroupEnabled()) {
1402 if (config.getNode().equals(node)) {
1403 if (config.installInHw() && !config.getStatus().equals(SUCCESS)) {
1404 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1405 config.setStatus(status.getDescription());
1409 // Update cluster cache
1410 refreshClusterStaticFlowsStatus(node);
1413 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1414 log.trace("Updating Static Flow configs on node down: {}", node);
1416 List<Integer> toRemove = new ArrayList<Integer>();
1417 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1419 FlowConfig config = entry.getValue();
1421 if (config.isPortGroupEnabled()) {
1425 if (config.installInHw() && config.getNode().equals(node)) {
1426 if (config.isInternalFlow()) {
1427 // Take note of this controller generated static flow
1428 toRemove.add(entry.getKey());
1430 config.setStatus(NODEDOWN);
1434 // Remove controller generated static flows for this node
1435 for (Integer index : toRemove) {
1436 staticFlows.remove(index);
1438 // Update cluster cache
1439 refreshClusterStaticFlowsStatus(node);
1443 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1444 log.trace("Updating Static Flow configs on container mode change: {}", update);
1446 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1447 FlowConfig config = entry.getValue();
1448 if (config.isPortGroupEnabled()) {
1451 if (config.installInHw() && !config.isInternalFlow()) {
1454 config.setStatus("Removed from node because in container mode");
1457 config.setStatus(SUCCESS);
1463 // Update cluster cache
1464 refreshClusterStaticFlowsStatus(null);
1468 public Status removeStaticFlow(FlowConfig config) {
1470 * No config.isInternal() check as NB does not take this path and GUI
1471 * cannot issue a delete on an internal generated flow. We need this
1472 * path to be accessible when switch mode is changed from proactive to
1473 * reactive, so that we can remove the internal generated LLDP and ARP
1477 // Look for the target configuration entry
1479 FlowConfig target = null;
1480 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1481 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1482 key = entry.getKey();
1483 target = entry.getValue();
1487 if (target == null) {
1488 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1491 // Program the network node
1492 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1494 // Update configuration database if programming was successful
1495 if (status.isSuccess()) {
1496 staticFlows.remove(key);
1503 public Status removeStaticFlow(String name, Node node) {
1504 // Look for the target configuration entry
1506 FlowConfig target = null;
1507 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1508 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1509 key = mapEntry.getKey();
1510 target = mapEntry.getValue();
1514 if (target == null) {
1515 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1518 // Validity check for api3 entry point
1519 if (target.isInternalFlow()) {
1520 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1521 String logMsg = msg + ": {}";
1522 log.warn(logMsg, name);
1523 return new Status(StatusCode.NOTACCEPTABLE, msg);
1526 if (target.isPortGroupEnabled()) {
1527 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1528 String logMsg = msg + ": {}";
1529 log.warn(logMsg, name);
1530 return new Status(StatusCode.NOTACCEPTABLE, msg);
1533 // Program the network node
1534 Status status = this.removeEntry(target.getFlowEntry(), false);
1536 // Update configuration database if programming was successful
1537 if (status.isSuccess()) {
1538 staticFlows.remove(key);
1545 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1546 // Validity check for api3 entry point
1547 if (newFlowConfig.isInternalFlow()) {
1548 String msg = "Invalid operation: Controller generated flow cannot be modified";
1549 String logMsg = msg + ": {}";
1550 log.warn(logMsg, newFlowConfig);
1551 return new Status(StatusCode.NOTACCEPTABLE, msg);
1555 Status status = newFlowConfig.validate(container);
1556 if (!status.isSuccess()) {
1557 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1558 newFlowConfig.setStatus(msg);
1559 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1560 return new Status(StatusCode.BADREQUEST, msg);
1563 FlowConfig oldFlowConfig = null;
1564 Integer index = null;
1565 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1566 FlowConfig entry = mapEntry.getValue();
1567 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1568 oldFlowConfig = entry;
1569 index = mapEntry.getKey();
1574 if (oldFlowConfig == null) {
1575 String msg = "Attempt to modify a non existing static flow";
1576 String logMsg = msg + ": {}";
1577 log.warn(logMsg, newFlowConfig);
1578 return new Status(StatusCode.NOTFOUND, msg);
1581 // Do not attempt to reinstall the flow, warn user
1582 if (newFlowConfig.equals(oldFlowConfig)) {
1583 String msg = "No modification detected";
1584 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1585 return new Status(StatusCode.SUCCESS, msg);
1588 // If flow is installed, program the network node
1589 status = new Status(StatusCode.SUCCESS, "Saved in config");
1590 if (oldFlowConfig.installInHw()) {
1591 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1594 // Update configuration database if programming was successful
1595 if (status.isSuccess()) {
1596 newFlowConfig.setStatus(status.getDescription());
1597 staticFlows.put(index, newFlowConfig);
1604 public Status toggleStaticFlowStatus(String name, Node node) {
1605 return toggleStaticFlowStatus(getStaticFlow(name, node));
1609 public Status toggleStaticFlowStatus(FlowConfig config) {
1610 if (config == null) {
1611 String msg = "Invalid request: null flow config";
1613 return new Status(StatusCode.BADREQUEST, msg);
1615 // Validity check for api3 entry point
1616 if (config.isInternalFlow()) {
1617 String msg = "Invalid operation: Controller generated flow cannot be modified";
1618 String logMsg = msg + ": {}";
1619 log.warn(logMsg, config);
1620 return new Status(StatusCode.NOTACCEPTABLE, msg);
1623 // Find the config entry
1625 FlowConfig target = null;
1626 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1627 FlowConfig conf = entry.getValue();
1628 if (conf.isByNameAndNodeIdEqual(config)) {
1629 key = entry.getKey();
1634 if (target != null) {
1635 // Program the network node
1636 Status status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1637 .installFlowEntry(target.getFlowEntry());
1638 if (status.isSuccess()) {
1639 // Update Configuration database
1640 target.setStatus(SUCCESS);
1641 target.toggleInstallation();
1642 staticFlows.put(key, target);
1647 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1651 * Reinsert all static flows entries in the cache to force cache updates in
1652 * the cluster. This is useful when only some parameters were changed in the
1653 * entries, like the status.
1656 * The node for which the static flow configurations have to be
1657 * refreshed. If null, all nodes static flows will be refreshed.
1659 private void refreshClusterStaticFlowsStatus(Node node) {
1660 // Refresh cluster cache
1661 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1662 if (node == null || entry.getValue().getNode().equals(node)) {
1663 staticFlows.put(entry.getKey(), entry.getValue());
1669 * Uninstall all the non-internal Flow Entries present in the software view.
1670 * A copy of each entry is stored in the inactive list so that it can be
1671 * re-applied when needed. This function is called on the global instance of
1672 * FRM only, when the first container is created
1674 private void uninstallAllFlowEntries() {
1675 log.info("Uninstalling all non-internal flows");
1677 // Store entries / create target list
1678 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1679 FlowEntryInstall flowEntries = mapEntry.getValue();
1680 // Skip internal generated static flows
1681 if (!flowEntries.isInternal()) {
1682 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1686 // Now remove the entries
1687 for (FlowEntry flowEntry : inactiveFlows.keySet()) {
1688 Status status = this.removeEntry(flowEntry, false);
1689 if (!status.isSuccess()) {
1690 log.warn("Failed to remove entry: {}. The failure is: {}", flowEntry, status.getDescription());
1696 * Re-install all the Flow Entries present in the inactive list The inactive
1697 * list will be empty at the end of this call This function is called on the
1698 * default container instance of FRM only when the last container is deleted
1700 private void reinstallAllFlowEntries() {
1701 log.info("Reinstalling all inactive flows");
1703 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1704 this.addEntry(flowEntry, false);
1707 // Empty inactive list in any case
1708 inactiveFlows.clear();
1712 public List<FlowConfig> getStaticFlows() {
1713 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1716 // TODO: need to come out with a better algorithm for maintaining the order
1717 // of the configuration entries
1718 // with actual one, index associated to deleted entries cannot be reused and
1720 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1721 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1722 for (int i = 0; i <= maxKey; i++) {
1723 FlowConfig entry = flowMap.get(i);
1724 if (entry != null) {
1725 orderedList.add(entry);
1732 public FlowConfig getStaticFlow(String name, Node node) {
1733 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1734 if (entry.getValue().isByNameAndNodeIdEqual(name, node)) {
1735 return entry.getValue();
1742 public List<FlowConfig> getStaticFlows(Node node) {
1743 List<FlowConfig> list = new ArrayList<FlowConfig>();
1744 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1745 if (entry.getValue().onNode(node)) {
1746 list.add(entry.getValue());
1753 public List<String> getStaticFlowNamesForNode(Node node) {
1754 List<String> list = new ArrayList<String>();
1755 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1756 if (entry.getValue().onNode(node)) {
1757 list.add(entry.getValue().getName());
1764 public List<Node> getListNodeWithConfiguredFlows() {
1765 Set<Node> set = new HashSet<Node>();
1766 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1767 set.add(entry.getValue().getNode());
1769 return new ArrayList<Node>(set);
1772 @SuppressWarnings("unchecked")
1773 private void loadFlowConfiguration() {
1774 ObjectReader objReader = new ObjectReader();
1775 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
1778 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
1781 if (pgConfig != null) {
1782 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
1783 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
1787 if (confList == null) {
1792 for (Integer key : confList.keySet()) {
1793 if (key.intValue() > maxKey) {
1794 maxKey = key.intValue();
1798 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
1799 addStaticFlowInternal(conf, true);
1804 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
1805 return ois.readObject();
1809 public Status saveConfig() {
1810 return saveConfigInternal();
1813 private Status saveConfigInternal() {
1814 ObjectWriter objWriter = new ObjectWriter();
1815 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1816 for (Integer ordinal : staticFlows.keySet()) {
1817 FlowConfig config = staticFlows.get(ordinal);
1818 // Do not save dynamic and controller generated static flows
1819 if (config.isDynamic() || config.isInternalFlow()) {
1822 nonDynamicFlows.put(ordinal, config);
1824 objWriter.write(nonDynamicFlows, frmFileName);
1825 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
1826 return new Status(StatusCode.SUCCESS, null);
1830 public void subnetNotify(Subnet sub, boolean add) {
1833 private void installImplicitARPReplyPunt(Node node) {
1839 List<String> puntAction = new ArrayList<String>();
1840 puntAction.add(ActionType.CONTROLLER.toString());
1842 FlowConfig allowARP = new FlowConfig();
1843 allowARP.setInstallInHw(true);
1844 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
1845 allowARP.setPriority("500");
1846 allowARP.setNode(node);
1847 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1848 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
1849 allowARP.setActions(puntAction);
1850 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
1854 public void modeChangeNotify(Node node, boolean proactive) {
1855 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
1857 List<String> puntAction = new ArrayList<String>();
1858 puntAction.add(ActionType.CONTROLLER.toString());
1860 FlowConfig allowARP = new FlowConfig();
1861 allowARP.setInstallInHw(true);
1862 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
1863 allowARP.setPriority("1");
1864 allowARP.setNode(node);
1865 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1866 allowARP.setActions(puntAction);
1867 defaultConfigs.add(allowARP);
1869 FlowConfig allowLLDP = new FlowConfig();
1870 allowLLDP.setInstallInHw(true);
1871 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
1872 allowLLDP.setPriority("1");
1873 allowLLDP.setNode(node);
1874 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue()).toUpperCase());
1875 allowLLDP.setActions(puntAction);
1876 defaultConfigs.add(allowLLDP);
1878 List<String> dropAction = new ArrayList<String>();
1879 dropAction.add(ActionType.DROP.toString());
1881 FlowConfig dropAllConfig = new FlowConfig();
1882 dropAllConfig.setInstallInHw(true);
1883 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop" + FlowConfig.INTERNALSTATICFLOWEND);
1884 dropAllConfig.setPriority("0");
1885 dropAllConfig.setNode(node);
1886 dropAllConfig.setActions(dropAction);
1887 defaultConfigs.add(dropAllConfig);
1889 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
1890 for (FlowConfig fc : defaultConfigs) {
1891 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
1892 if (status.isSuccess()) {
1893 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
1895 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"), fc.getName());
1901 * Remove from the databases all the flows installed on the node
1905 private void cleanDatabaseForNode(Node node) {
1906 log.info("Cleaning Flow database for Node {}", node);
1907 if (nodeFlows.containsKey(node)) {
1908 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
1910 for (FlowEntryInstall entry : toRemove) {
1911 updateLocalDatabase(entry, false);
1917 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
1918 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
1922 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
1926 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
1927 FlowConfig derivedFlow = new FlowConfig(original);
1928 derivedFlow.setDynamic(true);
1929 derivedFlow.setPortGroup(null);
1930 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
1931 derivedFlow.setIngressPort(port + "");
1935 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
1936 for (FlowConfig staticFlow : staticFlows.values()) {
1937 if (staticFlow.getPortGroup() == null) {
1940 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
1941 for (Short port : data.getPorts()) {
1942 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
1943 addStaticFlowInternal(derivedFlow, false);
1949 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
1950 for (FlowConfig staticFlow : staticFlows.values()) {
1951 if (staticFlow.getPortGroup() == null) {
1954 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
1955 for (Short port : data.getPorts()) {
1956 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
1957 removeStaticFlow(derivedFlow);
1964 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
1965 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
1966 Map<Node, PortGroup> existingData = portGroupData.get(config);
1967 if (existingData != null) {
1968 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
1969 PortGroup existingPortGroup = existingData.get(entry.getKey());
1970 if (existingPortGroup == null) {
1972 existingData.put(entry.getKey(), entry.getValue());
1973 addPortGroupFlows(config, entry.getKey(), entry.getValue());
1977 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
1978 addPortGroupFlows(config, entry.getKey(), entry.getValue());
1980 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
1981 removePortGroupFlows(config, entry.getKey(), entry.getValue());
1987 portGroupData.put(config, data);
1988 for (Node swid : data.keySet()) {
1989 addPortGroupFlows(config, swid, data.get(swid));
1996 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
1997 PortGroupConfig config = portGroupConfigs.get(name);
1998 if (config != null) {
2002 if ((portGroupProvider == null) && !restore) {
2005 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2009 config = new PortGroupConfig(name, regex);
2010 portGroupConfigs.put(name, config);
2011 if (portGroupProvider != null) {
2012 portGroupProvider.createPortGroupConfig(config);
2018 public boolean delPortGroupConfig(String name) {
2019 PortGroupConfig config = portGroupConfigs.get(name);
2020 if (config == null) {
2024 if (portGroupProvider != null) {
2025 portGroupProvider.deletePortGroupConfig(config);
2027 portGroupConfigs.remove(name);
2031 private void usePortGroupConfig(String name) {
2032 PortGroupConfig config = portGroupConfigs.get(name);
2033 if (config == null) {
2036 if (portGroupProvider != null) {
2037 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2038 portGroupData.put(config, data);
2043 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2044 return portGroupConfigs;
2047 public boolean isPortGroupSupported() {
2048 if (portGroupProvider == null) {
2054 public void setIContainer(IContainer s) {
2058 public void unsetIContainer(IContainer s) {
2059 if (this.container == s) {
2060 this.container = null;
2065 public PortGroupProvider getPortGroupProvider() {
2066 return portGroupProvider;
2069 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2070 this.portGroupProvider = null;
2073 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2074 this.portGroupProvider = portGroupProvider;
2075 portGroupProvider.registerPortGroupChange(this);
2076 for (PortGroupConfig config : portGroupConfigs.values()) {
2077 portGroupProvider.createPortGroupConfig(config);
2081 public void setFrmAware(IForwardingRulesManagerAware obj) {
2082 this.frmAware.add(obj);
2085 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2086 this.frmAware.remove(obj);
2089 void setClusterContainerService(IClusterContainerServices s) {
2090 log.debug("Cluster Service set");
2091 this.clusterContainerService = s;
2094 void unsetClusterContainerService(IClusterContainerServices s) {
2095 if (this.clusterContainerService == s) {
2096 log.debug("Cluster Service removed!");
2097 this.clusterContainerService = null;
2101 private String getContainerName() {
2102 if (container == null) {
2103 return GlobalConstants.DEFAULT.toString();
2105 return container.getName();
2109 * Function called by the dependency manager when all the required
2110 * dependencies are satisfied
2114 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2115 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2117 inContainerMode = false;
2119 if (portGroupProvider != null) {
2120 portGroupProvider.registerPortGroupChange(this);
2125 registerWithOSGIConsole();
2128 * If we are not the first cluster node to come up, do not initialize
2129 * the static flow entries ordinal
2131 if (staticFlowsOrdinal.size() == 0) {
2132 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2135 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2137 // Initialize the event handler thread
2138 frmEventHandler = new Thread(new Runnable() {
2143 FRMEvent event = pendingEvents.take();
2144 if (event == null) {
2145 log.warn("Dequeued null event");
2148 if (event instanceof NodeUpdateEvent) {
2149 NodeUpdateEvent update = (NodeUpdateEvent) event;
2150 Node node = update.getNode();
2151 switch (update.getUpdateType()) {
2153 addStaticFlowsToSwitch(node);
2156 cleanDatabaseForNode(node);
2157 updateStaticFlowConfigsOnNodeDown(node);
2161 } else if (event instanceof ErrorReportedEvent) {
2162 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2163 processErrorEvent(errEvent);
2165 log.warn("Dequeued unknown event {}", event.getClass().getSimpleName());
2167 } catch (InterruptedException e) {
2168 log.warn("FRM EventHandler thread interrupted", e);
2172 }, "FRM EventHandler Collector");
2176 * Function called by the dependency manager when at least one dependency
2177 * become unsatisfied or when the component is shutting down because for
2178 * example bundle is being stopped.
2186 * Function called by dependency manager after "init ()" is called and after
2187 * the services provided by the class are registered in the service registry
2191 // Initialize graceful stop flag
2194 // Start event handler thread
2195 frmEventHandler.start();
2198 * Read startup and build database if we have not already gotten the
2199 * configurations synced from another node
2201 if (staticFlows.isEmpty()) {
2202 loadFlowConfiguration();
2207 * Function called by the dependency manager before the services exported by
2208 * the component are unregistered, this will be followed by a "destroy ()"
2213 uninstallAllFlowEntries();
2216 public void setFlowProgrammerService(IFlowProgrammerService service) {
2217 this.programmer = service;
2220 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2221 if (this.programmer == service) {
2222 this.programmer = null;
2226 public void setSwitchManager(ISwitchManager switchManager) {
2227 this.switchManager = switchManager;
2230 public void unsetSwitchManager(ISwitchManager switchManager) {
2231 if (this.switchManager == switchManager) {
2232 this.switchManager = null;
2237 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2238 if (!container.getName().equals(containerName)) {
2244 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2245 if (!container.getName().equals(containerName)) {
2248 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2249 container.getName(), t, current);
2251 * Whether it is an addition or removal, we have to recompute the merged
2252 * flows entries taking into account all the current container flows
2253 * because flow merging is not an injective function
2255 updateFlowsContainerFlow();
2259 public void nodeConnectorUpdated(String containerName, NodeConnector p, UpdateType t) {
2260 if (!container.getName().equals(containerName)) {
2266 public void containerModeUpdated(UpdateType update) {
2267 // Only default container instance reacts on this event
2268 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2273 this.inContainerMode = true;
2274 this.uninstallAllFlowEntries();
2277 this.inContainerMode = false;
2278 this.reinstallAllFlowEntries();
2283 // Update our configuration DB
2284 updateStaticFlowConfigsOnContainerModeChange(update);
2287 protected abstract class FRMEvent {
2291 private class NodeUpdateEvent extends FRMEvent {
2292 private final Node node;
2293 private final UpdateType update;
2295 public NodeUpdateEvent(UpdateType update, Node node) {
2296 this.update = update;
2300 public UpdateType getUpdateType() {
2304 public Node getNode() {
2309 private class ErrorReportedEvent extends FRMEvent {
2310 private final long rid;
2311 private final Node node;
2312 private final Object error;
2314 public ErrorReportedEvent(long rid, Node node, Object error) {
2320 public long getRequestId() {
2324 public Object getError() {
2328 public Node getNode() {
2337 public String getHelp() {
2338 StringBuffer help = new StringBuffer();
2339 help.append("---FRM Matrix Application---\n");
2340 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2341 help.append("\t addMatrixConfig <name> <regex>\n");
2342 help.append("\t delMatrixConfig <name>\n");
2343 help.append("\t useMatrixConfig <name>\n");
2344 return help.toString();
2347 public void _printMatrixData(CommandInterpreter ci) {
2348 ci.println("Configs : ");
2349 ci.println("---------");
2350 ci.println(portGroupConfigs);
2352 ci.println("Data : ");
2353 ci.println("------");
2354 ci.println(portGroupData);
2357 public void _addMatrixConfig(CommandInterpreter ci) {
2358 String name = ci.nextArgument();
2359 String regex = ci.nextArgument();
2360 addPortGroupConfig(name, regex, false);
2363 public void _delMatrixConfig(CommandInterpreter ci) {
2364 String name = ci.nextArgument();
2365 delPortGroupConfig(name);
2368 public void _useMatrixConfig(CommandInterpreter ci) {
2369 String name = ci.nextArgument();
2370 usePortGroupConfig(name);
2373 public void _arpPunt(CommandInterpreter ci) {
2374 String switchId = ci.nextArgument();
2375 long swid = HexEncode.stringToLong(switchId);
2376 Node node = NodeCreator.createOFNode(swid);
2377 installImplicitARPReplyPunt(node);
2380 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2382 String nodeId = ci.nextArgument();
2383 if (nodeId == null) {
2384 ci.print("Node id not specified");
2388 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2389 } catch (NumberFormatException e) {
2390 ci.print("Node id not a number");
2393 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2396 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2398 String nodeId = ci.nextArgument();
2399 if (nodeId == null) {
2400 ci.print("Node id not specified");
2404 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2405 } catch (NumberFormatException e) {
2406 ci.print("Node id not a number");
2409 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2412 private Flow getSampleFlow(Node node) throws UnknownHostException {
2413 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2414 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2415 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2416 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2417 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2418 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2419 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2420 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2421 short ethertype = EtherTypes.IPv4.shortValue();
2422 short vlan = (short) 27;
2425 byte proto = IPProtocols.TCP.byteValue();
2426 short src = (short) 55000;
2430 * Create a SAL Flow aFlow
2432 Match match = new Match();
2433 match.setField(MatchType.IN_PORT, port);
2434 match.setField(MatchType.DL_SRC, srcMac);
2435 match.setField(MatchType.DL_DST, dstMac);
2436 match.setField(MatchType.DL_TYPE, ethertype);
2437 match.setField(MatchType.DL_VLAN, vlan);
2438 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2439 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2440 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2441 match.setField(MatchType.NW_TOS, tos);
2442 match.setField(MatchType.NW_PROTO, proto);
2443 match.setField(MatchType.TP_SRC, src);
2444 match.setField(MatchType.TP_DST, dst);
2446 List<Action> actions = new ArrayList<Action>();
2447 actions.add(new Output(oport));
2448 actions.add(new PopVlan());
2449 actions.add(new Flood());
2450 actions.add(new Controller());
2451 return new Flow(match, actions);
2455 public Status saveConfiguration() {
2456 return saveConfig();
2459 public void _frmNodeFlows(CommandInterpreter ci) {
2460 String nodeId = ci.nextArgument();
2461 Node node = Node.fromString(nodeId);
2463 ci.println("frmNodeFlows <node> [verbose]");
2466 boolean verbose = false;
2467 String verboseCheck = ci.nextArgument();
2468 if (verboseCheck != null) {
2469 verbose = verboseCheck.equals("true");
2472 if (!nodeFlows.containsKey(node)) {
2475 // Dump per node database
2476 for (FlowEntryInstall entry : nodeFlows.get(node)) {
2478 ci.println(node + " " + installedSwView.get(entry).getFlowName());
2480 ci.println(node + " " + installedSwView.get(entry).toString());
2485 public void _frmGroupFlows(CommandInterpreter ci) {
2486 String group = ci.nextArgument();
2487 if (group == null) {
2488 ci.println("frmGroupFlows <group> [verbose]");
2491 boolean verbose = false;
2492 String verboseCheck = ci.nextArgument();
2493 if (verboseCheck != null) {
2494 verbose = verboseCheck.equalsIgnoreCase("true");
2497 if (!groupFlows.containsKey(group)) {
2500 // Dump per node database
2501 ci.println("Group " + group + ":\n");
2502 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
2504 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
2506 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
2512 public void flowRemoved(Node node, Flow flow) {
2513 log.trace("Received flow removed notification on {} for {}", node, flow);
2515 // For flow entry identification, only node, match and priority matter
2516 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2517 FlowEntryInstall installedEntry = this.installedSwView.get(test);
2518 if (installedEntry == null) {
2519 log.trace("Entry is not known to us");
2523 // Update Static flow status
2525 FlowConfig target = null;
2526 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2527 FlowConfig conf = entry.getValue();
2528 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
2529 key = entry.getKey();
2534 if (target != null) {
2535 // Update Configuration database
2536 target.toggleInstallation();
2537 target.setStatus(SUCCESS);
2538 staticFlows.put(key, target);
2541 // Update software views
2542 this.updateLocalDatabase(installedEntry, false);
2546 public void flowErrorReported(Node node, long rid, Object err) {
2547 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
2548 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
2551 private void processErrorEvent(ErrorReportedEvent event) {
2552 Node node = event.getNode();
2553 long rid = event.getRequestId();
2554 Object error = event.getError();
2555 String errorString = (error == null) ? "Not provided" : error.toString();
2557 * If this was for a flow install, remove the corresponding entry from
2558 * the software view. If it was a Looking for the rid going through the
2559 * software database. TODO: A more efficient rid <-> FlowEntryInstall
2560 * mapping will have to be added in future
2562 FlowEntryInstall target = null;
2563 for (FlowEntryInstall index : nodeFlows.get(node)) {
2564 FlowEntryInstall entry = installedSwView.get(index);
2565 if (entry.getRequestId() == rid) {
2570 if (target != null) {
2571 // This was a flow install, update database
2572 this.updateLocalDatabase(target, false);
2576 if (frmAware != null) {
2577 synchronized (frmAware) {
2578 for (IForwardingRulesManagerAware frma : frmAware) {
2580 frma.requestFailed(rid, errorString);
2581 } catch (Exception e) {
2582 log.warn("Failed to notify {}", frma);
2590 public Status solicitStatusResponse(Node node, boolean blocking) {
2591 Status rv = new Status(StatusCode.INTERNALERROR);
2593 if (this.programmer != null) {
2595 rv = programmer.syncSendBarrierMessage(node);
2597 rv = programmer.asyncSendBarrierMessage(node);