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