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