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