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