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