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