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