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.util.ArrayList;
15 import java.util.Collections;
16 import java.util.EnumSet;
17 import java.util.HashSet;
18 import java.util.List;
20 import java.util.Map.Entry;
22 import java.util.concurrent.BlockingQueue;
23 import java.util.concurrent.Callable;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.LinkedBlockingQueue;
31 import org.opendaylight.controller.clustering.services.CacheConfigException;
32 import org.opendaylight.controller.clustering.services.CacheExistException;
33 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
34 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
35 import org.opendaylight.controller.clustering.services.IClusterServices;
36 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
37 import org.opendaylight.controller.connectionmanager.IConnectionManager;
38 import org.opendaylight.controller.containermanager.IContainerManager;
39 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
40 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
41 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
42 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
43 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
44 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
45 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
46 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
47 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
48 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
49 import org.opendaylight.controller.sal.action.Action;
50 import org.opendaylight.controller.sal.action.ActionType;
51 import org.opendaylight.controller.sal.action.Output;
52 import org.opendaylight.controller.sal.connection.ConnectionLocality;
53 import org.opendaylight.controller.sal.core.Config;
54 import org.opendaylight.controller.sal.core.ContainerFlow;
55 import org.opendaylight.controller.sal.core.IContainer;
56 import org.opendaylight.controller.sal.core.IContainerLocalListener;
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.IObjectReader;
69 import org.opendaylight.controller.sal.utils.ObjectReader;
70 import org.opendaylight.controller.sal.utils.ObjectWriter;
71 import org.opendaylight.controller.sal.utils.Status;
72 import org.opendaylight.controller.sal.utils.StatusCode;
73 import org.opendaylight.controller.switchmanager.IInventoryListener;
74 import org.opendaylight.controller.switchmanager.ISwitchManager;
75 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
76 import org.opendaylight.controller.switchmanager.Subnet;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * Class that manages forwarding rule installation and removal per container of
82 * the network. It also maintains the central repository of all the forwarding
83 * rules installed on the network nodes.
85 public class ForwardingRulesManager implements
86 IForwardingRulesManager,
87 PortGroupChangeListener,
88 IContainerLocalListener,
90 IConfigurationContainerAware,
93 ICacheUpdateAware<Object,Object>,
94 IFlowProgrammerListener {
96 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
97 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
98 private static final String PORT_REMOVED = "Port removed";
99 private static final String NODE_DOWN = "Node is Down";
100 private static final String INVALID_FLOW_ENTRY = "Invalid FlowEntry";
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 IContainerManager containerManager;
109 private boolean inContainerMode; // being used by global instance only
110 protected boolean stopping;
113 * Flow database. It's the software view of what was requested to install
114 * and what is installed on the switch. It is indexed by the entry itself.
115 * The entry's hashcode resumes the network node index, the flow's priority
116 * and the flow's match. The value element is a class which contains the
117 * flow entry pushed by the applications modules and the respective
118 * container flow merged version. In absence of container flows, the two
119 * flow entries are the same.
121 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
122 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
124 * Per node and per group indexing
126 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
127 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
130 * Inactive flow list. This is for the global instance of FRM It will
131 * contain all the flow entries which were installed on the global container
132 * when the first container is created.
134 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
136 private IContainer container;
137 private Set<IForwardingRulesManagerAware> frmAware =
138 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
139 private PortGroupProvider portGroupProvider;
140 private IFlowProgrammerService programmer;
141 private IClusterContainerServices clusterContainerService = null;
142 private ISwitchManager switchManager;
143 private Thread frmEventHandler;
144 protected BlockingQueue<FRMEvent> pendingEvents;
146 // Distributes FRM programming in the cluster
147 private IConnectionManager connectionManager;
150 * Name clustered caches used to support FRM entry distribution these are by
151 * necessity non-transactional as long as need to be able to synchronize
152 * states also while a transaction is in progress
154 static final String WORK_ORDER_CACHE = "frm.workOrder";
155 static final String WORK_STATUS_CACHE = "frm.workStatus";
156 static final String ORIGINAL_SW_VIEW_CACHE = "frm.originalSwView";
157 static final String INSTALLED_SW_VIEW_CACHE = "frm.installedSwView";
160 * Data structure responsible for distributing the FlowEntryInstall requests
161 * in the cluster. The key value is entry that is being either Installed or
162 * Updated or Delete. The value field is the same of the key value in case
163 * of Installation or Deletion, it's the new entry in case of Modification,
164 * this because the clustering caches don't allow null values.
166 * The logic behind this data structure is that the controller that initiate
167 * the request will place the order here, someone will pick it and then will
168 * remove from this data structure because is being served.
170 * TODO: We need to have a way to cleanup this data structure if entries are
171 * not picked by anyone, which is always a case can happen especially on
172 * Node disconnect cases.
174 protected ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
177 * Data structure responsible for retrieving the results of the workOrder
178 * submitted to the cluster.
180 * The logic behind this data structure is that the controller that has
181 * executed the order will then place the result in workStatus signaling
182 * that there was a success or a failure.
184 * TODO: The workStatus entries need to have a lifetime associated in case
185 * of requestor controller leaving the cluster.
187 protected ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
190 * Local Map used to hold the Future which a caller can use to monitor for
193 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
194 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
197 * Max pool size for the executor
199 private static final int maxPoolSize = 10;
203 * Entry being installed/updated/removed
205 * New entry will be placed after the update operation. Valid
206 * only for UpdateType.CHANGED, null for all the other cases
209 * @return a Future object for monitoring the progress of the result, or
210 * null in case the processing should take place locally
212 private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
214 // A null entry it's an unexpected condition, anyway it's safe to keep
215 // the handling local
220 Node n = e.getNode();
221 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
222 // Create the work order and distribute it
223 FlowEntryDistributionOrder fe =
224 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
225 // First create the monitor job
226 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
227 logsync.trace("Node {} not local so sending fe {}", n, fe);
228 workMonitor.put(fe, ret);
229 if (t.equals(UpdateType.CHANGED)) {
230 // Then distribute the work
231 workOrder.put(fe, u);
233 // Then distribute the work
234 workOrder.put(fe, e);
236 logsync.trace("WorkOrder requested");
237 // Now create an Handle to monitor the execution of the operation
241 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
246 * Adds a flow entry onto the network node It runs various validity checks
247 * and derive the final container flows merged entries that will be
248 * attempted to be installed
251 * the original flow entry application requested to add
253 * the flag indicating if this is a asynchronous request
254 * @return the status of this request. In case of asynchronous call, it will
255 * contain the unique id assigned to this request
257 private Status addEntry(FlowEntry flowEntry, boolean async) {
260 if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
261 String logMsg = INVALID_FLOW_ENTRY + ": {}";
262 log.warn(logMsg, flowEntry);
263 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
267 * Redundant Check: Check if the request is a redundant one from the
268 * same application the flowEntry is equal to an existing one. Given we
269 * do not have an application signature in the requested FlowEntry yet,
270 * we are here detecting the above condition by comparing the flow
271 * names, if set. If they are equal to the installed flow, most likely
272 * this is a redundant installation request from the same application
273 * and we can silently return success
275 * TODO: in future a sort of application reference list mechanism will
276 * be added to the FlowEntry so that exact flow can be used by different
279 FlowEntry present = this.originalSwView.get(flowEntry);
280 if (present != null) {
281 boolean sameFlow = present.getFlow().equals(flowEntry.getFlow());
282 boolean sameApp = present.getFlowName() != null && present.getFlowName().equals(flowEntry.getFlowName());
283 if (sameFlow && sameApp) {
284 log.trace("Skipping redundant request for flow {} on node {}", flowEntry.getFlowName(),
285 flowEntry.getNode());
286 return new Status(StatusCode.SUCCESS, "Entry is already present");
291 * Derive the container flow merged entries to install In presence of N
292 * container flows, we may end up with N different entries to install...
294 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
296 // Container Flow conflict Check
297 if (toInstallList.isEmpty()) {
298 String msg = "Flow Entry conflicts with all Container Flows";
299 String logMsg = msg + ": {}";
300 log.warn(logMsg, flowEntry);
301 return new Status(StatusCode.CONFLICT, msg);
304 // Derive the list of entries good to be installed
305 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
306 for (FlowEntryInstall entry : toInstallList) {
307 // Conflict Check: Verify new entry would not overwrite existing
309 if (this.installedSwView.containsKey(entry)) {
310 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
311 log.trace("Aborting to install {}", entry);
314 toInstallSafe.add(entry);
317 // Declare failure if all the container flow merged entries clash with
319 if (toInstallSafe.size() == 0) {
320 String msg = "A flow with same match and priority exists on the target node";
321 String logMsg = msg + ": {}";
322 log.warn(logMsg, flowEntry);
323 return new Status(StatusCode.CONFLICT, msg);
326 // Try to install an entry at the time
327 Status error = new Status(null, null);
328 Status succeded = null;
329 boolean oneSucceded = false;
330 for (FlowEntryInstall installEntry : toInstallSafe) {
332 // Install and update database
333 Status ret = addEntriesInternal(installEntry, async);
335 if (ret.isSuccess()) {
338 * The first successful status response will be returned For the
339 * asynchronous call, we can discard the container flow
340 * complication for now and assume we will always deal with one
341 * flow only per request
346 log.trace("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
350 return (oneSucceded) ? succeded : error;
354 * Given a flow entry and the list of container flows, it returns the list
355 * of container flow merged flow entries good to be installed on this
356 * container. If the list of container flows is null or empty, the install
357 * entry list will contain only one entry, the original flow entry. If the
358 * flow entry is congruent with all the N container flows, then the output
359 * install entry list will contain N entries. If the output list is empty,
360 * it means the passed flow entry conflicts with all the container flows.
363 * The list of container flows
364 * @return the list of container flow merged entries good to be installed on
367 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
368 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
370 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
371 // No container flows => entry good to be installed unchanged
372 toInstallList.add(new FlowEntryInstall(request.clone(), null));
374 // Create the list of entries to be installed. If the flow entry is
375 // not congruent with any container flow, no install entries will be
377 for (ContainerFlow cFlow : container.getContainerFlows()) {
378 if (cFlow.allowsFlow(request.getFlow())) {
379 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
383 return toInstallList;
387 * Modify a flow entry with a new one It runs various validity check and
388 * derive the final container flows merged flow entries to work with
390 * @param currentFlowEntry
391 * @param newFlowEntry
393 * the flag indicating if this is a asynchronous request
394 * @return the status of this request. In case of asynchronous call, it will
395 * contain the unique id assigned to this request
397 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
401 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
402 || newFlowEntry.getNode() == null || newFlowEntry.getFlow() == null) {
403 String msg = "Modify: " + INVALID_FLOW_ENTRY;
404 String logMsg = msg + ": {} or {}";
405 log.warn(logMsg, currentFlowEntry, newFlowEntry);
406 return new Status(StatusCode.NOTACCEPTABLE, msg);
408 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
409 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
410 String msg = "Modify: Incompatible Flow Entries";
411 String logMsg = msg + ": {} and {}";
412 log.warn(logMsg, currentFlowEntry, newFlowEntry);
413 return new Status(StatusCode.NOTACCEPTABLE, msg);
417 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
418 String msg = "Modify skipped as flows are the same";
419 String logMsg = msg + ": {} and {}";
420 log.debug(logMsg, currentFlowEntry, newFlowEntry);
421 return new Status(StatusCode.SUCCESS, msg);
425 * Conflict Check: Verify the new entry would not conflict with an
426 * existing one. This is a loose check on the previous original flow
427 * entry requests. No check on the container flow merged flow entries
430 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
431 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
432 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
433 String logMsg = msg + ": {}";
434 log.warn(logMsg, currentFlowEntry);
435 return new Status(StatusCode.CONFLICT, msg);
438 // Derive the installed and toInstall entries
439 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
440 container.getContainerFlows());
441 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
443 if (toInstallList.isEmpty()) {
444 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
445 String logMsg = msg + ": {}";
446 log.warn(logMsg, newFlowEntry);
448 return new Status(StatusCode.CONFLICT, msg);
452 * If the two list sizes differ, it means the new flow entry does not
453 * satisfy the same number of container flows the current entry does.
454 * This is only possible when the new entry and current entry have
455 * different match. In this scenario the modification would ultimately
456 * be handled as a remove and add operations in the protocol plugin.
458 * Also, if any of the new flow entries would clash with an existing
459 * one, we cannot proceed with the modify operation, because it would
460 * fail for some entries and leave stale entries on the network node.
461 * Modify path can be taken only if it can be performed completely, for
464 * So, for the above two cases, to simplify, let's decouple the modify
465 * in: 1) remove current entries 2) install new entries
467 Status succeeded = null;
468 boolean decouple = false;
469 if (installedList.size() != toInstallList.size()) {
470 log.trace("Modify: New flow entry does not satisfy the same "
471 + "number of container flows as the original entry does");
474 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
475 for (FlowEntryInstall installEntry : toInstallList) {
477 * Conflict Check: Verify the new entry would not overwrite another
480 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
481 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
482 log.trace("Modify: new container flow merged flow entry clashes with existing flow");
485 toInstallSafe.add(installEntry);
490 // Remove current entries
491 for (FlowEntryInstall currEntry : installedList) {
492 this.removeEntryInternal(currEntry, async);
494 // Install new entries
495 for (FlowEntryInstall newEntry : toInstallSafe) {
496 succeeded = this.addEntriesInternal(newEntry, async);
500 * The two list have the same size and the entries to install do not
501 * clash with any existing flow on the network node. We assume here
502 * (and might be wrong) that the same container flows that were
503 * satisfied by the current entries are the same that are satisfied
504 * by the new entries. Let's take the risk for now.
506 * Note: modification has to be complete. If any entry modification
507 * fails, we need to stop, restore the already modified entries, and
510 Status retModify = null;
512 int size = toInstallList.size();
514 // Modify and update database
515 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
516 if (retModify.isSuccess()) {
522 // Check if uncompleted modify
524 log.warn("Unable to perform a complete modify for all the container flows merged entries");
525 // Restore original entries
528 log.info("Attempting to restore initial entries");
529 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
530 if (retExt.isSuccess()) {
536 // Fatal error, recovery failed
538 String msg = "Flow recovery failed ! Unrecoverable Error";
540 return new Status(StatusCode.INTERNALERROR, msg);
543 succeeded = retModify;
546 * The first successful status response will be returned. For the
547 * asynchronous call, we can discard the container flow complication for
548 * now and assume we will always deal with one flow only per request
554 * This is the function that modifies the final container flows merged
555 * entries on the network node and update the database. It expects that all
556 * the validity checks are passed
558 * @param currentEntries
561 * the flag indicating if this is a asynchronous request
562 * @return the status of this request. In case of asynchronous call, it will
563 * contain the unique id assigned to this request
565 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
566 FlowEntryDistributionOrderFutureTask futureStatus =
567 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
568 if (futureStatus != null) {
569 Status retStatus = new Status(StatusCode.UNDEFINED);
571 retStatus = futureStatus.get();
572 if (retStatus.getCode()
573 .equals(StatusCode.TIMEOUT)) {
574 // A timeout happened, lets cleanup the workMonitor
575 workMonitor.remove(futureStatus.getOrder());
577 } catch (InterruptedException e) {
579 } catch (ExecutionException e) {
584 // Modify the flow on the network node
585 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
586 .getFlow(), newEntries.getInstall()
587 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
588 .getFlow(), newEntries.getInstall()
591 if (!status.isSuccess()) {
592 log.trace("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
593 status.getDescription());
597 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
600 newEntries.setRequestId(status.getRequestId());
601 updateSwViews(currentEntries, false);
602 updateSwViews(newEntries, true);
609 * Remove a flow entry. If the entry is not present in the software view
610 * (entry or node not present), it return successfully
613 * the flow entry to remove
615 * the flag indicating if this is a asynchronous request
616 * @return the status of this request. In case of asynchronous call, it will
617 * contain the unique id assigned to this request
619 private Status removeEntry(FlowEntry flowEntry, boolean async) {
620 Status error = new Status(null, null);
623 if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
624 String logMsg = INVALID_FLOW_ENTRY + ": {}";
625 log.warn(logMsg, flowEntry);
626 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
629 // Derive the container flows merged installed entries
630 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
632 Status succeeded = null;
633 boolean atLeastOneRemoved = false;
634 for (FlowEntryInstall entry : installedList) {
635 if (!installedSwView.containsKey(entry)) {
636 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
637 log.debug(logMsg, flowEntry);
638 if (installedList.size() == 1) {
639 // If we had only one entry to remove, we are done
640 return new Status(StatusCode.SUCCESS);
646 // Remove and update DB
647 Status ret = removeEntryInternal(entry, async);
649 if (!ret.isSuccess()) {
651 log.trace("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
652 if (installedList.size() == 1) {
653 // If we had only one entry to remove, this is fatal failure
658 atLeastOneRemoved = true;
663 * No worries if full removal failed. Consistency checker will take care
664 * of removing the stale entries later, or adjusting the software
665 * database if not in sync with hardware
667 return (atLeastOneRemoved) ? succeeded : error;
671 * This is the function that removes the final container flows merged entry
672 * from the network node and update the database. It expects that all the
673 * validity checks are passed
676 * the flow entry to remove
678 * the flag indicating if this is a asynchronous request
679 * @return the status of this request. In case of asynchronous call, it will
680 * contain the unique id assigned to this request
682 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
683 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
684 if (futureStatus != null) {
685 Status retStatus = new Status(StatusCode.UNDEFINED);
687 retStatus = futureStatus.get();
688 if (retStatus.getCode()
689 .equals(StatusCode.TIMEOUT)) {
690 // A timeout happened, lets cleanup the workMonitor
691 workMonitor.remove(futureStatus.getOrder());
693 } catch (InterruptedException e) {
695 } catch (ExecutionException e) {
700 // Mark the entry to be deleted (for CC just in case we fail)
704 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
705 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
708 if (!status.isSuccess()) {
709 log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", entry.getInstall(),
710 status.getDescription());
713 log.trace("Removed {}", entry.getInstall());
716 updateSwViews(entry, false);
723 * This is the function that installs the final container flow merged entry
724 * on the network node and updates the database. It expects that all the
725 * validity and conflict checks are passed. That means it does not check
726 * whether this flow would conflict or overwrite an existing one.
729 * the flow entry to install
731 * the flag indicating if this is a asynchronous request
732 * @return the status of this request. In case of asynchronous call, it will
733 * contain the unique id assigned to this request
735 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
736 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
737 if (futureStatus != null) {
738 Status retStatus = new Status(StatusCode.UNDEFINED);
740 retStatus = futureStatus.get();
741 if (retStatus.getCode()
742 .equals(StatusCode.TIMEOUT)) {
743 // A timeout happened, lets cleanup the workMonitor
744 workMonitor.remove(futureStatus.getOrder());
746 } catch (InterruptedException e) {
748 } catch (ExecutionException e) {
753 // Install the flow on the network node
754 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
755 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
758 if (!status.isSuccess()) {
759 log.trace("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
760 status.getDescription());
764 log.trace("Added {}", entry.getInstall());
767 entry.setRequestId(status.getRequestId());
768 updateSwViews(entry, true);
775 * Returns true if the flow conflicts with all the container's flows. This
776 * means that if the function returns true, the passed flow entry is
777 * congruent with at least one container flow, hence it is good to be
778 * installed on this container.
781 * @return true if flow conflicts with all the container flows, false
784 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
785 List<ContainerFlow> cFlowList = container.getContainerFlows();
787 // Validity check and avoid unnecessary computation
788 // Also takes care of default container where no container flows are
790 if (cFlowList == null || cFlowList.isEmpty()) {
794 for (ContainerFlow cFlow : cFlowList) {
795 if (cFlow.allowsFlow(flowEntry.getFlow())) {
796 // Entry is allowed by at least one container flow: good to go
803 private ConcurrentMap.Entry<Integer, FlowConfig> getStaticFlowEntry(String name, Node node) {
804 for (ConcurrentMap.Entry<Integer, FlowConfig> flowEntry : staticFlows.entrySet()) {
805 FlowConfig flowConfig = flowEntry.getValue();
806 if (flowConfig.isByNameAndNodeIdEqual(name, node)) {
813 private void updateIndexDatabase(FlowEntryInstall entry, boolean add) {
814 // Update node indexed flow database
815 updateNodeFlowsDB(entry, add);
817 // Update group indexed flow database
818 updateGroupFlowsDB(entry, add);
822 * Update the node mapped flows database
824 private void updateSwViews(FlowEntryInstall flowEntries, boolean add) {
826 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
827 installedSwView.put(flowEntries, flowEntries);
829 originalSwView.remove(flowEntries.getOriginal());
830 installedSwView.remove(flowEntries);
835 * Update the node mapped flows database
837 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
838 Node node = flowEntries.getNode();
840 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
841 if (nodeIndeces == null) {
845 nodeIndeces = new ArrayList<FlowEntryInstall>();
850 // there may be an already existing entry.
851 // remove it before adding the new one.
852 // This is necessary since we have observed that in some cases
853 // Infinispan does aggregation for operations (eg:- remove and then put a different value)
854 // related to the same key within the same transaction.
855 // Need this defensive code as the new FlowEntryInstall may be different
856 // than the old one even though the equals method returns true. This is because
857 // the equals method does not take into account the action list.
858 if(nodeIndeces.contains(flowEntries)) {
859 nodeIndeces.remove(flowEntries);
861 nodeIndeces.add(flowEntries);
863 nodeIndeces.remove(flowEntries);
866 // Update cache across cluster
867 if (nodeIndeces.isEmpty()) {
868 this.nodeFlows.remove(node);
870 this.nodeFlows.put(node, nodeIndeces);
875 * Update the group name mapped flows database
877 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
878 String groupName = flowEntries.getGroupName();
880 // Flow may not be part of a group
881 if (groupName == null) {
885 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
886 if (indices == null) {
890 indices = new ArrayList<FlowEntryInstall>();
895 // same comments in the similar code section in
896 // updateNodeFlowsDB method apply here too
897 if(indices.contains(flowEntries)) {
898 indices.remove(flowEntries);
900 indices.add(flowEntries);
902 indices.remove(flowEntries);
905 // Update cache across cluster
906 if (indices.isEmpty()) {
907 this.groupFlows.remove(groupName);
909 this.groupFlows.put(groupName, indices);
914 * Remove a flow entry that has been added previously First checks if the
915 * entry is effectively present in the local database
917 @SuppressWarnings("unused")
918 private Status removeEntry(Node node, String flowName) {
919 FlowEntryInstall target = null;
922 for (FlowEntryInstall entry : installedSwView.values()) {
923 if (entry.equalsByNodeAndName(node, flowName)) {
929 // If it is not there, stop any further processing
930 if (target == null) {
931 return new Status(StatusCode.SUCCESS, "Entry is not present");
935 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
938 if (status.isSuccess()) {
939 updateSwViews(target, false);
942 log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
943 status.getDescription());
950 public Status installFlowEntry(FlowEntry flowEntry) {
952 if (isContainerModeAllowed(flowEntry)) {
953 status = addEntry(flowEntry, false);
955 String msg = "Controller in container mode: Install Refused";
956 String logMsg = msg + ": {}";
957 status = new Status(StatusCode.NOTACCEPTABLE, msg);
958 log.warn(logMsg, flowEntry);
964 public Status installFlowEntryAsync(FlowEntry flowEntry) {
966 if (isContainerModeAllowed(flowEntry)) {
967 status = addEntry(flowEntry, true);
969 String msg = "Controller in container mode: Install Refused";
970 status = new Status(StatusCode.NOTACCEPTABLE, msg);
977 public Status uninstallFlowEntry(FlowEntry flowEntry) {
979 if (isContainerModeAllowed(flowEntry)) {
980 status = removeEntry(flowEntry, false);
982 String msg = "Controller in container mode: Uninstall Refused";
983 String logMsg = msg + ": {}";
984 status = new Status(StatusCode.NOTACCEPTABLE, msg);
985 log.warn(logMsg, flowEntry);
991 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
993 if (isContainerModeAllowed(flowEntry)) {
994 status = removeEntry(flowEntry, true);
996 String msg = "Controller in container mode: Uninstall Refused";
997 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1004 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1005 Status status = null;
1006 if (isContainerModeAllowed(currentFlowEntry)) {
1007 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1009 String msg = "Controller in container mode: Modify Refused";
1010 String logMsg = msg + ": {}";
1011 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1012 log.warn(logMsg, newFlowEntry);
1018 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1019 Status status = null;
1020 if (isContainerModeAllowed(currentFlowEntry)) {
1021 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
1023 String msg = "Controller in container mode: Modify Refused";
1024 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1031 * Returns whether the specified flow entry is allowed to be
1032 * installed/removed/modified based on the current container mode status.
1033 * This call always returns true in the container instance of forwarding
1034 * rules manager. It is meant for the global instance only (default
1035 * container) of forwarding rules manager. Idea is that for assuring
1036 * container isolation of traffic, flow installation in default container is
1037 * blocked when in container mode (containers are present). The only flows
1038 * that are allowed in container mode in the default container are the
1039 * proactive flows, the ones automatically installed on the network node
1040 * which forwarding mode has been configured to "proactive". These flows are
1041 * needed by controller to discover the nodes topology and to discover the
1042 * attached hosts for some SDN switches.
1045 * The flow entry to be installed/removed/modified
1046 * @return true if not in container mode or if flowEntry is internally
1049 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1050 return (!inContainerMode) ? true : flowEntry.isInternal();
1054 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1056 * Run a check on the original entries to decide whether to go with a
1057 * add or modify method. A loose check means only check against the
1058 * original flow entry requests and not against the installed flow
1059 * entries which are the result of the original entry merged with the
1060 * container flow(s) (if any). The modifyFlowEntry method in presence of
1061 * conflicts with the Container flows (if any) would revert back to a
1062 * delete + add pattern
1064 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1066 if (currentFlowEntry != null) {
1067 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1069 return installFlowEntry(newFlowEntry);
1074 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1076 * Run a check on the original entries to decide whether to go with a
1077 * add or modify method. A loose check means only check against the
1078 * original flow entry requests and not against the installed flow
1079 * entries which are the result of the original entry merged with the
1080 * container flow(s) (if any). The modifyFlowEntry method in presence of
1081 * conflicts with the Container flows (if any) would revert back to a
1082 * delete + add pattern
1084 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1086 if (currentFlowEntry != null) {
1087 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1089 return installFlowEntryAsync(newFlowEntry);
1094 public Status uninstallFlowEntryGroup(String groupName) {
1095 if (groupName == null || groupName.isEmpty()) {
1096 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1098 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1099 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1101 if (inContainerMode) {
1102 String msg = "Controller in container mode: Group Uninstall Refused";
1103 String logMsg = msg + ": {}";
1104 log.warn(logMsg, groupName);
1105 return new Status(StatusCode.NOTACCEPTABLE, msg);
1107 int toBeRemoved = 0;
1109 if (groupFlows.containsKey(groupName)) {
1110 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1111 toBeRemoved = list.size();
1112 for (FlowEntryInstall entry : list) {
1113 Status status = this.removeEntry(entry.getOriginal(), false);
1114 if (status.isSuccess()) {
1117 error = status.getDescription();
1121 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1122 "Not all the flows were removed: " + error);
1126 public Status uninstallFlowEntryGroupAsync(String groupName) {
1127 if (groupName == null || groupName.isEmpty()) {
1128 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1130 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1131 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1133 if (inContainerMode) {
1134 String msg = "Controller in container mode: Group Uninstall Refused";
1135 String logMsg = msg + ": {}";
1136 log.warn(logMsg, groupName);
1137 return new Status(StatusCode.NOTACCEPTABLE, msg);
1139 if (groupFlows.containsKey(groupName)) {
1140 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1141 for (FlowEntryInstall entry : list) {
1142 this.removeEntry(entry.getOriginal(), true);
1145 return new Status(StatusCode.SUCCESS);
1149 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1150 return entryConflictsWithContainerFlows(flowEntry);
1154 * Updates all installed flows because the container flow got updated This
1155 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1156 * Reinstall of all flows This is needed because a new container flows
1157 * merged flow may conflict with an existing old container flows merged flow
1158 * on the network node
1160 protected void updateFlowsContainerFlow() {
1161 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1162 // First remove all installed entries
1163 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1164 FlowEntryInstall current = entry.getValue();
1165 // Store the original entry
1166 toReInstall.add(current.getOriginal());
1167 // Remove the old couples. No validity checks to be run, use the
1169 this.removeEntryInternal(current, false);
1171 // Then reinstall the original entries
1172 for (FlowEntry entry : toReInstall) {
1173 // Reinstall the original flow entries, via the regular path: new
1174 // cFlow merge + validations
1175 this.installFlowEntry(entry);
1179 private void nonClusterObjectCreate() {
1180 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1181 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1182 TSPolicies = new ConcurrentHashMap<String, Object>();
1183 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1184 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1185 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1186 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1187 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1191 public void setTSPolicyData(String policyname, Object o, boolean add) {
1194 /* Check if this policy already exists */
1195 if (!(TSPolicies.containsKey(policyname))) {
1196 TSPolicies.put(policyname, o);
1199 TSPolicies.remove(policyname);
1201 if (frmAware != null) {
1202 synchronized (frmAware) {
1203 for (IForwardingRulesManagerAware frma : frmAware) {
1205 frma.policyUpdate(policyname, add);
1206 } catch (Exception e) {
1207 log.warn("Exception on callback", e);
1215 public Map<String, Object> getTSPolicyData() {
1220 public Object getTSPolicyData(String policyName) {
1221 if (TSPolicies.containsKey(policyName)) {
1222 return TSPolicies.get(policyName);
1229 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1230 List<FlowEntry> list = new ArrayList<FlowEntry>();
1231 if (policyName != null && !policyName.trim().isEmpty()) {
1232 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1233 if (policyName.equals(entry.getKey().getGroupName())) {
1234 list.add(entry.getValue().clone());
1242 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1243 List<FlowEntry> list = new ArrayList<FlowEntry>();
1244 if (policyName != null && !policyName.trim().isEmpty()) {
1245 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1246 if (policyName.equals(entry.getKey().getGroupName())) {
1247 list.add(entry.getValue().getInstall().clone());
1255 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1257 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1258 if (flow.getFlowName().equals(flowName)) {
1259 FlowEntry currentFlowEntry = flow.getOriginal();
1260 FlowEntry newFlowEntry = currentFlowEntry.clone();
1261 for (NodeConnector dstPort : portList) {
1262 newFlowEntry.getFlow().addAction(new Output(dstPort));
1264 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1265 if (error.isSuccess()) {
1266 log.trace("Ports {} added to FlowEntry {}", portList, flowName);
1268 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1269 currentFlowEntry.toString(), error.getDescription());
1274 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1278 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1279 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1280 FlowEntryInstall flow = this.installedSwView.get(index);
1281 if (flow.getFlowName().equals(flowName)) {
1282 FlowEntry currentFlowEntry = flow.getOriginal();
1283 FlowEntry newFlowEntry = currentFlowEntry.clone();
1284 for (NodeConnector dstPort : portList) {
1285 Action action = new Output(dstPort);
1286 newFlowEntry.getFlow().removeAction(action);
1288 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1289 if (status.isSuccess()) {
1290 log.trace("Ports {} removed from FlowEntry {}", portList, flowName);
1292 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1293 currentFlowEntry.toString(), status.getDescription());
1298 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1302 * This function assumes the target flow has only one output port
1305 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1306 FlowEntry currentFlowEntry = null;
1307 FlowEntry newFlowEntry = null;
1310 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1311 FlowEntryInstall flow = this.installedSwView.get(index);
1312 if (flow.getFlowName().equals(flowName)) {
1313 currentFlowEntry = flow.getOriginal();
1317 if (currentFlowEntry == null) {
1318 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1322 // Create a flow copy with the new output port
1323 newFlowEntry = currentFlowEntry.clone();
1324 Action target = null;
1325 for (Action action : newFlowEntry.getFlow().getActions()) {
1326 if (action.getType() == ActionType.OUTPUT) {
1331 newFlowEntry.getFlow().removeAction(target);
1332 newFlowEntry.getFlow().addAction(new Output(outPort));
1334 // Modify on network node
1335 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1337 if (status.isSuccess()) {
1338 log.trace("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1340 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1341 status.getDescription());
1347 public NodeConnector getOutputPort(Node node, String flowName) {
1348 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1349 FlowEntryInstall flow = this.installedSwView.get(index);
1350 if (flow.getFlowName().equals(flowName)) {
1351 for (Action action : flow.getOriginal().getFlow().getActions()) {
1352 if (action.getType() == ActionType.OUTPUT) {
1353 return ((Output) action).getPort();
1361 private void cacheStartup() {
1366 private void allocateCaches() {
1367 if (this.clusterContainerService == null) {
1368 log.warn("Un-initialized clusterContainerService, can't create cache");
1372 log.debug("Allocating caches for Container {}", container.getName());
1375 clusterContainerService.createCache(ORIGINAL_SW_VIEW_CACHE,
1376 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1378 clusterContainerService.createCache(INSTALLED_SW_VIEW_CACHE,
1379 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1381 clusterContainerService.createCache("frm.inactiveFlows",
1382 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1384 clusterContainerService.createCache("frm.staticFlows",
1385 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1387 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1388 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1390 clusterContainerService.createCache("frm.portGroupConfigs",
1391 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1393 clusterContainerService.createCache("frm.portGroupData",
1394 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1396 clusterContainerService.createCache("frm.TSPolicies",
1397 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1399 clusterContainerService.createCache(WORK_STATUS_CACHE,
1400 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1402 clusterContainerService.createCache(WORK_ORDER_CACHE,
1403 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1405 } catch (CacheConfigException cce) {
1406 log.error("CacheConfigException");
1407 } catch (CacheExistException cce) {
1408 log.error("CacheExistException");
1412 @SuppressWarnings({ "unchecked" })
1413 private void retrieveCaches() {
1414 ConcurrentMap<?, ?> map;
1416 if (this.clusterContainerService == null) {
1417 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1418 nonClusterObjectCreate();
1422 log.debug("Retrieving Caches for Container {}", container.getName());
1424 map = clusterContainerService.getCache(ORIGINAL_SW_VIEW_CACHE);
1426 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1428 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1431 map = clusterContainerService.getCache(INSTALLED_SW_VIEW_CACHE);
1433 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1435 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1438 map = clusterContainerService.getCache("frm.inactiveFlows");
1440 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1442 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1445 map = clusterContainerService.getCache("frm.staticFlows");
1447 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1449 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1452 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1454 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1456 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1459 map = clusterContainerService.getCache("frm.portGroupConfigs");
1461 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1463 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1466 map = clusterContainerService.getCache("frm.portGroupData");
1468 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1470 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1473 map = clusterContainerService.getCache("frm.TSPolicies");
1475 TSPolicies = (ConcurrentMap<String, Object>) map;
1477 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1480 map = clusterContainerService.getCache(WORK_ORDER_CACHE);
1482 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1484 log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName());
1487 map = clusterContainerService.getCache(WORK_STATUS_CACHE);
1489 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1491 log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName());
1495 private boolean flowConfigExists(FlowConfig config) {
1496 // Flow name has to be unique on per node id basis
1497 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1498 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1506 public Status addStaticFlow(FlowConfig config) {
1507 // Configuration object validation
1508 Status status = config.validate(container);
1509 if (!status.isSuccess()) {
1510 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1511 String error = "Invalid Configuration (" + status.getDescription() + ")";
1512 config.setStatus(error);
1513 return new Status(StatusCode.BADREQUEST, error);
1515 return addStaticFlowInternal(config, false);
1519 * Private method to add a static flow configuration which does not run any
1520 * validation on the passed FlowConfig object. If restore is set to true,
1521 * configuration is stored in configuration database regardless the
1522 * installation on the network node was successful. This is useful at boot
1523 * when static flows are present in startup configuration and are read
1524 * before the switches connects.
1527 * The static flow configuration
1529 * if true, the configuration is stored regardless the
1530 * installation on the network node was successful
1531 * @return The status of this request
1533 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1534 boolean multipleFlowPush = false;
1537 config.setStatus(StatusCode.SUCCESS.toString());
1540 if (flowConfigExists(config)) {
1541 error = "Entry with this name on specified switch already exists";
1542 log.warn("Entry with this name on specified switch already exists: {}", config);
1543 config.setStatus(error);
1544 return new Status(StatusCode.CONFLICT, error);
1547 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1548 for (String portGroupName : portGroupConfigs.keySet()) {
1549 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1550 multipleFlowPush = true;
1554 if (!multipleFlowPush) {
1555 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1556 error = "Invalid Configuration (Invalid PortGroup Name)";
1557 config.setStatus(error);
1558 return new Status(StatusCode.BADREQUEST, error);
1563 * If requested program the entry in hardware first before updating the
1566 if (!multipleFlowPush) {
1568 if (config.installInHw()) {
1569 FlowEntry entry = config.getFlowEntry();
1570 status = this.installFlowEntry(entry);
1571 if (!status.isSuccess()) {
1572 config.setStatus(status.getDescription());
1581 * When the control reaches this point, either of the following
1582 * conditions is true 1. This is a single entry configuration (non
1583 * PortGroup) and the hardware installation is successful 2. This is a
1584 * multiple entry configuration (PortGroup) and hardware installation is
1585 * NOT done directly on this event. 3. The User prefers to retain the
1586 * configuration in Controller and skip hardware installation.
1588 * Hence it is safe to update the StaticFlow DB at this point.
1590 * Note : For the case of PortGrouping, it is essential to have this DB
1591 * populated before the PortGroupListeners can query for the DB
1592 * triggered using portGroupChanged event...
1594 Integer ordinal = staticFlowsOrdinal.get(0);
1595 staticFlowsOrdinal.put(0, ++ordinal);
1596 staticFlows.put(ordinal, config);
1598 if (multipleFlowPush) {
1599 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1600 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1601 if (existingData != null) {
1602 portGroupChanged(pgconfig, existingData, true);
1605 return new Status(StatusCode.SUCCESS);
1608 private void addStaticFlowsToSwitch(Node node) {
1609 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1610 FlowConfig config = entry.getValue();
1611 if (config.isPortGroupEnabled()) {
1614 if (config.getNode().equals(node)) {
1615 if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) {
1616 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1617 config.setStatus(status.getDescription());
1621 // Update cluster cache
1622 refreshClusterStaticFlowsStatus(node);
1625 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1626 log.trace("Updating Static Flow configs on node down: {}", node);
1628 List<Integer> toRemove = new ArrayList<Integer>();
1629 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1631 FlowConfig config = entry.getValue();
1633 if (config.isPortGroupEnabled()) {
1637 if (config.installInHw() && config.getNode().equals(node)) {
1638 if (config.isInternalFlow()) {
1639 // Take note of this controller generated static flow
1640 toRemove.add(entry.getKey());
1642 config.setStatus(NODE_DOWN);
1646 // Remove controller generated static flows for this node
1647 for (Integer index : toRemove) {
1648 staticFlows.remove(index);
1650 // Update cluster cache
1651 refreshClusterStaticFlowsStatus(node);
1655 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1656 log.trace("Updating Static Flow configs on container mode change: {}", update);
1658 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1659 FlowConfig config = entry.getValue();
1660 if (config.isPortGroupEnabled()) {
1663 if (config.installInHw() && !config.isInternalFlow()) {
1666 config.setStatus("Removed from node because in container mode");
1669 config.setStatus(StatusCode.SUCCESS.toString());
1675 // Update cluster cache
1676 refreshClusterStaticFlowsStatus(null);
1680 public Status removeStaticFlow(FlowConfig config) {
1682 * No config.isInternal() check as NB does not take this path and GUI
1683 * cannot issue a delete on an internal generated flow. We need this
1684 * path to be accessible when switch mode is changed from proactive to
1685 * reactive, so that we can remove the internal generated LLDP and ARP
1689 // Look for the target configuration entry
1691 FlowConfig target = null;
1692 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1693 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1694 key = entry.getKey();
1695 target = entry.getValue();
1699 if (target == null) {
1700 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1703 // Program the network node
1704 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1706 // Update configuration database if programming was successful
1707 if (status.isSuccess()) {
1708 staticFlows.remove(key);
1715 public Status removeStaticFlow(String name, Node node) {
1716 // Look for the target configuration entry
1718 FlowConfig target = null;
1719 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1720 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1721 key = mapEntry.getKey();
1722 target = mapEntry.getValue();
1726 if (target == null) {
1727 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1730 // Validity check for api3 entry point
1731 if (target.isInternalFlow()) {
1732 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1733 String logMsg = msg + ": {}";
1734 log.warn(logMsg, name);
1735 return new Status(StatusCode.NOTACCEPTABLE, msg);
1738 if (target.isPortGroupEnabled()) {
1739 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1740 String logMsg = msg + ": {}";
1741 log.warn(logMsg, name);
1742 return new Status(StatusCode.NOTACCEPTABLE, msg);
1745 // Program the network node
1746 Status status = this.removeEntry(target.getFlowEntry(), false);
1748 // Update configuration database if programming was successful
1749 if (status.isSuccess()) {
1750 staticFlows.remove(key);
1757 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1758 // Validity check for api3 entry point
1759 if (newFlowConfig.isInternalFlow()) {
1760 String msg = "Invalid operation: Controller generated flow cannot be modified";
1761 String logMsg = msg + ": {}";
1762 log.warn(logMsg, newFlowConfig);
1763 return new Status(StatusCode.NOTACCEPTABLE, msg);
1767 Status status = newFlowConfig.validate(container);
1768 if (!status.isSuccess()) {
1769 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1770 newFlowConfig.setStatus(msg);
1771 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1772 return new Status(StatusCode.BADREQUEST, msg);
1775 FlowConfig oldFlowConfig = null;
1776 Integer index = null;
1777 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1778 FlowConfig entry = mapEntry.getValue();
1779 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1780 oldFlowConfig = entry;
1781 index = mapEntry.getKey();
1786 if (oldFlowConfig == null) {
1787 String msg = "Attempt to modify a non existing static flow";
1788 String logMsg = msg + ": {}";
1789 log.warn(logMsg, newFlowConfig);
1790 return new Status(StatusCode.NOTFOUND, msg);
1793 // Do not attempt to reinstall the flow, warn user
1794 if (newFlowConfig.equals(oldFlowConfig)) {
1795 String msg = "No modification detected";
1796 log.trace("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1797 return new Status(StatusCode.SUCCESS, msg);
1800 // If flow is installed, program the network node
1801 status = new Status(StatusCode.SUCCESS, "Saved in config");
1802 if (oldFlowConfig.installInHw()) {
1803 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1806 // Update configuration database if programming was successful
1807 if (status.isSuccess()) {
1808 newFlowConfig.setStatus(status.getDescription());
1809 staticFlows.put(index, newFlowConfig);
1816 public Status toggleStaticFlowStatus(String name, Node node) {
1817 return toggleStaticFlowStatus(getStaticFlow(name, node));
1821 public Status toggleStaticFlowStatus(FlowConfig config) {
1822 if (config == null) {
1823 String msg = "Invalid request: null flow config";
1825 return new Status(StatusCode.BADREQUEST, msg);
1827 // Validity check for api3 entry point
1828 if (config.isInternalFlow()) {
1829 String msg = "Invalid operation: Controller generated flow cannot be modified";
1830 String logMsg = msg + ": {}";
1831 log.warn(logMsg, config);
1832 return new Status(StatusCode.NOTACCEPTABLE, msg);
1835 // Find the config entry
1837 FlowConfig target = null;
1838 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1839 FlowConfig conf = entry.getValue();
1840 if (conf.isByNameAndNodeIdEqual(config)) {
1841 key = entry.getKey();
1846 if (target != null) {
1847 Status status = target.validate(container);
1848 if (!status.isSuccess()) {
1849 log.warn(status.getDescription());
1852 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1853 .installFlowEntry(target.getFlowEntry());
1854 if (status.isSuccess()) {
1855 // Update Configuration database
1856 target.setStatus(StatusCode.SUCCESS.toString());
1857 target.toggleInstallation();
1858 staticFlows.put(key, target);
1863 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1867 * Reinsert all static flows entries in the cache to force cache updates in
1868 * the cluster. This is useful when only some parameters were changed in the
1869 * entries, like the status.
1872 * The node for which the static flow configurations have to be
1873 * refreshed. If null, all nodes static flows will be refreshed.
1875 private void refreshClusterStaticFlowsStatus(Node node) {
1876 // Refresh cluster cache
1877 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1878 if (node == null || entry.getValue().getNode().equals(node)) {
1879 staticFlows.put(entry.getKey(), entry.getValue());
1885 * Uninstall all the non-internal Flow Entries present in the software view.
1886 * If requested, a copy of each original flow entry will be stored in the
1887 * inactive list so that it can be re-applied when needed (This is typically
1888 * the case when running in the default container and controller moved to
1889 * container mode) NOTE WELL: The routine as long as does a bulk change will
1890 * operate only on the entries for nodes locally attached so to avoid
1891 * redundant operations initiated by multiple nodes
1893 * @param preserveFlowEntries
1894 * if true, a copy of each original entry is stored in the
1897 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1898 log.trace("Uninstalling all non-internal flows");
1900 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1902 // Store entries / create target list
1903 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1904 FlowEntryInstall flowEntries = mapEntry.getValue();
1905 // Skip internal generated static flows
1906 if (!flowEntries.isInternal()) {
1907 toRemove.add(flowEntries);
1908 // Store the original entries if requested
1909 if (preserveFlowEntries) {
1910 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1915 // Now remove the entries
1916 for (FlowEntryInstall flowEntryHw : toRemove) {
1917 Node n = flowEntryHw.getNode();
1918 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
1919 Status status = this.removeEntryInternal(flowEntryHw, false);
1920 if (!status.isSuccess()) {
1921 log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1924 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
1931 * Re-install all the Flow Entries present in the inactive list The inactive
1932 * list will be empty at the end of this call This function is called on the
1933 * default container instance of FRM only when the last container is deleted
1935 private void reinstallAllFlowEntries() {
1936 log.trace("Reinstalling all inactive flows");
1938 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1939 this.addEntry(flowEntry, false);
1942 // Empty inactive list in any case
1943 inactiveFlows.clear();
1947 public List<FlowConfig> getStaticFlows() {
1948 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1951 // TODO: need to come out with a better algorithm for maintaining the order
1952 // of the configuration entries
1953 // with actual one, index associated to deleted entries cannot be reused and
1955 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1956 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1957 for (int i = 0; i <= maxKey; i++) {
1958 FlowConfig entry = flowMap.get(i);
1959 if (entry != null) {
1960 orderedList.add(entry);
1967 public FlowConfig getStaticFlow(String name, Node node) {
1968 ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
1970 return entry.getValue();
1976 public List<FlowConfig> getStaticFlows(Node node) {
1977 List<FlowConfig> list = new ArrayList<FlowConfig>();
1978 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1979 if (entry.getValue().onNode(node)) {
1980 list.add(entry.getValue());
1987 public List<String> getStaticFlowNamesForNode(Node node) {
1988 List<String> list = new ArrayList<String>();
1989 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1990 if (entry.getValue().onNode(node)) {
1991 list.add(entry.getValue().getName());
1998 public List<Node> getListNodeWithConfiguredFlows() {
1999 Set<Node> set = new HashSet<Node>();
2000 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2001 set.add(entry.getValue().getNode());
2003 return new ArrayList<Node>(set);
2006 @SuppressWarnings("unchecked")
2007 private void loadFlowConfiguration() {
2008 ObjectReader objReader = new ObjectReader();
2009 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2012 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2015 if (pgConfig != null) {
2016 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2017 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2021 if (confList == null) {
2026 for (Integer key : confList.keySet()) {
2027 if (key.intValue() > maxKey) {
2028 maxKey = key.intValue();
2032 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2033 addStaticFlowInternal(conf, true);
2038 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2039 return ois.readObject();
2043 public Status saveConfig() {
2044 return saveConfigInternal();
2047 private Status saveConfigInternal() {
2048 ObjectWriter objWriter = new ObjectWriter();
2049 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2050 for (Integer ordinal : staticFlows.keySet()) {
2051 FlowConfig config = staticFlows.get(ordinal);
2052 // Do not save dynamic and controller generated static flows
2053 if (config.isDynamic() || config.isInternalFlow()) {
2056 nonDynamicFlows.put(ordinal, config);
2058 objWriter.write(nonDynamicFlows, frmFileName);
2059 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2060 return new Status(StatusCode.SUCCESS, null);
2064 public void subnetNotify(Subnet sub, boolean add) {
2067 private boolean programInternalFlow(boolean proactive, FlowConfig fc) {
2068 boolean retVal = true; // program flows unless determined otherwise
2070 // if the flow already exists do not program
2071 if(flowConfigExists(fc)) {
2075 // if the flow does not exist do not program
2076 if(!flowConfigExists(fc)) {
2086 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2089 * This method can be called from within the OSGi framework context,
2090 * given the programming operation can take sometime, it not good
2091 * pratice to have in it's context operations that can take time,
2092 * hence moving off to a different thread for async processing.
2094 private ExecutorService executor;
2096 public void modeChangeNotify(final Node node, final boolean proactive) {
2097 Callable<Status> modeChangeCallable = new Callable<Status>() {
2099 public Status call() throws Exception {
2100 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2102 List<String> puntAction = new ArrayList<String>();
2103 puntAction.add(ActionType.CONTROLLER.toString());
2105 FlowConfig allowARP = new FlowConfig();
2106 allowARP.setInstallInHw(true);
2107 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2108 allowARP.setPriority("1");
2109 allowARP.setNode(node);
2110 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2112 allowARP.setActions(puntAction);
2113 defaultConfigs.add(allowARP);
2115 FlowConfig allowLLDP = new FlowConfig();
2116 allowLLDP.setInstallInHw(true);
2117 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2118 allowLLDP.setPriority("1");
2119 allowLLDP.setNode(node);
2120 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2122 allowLLDP.setActions(puntAction);
2123 defaultConfigs.add(allowLLDP);
2125 List<String> dropAction = new ArrayList<String>();
2126 dropAction.add(ActionType.DROP.toString());
2128 FlowConfig dropAllConfig = new FlowConfig();
2129 dropAllConfig.setInstallInHw(true);
2130 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2131 + FlowConfig.INTERNALSTATICFLOWEND);
2132 dropAllConfig.setPriority("0");
2133 dropAllConfig.setNode(node);
2134 dropAllConfig.setActions(dropAction);
2135 defaultConfigs.add(dropAllConfig);
2137 log.trace("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2138 for (FlowConfig fc : defaultConfigs) {
2139 // check if the frm really needs to act on the notification.
2140 // this is to check against duplicate notifications
2141 if(programInternalFlow(proactive, fc)) {
2142 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2143 if (status.isSuccess()) {
2144 log.trace("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2146 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2150 log.debug("Got redundant install request for internal flow: {} on node: {}. Request not sent to FRM.", fc.getName(), node);
2153 return new Status(StatusCode.SUCCESS);
2158 * Execute the work outside the caller context, this could be an
2159 * expensive operation and we don't want to block the caller for it.
2161 this.executor.submit(modeChangeCallable);
2165 * Remove from the databases all the flows installed on the node
2169 private void cleanDatabaseForNode(Node node) {
2170 log.trace("Cleaning Flow database for Node {}", node);
2171 if (nodeFlows.containsKey(node)) {
2172 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2174 for (FlowEntryInstall entry : toRemove) {
2175 updateSwViews(entry, false);
2180 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2185 Match match = flow.getMatch();
2186 if (match.isPresent(MatchType.IN_PORT)) {
2187 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2188 if (matchPort.equals(nc)) {
2192 List<Action> actionsList = flow.getActions();
2193 if (actionsList != null) {
2194 for (Action action : actionsList) {
2195 if (action instanceof Output) {
2196 NodeConnector actionPort = ((Output) action).getPort();
2197 if (actionPort.equals(nc)) {
2207 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2208 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2212 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2213 boolean updateStaticFlowCluster = false;
2219 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2220 if (config != null) {
2221 switch (config.getValue()) {
2222 case Config.ADMIN_DOWN:
2223 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2224 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2226 case Config.ADMIN_UP:
2227 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2228 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2230 case Config.ADMIN_UNDEF:
2237 // This is the case where a switch port is removed from the SDN agent space
2238 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2239 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2245 if (updateStaticFlowCluster) {
2246 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2251 * It goes through the static flows configuration, it identifies the ones
2252 * which have the specified node connector as input or output port and
2253 * install them on the network node if they are marked to be installed in
2254 * hardware and their status shows they were not installed yet
2256 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2257 boolean updated = false;
2258 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2259 for (FlowConfig flowConfig : flowConfigForNode) {
2260 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2261 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) {
2262 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2263 if (!status.isSuccess()) {
2264 flowConfig.setStatus(status.getDescription());
2266 flowConfig.setStatus(StatusCode.SUCCESS.toString());
2276 * Remove from the network node all the flows which have the specified node
2277 * connector as input or output port. If any of the flow entry is a static
2278 * flow, it updates the correspondent configuration.
2280 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2281 boolean updated = false;
2282 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2283 if (nodeFlowEntries == null) {
2286 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2287 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2288 Status status = this.removeEntryInternal(fei, true);
2289 if (!status.isSuccess()) {
2293 * If the flow entry is a static flow, then update its
2296 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2297 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2298 if (flowConfig != null) {
2299 flowConfig.setStatus(PORT_REMOVED);
2308 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2309 FlowConfig derivedFlow = new FlowConfig(original);
2310 derivedFlow.setDynamic(true);
2311 derivedFlow.setPortGroup(null);
2312 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2313 derivedFlow.setIngressPort(port + "");
2317 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2318 for (FlowConfig staticFlow : staticFlows.values()) {
2319 if (staticFlow.getPortGroup() == null) {
2322 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2323 for (Short port : data.getPorts()) {
2324 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2325 addStaticFlowInternal(derivedFlow, false);
2331 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2332 for (FlowConfig staticFlow : staticFlows.values()) {
2333 if (staticFlow.getPortGroup() == null) {
2336 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2337 for (Short port : data.getPorts()) {
2338 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2339 removeStaticFlow(derivedFlow);
2346 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2347 log.trace("PortGroup Changed for: {} Data: {}", config, portGroupData);
2348 Map<Node, PortGroup> existingData = portGroupData.get(config);
2349 if (existingData != null) {
2350 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2351 PortGroup existingPortGroup = existingData.get(entry.getKey());
2352 if (existingPortGroup == null) {
2354 existingData.put(entry.getKey(), entry.getValue());
2355 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2359 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2360 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2362 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2363 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2369 portGroupData.put(config, data);
2370 for (Node swid : data.keySet()) {
2371 addPortGroupFlows(config, swid, data.get(swid));
2378 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2379 PortGroupConfig config = portGroupConfigs.get(name);
2380 if (config != null) {
2384 if ((portGroupProvider == null) && !restore) {
2387 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2391 config = new PortGroupConfig(name, regex);
2392 portGroupConfigs.put(name, config);
2393 if (portGroupProvider != null) {
2394 portGroupProvider.createPortGroupConfig(config);
2400 public boolean delPortGroupConfig(String name) {
2401 PortGroupConfig config = portGroupConfigs.get(name);
2402 if (config == null) {
2406 if (portGroupProvider != null) {
2407 portGroupProvider.deletePortGroupConfig(config);
2409 portGroupConfigs.remove(name);
2414 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2415 return portGroupConfigs;
2418 public boolean isPortGroupSupported() {
2419 if (portGroupProvider == null) {
2425 public void setIContainer(IContainer s) {
2429 public void unsetIContainer(IContainer s) {
2430 if (this.container == s) {
2431 this.container = null;
2436 public PortGroupProvider getPortGroupProvider() {
2437 return portGroupProvider;
2440 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2441 this.portGroupProvider = null;
2444 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2445 this.portGroupProvider = portGroupProvider;
2446 portGroupProvider.registerPortGroupChange(this);
2447 for (PortGroupConfig config : portGroupConfigs.values()) {
2448 portGroupProvider.createPortGroupConfig(config);
2452 public void setFrmAware(IForwardingRulesManagerAware obj) {
2453 this.frmAware.add(obj);
2456 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2457 this.frmAware.remove(obj);
2460 void setClusterContainerService(IClusterContainerServices s) {
2461 log.debug("Cluster Service set");
2462 this.clusterContainerService = s;
2465 void unsetClusterContainerService(IClusterContainerServices s) {
2466 if (this.clusterContainerService == s) {
2467 log.debug("Cluster Service removed!");
2468 this.clusterContainerService = null;
2472 private String getContainerName() {
2473 if (container == null) {
2474 return GlobalConstants.DEFAULT.toString();
2476 return container.getName();
2480 * Function called by the dependency manager when all the required
2481 * dependencies are satisfied
2485 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2486 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2488 inContainerMode = false;
2490 if (portGroupProvider != null) {
2491 portGroupProvider.registerPortGroupChange(this);
2494 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
2495 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
2500 * If we are not the first cluster node to come up, do not initialize
2501 * the static flow entries ordinal
2503 if (staticFlowsOrdinal.size() == 0) {
2504 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2507 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2509 // Initialize the event handler thread
2510 frmEventHandler = new Thread(new Runnable() {
2515 final FRMEvent event = pendingEvents.take();
2516 if (event == null) {
2517 log.warn("Dequeued null event");
2520 log.trace("Dequeued {} event", event.getClass().getSimpleName());
2521 if (event instanceof NodeUpdateEvent) {
2522 NodeUpdateEvent update = (NodeUpdateEvent) event;
2523 Node node = update.getNode();
2524 switch (update.getUpdateType()) {
2526 addStaticFlowsToSwitch(node);
2529 cleanDatabaseForNode(node);
2530 updateStaticFlowConfigsOnNodeDown(node);
2534 } else if (event instanceof ErrorReportedEvent) {
2535 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2536 processErrorEvent(errEvent);
2537 } else if (event instanceof WorkOrderEvent) {
2539 * Take care of handling the remote Work request
2541 Runnable r = new Runnable() {
2544 WorkOrderEvent work = (WorkOrderEvent) event;
2545 FlowEntryDistributionOrder fe = work.getFe();
2547 logsync.trace("Executing the workOrder {}", fe);
2548 Status gotStatus = null;
2549 FlowEntryInstall feiCurrent = fe.getEntry();
2550 FlowEntryInstall feiNew = workOrder.get(fe);
2551 switch (fe.getUpType()) {
2553 gotStatus = addEntriesInternal(feiCurrent, false);
2556 gotStatus = modifyEntryInternal(feiCurrent, feiNew, false);
2559 gotStatus = removeEntryInternal(feiCurrent, false);
2563 workOrder.remove(fe);
2565 "The workOrder has been executed and now the status is being returned {}", fe);
2567 workStatus.put(fe, gotStatus);
2569 log.warn("Not expected null WorkOrder", work);
2573 if(executor != null) {
2574 executor.execute(r);
2576 } else if (event instanceof WorkStatusCleanup) {
2578 * Take care of handling the remote Work request
2580 WorkStatusCleanup work = (WorkStatusCleanup) event;
2581 FlowEntryDistributionOrder fe = work.getFe();
2583 logsync.trace("The workStatus {} is being removed", fe);
2584 workStatus.remove(fe);
2586 log.warn("Not expected null WorkStatus", work);
2588 } else if (event instanceof ContainerFlowChangeEvent) {
2590 * Whether it is an addition or removal, we have to
2591 * recompute the merged flows entries taking into
2592 * account all the current container flows because
2593 * flow merging is not an injective function
2595 updateFlowsContainerFlow();
2596 } else if (event instanceof UpdateIndexDBs) {
2597 UpdateIndexDBs update = (UpdateIndexDBs)event;
2598 updateIndexDatabase(update.getFei(), update.isAddition());
2600 log.warn("Dequeued unknown event {}", event.getClass().getSimpleName());
2602 } catch (InterruptedException e) {
2603 // clear pending events
2604 pendingEvents.clear();
2608 }, "FRM EventHandler Collector");
2612 * Function called by the dependency manager when at least one dependency
2613 * become unsatisfied or when the component is shutting down because for
2614 * example bundle is being stopped.
2618 // Interrupt the thread
2619 frmEventHandler.interrupt();
2620 // Clear the pendingEvents queue
2621 pendingEvents.clear();
2623 workMonitor.clear();
2627 * Function called by dependency manager after "init ()" is called and after
2628 * the services provided by the class are registered in the service registry
2633 * If running in default container, need to know if controller is in
2636 if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) {
2637 inContainerMode = containerManager.inContainerMode();
2640 // Initialize graceful stop flag
2643 // Allocate the executor service
2644 this.executor = Executors.newFixedThreadPool(maxPoolSize);
2646 // Start event handler thread
2647 frmEventHandler.start();
2649 // replay the installedSwView data structure to populate
2650 // node flows and group flows
2651 for (FlowEntryInstall fei : installedSwView.values()) {
2652 pendingEvents.offer(new UpdateIndexDBs(fei, true));
2656 * Read startup and build database if we are the coordinator
2658 if ((clusterContainerService != null) && (clusterContainerService.amICoordinator())) {
2659 loadFlowConfiguration();
2664 * Function called by the dependency manager before Container is Stopped and Destroyed.
2666 public void containerStop() {
2667 uninstallAllFlowEntries(false);
2671 * Function called by the dependency manager before the services exported by
2672 * the component are unregistered, this will be followed by a "destroy ()"
2677 // Shutdown executor
2678 this.executor.shutdownNow();
2679 // Now walk all the workMonitor and wake up the one sleeping because
2680 // destruction is happening
2681 for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2682 FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2687 public void setFlowProgrammerService(IFlowProgrammerService service) {
2688 this.programmer = service;
2691 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2692 if (this.programmer == service) {
2693 this.programmer = null;
2697 public void setSwitchManager(ISwitchManager switchManager) {
2698 this.switchManager = switchManager;
2701 public void unsetSwitchManager(ISwitchManager switchManager) {
2702 if (this.switchManager == switchManager) {
2703 this.switchManager = null;
2708 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2709 if (!container.getName().equals(containerName)) {
2715 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2716 if (!container.getName().equals(containerName)) {
2719 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2720 container.getName(), t, current);
2721 ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2722 pendingEvents.offer(ev);
2726 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2727 if (!container.getName().equals(containerName)) {
2731 boolean updateStaticFlowCluster = false;
2735 log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2736 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2739 log.trace("Port {} was added to container: reinstall interested flows", nc);
2740 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2748 if (updateStaticFlowCluster) {
2749 refreshClusterStaticFlowsStatus(nc.getNode());
2754 public void containerModeUpdated(UpdateType update) {
2755 // Only default container instance reacts on this event
2756 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2762 * Controller is moving to container mode. We are in the default
2763 * container context, we need to remove all our non-internal flows
2764 * to prevent any container isolation breakage. We also need to
2765 * preserve our flow so that they can be re-installed if we move
2766 * back to non container mode (no containers).
2768 this.inContainerMode = true;
2769 this.uninstallAllFlowEntries(true);
2772 this.inContainerMode = false;
2773 this.reinstallAllFlowEntries();
2778 // Update our configuration DB
2779 updateStaticFlowConfigsOnContainerModeChange(update);
2782 protected abstract class FRMEvent {
2786 private class NodeUpdateEvent extends FRMEvent {
2787 private final Node node;
2788 private final UpdateType update;
2790 public NodeUpdateEvent(UpdateType update, Node node) {
2791 this.update = update;
2795 public UpdateType getUpdateType() {
2799 public Node getNode() {
2804 private class ErrorReportedEvent extends FRMEvent {
2805 private final long rid;
2806 private final Node node;
2807 private final Object error;
2809 public ErrorReportedEvent(long rid, Node node, Object error) {
2815 public long getRequestId() {
2819 public Object getError() {
2823 public Node getNode() {
2828 private class WorkOrderEvent extends FRMEvent {
2829 private FlowEntryDistributionOrder fe;
2830 private FlowEntryInstall newEntry;
2836 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2838 this.newEntry = newEntry;
2844 public FlowEntryDistributionOrder getFe() {
2849 * @return the newEntry
2851 public FlowEntryInstall getNewEntry() {
2855 private class ContainerFlowChangeEvent extends FRMEvent {
2856 private final ContainerFlow previous;
2857 private final ContainerFlow current;
2858 private final UpdateType type;
2860 public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2861 this.previous = previous;
2862 this.current = current;
2866 public ContainerFlow getPrevious() {
2867 return this.previous;
2870 public ContainerFlow getCurrent() {
2871 return this.current;
2874 public UpdateType getType() {
2880 private class WorkStatusCleanup extends FRMEvent {
2881 private FlowEntryDistributionOrder fe;
2886 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2893 public FlowEntryDistributionOrder getFe() {
2898 private class UpdateIndexDBs extends FRMEvent {
2899 private FlowEntryInstall fei;
2900 private boolean add;
2904 * @param fei the flow entry which was installed/removed on the netwrok node
2907 UpdateIndexDBs(FlowEntryInstall fei, boolean add) {
2914 * @return the flowEntryInstall object which was added/removed
2915 * to/from the installed software view cache
2917 public FlowEntryInstall getFei() {
2923 * @return whether this was an flow addition or removal
2925 public boolean isAddition() {
2931 public Status saveConfiguration() {
2932 return saveConfig();
2936 public void flowRemoved(Node node, Flow flow) {
2937 log.trace("Received flow removed notification on {} for {}", node, flow);
2939 // For flow entry identification, only node, match and priority matter
2940 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2941 FlowEntryInstall installedEntry = this.installedSwView.get(test);
2942 if (installedEntry == null) {
2943 log.trace("Entry is not known to us");
2947 // Update Static flow status
2949 FlowConfig target = null;
2950 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2951 FlowConfig conf = entry.getValue();
2952 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
2953 key = entry.getKey();
2958 if (target != null) {
2959 // Update Configuration database
2960 if (target.getHardTimeout() != null || target.getIdleTimeout() != null) {
2962 * No need for checking if actual values: these strings were
2963 * validated at configuration creation. Also, after a switch
2964 * down scenario, no use to reinstall a timed flow. Mark it as
2965 * "do not install". User can manually toggle it.
2967 target.toggleInstallation();
2969 target.setStatus(StatusCode.GONE.toString());
2970 staticFlows.put(key, target);
2973 // Update software views
2974 this.updateSwViews(installedEntry, false);
2978 public void flowErrorReported(Node node, long rid, Object err) {
2979 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
2980 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
2983 private void processErrorEvent(ErrorReportedEvent event) {
2984 Node node = event.getNode();
2985 long rid = event.getRequestId();
2986 Object error = event.getError();
2987 String errorString = (error == null) ? "Not provided" : error.toString();
2989 * If this was for a flow install, remove the corresponding entry from
2990 * the software view. If it was a Looking for the rid going through the
2991 * software database. TODO: A more efficient rid <-> FlowEntryInstall
2992 * mapping will have to be added in future
2994 FlowEntryInstall target = null;
2995 List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
2996 // flowEntryInstallList could be null.
2998 if(flowEntryInstallList != null) {
2999 for (FlowEntryInstall index : flowEntryInstallList) {
3000 FlowEntryInstall entry = installedSwView.get(index);
3002 if (entry.getRequestId() == rid) {
3009 if (target != null) {
3010 // This was a flow install, update database
3011 this.updateSwViews(target, false);
3012 // also update the config
3013 if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3014 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3015 // staticFlowEntry should never be null.
3016 // the null check is just an extra defensive check.
3017 if(staticFlowEntry != null) {
3018 // Modify status and update cluster cache
3019 log.debug("Updating static flow configuration on async error event");
3020 String status = String.format("Cannot be installed on node. reason: %s", errorString);
3021 staticFlowEntry.getValue().setStatus(status);
3022 refreshClusterStaticFlowsStatus(node);
3028 if (frmAware != null) {
3029 synchronized (frmAware) {
3030 for (IForwardingRulesManagerAware frma : frmAware) {
3032 frma.requestFailed(rid, errorString);
3033 } catch (Exception e) {
3034 log.warn("Failed to notify {}", frma);
3042 public Status solicitStatusResponse(Node node, boolean blocking) {
3043 Status rv = new Status(StatusCode.INTERNALERROR);
3045 if (this.programmer != null) {
3047 rv = programmer.syncSendBarrierMessage(node);
3049 rv = programmer.asyncSendBarrierMessage(node);
3056 public void unsetIConnectionManager(IConnectionManager s) {
3057 if (s == this.connectionManager) {
3058 this.connectionManager = null;
3062 public void setIConnectionManager(IConnectionManager s) {
3063 this.connectionManager = s;
3066 public void unsetIContainerManager(IContainerManager s) {
3067 if (s == this.containerManager) {
3068 this.containerManager = null;
3072 public void setIContainerManager(IContainerManager s) {
3073 this.containerManager = s;
3077 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3084 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3086 * Streamline the updates for the per node and per group index databases
3088 if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3089 pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)new_value, true));
3094 * Local updates are of no interest
3098 if (cacheName.equals(WORK_ORDER_CACHE)) {
3099 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3101 * This is the case of one workOrder becoming available, so we need
3102 * to dispatch the work to the appropriate handler
3104 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3105 FlowEntryInstall fei = fe.getEntry();
3109 Node n = fei.getNode();
3110 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3111 logsync.trace("workOrder for fe {} processed locally", fe);
3112 // I'm the controller in charge for the request, queue it for
3114 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3116 } else if (cacheName.equals(WORK_STATUS_CACHE)) {
3117 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3119 * This is the case of one workOrder being completed and a status
3122 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3124 * Check if the order was initiated by this controller in that case
3125 * we need to actually look at the status returned
3127 if (fe.getRequestorController()
3128 .equals(clusterContainerService.getMyAddress())) {
3129 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3131 logsync.trace("workStatus response is for us {}", fe);
3132 // Signal we got the status
3133 fet.gotStatus(fe, workStatus.get(fe));
3134 pendingEvents.offer(new WorkStatusCleanup(fe));
3141 public void entryDeleted(Object key, String cacheName, boolean originLocal) {
3143 * Streamline the updates for the per node and per group index databases
3145 if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3146 pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)key, false));
3154 public List<FlowEntry> getFlowEntriesForNode(Node node) {
3155 List<FlowEntry> list = new ArrayList<FlowEntry>();
3157 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
3158 if (node.equals(entry.getKey().getNode())) {
3159 list.add(entry.getValue().clone());
3170 public List<FlowEntry> getInstalledFlowEntriesForNode(Node node) {
3171 List<FlowEntry> list = new ArrayList<FlowEntry>();
3173 List<FlowEntryInstall> flowEntryInstallList = this.nodeFlows.get(node);
3174 if(flowEntryInstallList != null) {
3175 for(FlowEntryInstall fi: flowEntryInstallList) {
3176 list.add(fi.getInstall().clone());