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