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