Fail toggle flow if port is no longer a part of slice
[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     @Override
2104     public void modeChangeNotify(Node node, boolean proactive) {
2105         List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2106
2107         List<String> puntAction = new ArrayList<String>();
2108         puntAction.add(ActionType.CONTROLLER.toString());
2109
2110         FlowConfig allowARP = new FlowConfig();
2111         allowARP.setInstallInHw(true);
2112         allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2113         allowARP.setPriority("1");
2114         allowARP.setNode(node);
2115         allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2116         allowARP.setActions(puntAction);
2117         defaultConfigs.add(allowARP);
2118
2119         FlowConfig allowLLDP = new FlowConfig();
2120         allowLLDP.setInstallInHw(true);
2121         allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2122         allowLLDP.setPriority("1");
2123         allowLLDP.setNode(node);
2124         allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue()).toUpperCase());
2125         allowLLDP.setActions(puntAction);
2126         defaultConfigs.add(allowLLDP);
2127
2128         List<String> dropAction = new ArrayList<String>();
2129         dropAction.add(ActionType.DROP.toString());
2130
2131         FlowConfig dropAllConfig = new FlowConfig();
2132         dropAllConfig.setInstallInHw(true);
2133         dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop" + FlowConfig.INTERNALSTATICFLOWEND);
2134         dropAllConfig.setPriority("0");
2135         dropAllConfig.setNode(node);
2136         dropAllConfig.setActions(dropAction);
2137         defaultConfigs.add(dropAllConfig);
2138
2139         log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2140         for (FlowConfig fc : defaultConfigs) {
2141             Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2142             if (status.isSuccess()) {
2143                 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2144             } else {
2145                 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"), fc.getName());
2146             }
2147         }
2148     }
2149
2150     /**
2151      * Remove from the databases all the flows installed on the node
2152      *
2153      * @param node
2154      */
2155     private void cleanDatabaseForNode(Node node) {
2156         log.info("Cleaning Flow database for Node {}", node);
2157         if (nodeFlows.containsKey(node)) {
2158             List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2159
2160             for (FlowEntryInstall entry : toRemove) {
2161                 updateLocalDatabase(entry, false);
2162             }
2163         }
2164     }
2165
2166     private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2167         if (nc == null) {
2168             return false;
2169         }
2170
2171         Match match = flow.getMatch();
2172         if (match.isPresent(MatchType.IN_PORT)) {
2173             NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2174             if (matchPort.equals(nc)) {
2175                 return true;
2176             }
2177         }
2178         List<Action> actionsList = flow.getActions();
2179         if (actionsList != null) {
2180             for (Action action : actionsList) {
2181                 if (action instanceof Output) {
2182                     NodeConnector actionPort = ((Output) action).getPort();
2183                     if (actionPort.equals(nc)) {
2184                         return true;
2185                     }
2186                 }
2187             }
2188         }
2189         return false;
2190     }
2191
2192     @Override
2193     public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2194         this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2195     }
2196
2197     @Override
2198     public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2199
2200     }
2201
2202     private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2203         FlowConfig derivedFlow = new FlowConfig(original);
2204         derivedFlow.setDynamic(true);
2205         derivedFlow.setPortGroup(null);
2206         derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2207         derivedFlow.setIngressPort(port + "");
2208         return derivedFlow;
2209     }
2210
2211     private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2212         for (FlowConfig staticFlow : staticFlows.values()) {
2213             if (staticFlow.getPortGroup() == null) {
2214                 continue;
2215             }
2216             if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2217                 for (Short port : data.getPorts()) {
2218                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2219                     addStaticFlowInternal(derivedFlow, false);
2220                 }
2221             }
2222         }
2223     }
2224
2225     private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2226         for (FlowConfig staticFlow : staticFlows.values()) {
2227             if (staticFlow.getPortGroup() == null) {
2228                 continue;
2229             }
2230             if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2231                 for (Short port : data.getPorts()) {
2232                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2233                     removeStaticFlow(derivedFlow);
2234                 }
2235             }
2236         }
2237     }
2238
2239     @Override
2240     public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2241         log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2242         Map<Node, PortGroup> existingData = portGroupData.get(config);
2243         if (existingData != null) {
2244             for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2245                 PortGroup existingPortGroup = existingData.get(entry.getKey());
2246                 if (existingPortGroup == null) {
2247                     if (add) {
2248                         existingData.put(entry.getKey(), entry.getValue());
2249                         addPortGroupFlows(config, entry.getKey(), entry.getValue());
2250                     }
2251                 } else {
2252                     if (add) {
2253                         existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2254                         addPortGroupFlows(config, entry.getKey(), entry.getValue());
2255                     } else {
2256                         existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2257                         removePortGroupFlows(config, entry.getKey(), entry.getValue());
2258                     }
2259                 }
2260             }
2261         } else {
2262             if (add) {
2263                 portGroupData.put(config, data);
2264                 for (Node swid : data.keySet()) {
2265                     addPortGroupFlows(config, swid, data.get(swid));
2266                 }
2267             }
2268         }
2269     }
2270
2271     @Override
2272     public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2273         PortGroupConfig config = portGroupConfigs.get(name);
2274         if (config != null) {
2275             return false;
2276         }
2277
2278         if ((portGroupProvider == null) && !restore) {
2279             return false;
2280         }
2281         if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2282             return false;
2283         }
2284
2285         config = new PortGroupConfig(name, regex);
2286         portGroupConfigs.put(name, config);
2287         if (portGroupProvider != null) {
2288             portGroupProvider.createPortGroupConfig(config);
2289         }
2290         return true;
2291     }
2292
2293     @Override
2294     public boolean delPortGroupConfig(String name) {
2295         PortGroupConfig config = portGroupConfigs.get(name);
2296         if (config == null) {
2297             return false;
2298         }
2299
2300         if (portGroupProvider != null) {
2301             portGroupProvider.deletePortGroupConfig(config);
2302         }
2303         portGroupConfigs.remove(name);
2304         return true;
2305     }
2306
2307     private void usePortGroupConfig(String name) {
2308         PortGroupConfig config = portGroupConfigs.get(name);
2309         if (config == null) {
2310             return;
2311         }
2312         if (portGroupProvider != null) {
2313             Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2314             portGroupData.put(config, data);
2315         }
2316     }
2317
2318     @Override
2319     public Map<String, PortGroupConfig> getPortGroupConfigs() {
2320         return portGroupConfigs;
2321     }
2322
2323     public boolean isPortGroupSupported() {
2324         if (portGroupProvider == null) {
2325             return false;
2326         }
2327         return true;
2328     }
2329
2330     public void setIContainer(IContainer s) {
2331         this.container = s;
2332     }
2333
2334     public void unsetIContainer(IContainer s) {
2335         if (this.container == s) {
2336             this.container = null;
2337         }
2338     }
2339
2340     @Override
2341     public PortGroupProvider getPortGroupProvider() {
2342         return portGroupProvider;
2343     }
2344
2345     public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2346         this.portGroupProvider = null;
2347     }
2348
2349     public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2350         this.portGroupProvider = portGroupProvider;
2351         portGroupProvider.registerPortGroupChange(this);
2352         for (PortGroupConfig config : portGroupConfigs.values()) {
2353             portGroupProvider.createPortGroupConfig(config);
2354         }
2355     }
2356
2357     public void setFrmAware(IForwardingRulesManagerAware obj) {
2358         this.frmAware.add(obj);
2359     }
2360
2361     public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2362         this.frmAware.remove(obj);
2363     }
2364
2365     void setClusterContainerService(IClusterContainerServices s) {
2366         log.debug("Cluster Service set");
2367         this.clusterContainerService = s;
2368     }
2369
2370     void unsetClusterContainerService(IClusterContainerServices s) {
2371         if (this.clusterContainerService == s) {
2372             log.debug("Cluster Service removed!");
2373             this.clusterContainerService = null;
2374         }
2375     }
2376
2377     private String getContainerName() {
2378         if (container == null) {
2379             return GlobalConstants.DEFAULT.toString();
2380         }
2381         return container.getName();
2382     }
2383
2384     /**
2385      * Function called by the dependency manager when all the required
2386      * dependencies are satisfied
2387      *
2388      */
2389     void init() {
2390         frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2391         portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2392
2393         inContainerMode = false;
2394
2395         if (portGroupProvider != null) {
2396             portGroupProvider.registerPortGroupChange(this);
2397         }
2398
2399         cacheStartup();
2400
2401         registerWithOSGIConsole();
2402
2403         /*
2404          * If we are not the first cluster node to come up, do not initialize
2405          * the static flow entries ordinal
2406          */
2407         if (staticFlowsOrdinal.size() == 0) {
2408             staticFlowsOrdinal.put(0, Integer.valueOf(0));
2409         }
2410
2411         pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2412
2413         // Initialize the event handler thread
2414         frmEventHandler = new Thread(new Runnable() {
2415             @Override
2416             public void run() {
2417                 while (!stopping) {
2418                     try {
2419                         FRMEvent event = pendingEvents.take();
2420                         if (event == null) {
2421                             log.warn("Dequeued null event");
2422                             continue;
2423                         }
2424                         if (event instanceof NodeUpdateEvent) {
2425                             NodeUpdateEvent update = (NodeUpdateEvent) event;
2426                             Node node = update.getNode();
2427                             switch (update.getUpdateType()) {
2428                             case ADDED:
2429                                 addStaticFlowsToSwitch(node);
2430                                 break;
2431                             case REMOVED:
2432                                 cleanDatabaseForNode(node);
2433                                 updateStaticFlowConfigsOnNodeDown(node);
2434                                 break;
2435                             default:
2436                             }
2437                         } else if (event instanceof ErrorReportedEvent) {
2438                             ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2439                             processErrorEvent(errEvent);
2440                         } else if (event instanceof WorkOrderEvent) {
2441                             /*
2442                              * Take care of handling the remote Work request
2443                              */
2444                             WorkOrderEvent work = (WorkOrderEvent) event;
2445                             FlowEntryDistributionOrder fe = work.getFe();
2446                             if (fe != null) {
2447                                 logsync.trace("Executing the workOrder {}", fe);
2448                                 Status gotStatus = null;
2449                                 FlowEntryInstall feiCurrent = fe.getEntry();
2450                                 FlowEntryInstall feiNew = workOrder.get(fe.getEntry());
2451                                 switch (fe.getUpType()) {
2452                                 case ADDED:
2453                                     /*
2454                                      * TODO: Not still sure how to handle the
2455                                      * sync entries
2456                                      */
2457                                     gotStatus = addEntriesInternal(feiCurrent, true);
2458                                     break;
2459                                 case CHANGED:
2460                                     gotStatus = modifyEntryInternal(feiCurrent, feiNew, true);
2461                                     break;
2462                                 case REMOVED:
2463                                     gotStatus = removeEntryInternal(feiCurrent, true);
2464                                     break;
2465                                 }
2466                                 // Remove the Order
2467                                 workOrder.remove(fe);
2468                                 logsync.trace(
2469                                         "The workOrder has been executed and now the status is being returned {}", fe);
2470                                 // Place the status
2471                                 workStatus.put(fe, gotStatus);
2472                             } else {
2473                                 log.warn("Not expected null WorkOrder", work);
2474                             }
2475                         } else if (event instanceof WorkStatusCleanup) {
2476                             /*
2477                              * Take care of handling the remote Work request
2478                              */
2479                             WorkStatusCleanup work = (WorkStatusCleanup) event;
2480                             FlowEntryDistributionOrder fe = work.getFe();
2481                             if (fe != null) {
2482                                 logsync.trace("The workStatus {} is being removed", fe);
2483                                 workStatus.remove(fe);
2484                             } else {
2485                                 log.warn("Not expected null WorkStatus", work);
2486                             }
2487                         } else {
2488                             log.warn("Dequeued unknown event {}", event.getClass()
2489                                     .getSimpleName());
2490                         }
2491                     } catch (InterruptedException e) {
2492                         // clear pending events
2493                         pendingEvents.clear();
2494                     }
2495                 }
2496             }
2497         }, "FRM EventHandler Collector");
2498     }
2499
2500     /**
2501      * Function called by the dependency manager when at least one dependency
2502      * become unsatisfied or when the component is shutting down because for
2503      * example bundle is being stopped.
2504      *
2505      */
2506     void destroy() {
2507         // Interrupt the thread
2508         frmEventHandler.interrupt();
2509         // Clear the pendingEvents queue
2510         pendingEvents.clear();
2511         frmAware.clear();
2512         workMonitor.clear();
2513     }
2514
2515     /**
2516      * Function called by dependency manager after "init ()" is called and after
2517      * the services provided by the class are registered in the service registry
2518      *
2519      */
2520     void start() {
2521         // Initialize graceful stop flag
2522         stopping = false;
2523
2524         // Allocate the executor service
2525         this.executor = Executors.newSingleThreadExecutor();
2526
2527         // Start event handler thread
2528         frmEventHandler.start();
2529
2530         /*
2531          * Read startup and build database if we have not already gotten the
2532          * configurations synced from another node
2533          */
2534         if (staticFlows.isEmpty()) {
2535             loadFlowConfiguration();
2536         }
2537     }
2538
2539     /**
2540      * Function called by the dependency manager before the services exported by
2541      * the component are unregistered, this will be followed by a "destroy ()"
2542      * calls
2543      */
2544     void stop() {
2545         stopping = true;
2546         uninstallAllFlowEntries(false);
2547         // Shutdown executor
2548         this.executor.shutdownNow();
2549     }
2550
2551     public void setFlowProgrammerService(IFlowProgrammerService service) {
2552         this.programmer = service;
2553     }
2554
2555     public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2556         if (this.programmer == service) {
2557             this.programmer = null;
2558         }
2559     }
2560
2561     public void setSwitchManager(ISwitchManager switchManager) {
2562         this.switchManager = switchManager;
2563     }
2564
2565     public void unsetSwitchManager(ISwitchManager switchManager) {
2566         if (this.switchManager == switchManager) {
2567             this.switchManager = null;
2568         }
2569     }
2570
2571     @Override
2572     public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2573         if (!container.getName().equals(containerName)) {
2574             return;
2575         }
2576     }
2577
2578     @Override
2579     public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2580         if (!container.getName().equals(containerName)) {
2581             return;
2582         }
2583         log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2584                 container.getName(), t, current);
2585         /*
2586          * Whether it is an addition or removal, we have to recompute the merged
2587          * flows entries taking into account all the current container flows
2588          * because flow merging is not an injective function
2589          */
2590         updateFlowsContainerFlow();
2591     }
2592
2593     @Override
2594     public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2595         if (!container.getName().equals(containerName)) {
2596             return;
2597         }
2598
2599         boolean updateStaticFlowCluster = false;
2600
2601         switch (t) {
2602         case REMOVED:
2603
2604             List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nc.getNode());
2605             if (nodeFlowEntries == null) {
2606                 return;
2607             }
2608             for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2609                 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nc)) {
2610                     Status status = this.removeEntryInternal(fei, true);
2611                     if (!status.isSuccess()) {
2612                         continue;
2613                     }
2614                     /*
2615                      * If the flow entry is a static flow, then update its
2616                      * configuration
2617                      */
2618                     if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2619                         FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2620                         if (flowConfig != null) {
2621                             flowConfig.setStatus(PORTREMOVED);
2622                             updateStaticFlowCluster = true;
2623                         }
2624                     }
2625                 }
2626             }
2627             if (updateStaticFlowCluster) {
2628                 refreshClusterStaticFlowsStatus(nc.getNode());
2629             }
2630             break;
2631         case ADDED:
2632             List<FlowConfig> flowConfigForNode = getStaticFlows(nc.getNode());
2633             for (FlowConfig flowConfig : flowConfigForNode) {
2634                 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nc)) {
2635                     if (flowConfig.installInHw()) {
2636                         Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2637                         if (!status.isSuccess()) {
2638                             flowConfig.setStatus(status.getDescription());
2639                         } else {
2640                             flowConfig.setStatus(SUCCESS);
2641                         }
2642                         updateStaticFlowCluster = true;
2643                     }
2644                 }
2645             }
2646             if (updateStaticFlowCluster) {
2647                 refreshClusterStaticFlowsStatus(nc.getNode());
2648             }
2649             break;
2650         case CHANGED:
2651             break;
2652         default:
2653         }
2654     }
2655
2656     @Override
2657     public void containerModeUpdated(UpdateType update) {
2658         // Only default container instance reacts on this event
2659         if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2660             return;
2661         }
2662         switch (update) {
2663         case ADDED:
2664             /*
2665              * Controller is moving to container mode. We are in the default
2666              * container context, we need to remove all our non-internal flows
2667              * to prevent any container isolation breakage. We also need to
2668              * preserve our flow so that they can be re-installed if we move
2669              * back to non container mode (no containers).
2670              */
2671             this.inContainerMode = true;
2672             this.uninstallAllFlowEntries(true);
2673             break;
2674         case REMOVED:
2675             this.inContainerMode = false;
2676             this.reinstallAllFlowEntries();
2677             break;
2678         default:
2679         }
2680
2681         // Update our configuration DB
2682         updateStaticFlowConfigsOnContainerModeChange(update);
2683     }
2684
2685     protected abstract class FRMEvent {
2686
2687     }
2688
2689     private class NodeUpdateEvent extends FRMEvent {
2690         private final Node node;
2691         private final UpdateType update;
2692
2693         public NodeUpdateEvent(UpdateType update, Node node) {
2694             this.update = update;
2695             this.node = node;
2696         }
2697
2698         public UpdateType getUpdateType() {
2699             return update;
2700         }
2701
2702         public Node getNode() {
2703             return node;
2704         }
2705     }
2706
2707     private class ErrorReportedEvent extends FRMEvent {
2708         private final long rid;
2709         private final Node node;
2710         private final Object error;
2711
2712         public ErrorReportedEvent(long rid, Node node, Object error) {
2713             this.rid = rid;
2714             this.node = node;
2715             this.error = error;
2716         }
2717
2718         public long getRequestId() {
2719             return rid;
2720         }
2721
2722         public Object getError() {
2723             return error;
2724         }
2725
2726         public Node getNode() {
2727             return node;
2728         }
2729     }
2730
2731     private class WorkOrderEvent extends FRMEvent {
2732         private FlowEntryDistributionOrder fe;
2733         private FlowEntryInstall newEntry;
2734
2735         /**
2736          * @param fe
2737          * @param newEntry
2738          */
2739         WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2740             this.fe = fe;
2741             this.newEntry = newEntry;
2742         }
2743
2744         /**
2745          * @return the fe
2746          */
2747         public FlowEntryDistributionOrder getFe() {
2748             return fe;
2749         }
2750
2751         /**
2752          * @return the newEntry
2753          */
2754         public FlowEntryInstall getNewEntry() {
2755             return newEntry;
2756         }
2757     }
2758
2759     private class WorkStatusCleanup extends FRMEvent {
2760         private FlowEntryDistributionOrder fe;
2761
2762         /**
2763          * @param fe
2764          */
2765         WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2766             this.fe = fe;
2767         }
2768
2769         /**
2770          * @return the fe
2771          */
2772         public FlowEntryDistributionOrder getFe() {
2773             return fe;
2774         }
2775     }
2776
2777     /*
2778      * OSGI COMMANDS
2779      */
2780     @Override
2781     public String getHelp() {
2782         StringBuffer help = new StringBuffer();
2783         help.append("---FRM Matrix Application---\n");
2784         help.append("\t printMatrixData        - Prints the Matrix Configs\n");
2785         help.append("\t addMatrixConfig <name> <regex>\n");
2786         help.append("\t delMatrixConfig <name>\n");
2787         help.append("\t useMatrixConfig <name>\n");
2788         return help.toString();
2789     }
2790
2791     public void _printMatrixData(CommandInterpreter ci) {
2792         ci.println("Configs : ");
2793         ci.println("---------");
2794         ci.println(portGroupConfigs);
2795
2796         ci.println("Data : ");
2797         ci.println("------");
2798         ci.println(portGroupData);
2799     }
2800
2801     public void _addMatrixConfig(CommandInterpreter ci) {
2802         String name = ci.nextArgument();
2803         String regex = ci.nextArgument();
2804         addPortGroupConfig(name, regex, false);
2805     }
2806
2807     public void _delMatrixConfig(CommandInterpreter ci) {
2808         String name = ci.nextArgument();
2809         delPortGroupConfig(name);
2810     }
2811
2812     public void _useMatrixConfig(CommandInterpreter ci) {
2813         String name = ci.nextArgument();
2814         usePortGroupConfig(name);
2815     }
2816
2817     public void _arpPunt(CommandInterpreter ci) {
2818         String switchId = ci.nextArgument();
2819         long swid = HexEncode.stringToLong(switchId);
2820         Node node = NodeCreator.createOFNode(swid);
2821         installImplicitARPReplyPunt(node);
2822     }
2823
2824     public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2825         Node node = null;
2826         String nodeId = ci.nextArgument();
2827         if (nodeId == null) {
2828             ci.print("Node id not specified");
2829             return;
2830         }
2831         try {
2832             node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2833         } catch (NumberFormatException e) {
2834             ci.print("Node id not a number");
2835             return;
2836         }
2837         ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2838     }
2839
2840     public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2841         Node node = null;
2842         String nodeId = ci.nextArgument();
2843         if (nodeId == null) {
2844             ci.print("Node id not specified");
2845             return;
2846         }
2847         try {
2848             node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2849         } catch (NumberFormatException e) {
2850             ci.print("Node id not a number");
2851             return;
2852         }
2853         ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2854     }
2855
2856     private Flow getSampleFlow(Node node) throws UnknownHostException {
2857         NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2858         NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2859         byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2860         byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2861         InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2862         InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2863         InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2864         InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2865         short ethertype = EtherTypes.IPv4.shortValue();
2866         short vlan = (short) 27;
2867         byte vlanPr = 3;
2868         Byte tos = 4;
2869         byte proto = IPProtocols.TCP.byteValue();
2870         short src = (short) 55000;
2871         short dst = 80;
2872
2873         /*
2874          * Create a SAL Flow aFlow
2875          */
2876         Match match = new Match();
2877         match.setField(MatchType.IN_PORT, port);
2878         match.setField(MatchType.DL_SRC, srcMac);
2879         match.setField(MatchType.DL_DST, dstMac);
2880         match.setField(MatchType.DL_TYPE, ethertype);
2881         match.setField(MatchType.DL_VLAN, vlan);
2882         match.setField(MatchType.DL_VLAN_PR, vlanPr);
2883         match.setField(MatchType.NW_SRC, srcIP, ipMask);
2884         match.setField(MatchType.NW_DST, dstIP, ipMask2);
2885         match.setField(MatchType.NW_TOS, tos);
2886         match.setField(MatchType.NW_PROTO, proto);
2887         match.setField(MatchType.TP_SRC, src);
2888         match.setField(MatchType.TP_DST, dst);
2889
2890         List<Action> actions = new ArrayList<Action>();
2891         actions.add(new Output(oport));
2892         actions.add(new PopVlan());
2893         actions.add(new Flood());
2894         actions.add(new Controller());
2895         return new Flow(match, actions);
2896     }
2897
2898     @Override
2899     public Status saveConfiguration() {
2900         return saveConfig();
2901     }
2902
2903     public void _frmNodeFlows(CommandInterpreter ci) {
2904         String nodeId = ci.nextArgument();
2905         Node node = Node.fromString(nodeId);
2906         if (node == null) {
2907             ci.println("frmNodeFlows <node> [verbose]");
2908             return;
2909         }
2910         boolean verbose = false;
2911         String verboseCheck = ci.nextArgument();
2912         if (verboseCheck != null) {
2913             verbose = verboseCheck.equals("true");
2914         }
2915
2916         if (!nodeFlows.containsKey(node)) {
2917             return;
2918         }
2919         // Dump per node database
2920         for (FlowEntryInstall entry : nodeFlows.get(node)) {
2921             if (!verbose) {
2922                 ci.println(node + " " + installedSwView.get(entry).getFlowName());
2923             } else {
2924                 ci.println(node + " " + installedSwView.get(entry).toString());
2925             }
2926         }
2927     }
2928
2929     public void _frmGroupFlows(CommandInterpreter ci) {
2930         String group = ci.nextArgument();
2931         if (group == null) {
2932             ci.println("frmGroupFlows <group> [verbose]");
2933             return;
2934         }
2935         boolean verbose = false;
2936         String verboseCheck = ci.nextArgument();
2937         if (verboseCheck != null) {
2938             verbose = verboseCheck.equalsIgnoreCase("true");
2939         }
2940
2941         if (!groupFlows.containsKey(group)) {
2942             return;
2943         }
2944         // Dump per node database
2945         ci.println("Group " + group + ":\n");
2946         for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
2947             if (!verbose) {
2948                 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
2949             } else {
2950                 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
2951             }
2952         }
2953     }
2954
2955     @Override
2956     public void flowRemoved(Node node, Flow flow) {
2957         log.trace("Received flow removed notification on {} for {}", node, flow);
2958
2959         // For flow entry identification, only node, match and priority matter
2960         FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2961         FlowEntryInstall installedEntry = this.installedSwView.get(test);
2962         if (installedEntry == null) {
2963             log.trace("Entry is not known to us");
2964             return;
2965         }
2966
2967         // Update Static flow status
2968         Integer key = 0;
2969         FlowConfig target = null;
2970         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2971             FlowConfig conf = entry.getValue();
2972             if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
2973                 key = entry.getKey();
2974                 target = conf;
2975                 break;
2976             }
2977         }
2978         if (target != null) {
2979             // Update Configuration database
2980             target.toggleInstallation();
2981             target.setStatus(SUCCESS);
2982             staticFlows.put(key, target);
2983         }
2984
2985         // Update software views
2986         this.updateLocalDatabase(installedEntry, false);
2987     }
2988
2989     @Override
2990     public void flowErrorReported(Node node, long rid, Object err) {
2991         log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
2992         pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
2993     }
2994
2995     private void processErrorEvent(ErrorReportedEvent event) {
2996         Node node = event.getNode();
2997         long rid = event.getRequestId();
2998         Object error = event.getError();
2999         String errorString = (error == null) ? "Not provided" : error.toString();
3000         /*
3001          * If this was for a flow install, remove the corresponding entry from
3002          * the software view. If it was a Looking for the rid going through the
3003          * software database. TODO: A more efficient rid <-> FlowEntryInstall
3004          * mapping will have to be added in future
3005          */
3006         FlowEntryInstall target = null;
3007         for (FlowEntryInstall index : nodeFlows.get(node)) {
3008             FlowEntryInstall entry = installedSwView.get(index);
3009             if (entry.getRequestId() == rid) {
3010                 target = entry;
3011                 break;
3012             }
3013         }
3014         if (target != null) {
3015             // This was a flow install, update database
3016             this.updateLocalDatabase(target, false);
3017         }
3018
3019         // Notify listeners
3020         if (frmAware != null) {
3021             synchronized (frmAware) {
3022                 for (IForwardingRulesManagerAware frma : frmAware) {
3023                     try {
3024                         frma.requestFailed(rid, errorString);
3025                     } catch (Exception e) {
3026                         log.warn("Failed to notify {}", frma);
3027                     }
3028                 }
3029             }
3030         }
3031     }
3032
3033     @Override
3034     public Status solicitStatusResponse(Node node, boolean blocking) {
3035         Status rv = new Status(StatusCode.INTERNALERROR);
3036
3037         if (this.programmer != null) {
3038             if (blocking) {
3039                 rv = programmer.syncSendBarrierMessage(node);
3040             } else {
3041                 rv = programmer.asyncSendBarrierMessage(node);
3042             }
3043         }
3044
3045         return rv;
3046     }
3047
3048     public void unsetIConnectionManager(IConnectionManager s) {
3049         if (s == this.connectionManager) {
3050             this.connectionManager = null;
3051         }
3052     }
3053
3054     public void setIConnectionManager(IConnectionManager s) {
3055         this.connectionManager = s;
3056     }
3057
3058     @Override
3059     public void entryCreated(Object key, String cacheName, boolean originLocal) {
3060         /*
3061          * Do nothing
3062          */
3063     }
3064
3065     @Override
3066     public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3067         if (originLocal) {
3068             /*
3069              * Local updates are of no interest
3070              */
3071             return;
3072         }
3073         if (cacheName.equals(WORKORDERCACHE)) {
3074             logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3075             /*
3076              * This is the case of one workOrder becoming available, so we need
3077              * to dispatch the work to the appropriate handler
3078              */
3079             FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3080             FlowEntryInstall fei = fe.getEntry();
3081             if (fei == null) {
3082                 return;
3083             }
3084             Node n = fei.getNode();
3085             if (connectionManager.isLocal(n)) {
3086                 logsync.trace("workOrder for fe {} processed locally", fe);
3087                 // I'm the controller in charge for the request, queue it for
3088                 // processing
3089                 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3090             }
3091         } else if (cacheName.equals(WORKSTATUSCACHE)) {
3092             logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3093             /*
3094              * This is the case of one workOrder being completed and a status
3095              * returned
3096              */
3097             FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3098             /*
3099              * Check if the order was initiated by this controller in that case
3100              * we need to actually look at the status returned
3101              */
3102             if (fe.getRequestorController()
3103                     .equals(clusterContainerService.getMyAddress())) {
3104                 FlowEntryDistributionOrderFutureTask fet = workMonitor.get(fe);
3105                 if (fet != null) {
3106                     logsync.trace("workStatus response is for us {}", fe);
3107                     // Signal we got the status
3108                     fet.gotStatus(fe, workStatus.get(fe));
3109                     pendingEvents.offer(new WorkStatusCleanup(fe));
3110                 }
3111             }
3112         }
3113     }
3114
3115     @Override
3116     public void entryDeleted(Object key, String cacheName, boolean originLocal) {
3117         /*
3118          * Do nothing
3119          */
3120     }
3121 }