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