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