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