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