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.EtherTypes;
67 import org.opendaylight.controller.sal.utils.GlobalConstants;
68 import org.opendaylight.controller.sal.utils.HexEncode;
69 import org.opendaylight.controller.sal.utils.IObjectReader;
70 import org.opendaylight.controller.sal.utils.IPProtocols;
71 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
72 import org.opendaylight.controller.sal.utils.NodeCreator;
73 import org.opendaylight.controller.sal.utils.ObjectReader;
74 import org.opendaylight.controller.sal.utils.ObjectWriter;
75 import org.opendaylight.controller.sal.utils.Status;
76 import org.opendaylight.controller.sal.utils.StatusCode;
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
142 * the flag indicating if this is a asynchronous request
143 * @return the status of this request. In case of asynchronous call, it
144 * will contain the unique id assigned to this request
146 private Status addEntry(FlowEntry flowEntry, boolean async) {
149 if (flowEntry == null || flowEntry.getNode() == null) {
150 String msg = "Invalid FlowEntry";
151 String logMsg = msg + ": {}";
152 log.warn(logMsg, flowEntry);
153 return new Status(StatusCode.NOTACCEPTABLE, msg);
157 * Derive the container flow merged entries to install In presence of N
158 * container flows, we may end up with N different entries to install...
160 List<FlowEntryInstall> toInstallList = deriveInstallEntries(
161 flowEntry.clone(), container.getContainerFlows());
163 // Container Flow conflict Check
164 if (toInstallList.isEmpty()) {
165 String msg = "Flow Entry conflicts with all Container Flows";
166 String logMsg = msg + ": {}";
167 log.warn(logMsg, flowEntry);
168 return new Status(StatusCode.CONFLICT, msg);
171 // Derive the list of entries good to be installed
172 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
173 for (FlowEntryInstall entry : toInstallList) {
174 // Conflict Check: Verify new entry would not overwrite existing
176 if (findMatch(entry.getInstall(), false) != null) {
177 log.warn("Operation Rejected: A flow with same match "
178 + "and priority exists on the target node");
179 log.trace("Aborting to install {}", entry);
182 toInstallSafe.add(entry);
185 // Declare failure if all the container flow merged entries clash with
187 if (toInstallSafe.size() == 0) {
188 String msg = "A flow with same match and priority exists "
189 + "on the target node";
190 String logMsg = msg + ": {}";
191 log.warn(logMsg, flowEntry);
192 return new Status(StatusCode.CONFLICT, msg);
195 // Try to install an entry at the time
196 Status error = new Status(null, null);
197 Status succeded = null;
198 boolean oneSucceded = false;
199 for (FlowEntryInstall installEntry : toInstallSafe) {
201 // Install and update database
202 Status ret = addEntriesInternal(installEntry, async);
204 if (ret.isSuccess()) {
207 * The first successful status response will be returned
208 * For the asynchronous call, we can discard the container flow
209 * complication for now and assume we will always deal with
210 * one flow only per request
215 log.warn("Failed to install the entry: {}. The failure is: {}",
216 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,
238 List<ContainerFlow> cFlowList) {
239 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(
242 if (container.getContainerFlows() == null
243 || container.getContainerFlows().isEmpty()) {
244 // No container flows => entry good to be installed unchanged
245 toInstallList.add(new FlowEntryInstall(request.clone(), null));
247 // Create the list of entries to be installed. If the flow entry is
248 // not congruent with any container flow, no install entries will be
250 for (ContainerFlow cFlow : container.getContainerFlows()) {
251 if (cFlow.allowsFlow(request.getFlow())) {
252 toInstallList.add(new FlowEntryInstall(request.clone(),
257 return toInstallList;
261 * Modify a flow entry with a new one It runs various validity check and
262 * derive the final container flows merged flow entries to work with
264 * @param currentFlowEntry
265 * @param newFlowEntry
267 * the flag indicating if this is a asynchronous request
268 * @return the status of this request. In case of asynchronous call, it
269 * will contain the unique id assigned to this request
271 private Status modifyEntry(FlowEntry currentFlowEntry,
272 FlowEntry newFlowEntry, boolean async) {
277 if (currentFlowEntry == null || currentFlowEntry.getNode() == null
278 || newFlowEntry == null || newFlowEntry.getNode() == null) {
279 String msg = "Modify: Invalid FlowEntry";
280 String logMsg = msg + ": {} or {}";
281 log.warn(logMsg, currentFlowEntry, newFlowEntry);
282 return new Status(StatusCode.NOTACCEPTABLE, msg);
284 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
285 || !currentFlowEntry.getFlowName().equals(
286 newFlowEntry.getFlowName())) {
287 String msg = "Modify: Incompatible Flow Entries";
288 String logMsg = msg + ": {} and {}";
289 log.warn(logMsg, currentFlowEntry, newFlowEntry);
290 return new Status(StatusCode.NOTACCEPTABLE, msg);
294 if (currentFlowEntry.equals(newFlowEntry)) {
295 String msg = "Modify skipped as flows are the same";
296 String logMsg = msg + ": {} and {}";
297 log.debug(logMsg, currentFlowEntry, newFlowEntry);
298 return new Status(StatusCode.SUCCESS, msg);
301 // Conflict Check: Verify the new entry would not conflict with another
303 // This is a loose check on the previous original flow entry requests.
305 // on the container flow merged flow entries (if any) yet
306 FlowEntryInstall sameMatchOriginalEntry = findMatch(newFlowEntry, true);
307 if (sameMatchOriginalEntry != null
308 && !sameMatchOriginalEntry.getOriginal().equals(
310 String msg = "Operation Rejected: Another flow with same match "
311 + "and priority exists on the target node";
312 String logMsg = msg + ": {}";
313 log.warn(logMsg, currentFlowEntry);
314 return new Status(StatusCode.CONFLICT, msg);
317 // Derive the installed and toInstall entries
318 List<FlowEntryInstall> installedList = deriveInstallEntries(
319 currentFlowEntry.clone(), container.getContainerFlows());
320 List<FlowEntryInstall> toInstallList = deriveInstallEntries(
321 newFlowEntry.clone(), container.getContainerFlows());
323 if (toInstallList.isEmpty()) {
324 String msg = "Modify Operation Rejected: The new entry "
325 + "conflicts with all the container flows";
326 String logMsg = msg + ": {}";
327 log.warn(logMsg, newFlowEntry);
329 return new Status(StatusCode.CONFLICT, msg);
333 * If the two list sizes differ, it means the new flow entry does not
334 * satisfy the same number of container flows the current entry does.
335 * This is only possible when the new entry and current entry have
336 * different match. In this scenario the modification would ultimately
337 * be handled as a remove and add operations in the protocol plugin.
339 * Also, if any of the new flow entries would clash with an existing
340 * one, we cannot proceed with the modify operation, because it would
341 * fail for some entries and leave stale entries on the network node.
342 * Modify path can be taken only if it can be performed completely, for
345 * So, for the above two cases, to simplify, let's decouple the modify
346 * in: 1) remove current entries 2) install new entries
348 Status succeeded = null;
349 boolean decouple = false;
350 if (installedList.size() != toInstallList.size()) {
351 log.info("Modify: New flow entry does not satisfy the same "
352 + "number of container flows as the original entry does");
355 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
356 for (FlowEntryInstall installEntry : toInstallList) {
357 // Conflict Check: Verify the new entry would not overwrite another
359 FlowEntryInstall sameMatchEntry = findMatch(
360 installEntry.getInstall(), false);
361 if (sameMatchEntry != null
362 && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
363 log.info("Modify: new container flow merged flow entry "
364 + "clashes with existing flow");
367 toInstallSafe.add(installEntry);
372 // Remove current entries
373 for (FlowEntryInstall currEntry : installedList) {
374 this.removeEntryInternal(currEntry, async);
376 // Install new entries
377 for (FlowEntryInstall newEntry : toInstallSafe) {
378 succeeded = this.addEntriesInternal(newEntry, async);
382 * The two list have the same size and the entries to install do not
383 * clash with any existing flow on the network node. We assume here
384 * (and might be wrong) that the same container flows that were
385 * satisfied by the current entries are the same that are satisfied
386 * by the new entries. Let's take the risk for now.
388 * Note: modification has to be complete. If any entry modification
389 * fails, we need to stop, restore the already modified entries, and
392 Status retModify = null;
394 int size = toInstallList.size();
396 // Modify and update database
397 retModify = modifyEntryInternal(installedList.get(i),
398 toInstallList.get(i), async);
399 if (retModify.isSuccess()) {
405 // Check if uncompleted modify
407 log.warn("Unable to perform a complete modify for all "
408 + "the container flows merged entries");
409 // Restore original entries
412 log.info("Attempting to restore initial entries");
413 retExt = modifyEntryInternal(toInstallList.get(i),
414 installedList.get(i), async);
415 if (retExt.isSuccess()) {
421 // Fatal error, recovery failed
423 String msg = "Flow recovery failed ! Unrecoverable Error";
425 return new Status(StatusCode.INTERNALERROR, msg);
428 succeeded = retModify;
431 * The first successful status response will be returned.
432 * For the asynchronous call, we can discard the container flow
433 * complication for now and assume we will always deal with
434 * one flow only per request
440 * This is the function that modifies the final container flows merged
441 * entries on the network node and update the database. It expects that all
442 * the validity checks are passed
444 * @param currentEntries
447 * the flag indicating if this is a asynchronous request
448 * @return the status of this request. In case of asynchronous call, it
449 * will contain the unique id assigned to this request
451 private Status modifyEntryInternal(FlowEntryInstall currentEntries,
452 FlowEntryInstall newEntries, boolean async) {
453 // Modify the flow on the network node
454 Status status = (async)?
455 programmer.modifyFlowAsync(currentEntries.getNode(),
456 currentEntries.getInstall().getFlow(), newEntries.getInstall()
458 programmer.modifyFlow(currentEntries.getNode(),
459 currentEntries.getInstall().getFlow(), newEntries.getInstall()
463 if (!status.isSuccess()) {
465 "SDN Plugin failed to program the flow: {}. The failure is: {}",
466 newEntries.getInstall(), status.getDescription());
470 log.trace("Modified {} => {}", currentEntries.getInstall(),
471 newEntries.getInstall());
474 newEntries.setRequestId(status.getRequestId());
475 updateLocalDatabase(currentEntries, false);
476 updateLocalDatabase(newEntries, true);
482 * Remove a flow entry. If the entry is not present in the software view
483 * (entry or node not present), it return successfully
486 * the flow entry to remove
488 * the flag indicating if this is a asynchronous request
489 * @return the status of this request. In case of asynchronous call, it
490 * will contain the unique id assigned to this request
492 private synchronized Status removeEntry(FlowEntry flowEntry, boolean async) {
493 Status error = new Status(null, null);
496 if (flowEntry == null || flowEntry.getNode() == null) {
497 String msg = "Invalid FlowEntry";
498 String logMsg = msg + ": {}";
499 log.warn(logMsg, flowEntry);
500 return new Status(StatusCode.NOTACCEPTABLE, msg);
503 // Derive the container flows merged installed entries
504 List<FlowEntryInstall> installedList = deriveInstallEntries(
505 flowEntry.clone(), container.getContainerFlows());
507 Set<FlowEntryInstall> flowsOnNode = nodeFlows.get(flowEntry.getNode());
508 Status succeeded = null;
509 boolean atLeastOneRemoved = false;
510 for (FlowEntryInstall entry : installedList) {
511 if (flowsOnNode == null) {
512 String msg = "Removal skipped (Node down) for flow entry";
513 String logMsg = msg + ": {}";
514 log.debug(logMsg, flowEntry);
515 return new Status(StatusCode.SUCCESS, msg);
517 if (!flowsOnNode.contains(entry)) {
518 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
519 log.debug(logMsg, flowEntry);
520 if (installedList.size() == 1) {
521 // If we had only one entry to remove, we are done
522 return new Status(StatusCode.SUCCESS);
528 // Remove and update DB
529 Status ret = removeEntryInternal(entry, async);
531 if (!ret.isSuccess()) {
533 log.warn("Failed to remove the entry: {}. The failure is: {}",
534 entry.getInstall(), ret.getDescription());
535 if (installedList.size() == 1) {
536 // If we had only one entry to remove, this is fatal failure
541 atLeastOneRemoved = true;
546 * No worries if full removal failed. Consistency checker will take care
547 * of removing the stale entries later, or adjusting the software
548 * database if not in sync with hardware
550 return (atLeastOneRemoved) ? succeeded : error;
554 * This is the function that removes the final container flows merged entry
555 * from the network node and update the database. It expects that all the
556 * validity checks are passed
559 * the flow entry to remove
561 * the flag indicating if this is a asynchronous request
562 * @return the status of this request. In case of asynchronous call, it
563 * will contain the unique id assigned to this request
565 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
566 // Mark the entry to be deleted (for CC just in case we fail)
570 Status status = (async)?
571 programmer.removeFlowAsync(entry.getNode(), entry
572 .getInstall().getFlow()) :
573 programmer.removeFlow(entry.getNode(), entry
574 .getInstall().getFlow());
577 if (!status.isSuccess()) {
579 "SDN Plugin failed to program the flow: {}. The failure is: {}",
580 entry.getInstall(), status.getDescription());
583 log.trace("Removed {}", entry.getInstall());
586 updateLocalDatabase(entry, false);
592 * This is the function that installs the final container flow merged entry
593 * on the network node and updates the database. It expects that all the
594 * validity and conflict checks are passed. That means it does not check
595 * whether this flow would conflict or overwrite an existing one.
598 * the flow entry to install
600 * the flag indicating if this is a asynchronous request
601 * @return the status of this request. In case of asynchronous call, it
602 * will contain the unique id assigned to this request
604 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
605 // Install the flow on the network node
606 Status status = (async)?
607 programmer.addFlowAsync(entry.getNode(), entry.getInstall()
609 programmer.addFlow(entry.getNode(), entry.getInstall()
613 if (!status.isSuccess()) {
615 "SDN Plugin failed to program the flow: {}. The failure is: {}",
616 entry.getInstall(), status.getDescription());
620 log.trace("Added {}", entry.getInstall());
623 entry.setRequestId(status.getRequestId());
624 updateLocalDatabase(entry, true);
630 * Returns true if the flow conflicts with all the container's flows. This
631 * means that if the function returns true, the passed flow entry is
632 * congruent with at least one container flow, hence it is good to be
633 * installed on this container.
636 * @return true if flow conflicts with all the container flows, false
639 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
640 List<ContainerFlow> cFlowList = container.getContainerFlows();
642 // Validity check and avoid unnecessary computation
643 // Also takes care of default container where no container flows are
645 if (cFlowList == null || cFlowList.isEmpty()) {
649 for (ContainerFlow cFlow : cFlowList) {
650 if (cFlow.allowsFlow(flowEntry.getFlow())) {
651 // Entry is allowed by at least one container flow: good to go
658 private synchronized void updateLocalDatabase(FlowEntryInstall entry,
660 // Update node indexed flow database
661 updateNodeFlowsDB(entry, add);
663 // Update group indexed flow database
664 updateGroupFlowsDB(entry, add);
668 * Update the node mapped flows database
670 private synchronized void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
671 Node node = flowEntries.getNode();
673 Set<FlowEntryInstall> flowEntrylist = this.nodeFlows.get(node);
674 if (flowEntrylist == null) {
678 flowEntrylist = new HashSet<FlowEntryInstall>();
683 flowEntrylist.add(flowEntries);
685 flowEntrylist.remove(flowEntries);
688 if (flowEntrylist.isEmpty()) {
689 this.nodeFlows.remove(node);
691 this.nodeFlows.put(node, flowEntrylist);
696 * Update the group name mapped flows database
698 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
699 Set<FlowEntryInstall> flowList;
700 FlowEntryInstall exists = null;
701 String flowName = flowEntries.getFlowName();
702 String groupName = flowEntries.getGroupName();
704 if (this.groupFlows == null) {
708 // Flow may not be part of a group
709 if (groupName == null) {
713 if (this.groupFlows.containsKey(groupName)) {
714 flowList = this.groupFlows.get(groupName);
719 flowList = new HashSet<FlowEntryInstall>();
723 for (FlowEntryInstall flow : flowList) {
724 if (flow.equalsByNodeAndName(flowEntries.getNode(), flowName)) {
730 if (exists == null && add == false) {
734 if (exists != null) {
735 flowList.remove(exists);
739 flowList.add(flowEntries);
742 if (flowList.isEmpty()) {
743 this.groupFlows.remove(groupName);
745 this.groupFlows.put(groupName, flowList);
750 * Remove a flow entry that has been added previously First checks if the
751 * entry is effectively present in the local database
753 @SuppressWarnings("unused")
754 private synchronized Status removeEntry(Node node, String flowName) {
755 FlowEntryInstall target = null;
758 for (FlowEntryInstall entry : this.nodeFlows.get(node)) {
759 if (entry.equalsByNodeAndName(node, flowName)) {
765 // If it is not there, stop any further processing
766 if (target == null) {
767 return new Status(StatusCode.SUCCESS, "Entry is not present");
771 Status status = programmer.removeFlow(target.getNode(), target
772 .getInstall().getFlow());
775 if (status.isSuccess()) {
776 updateLocalDatabase(target, false);
780 "SDN Plugin failed to remove the flow: {}. The failure is: {}",
781 target.getInstall(), status.getDescription());
788 public Status installFlowEntry(FlowEntry flowEntry) {
790 if (inContainerMode) {
791 String msg = "Controller in container mode: Install Refused";
792 String logMsg = msg + ": {}";
793 status = new Status(StatusCode.NOTACCEPTABLE, msg);
794 log.warn(logMsg, flowEntry);
796 status = addEntry(flowEntry, false);
802 public Status installFlowEntryAsync(FlowEntry flowEntry) {
804 if (inContainerMode) {
805 String msg = "Controller in container mode: Install Refused";
806 status = new Status(StatusCode.NOTACCEPTABLE, msg);
809 status = addEntry(flowEntry, true);
815 public Status uninstallFlowEntry(FlowEntry entry) {
817 if (inContainerMode) {
818 String msg = "Controller in container mode: Uninstall Refused";
819 String logMsg = msg + ": {}";
820 status = new Status(StatusCode.NOTACCEPTABLE, msg);
821 log.warn(logMsg, entry);
823 status = removeEntry(entry, false);
829 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
831 if (inContainerMode) {
832 String msg = "Controller in container mode: Uninstall Refused";
833 status = new Status(StatusCode.NOTACCEPTABLE, msg);
836 status = removeEntry(flowEntry, true);
842 public Status modifyFlowEntry(FlowEntry currentFlowEntry,
843 FlowEntry newFlowEntry) {
844 Status status = null;
845 if (inContainerMode) {
846 String msg = "Controller in container mode: Modify Refused";
847 String logMsg = msg + ": {}";
848 status = new Status(StatusCode.NOTACCEPTABLE, msg);
849 log.warn(logMsg, newFlowEntry);
851 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
857 public Status modifyFlowEntryAsync(FlowEntry current, FlowEntry newone) {
858 Status status = null;
859 if (inContainerMode) {
860 String msg = "Controller in container mode: Modify Refused";
861 status = new Status(StatusCode.NOTACCEPTABLE, msg);
864 status = modifyEntry(current, newone, true);
870 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
872 * Run a loose check on the installed entries to decide whether to go
873 * with a add or modify method. A loose check means only check against
874 * the original flow entry requests and not against the installed flow
875 * entries which are the result of the original entry merged with the
876 * container flow(s) (if any). The modifyFlowEntry method in presence of
877 * conflicts with the Container flows (if any) would revert back to a
878 * delete + add pattern
880 FlowEntryInstall currentFlowEntries = findMatch(newFlowEntry, true);
882 if (currentFlowEntries != null) {
883 return modifyFlowEntry(currentFlowEntries.getOriginal(),
886 return installFlowEntry(newFlowEntry);
891 public Status modifyOrAddFlowEntryAsync(FlowEntry newone) {
893 * Run a loose check on the installed entries to decide whether to go
894 * with a add or modify method. A loose check means only check against
895 * the original flow entry requests and not against the installed flow
896 * entries which are the result of the original entry merged with the
897 * container flow(s) (if any). The modifyFlowEntry method in presence of
898 * conflicts with the Container flows (if any) would revert back to a
899 * delete + add pattern
901 FlowEntryInstall currentFlowEntries = findMatch(newone, true);
903 if (currentFlowEntries != null) {
904 return modifyFlowEntryAsync(currentFlowEntries.getOriginal(),
907 return installFlowEntryAsync(newone);
913 * Try to find in the database if a Flow with the same Match and priority of
914 * the passed one already exists for the specified network node. Flow,
915 * priority and network node are all specified in the FlowEntry If found,
916 * the respective FlowEntryInstall Object is returned
919 * the FlowEntry to be tested against the ones installed
921 * if true, the function will run the check against the original
922 * flow entry portion of the installed entries
923 * @return null if not found, otherwise the FlowEntryInstall which contains
924 * the existing flow entry
926 private synchronized FlowEntryInstall findMatch(FlowEntry flowEntry, boolean looseCheck) {
927 Flow flow = flowEntry.getFlow();
928 Match match = flow.getMatch();
929 short priority = flow.getPriority();
930 Set<FlowEntryInstall> thisNodeList = nodeFlows.get(flowEntry.getNode());
932 if (thisNodeList != null) {
933 for (FlowEntryInstall flowEntries : thisNodeList) {
934 flow = (looseCheck == false) ? flowEntries.getInstall()
935 .getFlow() : flowEntries.getOriginal().getFlow();
936 if (flow.getMatch().equals(match)
937 && flow.getPriority() == priority) {
945 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
946 return entryConflictsWithContainerFlows(flowEntry);
950 * Updates all installed flows because the container flow got updated This
951 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
952 * Reinstall of all flows This is needed because a new container flows
953 * merged flow may conflict with an existing old container flows merged flow
954 * on the network node
956 private synchronized void updateFlowsContainerFlow() {
957 List<FlowEntryInstall> oldCouples = new ArrayList<FlowEntryInstall>();
958 List<FlowEntry> toReinstall = new ArrayList<FlowEntry>();
959 for (Entry<Node, Set<FlowEntryInstall>> entry : this.nodeFlows
963 if (entry.getValue() == null) {
966 // Create a set of old entries and one of original entries to be
968 for (FlowEntryInstall oldCouple : entry.getValue()) {
969 oldCouples.add(oldCouple);
970 toReinstall.add(oldCouple.getOriginal());
972 // Remove the old couples. No validity checks to be run, use the
974 for (FlowEntryInstall oldCouple : oldCouples) {
975 this.removeEntryInternal(oldCouple, false);
977 // Reinstall the original flow entries, via the regular path: new
978 // cFlow merge + validations
979 for (FlowEntry flowEntry : toReinstall) {
980 this.installFlowEntry(flowEntry);
985 public void nonClusterObjectCreate() {
986 nodeFlows = new ConcurrentHashMap<Node, Set<FlowEntryInstall>>();
987 TSPolicies = new ConcurrentHashMap<String, Object>();
988 groupFlows = new ConcurrentHashMap<String, Set<FlowEntryInstall>>();
989 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
990 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
991 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
992 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
993 flowsSaveEvent = new HashMap<Long, String>();
994 inactiveFlows = new ArrayList<FlowEntry>(1);
997 private void registerWithOSGIConsole() {
998 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
1000 bundleContext.registerService(CommandProvider.class.getName(), this,
1005 public void setTSPolicyData(String policyname, Object o, boolean add) {
1008 /* Check if this policy already exists */
1009 if (!(TSPolicies.containsKey(policyname))) {
1010 TSPolicies.put(policyname, o);
1013 TSPolicies.remove(policyname);
1015 if (frmAware != null) {
1016 synchronized (frmAware) {
1017 for (IForwardingRulesManagerAware frma : frmAware) {
1019 frma.policyUpdate(policyname, add);
1020 } catch (Exception e) {
1021 log.warn("Exception on callback", e);
1029 public Map<String, Object> getTSPolicyData() {
1034 public Object getTSPolicyData(String policyName) {
1035 if (TSPolicies.containsKey(policyName)) {
1036 return TSPolicies.get(policyName);
1043 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1044 List<FlowEntry> list = null;
1045 if (this.groupFlows != null && this.groupFlows.containsKey(policyName)) {
1046 list = new ArrayList<FlowEntry>();
1047 for (FlowEntryInstall entries : groupFlows.get(policyName)) {
1048 list.add(entries.getOriginal());
1050 return new ArrayList<FlowEntry>();
1056 public synchronized void addOutputPort(Node node, String flowName,
1057 List<NodeConnector> portList) {
1059 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
1061 for (FlowEntryInstall flow : flowEntryList) {
1062 if (flow.getFlowName().equals(flowName)) {
1063 FlowEntry currentFlowEntry = flow.getOriginal();
1064 FlowEntry newFlowEntry = currentFlowEntry.clone();
1065 for (NodeConnector dstPort : portList) {
1066 newFlowEntry.getFlow().addAction(new Output(dstPort));
1068 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1069 if (error.isSuccess()) {
1070 log.info("Ports {} added to FlowEntry {}", portList,
1074 "Failed to add ports {} to Flow entry {}. The failure is: {}",
1075 portList, currentFlowEntry.toString(),
1076 error.getDescription());
1081 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found",
1086 public synchronized void removeOutputPort(Node node, String flowName,
1087 List<NodeConnector> portList) {
1089 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
1091 for (FlowEntryInstall flow : flowEntryList) {
1092 if (flow.getFlowName().equals(flowName)) {
1093 FlowEntry currentFlowEntry = flow.getOriginal();
1094 FlowEntry newFlowEntry = currentFlowEntry.clone();
1095 for (NodeConnector dstPort : portList) {
1096 Action action = new Output(dstPort);
1097 newFlowEntry.getFlow().removeAction(action);
1099 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1100 if (status.isSuccess()) {
1101 log.info("Ports {} removed from FlowEntry {}", portList,
1105 "Failed to remove ports {} from Flow entry {}. The failure is: {}",
1106 portList, currentFlowEntry.toString(),
1107 status.getDescription());
1113 "Failed to remove ports from Flow {} on Node {}: Entry Not Found",
1118 * This function assumes the target flow has only one output port
1121 public synchronized void replaceOutputPort(Node node, String flowName,
1122 NodeConnector outPort) {
1123 FlowEntry currentFlowEntry = null;
1124 FlowEntry newFlowEntry = null;
1125 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
1128 for (FlowEntryInstall flow : flowEntryList) {
1129 if (flow.getFlowName().equals(flowName)) {
1130 currentFlowEntry = flow.getOriginal();
1134 if (currentFlowEntry == null) {
1136 "Failed to replace output port for flow {} on node {}: Entry Not Found",
1141 // Create a flow copy with the new output port
1142 newFlowEntry = currentFlowEntry.clone();
1143 Action target = null;
1144 for (Action action : newFlowEntry.getFlow().getActions()) {
1145 if (action.getType() == ActionType.OUTPUT) {
1150 newFlowEntry.getFlow().removeAction(target);
1151 newFlowEntry.getFlow().addAction(new Output(outPort));
1153 // Modify on network node
1154 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1156 if (status.isSuccess()) {
1157 log.info("Output port replaced with {} for flow {} on node {}",
1158 outPort, flowName, node);
1161 "Failed to replace output port for flow {} on node {}. The failure is: {}",
1162 flowName, node, status.getDescription());
1168 public synchronized NodeConnector getOutputPort(Node node, String flowName) {
1169 Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
1171 for (FlowEntryInstall flow : flowEntryList) {
1172 if (flow.getFlowName().equals(flowName)) {
1173 for (Action action : flow.getOriginal().getFlow().getActions()) {
1174 if (action.getType() == ActionType.OUTPUT) {
1175 return ((Output) action).getPort();
1184 private void cacheStartup() {
1189 @SuppressWarnings("deprecation")
1190 private void allocateCaches() {
1191 if (this.clusterContainerService == null) {
1192 log.warn("Un-initialized clusterContainerService, can't create cache");
1196 log.debug("FRM allocateCaches for Container {}", container);
1199 clusterContainerService.createCache("frm.nodeFlows",
1200 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1202 clusterContainerService.createCache("frm.groupFlows",
1203 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1205 clusterContainerService.createCache("frm.staticFlows",
1206 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1208 clusterContainerService.createCache("frm.flowsSaveEvent",
1209 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1211 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1212 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1214 clusterContainerService.createCache("frm.portGroupConfigs",
1215 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1217 clusterContainerService.createCache("frm.portGroupData",
1218 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1220 clusterContainerService.createCache("frm.TSPolicies",
1221 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1223 } catch (CacheConfigException cce) {
1224 log.error("FRM CacheConfigException", cce);
1225 } catch (CacheExistException cce) {
1226 log.error("FRM CacheExistException", cce);
1230 @SuppressWarnings({ "unchecked", "deprecation" })
1231 private void retrieveCaches() {
1232 ConcurrentMap<?, ?> map;
1234 if (this.clusterContainerService == null) {
1235 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1239 log.debug("FRM retrieveCaches for Container {}", container);
1241 map = clusterContainerService.getCache("frm.nodeFlows");
1243 nodeFlows = (ConcurrentMap<Node, Set<FlowEntryInstall>>) map;
1246 "FRM Cache frm.nodeFlows allocation failed for Container {}",
1250 map = clusterContainerService.getCache("frm.groupFlows");
1252 groupFlows = (ConcurrentMap<String, Set<FlowEntryInstall>>) map;
1255 "FRM Cache frm.groupFlows allocation failed for Container {}",
1259 map = clusterContainerService.getCache("frm.staticFlows");
1261 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1264 "FRM Cache frm.staticFlows allocation failed for Container {}",
1268 map = clusterContainerService.getCache("frm.flowsSaveEvent");
1270 flowsSaveEvent = (ConcurrentMap<Long, String>) map;
1273 "FRM Cache frm.flowsSaveEvent allocation failed for Container {}",
1277 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1279 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1282 "FRM Cache frm.staticFlowsOrdinal allocation failed for Container {}",
1286 map = clusterContainerService.getCache("frm.portGroupConfigs");
1288 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1291 "FRM Cache frm.portGroupConfigs allocation failed for Container {}",
1295 map = clusterContainerService.getCache("frm.portGroupData");
1297 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1300 "FRM Cache frm.portGroupData allocation failed for Container {}",
1304 map = clusterContainerService.getCache("frm.TSPolicies");
1306 TSPolicies = (ConcurrentMap<String, Object>) map;
1309 "FRM Cache frm.TSPolicies allocation failed for Container {}",
1315 @SuppressWarnings("deprecation")
1316 private void destroyCaches() {
1317 if (this.clusterContainerService == null) {
1318 log.warn("Un-initialized clusterContainerService, can't destroy cache");
1322 log.debug("FRM destroyCaches for Container {}", container);
1323 clusterContainerService.destroyCache("frm.nodeFlows");
1324 clusterContainerService.destroyCache("frm.TSPolicies");
1325 clusterContainerService.destroyCache("frm.groupFlows");
1326 clusterContainerService.destroyCache("frm.staticFlows");
1327 clusterContainerService.destroyCache("frm.flowsSaveEvent");
1328 clusterContainerService.destroyCache("frm.staticFlowsOrdinal");
1329 clusterContainerService.destroyCache("frm.portGroupData");
1330 clusterContainerService.destroyCache("frm.portGroupConfigs");
1331 nonClusterObjectCreate();
1334 private boolean flowConfigExists(FlowConfig config) {
1335 // As per customer requirement, flow name has to be unique on per node
1337 for (FlowConfig fc : staticFlows.values()) {
1338 if (fc.isByNameAndNodeIdEqual(config)) {
1346 public Status addStaticFlow(FlowConfig config, boolean restore) {
1347 StringBuffer resultStr = new StringBuffer();
1348 boolean multipleFlowPush = false;
1351 config.setStatus(StatusCode.SUCCESS.toString());
1354 if (flowConfigExists(config)) {
1355 error = "Entry with this name on specified switch already exists";
1357 "Entry with this name on specified switch already exists: {}",
1359 config.setStatus(error);
1360 return new Status(StatusCode.CONFLICT, error);
1363 // Skip validation check if we are trying to restore a saved config
1364 if (!restore && !config.isValid(container, resultStr)) {
1365 log.warn("Invalid Configuration for flow {}. The failure is {}",
1366 config, resultStr.toString());
1367 error = "Invalid Configuration (" + resultStr.toString() + ")";
1368 config.setStatus(error);
1369 return new Status(StatusCode.BADREQUEST, error);
1372 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1373 for (String portGroupName : portGroupConfigs.keySet()) {
1374 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1375 multipleFlowPush = true;
1379 if (!multipleFlowPush) {
1381 "Invalid Configuration(Invalid PortGroup Name) for flow {}",
1383 error = "Invalid Configuration (Invalid PortGroup Name)";
1384 config.setStatus(error);
1385 return new Status(StatusCode.BADREQUEST, error);
1390 * If requested program the entry in hardware first before updating the
1393 if (!multipleFlowPush) {
1395 if (config.installInHw()) {
1396 FlowEntry entry = config.getFlowEntry();
1397 status = this.addEntry(entry, false);
1398 if (!status.isSuccess()) {
1399 config.setStatus(status.getDescription());
1408 * When the control reaches this point, either of the following
1409 * conditions is true 1. This is a single entry configuration (non
1410 * PortGroup) and the hardware installation is successful 2. This is a
1411 * multiple entry configuration (PortGroup) and hardware installation is
1412 * NOT done directly on this event. 3. The User prefers to retain the
1413 * configuration in Controller and skip hardware installation.
1415 * Hence it is safe to update the StaticFlow DB at this point.
1417 * Note : For the case of PortGrouping, it is essential to have this DB
1418 * populated before the PortGroupListeners can query for the DB
1419 * triggered using portGroupChanged event...
1421 Integer ordinal = staticFlowsOrdinal.get(0);
1422 staticFlowsOrdinal.put(0, ++ordinal);
1423 staticFlows.put(ordinal, config);
1425 if (multipleFlowPush) {
1426 PortGroupConfig pgconfig = portGroupConfigs.get(config
1428 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1429 if (existingData != null) {
1430 portGroupChanged(pgconfig, existingData, true);
1433 return new Status(StatusCode.SUCCESS);
1436 private void addStaticFlowsToSwitch(Node node) {
1437 for (FlowConfig config : staticFlows.values()) {
1438 if (config.isPortGroupEnabled()) {
1441 if (config.getNode().equals(node)) {
1442 if (config.installInHw()
1443 && !config.getStatus().equals(
1444 StatusCode.SUCCESS.toString())) {
1445 Status status = this.addEntry(config.getFlowEntry(), false);
1446 config.setStatus(status.getDescription());
1452 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1453 log.trace("Updating Static Flow configs on node down: {}", node);
1455 List<Integer> toRemove = new ArrayList<Integer>();
1456 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1458 FlowConfig config = entry.getValue();
1460 if (config.isPortGroupEnabled()) {
1464 if (config.installInHw() && config.getNode().equals(node)) {
1465 if (config.isInternalFlow()) {
1466 // Take note of this controller generated static flow
1467 toRemove.add(entry.getKey());
1469 config.setStatus(NODEDOWN);
1473 // Remove controller generated static flows for this node
1474 for (Integer index : toRemove) {
1475 staticFlows.remove(index);
1479 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1480 log.trace("Updating Static Flow configs on container mode change: {}",
1483 for (FlowConfig config : staticFlows.values()) {
1484 if (config.isPortGroupEnabled()) {
1487 if (config.installInHw()) {
1490 config.setStatus("Removed from node because in container mode");
1493 config.setStatus(StatusCode.SUCCESS.toString());
1501 public Status removeStaticFlow(FlowConfig config) {
1503 * No config.isInternal() check as NB does not take this path and GUI
1504 * cannot issue a delete on an internal generated flow. We need this
1505 * path to be accessible when switch mode is changed from proactive to
1506 * reactive, so that we can remove the internal generated LLDP and ARP
1509 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1510 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1511 // Program the network node
1512 Status status = this.removeEntry(config.getFlowEntry(), false);
1513 // Update configuration database if programming was successful
1514 if (status.isSuccess()) {
1515 staticFlows.remove(entry.getKey());
1518 entry.getValue().setStatus(status.getDescription());
1523 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1527 public Status removeStaticFlow(String name, Node node) {
1528 for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1529 FlowConfig entry = mapEntry.getValue();
1530 Status status = new Status(null, null);
1531 if (entry.isByNameAndNodeIdEqual(name, node)) {
1532 // Validity check for api3 entry point
1533 if (entry.isInternalFlow()) {
1534 String msg = "Invalid operation: Controller generated "
1535 + "flow cannot be deleted";
1536 String logMsg = msg + ": {}";
1537 log.warn(logMsg, name);
1538 return new Status(StatusCode.NOTACCEPTABLE, msg);
1540 if (!entry.isPortGroupEnabled()) {
1541 // Program the network node
1542 status = this.removeEntry(entry.getFlowEntry(), false);
1544 // Update configuration database if programming was successful
1545 if (status.isSuccess()) {
1546 staticFlows.remove(mapEntry.getKey());
1549 entry.setStatus(status.getDescription());
1554 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1557 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1558 // Validity check for api3 entry point
1559 if (newFlowConfig.isInternalFlow()) {
1560 String msg = "Invalid operation: Controller generated flow "
1561 + "cannot be modified";
1562 String logMsg = msg + ": {}";
1563 log.warn(logMsg, newFlowConfig);
1564 return new Status(StatusCode.NOTACCEPTABLE, msg);
1568 StringBuffer resultStr = new StringBuffer();
1569 if (!newFlowConfig.isValid(container, resultStr)) {
1570 String msg = "Invalid Configuration (" + resultStr.toString() + ")";
1571 newFlowConfig.setStatus(msg);
1572 log.warn("Invalid Configuration for flow {}. The failure is {}",
1573 newFlowConfig, resultStr.toString());
1574 return new Status(StatusCode.BADREQUEST, msg);
1577 FlowConfig oldFlowConfig = null;
1578 Integer index = null;
1579 for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1580 FlowConfig entry = mapEntry.getValue();
1581 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(),
1582 newFlowConfig.getNode())) {
1583 oldFlowConfig = entry;
1584 index = mapEntry.getKey();
1589 if (oldFlowConfig == null) {
1590 String msg = "Attempt to modify a non existing static flow";
1591 String logMsg = msg + ": {}";
1592 log.warn(logMsg, newFlowConfig);
1593 return new Status(StatusCode.NOTFOUND, msg);
1596 // Do not attempt to reinstall the flow, warn user
1597 if (newFlowConfig.equals(oldFlowConfig)) {
1598 String msg = "No modification detected";
1600 "Static flow modification skipped. New flow and old flow are the same: {}",
1602 return new Status(StatusCode.SUCCESS, msg);
1605 // If flow is installed, program the network node
1606 Status status = new Status(StatusCode.SUCCESS, "Saved in config");
1607 if (oldFlowConfig.installInHw()) {
1608 status = this.modifyEntry(oldFlowConfig.getFlowEntry(),
1609 newFlowConfig.getFlowEntry(), false);
1612 // Update configuration database if programming was successful
1613 if (status.isSuccess()) {
1614 newFlowConfig.setStatus(status.getDescription());
1615 staticFlows.put(index, newFlowConfig);
1622 public Status toggleStaticFlowStatus(String name, Node node) {
1623 return toggleStaticFlowStatus(getStaticFlow(name, node));
1627 public Status toggleStaticFlowStatus(FlowConfig config) {
1628 if (config == null) {
1629 String msg = "Invalid request: null flow config";
1631 return new Status(StatusCode.BADREQUEST, msg);
1633 // Validity check for api3 entry point
1634 if (config.isInternalFlow()) {
1635 String msg = "Invalid operation: Controller generated flow "
1636 + "cannot be modified";
1637 String logMsg = msg + ": {}";
1638 log.warn(logMsg, config);
1639 return new Status(StatusCode.NOTACCEPTABLE, msg);
1642 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1643 FlowConfig conf = entry.getValue();
1644 if (conf.isByNameAndNodeIdEqual(config)) {
1645 // Program the network node
1646 Status status = new Status(StatusCode.SUCCESS);
1647 if (conf.installInHw()) {
1648 status = this.removeEntry(conf.getFlowEntry(), false);
1650 status = this.addEntry(conf.getFlowEntry(), false);
1652 if (!status.isSuccess()) {
1653 conf.setStatus(status.getDescription());
1657 // Update Configuration database
1658 conf.setStatus(StatusCode.SUCCESS.toString());
1659 conf.toggleStatus();
1663 return new Status(StatusCode.NOTFOUND,
1664 "Unable to locate the entry. Failed to toggle status");
1668 * Uninstall all the Flow Entries present in the software view A copy of
1669 * each entry is stored in the inactive list so that it can be re-applied
1670 * when needed This function is called on the default container instance of
1671 * FRM only when the first container is created
1673 private void uninstallAllFlowEntries() {
1674 log.info("Uninstalling all flows");
1676 // Store entries / create target list
1677 for (ConcurrentMap.Entry<Node, Set<FlowEntryInstall>> mapEntry : nodeFlows
1679 for (FlowEntryInstall flowEntries : mapEntry.getValue()) {
1680 inactiveFlows.add(flowEntries.getOriginal());
1684 // Now remove the entries
1685 for (FlowEntry flowEntry : inactiveFlows) {
1686 Status status = this.removeEntry(flowEntry, false);
1687 if (!status.isSuccess()) {
1688 log.warn("Failed to remove entry: {}. The failure is: {}",
1689 flowEntry, status.getDescription());
1695 * Re-install all the Flow Entries present in the inactive list The inactive
1696 * list will be empty at the end of this call This function is called on the
1697 * default container instance of FRM only when the last container is deleted
1699 private void reinstallAllFlowEntries() {
1700 log.info("Reinstalling all inactive flows");
1702 for (FlowEntry flowEntry : this.inactiveFlows) {
1703 Status status = this.addEntry(flowEntry, false);
1704 if (!status.isSuccess()) {
1705 log.warn("Failed to install entry: {}. The failure is: {}",
1706 flowEntry, status.getDescription());
1710 // Empty inactive list in any case
1711 inactiveFlows.clear();
1714 public List<FlowConfig> getStaticFlows() {
1715 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0)
1719 // TODO: need to come out with a better algorithm for mantaining the order
1720 // of the configuration entries
1721 // with actual one, index associated to deleted entries cannot be reused and
1723 private List<FlowConfig> getStaticFlowsOrderedList(
1724 ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1725 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1726 for (int i = 0; i <= maxKey; i++) {
1727 FlowConfig entry = flowMap.get(i);
1728 if (entry != null) {
1729 orderedList.add(entry);
1736 public FlowConfig getStaticFlow(String name, Node node) {
1737 for (FlowConfig config : staticFlows.values()) {
1738 if (config.isByNameAndNodeIdEqual(name, node)) {
1746 public List<FlowConfig> getStaticFlows(Node node) {
1747 List<FlowConfig> list = new ArrayList<FlowConfig>();
1748 for (FlowConfig config : staticFlows.values()) {
1749 if (config.onNode(node)) {
1757 public List<String> getStaticFlowNamesForNode(Node node) {
1758 List<String> list = new ArrayList<String>();
1759 for (FlowConfig config : staticFlows.values()) {
1760 if (config.onNode(node)) {
1761 list.add(config.getName());
1768 public List<Node> getListNodeWithConfiguredFlows() {
1769 Set<Node> set = new HashSet<Node>();
1770 for (FlowConfig config : staticFlows.values()) {
1771 set.add(config.getNode());
1773 return new ArrayList<Node>(set);
1776 @SuppressWarnings("unchecked")
1777 private void loadFlowConfiguration() {
1778 ObjectReader objReader = new ObjectReader();
1779 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader
1780 .read(this, frmFileName);
1782 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader
1783 .read(this, portGroupFileName);
1785 if (pgConfig != null) {
1786 for (Map.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
1787 addPortGroupConfig(entry.getKey(), entry.getValue()
1788 .getMatchString(), true);
1792 if (confList == null) {
1797 for (Integer key : confList.keySet()) {
1798 if (key.intValue() > maxKey)
1799 maxKey = key.intValue();
1802 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
1803 addStaticFlow(conf, true);
1808 public Object readObject(ObjectInputStream ois)
1809 throws FileNotFoundException, IOException, ClassNotFoundException {
1810 return ois.readObject();
1813 public Status saveConfig() {
1814 // Publish the save config event to the cluster nodes
1815 flowsSaveEvent.put(new Date().getTime(), SAVE);
1816 return saveConfigInternal();
1819 private Status saveConfigInternal() {
1820 ObjectWriter objWriter = new ObjectWriter();
1821 ConcurrentHashMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1822 for (Integer ordinal : staticFlows.keySet()) {
1823 FlowConfig config = staticFlows.get(ordinal);
1824 // Do not save dynamic and controller generated static flows
1825 if (config.isDynamic() || config.isInternalFlow()) {
1828 nonDynamicFlows.put(ordinal, config);
1830 objWriter.write(nonDynamicFlows, frmFileName);
1831 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(
1832 portGroupConfigs), portGroupFileName);
1833 return new Status(StatusCode.SUCCESS, null);
1837 public void entryCreated(Long key, String cacheName, boolean local) {
1841 public void entryUpdated(Long key, String new_value, String cacheName,
1842 boolean originLocal) {
1843 saveConfigInternal();
1847 public void entryDeleted(Long key, String cacheName, boolean originLocal) {
1851 public void subnetNotify(Subnet sub, boolean add) {
1854 private void installImplicitARPReplyPunt(Node node) {
1860 List<String> puntAction = new ArrayList<String>();
1861 puntAction.add(ActionType.CONTROLLER.toString());
1863 FlowConfig allowARP = new FlowConfig();
1864 allowARP.setInstallInHw(true);
1865 allowARP.setName("**Punt ARP Reply");
1866 allowARP.setPriority("500");
1867 allowARP.setNode(node);
1868 allowARP.setEtherType("0x"
1869 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1870 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager
1871 .getControllerMAC()));
1872 allowARP.setActions(puntAction);
1873 addStaticFlow(allowARP, false);
1877 public void modeChangeNotify(Node node, boolean proactive) {
1878 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
1880 List<String> puntAction = new ArrayList<String>();
1881 puntAction.add(ActionType.CONTROLLER.toString());
1883 FlowConfig allowARP = new FlowConfig();
1884 allowARP.setInstallInHw(true);
1885 allowARP.setName("**Punt ARP");
1886 allowARP.setPriority("1");
1887 allowARP.setNode(node);
1888 allowARP.setEtherType("0x"
1889 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1890 allowARP.setActions(puntAction);
1891 defaultConfigs.add(allowARP);
1893 FlowConfig allowLLDP = new FlowConfig();
1894 allowLLDP.setInstallInHw(true);
1895 allowLLDP.setName("**Punt LLDP");
1896 allowLLDP.setPriority("1");
1897 allowLLDP.setNode(node);
1900 + Integer.toHexString(EtherTypes.LLDP.intValue())
1902 allowLLDP.setActions(puntAction);
1903 defaultConfigs.add(allowLLDP);
1905 List<String> dropAction = new ArrayList<String>();
1906 dropAction.add(ActionType.DROP.toString());
1908 FlowConfig dropAllConfig = new FlowConfig();
1909 dropAllConfig.setInstallInHw(true);
1910 dropAllConfig.setName("**Catch-All Drop");
1911 dropAllConfig.setPriority("0");
1912 dropAllConfig.setNode(node);
1913 dropAllConfig.setActions(dropAction);
1914 defaultConfigs.add(dropAllConfig);
1916 for (FlowConfig fc : defaultConfigs) {
1918 addStaticFlow(fc, false);
1920 removeStaticFlow(fc);
1924 log.info("Set Switch {} Mode to {}", node, proactive);
1928 * Remove from the databases all the flows installed on the node
1932 private synchronized void cleanDatabaseForNode(Node node) {
1933 log.info("Cleaning Flow database for Node {}", node.toString());
1935 // Find out which groups the node's flows are part of
1936 Set<String> affectedGroups = new HashSet<String>();
1937 Set<FlowEntryInstall> flowEntryList = nodeFlows.get(node);
1938 if (flowEntryList != null) {
1939 for (FlowEntryInstall entry : flowEntryList) {
1940 String groupName = entry.getGroupName();
1941 if (groupName != null) {
1942 affectedGroups.add(groupName);
1947 // Remove the node's flows from the group indexed flow database
1948 if (!affectedGroups.isEmpty()) {
1949 for (String group : affectedGroups) {
1950 Set<FlowEntryInstall> flowList = groupFlows.get(group);
1951 Set<FlowEntryInstall> toRemove = new HashSet<FlowEntryInstall>();
1952 for (FlowEntryInstall entry : flowList) {
1953 if (node.equals(entry.getNode())) {
1954 toRemove.add(entry);
1957 flowList.removeAll(toRemove);
1958 if (flowList.isEmpty()) {
1959 groupFlows.remove(group);
1964 // Remove the node's flows from the node indexed flow database
1965 nodeFlows.remove(node);
1969 public void notifyNode(Node node, UpdateType type,
1970 Map<String, Property> propMap) {
1973 addStaticFlowsToSwitch(node);
1976 cleanDatabaseForNode(node);
1977 updateStaticFlowConfigsOnNodeDown(node);
1985 public void notifyNodeConnector(NodeConnector nodeConnector,
1986 UpdateType type, Map<String, Property> propMap) {
1989 private FlowConfig getDerivedFlowConfig(FlowConfig original,
1990 String configName, Short port) {
1991 FlowConfig derivedFlow = new FlowConfig(original);
1992 derivedFlow.setDynamic(true);
1993 derivedFlow.setPortGroup(null);
1994 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
1995 derivedFlow.setIngressPort(port + "");
1999 private void addPortGroupFlows(PortGroupConfig config, Node node,
2001 for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
2003 FlowConfig staticFlow = it.next();
2004 if (staticFlow.getPortGroup() == null) {
2007 if ((staticFlow.getNode().equals(node))
2008 && (staticFlow.getPortGroup().equals(config.getName()))) {
2009 for (Short port : data.getPorts()) {
2010 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
2011 config.getName(), port);
2012 addStaticFlow(derivedFlow, false);
2018 private void removePortGroupFlows(PortGroupConfig config, Node node,
2020 for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
2022 FlowConfig staticFlow = it.next();
2023 if (staticFlow.getPortGroup() == null) {
2026 if ((staticFlow.getNode().equals(node))
2027 && (staticFlow.getPortGroup().equals(config.getName()))) {
2028 for (Short port : data.getPorts()) {
2029 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
2030 config.getName(), port);
2031 removeStaticFlow(derivedFlow);
2038 public void portGroupChanged(PortGroupConfig config,
2039 Map<Node, PortGroup> data, boolean add) {
2040 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2041 Map<Node, PortGroup> existingData = portGroupData.get(config);
2042 if (existingData != null) {
2043 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2044 PortGroup existingPortGroup = existingData.get(entry.getKey());
2045 if (existingPortGroup == null) {
2047 existingData.put(entry.getKey(), entry.getValue());
2048 addPortGroupFlows(config, entry.getKey(),
2053 existingPortGroup.getPorts().addAll(
2054 entry.getValue().getPorts());
2055 addPortGroupFlows(config, entry.getKey(),
2058 existingPortGroup.getPorts().removeAll(
2059 entry.getValue().getPorts());
2060 removePortGroupFlows(config, entry.getKey(),
2067 portGroupData.put(config, data);
2068 for (Node swid : data.keySet()) {
2069 addPortGroupFlows(config, swid, data.get(swid));
2075 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2076 PortGroupConfig config = portGroupConfigs.get(name);
2080 if ((portGroupProvider == null) && !restore) {
2083 if ((portGroupProvider != null)
2084 && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2088 config = new PortGroupConfig(name, regex);
2089 portGroupConfigs.put(name, config);
2090 if (portGroupProvider != null) {
2091 portGroupProvider.createPortGroupConfig(config);
2096 public boolean delPortGroupConfig(String name) {
2097 PortGroupConfig config = portGroupConfigs.get(name);
2098 if (config == null) {
2102 if (portGroupProvider != null) {
2103 portGroupProvider.deletePortGroupConfig(config);
2105 portGroupConfigs.remove(name);
2109 private void usePortGroupConfig(String name) {
2110 PortGroupConfig config = portGroupConfigs.get(name);
2111 if (config == null) {
2114 if (portGroupProvider != null) {
2115 Map<Node, PortGroup> data = portGroupProvider
2116 .getPortGroupData(config);
2117 portGroupData.put(config, data);
2122 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2123 return portGroupConfigs;
2126 public boolean isPortGroupSupported() {
2127 if (portGroupProvider == null) {
2133 // Fir PortGroupProvider to use regular Dependency Manager
2134 /* @SuppressWarnings("rawtypes") */
2135 /* public void bind(Object arg0, Map arg1) throws Exception { */
2136 /* if (arg0 instanceof PortGroupProvider) { */
2137 /* setPortGroupProvider((PortGroupProvider)arg0); */
2141 /* @SuppressWarnings("rawtypes") */
2143 /* public void unbind(Object arg0, Map arg1) throws Exception { */
2144 /* if (arg0 instanceof PortGroupProvider) { */
2145 /* portGroupProvider = null; */
2149 public void setIContainer(IContainer s) {
2153 public void unsetIContainer(IContainer s) {
2154 if (this.container == s) {
2155 this.container = null;
2159 public PortGroupProvider getPortGroupProvider() {
2160 return portGroupProvider;
2163 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2164 this.portGroupProvider = null;
2167 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2168 this.portGroupProvider = portGroupProvider;
2169 portGroupProvider.registerPortGroupChange(this);
2170 for (PortGroupConfig config : portGroupConfigs.values()) {
2171 portGroupProvider.createPortGroupConfig(config);
2175 public void setHostFinder(IfIptoHost hostFinder) {
2176 this.hostFinder = hostFinder;
2179 public void unsetHostFinder(IfIptoHost hostFinder) {
2180 if (this.hostFinder == hostFinder) {
2181 this.hostFinder = null;
2185 public void setFrmAware(IForwardingRulesManagerAware obj) {
2186 this.frmAware.add(obj);
2189 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2190 this.frmAware.remove(obj);
2193 void setClusterContainerService(IClusterContainerServices s) {
2194 log.debug("Cluster Service set");
2195 this.clusterContainerService = s;
2198 void unsetClusterContainerService(IClusterContainerServices s) {
2199 if (this.clusterContainerService == s) {
2200 log.debug("Cluster Service removed!");
2201 this.clusterContainerService = null;
2205 private String getContainerName() {
2206 if (container == null) {
2207 return GlobalConstants.DEFAULT.toString();
2209 return container.getName();
2213 * Function called by the dependency manager when all the required
2214 * dependencies are satisfied
2218 frmAware = Collections
2219 .synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
2220 frmFileName = GlobalConstants.STARTUPHOME.toString()
2221 + "frm_staticflows_" + this.getContainerName() + ".conf";
2222 portGroupFileName = GlobalConstants.STARTUPHOME.toString()
2223 + "portgroup_" + this.getContainerName() + ".conf";
2225 inContainerMode = false;
2227 if (portGroupProvider != null) {
2228 portGroupProvider.registerPortGroupChange(this);
2231 nonClusterObjectCreate();
2235 registerWithOSGIConsole();
2238 * If we are not the first cluster node to come up, do not initialize
2239 * the static flow entries ordinal
2241 if (staticFlowsOrdinal.size() == 0) {
2242 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2247 * Function called by the dependency manager when at least one dependency
2248 * become unsatisfied or when the component is shutting down because for
2249 * example bundle is being stopped.
2257 * Function called by dependency manager after "init ()" is called and after
2258 * the services provided by the class are registered in the service registry
2263 * Read startup and build database if we have not already gotten the
2264 * configurations synced from another node
2266 if (staticFlows.isEmpty()) {
2267 loadFlowConfiguration();
2272 * Function called by the dependency manager before the services exported by
2273 * the component are unregistered, this will be followed by a "destroy ()"
2280 public void setFlowProgrammerService(IFlowProgrammerService service) {
2281 this.programmer = service;
2284 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2285 if (this.programmer == service) {