BUG 2302 : odl-clustering-test-app should not be part of the odl-restconf-all feature set
[controller.git] / opendaylight / forwardingrulesmanager / implementation / src / main / java / org / opendaylight / controller / forwardingrulesmanager / internal / ForwardingRulesManager.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.forwardingrulesmanager.internal;
10
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;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Set;
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;
30
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.ConfigurationObject;
37 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
38 import org.opendaylight.controller.configuration.IConfigurationContainerService;
39 import org.opendaylight.controller.connectionmanager.IConnectionManager;
40 import org.opendaylight.controller.containermanager.IContainerManager;
41 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
42 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
43 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
44 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
45 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
46 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
47 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
48 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
50 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
51 import org.opendaylight.controller.sal.action.Action;
52 import org.opendaylight.controller.sal.action.ActionType;
53 import org.opendaylight.controller.sal.action.Enqueue;
54 import org.opendaylight.controller.sal.action.Flood;
55 import org.opendaylight.controller.sal.action.FloodAll;
56 import org.opendaylight.controller.sal.action.Output;
57 import org.opendaylight.controller.sal.connection.ConnectionLocality;
58 import org.opendaylight.controller.sal.core.Config;
59 import org.opendaylight.controller.sal.core.ContainerFlow;
60 import org.opendaylight.controller.sal.core.IContainer;
61 import org.opendaylight.controller.sal.core.IContainerLocalListener;
62 import org.opendaylight.controller.sal.core.Node;
63 import org.opendaylight.controller.sal.core.NodeConnector;
64 import org.opendaylight.controller.sal.core.Property;
65 import org.opendaylight.controller.sal.core.UpdateType;
66 import org.opendaylight.controller.sal.flowprogrammer.Flow;
67 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
68 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
69 import org.opendaylight.controller.sal.match.Match;
70 import org.opendaylight.controller.sal.match.MatchType;
71 import org.opendaylight.controller.sal.utils.EtherTypes;
72 import org.opendaylight.controller.sal.utils.GlobalConstants;
73 import org.opendaylight.controller.sal.utils.IObjectReader;
74 import org.opendaylight.controller.sal.utils.Status;
75 import org.opendaylight.controller.sal.utils.StatusCode;
76 import org.opendaylight.controller.switchmanager.IInventoryListener;
77 import org.opendaylight.controller.switchmanager.ISwitchManager;
78 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
79 import org.opendaylight.controller.switchmanager.Subnet;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82
83 /**
84  * Class that manages forwarding rule installation and removal per container of
85  * the network. It also maintains the central repository of all the forwarding
86  * rules installed on the network nodes.
87  */
88 public class ForwardingRulesManager implements
89         IForwardingRulesManager,
90         PortGroupChangeListener,
91         IContainerLocalListener,
92         ISwitchManagerAware,
93         IConfigurationContainerAware,
94         IInventoryListener,
95         IObjectReader,
96         ICacheUpdateAware<Object,Object>,
97         IFlowProgrammerListener {
98
99     private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
100     private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
101     private static final String PORT_REMOVED = "Port removed";
102     private static final String NODE_DOWN = "Node is Down";
103     private static final String INVALID_FLOW_ENTRY = "Invalid FlowEntry";
104     private static final String STATIC_FLOWS_FILE_NAME = "frm_staticflows.conf";
105     private static final String PORT_GROUP_FILE_NAME = "portgroup.conf";
106     private ConcurrentMap<Integer, FlowConfig> staticFlows;
107     private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
108     private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
109     private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
110     private ConcurrentMap<String, Object> TSPolicies;
111     private IContainerManager containerManager;
112     private IConfigurationContainerService configurationService;
113     private boolean inContainerMode; // being used by global instance only
114     protected boolean stopping;
115
116     /*
117      * Flow database. It's the software view of what was requested to install
118      * and what is installed on the switch. It is indexed by the entry itself.
119      * The entry's hashcode resumes the network node index, the flow's priority
120      * and the flow's match. The value element is a class which contains the
121      * flow entry pushed by the applications modules and the respective
122      * container flow merged version. In absence of container flows, the two
123      * flow entries are the same.
124      */
125     private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
126     private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
127     /*
128      * Per node and per group indexing
129      */
130     private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
131     private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
132
133     /*
134      * Inactive flow list. This is for the global instance of FRM It will
135      * contain all the flow entries which were installed on the global container
136      * when the first container is created.
137      */
138     private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
139
140     private IContainer container;
141     private Set<IForwardingRulesManagerAware> frmAware =
142         Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
143     private PortGroupProvider portGroupProvider;
144     private IFlowProgrammerService programmer;
145     private IClusterContainerServices clusterContainerService = null;
146     private ISwitchManager switchManager;
147     private Thread frmEventHandler;
148     protected BlockingQueue<FRMEvent> pendingEvents;
149
150     // Distributes FRM programming in the cluster
151     private IConnectionManager connectionManager;
152
153     /*
154      * Name clustered caches used to support FRM entry distribution these are by
155      * necessity non-transactional as long as need to be able to synchronize
156      * states also while a transaction is in progress
157      */
158     static final String WORK_ORDER_CACHE = "frm.workOrder";
159     static final String WORK_STATUS_CACHE = "frm.workStatus";
160     static final String ORIGINAL_SW_VIEW_CACHE = "frm.originalSwView";
161     static final String INSTALLED_SW_VIEW_CACHE = "frm.installedSwView";
162
163     /*
164      * Data structure responsible for distributing the FlowEntryInstall requests
165      * in the cluster. The key value is entry that is being either Installed or
166      * Updated or Delete. The value field is the same of the key value in case
167      * of Installation or Deletion, it's the new entry in case of Modification,
168      * this because the clustering caches don't allow null values.
169      *
170      * The logic behind this data structure is that the controller that initiate
171      * the request will place the order here, someone will pick it and then will
172      * remove from this data structure because is being served.
173      *
174      * TODO: We need to have a way to cleanup this data structure if entries are
175      * not picked by anyone, which is always a case can happen especially on
176      * Node disconnect cases.
177      */
178     protected ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
179
180     /*
181      * Data structure responsible for retrieving the results of the workOrder
182      * submitted to the cluster.
183      *
184      * The logic behind this data structure is that the controller that has
185      * executed the order will then place the result in workStatus signaling
186      * that there was a success or a failure.
187      *
188      * TODO: The workStatus entries need to have a lifetime associated in case
189      * of requestor controller leaving the cluster.
190      */
191     protected ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
192
193     /*
194      * Local Map used to hold the Future which a caller can use to monitor for
195      * completion
196      */
197     private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
198             new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
199
200     /*
201      * Max pool size for the executor
202      */
203     private static final int maxPoolSize = 10;
204
205     /**
206      * @param e
207      *            Entry being installed/updated/removed
208      * @param u
209      *            New entry will be placed after the update operation. Valid
210      *            only for UpdateType.CHANGED, null for all the other cases
211      * @param t
212      *            Type of update
213      * @return a Future object for monitoring the progress of the result, or
214      *         null in case the processing should take place locally
215      */
216     private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
217             UpdateType t) {
218         // A null entry it's an unexpected condition, anyway it's safe to keep
219         // the handling local
220         if (e == null) {
221             return null;
222         }
223
224         Node n = e.getNode();
225         if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
226             // Create the work order and distribute it
227             FlowEntryDistributionOrder fe =
228                     new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
229             // First create the monitor job
230             FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
231             logsync.trace("Node {} not local so sending fe {}", n, fe);
232             workMonitor.put(fe, ret);
233             if (t.equals(UpdateType.CHANGED)) {
234                 // Then distribute the work
235                 workOrder.put(fe, u);
236             } else {
237                 // Then distribute the work
238                 workOrder.put(fe, e);
239             }
240             logsync.trace("WorkOrder requested");
241             // Now create an Handle to monitor the execution of the operation
242             return ret;
243         }
244
245         logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
246         return null;
247     }
248
249     /**
250      * Checks if the FlowEntry targets are valid for this container
251      *
252      * @param flowEntry
253      *            The flow entry to test
254      * @return a Status object representing the result of the validation
255      */
256     private Status validateEntry(FlowEntry flowEntry) {
257         // Node presence check
258         Node node = flowEntry.getNode();
259         if (!switchManager.getNodes().contains(node)) {
260             return new Status(StatusCode.BADREQUEST, String.format("Node %s is not present in this container", node));
261         }
262
263         // Ports and actions validation check
264         Flow flow = flowEntry.getFlow();
265         Match match = flow.getMatch();
266         if (match.isPresent(MatchType.IN_PORT)) {
267             NodeConnector inputPort = (NodeConnector)match.getField(MatchType.IN_PORT).getValue();
268             if (!switchManager.getNodeConnectors(node).contains(inputPort)) {
269                 String msg = String.format("Ingress port %s is not present on this container", inputPort);
270                 return new Status(StatusCode.BADREQUEST, msg);
271             }
272         }
273         for (Action action : flow.getActions()) {
274             if (action instanceof Flood && !GlobalConstants.DEFAULT.toString().equals(getContainerName())) {
275                 return new Status(StatusCode.BADREQUEST, String.format("Flood is only allowed in default container"));
276             }
277             if (action instanceof FloodAll && !GlobalConstants.DEFAULT.toString().equals(getContainerName())) {
278                 return new Status(StatusCode.BADREQUEST, String.format("FloodAll is only allowed in default container"));
279             }
280             if (action instanceof Output) {
281                 Output out = (Output)action;
282                 NodeConnector outputPort = out.getPort();
283                 if (!switchManager.getNodeConnectors(node).contains(outputPort)) {
284                     String msg = String.format("Output port %s is not present on this container", outputPort);
285                     return new Status(StatusCode.BADREQUEST, msg);
286                 }
287             }
288             if (action instanceof Enqueue) {
289                 Enqueue out = (Enqueue)action;
290                 NodeConnector outputPort = out.getPort();
291                 if (!switchManager.getNodeConnectors(node).contains(outputPort)) {
292                     String msg = String.format("Enqueue port %s is not present on this container", outputPort);
293                     return new Status(StatusCode.BADREQUEST, msg);
294                 }
295             }
296         }
297         return new Status(StatusCode.SUCCESS);
298     }
299
300     /**
301      * Adds a flow entry onto the network node It runs various validity checks
302      * and derive the final container flows merged entries that will be
303      * attempted to be installed
304      *
305      * @param flowEntry
306      *            the original flow entry application requested to add
307      * @param async
308      *            the flag indicating if this is a asynchronous request
309      * @return the status of this request. In case of asynchronous call, it will
310      *         contain the unique id assigned to this request
311      */
312     private Status addEntry(FlowEntry flowEntry, boolean async) {
313
314         // Sanity Check
315         if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
316             String logMsg = INVALID_FLOW_ENTRY + ": {}";
317             log.warn(logMsg, flowEntry);
318             return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
319         }
320
321         // Operational check: input, output and queue ports presence check and
322         // action validation for this container
323         Status status = validateEntry(flowEntry);
324         if (!status.isSuccess()) {
325             String msg = String.format("%s: %s", INVALID_FLOW_ENTRY, status.getDescription());
326             log.warn("{}: {}", msg, flowEntry);
327             return new Status(StatusCode.NOTACCEPTABLE, msg);
328         }
329
330         /*
331          * Redundant Check: Check if the request is a redundant one from the
332          * same application the flowEntry is equal to an existing one. Given we
333          * do not have an application signature in the requested FlowEntry yet,
334          * we are here detecting the above condition by comparing the flow
335          * names, if set. If they are equal to the installed flow, most likely
336          * this is a redundant installation request from the same application
337          * and we can silently return success
338          *
339          * TODO: in future a sort of application reference list mechanism will
340          * be added to the FlowEntry so that exact flow can be used by different
341          * applications.
342          */
343         FlowEntry present = this.originalSwView.get(flowEntry);
344         if (present != null) {
345             boolean sameFlow = present.getFlow().equals(flowEntry.getFlow());
346             boolean sameApp = present.getFlowName() != null && present.getFlowName().equals(flowEntry.getFlowName());
347             if (sameFlow && sameApp) {
348                 log.trace("Skipping redundant request for flow {} on node {}", flowEntry.getFlowName(),
349                         flowEntry.getNode());
350                 return new Status(StatusCode.SUCCESS, "Entry is already present");
351             }
352         }
353
354         /*
355          * Derive the container flow merged entries to install In presence of N
356          * container flows, we may end up with N different entries to install...
357          */
358         List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
359
360         // Container Flow conflict Check
361         if (toInstallList.isEmpty()) {
362             String msg = "Flow Entry conflicts with all Container Flows";
363             String logMsg = msg + ": {}";
364             log.warn(logMsg, flowEntry);
365             return new Status(StatusCode.CONFLICT, msg);
366         }
367
368         // Derive the list of entries good to be installed
369         List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
370         for (FlowEntryInstall entry : toInstallList) {
371             // Conflict Check: Verify new entry would not overwrite existing
372             // ones
373             if (this.installedSwView.containsKey(entry)) {
374                 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
375                 log.trace("Aborting to install {}", entry);
376                 continue;
377             }
378             toInstallSafe.add(entry);
379         }
380
381         // Declare failure if all the container flow merged entries clash with
382         // existing entries
383         if (toInstallSafe.size() == 0) {
384             String msg = "A flow with same match and priority exists on the target node";
385             String logMsg = msg + ": {}";
386             log.warn(logMsg, flowEntry);
387             return new Status(StatusCode.CONFLICT, msg);
388         }
389
390         // Try to install an entry at the time
391         Status error = new Status(null, null);
392         Status succeded = null;
393         boolean oneSucceded = false;
394         for (FlowEntryInstall installEntry : toInstallSafe) {
395
396             // Install and update database
397             Status ret = addEntryInternal(installEntry, async);
398
399             if (ret.isSuccess()) {
400                 oneSucceded = true;
401                 /*
402                  * The first successful status response will be returned For the
403                  * asynchronous call, we can discard the container flow
404                  * complication for now and assume we will always deal with one
405                  * flow only per request
406                  */
407                 succeded = ret;
408             } else {
409                 error = ret;
410                 log.trace("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
411             }
412         }
413
414         return (oneSucceded) ? succeded : error;
415     }
416
417     /**
418      * Given a flow entry and the list of container flows, it returns the list
419      * of container flow merged flow entries good to be installed on this
420      * container. If the list of container flows is null or empty, the install
421      * entry list will contain only one entry, the original flow entry. If the
422      * flow entry is congruent with all the N container flows, then the output
423      * install entry list will contain N entries. If the output list is empty,
424      * it means the passed flow entry conflicts with all the container flows.
425      *
426      * @param cFlowList
427      *            The list of container flows
428      * @return the list of container flow merged entries good to be installed on
429      *         this container
430      */
431     private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
432         List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
433
434         if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
435             // No container flows => entry good to be installed unchanged
436             toInstallList.add(new FlowEntryInstall(request.clone(), null));
437         } else {
438             // Create the list of entries to be installed. If the flow entry is
439             // not congruent with any container flow, no install entries will be
440             // created
441             for (ContainerFlow cFlow : container.getContainerFlows()) {
442                 if (cFlow.allowsFlow(request.getFlow())) {
443                     toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
444                 }
445             }
446         }
447         return toInstallList;
448     }
449
450     /**
451      * Modify a flow entry with a new one It runs various validity check and
452      * derive the final container flows merged flow entries to work with
453      *
454      * @param currentFlowEntry
455      * @param newFlowEntry
456      * @param async
457      *            the flag indicating if this is a asynchronous request
458      * @return the status of this request. In case of asynchronous call, it will
459      *         contain the unique id assigned to this request
460      */
461     private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
462         Status retExt;
463
464         // Sanity checks
465         if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
466                 || newFlowEntry.getNode() == null || newFlowEntry.getFlow() == null) {
467             String msg = "Modify: " + INVALID_FLOW_ENTRY;
468             String logMsg = msg + ": {} or {}";
469             log.warn(logMsg, currentFlowEntry, newFlowEntry);
470             return new Status(StatusCode.NOTACCEPTABLE, msg);
471         }
472         if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
473                 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
474             String msg = "Modify: Incompatible Flow Entries";
475             String logMsg = msg + ": {} and {}";
476             log.warn(logMsg, currentFlowEntry, newFlowEntry);
477             return new Status(StatusCode.NOTACCEPTABLE, msg);
478         }
479
480         // Equality Check
481         if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
482             String msg = "Modify skipped as flows are the same";
483             String logMsg = msg + ": {} and {}";
484             log.debug(logMsg, currentFlowEntry, newFlowEntry);
485             return new Status(StatusCode.SUCCESS, msg);
486         }
487
488         // Operational check: input, output and queue ports presence check and
489         // action validation for this container
490         Status status = validateEntry(newFlowEntry);
491         if (!status.isSuccess()) {
492             String msg = String.format("Modify: %s: %s", INVALID_FLOW_ENTRY, status.getDescription());
493             log.warn("{}: {}", msg, newFlowEntry);
494             return new Status(StatusCode.NOTACCEPTABLE, msg);
495         }
496
497         /*
498          * Conflict Check: Verify the new entry would not conflict with an
499          * existing one. This is a loose check on the previous original flow
500          * entry requests. No check on the container flow merged flow entries
501          * (if any) yet
502          */
503         FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
504         if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
505             String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
506             String logMsg = msg + ": {}";
507             log.warn(logMsg, currentFlowEntry);
508             return new Status(StatusCode.CONFLICT, msg);
509         }
510
511         // Derive the installed and toInstall entries
512         List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
513                 container.getContainerFlows());
514         List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
515
516         if (toInstallList.isEmpty()) {
517             String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
518             String logMsg = msg + ": {}";
519             log.warn(logMsg, newFlowEntry);
520             log.warn(msg);
521             return new Status(StatusCode.CONFLICT, msg);
522         }
523
524         /*
525          * If the two list sizes differ, it means the new flow entry does not
526          * satisfy the same number of container flows the current entry does.
527          * This is only possible when the new entry and current entry have
528          * different match. In this scenario the modification would ultimately
529          * be handled as a remove and add operations in the protocol plugin.
530          *
531          * Also, if any of the new flow entries would clash with an existing
532          * one, we cannot proceed with the modify operation, because it would
533          * fail for some entries and leave stale entries on the network node.
534          * Modify path can be taken only if it can be performed completely, for
535          * all entries.
536          *
537          * So, for the above two cases, to simplify, let's decouple the modify
538          * in: 1) remove current entries 2) install new entries
539          */
540         Status succeeded = null;
541         boolean decouple = false;
542         if (installedList.size() != toInstallList.size()) {
543             log.trace("Modify: New flow entry does not satisfy the same "
544                     + "number of container flows as the original entry does");
545             decouple = true;
546         }
547         List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
548         for (FlowEntryInstall installEntry : toInstallList) {
549             /*
550              * Conflict Check: Verify the new entry would not overwrite another
551              * existing one
552              */
553             FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
554             if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
555                 log.trace("Modify: new container flow merged flow entry clashes with existing flow");
556                 decouple = true;
557             } else {
558                 toInstallSafe.add(installEntry);
559             }
560         }
561
562         if (decouple) {
563             // Remove current entries
564             for (FlowEntryInstall currEntry : installedList) {
565                 this.removeEntryInternal(currEntry, async);
566             }
567             // Install new entries
568             for (FlowEntryInstall newEntry : toInstallSafe) {
569                 succeeded = this.addEntryInternal(newEntry, async);
570             }
571         } else {
572             /*
573              * The two list have the same size and the entries to install do not
574              * clash with any existing flow on the network node. We assume here
575              * (and might be wrong) that the same container flows that were
576              * satisfied by the current entries are the same that are satisfied
577              * by the new entries. Let's take the risk for now.
578              *
579              * Note: modification has to be complete. If any entry modification
580              * fails, we need to stop, restore the already modified entries, and
581              * declare failure.
582              */
583             Status retModify = null;
584             int i = 0;
585             int size = toInstallList.size();
586             while (i < size) {
587                 // Modify and update database
588                 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
589                 if (retModify.isSuccess()) {
590                     i++;
591                 } else {
592                     break;
593                 }
594             }
595             // Check if uncompleted modify
596             if (i < size) {
597                 log.warn("Unable to perform a complete modify for all  the container flows merged entries");
598                 // Restore original entries
599                 int j = 0;
600                 while (j < i) {
601                     log.info("Attempting to restore initial entries");
602                     retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
603                     if (retExt.isSuccess()) {
604                         j++;
605                     } else {
606                         break;
607                     }
608                 }
609                 // Fatal error, recovery failed
610                 if (j < i) {
611                     String msg = "Flow recovery failed ! Unrecoverable Error";
612                     log.error(msg);
613                     return new Status(StatusCode.INTERNALERROR, msg);
614                 }
615             }
616             succeeded = retModify;
617         }
618         /*
619          * The first successful status response will be returned. For the
620          * asynchronous call, we can discard the container flow complication for
621          * now and assume we will always deal with one flow only per request
622          */
623         return succeeded;
624     }
625
626     /**
627      * This is the function that modifies the final container flows merged
628      * entries on the network node and update the database. It expects that all
629      * the validity checks are passed.
630      * This function is supposed to be called only on the controller on which
631      * the IFRM call is executed.
632      *
633      * @param currentEntries
634      * @param newEntries
635      * @param async
636      *            the flag indicating if this is a asynchronous request
637      * @return the status of this request. In case of asynchronous call, it will
638      *         contain the unique id assigned to this request
639      */
640     private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
641         Status status = new Status(StatusCode.UNDEFINED);
642         FlowEntryDistributionOrderFutureTask futureStatus =
643                 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
644         if (futureStatus != null) {
645             try {
646                 status = futureStatus.get();
647                 if (status.getCode()
648                         .equals(StatusCode.TIMEOUT)) {
649                     // A timeout happened, lets cleanup the workMonitor
650                     workMonitor.remove(futureStatus.getOrder());
651                 }
652             } catch (InterruptedException e) {
653                 log.error("", e);
654             } catch (ExecutionException e) {
655                 log.error("", e);
656             }
657         } else {
658             // Modify the flow on the network node
659             status = modifyEntryInHw(currentEntries, newEntries, async);
660         }
661
662         if (!status.isSuccess()) {
663             log.trace("{} SDN Plugin failed to program the flow: {}. The failure is: {}",
664                     (futureStatus != null) ? "Remote" : "Local", newEntries.getInstall(), status.getDescription());
665             return status;
666         }
667
668         log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
669
670         // Update DB
671         newEntries.setRequestId(status.getRequestId());
672         updateSwViews(currentEntries, false);
673         updateSwViews(newEntries, true);
674
675         return status;
676     }
677
678     private Status modifyEntryInHw(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
679         return async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall().getFlow(),
680                 newEntries.getInstall().getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries
681                 .getInstall().getFlow(), newEntries.getInstall().getFlow());
682     }
683
684     /**
685      * Remove a flow entry. If the entry is not present in the software view
686      * (entry or node not present), it return successfully
687      *
688      * @param flowEntry
689      *            the flow entry to remove
690      * @param async
691      *            the flag indicating if this is a asynchronous request
692      * @return the status of this request. In case of asynchronous call, it will
693      *         contain the unique id assigned to this request
694      */
695     private Status removeEntry(FlowEntry flowEntry, boolean async) {
696         Status error = new Status(null, null);
697
698         // Sanity Check
699         if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
700             String logMsg = INVALID_FLOW_ENTRY + ": {}";
701             log.warn(logMsg, flowEntry);
702             return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
703         }
704
705         // Derive the container flows merged installed entries
706         List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
707
708         Status succeeded = null;
709         boolean atLeastOneRemoved = false;
710         for (FlowEntryInstall entry : installedList) {
711             if (!installedSwView.containsKey(entry)) {
712                 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
713                 log.debug(logMsg, flowEntry);
714                 if (installedList.size() == 1) {
715                     // If we had only one entry to remove, we are done
716                     return new Status(StatusCode.SUCCESS);
717                 } else {
718                     continue;
719                 }
720             }
721
722             // Remove and update DB
723             Status ret = removeEntryInternal(entry, async);
724
725             if (!ret.isSuccess()) {
726                 error = ret;
727                 log.trace("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
728                 if (installedList.size() == 1) {
729                     // If we had only one entry to remove, this is fatal failure
730                     return error;
731                 }
732             } else {
733                 succeeded = ret;
734                 atLeastOneRemoved = true;
735             }
736         }
737
738         /*
739          * No worries if full removal failed. Consistency checker will take care
740          * of removing the stale entries later, or adjusting the software
741          * database if not in sync with hardware
742          */
743         return (atLeastOneRemoved) ? succeeded : error;
744     }
745
746     /**
747      * This is the function that removes the final container flows merged entry
748      * from the network node and update the database. It expects that all the
749      * validity checks are passed
750      * This function is supposed to be called only on the controller on which
751      * the IFRM call is executed.
752      *
753      * @param entry
754      *            the flow entry to remove
755      * @param async
756      *            the flag indicating if this is a asynchronous request
757      * @return the status of this request. In case of asynchronous call, it will
758      *         contain the unique id assigned to this request
759      */
760     private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
761         Status status = new Status(StatusCode.UNDEFINED);
762         FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
763         if (futureStatus != null) {
764             try {
765                 status = futureStatus.get();
766                 if (status.getCode().equals(StatusCode.TIMEOUT)) {
767                     // A timeout happened, lets cleanup the workMonitor
768                     workMonitor.remove(futureStatus.getOrder());
769                 }
770             } catch (InterruptedException e) {
771                 log.error("", e);
772             } catch (ExecutionException e) {
773                 log.error("", e);
774             }
775         } else {
776             // Mark the entry to be deleted (for CC just in case we fail)
777             entry.toBeDeleted();
778
779             // Remove from node
780             status = removeEntryInHw(entry, async);
781         }
782
783         if (!status.isSuccess()) {
784             log.trace("{} SDN Plugin failed to remove the flow: {}. The failure is: {}",
785                     (futureStatus != null) ? "Remote" : "Local", entry.getInstall(), status.getDescription());
786             return status;
787         }
788
789         log.trace("Removed  {}", entry.getInstall());
790
791         // Update DB
792         updateSwViews(entry, false);
793
794         return status;
795     }
796
797     private Status removeEntryInHw(FlowEntryInstall entry, boolean async) {
798         return async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall().getFlow()) : programmer
799                 .removeFlow(entry.getNode(), entry.getInstall().getFlow());
800     }
801
802     /**
803      * This is the function that installs the final container flow merged entry
804      * on the network node and updates the database. It expects that all the
805      * validity and conflict checks are passed. That means it does not check
806      * whether this flow would conflict or overwrite an existing one.
807      * This function is supposed to be called only on the controller on which
808      * the IFRM call is executed.
809      *
810      * @param entry
811      *            the flow entry to install
812      * @param async
813      *            the flag indicating if this is a asynchronous request
814      * @return the status of this request. In case of asynchronous call, it will
815      *         contain the unique id assigned to this request
816      */
817     private Status addEntryInternal(FlowEntryInstall entry, boolean async) {
818         Status status = new Status(StatusCode.UNDEFINED);
819         FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
820         if (futureStatus != null) {
821             try {
822                 status = futureStatus.get();
823                 if (status.getCode().equals(StatusCode.TIMEOUT)) {
824                     // A timeout happened, lets cleanup the workMonitor
825                     workMonitor.remove(futureStatus.getOrder());
826                 }
827             } catch (InterruptedException e) {
828                 log.error("", e);
829             } catch (ExecutionException e) {
830                 log.error("", e);
831             }
832         } else {
833             status = addEntryInHw(entry, async);
834         }
835
836         if (!status.isSuccess()) {
837             log.trace("{} SDN Plugin failed to program the flow: {}. The failure is: {}",
838                     (futureStatus != null) ? "Remote" : "Local", entry.getInstall(), status.getDescription());
839             return status;
840         }
841
842         log.trace("Added    {}", entry.getInstall());
843
844         // Update DB
845         entry.setRequestId(status.getRequestId());
846         updateSwViews(entry, true);
847
848         return status;
849     }
850
851     private Status addEntryInHw(FlowEntryInstall entry, boolean async) {
852         // Install the flow on the network node
853         return async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall().getFlow()) : programmer.addFlow(
854                 entry.getNode(), entry.getInstall().getFlow());
855     }
856
857     /**
858      * Returns true if the flow conflicts with all the container's flows. This
859      * means that if the function returns true, the passed flow entry is
860      * congruent with at least one container flow, hence it is good to be
861      * installed on this container.
862      *
863      * @param flowEntry
864      * @return true if flow conflicts with all the container flows, false
865      *         otherwise
866      */
867     private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
868         List<ContainerFlow> cFlowList = container.getContainerFlows();
869
870         // Validity check and avoid unnecessary computation
871         // Also takes care of default container where no container flows are
872         // present
873         if (cFlowList == null || cFlowList.isEmpty()) {
874             return false;
875         }
876
877         for (ContainerFlow cFlow : cFlowList) {
878             if (cFlow.allowsFlow(flowEntry.getFlow())) {
879                 // Entry is allowed by at least one container flow: good to go
880                 return false;
881             }
882         }
883         return true;
884     }
885
886     private ConcurrentMap.Entry<Integer, FlowConfig> getStaticFlowEntry(String name, Node node) {
887         for (ConcurrentMap.Entry<Integer, FlowConfig> flowEntry : staticFlows.entrySet()) {
888             FlowConfig flowConfig = flowEntry.getValue();
889             if (flowConfig.isByNameAndNodeIdEqual(name, node)) {
890                 return flowEntry;
891             }
892         }
893         return null;
894     }
895
896     private void updateIndexDatabase(FlowEntryInstall entry, boolean add) {
897         // Update node indexed flow database
898         updateNodeFlowsDB(entry, add);
899
900         // Update group indexed flow database
901         updateGroupFlowsDB(entry, add);
902     }
903
904     /*
905      * Update the node mapped flows database
906      */
907     private void updateSwViews(FlowEntryInstall flowEntries, boolean add) {
908         if (add) {
909             originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
910             installedSwView.put(flowEntries, flowEntries);
911         } else {
912             originalSwView.remove(flowEntries.getOriginal());
913             installedSwView.remove(flowEntries);
914         }
915     }
916
917     /*
918      * Update the node mapped flows database
919      */
920     private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
921         Node node = flowEntries.getNode();
922
923         List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
924         if (nodeIndeces == null) {
925             if (!add) {
926                 return;
927             } else {
928                 nodeIndeces = new ArrayList<FlowEntryInstall>();
929             }
930         }
931
932         if (add) {
933             // there may be an already existing entry.
934             // remove it before adding the new one.
935             // This is necessary since we have observed that in some cases
936             // Infinispan does aggregation for operations (eg:- remove and then put a different value)
937             // related to the same key within the same transaction.
938             // Need this defensive code as the new FlowEntryInstall may be different
939             // than the old one even though the equals method returns true. This is because
940             // the equals method does not take into account the action list.
941             if(nodeIndeces.contains(flowEntries)) {
942                 nodeIndeces.remove(flowEntries);
943             }
944             nodeIndeces.add(flowEntries);
945         } else {
946             nodeIndeces.remove(flowEntries);
947         }
948
949         // Update cache across cluster
950         if (nodeIndeces.isEmpty()) {
951             this.nodeFlows.remove(node);
952         } else {
953             this.nodeFlows.put(node, nodeIndeces);
954         }
955     }
956
957     /*
958      * Update the group name mapped flows database
959      */
960     private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
961         String groupName = flowEntries.getGroupName();
962
963         // Flow may not be part of a group
964         if (groupName == null) {
965             return;
966         }
967
968         List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
969         if (indices == null) {
970             if (!add) {
971                 return;
972             } else {
973                 indices = new ArrayList<FlowEntryInstall>();
974             }
975         }
976
977         if (add) {
978             // same comments in the similar code section in
979             // updateNodeFlowsDB method apply here too
980             if(indices.contains(flowEntries)) {
981                 indices.remove(flowEntries);
982             }
983             indices.add(flowEntries);
984         } else {
985             indices.remove(flowEntries);
986         }
987
988         // Update cache across cluster
989         if (indices.isEmpty()) {
990             this.groupFlows.remove(groupName);
991         } else {
992             this.groupFlows.put(groupName, indices);
993         }
994     }
995
996     /**
997      * Remove a flow entry that has been added previously First checks if the
998      * entry is effectively present in the local database
999      */
1000     @SuppressWarnings("unused")
1001     private Status removeEntry(Node node, String flowName) {
1002         FlowEntryInstall target = null;
1003
1004         // Find in database
1005         for (FlowEntryInstall entry : installedSwView.values()) {
1006             if (entry.equalsByNodeAndName(node, flowName)) {
1007                 target = entry;
1008                 break;
1009             }
1010         }
1011
1012         // If it is not there, stop any further processing
1013         if (target == null) {
1014             return new Status(StatusCode.SUCCESS, "Entry is not present");
1015         }
1016
1017         // Remove from node
1018         Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
1019
1020         // Update DB
1021         if (status.isSuccess()) {
1022             updateSwViews(target, false);
1023         } else {
1024             // log the error
1025             log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
1026                     status.getDescription());
1027         }
1028
1029         return status;
1030     }
1031
1032     @Override
1033     public Status installFlowEntry(FlowEntry flowEntry) {
1034         Status status;
1035         if (isContainerModeAllowed(flowEntry)) {
1036             status = addEntry(flowEntry, false);
1037         } else {
1038             String msg = "Controller in container mode: Install Refused";
1039             String logMsg = msg + ": {}";
1040             status = new Status(StatusCode.NOTACCEPTABLE, msg);
1041             log.warn(logMsg, flowEntry);
1042         }
1043         return status;
1044     }
1045
1046     @Override
1047     public Status installFlowEntryAsync(FlowEntry flowEntry) {
1048         Status status;
1049         if (isContainerModeAllowed(flowEntry)) {
1050             status = addEntry(flowEntry, true);
1051         } else {
1052             String msg = "Controller in container mode: Install Refused";
1053             status = new Status(StatusCode.NOTACCEPTABLE, msg);
1054             log.warn(msg);
1055         }
1056         return status;
1057     }
1058
1059     @Override
1060     public Status uninstallFlowEntry(FlowEntry flowEntry) {
1061         Status status;
1062         if (isContainerModeAllowed(flowEntry)) {
1063             status = removeEntry(flowEntry, false);
1064         } else {
1065             String msg = "Controller in container mode: Uninstall Refused";
1066             String logMsg = msg + ": {}";
1067             status = new Status(StatusCode.NOTACCEPTABLE, msg);
1068             log.warn(logMsg, flowEntry);
1069         }
1070         return status;
1071     }
1072
1073     @Override
1074     public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
1075         Status status;
1076         if (isContainerModeAllowed(flowEntry)) {
1077             status = removeEntry(flowEntry, true);
1078         } else {
1079             String msg = "Controller in container mode: Uninstall Refused";
1080             status = new Status(StatusCode.NOTACCEPTABLE, msg);
1081             log.warn(msg);
1082         }
1083         return status;
1084     }
1085
1086     @Override
1087     public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1088         Status status = null;
1089         if (isContainerModeAllowed(currentFlowEntry)) {
1090             status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1091         } else {
1092             String msg = "Controller in container mode: Modify Refused";
1093             String logMsg = msg + ": {}";
1094             status = new Status(StatusCode.NOTACCEPTABLE, msg);
1095             log.warn(logMsg, newFlowEntry);
1096         }
1097         return status;
1098     }
1099
1100     @Override
1101     public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1102         Status status = null;
1103         if (isContainerModeAllowed(currentFlowEntry)) {
1104             status = modifyEntry(currentFlowEntry, newFlowEntry, true);
1105         } else {
1106             String msg = "Controller in container mode: Modify Refused";
1107             status = new Status(StatusCode.NOTACCEPTABLE, msg);
1108             log.warn(msg);
1109         }
1110         return status;
1111     }
1112
1113     /**
1114      * Returns whether the specified flow entry is allowed to be
1115      * installed/removed/modified based on the current container mode status.
1116      * This call always returns true in the container instance of forwarding
1117      * rules manager. It is meant for the global instance only (default
1118      * container) of forwarding rules manager. Idea is that for assuring
1119      * container isolation of traffic, flow installation in default container is
1120      * blocked when in container mode (containers are present). The only flows
1121      * that are allowed in container mode in the default container are the
1122      * proactive flows, the ones automatically installed on the network node
1123      * which forwarding mode has been configured to "proactive". These flows are
1124      * needed by controller to discover the nodes topology and to discover the
1125      * attached hosts for some SDN switches.
1126      *
1127      * @param flowEntry
1128      *            The flow entry to be installed/removed/modified
1129      * @return true if not in container mode or if flowEntry is internally
1130      *         generated
1131      */
1132     private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1133         return (!inContainerMode) ? true : flowEntry.isInternal();
1134     }
1135
1136     @Override
1137     public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1138         /*
1139          * Run a check on the original entries to decide whether to go with a
1140          * add or modify method. A loose check means only check against the
1141          * original flow entry requests and not against the installed flow
1142          * entries which are the result of the original entry merged with the
1143          * container flow(s) (if any). The modifyFlowEntry method in presence of
1144          * conflicts with the Container flows (if any) would revert back to a
1145          * delete + add pattern
1146          */
1147         FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1148
1149         if (currentFlowEntry != null) {
1150             return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1151         } else {
1152             return installFlowEntry(newFlowEntry);
1153         }
1154     }
1155
1156     @Override
1157     public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1158         /*
1159          * Run a check on the original entries to decide whether to go with a
1160          * add or modify method. A loose check means only check against the
1161          * original flow entry requests and not against the installed flow
1162          * entries which are the result of the original entry merged with the
1163          * container flow(s) (if any). The modifyFlowEntry method in presence of
1164          * conflicts with the Container flows (if any) would revert back to a
1165          * delete + add pattern
1166          */
1167         FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1168
1169         if (currentFlowEntry != null) {
1170             return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1171         } else {
1172             return installFlowEntryAsync(newFlowEntry);
1173         }
1174     }
1175
1176     @Override
1177     public Status uninstallFlowEntryGroup(String groupName) {
1178         if (groupName == null || groupName.isEmpty()) {
1179             return new Status(StatusCode.BADREQUEST, "Invalid group name");
1180         }
1181         if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1182             return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1183         }
1184         if (inContainerMode) {
1185             String msg = "Controller in container mode: Group Uninstall Refused";
1186             String logMsg = msg + ": {}";
1187             log.warn(logMsg, groupName);
1188             return new Status(StatusCode.NOTACCEPTABLE, msg);
1189         }
1190         int toBeRemoved = 0;
1191         String error = "";
1192         if (groupFlows.containsKey(groupName)) {
1193             List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1194             toBeRemoved = list.size();
1195             for (FlowEntryInstall entry : list) {
1196                 // since this is the entry that was stored in groupFlows
1197                 // it is already validated and merged
1198                 // so can call removeEntryInternal directly
1199                 Status status = this.removeEntryInternal(entry, false);
1200                 if (status.isSuccess()) {
1201                     toBeRemoved -= 1;
1202                 } else {
1203                     error = status.getDescription();
1204                 }
1205             }
1206         }
1207         return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1208                 "Not all the flows were removed: " + error);
1209     }
1210
1211     @Override
1212     public Status uninstallFlowEntryGroupAsync(String groupName) {
1213         if (groupName == null || groupName.isEmpty()) {
1214             return new Status(StatusCode.BADREQUEST, "Invalid group name");
1215         }
1216         if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1217             return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1218         }
1219         if (inContainerMode) {
1220             String msg = "Controller in container mode: Group Uninstall Refused";
1221             String logMsg = msg + ": {}";
1222             log.warn(logMsg, groupName);
1223             return new Status(StatusCode.NOTACCEPTABLE, msg);
1224         }
1225         if (groupFlows.containsKey(groupName)) {
1226             List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1227             for (FlowEntryInstall entry : list) {
1228                 this.removeEntry(entry.getOriginal(), true);
1229             }
1230         }
1231         return new Status(StatusCode.SUCCESS);
1232     }
1233
1234     @Override
1235     public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1236         return entryConflictsWithContainerFlows(flowEntry);
1237     }
1238
1239     /**
1240      * Updates all installed flows because the container flow got updated This
1241      * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1242      * Reinstall of all flows This is needed because a new container flows
1243      * merged flow may conflict with an existing old container flows merged flow
1244      * on the network node
1245      */
1246     protected void updateFlowsContainerFlow() {
1247         Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1248         // First remove all installed entries
1249         for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1250             FlowEntryInstall current = entry.getValue();
1251             // Store the original entry
1252             toReInstall.add(current.getOriginal());
1253             // Remove the old couples. No validity checks to be run, use the
1254             // internal remove
1255             this.removeEntryInternal(current, false);
1256         }
1257         // Then reinstall the original entries
1258         for (FlowEntry entry : toReInstall) {
1259             // Reinstall the original flow entries, via the regular path: new
1260             // cFlow merge + validations
1261             this.installFlowEntry(entry);
1262         }
1263     }
1264
1265     private void nonClusterObjectCreate() {
1266         originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1267         installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1268         TSPolicies = new ConcurrentHashMap<String, Object>();
1269         staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1270         portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1271         portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1272         staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1273         inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1274     }
1275
1276     @Override
1277     public void setTSPolicyData(String policyname, Object o, boolean add) {
1278
1279         if (add) {
1280             /* Check if this policy already exists */
1281             if (!(TSPolicies.containsKey(policyname))) {
1282                 TSPolicies.put(policyname, o);
1283             }
1284         } else {
1285             TSPolicies.remove(policyname);
1286         }
1287         if (frmAware != null) {
1288             synchronized (frmAware) {
1289                 for (IForwardingRulesManagerAware frma : frmAware) {
1290                     try {
1291                         frma.policyUpdate(policyname, add);
1292                     } catch (Exception e) {
1293                         log.warn("Exception on callback", e);
1294                     }
1295                 }
1296             }
1297         }
1298     }
1299
1300     @Override
1301     public Map<String, Object> getTSPolicyData() {
1302         return TSPolicies;
1303     }
1304
1305     @Override
1306     public Object getTSPolicyData(String policyName) {
1307         if (TSPolicies.containsKey(policyName)) {
1308             return TSPolicies.get(policyName);
1309         } else {
1310             return null;
1311         }
1312     }
1313
1314     @Override
1315     public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1316         List<FlowEntry> list = new ArrayList<FlowEntry>();
1317         if (policyName != null && !policyName.trim().isEmpty()) {
1318             for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1319                 if (policyName.equals(entry.getKey().getGroupName())) {
1320                     list.add(entry.getValue().clone());
1321                 }
1322             }
1323         }
1324         return list;
1325     }
1326
1327     @Override
1328     public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1329         List<FlowEntry> list = new ArrayList<FlowEntry>();
1330         if (policyName != null && !policyName.trim().isEmpty()) {
1331             for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1332                 if (policyName.equals(entry.getKey().getGroupName())) {
1333                     list.add(entry.getValue().getInstall().clone());
1334                 }
1335             }
1336         }
1337         return list;
1338     }
1339
1340     @Override
1341     public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1342
1343         for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1344             if (flow.getFlowName().equals(flowName)) {
1345                 FlowEntry currentFlowEntry = flow.getOriginal();
1346                 FlowEntry newFlowEntry = currentFlowEntry.clone();
1347                 for (NodeConnector dstPort : portList) {
1348                     newFlowEntry.getFlow().addAction(new Output(dstPort));
1349                 }
1350                 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1351                 if (error.isSuccess()) {
1352                     log.trace("Ports {} added to FlowEntry {}", portList, flowName);
1353                 } else {
1354                     log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1355                             currentFlowEntry.toString(), error.getDescription());
1356                 }
1357                 return;
1358             }
1359         }
1360         log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1361     }
1362
1363     @Override
1364     public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1365         for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1366             FlowEntryInstall flow = this.installedSwView.get(index);
1367             if (flow.getFlowName().equals(flowName)) {
1368                 FlowEntry currentFlowEntry = flow.getOriginal();
1369                 FlowEntry newFlowEntry = currentFlowEntry.clone();
1370                 for (NodeConnector dstPort : portList) {
1371                     Action action = new Output(dstPort);
1372                     newFlowEntry.getFlow().removeAction(action);
1373                 }
1374                 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1375                 if (status.isSuccess()) {
1376                     log.trace("Ports {} removed from FlowEntry {}", portList, flowName);
1377                 } else {
1378                     log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1379                             currentFlowEntry.toString(), status.getDescription());
1380                 }
1381                 return;
1382             }
1383         }
1384         log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1385     }
1386
1387     /*
1388      * This function assumes the target flow has only one output port
1389      */
1390     @Override
1391     public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1392         FlowEntry currentFlowEntry = null;
1393         FlowEntry newFlowEntry = null;
1394
1395         // Find the flow
1396         for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1397             FlowEntryInstall flow = this.installedSwView.get(index);
1398             if (flow.getFlowName().equals(flowName)) {
1399                 currentFlowEntry = flow.getOriginal();
1400                 break;
1401             }
1402         }
1403         if (currentFlowEntry == null) {
1404             log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1405             return;
1406         }
1407
1408         // Create a flow copy with the new output port
1409         newFlowEntry = currentFlowEntry.clone();
1410         Action target = null;
1411         for (Action action : newFlowEntry.getFlow().getActions()) {
1412             if (action.getType() == ActionType.OUTPUT) {
1413                 target = action;
1414                 break;
1415             }
1416         }
1417         newFlowEntry.getFlow().removeAction(target);
1418         newFlowEntry.getFlow().addAction(new Output(outPort));
1419
1420         // Modify on network node
1421         Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1422
1423         if (status.isSuccess()) {
1424             log.trace("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1425         } else {
1426             log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1427                     status.getDescription());
1428         }
1429         return;
1430     }
1431
1432     @Override
1433     public NodeConnector getOutputPort(Node node, String flowName) {
1434         for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1435             FlowEntryInstall flow = this.installedSwView.get(index);
1436             if (flow.getFlowName().equals(flowName)) {
1437                 for (Action action : flow.getOriginal().getFlow().getActions()) {
1438                     if (action.getType() == ActionType.OUTPUT) {
1439                         return ((Output) action).getPort();
1440                     }
1441                 }
1442             }
1443         }
1444         return null;
1445     }
1446
1447     private void cacheStartup() {
1448         allocateCaches();
1449         retrieveCaches();
1450     }
1451
1452     private void allocateCaches() {
1453         if (this.clusterContainerService == null) {
1454             log.warn("Un-initialized clusterContainerService, can't create cache");
1455             return;
1456         }
1457
1458         log.debug("Allocating caches for Container {}", container.getName());
1459
1460         try {
1461             clusterContainerService.createCache(ORIGINAL_SW_VIEW_CACHE,
1462                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1463
1464             clusterContainerService.createCache(INSTALLED_SW_VIEW_CACHE,
1465                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1466
1467             clusterContainerService.createCache("frm.inactiveFlows",
1468                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1469
1470             clusterContainerService.createCache("frm.staticFlows",
1471                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1472
1473             clusterContainerService.createCache("frm.staticFlowsOrdinal",
1474                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1475
1476             clusterContainerService.createCache("frm.portGroupConfigs",
1477                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1478
1479             clusterContainerService.createCache("frm.portGroupData",
1480                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1481
1482             clusterContainerService.createCache("frm.TSPolicies",
1483                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1484
1485             clusterContainerService.createCache(WORK_STATUS_CACHE,
1486                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1487
1488             clusterContainerService.createCache(WORK_ORDER_CACHE,
1489                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1490
1491         } catch (CacheConfigException cce) {
1492             log.error("CacheConfigException");
1493         } catch (CacheExistException cce) {
1494             log.error("CacheExistException");
1495         }
1496     }
1497
1498     @SuppressWarnings({ "unchecked" })
1499     private void retrieveCaches() {
1500         ConcurrentMap<?, ?> map;
1501
1502         if (this.clusterContainerService == null) {
1503             log.warn("un-initialized clusterContainerService, can't retrieve cache");
1504             nonClusterObjectCreate();
1505             return;
1506         }
1507
1508         log.debug("Retrieving Caches for Container {}", container.getName());
1509
1510         map = clusterContainerService.getCache(ORIGINAL_SW_VIEW_CACHE);
1511         if (map != null) {
1512             originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1513         } else {
1514             log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1515         }
1516
1517         map = clusterContainerService.getCache(INSTALLED_SW_VIEW_CACHE);
1518         if (map != null) {
1519             installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1520         } else {
1521             log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1522         }
1523
1524         map = clusterContainerService.getCache("frm.inactiveFlows");
1525         if (map != null) {
1526             inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1527         } else {
1528             log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1529         }
1530
1531         map = clusterContainerService.getCache("frm.staticFlows");
1532         if (map != null) {
1533             staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1534         } else {
1535             log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1536         }
1537
1538         map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1539         if (map != null) {
1540             staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1541         } else {
1542             log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1543         }
1544
1545         map = clusterContainerService.getCache("frm.portGroupConfigs");
1546         if (map != null) {
1547             portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1548         } else {
1549             log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1550         }
1551
1552         map = clusterContainerService.getCache("frm.portGroupData");
1553         if (map != null) {
1554             portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1555         } else {
1556             log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1557         }
1558
1559         map = clusterContainerService.getCache("frm.TSPolicies");
1560         if (map != null) {
1561             TSPolicies = (ConcurrentMap<String, Object>) map;
1562         } else {
1563             log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1564         }
1565
1566         map = clusterContainerService.getCache(WORK_ORDER_CACHE);
1567         if (map != null) {
1568             workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1569         } else {
1570             log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName());
1571         }
1572
1573         map = clusterContainerService.getCache(WORK_STATUS_CACHE);
1574         if (map != null) {
1575             workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1576         } else {
1577             log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName());
1578         }
1579     }
1580
1581     private boolean flowConfigExists(FlowConfig config) {
1582         // Flow name has to be unique on per node id basis
1583         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1584             if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1585                 return true;
1586             }
1587         }
1588         return false;
1589     }
1590
1591     @Override
1592     public Status addStaticFlow(FlowConfig config) {
1593         return addStaticFlow(config, false);
1594     }
1595
1596     private Status addStaticFlow(FlowConfig config, boolean async) {
1597         // Configuration object validation
1598         Status status = config.validate();
1599         if (!status.isSuccess()) {
1600             log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1601             String error = "Invalid Configuration (" + status.getDescription() + ")";
1602             config.setStatus(error);
1603             return new Status(StatusCode.BADREQUEST, error);
1604         }
1605         return addStaticFlowInternal(config, async, false);
1606     }
1607
1608
1609     @Override
1610     public Status addStaticFlowAsync(FlowConfig config) {
1611         return addStaticFlow(config, true);
1612     }
1613
1614     /**
1615      * Private method to add a static flow configuration which does not run any
1616      * validation on the passed FlowConfig object. If restore is set to true,
1617      * configuration is stored in configuration database regardless the
1618      * installation on the network node was successful. This is useful at boot
1619      * when static flows are present in startup configuration and are read
1620      * before the switches connects.
1621      *
1622      * @param config
1623      *            The static flow configuration
1624      * @param restore
1625      *            if true, the configuration is stored regardless the
1626      *            installation on the network node was successful
1627      * @return The status of this request
1628      */
1629     private Status addStaticFlowInternal(FlowConfig config, boolean async, boolean restore) {
1630         boolean multipleFlowPush = false;
1631         String error;
1632         Status status;
1633         config.setStatus(StatusCode.SUCCESS.toString());
1634
1635         // Presence check
1636         if (flowConfigExists(config)) {
1637             error = "Entry with this name on specified switch already exists";
1638             log.warn("Entry with this name on specified switch already exists: {}", config);
1639             config.setStatus(error);
1640             return new Status(StatusCode.CONFLICT, error);
1641         }
1642
1643         if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1644             for (String portGroupName : portGroupConfigs.keySet()) {
1645                 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1646                     multipleFlowPush = true;
1647                     break;
1648                 }
1649             }
1650             if (!multipleFlowPush) {
1651                 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1652                 error = "Invalid Configuration (Invalid PortGroup Name)";
1653                 config.setStatus(error);
1654                 return new Status(StatusCode.BADREQUEST, error);
1655             }
1656         }
1657
1658         /*
1659          * If requested program the entry in hardware first before updating the
1660          * StaticFlow DB
1661          */
1662         if (!multipleFlowPush) {
1663             // Program hw
1664             if (config.installInHw()) {
1665                 FlowEntry entry = config.getFlowEntry();
1666                 status = async ? this.installFlowEntryAsync(entry) : this.installFlowEntry(entry);
1667                 if (!status.isSuccess()) {
1668                     config.setStatus(status.getDescription());
1669                     if (!restore) {
1670                         return status;
1671                     }
1672                 }
1673             }
1674         }
1675
1676         /*
1677          * When the control reaches this point, either of the following
1678          * conditions is true 1. This is a single entry configuration (non
1679          * PortGroup) and the hardware installation is successful 2. This is a
1680          * multiple entry configuration (PortGroup) and hardware installation is
1681          * NOT done directly on this event. 3. The User prefers to retain the
1682          * configuration in Controller and skip hardware installation.
1683          *
1684          * Hence it is safe to update the StaticFlow DB at this point.
1685          *
1686          * Note : For the case of PortGrouping, it is essential to have this DB
1687          * populated before the PortGroupListeners can query for the DB
1688          * triggered using portGroupChanged event...
1689          */
1690         Integer ordinal = staticFlowsOrdinal.get(0);
1691         staticFlowsOrdinal.put(0, ++ordinal);
1692         staticFlows.put(ordinal, config);
1693
1694         if (multipleFlowPush) {
1695             PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1696             Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1697             if (existingData != null) {
1698                 portGroupChanged(pgconfig, existingData, true);
1699             }
1700         }
1701         return new Status(StatusCode.SUCCESS);
1702     }
1703
1704     private void addStaticFlowsToSwitch(Node node) {
1705         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1706             FlowConfig config = entry.getValue();
1707             if (config.isPortGroupEnabled()) {
1708                 continue;
1709             }
1710             if (config.getNode().equals(node)) {
1711                 if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) {
1712                     Status status = this.installFlowEntryAsync(config.getFlowEntry());
1713                     config.setStatus(status.getDescription());
1714                 }
1715             }
1716         }
1717         // Update cluster cache
1718         refreshClusterStaticFlowsStatus(node);
1719     }
1720
1721     private void updateStaticFlowConfigsOnNodeDown(Node node) {
1722         log.trace("Updating Static Flow configs on node down: {}", node);
1723
1724         List<Integer> toRemove = new ArrayList<Integer>();
1725         for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1726
1727             FlowConfig config = entry.getValue();
1728
1729             if (config.isPortGroupEnabled()) {
1730                 continue;
1731             }
1732
1733             if (config.installInHw() && config.getNode().equals(node)) {
1734                 if (config.isInternalFlow()) {
1735                     // Take note of this controller generated static flow
1736                     toRemove.add(entry.getKey());
1737                 } else {
1738                     config.setStatus(NODE_DOWN);
1739                 }
1740             }
1741         }
1742         // Remove controller generated static flows for this node
1743         for (Integer index : toRemove) {
1744             staticFlows.remove(index);
1745         }
1746         // Update cluster cache
1747         refreshClusterStaticFlowsStatus(node);
1748
1749     }
1750
1751     private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1752         log.trace("Updating Static Flow configs on container mode change: {}", update);
1753
1754         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1755             FlowConfig config = entry.getValue();
1756             if (config.isPortGroupEnabled()) {
1757                 continue;
1758             }
1759             if (config.installInHw() && !config.isInternalFlow()) {
1760                 switch (update) {
1761                 case ADDED:
1762                     config.setStatus("Removed from node because in container mode");
1763                     break;
1764                 case REMOVED:
1765                     config.setStatus(StatusCode.SUCCESS.toString());
1766                     break;
1767                 default:
1768                     break;
1769                 }
1770             }
1771         }
1772         // Update cluster cache
1773         refreshClusterStaticFlowsStatus(null);
1774     }
1775
1776     @Override
1777     public Status removeStaticFlow(FlowConfig config) {
1778         return removeStaticFlow(config, false);
1779     }
1780
1781     @Override
1782     public Status removeStaticFlowAsync(FlowConfig config) {
1783         return removeStaticFlow(config, true);
1784     }
1785
1786     private Status removeStaticFlow(FlowConfig config, boolean async) {
1787         /*
1788          * No config.isInternal() check as NB does not take this path and GUI
1789          * cannot issue a delete on an internal generated flow. We need this
1790          * path to be accessible when switch mode is changed from proactive to
1791          * reactive, so that we can remove the internal generated LLDP and ARP
1792          * punt flows
1793          */
1794
1795         // Look for the target configuration entry
1796         Integer key = 0;
1797         FlowConfig target = null;
1798         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1799             if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1800                 key = entry.getKey();
1801                 target = entry.getValue();
1802                 break;
1803             }
1804         }
1805         if (target == null) {
1806             return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1807         }
1808
1809         // Program the network node
1810         Status status = async ? this.uninstallFlowEntryAsync(config.getFlowEntry()) : this.uninstallFlowEntry(config
1811                 .getFlowEntry());
1812
1813         // Update configuration database if programming was successful
1814         if (status.isSuccess()) {
1815             staticFlows.remove(key);
1816         }
1817
1818         return status;
1819     }
1820
1821     @Override
1822     public Status removeStaticFlow(String name, Node node) {
1823        return removeStaticFlow(name, node, false);
1824     }
1825
1826     @Override
1827     public Status removeStaticFlowAsync(String name, Node node) {
1828         return removeStaticFlow(name, node, true);
1829     }
1830
1831     private Status removeStaticFlow(String name, Node node, boolean async) {
1832         // Look for the target configuration entry
1833         Integer key = 0;
1834         FlowConfig target = null;
1835         for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1836             if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1837                 key = mapEntry.getKey();
1838                 target = mapEntry.getValue();
1839                 break;
1840             }
1841         }
1842         if (target == null) {
1843             return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1844         }
1845
1846         // Validity check for api3 entry point
1847         if (target.isInternalFlow()) {
1848             String msg = "Invalid operation: Controller generated flow cannot be deleted";
1849             String logMsg = msg + ": {}";
1850             log.warn(logMsg, name);
1851             return new Status(StatusCode.NOTACCEPTABLE, msg);
1852         }
1853
1854         if (target.isPortGroupEnabled()) {
1855             String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1856             String logMsg = msg + ": {}";
1857             log.warn(logMsg, name);
1858             return new Status(StatusCode.NOTACCEPTABLE, msg);
1859         }
1860
1861         // Program the network node
1862         Status status = this.removeEntry(target.getFlowEntry(), async);
1863
1864         // Update configuration database if programming was successful
1865         if (status.isSuccess()) {
1866             staticFlows.remove(key);
1867         }
1868
1869         return status;
1870     }
1871
1872     @Override
1873     public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1874         // Validity check for api3 entry point
1875         if (newFlowConfig.isInternalFlow()) {
1876             String msg = "Invalid operation: Controller generated flow cannot be modified";
1877             String logMsg = msg + ": {}";
1878             log.warn(logMsg, newFlowConfig);
1879             return new Status(StatusCode.NOTACCEPTABLE, msg);
1880         }
1881
1882         // Validity Check
1883         Status status = newFlowConfig.validate();
1884         if (!status.isSuccess()) {
1885             String msg = "Invalid Configuration (" + status.getDescription() + ")";
1886             newFlowConfig.setStatus(msg);
1887             log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1888             return new Status(StatusCode.BADREQUEST, msg);
1889         }
1890
1891         FlowConfig oldFlowConfig = null;
1892         Integer index = null;
1893         for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1894             FlowConfig entry = mapEntry.getValue();
1895             if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1896                 oldFlowConfig = entry;
1897                 index = mapEntry.getKey();
1898                 break;
1899             }
1900         }
1901
1902         if (oldFlowConfig == null) {
1903             String msg = "Attempt to modify a non existing static flow";
1904             String logMsg = msg + ": {}";
1905             log.warn(logMsg, newFlowConfig);
1906             return new Status(StatusCode.NOTFOUND, msg);
1907         }
1908
1909         // Do not attempt to reinstall the flow, warn user
1910         if (newFlowConfig.equals(oldFlowConfig)) {
1911             String msg = "No modification detected";
1912             log.trace("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1913             return new Status(StatusCode.SUCCESS, msg);
1914         }
1915
1916         // If flow is installed, program the network node
1917         status = new Status(StatusCode.SUCCESS, "Saved in config");
1918         if (oldFlowConfig.installInHw()) {
1919             status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1920         }
1921
1922         // Update configuration database if programming was successful
1923         if (status.isSuccess()) {
1924             newFlowConfig.setStatus(status.getDescription());
1925             staticFlows.put(index, newFlowConfig);
1926         }
1927
1928         return status;
1929     }
1930
1931     @Override
1932     public Status toggleStaticFlowStatus(String name, Node node) {
1933         return toggleStaticFlowStatus(getStaticFlow(name, node));
1934     }
1935
1936     @Override
1937     public Status toggleStaticFlowStatus(FlowConfig config) {
1938         if (config == null) {
1939             String msg = "Invalid request: null flow config";
1940             log.warn(msg);
1941             return new Status(StatusCode.BADREQUEST, msg);
1942         }
1943         // Validity check for api3 entry point
1944         if (config.isInternalFlow()) {
1945             String msg = "Invalid operation: Controller generated flow cannot be modified";
1946             String logMsg = msg + ": {}";
1947             log.warn(logMsg, config);
1948             return new Status(StatusCode.NOTACCEPTABLE, msg);
1949         }
1950
1951         // Find the config entry
1952         Integer key = 0;
1953         FlowConfig target = null;
1954         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1955             FlowConfig conf = entry.getValue();
1956             if (conf.isByNameAndNodeIdEqual(config)) {
1957                 key = entry.getKey();
1958                 target = conf;
1959                 break;
1960             }
1961         }
1962         if (target != null) {
1963             Status status = target.validate();
1964             if (!status.isSuccess()) {
1965                 log.warn(status.getDescription());
1966                 return status;
1967             }
1968             status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1969                                     .installFlowEntry(target.getFlowEntry());
1970             if (status.isSuccess()) {
1971                 // Update Configuration database
1972                 target.setStatus(StatusCode.SUCCESS.toString());
1973                 target.toggleInstallation();
1974                 staticFlows.put(key, target);
1975             }
1976             return status;
1977         }
1978
1979         return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1980     }
1981
1982     /**
1983      * Reinsert all static flows entries in the cache to force cache updates in
1984      * the cluster. This is useful when only some parameters were changed in the
1985      * entries, like the status.
1986      *
1987      * @param node
1988      *            The node for which the static flow configurations have to be
1989      *            refreshed. If null, all nodes static flows will be refreshed.
1990      */
1991     private void refreshClusterStaticFlowsStatus(Node node) {
1992         // Refresh cluster cache
1993         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1994             if (node == null || entry.getValue().getNode().equals(node)) {
1995                 staticFlows.put(entry.getKey(), entry.getValue());
1996             }
1997         }
1998     }
1999
2000     /**
2001      * Uninstall all the non-internal Flow Entries present in the software view.
2002      * If requested, a copy of each original flow entry will be stored in the
2003      * inactive list so that it can be re-applied when needed (This is typically
2004      * the case when running in the default container and controller moved to
2005      * container mode) NOTE WELL: The routine as long as does a bulk change will
2006      * operate only on the entries for nodes locally attached so to avoid
2007      * redundant operations initiated by multiple nodes
2008      *
2009      * @param preserveFlowEntries
2010      *            if true, a copy of each original entry is stored in the
2011      *            inactive list
2012      */
2013     private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
2014         log.trace("Uninstalling all non-internal flows");
2015
2016         List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
2017
2018         // Store entries / create target list
2019         for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
2020             FlowEntryInstall flowEntries = mapEntry.getValue();
2021             // Skip internal generated static flows
2022             if (!flowEntries.isInternal()) {
2023                 toRemove.add(flowEntries);
2024                 // Store the original entries if requested
2025                 if (preserveFlowEntries) {
2026                     inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
2027                 }
2028             }
2029         }
2030
2031         // Now remove the entries
2032         for (FlowEntryInstall flowEntryHw : toRemove) {
2033             Node n = flowEntryHw.getNode();
2034             if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
2035                 Status status = this.removeEntryInternal(flowEntryHw, false);
2036                 if (!status.isSuccess()) {
2037                     log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
2038                 }
2039             } else {
2040                 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
2041                         flowEntryHw);
2042             }
2043         }
2044     }
2045
2046     /**
2047      * Re-install all the Flow Entries present in the inactive list The inactive
2048      * list will be empty at the end of this call This function is called on the
2049      * default container instance of FRM only when the last container is deleted
2050      */
2051     private void reinstallAllFlowEntries() {
2052         log.trace("Reinstalling all inactive flows");
2053
2054         for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
2055             this.addEntry(flowEntry, false);
2056         }
2057
2058         // Empty inactive list in any case
2059         inactiveFlows.clear();
2060     }
2061
2062     @Override
2063     public List<FlowConfig> getStaticFlows() {
2064         return new ArrayList<FlowConfig>(staticFlows.values());
2065     }
2066
2067     @Override
2068     public FlowConfig getStaticFlow(String name, Node node) {
2069         ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
2070         if(entry != null) {
2071             return entry.getValue();
2072         }
2073         return null;
2074     }
2075
2076     @Override
2077     public List<FlowConfig> getStaticFlows(Node node) {
2078         List<FlowConfig> list = new ArrayList<FlowConfig>();
2079         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2080             if (entry.getValue().onNode(node)) {
2081                 list.add(entry.getValue());
2082             }
2083         }
2084         return list;
2085     }
2086
2087     @Override
2088     public List<String> getStaticFlowNamesForNode(Node node) {
2089         List<String> list = new ArrayList<String>();
2090         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2091             if (entry.getValue().onNode(node)) {
2092                 list.add(entry.getValue().getName());
2093             }
2094         }
2095         return list;
2096     }
2097
2098     @Override
2099     public List<Node> getListNodeWithConfiguredFlows() {
2100         Set<Node> set = new HashSet<Node>();
2101         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2102             set.add(entry.getValue().getNode());
2103         }
2104         return new ArrayList<Node>(set);
2105     }
2106
2107     private void loadFlowConfiguration() {
2108         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, PORT_GROUP_FILE_NAME)) {
2109             addPortGroupConfig(((PortGroupConfig) conf).getName(), ((PortGroupConfig) conf).getMatchString(), true);
2110         }
2111
2112         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, STATIC_FLOWS_FILE_NAME)) {
2113             addStaticFlowInternal((FlowConfig) conf, false, true);
2114         }
2115     }
2116
2117     @Override
2118     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2119         return ois.readObject();
2120     }
2121
2122     @Override
2123     public Status saveConfig() {
2124         return saveConfigInternal();
2125     }
2126
2127     private Status saveConfigInternal() {
2128         List<ConfigurationObject> nonDynamicFlows = new ArrayList<ConfigurationObject>();
2129
2130         for (Integer ordinal : staticFlows.keySet()) {
2131             FlowConfig config = staticFlows.get(ordinal);
2132             // Do not save dynamic and controller generated static flows
2133             if (config.isDynamic() || config.isInternalFlow()) {
2134                 continue;
2135             }
2136             nonDynamicFlows.add(config);
2137         }
2138
2139         configurationService.persistConfiguration(nonDynamicFlows, STATIC_FLOWS_FILE_NAME);
2140         configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(portGroupConfigs.values()),
2141                 PORT_GROUP_FILE_NAME);
2142
2143         return new Status(StatusCode.SUCCESS);
2144     }
2145
2146     @Override
2147     public void subnetNotify(Subnet sub, boolean add) {
2148     }
2149
2150     private boolean programInternalFlow(boolean proactive, FlowConfig fc) {
2151         boolean retVal = true; // program flows unless determined otherwise
2152         if(proactive) {
2153             // if the flow already exists do not program
2154             if(flowConfigExists(fc)) {
2155                 retVal = false;
2156             }
2157         } else {
2158             // if the flow does not exist do not program
2159             if(!flowConfigExists(fc)) {
2160                 retVal = false;
2161             }
2162         }
2163         return retVal;
2164     }
2165
2166     /**
2167      * (non-Javadoc)
2168      *
2169      * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2170      *      boolean)
2171      *
2172      *      This method can be called from within the OSGi framework context,
2173      *      given the programming operation can take sometime, it not good
2174      *      pratice to have in it's context operations that can take time,
2175      *      hence moving off to a different thread for async processing.
2176      */
2177     private ExecutorService executor;
2178     @Override
2179     public void modeChangeNotify(final Node node, final boolean proactive) {
2180         Callable<Status> modeChangeCallable = new Callable<Status>() {
2181             @Override
2182             public Status call() throws Exception {
2183                 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2184
2185                 List<String> puntAction = new ArrayList<String>();
2186                 puntAction.add(ActionType.CONTROLLER.toString());
2187
2188                 FlowConfig allowARP = new FlowConfig();
2189                 allowARP.setInstallInHw(true);
2190                 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2191                 allowARP.setPriority("1");
2192                 allowARP.setNode(node);
2193                 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2194                         .toUpperCase());
2195                 allowARP.setActions(puntAction);
2196                 defaultConfigs.add(allowARP);
2197
2198                 FlowConfig allowLLDP = new FlowConfig();
2199                 allowLLDP.setInstallInHw(true);
2200                 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2201                 allowLLDP.setPriority("1");
2202                 allowLLDP.setNode(node);
2203                 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2204                         .toUpperCase());
2205                 allowLLDP.setActions(puntAction);
2206                 defaultConfigs.add(allowLLDP);
2207
2208                 List<String> dropAction = new ArrayList<String>();
2209                 dropAction.add(ActionType.DROP.toString());
2210
2211                 FlowConfig dropAllConfig = new FlowConfig();
2212                 dropAllConfig.setInstallInHw(true);
2213                 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2214                         + FlowConfig.INTERNALSTATICFLOWEND);
2215                 dropAllConfig.setPriority("0");
2216                 dropAllConfig.setNode(node);
2217                 dropAllConfig.setActions(dropAction);
2218                 defaultConfigs.add(dropAllConfig);
2219
2220                 log.trace("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2221                 for (FlowConfig fc : defaultConfigs) {
2222                     // check if the frm really needs to act on the notification.
2223                     // this is to check against duplicate notifications
2224                     if(programInternalFlow(proactive, fc)) {
2225                         Status status = (proactive) ? addStaticFlowInternal(fc, false, false) : removeStaticFlow(fc);
2226                         if (status.isSuccess()) {
2227                             log.trace("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2228                         } else {
2229                             log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2230                                     fc.getName());
2231                         }
2232                     } else {
2233                         log.debug("Got redundant install request for internal flow: {} on node: {}. Request not sent to FRM.", fc.getName(), node);
2234                     }
2235                 }
2236                 return new Status(StatusCode.SUCCESS);
2237             }
2238         };
2239
2240         /*
2241          * Execute the work outside the caller context, this could be an
2242          * expensive operation and we don't want to block the caller for it.
2243          */
2244         this.executor.submit(modeChangeCallable);
2245     }
2246
2247     /**
2248      * Remove from the databases all the flows installed on the node
2249      *
2250      * @param node
2251      */
2252     private void cleanDatabaseForNode(Node node) {
2253         log.trace("Cleaning Flow database for Node {}", node);
2254         if (nodeFlows.containsKey(node)) {
2255             List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2256
2257             for (FlowEntryInstall entry : toRemove) {
2258                 updateSwViews(entry, false);
2259             }
2260         }
2261     }
2262
2263     private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2264         if (nc == null) {
2265             return false;
2266         }
2267
2268         Match match = flow.getMatch();
2269         if (match.isPresent(MatchType.IN_PORT)) {
2270             NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2271             if (matchPort.equals(nc)) {
2272                 return true;
2273             }
2274         }
2275         List<Action> actionsList = flow.getActions();
2276         if (actionsList != null) {
2277             for (Action action : actionsList) {
2278                 if (action instanceof Output) {
2279                     NodeConnector actionPort = ((Output) action).getPort();
2280                     if (actionPort.equals(nc)) {
2281                         return true;
2282                     }
2283                 }
2284             }
2285         }
2286         return false;
2287     }
2288
2289     @Override
2290     public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2291         this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2292     }
2293
2294     @Override
2295     public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2296         boolean updateStaticFlowCluster = false;
2297
2298         switch (type) {
2299         case ADDED:
2300             break;
2301         case CHANGED:
2302             Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2303             if (config != null) {
2304                 switch (config.getValue()) {
2305                 case Config.ADMIN_DOWN:
2306                     log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2307                     updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2308                     break;
2309                 case Config.ADMIN_UP:
2310                     log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2311                     updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2312                     break;
2313                 case Config.ADMIN_UNDEF:
2314                     break;
2315                 default:
2316                 }
2317             }
2318             break;
2319         case REMOVED:
2320             // This is the case where a switch port is removed from the SDN agent space
2321             log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2322             updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2323             break;
2324         default:
2325
2326         }
2327
2328         if (updateStaticFlowCluster) {
2329             refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2330         }
2331     }
2332
2333     /*
2334      * It goes through the static flows configuration, it identifies the ones
2335      * which have the specified node connector as input or output port and
2336      * install them on the network node if they are marked to be installed in
2337      * hardware and their status shows they were not installed yet
2338      */
2339     private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2340         boolean updated = false;
2341         List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2342         for (FlowConfig flowConfig : flowConfigForNode) {
2343             if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2344                 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) {
2345                     Status status = this.installFlowEntryAsync(flowConfig.getFlowEntry());
2346                     if (!status.isSuccess()) {
2347                         flowConfig.setStatus(status.getDescription());
2348                     } else {
2349                         flowConfig.setStatus(StatusCode.SUCCESS.toString());
2350                     }
2351                     updated = true;
2352                 }
2353             }
2354         }
2355         return updated;
2356     }
2357
2358     /*
2359      * Remove from the network node all the flows which have the specified node
2360      * connector as input or output port. If any of the flow entry is a static
2361      * flow, it updates the correspondent configuration.
2362      */
2363     private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2364         boolean updated = false;
2365         List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2366         if (nodeFlowEntries == null) {
2367             return updated;
2368         }
2369         for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2370             if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2371                 Status status = this.removeEntryInternal(fei, true);
2372                 if (!status.isSuccess()) {
2373                     continue;
2374                 }
2375                 /*
2376                  * If the flow entry is a static flow, then update its
2377                  * configuration
2378                  */
2379                 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2380                     FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2381                     if (flowConfig != null) {
2382                         flowConfig.setStatus(PORT_REMOVED);
2383                         updated = true;
2384                     }
2385                 }
2386             }
2387         }
2388         return updated;
2389     }
2390
2391     private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2392         FlowConfig derivedFlow = new FlowConfig(original);
2393         derivedFlow.setDynamic(true);
2394         derivedFlow.setPortGroup(null);
2395         derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2396         derivedFlow.setIngressPort(port + "");
2397         return derivedFlow;
2398     }
2399
2400     private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2401         for (FlowConfig staticFlow : staticFlows.values()) {
2402             if (staticFlow.getPortGroup() == null) {
2403                 continue;
2404             }
2405             if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2406                 for (Short port : data.getPorts()) {
2407                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2408                     addStaticFlowInternal(derivedFlow, false, false);
2409                 }
2410             }
2411         }
2412     }
2413
2414     private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2415         for (FlowConfig staticFlow : staticFlows.values()) {
2416             if (staticFlow.getPortGroup() == null) {
2417                 continue;
2418             }
2419             if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2420                 for (Short port : data.getPorts()) {
2421                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2422                     removeStaticFlow(derivedFlow);
2423                 }
2424             }
2425         }
2426     }
2427
2428     @Override
2429     public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2430         log.trace("PortGroup Changed for: {} Data: {}", config, portGroupData);
2431         Map<Node, PortGroup> existingData = portGroupData.get(config);
2432         if (existingData != null) {
2433             for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2434                 PortGroup existingPortGroup = existingData.get(entry.getKey());
2435                 if (existingPortGroup == null) {
2436                     if (add) {
2437                         existingData.put(entry.getKey(), entry.getValue());
2438                         addPortGroupFlows(config, entry.getKey(), entry.getValue());
2439                     }
2440                 } else {
2441                     if (add) {
2442                         existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2443                         addPortGroupFlows(config, entry.getKey(), entry.getValue());
2444                     } else {
2445                         existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2446                         removePortGroupFlows(config, entry.getKey(), entry.getValue());
2447                     }
2448                 }
2449             }
2450         } else {
2451             if (add) {
2452                 portGroupData.put(config, data);
2453                 for (Node swid : data.keySet()) {
2454                     addPortGroupFlows(config, swid, data.get(swid));
2455                 }
2456             }
2457         }
2458     }
2459
2460     @Override
2461     public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2462         PortGroupConfig config = portGroupConfigs.get(name);
2463         if (config != null) {
2464             return false;
2465         }
2466
2467         if ((portGroupProvider == null) && !restore) {
2468             return false;
2469         }
2470         if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2471             return false;
2472         }
2473
2474         config = new PortGroupConfig(name, regex);
2475         portGroupConfigs.put(name, config);
2476         if (portGroupProvider != null) {
2477             portGroupProvider.createPortGroupConfig(config);
2478         }
2479         return true;
2480     }
2481
2482     @Override
2483     public boolean delPortGroupConfig(String name) {
2484         PortGroupConfig config = portGroupConfigs.get(name);
2485         if (config == null) {
2486             return false;
2487         }
2488
2489         if (portGroupProvider != null) {
2490             portGroupProvider.deletePortGroupConfig(config);
2491         }
2492         portGroupConfigs.remove(name);
2493         return true;
2494     }
2495
2496     @Override
2497     public Map<String, PortGroupConfig> getPortGroupConfigs() {
2498         return portGroupConfigs;
2499     }
2500
2501     public boolean isPortGroupSupported() {
2502         if (portGroupProvider == null) {
2503             return false;
2504         }
2505         return true;
2506     }
2507
2508     public void setIContainer(IContainer s) {
2509         this.container = s;
2510     }
2511
2512     public void unsetIContainer(IContainer s) {
2513         if (this.container == s) {
2514             this.container = null;
2515         }
2516     }
2517
2518     public void setConfigurationContainerService(IConfigurationContainerService service) {
2519         log.trace("Got configuration service set request {}", service);
2520         this.configurationService = service;
2521     }
2522
2523     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
2524         log.trace("Got configuration service UNset request");
2525         this.configurationService = null;
2526     }
2527
2528     @Override
2529     public PortGroupProvider getPortGroupProvider() {
2530         return portGroupProvider;
2531     }
2532
2533     public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2534         this.portGroupProvider = null;
2535     }
2536
2537     public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2538         this.portGroupProvider = portGroupProvider;
2539         portGroupProvider.registerPortGroupChange(this);
2540         for (PortGroupConfig config : portGroupConfigs.values()) {
2541             portGroupProvider.createPortGroupConfig(config);
2542         }
2543     }
2544
2545     public void setFrmAware(IForwardingRulesManagerAware obj) {
2546         this.frmAware.add(obj);
2547     }
2548
2549     public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2550         this.frmAware.remove(obj);
2551     }
2552
2553     void setClusterContainerService(IClusterContainerServices s) {
2554         log.debug("Cluster Service set");
2555         this.clusterContainerService = s;
2556     }
2557
2558     void unsetClusterContainerService(IClusterContainerServices s) {
2559         if (this.clusterContainerService == s) {
2560             log.debug("Cluster Service removed!");
2561             this.clusterContainerService = null;
2562         }
2563     }
2564
2565     private String getContainerName() {
2566         if (container == null) {
2567             return GlobalConstants.DEFAULT.toString();
2568         }
2569         return container.getName();
2570     }
2571
2572     /**
2573      * Function called by the dependency manager when all the required
2574      * dependencies are satisfied
2575      *
2576      */
2577     void init() {
2578
2579         inContainerMode = false;
2580
2581         if (portGroupProvider != null) {
2582             portGroupProvider.registerPortGroupChange(this);
2583         }
2584
2585         nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
2586         groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
2587
2588         cacheStartup();
2589
2590         /*
2591          * If we are not the first cluster node to come up, do not initialize
2592          * the static flow entries ordinal
2593          */
2594         if (staticFlowsOrdinal.size() == 0) {
2595             staticFlowsOrdinal.put(0, Integer.valueOf(0));
2596         }
2597
2598         pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2599
2600         // Initialize the event handler thread
2601         frmEventHandler = new Thread(new Runnable() {
2602             @Override
2603             public void run() {
2604                 while (!stopping) {
2605                     try {
2606                         final FRMEvent event = pendingEvents.take();
2607                         if (event == null) {
2608                             log.warn("Dequeued null event");
2609                             continue;
2610                         }
2611                         log.trace("Dequeued {} event", event.getClass().getSimpleName());
2612                         if (event instanceof NodeUpdateEvent) {
2613                             NodeUpdateEvent update = (NodeUpdateEvent) event;
2614                             Node node = update.getNode();
2615                             switch (update.getUpdateType()) {
2616                             case ADDED:
2617                                 addStaticFlowsToSwitch(node);
2618                                 break;
2619                             case REMOVED:
2620                                 cleanDatabaseForNode(node);
2621                                 updateStaticFlowConfigsOnNodeDown(node);
2622                                 break;
2623                             default:
2624                             }
2625                         } else if (event instanceof ErrorReportedEvent) {
2626                             ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2627                             processErrorEvent(errEvent);
2628                         } else if (event instanceof WorkOrderEvent) {
2629                             /*
2630                              * Take care of handling the remote Work request
2631                              */
2632                             Runnable r = new Runnable() {
2633                                 @Override
2634                                 public void run() {
2635                                     WorkOrderEvent work = (WorkOrderEvent) event;
2636                                     FlowEntryDistributionOrder fe = work.getFe();
2637                                     if (fe != null) {
2638                                         logsync.trace("Executing the workOrder {}", fe);
2639                                         Status gotStatus = null;
2640                                         FlowEntryInstall feiCurrent = fe.getEntry();
2641                                         FlowEntryInstall feiNew = workOrder.get(fe);
2642                                         switch (fe.getUpType()) {
2643                                         case ADDED:
2644                                             gotStatus = addEntryInHw(feiCurrent, false);
2645                                             break;
2646                                         case CHANGED:
2647                                             gotStatus = modifyEntryInHw(feiCurrent, feiNew, false);
2648                                             break;
2649                                         case REMOVED:
2650                                             gotStatus = removeEntryInHw(feiCurrent, false);
2651                                             break;
2652                                         }
2653                                         // Remove the Order
2654                                         workOrder.remove(fe);
2655                                         logsync.trace(
2656                                                 "The workOrder has been executed and now the status is being returned {}", fe);
2657                                         // Place the status
2658                                         workStatus.put(fe, gotStatus);
2659                                     } else {
2660                                         log.warn("Not expected null WorkOrder", work);
2661                                     }
2662                                 }
2663                             };
2664                             if(executor != null) {
2665                                 executor.execute(r);
2666                             }
2667                         } else if (event instanceof WorkStatusCleanup) {
2668                             /*
2669                              * Take care of handling the remote Work request
2670                              */
2671                             WorkStatusCleanup work = (WorkStatusCleanup) event;
2672                             FlowEntryDistributionOrder fe = work.getFe();
2673                             if (fe != null) {
2674                                 logsync.trace("The workStatus {} is being removed", fe);
2675                                 workStatus.remove(fe);
2676                             } else {
2677                                 log.warn("Not expected null WorkStatus", work);
2678                             }
2679                         }  else if (event instanceof ContainerFlowChangeEvent) {
2680                             /*
2681                              * Whether it is an addition or removal, we have to
2682                              * recompute the merged flows entries taking into
2683                              * account all the current container flows because
2684                              * flow merging is not an injective function
2685                              */
2686                             updateFlowsContainerFlow();
2687                         } else if (event instanceof UpdateIndexDBs) {
2688                             UpdateIndexDBs update = (UpdateIndexDBs)event;
2689                             updateIndexDatabase(update.getFei(), update.isAddition());
2690                         } else {
2691                             log.warn("Dequeued unknown event {}", event.getClass().getSimpleName());
2692                         }
2693                     } catch (InterruptedException e) {
2694                         // clear pending events
2695                         pendingEvents.clear();
2696                     }
2697                 }
2698             }
2699         }, "FRM EventHandler Collector");
2700     }
2701
2702     /**
2703      * Function called by the dependency manager when at least one dependency
2704      * become unsatisfied or when the component is shutting down because for
2705      * example bundle is being stopped.
2706      *
2707      */
2708     void destroy() {
2709         // Interrupt the thread
2710         frmEventHandler.interrupt();
2711         // Clear the pendingEvents queue
2712         pendingEvents.clear();
2713         frmAware.clear();
2714         workMonitor.clear();
2715     }
2716
2717     /**
2718      * Function called by dependency manager after "init ()" is called and after
2719      * the services provided by the class are registered in the service registry
2720      *
2721      */
2722     void start() {
2723         /*
2724          * If running in default container, need to know if controller is in
2725          * container mode
2726          */
2727         if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) {
2728             inContainerMode = containerManager.inContainerMode();
2729         }
2730
2731         // Initialize graceful stop flag
2732         stopping = false;
2733
2734         // Allocate the executor service
2735         this.executor = Executors.newFixedThreadPool(maxPoolSize);
2736
2737         // Start event handler thread
2738         frmEventHandler.start();
2739
2740         // replay the installedSwView data structure to populate
2741         // node flows and group flows
2742         for (FlowEntryInstall fei : installedSwView.values()) {
2743             pendingEvents.offer(new UpdateIndexDBs(fei, true));
2744         }
2745
2746         /*
2747          * Read startup and build database if we are the coordinator
2748          */
2749         loadFlowConfiguration();
2750     }
2751
2752     /**
2753      * Function called by the dependency manager before Container is Stopped and Destroyed.
2754      */
2755     public void containerStop() {
2756         uninstallAllFlowEntries(false);
2757     }
2758
2759     /**
2760      * Function called by the dependency manager before the services exported by
2761      * the component are unregistered, this will be followed by a "destroy ()"
2762      * calls
2763      */
2764     void stop() {
2765         stopping = true;
2766         // Shutdown executor
2767         this.executor.shutdownNow();
2768         // Now walk all the workMonitor and wake up the one sleeping because
2769         // destruction is happening
2770         for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2771             FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2772             task.cancel(true);
2773         }
2774     }
2775
2776     public void setFlowProgrammerService(IFlowProgrammerService service) {
2777         this.programmer = service;
2778     }
2779
2780     public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2781         if (this.programmer == service) {
2782             this.programmer = null;
2783         }
2784     }
2785
2786     public void setSwitchManager(ISwitchManager switchManager) {
2787         this.switchManager = switchManager;
2788     }
2789
2790     public void unsetSwitchManager(ISwitchManager switchManager) {
2791         if (this.switchManager == switchManager) {
2792             this.switchManager = null;
2793         }
2794     }
2795
2796     @Override
2797     public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2798         if (!container.getName().equals(containerName)) {
2799             return;
2800         }
2801     }
2802
2803     @Override
2804     public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2805         if (!container.getName().equals(containerName)) {
2806             return;
2807         }
2808         log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2809                 container.getName(), t, current);
2810         ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2811         pendingEvents.offer(ev);
2812     }
2813
2814     @Override
2815     public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2816         if (!container.getName().equals(containerName)) {
2817             return;
2818         }
2819
2820         boolean updateStaticFlowCluster = false;
2821
2822         switch (t) {
2823         case REMOVED:
2824             log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2825             updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2826             break;
2827         case ADDED:
2828             log.trace("Port {} was added to container: reinstall interested flows", nc);
2829             updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2830
2831             break;
2832         case CHANGED:
2833             break;
2834         default:
2835         }
2836
2837         if (updateStaticFlowCluster) {
2838             refreshClusterStaticFlowsStatus(nc.getNode());
2839         }
2840     }
2841
2842     @Override
2843     public void containerModeUpdated(UpdateType update) {
2844         // Only default container instance reacts on this event
2845         if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2846             return;
2847         }
2848         switch (update) {
2849         case ADDED:
2850             /*
2851              * Controller is moving to container mode. We are in the default
2852              * container context, we need to remove all our non-internal flows
2853              * to prevent any container isolation breakage. We also need to
2854              * preserve our flow so that they can be re-installed if we move
2855              * back to non container mode (no containers).
2856              */
2857             this.inContainerMode = true;
2858             this.uninstallAllFlowEntries(true);
2859             break;
2860         case REMOVED:
2861             this.inContainerMode = false;
2862             this.reinstallAllFlowEntries();
2863             break;
2864         default:
2865             break;
2866         }
2867
2868         // Update our configuration DB
2869         updateStaticFlowConfigsOnContainerModeChange(update);
2870     }
2871
2872     protected abstract class FRMEvent {
2873
2874     }
2875
2876     private class NodeUpdateEvent extends FRMEvent {
2877         private final Node node;
2878         private final UpdateType update;
2879
2880         public NodeUpdateEvent(UpdateType update, Node node) {
2881             this.update = update;
2882             this.node = node;
2883         }
2884
2885         public UpdateType getUpdateType() {
2886             return update;
2887         }
2888
2889         public Node getNode() {
2890             return node;
2891         }
2892     }
2893
2894     private class ErrorReportedEvent extends FRMEvent {
2895         private final long rid;
2896         private final Node node;
2897         private final Object error;
2898
2899         public ErrorReportedEvent(long rid, Node node, Object error) {
2900             this.rid = rid;
2901             this.node = node;
2902             this.error = error;
2903         }
2904
2905         public long getRequestId() {
2906             return rid;
2907         }
2908
2909         public Object getError() {
2910             return error;
2911         }
2912
2913         public Node getNode() {
2914             return node;
2915         }
2916     }
2917
2918     private class WorkOrderEvent extends FRMEvent {
2919         private FlowEntryDistributionOrder fe;
2920         private FlowEntryInstall newEntry;
2921
2922         /**
2923          * @param fe
2924          * @param newEntry
2925          */
2926         WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2927             this.fe = fe;
2928             this.newEntry = newEntry;
2929         }
2930
2931         /**
2932          * @return the fe
2933          */
2934         public FlowEntryDistributionOrder getFe() {
2935             return fe;
2936         }
2937
2938         /**
2939          * @return the newEntry
2940          */
2941         public FlowEntryInstall getNewEntry() {
2942             return newEntry;
2943         }
2944     }
2945     private class ContainerFlowChangeEvent extends FRMEvent {
2946         private final ContainerFlow previous;
2947         private final ContainerFlow current;
2948         private final UpdateType type;
2949
2950         public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2951             this.previous = previous;
2952             this.current = current;
2953             this.type = type;
2954         }
2955
2956         public ContainerFlow getPrevious() {
2957             return this.previous;
2958         }
2959
2960         public ContainerFlow getCurrent() {
2961             return this.current;
2962         }
2963
2964         public UpdateType getType() {
2965             return this.type;
2966         }
2967     }
2968
2969
2970     private class WorkStatusCleanup extends FRMEvent {
2971         private FlowEntryDistributionOrder fe;
2972
2973         /**
2974          * @param fe
2975          */
2976         WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2977             this.fe = fe;
2978         }
2979
2980         /**
2981          * @return the fe
2982          */
2983         public FlowEntryDistributionOrder getFe() {
2984             return fe;
2985         }
2986     }
2987
2988     private class UpdateIndexDBs extends FRMEvent {
2989         private FlowEntryInstall fei;
2990         private boolean add;
2991
2992         /**
2993          *
2994          * @param fei the flow entry which was installed/removed on the netwrok node
2995          * @param update
2996          */
2997         UpdateIndexDBs(FlowEntryInstall fei, boolean add) {
2998             this.fei = fei;
2999             this.add = add;
3000         }
3001
3002
3003         /**
3004          * @return the flowEntryInstall object which was added/removed
3005          * to/from the installed software view cache
3006          */
3007         public FlowEntryInstall getFei() {
3008             return fei;
3009         }
3010
3011         /**
3012          *
3013          * @return whether this was an flow addition or removal
3014          */
3015         public boolean isAddition() {
3016             return add;
3017         }
3018     }
3019
3020     @Override
3021     public Status saveConfiguration() {
3022         return saveConfig();
3023     }
3024
3025     @Override
3026     public void flowRemoved(Node node, Flow flow) {
3027         log.trace("Received flow removed notification on {} for {}", node, flow);
3028
3029         // For flow entry identification, only node, match and priority matter
3030         FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
3031         FlowEntryInstall installedEntry = this.installedSwView.get(test);
3032         if (installedEntry == null) {
3033             log.trace("Entry is not known to us");
3034             return;
3035         }
3036
3037         // Update Static flow status
3038         Integer key = 0;
3039         FlowConfig target = null;
3040         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3041             FlowConfig conf = entry.getValue();
3042             if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3043                 key = entry.getKey();
3044                 target = conf;
3045                 break;
3046             }
3047         }
3048         if (target != null) {
3049             // Update Configuration database
3050             if (target.getHardTimeout() != null || target.getIdleTimeout() != null) {
3051                 /*
3052                  * No need for checking if actual values: these strings were
3053                  * validated at configuration creation. Also, after a switch
3054                  * down scenario, no use to reinstall a timed flow. Mark it as
3055                  * "do not install". User can manually toggle it.
3056                  */
3057                 target.toggleInstallation();
3058             }
3059             target.setStatus(StatusCode.GONE.toString());
3060             staticFlows.put(key, target);
3061         }
3062
3063         // Update software views
3064         this.updateSwViews(installedEntry, false);
3065     }
3066
3067     @Override
3068     public void flowErrorReported(Node node, long rid, Object err) {
3069         log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3070         pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3071     }
3072
3073     private void processErrorEvent(ErrorReportedEvent event) {
3074         Node node = event.getNode();
3075         long rid = event.getRequestId();
3076         Object error = event.getError();
3077         String errorString = (error == null) ? "Not provided" : error.toString();
3078         /*
3079          * If this was for a flow install, remove the corresponding entry from
3080          * the software view. If it was a Looking for the rid going through the
3081          * software database. TODO: A more efficient rid <-> FlowEntryInstall
3082          * mapping will have to be added in future
3083          */
3084         FlowEntryInstall target = null;
3085         List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3086         // flowEntryInstallList could be null.
3087         // so check for it.
3088         if(flowEntryInstallList != null) {
3089             for (FlowEntryInstall index : flowEntryInstallList) {
3090                 FlowEntryInstall entry = installedSwView.get(index);
3091                 if(entry != null) {
3092                     if (entry.getRequestId() == rid) {
3093                         target = entry;
3094                         break;
3095                     }
3096                 }
3097             }
3098         }
3099         if (target != null) {
3100             // This was a flow install, update database
3101             this.updateSwViews(target, false);
3102             // also update the config
3103             if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3104                 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3105                 // staticFlowEntry should never be null.
3106                 // the null check is just an extra defensive check.
3107                 if(staticFlowEntry != null) {
3108                     // Modify status and update cluster cache
3109                     log.debug("Updating static flow configuration on async error event");
3110                     String status = String.format("Cannot be installed on node. reason: %s", errorString);
3111                     staticFlowEntry.getValue().setStatus(status);
3112                     refreshClusterStaticFlowsStatus(node);
3113                 }
3114             }
3115         }
3116
3117         // Notify listeners
3118         if (frmAware != null) {
3119             synchronized (frmAware) {
3120                 for (IForwardingRulesManagerAware frma : frmAware) {
3121                     try {
3122                         frma.requestFailed(rid, errorString);
3123                     } catch (Exception e) {
3124                         log.warn("Failed to notify {}", frma);
3125                     }
3126                 }
3127             }
3128         }
3129     }
3130
3131     @Override
3132     public Status solicitStatusResponse(Node node, boolean blocking) {
3133         Status rv = new Status(StatusCode.INTERNALERROR);
3134
3135         if (this.programmer != null) {
3136             if (blocking) {
3137                 rv = programmer.syncSendBarrierMessage(node);
3138             } else {
3139                 rv = programmer.asyncSendBarrierMessage(node);
3140             }
3141         }
3142
3143         return rv;
3144     }
3145
3146     public void unsetIConnectionManager(IConnectionManager s) {
3147         if (s == this.connectionManager) {
3148             this.connectionManager = null;
3149         }
3150     }
3151
3152     public void setIConnectionManager(IConnectionManager s) {
3153         this.connectionManager = s;
3154     }
3155
3156     public void unsetIContainerManager(IContainerManager s) {
3157         if (s == this.containerManager) {
3158             this.containerManager = null;
3159         }
3160     }
3161
3162     public void setIContainerManager(IContainerManager s) {
3163         this.containerManager = s;
3164     }
3165
3166     @Override
3167     public void entryCreated(Object key, String cacheName, boolean originLocal) {
3168         /*
3169          * Do nothing
3170          */
3171     }
3172
3173     @Override
3174     public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3175         /*
3176          * Streamline the updates for the per node and per group index databases
3177          */
3178         if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3179             pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)new_value, true));
3180         }
3181
3182         if (originLocal) {
3183             /*
3184              * Local updates are of no interest
3185              */
3186             return;
3187         }
3188         if (cacheName.equals(WORK_ORDER_CACHE)) {
3189             logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3190             /*
3191              * This is the case of one workOrder becoming available, so we need
3192              * to dispatch the work to the appropriate handler
3193              */
3194             FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3195             FlowEntryInstall fei = fe.getEntry();
3196             if (fei == null) {
3197                 return;
3198             }
3199             Node n = fei.getNode();
3200             if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3201                 logsync.trace("workOrder for fe {} processed locally", fe);
3202                 // I'm the controller in charge for the request, queue it for
3203                 // processing
3204                 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3205             }
3206         } else if (cacheName.equals(WORK_STATUS_CACHE)) {
3207             logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3208             /*
3209              * This is the case of one workOrder being completed and a status
3210              * returned
3211              */
3212             FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3213             /*
3214              * Check if the order was initiated by this controller in that case
3215              * we need to actually look at the status returned
3216              */
3217             if (fe.getRequestorController()
3218                     .equals(clusterContainerService.getMyAddress())) {
3219                 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3220                 if (fet != null) {
3221                     logsync.trace("workStatus response is for us {}", fe);
3222                     // Signal we got the status
3223                     fet.gotStatus(fe, workStatus.get(fe));
3224                     pendingEvents.offer(new WorkStatusCleanup(fe));
3225                 }
3226             }
3227         }
3228     }
3229
3230     @Override
3231     public void entryDeleted(Object key, String cacheName, boolean originLocal) {
3232         /*
3233          * Streamline the updates for the per node and per group index databases
3234          */
3235         if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3236             pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)key, false));
3237         }
3238     }
3239
3240     /**
3241      * {@inheritDoc}
3242      */
3243     @Override
3244     public List<FlowEntry> getFlowEntriesForNode(Node node) {
3245         List<FlowEntry> list = new ArrayList<FlowEntry>();
3246         if (node != null) {
3247             for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
3248                 if (node.equals(entry.getKey().getNode())) {
3249                     list.add(entry.getValue().clone());
3250                 }
3251             }
3252         }
3253         return list;
3254     }
3255
3256     /**
3257      * {@inheritDoc}
3258      */
3259     @Override
3260     public List<FlowEntry> getInstalledFlowEntriesForNode(Node node) {
3261         List<FlowEntry> list = new ArrayList<FlowEntry>();
3262         if (node != null) {
3263             List<FlowEntryInstall> flowEntryInstallList = this.nodeFlows.get(node);
3264             if(flowEntryInstallList != null) {
3265                 for(FlowEntryInstall fi: flowEntryInstallList) {
3266                     list.add(fi.getInstall().clone());
3267                 }
3268             }
3269         }
3270         return list;
3271     }
3272
3273 }