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