FlowConfig to only run syntactic validation
[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                 Status status = this.removeEntry(entry.getOriginal(), false);
1197                 if (status.isSuccess()) {
1198                     toBeRemoved -= 1;
1199                 } else {
1200                     error = status.getDescription();
1201                 }
1202             }
1203         }
1204         return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1205                 "Not all the flows were removed: " + error);
1206     }
1207
1208     @Override
1209     public Status uninstallFlowEntryGroupAsync(String groupName) {
1210         if (groupName == null || groupName.isEmpty()) {
1211             return new Status(StatusCode.BADREQUEST, "Invalid group name");
1212         }
1213         if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1214             return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1215         }
1216         if (inContainerMode) {
1217             String msg = "Controller in container mode: Group Uninstall Refused";
1218             String logMsg = msg + ": {}";
1219             log.warn(logMsg, groupName);
1220             return new Status(StatusCode.NOTACCEPTABLE, msg);
1221         }
1222         if (groupFlows.containsKey(groupName)) {
1223             List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1224             for (FlowEntryInstall entry : list) {
1225                 this.removeEntry(entry.getOriginal(), true);
1226             }
1227         }
1228         return new Status(StatusCode.SUCCESS);
1229     }
1230
1231     @Override
1232     public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1233         return entryConflictsWithContainerFlows(flowEntry);
1234     }
1235
1236     /**
1237      * Updates all installed flows because the container flow got updated This
1238      * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1239      * Reinstall of all flows This is needed because a new container flows
1240      * merged flow may conflict with an existing old container flows merged flow
1241      * on the network node
1242      */
1243     protected void updateFlowsContainerFlow() {
1244         Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1245         // First remove all installed entries
1246         for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1247             FlowEntryInstall current = entry.getValue();
1248             // Store the original entry
1249             toReInstall.add(current.getOriginal());
1250             // Remove the old couples. No validity checks to be run, use the
1251             // internal remove
1252             this.removeEntryInternal(current, false);
1253         }
1254         // Then reinstall the original entries
1255         for (FlowEntry entry : toReInstall) {
1256             // Reinstall the original flow entries, via the regular path: new
1257             // cFlow merge + validations
1258             this.installFlowEntry(entry);
1259         }
1260     }
1261
1262     private void nonClusterObjectCreate() {
1263         originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1264         installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1265         TSPolicies = new ConcurrentHashMap<String, Object>();
1266         staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1267         portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1268         portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1269         staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1270         inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1271     }
1272
1273     @Override
1274     public void setTSPolicyData(String policyname, Object o, boolean add) {
1275
1276         if (add) {
1277             /* Check if this policy already exists */
1278             if (!(TSPolicies.containsKey(policyname))) {
1279                 TSPolicies.put(policyname, o);
1280             }
1281         } else {
1282             TSPolicies.remove(policyname);
1283         }
1284         if (frmAware != null) {
1285             synchronized (frmAware) {
1286                 for (IForwardingRulesManagerAware frma : frmAware) {
1287                     try {
1288                         frma.policyUpdate(policyname, add);
1289                     } catch (Exception e) {
1290                         log.warn("Exception on callback", e);
1291                     }
1292                 }
1293             }
1294         }
1295     }
1296
1297     @Override
1298     public Map<String, Object> getTSPolicyData() {
1299         return TSPolicies;
1300     }
1301
1302     @Override
1303     public Object getTSPolicyData(String policyName) {
1304         if (TSPolicies.containsKey(policyName)) {
1305             return TSPolicies.get(policyName);
1306         } else {
1307             return null;
1308         }
1309     }
1310
1311     @Override
1312     public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1313         List<FlowEntry> list = new ArrayList<FlowEntry>();
1314         if (policyName != null && !policyName.trim().isEmpty()) {
1315             for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1316                 if (policyName.equals(entry.getKey().getGroupName())) {
1317                     list.add(entry.getValue().clone());
1318                 }
1319             }
1320         }
1321         return list;
1322     }
1323
1324     @Override
1325     public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1326         List<FlowEntry> list = new ArrayList<FlowEntry>();
1327         if (policyName != null && !policyName.trim().isEmpty()) {
1328             for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1329                 if (policyName.equals(entry.getKey().getGroupName())) {
1330                     list.add(entry.getValue().getInstall().clone());
1331                 }
1332             }
1333         }
1334         return list;
1335     }
1336
1337     @Override
1338     public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1339
1340         for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1341             if (flow.getFlowName().equals(flowName)) {
1342                 FlowEntry currentFlowEntry = flow.getOriginal();
1343                 FlowEntry newFlowEntry = currentFlowEntry.clone();
1344                 for (NodeConnector dstPort : portList) {
1345                     newFlowEntry.getFlow().addAction(new Output(dstPort));
1346                 }
1347                 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1348                 if (error.isSuccess()) {
1349                     log.trace("Ports {} added to FlowEntry {}", portList, flowName);
1350                 } else {
1351                     log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1352                             currentFlowEntry.toString(), error.getDescription());
1353                 }
1354                 return;
1355             }
1356         }
1357         log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1358     }
1359
1360     @Override
1361     public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1362         for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1363             FlowEntryInstall flow = this.installedSwView.get(index);
1364             if (flow.getFlowName().equals(flowName)) {
1365                 FlowEntry currentFlowEntry = flow.getOriginal();
1366                 FlowEntry newFlowEntry = currentFlowEntry.clone();
1367                 for (NodeConnector dstPort : portList) {
1368                     Action action = new Output(dstPort);
1369                     newFlowEntry.getFlow().removeAction(action);
1370                 }
1371                 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1372                 if (status.isSuccess()) {
1373                     log.trace("Ports {} removed from FlowEntry {}", portList, flowName);
1374                 } else {
1375                     log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1376                             currentFlowEntry.toString(), status.getDescription());
1377                 }
1378                 return;
1379             }
1380         }
1381         log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1382     }
1383
1384     /*
1385      * This function assumes the target flow has only one output port
1386      */
1387     @Override
1388     public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1389         FlowEntry currentFlowEntry = null;
1390         FlowEntry newFlowEntry = null;
1391
1392         // Find the flow
1393         for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1394             FlowEntryInstall flow = this.installedSwView.get(index);
1395             if (flow.getFlowName().equals(flowName)) {
1396                 currentFlowEntry = flow.getOriginal();
1397                 break;
1398             }
1399         }
1400         if (currentFlowEntry == null) {
1401             log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1402             return;
1403         }
1404
1405         // Create a flow copy with the new output port
1406         newFlowEntry = currentFlowEntry.clone();
1407         Action target = null;
1408         for (Action action : newFlowEntry.getFlow().getActions()) {
1409             if (action.getType() == ActionType.OUTPUT) {
1410                 target = action;
1411                 break;
1412             }
1413         }
1414         newFlowEntry.getFlow().removeAction(target);
1415         newFlowEntry.getFlow().addAction(new Output(outPort));
1416
1417         // Modify on network node
1418         Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1419
1420         if (status.isSuccess()) {
1421             log.trace("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1422         } else {
1423             log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1424                     status.getDescription());
1425         }
1426         return;
1427     }
1428
1429     @Override
1430     public NodeConnector getOutputPort(Node node, String flowName) {
1431         for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1432             FlowEntryInstall flow = this.installedSwView.get(index);
1433             if (flow.getFlowName().equals(flowName)) {
1434                 for (Action action : flow.getOriginal().getFlow().getActions()) {
1435                     if (action.getType() == ActionType.OUTPUT) {
1436                         return ((Output) action).getPort();
1437                     }
1438                 }
1439             }
1440         }
1441         return null;
1442     }
1443
1444     private void cacheStartup() {
1445         allocateCaches();
1446         retrieveCaches();
1447     }
1448
1449     private void allocateCaches() {
1450         if (this.clusterContainerService == null) {
1451             log.warn("Un-initialized clusterContainerService, can't create cache");
1452             return;
1453         }
1454
1455         log.debug("Allocating caches for Container {}", container.getName());
1456
1457         try {
1458             clusterContainerService.createCache(ORIGINAL_SW_VIEW_CACHE,
1459                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1460
1461             clusterContainerService.createCache(INSTALLED_SW_VIEW_CACHE,
1462                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1463
1464             clusterContainerService.createCache("frm.inactiveFlows",
1465                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1466
1467             clusterContainerService.createCache("frm.staticFlows",
1468                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1469
1470             clusterContainerService.createCache("frm.staticFlowsOrdinal",
1471                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1472
1473             clusterContainerService.createCache("frm.portGroupConfigs",
1474                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1475
1476             clusterContainerService.createCache("frm.portGroupData",
1477                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1478
1479             clusterContainerService.createCache("frm.TSPolicies",
1480                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1481
1482             clusterContainerService.createCache(WORK_STATUS_CACHE,
1483                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1484
1485             clusterContainerService.createCache(WORK_ORDER_CACHE,
1486                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1487
1488         } catch (CacheConfigException cce) {
1489             log.error("CacheConfigException");
1490         } catch (CacheExistException cce) {
1491             log.error("CacheExistException");
1492         }
1493     }
1494
1495     @SuppressWarnings({ "unchecked" })
1496     private void retrieveCaches() {
1497         ConcurrentMap<?, ?> map;
1498
1499         if (this.clusterContainerService == null) {
1500             log.warn("un-initialized clusterContainerService, can't retrieve cache");
1501             nonClusterObjectCreate();
1502             return;
1503         }
1504
1505         log.debug("Retrieving Caches for Container {}", container.getName());
1506
1507         map = clusterContainerService.getCache(ORIGINAL_SW_VIEW_CACHE);
1508         if (map != null) {
1509             originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1510         } else {
1511             log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1512         }
1513
1514         map = clusterContainerService.getCache(INSTALLED_SW_VIEW_CACHE);
1515         if (map != null) {
1516             installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1517         } else {
1518             log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1519         }
1520
1521         map = clusterContainerService.getCache("frm.inactiveFlows");
1522         if (map != null) {
1523             inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1524         } else {
1525             log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1526         }
1527
1528         map = clusterContainerService.getCache("frm.staticFlows");
1529         if (map != null) {
1530             staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1531         } else {
1532             log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1533         }
1534
1535         map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1536         if (map != null) {
1537             staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1538         } else {
1539             log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1540         }
1541
1542         map = clusterContainerService.getCache("frm.portGroupConfigs");
1543         if (map != null) {
1544             portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1545         } else {
1546             log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1547         }
1548
1549         map = clusterContainerService.getCache("frm.portGroupData");
1550         if (map != null) {
1551             portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1552         } else {
1553             log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1554         }
1555
1556         map = clusterContainerService.getCache("frm.TSPolicies");
1557         if (map != null) {
1558             TSPolicies = (ConcurrentMap<String, Object>) map;
1559         } else {
1560             log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1561         }
1562
1563         map = clusterContainerService.getCache(WORK_ORDER_CACHE);
1564         if (map != null) {
1565             workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1566         } else {
1567             log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName());
1568         }
1569
1570         map = clusterContainerService.getCache(WORK_STATUS_CACHE);
1571         if (map != null) {
1572             workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1573         } else {
1574             log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName());
1575         }
1576     }
1577
1578     private boolean flowConfigExists(FlowConfig config) {
1579         // Flow name has to be unique on per node id basis
1580         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1581             if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1582                 return true;
1583             }
1584         }
1585         return false;
1586     }
1587
1588     @Override
1589     public Status addStaticFlow(FlowConfig config) {
1590         // Configuration object validation
1591         Status status = config.validate();
1592         if (!status.isSuccess()) {
1593             log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1594             String error = "Invalid Configuration (" + status.getDescription() + ")";
1595             config.setStatus(error);
1596             return new Status(StatusCode.BADREQUEST, error);
1597         }
1598         return addStaticFlowInternal(config, false);
1599     }
1600
1601     /**
1602      * Private method to add a static flow configuration which does not run any
1603      * validation on the passed FlowConfig object. If restore is set to true,
1604      * configuration is stored in configuration database regardless the
1605      * installation on the network node was successful. This is useful at boot
1606      * when static flows are present in startup configuration and are read
1607      * before the switches connects.
1608      *
1609      * @param config
1610      *            The static flow configuration
1611      * @param restore
1612      *            if true, the configuration is stored regardless the
1613      *            installation on the network node was successful
1614      * @return The status of this request
1615      */
1616     private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1617         boolean multipleFlowPush = false;
1618         String error;
1619         Status status;
1620         config.setStatus(StatusCode.SUCCESS.toString());
1621
1622         // Presence check
1623         if (flowConfigExists(config)) {
1624             error = "Entry with this name on specified switch already exists";
1625             log.warn("Entry with this name on specified switch already exists: {}", config);
1626             config.setStatus(error);
1627             return new Status(StatusCode.CONFLICT, error);
1628         }
1629
1630         if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1631             for (String portGroupName : portGroupConfigs.keySet()) {
1632                 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1633                     multipleFlowPush = true;
1634                     break;
1635                 }
1636             }
1637             if (!multipleFlowPush) {
1638                 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1639                 error = "Invalid Configuration (Invalid PortGroup Name)";
1640                 config.setStatus(error);
1641                 return new Status(StatusCode.BADREQUEST, error);
1642             }
1643         }
1644
1645         /*
1646          * If requested program the entry in hardware first before updating the
1647          * StaticFlow DB
1648          */
1649         if (!multipleFlowPush) {
1650             // Program hw
1651             if (config.installInHw()) {
1652                 FlowEntry entry = config.getFlowEntry();
1653                 status = this.installFlowEntry(entry);
1654                 if (!status.isSuccess()) {
1655                     config.setStatus(status.getDescription());
1656                     if (!restore) {
1657                         return status;
1658                     }
1659                 }
1660             }
1661         }
1662
1663         /*
1664          * When the control reaches this point, either of the following
1665          * conditions is true 1. This is a single entry configuration (non
1666          * PortGroup) and the hardware installation is successful 2. This is a
1667          * multiple entry configuration (PortGroup) and hardware installation is
1668          * NOT done directly on this event. 3. The User prefers to retain the
1669          * configuration in Controller and skip hardware installation.
1670          *
1671          * Hence it is safe to update the StaticFlow DB at this point.
1672          *
1673          * Note : For the case of PortGrouping, it is essential to have this DB
1674          * populated before the PortGroupListeners can query for the DB
1675          * triggered using portGroupChanged event...
1676          */
1677         Integer ordinal = staticFlowsOrdinal.get(0);
1678         staticFlowsOrdinal.put(0, ++ordinal);
1679         staticFlows.put(ordinal, config);
1680
1681         if (multipleFlowPush) {
1682             PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1683             Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1684             if (existingData != null) {
1685                 portGroupChanged(pgconfig, existingData, true);
1686             }
1687         }
1688         return new Status(StatusCode.SUCCESS);
1689     }
1690
1691     private void addStaticFlowsToSwitch(Node node) {
1692         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1693             FlowConfig config = entry.getValue();
1694             if (config.isPortGroupEnabled()) {
1695                 continue;
1696             }
1697             if (config.getNode().equals(node)) {
1698                 if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) {
1699                     Status status = this.installFlowEntryAsync(config.getFlowEntry());
1700                     config.setStatus(status.getDescription());
1701                 }
1702             }
1703         }
1704         // Update cluster cache
1705         refreshClusterStaticFlowsStatus(node);
1706     }
1707
1708     private void updateStaticFlowConfigsOnNodeDown(Node node) {
1709         log.trace("Updating Static Flow configs on node down: {}", node);
1710
1711         List<Integer> toRemove = new ArrayList<Integer>();
1712         for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1713
1714             FlowConfig config = entry.getValue();
1715
1716             if (config.isPortGroupEnabled()) {
1717                 continue;
1718             }
1719
1720             if (config.installInHw() && config.getNode().equals(node)) {
1721                 if (config.isInternalFlow()) {
1722                     // Take note of this controller generated static flow
1723                     toRemove.add(entry.getKey());
1724                 } else {
1725                     config.setStatus(NODE_DOWN);
1726                 }
1727             }
1728         }
1729         // Remove controller generated static flows for this node
1730         for (Integer index : toRemove) {
1731             staticFlows.remove(index);
1732         }
1733         // Update cluster cache
1734         refreshClusterStaticFlowsStatus(node);
1735
1736     }
1737
1738     private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1739         log.trace("Updating Static Flow configs on container mode change: {}", update);
1740
1741         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1742             FlowConfig config = entry.getValue();
1743             if (config.isPortGroupEnabled()) {
1744                 continue;
1745             }
1746             if (config.installInHw() && !config.isInternalFlow()) {
1747                 switch (update) {
1748                 case ADDED:
1749                     config.setStatus("Removed from node because in container mode");
1750                     break;
1751                 case REMOVED:
1752                     config.setStatus(StatusCode.SUCCESS.toString());
1753                     break;
1754                 default:
1755                     break;
1756                 }
1757             }
1758         }
1759         // Update cluster cache
1760         refreshClusterStaticFlowsStatus(null);
1761     }
1762
1763     @Override
1764     public Status removeStaticFlow(FlowConfig config) {
1765         /*
1766          * No config.isInternal() check as NB does not take this path and GUI
1767          * cannot issue a delete on an internal generated flow. We need this
1768          * path to be accessible when switch mode is changed from proactive to
1769          * reactive, so that we can remove the internal generated LLDP and ARP
1770          * punt flows
1771          */
1772
1773         // Look for the target configuration entry
1774         Integer key = 0;
1775         FlowConfig target = null;
1776         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1777             if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1778                 key = entry.getKey();
1779                 target = entry.getValue();
1780                 break;
1781             }
1782         }
1783         if (target == null) {
1784             return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1785         }
1786
1787         // Program the network node
1788         Status status = this.uninstallFlowEntry(config.getFlowEntry());
1789
1790         // Update configuration database if programming was successful
1791         if (status.isSuccess()) {
1792             staticFlows.remove(key);
1793         }
1794
1795         return status;
1796     }
1797
1798     @Override
1799     public Status removeStaticFlow(String name, Node node) {
1800         // Look for the target configuration entry
1801         Integer key = 0;
1802         FlowConfig target = null;
1803         for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1804             if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1805                 key = mapEntry.getKey();
1806                 target = mapEntry.getValue();
1807                 break;
1808             }
1809         }
1810         if (target == null) {
1811             return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1812         }
1813
1814         // Validity check for api3 entry point
1815         if (target.isInternalFlow()) {
1816             String msg = "Invalid operation: Controller generated flow cannot be deleted";
1817             String logMsg = msg + ": {}";
1818             log.warn(logMsg, name);
1819             return new Status(StatusCode.NOTACCEPTABLE, msg);
1820         }
1821
1822         if (target.isPortGroupEnabled()) {
1823             String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1824             String logMsg = msg + ": {}";
1825             log.warn(logMsg, name);
1826             return new Status(StatusCode.NOTACCEPTABLE, msg);
1827         }
1828
1829         // Program the network node
1830         Status status = this.removeEntry(target.getFlowEntry(), false);
1831
1832         // Update configuration database if programming was successful
1833         if (status.isSuccess()) {
1834             staticFlows.remove(key);
1835         }
1836
1837         return status;
1838     }
1839
1840     @Override
1841     public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1842         // Validity check for api3 entry point
1843         if (newFlowConfig.isInternalFlow()) {
1844             String msg = "Invalid operation: Controller generated flow cannot be modified";
1845             String logMsg = msg + ": {}";
1846             log.warn(logMsg, newFlowConfig);
1847             return new Status(StatusCode.NOTACCEPTABLE, msg);
1848         }
1849
1850         // Validity Check
1851         Status status = newFlowConfig.validate();
1852         if (!status.isSuccess()) {
1853             String msg = "Invalid Configuration (" + status.getDescription() + ")";
1854             newFlowConfig.setStatus(msg);
1855             log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1856             return new Status(StatusCode.BADREQUEST, msg);
1857         }
1858
1859         FlowConfig oldFlowConfig = null;
1860         Integer index = null;
1861         for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1862             FlowConfig entry = mapEntry.getValue();
1863             if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1864                 oldFlowConfig = entry;
1865                 index = mapEntry.getKey();
1866                 break;
1867             }
1868         }
1869
1870         if (oldFlowConfig == null) {
1871             String msg = "Attempt to modify a non existing static flow";
1872             String logMsg = msg + ": {}";
1873             log.warn(logMsg, newFlowConfig);
1874             return new Status(StatusCode.NOTFOUND, msg);
1875         }
1876
1877         // Do not attempt to reinstall the flow, warn user
1878         if (newFlowConfig.equals(oldFlowConfig)) {
1879             String msg = "No modification detected";
1880             log.trace("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1881             return new Status(StatusCode.SUCCESS, msg);
1882         }
1883
1884         // If flow is installed, program the network node
1885         status = new Status(StatusCode.SUCCESS, "Saved in config");
1886         if (oldFlowConfig.installInHw()) {
1887             status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1888         }
1889
1890         // Update configuration database if programming was successful
1891         if (status.isSuccess()) {
1892             newFlowConfig.setStatus(status.getDescription());
1893             staticFlows.put(index, newFlowConfig);
1894         }
1895
1896         return status;
1897     }
1898
1899     @Override
1900     public Status toggleStaticFlowStatus(String name, Node node) {
1901         return toggleStaticFlowStatus(getStaticFlow(name, node));
1902     }
1903
1904     @Override
1905     public Status toggleStaticFlowStatus(FlowConfig config) {
1906         if (config == null) {
1907             String msg = "Invalid request: null flow config";
1908             log.warn(msg);
1909             return new Status(StatusCode.BADREQUEST, msg);
1910         }
1911         // Validity check for api3 entry point
1912         if (config.isInternalFlow()) {
1913             String msg = "Invalid operation: Controller generated flow cannot be modified";
1914             String logMsg = msg + ": {}";
1915             log.warn(logMsg, config);
1916             return new Status(StatusCode.NOTACCEPTABLE, msg);
1917         }
1918
1919         // Find the config entry
1920         Integer key = 0;
1921         FlowConfig target = null;
1922         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1923             FlowConfig conf = entry.getValue();
1924             if (conf.isByNameAndNodeIdEqual(config)) {
1925                 key = entry.getKey();
1926                 target = conf;
1927                 break;
1928             }
1929         }
1930         if (target != null) {
1931             Status status = target.validate();
1932             if (!status.isSuccess()) {
1933                 log.warn(status.getDescription());
1934                 return status;
1935             }
1936             status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1937                                     .installFlowEntry(target.getFlowEntry());
1938             if (status.isSuccess()) {
1939                 // Update Configuration database
1940                 target.setStatus(StatusCode.SUCCESS.toString());
1941                 target.toggleInstallation();
1942                 staticFlows.put(key, target);
1943             }
1944             return status;
1945         }
1946
1947         return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1948     }
1949
1950     /**
1951      * Reinsert all static flows entries in the cache to force cache updates in
1952      * the cluster. This is useful when only some parameters were changed in the
1953      * entries, like the status.
1954      *
1955      * @param node
1956      *            The node for which the static flow configurations have to be
1957      *            refreshed. If null, all nodes static flows will be refreshed.
1958      */
1959     private void refreshClusterStaticFlowsStatus(Node node) {
1960         // Refresh cluster cache
1961         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1962             if (node == null || entry.getValue().getNode().equals(node)) {
1963                 staticFlows.put(entry.getKey(), entry.getValue());
1964             }
1965         }
1966     }
1967
1968     /**
1969      * Uninstall all the non-internal Flow Entries present in the software view.
1970      * If requested, a copy of each original flow entry will be stored in the
1971      * inactive list so that it can be re-applied when needed (This is typically
1972      * the case when running in the default container and controller moved to
1973      * container mode) NOTE WELL: The routine as long as does a bulk change will
1974      * operate only on the entries for nodes locally attached so to avoid
1975      * redundant operations initiated by multiple nodes
1976      *
1977      * @param preserveFlowEntries
1978      *            if true, a copy of each original entry is stored in the
1979      *            inactive list
1980      */
1981     private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1982         log.trace("Uninstalling all non-internal flows");
1983
1984         List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1985
1986         // Store entries / create target list
1987         for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1988             FlowEntryInstall flowEntries = mapEntry.getValue();
1989             // Skip internal generated static flows
1990             if (!flowEntries.isInternal()) {
1991                 toRemove.add(flowEntries);
1992                 // Store the original entries if requested
1993                 if (preserveFlowEntries) {
1994                     inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1995                 }
1996             }
1997         }
1998
1999         // Now remove the entries
2000         for (FlowEntryInstall flowEntryHw : toRemove) {
2001             Node n = flowEntryHw.getNode();
2002             if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
2003                 Status status = this.removeEntryInternal(flowEntryHw, false);
2004                 if (!status.isSuccess()) {
2005                     log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
2006                 }
2007             } else {
2008                 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
2009                         flowEntryHw);
2010             }
2011         }
2012     }
2013
2014     /**
2015      * Re-install all the Flow Entries present in the inactive list The inactive
2016      * list will be empty at the end of this call This function is called on the
2017      * default container instance of FRM only when the last container is deleted
2018      */
2019     private void reinstallAllFlowEntries() {
2020         log.trace("Reinstalling all inactive flows");
2021
2022         for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
2023             this.addEntry(flowEntry, false);
2024         }
2025
2026         // Empty inactive list in any case
2027         inactiveFlows.clear();
2028     }
2029
2030     @Override
2031     public List<FlowConfig> getStaticFlows() {
2032         return new ArrayList<FlowConfig>(staticFlows.values());
2033     }
2034
2035     @Override
2036     public FlowConfig getStaticFlow(String name, Node node) {
2037         ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
2038         if(entry != null) {
2039             return entry.getValue();
2040         }
2041         return null;
2042     }
2043
2044     @Override
2045     public List<FlowConfig> getStaticFlows(Node node) {
2046         List<FlowConfig> list = new ArrayList<FlowConfig>();
2047         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2048             if (entry.getValue().onNode(node)) {
2049                 list.add(entry.getValue());
2050             }
2051         }
2052         return list;
2053     }
2054
2055     @Override
2056     public List<String> getStaticFlowNamesForNode(Node node) {
2057         List<String> list = new ArrayList<String>();
2058         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2059             if (entry.getValue().onNode(node)) {
2060                 list.add(entry.getValue().getName());
2061             }
2062         }
2063         return list;
2064     }
2065
2066     @Override
2067     public List<Node> getListNodeWithConfiguredFlows() {
2068         Set<Node> set = new HashSet<Node>();
2069         for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2070             set.add(entry.getValue().getNode());
2071         }
2072         return new ArrayList<Node>(set);
2073     }
2074
2075     private void loadFlowConfiguration() {
2076         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, PORT_GROUP_FILE_NAME)) {
2077             addPortGroupConfig(((PortGroupConfig) conf).getName(), ((PortGroupConfig) conf).getMatchString(), true);
2078         }
2079
2080         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, STATIC_FLOWS_FILE_NAME)) {
2081             addStaticFlowInternal((FlowConfig) conf, true);
2082         }
2083     }
2084
2085     @Override
2086     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2087         return ois.readObject();
2088     }
2089
2090     @Override
2091     public Status saveConfig() {
2092         return saveConfigInternal();
2093     }
2094
2095     private Status saveConfigInternal() {
2096         List<ConfigurationObject> nonDynamicFlows = new ArrayList<ConfigurationObject>();
2097
2098         for (Integer ordinal : staticFlows.keySet()) {
2099             FlowConfig config = staticFlows.get(ordinal);
2100             // Do not save dynamic and controller generated static flows
2101             if (config.isDynamic() || config.isInternalFlow()) {
2102                 continue;
2103             }
2104             nonDynamicFlows.add(config);
2105         }
2106
2107         configurationService.persistConfiguration(nonDynamicFlows, STATIC_FLOWS_FILE_NAME);
2108         configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(portGroupConfigs.values()),
2109                 PORT_GROUP_FILE_NAME);
2110
2111         return new Status(StatusCode.SUCCESS);
2112     }
2113
2114     @Override
2115     public void subnetNotify(Subnet sub, boolean add) {
2116     }
2117
2118     private boolean programInternalFlow(boolean proactive, FlowConfig fc) {
2119         boolean retVal = true; // program flows unless determined otherwise
2120         if(proactive) {
2121             // if the flow already exists do not program
2122             if(flowConfigExists(fc)) {
2123                 retVal = false;
2124             }
2125         } else {
2126             // if the flow does not exist do not program
2127             if(!flowConfigExists(fc)) {
2128                 retVal = false;
2129             }
2130         }
2131         return retVal;
2132     }
2133
2134     /**
2135      * (non-Javadoc)
2136      *
2137      * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2138      *      boolean)
2139      *
2140      *      This method can be called from within the OSGi framework context,
2141      *      given the programming operation can take sometime, it not good
2142      *      pratice to have in it's context operations that can take time,
2143      *      hence moving off to a different thread for async processing.
2144      */
2145     private ExecutorService executor;
2146     @Override
2147     public void modeChangeNotify(final Node node, final boolean proactive) {
2148         Callable<Status> modeChangeCallable = new Callable<Status>() {
2149             @Override
2150             public Status call() throws Exception {
2151                 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2152
2153                 List<String> puntAction = new ArrayList<String>();
2154                 puntAction.add(ActionType.CONTROLLER.toString());
2155
2156                 FlowConfig allowARP = new FlowConfig();
2157                 allowARP.setInstallInHw(true);
2158                 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2159                 allowARP.setPriority("1");
2160                 allowARP.setNode(node);
2161                 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2162                         .toUpperCase());
2163                 allowARP.setActions(puntAction);
2164                 defaultConfigs.add(allowARP);
2165
2166                 FlowConfig allowLLDP = new FlowConfig();
2167                 allowLLDP.setInstallInHw(true);
2168                 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2169                 allowLLDP.setPriority("1");
2170                 allowLLDP.setNode(node);
2171                 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2172                         .toUpperCase());
2173                 allowLLDP.setActions(puntAction);
2174                 defaultConfigs.add(allowLLDP);
2175
2176                 List<String> dropAction = new ArrayList<String>();
2177                 dropAction.add(ActionType.DROP.toString());
2178
2179                 FlowConfig dropAllConfig = new FlowConfig();
2180                 dropAllConfig.setInstallInHw(true);
2181                 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2182                         + FlowConfig.INTERNALSTATICFLOWEND);
2183                 dropAllConfig.setPriority("0");
2184                 dropAllConfig.setNode(node);
2185                 dropAllConfig.setActions(dropAction);
2186                 defaultConfigs.add(dropAllConfig);
2187
2188                 log.trace("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2189                 for (FlowConfig fc : defaultConfigs) {
2190                     // check if the frm really needs to act on the notification.
2191                     // this is to check against duplicate notifications
2192                     if(programInternalFlow(proactive, fc)) {
2193                         Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2194                         if (status.isSuccess()) {
2195                             log.trace("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2196                         } else {
2197                             log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2198                                     fc.getName());
2199                         }
2200                     } else {
2201                         log.debug("Got redundant install request for internal flow: {} on node: {}. Request not sent to FRM.", fc.getName(), node);
2202                     }
2203                 }
2204                 return new Status(StatusCode.SUCCESS);
2205             }
2206         };
2207
2208         /*
2209          * Execute the work outside the caller context, this could be an
2210          * expensive operation and we don't want to block the caller for it.
2211          */
2212         this.executor.submit(modeChangeCallable);
2213     }
2214
2215     /**
2216      * Remove from the databases all the flows installed on the node
2217      *
2218      * @param node
2219      */
2220     private void cleanDatabaseForNode(Node node) {
2221         log.trace("Cleaning Flow database for Node {}", node);
2222         if (nodeFlows.containsKey(node)) {
2223             List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2224
2225             for (FlowEntryInstall entry : toRemove) {
2226                 updateSwViews(entry, false);
2227             }
2228         }
2229     }
2230
2231     private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2232         if (nc == null) {
2233             return false;
2234         }
2235
2236         Match match = flow.getMatch();
2237         if (match.isPresent(MatchType.IN_PORT)) {
2238             NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2239             if (matchPort.equals(nc)) {
2240                 return true;
2241             }
2242         }
2243         List<Action> actionsList = flow.getActions();
2244         if (actionsList != null) {
2245             for (Action action : actionsList) {
2246                 if (action instanceof Output) {
2247                     NodeConnector actionPort = ((Output) action).getPort();
2248                     if (actionPort.equals(nc)) {
2249                         return true;
2250                     }
2251                 }
2252             }
2253         }
2254         return false;
2255     }
2256
2257     @Override
2258     public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2259         this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2260     }
2261
2262     @Override
2263     public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2264         boolean updateStaticFlowCluster = false;
2265
2266         switch (type) {
2267         case ADDED:
2268             break;
2269         case CHANGED:
2270             Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2271             if (config != null) {
2272                 switch (config.getValue()) {
2273                 case Config.ADMIN_DOWN:
2274                     log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2275                     updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2276                     break;
2277                 case Config.ADMIN_UP:
2278                     log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2279                     updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2280                     break;
2281                 case Config.ADMIN_UNDEF:
2282                     break;
2283                 default:
2284                 }
2285             }
2286             break;
2287         case REMOVED:
2288             // This is the case where a switch port is removed from the SDN agent space
2289             log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2290             updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2291             break;
2292         default:
2293
2294         }
2295
2296         if (updateStaticFlowCluster) {
2297             refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2298         }
2299     }
2300
2301     /*
2302      * It goes through the static flows configuration, it identifies the ones
2303      * which have the specified node connector as input or output port and
2304      * install them on the network node if they are marked to be installed in
2305      * hardware and their status shows they were not installed yet
2306      */
2307     private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2308         boolean updated = false;
2309         List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2310         for (FlowConfig flowConfig : flowConfigForNode) {
2311             if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2312                 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) {
2313                     Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2314                     if (!status.isSuccess()) {
2315                         flowConfig.setStatus(status.getDescription());
2316                     } else {
2317                         flowConfig.setStatus(StatusCode.SUCCESS.toString());
2318                     }
2319                     updated = true;
2320                 }
2321             }
2322         }
2323         return updated;
2324     }
2325
2326     /*
2327      * Remove from the network node all the flows which have the specified node
2328      * connector as input or output port. If any of the flow entry is a static
2329      * flow, it updates the correspondent configuration.
2330      */
2331     private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2332         boolean updated = false;
2333         List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2334         if (nodeFlowEntries == null) {
2335             return updated;
2336         }
2337         for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2338             if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2339                 Status status = this.removeEntryInternal(fei, true);
2340                 if (!status.isSuccess()) {
2341                     continue;
2342                 }
2343                 /*
2344                  * If the flow entry is a static flow, then update its
2345                  * configuration
2346                  */
2347                 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2348                     FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2349                     if (flowConfig != null) {
2350                         flowConfig.setStatus(PORT_REMOVED);
2351                         updated = true;
2352                     }
2353                 }
2354             }
2355         }
2356         return updated;
2357     }
2358
2359     private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2360         FlowConfig derivedFlow = new FlowConfig(original);
2361         derivedFlow.setDynamic(true);
2362         derivedFlow.setPortGroup(null);
2363         derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2364         derivedFlow.setIngressPort(port + "");
2365         return derivedFlow;
2366     }
2367
2368     private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2369         for (FlowConfig staticFlow : staticFlows.values()) {
2370             if (staticFlow.getPortGroup() == null) {
2371                 continue;
2372             }
2373             if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2374                 for (Short port : data.getPorts()) {
2375                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2376                     addStaticFlowInternal(derivedFlow, false);
2377                 }
2378             }
2379         }
2380     }
2381
2382     private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2383         for (FlowConfig staticFlow : staticFlows.values()) {
2384             if (staticFlow.getPortGroup() == null) {
2385                 continue;
2386             }
2387             if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2388                 for (Short port : data.getPorts()) {
2389                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2390                     removeStaticFlow(derivedFlow);
2391                 }
2392             }
2393         }
2394     }
2395
2396     @Override
2397     public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2398         log.trace("PortGroup Changed for: {} Data: {}", config, portGroupData);
2399         Map<Node, PortGroup> existingData = portGroupData.get(config);
2400         if (existingData != null) {
2401             for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2402                 PortGroup existingPortGroup = existingData.get(entry.getKey());
2403                 if (existingPortGroup == null) {
2404                     if (add) {
2405                         existingData.put(entry.getKey(), entry.getValue());
2406                         addPortGroupFlows(config, entry.getKey(), entry.getValue());
2407                     }
2408                 } else {
2409                     if (add) {
2410                         existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2411                         addPortGroupFlows(config, entry.getKey(), entry.getValue());
2412                     } else {
2413                         existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2414                         removePortGroupFlows(config, entry.getKey(), entry.getValue());
2415                     }
2416                 }
2417             }
2418         } else {
2419             if (add) {
2420                 portGroupData.put(config, data);
2421                 for (Node swid : data.keySet()) {
2422                     addPortGroupFlows(config, swid, data.get(swid));
2423                 }
2424             }
2425         }
2426     }
2427
2428     @Override
2429     public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2430         PortGroupConfig config = portGroupConfigs.get(name);
2431         if (config != null) {
2432             return false;
2433         }
2434
2435         if ((portGroupProvider == null) && !restore) {
2436             return false;
2437         }
2438         if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2439             return false;
2440         }
2441
2442         config = new PortGroupConfig(name, regex);
2443         portGroupConfigs.put(name, config);
2444         if (portGroupProvider != null) {
2445             portGroupProvider.createPortGroupConfig(config);
2446         }
2447         return true;
2448     }
2449
2450     @Override
2451     public boolean delPortGroupConfig(String name) {
2452         PortGroupConfig config = portGroupConfigs.get(name);
2453         if (config == null) {
2454             return false;
2455         }
2456
2457         if (portGroupProvider != null) {
2458             portGroupProvider.deletePortGroupConfig(config);
2459         }
2460         portGroupConfigs.remove(name);
2461         return true;
2462     }
2463
2464     @Override
2465     public Map<String, PortGroupConfig> getPortGroupConfigs() {
2466         return portGroupConfigs;
2467     }
2468
2469     public boolean isPortGroupSupported() {
2470         if (portGroupProvider == null) {
2471             return false;
2472         }
2473         return true;
2474     }
2475
2476     public void setIContainer(IContainer s) {
2477         this.container = s;
2478     }
2479
2480     public void unsetIContainer(IContainer s) {
2481         if (this.container == s) {
2482             this.container = null;
2483         }
2484     }
2485
2486     public void setConfigurationContainerService(IConfigurationContainerService service) {
2487         log.trace("Got configuration service set request {}", service);
2488         this.configurationService = service;
2489     }
2490
2491     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
2492         log.trace("Got configuration service UNset request");
2493         this.configurationService = null;
2494     }
2495
2496     @Override
2497     public PortGroupProvider getPortGroupProvider() {
2498         return portGroupProvider;
2499     }
2500
2501     public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2502         this.portGroupProvider = null;
2503     }
2504
2505     public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2506         this.portGroupProvider = portGroupProvider;
2507         portGroupProvider.registerPortGroupChange(this);
2508         for (PortGroupConfig config : portGroupConfigs.values()) {
2509             portGroupProvider.createPortGroupConfig(config);
2510         }
2511     }
2512
2513     public void setFrmAware(IForwardingRulesManagerAware obj) {
2514         this.frmAware.add(obj);
2515     }
2516
2517     public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2518         this.frmAware.remove(obj);
2519     }
2520
2521     void setClusterContainerService(IClusterContainerServices s) {
2522         log.debug("Cluster Service set");
2523         this.clusterContainerService = s;
2524     }
2525
2526     void unsetClusterContainerService(IClusterContainerServices s) {
2527         if (this.clusterContainerService == s) {
2528             log.debug("Cluster Service removed!");
2529             this.clusterContainerService = null;
2530         }
2531     }
2532
2533     private String getContainerName() {
2534         if (container == null) {
2535             return GlobalConstants.DEFAULT.toString();
2536         }
2537         return container.getName();
2538     }
2539
2540     /**
2541      * Function called by the dependency manager when all the required
2542      * dependencies are satisfied
2543      *
2544      */
2545     void init() {
2546
2547         inContainerMode = false;
2548
2549         if (portGroupProvider != null) {
2550             portGroupProvider.registerPortGroupChange(this);
2551         }
2552
2553         nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
2554         groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
2555
2556         cacheStartup();
2557
2558         /*
2559          * If we are not the first cluster node to come up, do not initialize
2560          * the static flow entries ordinal
2561          */
2562         if (staticFlowsOrdinal.size() == 0) {
2563             staticFlowsOrdinal.put(0, Integer.valueOf(0));
2564         }
2565
2566         pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2567
2568         // Initialize the event handler thread
2569         frmEventHandler = new Thread(new Runnable() {
2570             @Override
2571             public void run() {
2572                 while (!stopping) {
2573                     try {
2574                         final FRMEvent event = pendingEvents.take();
2575                         if (event == null) {
2576                             log.warn("Dequeued null event");
2577                             continue;
2578                         }
2579                         log.trace("Dequeued {} event", event.getClass().getSimpleName());
2580                         if (event instanceof NodeUpdateEvent) {
2581                             NodeUpdateEvent update = (NodeUpdateEvent) event;
2582                             Node node = update.getNode();
2583                             switch (update.getUpdateType()) {
2584                             case ADDED:
2585                                 addStaticFlowsToSwitch(node);
2586                                 break;
2587                             case REMOVED:
2588                                 cleanDatabaseForNode(node);
2589                                 updateStaticFlowConfigsOnNodeDown(node);
2590                                 break;
2591                             default:
2592                             }
2593                         } else if (event instanceof ErrorReportedEvent) {
2594                             ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2595                             processErrorEvent(errEvent);
2596                         } else if (event instanceof WorkOrderEvent) {
2597                             /*
2598                              * Take care of handling the remote Work request
2599                              */
2600                             Runnable r = new Runnable() {
2601                                 @Override
2602                                 public void run() {
2603                                     WorkOrderEvent work = (WorkOrderEvent) event;
2604                                     FlowEntryDistributionOrder fe = work.getFe();
2605                                     if (fe != null) {
2606                                         logsync.trace("Executing the workOrder {}", fe);
2607                                         Status gotStatus = null;
2608                                         FlowEntryInstall feiCurrent = fe.getEntry();
2609                                         FlowEntryInstall feiNew = workOrder.get(fe);
2610                                         switch (fe.getUpType()) {
2611                                         case ADDED:
2612                                             gotStatus = addEntryInHw(feiCurrent, false);
2613                                             break;
2614                                         case CHANGED:
2615                                             gotStatus = modifyEntryInHw(feiCurrent, feiNew, false);
2616                                             break;
2617                                         case REMOVED:
2618                                             gotStatus = removeEntryInHw(feiCurrent, false);
2619                                             break;
2620                                         }
2621                                         // Remove the Order
2622                                         workOrder.remove(fe);
2623                                         logsync.trace(
2624                                                 "The workOrder has been executed and now the status is being returned {}", fe);
2625                                         // Place the status
2626                                         workStatus.put(fe, gotStatus);
2627                                     } else {
2628                                         log.warn("Not expected null WorkOrder", work);
2629                                     }
2630                                 }
2631                             };
2632                             if(executor != null) {
2633                                 executor.execute(r);
2634                             }
2635                         } else if (event instanceof WorkStatusCleanup) {
2636                             /*
2637                              * Take care of handling the remote Work request
2638                              */
2639                             WorkStatusCleanup work = (WorkStatusCleanup) event;
2640                             FlowEntryDistributionOrder fe = work.getFe();
2641                             if (fe != null) {
2642                                 logsync.trace("The workStatus {} is being removed", fe);
2643                                 workStatus.remove(fe);
2644                             } else {
2645                                 log.warn("Not expected null WorkStatus", work);
2646                             }
2647                         }  else if (event instanceof ContainerFlowChangeEvent) {
2648                             /*
2649                              * Whether it is an addition or removal, we have to
2650                              * recompute the merged flows entries taking into
2651                              * account all the current container flows because
2652                              * flow merging is not an injective function
2653                              */
2654                             updateFlowsContainerFlow();
2655                         } else if (event instanceof UpdateIndexDBs) {
2656                             UpdateIndexDBs update = (UpdateIndexDBs)event;
2657                             updateIndexDatabase(update.getFei(), update.isAddition());
2658                         } else {
2659                             log.warn("Dequeued unknown event {}", event.getClass().getSimpleName());
2660                         }
2661                     } catch (InterruptedException e) {
2662                         // clear pending events
2663                         pendingEvents.clear();
2664                     }
2665                 }
2666             }
2667         }, "FRM EventHandler Collector");
2668     }
2669
2670     /**
2671      * Function called by the dependency manager when at least one dependency
2672      * become unsatisfied or when the component is shutting down because for
2673      * example bundle is being stopped.
2674      *
2675      */
2676     void destroy() {
2677         // Interrupt the thread
2678         frmEventHandler.interrupt();
2679         // Clear the pendingEvents queue
2680         pendingEvents.clear();
2681         frmAware.clear();
2682         workMonitor.clear();
2683     }
2684
2685     /**
2686      * Function called by dependency manager after "init ()" is called and after
2687      * the services provided by the class are registered in the service registry
2688      *
2689      */
2690     void start() {
2691         /*
2692          * If running in default container, need to know if controller is in
2693          * container mode
2694          */
2695         if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) {
2696             inContainerMode = containerManager.inContainerMode();
2697         }
2698
2699         // Initialize graceful stop flag
2700         stopping = false;
2701
2702         // Allocate the executor service
2703         this.executor = Executors.newFixedThreadPool(maxPoolSize);
2704
2705         // Start event handler thread
2706         frmEventHandler.start();
2707
2708         // replay the installedSwView data structure to populate
2709         // node flows and group flows
2710         for (FlowEntryInstall fei : installedSwView.values()) {
2711             pendingEvents.offer(new UpdateIndexDBs(fei, true));
2712         }
2713
2714         /*
2715          * Read startup and build database if we are the coordinator
2716          */
2717         loadFlowConfiguration();
2718     }
2719
2720     /**
2721      * Function called by the dependency manager before Container is Stopped and Destroyed.
2722      */
2723     public void containerStop() {
2724         uninstallAllFlowEntries(false);
2725     }
2726
2727     /**
2728      * Function called by the dependency manager before the services exported by
2729      * the component are unregistered, this will be followed by a "destroy ()"
2730      * calls
2731      */
2732     void stop() {
2733         stopping = true;
2734         // Shutdown executor
2735         this.executor.shutdownNow();
2736         // Now walk all the workMonitor and wake up the one sleeping because
2737         // destruction is happening
2738         for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2739             FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2740             task.cancel(true);
2741         }
2742     }
2743
2744     public void setFlowProgrammerService(IFlowProgrammerService service) {
2745         this.programmer = service;
2746     }
2747
2748     public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2749         if (this.programmer == service) {
2750             this.programmer = null;
2751         }
2752     }
2753
2754     public void setSwitchManager(ISwitchManager switchManager) {
2755         this.switchManager = switchManager;
2756     }
2757
2758     public void unsetSwitchManager(ISwitchManager switchManager) {
2759         if (this.switchManager == switchManager) {
2760             this.switchManager = null;
2761         }
2762     }
2763
2764     @Override
2765     public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2766         if (!container.getName().equals(containerName)) {
2767             return;
2768         }
2769     }
2770
2771     @Override
2772     public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2773         if (!container.getName().equals(containerName)) {
2774             return;
2775         }
2776         log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2777                 container.getName(), t, current);
2778         ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2779         pendingEvents.offer(ev);
2780     }
2781
2782     @Override
2783     public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2784         if (!container.getName().equals(containerName)) {
2785             return;
2786         }
2787
2788         boolean updateStaticFlowCluster = false;
2789
2790         switch (t) {
2791         case REMOVED:
2792             log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2793             updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2794             break;
2795         case ADDED:
2796             log.trace("Port {} was added to container: reinstall interested flows", nc);
2797             updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2798
2799             break;
2800         case CHANGED:
2801             break;
2802         default:
2803         }
2804
2805         if (updateStaticFlowCluster) {
2806             refreshClusterStaticFlowsStatus(nc.getNode());
2807         }
2808     }
2809
2810     @Override
2811     public void containerModeUpdated(UpdateType update) {
2812         // Only default container instance reacts on this event
2813         if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2814             return;
2815         }
2816         switch (update) {
2817         case ADDED:
2818             /*
2819              * Controller is moving to container mode. We are in the default
2820              * container context, we need to remove all our non-internal flows
2821              * to prevent any container isolation breakage. We also need to
2822              * preserve our flow so that they can be re-installed if we move
2823              * back to non container mode (no containers).
2824              */
2825             this.inContainerMode = true;
2826             this.uninstallAllFlowEntries(true);
2827             break;
2828         case REMOVED:
2829             this.inContainerMode = false;
2830             this.reinstallAllFlowEntries();
2831             break;
2832         default:
2833             break;
2834         }
2835
2836         // Update our configuration DB
2837         updateStaticFlowConfigsOnContainerModeChange(update);
2838     }
2839
2840     protected abstract class FRMEvent {
2841
2842     }
2843
2844     private class NodeUpdateEvent extends FRMEvent {
2845         private final Node node;
2846         private final UpdateType update;
2847
2848         public NodeUpdateEvent(UpdateType update, Node node) {
2849             this.update = update;
2850             this.node = node;
2851         }
2852
2853         public UpdateType getUpdateType() {
2854             return update;
2855         }
2856
2857         public Node getNode() {
2858             return node;
2859         }
2860     }
2861
2862     private class ErrorReportedEvent extends FRMEvent {
2863         private final long rid;
2864         private final Node node;
2865         private final Object error;
2866
2867         public ErrorReportedEvent(long rid, Node node, Object error) {
2868             this.rid = rid;
2869             this.node = node;
2870             this.error = error;
2871         }
2872
2873         public long getRequestId() {
2874             return rid;
2875         }
2876
2877         public Object getError() {
2878             return error;
2879         }
2880
2881         public Node getNode() {
2882             return node;
2883         }
2884     }
2885
2886     private class WorkOrderEvent extends FRMEvent {
2887         private FlowEntryDistributionOrder fe;
2888         private FlowEntryInstall newEntry;
2889
2890         /**
2891          * @param fe
2892          * @param newEntry
2893          */
2894         WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2895             this.fe = fe;
2896             this.newEntry = newEntry;
2897         }
2898
2899         /**
2900          * @return the fe
2901          */
2902         public FlowEntryDistributionOrder getFe() {
2903             return fe;
2904         }
2905
2906         /**
2907          * @return the newEntry
2908          */
2909         public FlowEntryInstall getNewEntry() {
2910             return newEntry;
2911         }
2912     }
2913     private class ContainerFlowChangeEvent extends FRMEvent {
2914         private final ContainerFlow previous;
2915         private final ContainerFlow current;
2916         private final UpdateType type;
2917
2918         public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2919             this.previous = previous;
2920             this.current = current;
2921             this.type = type;
2922         }
2923
2924         public ContainerFlow getPrevious() {
2925             return this.previous;
2926         }
2927
2928         public ContainerFlow getCurrent() {
2929             return this.current;
2930         }
2931
2932         public UpdateType getType() {
2933             return this.type;
2934         }
2935     }
2936
2937
2938     private class WorkStatusCleanup extends FRMEvent {
2939         private FlowEntryDistributionOrder fe;
2940
2941         /**
2942          * @param fe
2943          */
2944         WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2945             this.fe = fe;
2946         }
2947
2948         /**
2949          * @return the fe
2950          */
2951         public FlowEntryDistributionOrder getFe() {
2952             return fe;
2953         }
2954     }
2955
2956     private class UpdateIndexDBs extends FRMEvent {
2957         private FlowEntryInstall fei;
2958         private boolean add;
2959
2960         /**
2961          *
2962          * @param fei the flow entry which was installed/removed on the netwrok node
2963          * @param update
2964          */
2965         UpdateIndexDBs(FlowEntryInstall fei, boolean add) {
2966             this.fei = fei;
2967             this.add = add;
2968         }
2969
2970
2971         /**
2972          * @return the flowEntryInstall object which was added/removed
2973          * to/from the installed software view cache
2974          */
2975         public FlowEntryInstall getFei() {
2976             return fei;
2977         }
2978
2979         /**
2980          *
2981          * @return whether this was an flow addition or removal
2982          */
2983         public boolean isAddition() {
2984             return add;
2985         }
2986     }
2987
2988     @Override
2989     public Status saveConfiguration() {
2990         return saveConfig();
2991     }
2992
2993     @Override
2994     public void flowRemoved(Node node, Flow flow) {
2995         log.trace("Received flow removed notification on {} for {}", node, flow);
2996
2997         // For flow entry identification, only node, match and priority matter
2998         FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2999         FlowEntryInstall installedEntry = this.installedSwView.get(test);
3000         if (installedEntry == null) {
3001             log.trace("Entry is not known to us");
3002             return;
3003         }
3004
3005         // Update Static flow status
3006         Integer key = 0;
3007         FlowConfig target = null;
3008         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3009             FlowConfig conf = entry.getValue();
3010             if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3011                 key = entry.getKey();
3012                 target = conf;
3013                 break;
3014             }
3015         }
3016         if (target != null) {
3017             // Update Configuration database
3018             if (target.getHardTimeout() != null || target.getIdleTimeout() != null) {
3019                 /*
3020                  * No need for checking if actual values: these strings were
3021                  * validated at configuration creation. Also, after a switch
3022                  * down scenario, no use to reinstall a timed flow. Mark it as
3023                  * "do not install". User can manually toggle it.
3024                  */
3025                 target.toggleInstallation();
3026             }
3027             target.setStatus(StatusCode.GONE.toString());
3028             staticFlows.put(key, target);
3029         }
3030
3031         // Update software views
3032         this.updateSwViews(installedEntry, false);
3033     }
3034
3035     @Override
3036     public void flowErrorReported(Node node, long rid, Object err) {
3037         log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3038         pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3039     }
3040
3041     private void processErrorEvent(ErrorReportedEvent event) {
3042         Node node = event.getNode();
3043         long rid = event.getRequestId();
3044         Object error = event.getError();
3045         String errorString = (error == null) ? "Not provided" : error.toString();
3046         /*
3047          * If this was for a flow install, remove the corresponding entry from
3048          * the software view. If it was a Looking for the rid going through the
3049          * software database. TODO: A more efficient rid <-> FlowEntryInstall
3050          * mapping will have to be added in future
3051          */
3052         FlowEntryInstall target = null;
3053         List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3054         // flowEntryInstallList could be null.
3055         // so check for it.
3056         if(flowEntryInstallList != null) {
3057             for (FlowEntryInstall index : flowEntryInstallList) {
3058                 FlowEntryInstall entry = installedSwView.get(index);
3059                 if(entry != null) {
3060                     if (entry.getRequestId() == rid) {
3061                         target = entry;
3062                         break;
3063                     }
3064                 }
3065             }
3066         }
3067         if (target != null) {
3068             // This was a flow install, update database
3069             this.updateSwViews(target, false);
3070             // also update the config
3071             if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3072                 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3073                 // staticFlowEntry should never be null.
3074                 // the null check is just an extra defensive check.
3075                 if(staticFlowEntry != null) {
3076                     // Modify status and update cluster cache
3077                     log.debug("Updating static flow configuration on async error event");
3078                     String status = String.format("Cannot be installed on node. reason: %s", errorString);
3079                     staticFlowEntry.getValue().setStatus(status);
3080                     refreshClusterStaticFlowsStatus(node);
3081                 }
3082             }
3083         }
3084
3085         // Notify listeners
3086         if (frmAware != null) {
3087             synchronized (frmAware) {
3088                 for (IForwardingRulesManagerAware frma : frmAware) {
3089                     try {
3090                         frma.requestFailed(rid, errorString);
3091                     } catch (Exception e) {
3092                         log.warn("Failed to notify {}", frma);
3093                     }
3094                 }
3095             }
3096         }
3097     }
3098
3099     @Override
3100     public Status solicitStatusResponse(Node node, boolean blocking) {
3101         Status rv = new Status(StatusCode.INTERNALERROR);
3102
3103         if (this.programmer != null) {
3104             if (blocking) {
3105                 rv = programmer.syncSendBarrierMessage(node);
3106             } else {
3107                 rv = programmer.asyncSendBarrierMessage(node);
3108             }
3109         }
3110
3111         return rv;
3112     }
3113
3114     public void unsetIConnectionManager(IConnectionManager s) {
3115         if (s == this.connectionManager) {
3116             this.connectionManager = null;
3117         }
3118     }
3119
3120     public void setIConnectionManager(IConnectionManager s) {
3121         this.connectionManager = s;
3122     }
3123
3124     public void unsetIContainerManager(IContainerManager s) {
3125         if (s == this.containerManager) {
3126             this.containerManager = null;
3127         }
3128     }
3129
3130     public void setIContainerManager(IContainerManager s) {
3131         this.containerManager = s;
3132     }
3133
3134     @Override
3135     public void entryCreated(Object key, String cacheName, boolean originLocal) {
3136         /*
3137          * Do nothing
3138          */
3139     }
3140
3141     @Override
3142     public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3143         /*
3144          * Streamline the updates for the per node and per group index databases
3145          */
3146         if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3147             pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)new_value, true));
3148         }
3149
3150         if (originLocal) {
3151             /*
3152              * Local updates are of no interest
3153              */
3154             return;
3155         }
3156         if (cacheName.equals(WORK_ORDER_CACHE)) {
3157             logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3158             /*
3159              * This is the case of one workOrder becoming available, so we need
3160              * to dispatch the work to the appropriate handler
3161              */
3162             FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3163             FlowEntryInstall fei = fe.getEntry();
3164             if (fei == null) {
3165                 return;
3166             }
3167             Node n = fei.getNode();
3168             if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3169                 logsync.trace("workOrder for fe {} processed locally", fe);
3170                 // I'm the controller in charge for the request, queue it for
3171                 // processing
3172                 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3173             }
3174         } else if (cacheName.equals(WORK_STATUS_CACHE)) {
3175             logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3176             /*
3177              * This is the case of one workOrder being completed and a status
3178              * returned
3179              */
3180             FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3181             /*
3182              * Check if the order was initiated by this controller in that case
3183              * we need to actually look at the status returned
3184              */
3185             if (fe.getRequestorController()
3186                     .equals(clusterContainerService.getMyAddress())) {
3187                 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3188                 if (fet != null) {
3189                     logsync.trace("workStatus response is for us {}", fe);
3190                     // Signal we got the status
3191                     fet.gotStatus(fe, workStatus.get(fe));
3192                     pendingEvents.offer(new WorkStatusCleanup(fe));
3193                 }
3194             }
3195         }
3196     }
3197
3198     @Override
3199     public void entryDeleted(Object key, String cacheName, boolean originLocal) {
3200         /*
3201          * Streamline the updates for the per node and per group index databases
3202          */
3203         if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3204             pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)key, false));
3205         }
3206     }
3207
3208     /**
3209      * {@inheritDoc}
3210      */
3211     @Override
3212     public List<FlowEntry> getFlowEntriesForNode(Node node) {
3213         List<FlowEntry> list = new ArrayList<FlowEntry>();
3214         if (node != null) {
3215             for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
3216                 if (node.equals(entry.getKey().getNode())) {
3217                     list.add(entry.getValue().clone());
3218                 }
3219             }
3220         }
3221         return list;
3222     }
3223
3224     /**
3225      * {@inheritDoc}
3226      */
3227     @Override
3228     public List<FlowEntry> getInstalledFlowEntriesForNode(Node node) {
3229         List<FlowEntry> list = new ArrayList<FlowEntry>();
3230         if (node != null) {
3231             List<FlowEntryInstall> flowEntryInstallList = this.nodeFlows.get(node);
3232             if(flowEntryInstallList != null) {
3233                 for(FlowEntryInstall fi: flowEntryInstallList) {
3234                     list.add(fi.getInstall().clone());
3235                 }
3236             }
3237         }
3238         return list;
3239     }
3240 }