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