Redirecting Caught and Uncaught Exceptions to OSGI Console and Log File
[controller.git] / opendaylight / forwardingrulesmanager / src / main / java / org / opendaylight / controller / forwardingrulesmanager / internal / ForwardingRulesManagerImpl.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.Date;
19 import java.util.EnumSet;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29
30 import org.eclipse.osgi.framework.console.CommandInterpreter;
31 import org.eclipse.osgi.framework.console.CommandProvider;
32 import org.opendaylight.controller.clustering.services.CacheConfigException;
33 import org.opendaylight.controller.clustering.services.CacheExistException;
34 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
35 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
36 import org.opendaylight.controller.clustering.services.IClusterServices;
37 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
38 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
39 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
40 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
41 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
42 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
43 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
44 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
45 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
46 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
47 import org.opendaylight.controller.hosttracker.IfIptoHost;
48 import org.opendaylight.controller.sal.action.Action;
49 import org.opendaylight.controller.sal.action.ActionType;
50 import org.opendaylight.controller.sal.action.Controller;
51 import org.opendaylight.controller.sal.action.Flood;
52 import org.opendaylight.controller.sal.action.Output;
53 import org.opendaylight.controller.sal.action.PopVlan;
54 import org.opendaylight.controller.sal.core.ContainerFlow;
55 import org.opendaylight.controller.sal.core.IContainer;
56 import org.opendaylight.controller.sal.core.IContainerListener;
57 import org.opendaylight.controller.sal.core.Node;
58 import org.opendaylight.controller.sal.core.NodeConnector;
59 import org.opendaylight.controller.sal.core.Property;
60 import org.opendaylight.controller.sal.core.UpdateType;
61 import org.opendaylight.controller.sal.flowprogrammer.Flow;
62 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
63 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
64 import org.opendaylight.controller.sal.match.Match;
65 import org.opendaylight.controller.sal.match.MatchType;
66 import org.opendaylight.controller.sal.utils.StatusCode;
67 import org.opendaylight.controller.sal.utils.EtherTypes;
68 import org.opendaylight.controller.sal.utils.GlobalConstants;
69 import org.opendaylight.controller.sal.utils.HexEncode;
70 import org.opendaylight.controller.sal.utils.IObjectReader;
71 import org.opendaylight.controller.sal.utils.IPProtocols;
72 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
73 import org.opendaylight.controller.sal.utils.NodeCreator;
74 import org.opendaylight.controller.sal.utils.ObjectReader;
75 import org.opendaylight.controller.sal.utils.ObjectWriter;
76 import org.opendaylight.controller.sal.utils.Status;
77 import org.opendaylight.controller.switchmanager.IInventoryListener;
78 import org.opendaylight.controller.switchmanager.ISwitchManager;
79 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
80 import org.opendaylight.controller.switchmanager.Subnet;
81 import org.osgi.framework.BundleContext;
82 import org.osgi.framework.FrameworkUtil;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 /**
87  * Class that manages forwarding rule installation and removal per container of
88  * the network. It also maintains the central repository of all the forwarding
89  * rules installed on the network nodes.
90  */
91 public class ForwardingRulesManagerImpl implements IForwardingRulesManager,
92         PortGroupChangeListener, IContainerListener, ISwitchManagerAware,
93         IConfigurationContainerAware, IInventoryListener, IObjectReader,
94         ICacheUpdateAware<Long, String>, CommandProvider,
95         IFlowProgrammerListener {
96     private static final String SAVE = "Save";
97     private static final String NODEDOWN = "Node is Down";
98     private static final Logger log = LoggerFactory
99             .getLogger(ForwardingRulesManagerImpl.class);
100     private Map<Long, String> flowsSaveEvent;
101     private String frmFileName;
102     private String portGroupFileName;
103     private ConcurrentMap<Integer, FlowConfig> staticFlows;
104     private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
105     private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
106     private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
107     private ConcurrentMap<String, Object> TSPolicies;
108     private boolean inContainerMode; // being used by default instance only
109     /*
110      * Flow database. It's the software view of what was installed on the
111      * switch. It is indexed by node. For convenience a version indexed by group
112      * name is also maintained. The core element is a class which contains the
113      * flow entry pushed by the functional modules and the respective container
114      * flow merged version. In absence of container flows, the two flow entries
115      * are the same.
116      */
117     private ConcurrentMap<Node, Set<FlowEntryInstall>> nodeFlows;
118     private ConcurrentMap<String, Set<FlowEntryInstall>> groupFlows;
119     /*
120      * Inactive flow list. This is for the global instance of FRM It will
121      * contain all the flow entries which were installed on the global container
122      * when the first container is created.
123      */
124     private List<FlowEntry> inactiveFlows;
125
126     private IfIptoHost hostFinder;
127     private IContainer container;
128     private Set<IForwardingRulesManagerAware> frmAware;
129     private PortGroupProvider portGroupProvider;
130     private IFlowProgrammerService programmer;
131     private IClusterContainerServices clusterContainerService = null;
132     private ISwitchManager switchManager;
133
134     /**
135      * Adds a flow entry onto the network node It runs various validity checks
136      * and derive the final container flows merged entries that will be
137      * attempted to be installed
138      * 
139      * @param flowEntry
140      *            the original flow entry application requested to add
141      * @return
142      */
143     private Status addEntry(FlowEntry flowEntry) {
144         // Sanity Check
145         if (flowEntry == null || flowEntry.getNode() == null) {
146             String msg = "Invalid FlowEntry";
147             log.warn(msg + ": " + flowEntry);
148             return new Status(StatusCode.NOTACCEPTABLE, msg);
149         }
150
151         /*
152          * Derive the container flow merged entries to install In presence of N
153          * container flows, we may end up with N different entries to install...
154          */
155         List<FlowEntryInstall> toInstallList = deriveInstallEntries(
156                 flowEntry.clone(), container.getContainerFlows());
157
158         // Container Flow conflict Check
159         if (toInstallList.isEmpty()) {
160             String msg = "Flow Entry conflicts with all Container Flows";
161             log.warn(msg);
162             return new Status(StatusCode.CONFLICT, msg);
163         }
164
165         // Derive the list of entries good to be installed
166         List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
167         for (FlowEntryInstall entry : toInstallList) {
168             // Conflict Check: Verify new entry would not overwrite existing
169             // ones
170             if (findMatch(entry.getInstall(), false) != null) {
171                 log.warn("Operation Rejected: A flow with same match "
172                         + "and priority exists on the target node");
173                 log.trace("Aborting to install " + entry);
174                 continue;
175             }
176             toInstallSafe.add(entry);
177         }
178
179         // Declare failure if all the container flow merged entries clash with
180         // existing entries
181         if (toInstallSafe.size() == 0) {
182             String msg = "A flow with same match and priority exists "
183                     + "on the target node";
184             log.warn(msg);
185             return new Status(StatusCode.CONFLICT, msg);
186         }
187
188         // Try to install an entry at the time
189         Status error = new Status(null, null);
190         boolean oneSucceded = false;
191         for (FlowEntryInstall installEntry : toInstallList) {
192
193             // Install and update database
194             Status ret = addEntriesInternal(installEntry);
195
196             if (ret.isSuccess()) {
197                 oneSucceded = true;
198             } else {
199                 error = ret;
200                 log.warn("Failed to install the entry: " + ret.getDescription());
201             }
202         }
203
204         return (oneSucceded) ? new Status(StatusCode.SUCCESS, null) : error;
205     }
206
207     /**
208      * Given a flow entry and the list of container flows, it returns the list
209      * of container flow merged flow entries good to be installed on this
210      * container. If the list of container flows is null or empty, the install
211      * entry list will contain only one entry, the original flow entry. If the
212      * flow entry is congruent with all the N container flows, then the output
213      * install entry list will contain N entries. If the output list is empty,
214      * it means the passed flow entry conflicts with all the container flows.
215      * 
216      * @param cFlowList
217      *            The list of container flows
218      * @return the list of container flow merged entries good to be installed on
219      *         this container
220      */
221     private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request,
222             List<ContainerFlow> cFlowList) {
223         List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(
224                 1);
225
226         if (container.getContainerFlows() == null
227                 || container.getContainerFlows().isEmpty()) {
228             // No container flows => entry good to be installed unchanged
229             toInstallList.add(new FlowEntryInstall(request.clone(), null));
230         } else {
231             // Create the list of entries to be installed. If the flow entry is
232             // not congruent with any container flow, no install entries will be
233             // created
234             for (ContainerFlow cFlow : container.getContainerFlows()) {
235                 if (cFlow.allowsFlow(request.getFlow())) {
236                     toInstallList.add(new FlowEntryInstall(request.clone(),
237                             cFlow));
238                 }
239             }
240         }
241         return toInstallList;
242     }
243
244     /**
245      * Modify a flow entry with a new one It runs various validity check and
246      * derive the final container flows merged flow entries to work with
247      * 
248      * @param currentFlowEntry
249      * @param newFlowEntry
250      * @return Success or error string
251      */
252     private Status modifyEntry(FlowEntry currentFlowEntry,
253             FlowEntry newFlowEntry) {
254         Status retExt;
255
256         // Sanity checks
257         if (currentFlowEntry == null || currentFlowEntry.getNode() == null
258                 || newFlowEntry == null || newFlowEntry.getNode() == null) {
259             String msg = "Modify: Invalid FlowEntry";
260             log.warn(msg + ": {} or {} ", currentFlowEntry, newFlowEntry);
261             return new Status(StatusCode.NOTACCEPTABLE, msg);
262         }
263         if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
264                 || !currentFlowEntry.getFlowName().equals(
265                         newFlowEntry.getFlowName())) {
266             String msg = "Modify: Incompatible Flow Entries";
267             log.warn(msg + ": {} and {}", currentFlowEntry, newFlowEntry);
268             return new Status(StatusCode.NOTACCEPTABLE, msg);
269         }
270
271         // Equality Check
272         if (currentFlowEntry.equals(newFlowEntry)) {
273             String msg = "Modify skipped as flows are the same";
274             log.debug(msg + ": " + currentFlowEntry + " and " + newFlowEntry);
275             return new Status(StatusCode.SUCCESS, msg);
276         }
277
278         // Conflict Check: Verify the new entry would not conflict with another
279         // existing one
280         // This is a loose check on the previous original flow entry requests.
281         // No check
282         // on the container flow merged flow entries (if any) yet
283         FlowEntryInstall sameMatchOriginalEntry = findMatch(newFlowEntry, true);
284         if (sameMatchOriginalEntry != null
285                 && !sameMatchOriginalEntry.getOriginal().equals(
286                         currentFlowEntry)) {
287             String msg = "Operation Rejected: Another flow with same match "
288                     + "and priority exists on the target node";
289             log.warn(msg);
290             return new Status(StatusCode.CONFLICT, msg);
291         }
292
293         // Derive the installed and toInstall entries
294         List<FlowEntryInstall> installedList = deriveInstallEntries(
295                 currentFlowEntry.clone(), container.getContainerFlows());
296         List<FlowEntryInstall> toInstallList = deriveInstallEntries(
297                 newFlowEntry.clone(), container.getContainerFlows());
298
299         if (toInstallList.isEmpty()) {
300             String msg = "Modify Operation Rejected: The new entry "
301                     + "conflicts with all the container flows";
302             log.warn(msg);
303             return new Status(StatusCode.CONFLICT, msg);
304         }
305
306         /*
307          * If the two list sizes differ, it means the new flow entry does not
308          * satisfy the same number of container flows the current entry does.
309          * This is only possible when the new entry and current entry have
310          * different match. In this scenario the modification would ultimately
311          * be handled as a remove and add operations in the protocol plugin.
312          * 
313          * Also, if any of the new flow entries would clash with an existing
314          * one, we cannot proceed with the modify operation, because it would
315          * fail for some entries and leave stale entries on the network node.
316          * Modify path can be taken only if it can be performed completely, for
317          * all entries.
318          * 
319          * So, for the above two cases, to simplify, let's decouple the modify
320          * in: 1) remove current entries 2) install new entries
321          */
322         boolean decouple = false;
323         if (installedList.size() != toInstallList.size()) {
324             log.info("Modify: New flow entry does not satisfy the same "
325                     + "number of container flows as the original entry does");
326             decouple = true;
327         }
328         List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
329         for (FlowEntryInstall installEntry : toInstallList) {
330             // Conflict Check: Verify the new entry would not overwrite another
331             // existing one
332             FlowEntryInstall sameMatchEntry = findMatch(
333                     installEntry.getInstall(), false);
334             if (sameMatchEntry != null
335                     && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
336                 log.info("Modify: new container flow merged flow entry "
337                         + "clashes with existing flow");
338                 decouple = true;
339             } else {
340                 toInstallSafe.add(installEntry);
341             }
342         }
343
344         if (decouple) {
345             // Remove current entries
346             for (FlowEntryInstall currEntry : installedList) {
347                 this.removeEntryInternal(currEntry);
348             }
349             // Install new entries
350             for (FlowEntryInstall newEntry : toInstallSafe) {
351                 this.addEntriesInternal(newEntry);
352             }
353         } else {
354             /*
355              * The two list have the same size and the entries to install do not
356              * clash with any existing flow on the network node. We assume here
357              * (and might be wrong) that the same container flows that were
358              * satisfied by the current entries are the same that are satisfied
359              * by the new entries. Let's take the risk for now.
360              * 
361              * Note: modification has to be complete. If any entry modification
362              * fails, we need to stop, restore the already modified entries, and
363              * declare failure.
364              */
365             Status retModify;
366             int i = 0;
367             int size = toInstallList.size();
368             while (i < size) {
369                 // Modify and update database
370                 retModify = modifyEntryInternal(installedList.get(i),
371                         toInstallList.get(i));
372                 if (retModify.isSuccess()) {
373                     i++;
374                 } else {
375                     break;
376                 }
377             }
378             // Check if uncompleted modify
379             if (i < size) {
380                 log.warn("Unable to perform a complete modify for all "
381                         + "the container flows merged entries");
382                 // Restore original entries
383                 int j = 0;
384                 while (j < i) {
385                     log.info("Attempting to restore initial entries");
386                     retExt = modifyEntryInternal(toInstallList.get(i),
387                             installedList.get(i));
388                     if (retExt.isSuccess()) {
389                         j++;
390                     } else {
391                         break;
392                     }
393                 }
394                 // Fatal error, recovery failed
395                 if (j < i) {
396                     String msg = "Flow recovery failed ! Unrecoverable Error";
397                     log.error(msg);
398                     return new Status(StatusCode.INTERNALERROR, msg);
399                 }
400             }
401         }
402         return new Status(StatusCode.SUCCESS, null);
403     }
404
405     /**
406      * This is the function that modifies the final container flows merged
407      * entries on the network node and update the database. It expects that all
408      * the validity checks are passed
409      * 
410      * @param currentEntries
411      * @param newEntries
412      * @return
413      */
414     private Status modifyEntryInternal(FlowEntryInstall currentEntries,
415             FlowEntryInstall newEntries) {
416         // Modify the flow on the network node
417         Status status = programmer.modifyFlow(currentEntries.getNode(),
418                 currentEntries.getInstall().getFlow(), newEntries.getInstall()
419                         .getFlow());
420
421         if (!status.isSuccess()) {
422             log.warn("SDN Plugin failed to program the flow: "
423                     + status.getDescription());
424             return status;
425         }
426
427         log.trace("Modified {} => {}", currentEntries.getInstall(),
428                 newEntries.getInstall());
429
430         // Update DB
431         updateLocalDatabase(currentEntries, false);
432         updateLocalDatabase(newEntries, true);
433
434         return status;
435     }
436
437     /**
438      * Remove a flow entry. If the entry is not present in the software view
439      * (entry or node not present), it return successfully
440      * 
441      * @param flowEntry
442      * @return
443      */
444     private Status removeEntry(FlowEntry flowEntry) {
445         Status error = new Status(null, null);
446
447         // Sanity Check
448         if (flowEntry == null || flowEntry.getNode() == null) {
449             String msg = "Invalid FlowEntry";
450             log.warn(msg + ": " + flowEntry);
451             return new Status(StatusCode.NOTACCEPTABLE, msg);
452         }
453
454         // Derive the container flows merged installed entries
455         List<FlowEntryInstall> installedList = deriveInstallEntries(
456                 flowEntry.clone(), container.getContainerFlows());
457
458         Set<FlowEntryInstall> flowsOnNode = nodeFlows.get(flowEntry.getNode());
459         boolean atLeastOneRemoved = false;
460         for (FlowEntryInstall entry : installedList) {
461             if (flowsOnNode == null) {
462                 String msg = "Removal skipped (Node down or Flow not on Node)";
463                 log.debug(msg + " for flow entry " + flowEntry);
464                 return new Status(StatusCode.SUCCESS, msg);
465             }
466             if (!flowsOnNode.contains(entry)) {
467                 log.debug("Removal skipped (not present in software view) "
468                         + "for flow entry " + flowEntry);
469
470                 if (installedList.size() == 1) {
471                     // If we had only one entry to remove, we are done
472                     return new Status(StatusCode.SUCCESS, null);
473                 } else {
474                     continue;
475                 }
476             }
477
478             // Remove and update DB
479             Status ret = removeEntryInternal(entry);
480
481             if (!ret.isSuccess()) {
482                 error = ret;
483                 log.warn("Failed to remove the entry: " + ret.getDescription());
484                 if (installedList.size() == 1) {
485                     // If we had only one entry to remove, this is fatal failure
486                     return error;
487                 }
488             } else {
489                 atLeastOneRemoved = true;
490             }
491         }
492
493         /*
494          * No worries if full removal failed. Consistency checker will take care
495          * of removing the stale entries later, or adjusting the software
496          * database if not in sync with hardware
497          */
498         return (atLeastOneRemoved) ? new Status(StatusCode.SUCCESS, null)
499                 : error;
500     }
501
502     /**
503      * This is the function that removes the final container flows merged entry
504      * from the network node and update the database. It expects that all the
505      * validity checks are passed
506      * 
507      * @param entry
508      *            the FlowEntryInstall
509      * @return "Success" or error string
510      */
511     private Status removeEntryInternal(FlowEntryInstall entry) {
512         // Mark the entry to be deleted (for CC just in case we fail)
513         entry.toBeDeleted();
514
515         // Remove from node
516         Status status = programmer.removeFlow(entry.getNode(), entry
517                 .getInstall().getFlow());
518
519         if (!status.isSuccess()) {
520             log.warn("SDN Plugin failed to remove the flow: "
521                     + status.getDescription());
522             return status;
523         }
524         log.trace("Removed  {}", entry.getInstall());
525
526         // Update DB
527         updateLocalDatabase(entry, false);
528
529         return status;
530     }
531
532     /**
533      * This is the function that installs the final container flow merged entry
534      * on the network node and updates the database. It expects that all the
535      * validity and conflict checks are passed. That means it does not check
536      * whether this flow would conflict or overwrite an existing one.
537      * 
538      * @param entry
539      *            the FlowEntryInstall
540      * @return "Success" or error string
541      */
542     private Status addEntriesInternal(FlowEntryInstall entry) {
543         // Install the flow on the network node
544         Status status = programmer.addFlow(entry.getNode(), entry.getInstall()
545                 .getFlow());
546
547         if (!status.isSuccess()) {
548             log.warn("SDN Plugin failed to program the flow: "
549                     + status.getDescription());
550             return status;
551         }
552
553         log.trace("Added    {}", entry.getInstall());
554
555         // Update DB
556         updateLocalDatabase(entry, true);
557
558         return status;
559     }
560
561     /**
562      * Returns true if the flow conflicts with all the container's flows. This
563      * means that if the function returns true, the passed flow entry is
564      * congruent with at least one container flow, hence it is good to be
565      * installed on this container.
566      * 
567      * @param flowEntry
568      * @return true if flow conflicts with all the container flows, false
569      *         otherwise
570      */
571     private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
572         List<ContainerFlow> cFlowList = container.getContainerFlows();
573
574         // Validity check and avoid unnecessary computation
575         // Also takes care of default container where no container flows are
576         // present
577         if (cFlowList == null || cFlowList.isEmpty()) {
578             return false;
579         }
580
581         for (ContainerFlow cFlow : cFlowList) {
582             if (cFlow.allowsFlow(flowEntry.getFlow())) {
583                 // Entry is allowed by at least one container flow: good to go
584                 return false;
585             }
586         }
587         return true;
588     }
589
590     private synchronized void updateLocalDatabase(FlowEntryInstall entry,
591             boolean add) {
592         // Update node indexed flow database
593         updateNodeFlowsDB(entry, add);
594
595         // Update group indexed flow database
596         updateGroupFlowsDB(entry, add);
597     }
598
599     /*
600      * Update the node mapped flows database
601      */
602     private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
603         Node node = flowEntries.getNode();
604
605         Set<FlowEntryInstall> flowEntrylist = this.nodeFlows.get(node);
606         if (flowEntrylist == null) {
607             if (add == false) {
608                 return;
609             } else {
610                 flowEntrylist = new HashSet<FlowEntryInstall>();
611             }
612         }
613
614         if (add == true) {
615             flowEntrylist.add(flowEntries);
616         } else {
617             flowEntrylist.remove(flowEntries);
618         }
619
620         if (flowEntrylist.isEmpty()) {
621             this.nodeFlows.remove(node);
622         } else {
623             this.nodeFlows.put(node, flowEntrylist);
624         }
625     }
626
627     /*
628      * Update the group name mapped flows database
629      */
630     private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
631         Set<FlowEntryInstall> flowList;
632         FlowEntryInstall exists = null;
633         String flowName = flowEntries.getFlowName();
634         String groupName = flowEntries.getGroupName();
635
636         if (this.groupFlows == null) {
637             return;
638         }
639
640         // Flow may not be part of a group
641         if (groupName == null) {
642             return;
643         }
644
645         if (this.groupFlows.containsKey(groupName)) {
646             flowList = this.groupFlows.get(groupName);
647         } else {
648             if (add == false) {
649                 return;
650             } else {
651                 flowList = new HashSet<FlowEntryInstall>();
652             }
653         }
654
655         for (FlowEntryInstall flow : flowList) {
656             if (flow.equalsByNodeAndName(flowEntries.getNode(), flowName)) {
657                 exists = flow;
658                 break;
659             }
660         }
661
662         if (exists == null && add == false) {
663             return;
664         }
665
666         if (exists != null) {
667             flowList.remove(exists);
668         }
669
670         if (add == true) {
671             flowList.add(flowEntries);
672         }
673
674         if (flowList.isEmpty()) {
675             this.groupFlows.remove(groupName);
676         } else {
677             this.groupFlows.put(groupName, flowList);
678         }
679     }
680
681     /**
682      * Remove a flow entry that has been added previously First checks if the
683      * entry is effectively present in the local database
684      */
685     @SuppressWarnings("unused")
686     private Status removeEntry(Node node, String flowName) {
687         FlowEntryInstall target = null;
688
689         // Find in database
690         for (FlowEntryInstall entry : this.nodeFlows.get(node)) {
691             if (entry.equalsByNodeAndName(node, flowName)) {
692                 target = entry;
693                 break;
694             }
695         }
696
697         // If it is not there, stop any further processing
698         if (target == null) {
699             return new Status(StatusCode.SUCCESS, "Entry is not present");
700         }
701
702         // Remove from node
703         Status status = programmer.removeFlow(target.getNode(), target
704                 .getInstall().getFlow());
705
706         // Update DB
707         if (status.isSuccess()) {
708             updateLocalDatabase(target, false);
709         }
710
711         return status;
712     }
713
714     @Override
715     public Status installFlowEntry(FlowEntry flowEntry) {
716         Status status;
717         if (inContainerMode) {
718             String msg = "Controller in container mode: Install Refused";
719             status = new Status(StatusCode.NOTACCEPTABLE, msg);
720             log.warn(msg);
721         } else {
722             status = addEntry(flowEntry);
723         }
724         return status;
725     }
726
727     @Override
728     public Status uninstallFlowEntry(FlowEntry entry) {
729         Status status;
730         if (inContainerMode) {
731             String msg = "Controller in container mode: Uninstall Refused";
732             status = new Status(StatusCode.NOTACCEPTABLE, msg);
733             log.warn(msg);
734         } else {
735             status = removeEntry(entry);
736         }
737         return status;
738     }
739
740     @Override
741     public Status modifyFlowEntry(FlowEntry currentFlowEntry,
742             FlowEntry newFlowEntry) {
743         Status status = null;
744         if (inContainerMode) {
745             String msg = "Controller in container mode: Modify Refused";
746             status = new Status(StatusCode.NOTACCEPTABLE, msg);
747             log.warn(msg);
748         } else {
749             status = modifyEntry(currentFlowEntry, newFlowEntry);
750         }
751         return status;
752     }
753
754     @Override
755     public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
756         /*
757          * Run a loose check on the installed entries to decide whether to go
758          * with a add or modify method. A loose check means only check against
759          * the original flow entry requests and not against the installed flow
760          * entries which are the result of the original entry merged with the
761          * container flow(s) (if any). The modifyFlowEntry method in presence of
762          * conflicts with the Container flows (if any) would revert back to a
763          * delete + add pattern
764          */
765         FlowEntryInstall currentFlowEntries = findMatch(newFlowEntry, true);
766
767         if (currentFlowEntries != null) {
768             return modifyFlowEntry(currentFlowEntries.getOriginal(),
769                     newFlowEntry);
770         } else {
771             return installFlowEntry(newFlowEntry);
772         }
773     }
774
775     /**
776      * Try to find in the database if a Flow with the same Match and priority of
777      * the passed one already exists for the specified network node. Flow,
778      * priority and network node are all specified in the FlowEntry If found,
779      * the respective FlowEntryInstall Object is returned
780      * 
781      * @param flowEntry
782      *            the FlowEntry to be tested against the ones installed
783      * @param looseCheck
784      *            if true, the function will run the check against the original
785      *            flow entry portion of the installed entries
786      * @return null if not found, otherwise the FlowEntryInstall which contains
787      *         the existing flow entry
788      */
789     private FlowEntryInstall findMatch(FlowEntry flowEntry, boolean looseCheck) {
790         Flow flow = flowEntry.getFlow();
791         Match match = flow.getMatch();
792         short priority = flow.getPriority();
793         Set<FlowEntryInstall> thisNodeList = nodeFlows.get(flowEntry.getNode());
794
795         if (thisNodeList != null) {
796             for (FlowEntryInstall flowEntries : thisNodeList) {
797                 flow = (looseCheck == false) ? flowEntries.getInstall()
798                         .getFlow() : flowEntries.getOriginal().getFlow();
799                 if (flow.getMatch().equals(match)
800                         && flow.getPriority() == priority) {
801                     return flowEntries;
802                 }
803             }
804         }
805         return null;
806     }
807
808     public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
809         return entryConflictsWithContainerFlows(flowEntry);
810     }
811
812     /**
813      * Updates all installed flows because the container flow got updated This
814      * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
815      * Reinstall of all flows This is needed because a new container flows
816      * merged flow may conflict with an existing old container flows merged flow
817      * on the network node
818      */
819     private void updateFlowsContainerFlow() {
820         List<FlowEntryInstall> oldCouples = new ArrayList<FlowEntryInstall>();
821         List<FlowEntry> toReinstall = new ArrayList<FlowEntry>();
822         for (Entry<Node, Set<FlowEntryInstall>> entry : this.nodeFlows
823                 .entrySet()) {
824             oldCouples.clear();
825             toReinstall.clear();
826             if (entry.getValue() == null) {
827                 continue;
828             }
829             // Create a set of old entries and one of original entries to be
830             // reinstalled
831             for (FlowEntryInstall oldCouple : entry.getValue()) {
832                 oldCouples.add(oldCouple);
833                 toReinstall.add(oldCouple.getOriginal());
834             }
835             // Remove the old couples. No validity checks to be run, use the
836             // internal remove
837             for (FlowEntryInstall oldCouple : oldCouples) {
838                 this.removeEntryInternal(oldCouple);
839             }
840             // Reinstall the original flow entries, via the regular path: new
841             // cFlow merge + validations
842             for (FlowEntry flowEntry : toReinstall) {
843                 this.installFlowEntry(flowEntry);
844             }
845         }
846     }
847
848     public void nonClusterObjectCreate() {
849         nodeFlows = new ConcurrentHashMap<Node, Set<FlowEntryInstall>>();
850         TSPolicies = new ConcurrentHashMap<String, Object>();
851         groupFlows = new ConcurrentHashMap<String, Set<FlowEntryInstall>>();
852         staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
853         portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
854         portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
855         staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
856         flowsSaveEvent = new HashMap<Long, String>();
857         inactiveFlows = new ArrayList<FlowEntry>(1);
858     }
859
860     private void registerWithOSGIConsole() {
861         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
862                 .getBundleContext();
863         bundleContext.registerService(CommandProvider.class.getName(), this,
864                 null);
865     }
866
867     @Override
868     public void setTSPolicyData(String policyname, Object o, boolean add) {
869
870         if (add) {
871             /* Check if this policy already exists */
872             if (!(TSPolicies.containsKey(policyname))) {
873                 TSPolicies.put(policyname, o);
874             }
875         } else {
876             TSPolicies.remove(policyname);
877         }
878         if (frmAware != null) {
879             synchronized (frmAware) {
880                 for (IForwardingRulesManagerAware frma : frmAware) {
881                     try {
882                         frma.policyUpdate(policyname, add);
883                     } catch (Exception e) {
884                         log.error("Exception on callback", e);
885                     }
886                 }
887             }
888         }
889     }
890
891     @Override
892     public Map<String, Object> getTSPolicyData() {
893         return TSPolicies;
894     }
895
896     @Override
897     public Object getTSPolicyData(String policyName) {
898         if (TSPolicies.containsKey(policyName)) {
899             return TSPolicies.get(policyName);
900         } else {
901             return null;
902         }
903     }
904
905     @Override
906     public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
907         List<FlowEntry> list = null;
908         if (this.groupFlows != null && this.groupFlows.containsKey(policyName)) {
909             list = new ArrayList<FlowEntry>();
910             for (FlowEntryInstall entries : groupFlows.get(policyName)) {
911                 list.add(entries.getOriginal());
912             }
913             return new ArrayList<FlowEntry>();
914         }
915         return list;
916     }
917
918     @Override
919     public void addOutputPort(Node node, String flowName,
920             List<NodeConnector> portList) {
921
922         Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
923
924         for (FlowEntryInstall flow : flowEntryList) {
925             if (flow.getFlowName().equals(flowName)) {
926                 FlowEntry currentFlowEntry = flow.getOriginal();
927                 FlowEntry newFlowEntry = currentFlowEntry.clone();
928                 for (NodeConnector dstPort : portList) {
929                     newFlowEntry.getFlow().addAction(new Output(dstPort));
930                 }
931                 Status error = modifyEntry(currentFlowEntry, newFlowEntry);
932                 if (error.isSuccess()) {
933                     log.info("Ports {} added to FlowEntry {}", portList,
934                             flowName);
935                 } else {
936                     log.warn("Failed to add ports {} to Flow entry {}: "
937                             + error.getDescription(), portList,
938                             currentFlowEntry.toString());
939                 }
940                 return;
941             }
942         }
943         log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found",
944                 flowName, node);
945     }
946
947     @Override
948     public void removeOutputPort(Node node, String flowName,
949             List<NodeConnector> portList) {
950
951         Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
952
953         for (FlowEntryInstall flow : flowEntryList) {
954             if (flow.getFlowName().equals(flowName)) {
955                 FlowEntry currentFlowEntry = flow.getOriginal();
956                 FlowEntry newFlowEntry = currentFlowEntry.clone();
957                 for (NodeConnector dstPort : portList) {
958                     Action action = new Output(dstPort);
959                     newFlowEntry.getFlow().removeAction(action);
960                 }
961                 Status status = modifyEntry(currentFlowEntry, newFlowEntry);
962                 if (status.isSuccess()) {
963                     log.info("Ports {} removed from FlowEntry {}", portList,
964                             flowName);
965                 } else {
966                     log.warn("Failed to remove ports {} from Flow entry {}: "
967                             + status.getDescription(), portList,
968                             currentFlowEntry.toString());
969                 }
970                 return;
971             }
972         }
973         log.warn(
974                 "Failed to remove ports from Flow {} on Node {}: Entry Not Found",
975                 flowName, node);
976     }
977
978     /*
979      * This function assumes the target flow has only one output port
980      */
981     @Override
982     public void replaceOutputPort(Node node, String flowName,
983             NodeConnector outPort) {
984         FlowEntry currentFlowEntry = null;
985         FlowEntry newFlowEntry = null;
986         Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
987
988         // Find the flow
989         for (FlowEntryInstall flow : flowEntryList) {
990             if (flow.getFlowName().equals(flowName)) {
991                 currentFlowEntry = flow.getOriginal();
992                 break;
993             }
994         }
995         if (currentFlowEntry == null) {
996             log.warn(
997                     "Failed to replace output port for flow {} on node {}: Entry Not Found",
998                     flowName, node);
999             return;
1000         }
1001
1002         // Create a flow copy with the new output port
1003         newFlowEntry = currentFlowEntry.clone();
1004         Action target = null;
1005         for (Action action : newFlowEntry.getFlow().getActions()) {
1006             if (action.getType() == ActionType.OUTPUT) {
1007                 target = action;
1008                 break;
1009             }
1010         }
1011         newFlowEntry.getFlow().removeAction(target);
1012         newFlowEntry.getFlow().addAction(new Output(outPort));
1013
1014         // Modify on network node
1015         Status status = modifyEntry(currentFlowEntry, newFlowEntry);
1016
1017         if (status.isSuccess()) {
1018             log.info("Output port replaced with " + outPort
1019                     + " for flow {} on node {}", flowName, node);
1020         } else {
1021             log.warn("Failed to replace output port for flow {} on node {}: ",
1022                     status.getDescription(), flowName, node);
1023         }
1024         return;
1025     }
1026
1027     @Override
1028     public NodeConnector getOutputPort(Node node, String flowName) {
1029         Set<FlowEntryInstall> flowEntryList = this.nodeFlows.get(node);
1030
1031         for (FlowEntryInstall flow : flowEntryList) {
1032             if (flow.getFlowName().equals(flowName)) {
1033                 for (Action action : flow.getOriginal().getFlow().getActions()) {
1034                     if (action.getType() == ActionType.OUTPUT) {
1035                         return ((Output) action).getPort();
1036                     }
1037                 }
1038             }
1039         }
1040
1041         return null;
1042     }
1043
1044     private void cacheStartup() {
1045         allocateCaches();
1046         retrieveCaches();
1047     }
1048
1049     @SuppressWarnings("deprecation")
1050     private void allocateCaches() {
1051         if (this.clusterContainerService == null) {
1052             log.warn("Un-initialized clusterContainerService, can't create cache");
1053             return;
1054         }
1055
1056         log.debug("FRM allocateCaches for Container {}", container);
1057
1058         try {
1059             clusterContainerService.createCache("frm.nodeFlows",
1060                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1061
1062             clusterContainerService.createCache("frm.groupFlows",
1063                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1064
1065             clusterContainerService.createCache("frm.staticFlows",
1066                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1067
1068             clusterContainerService.createCache("frm.flowsSaveEvent",
1069                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1070
1071             clusterContainerService.createCache("frm.staticFlowsOrdinal",
1072                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1073
1074             clusterContainerService.createCache("frm.portGroupConfigs",
1075                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1076
1077             clusterContainerService.createCache("frm.portGroupData",
1078                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1079
1080             clusterContainerService.createCache("frm.TSPolicies",
1081                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1082
1083         } catch (CacheConfigException cce) {
1084             log.error("FRM CacheConfigException");
1085         } catch (CacheExistException cce) {
1086             log.error("FRM CacheExistException");
1087         }
1088     }
1089
1090     @SuppressWarnings({ "unchecked", "deprecation" })
1091     private void retrieveCaches() {
1092         ConcurrentMap<?, ?> map;
1093
1094         if (this.clusterContainerService == null) {
1095             log.warn("un-initialized clusterContainerService, can't retrieve cache");
1096             return;
1097         }
1098
1099         log.debug("FRM retrieveCaches for Container {}", container);
1100
1101         map = clusterContainerService.getCache("frm.nodeFlows");
1102         if (map != null) {
1103             nodeFlows = (ConcurrentMap<Node, Set<FlowEntryInstall>>) map;
1104         } else {
1105             log.error(
1106                     "FRM Cache frm.nodeFlows allocation failed for Container {}",
1107                     container);
1108         }
1109
1110         map = clusterContainerService.getCache("frm.groupFlows");
1111         if (map != null) {
1112             groupFlows = (ConcurrentMap<String, Set<FlowEntryInstall>>) map;
1113         } else {
1114             log.error(
1115                     "FRM Cache frm.groupFlows allocation failed for Container {}",
1116                     container);
1117         }
1118
1119         map = clusterContainerService.getCache("frm.staticFlows");
1120         if (map != null) {
1121             staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1122         } else {
1123             log.error(
1124                     "FRM Cache frm.staticFlows allocation failed for Container {}",
1125                     container);
1126         }
1127
1128         map = clusterContainerService.getCache("frm.flowsSaveEvent");
1129         if (map != null) {
1130             flowsSaveEvent = (ConcurrentMap<Long, String>) map;
1131         } else {
1132             log.error(
1133                     "FRM Cache frm.flowsSaveEvent allocation failed for Container {}",
1134                     container);
1135         }
1136
1137         map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1138         if (map != null) {
1139             staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1140         } else {
1141             log.error(
1142                     "FRM Cache frm.staticFlowsOrdinal allocation failed for Container {}",
1143                     container);
1144         }
1145
1146         map = clusterContainerService.getCache("frm.portGroupConfigs");
1147         if (map != null) {
1148             portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1149         } else {
1150             log.error(
1151                     "FRM Cache frm.portGroupConfigs allocation failed for Container {}",
1152                     container);
1153         }
1154
1155         map = clusterContainerService.getCache("frm.portGroupData");
1156         if (map != null) {
1157             portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1158         } else {
1159             log.error(
1160                     "FRM Cache frm.portGroupData allocation failed for Container {}",
1161                     container);
1162         }
1163
1164         map = clusterContainerService.getCache("frm.TSPolicies");
1165         if (map != null) {
1166             TSPolicies = (ConcurrentMap<String, Object>) map;
1167         } else {
1168             log.error(
1169                     "FRM Cache frm.TSPolicies allocation failed for Container {}",
1170                     container);
1171         }
1172
1173     }
1174
1175     @SuppressWarnings("deprecation")
1176     private void destroyCaches() {
1177         if (this.clusterContainerService == null) {
1178             log.warn("Un-initialized clusterContainerService, can't destroy cache");
1179             return;
1180         }
1181
1182         log.debug("FRM destroyCaches for Container {}", container);
1183         clusterContainerService.destroyCache("frm.nodeFlows");
1184         clusterContainerService.destroyCache("frm.TSPolicies");
1185         clusterContainerService.destroyCache("frm.groupFlows");
1186         clusterContainerService.destroyCache("frm.staticFlows");
1187         clusterContainerService.destroyCache("frm.flowsSaveEvent");
1188         clusterContainerService.destroyCache("frm.staticFlowsOrdinal");
1189         clusterContainerService.destroyCache("frm.portGroupData");
1190         clusterContainerService.destroyCache("frm.portGroupConfigs");
1191         nonClusterObjectCreate();
1192     }
1193
1194     private boolean flowConfigExists(FlowConfig config) {
1195         // As per customer requirement, flow name has to be unique on per node
1196         // id basis
1197         for (FlowConfig fc : staticFlows.values()) {
1198             if (fc.isByNameAndNodeIdEqual(config)) {
1199                 return true;
1200             }
1201         }
1202         return false;
1203     }
1204
1205     @Override
1206     public Status addStaticFlow(FlowConfig config, boolean restore) {
1207         StringBuffer resultStr = new StringBuffer();
1208         boolean multipleFlowPush = false;
1209         String error;
1210         Status status;
1211         config.setStatus(StatusCode.SUCCESS.toString());
1212
1213         // Presence check
1214         if (flowConfigExists(config)) {
1215             error = "Entry with this name on specified switch already exists";
1216             config.setStatus(error);
1217             return new Status(StatusCode.CONFLICT, error);
1218         }
1219
1220         // Skip validation check if we are trying to restore a saved config
1221         if (!restore && !config.isValid(container, resultStr)) {
1222             log.debug(resultStr.toString());
1223             error = "Invalid Configuration (" + resultStr.toString() + ")";
1224             config.setStatus(error);
1225             return new Status(StatusCode.BADREQUEST, error);
1226         }
1227
1228         if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1229             for (String portGroupName : portGroupConfigs.keySet()) {
1230                 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1231                     multipleFlowPush = true;
1232                     break;
1233                 }
1234             }
1235             if (!multipleFlowPush) {
1236                 log.debug(resultStr.toString());
1237                 error = "Invalid Configuration (Invalid PortGroup Name)";
1238                 config.setStatus(error);
1239                 return new Status(StatusCode.BADREQUEST, error);
1240             }
1241         }
1242
1243         /*
1244          * If requested program the entry in hardware first before updating the
1245          * StaticFlow DB
1246          */
1247         if (!multipleFlowPush) {
1248             // Program hw
1249             if (config.installInHw()) {
1250                 FlowEntry entry = config.getFlowEntry();
1251                 status = this.addEntry(entry);
1252                 if (!status.isSuccess()) {
1253                     config.setStatus(status.getDescription());
1254                     if (!restore) {
1255                         return status;
1256                     }
1257                 }
1258             }
1259         }
1260
1261         /*
1262          * When the control reaches this point, either of the following
1263          * conditions is true 1. This is a single entry configuration (non
1264          * PortGroup) and the hardware installation is successful 2. This is a
1265          * multiple entry configuration (PortGroup) and hardware installation is
1266          * NOT done directly on this event. 3. The User prefers to retain the
1267          * configuration in Controller and skip hardware installation.
1268          * 
1269          * Hence it is safe to update the StaticFlow DB at this point.
1270          * 
1271          * Note : For the case of PortGrouping, it is essential to have this DB
1272          * populated before the PortGroupListeners can query for the DB
1273          * triggered using portGroupChanged event...
1274          */
1275         Integer ordinal = staticFlowsOrdinal.get(0);
1276         staticFlowsOrdinal.put(0, ++ordinal);
1277         staticFlows.put(ordinal, config);
1278
1279         if (multipleFlowPush) {
1280             PortGroupConfig pgconfig = portGroupConfigs.get(config
1281                     .getPortGroup());
1282             Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1283             if (existingData != null) {
1284                 portGroupChanged(pgconfig, existingData, true);
1285             }
1286         }
1287         return new Status(StatusCode.SUCCESS, null);
1288     }
1289
1290     private void addStaticFlowsToSwitch(Node node) {
1291         for (FlowConfig config : staticFlows.values()) {
1292             if (config.isPortGroupEnabled()) {
1293                 continue;
1294             }
1295             if (config.getNode().equals(node)) {
1296                 if (config.installInHw()
1297                         && !config.getStatus().equals(
1298                                 StatusCode.SUCCESS.toString())) {
1299                     Status status = this.addEntry(config.getFlowEntry());
1300                     config.setStatus(status.getDescription());
1301                 }
1302             }
1303         }
1304     }
1305
1306     private void updateStaticFlowConfigsOnNodeDown(Node node) {
1307         log.trace("Updating Static Flow configs on node down: " + node);
1308
1309         List<Integer> toRemove = new ArrayList<Integer>();
1310         for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1311
1312             FlowConfig config = entry.getValue();
1313
1314             if (config.isPortGroupEnabled()) {
1315                 continue;
1316             }
1317
1318             if (config.installInHw() && config.getNode().equals(node)) {
1319                 if (config.isInternalFlow()) {
1320                     // Take note of this controller generated static flow
1321                     toRemove.add(entry.getKey());
1322                 } else {
1323                     config.setStatus(NODEDOWN);
1324                 }
1325             }
1326         }
1327         // Remove controller generated static flows for this node
1328         for (Integer index : toRemove) {
1329             staticFlows.remove(index);
1330         }
1331     }
1332
1333     private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1334         log.trace("Updating Static Flow configs on container mode change: "
1335                 + update);
1336
1337         for (FlowConfig config : staticFlows.values()) {
1338             if (config.isPortGroupEnabled()) {
1339                 continue;
1340             }
1341             if (config.installInHw()) {
1342                 switch (update) {
1343                 case ADDED:
1344                     config.setStatus("Removed from node because in container mode");
1345                     break;
1346                 case REMOVED:
1347                     config.setStatus(StatusCode.SUCCESS.toString());
1348                     break;
1349                 default:
1350                 }
1351             }
1352         }
1353     }
1354
1355     public Status removeStaticFlow(FlowConfig config) {
1356         /*
1357          * No config.isInternal() check as NB does not take this path and GUI
1358          * cannot issue a delete on an internal generated flow. We need this
1359          * path to be accessible when switch mode is changed from proactive to
1360          * reactive, so that we can remove the internal generated LLDP and ARP
1361          * punt flows
1362          */
1363         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1364             if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1365                 // Program the network node
1366                 Status status = this.removeEntry(config.getFlowEntry());
1367                 // Update configuration database if programming was successful
1368                 if (status.isSuccess()) {
1369                     staticFlows.remove(entry.getKey());
1370                     return status;
1371                 } else {
1372                     entry.getValue().setStatus(status.getDescription());
1373                     return status;
1374                 }
1375             }
1376         }
1377         return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1378     }
1379
1380     @Override
1381     public Status removeStaticFlow(String name, Node node) {
1382         for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1383             FlowConfig entry = mapEntry.getValue();
1384             Status status = new Status(null, null);
1385             if (entry.isByNameAndNodeIdEqual(name, node)) {
1386                 // Validity check for api3 entry point
1387                 if (entry.isInternalFlow()) {
1388                     String msg = "Invalid operation: Controller generated "
1389                             + "flow cannot be deleted";
1390                     log.warn(msg);
1391                     return new Status(StatusCode.NOTACCEPTABLE, msg);
1392                 }
1393                 if (!entry.isPortGroupEnabled()) {
1394                     // Program the network node
1395                     status = this.removeEntry(entry.getFlowEntry());
1396                 }
1397                 // Update configuration database if programming was successful
1398                 if (status.isSuccess()) {
1399                     staticFlows.remove(mapEntry.getKey());
1400                     return status;
1401                 } else {
1402                     entry.setStatus(status.getDescription());
1403                     return status;
1404                 }
1405             }
1406         }
1407         return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1408     }
1409
1410     public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1411         // Validity check for api3 entry point
1412         if (newFlowConfig.isInternalFlow()) {
1413             String msg = "Invalid operation: Controller generated flow "
1414                     + "cannot be modified";
1415             log.warn(msg);
1416             return new Status(StatusCode.NOTACCEPTABLE, msg);
1417         }
1418
1419         // Validity Check
1420         StringBuffer resultStr = new StringBuffer();
1421         if (!newFlowConfig.isValid(container, resultStr)) {
1422             String msg = "Invalid Configuration (" + resultStr.toString() + ")";
1423             newFlowConfig.setStatus(msg);
1424             log.warn(msg);
1425             return new Status(StatusCode.BADREQUEST, msg);
1426         }
1427
1428         FlowConfig oldFlowConfig = null;
1429         Integer index = null;
1430         for (Map.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1431             FlowConfig entry = mapEntry.getValue();
1432             if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(),
1433                     newFlowConfig.getNode())) {
1434                 oldFlowConfig = entry;
1435                 index = mapEntry.getKey();
1436                 break;
1437             }
1438         }
1439
1440         if (oldFlowConfig == null) {
1441             String msg = "Attempt to modify a non existing static flow";
1442             log.warn(msg);
1443             return new Status(StatusCode.NOTFOUND, msg);
1444         }
1445
1446         // Do not attempt to reinstall the flow, warn user
1447         if (newFlowConfig.equals(oldFlowConfig)) {
1448             String msg = "No modification detected";
1449             log.info("Static flow modification skipped: " + msg);
1450             return new Status(StatusCode.SUCCESS, msg);
1451         }
1452
1453         // If flow is installed, program the network node
1454         Status status = new Status(StatusCode.SUCCESS, "Saved in config");
1455         if (oldFlowConfig.installInHw()) {
1456             status = this.modifyEntry(oldFlowConfig.getFlowEntry(),
1457                     newFlowConfig.getFlowEntry());
1458         }
1459
1460         // Update configuration database if programming was successful
1461         if (status.isSuccess()) {
1462             newFlowConfig.setStatus(status.getDescription());
1463             staticFlows.put(index, newFlowConfig);
1464         }
1465
1466         return status;
1467     }
1468
1469     @Override
1470     public Status toggleStaticFlowStatus(String name, Node node) {
1471         return toggleStaticFlowStatus(getStaticFlow(name, node));
1472     }
1473
1474     @Override
1475     public Status toggleStaticFlowStatus(FlowConfig config) {
1476         if (config == null) {
1477             String msg = "Invalid request: null flow config";
1478             log.warn(msg);
1479             return new Status(StatusCode.BADREQUEST, msg);
1480         }
1481         // Validity check for api3 entry point
1482         if (config.isInternalFlow()) {
1483             String msg = "Invalid operation: Controller generated flow "
1484                     + "cannot be modified";
1485             log.warn(msg);
1486             return new Status(StatusCode.NOTACCEPTABLE, msg);
1487         }
1488
1489         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1490             FlowConfig conf = entry.getValue();
1491             if (conf.isByNameAndNodeIdEqual(config)) {
1492                 // Program the network node
1493                 Status status = new Status(StatusCode.SUCCESS, null);
1494                 if (conf.installInHw()) {
1495                     status = this.removeEntry(conf.getFlowEntry());
1496                 } else {
1497                     status = this.addEntry(conf.getFlowEntry());
1498                 }
1499                 if (!status.isSuccess()) {
1500                     conf.setStatus(status.getDescription());
1501                     return status;
1502                 }
1503
1504                 // Update Configuration database
1505                 conf.setStatus(StatusCode.SUCCESS.toString());
1506                 conf.toggleStatus();
1507                 return status;
1508             }
1509         }
1510         return new Status(StatusCode.NOTFOUND,
1511                 "Unable to locate the entry. Failed to toggle status");
1512     }
1513
1514     /**
1515      * Uninstall all the Flow Entries present in the software view A copy of
1516      * each entry is stored in the inactive list so that it can be re-applied
1517      * when needed This function is called on the default container instance of
1518      * FRM only when the first container is created
1519      */
1520     private void uninstallAllFlowEntries() {
1521         log.info("Uninstalling all flows");
1522
1523         // Store entries / create target list
1524         for (ConcurrentMap.Entry<Node, Set<FlowEntryInstall>> mapEntry : nodeFlows
1525                 .entrySet()) {
1526             for (FlowEntryInstall flowEntries : mapEntry.getValue()) {
1527                 inactiveFlows.add(flowEntries.getOriginal());
1528             }
1529         }
1530
1531         // Now remove the entries
1532         for (FlowEntry flowEntry : inactiveFlows) {
1533             Status status = this.removeEntry(flowEntry);
1534             if (!status.isSuccess()) {
1535                 log.warn(
1536                         "Failed to remove entry: {}: "
1537                                 + status.getDescription(), flowEntry);
1538             }
1539         }
1540     }
1541
1542     /**
1543      * Re-install all the Flow Entries present in the inactive list The inactive
1544      * list will be empty at the end of this call This function is called on the
1545      * default container instance of FRM only when the last container is deleted
1546      */
1547     private void reinstallAllFlowEntries() {
1548         log.info("Reinstalling all inactive flows");
1549
1550         for (FlowEntry flowEntry : this.inactiveFlows) {
1551             Status status = this.addEntry(flowEntry);
1552             if (!status.isSuccess()) {
1553                 log.warn(
1554                         "Failed to install entry: {}: "
1555                                 + status.getDescription(), flowEntry);
1556             }
1557         }
1558
1559         // Empty inactive list in any case
1560         inactiveFlows.clear();
1561     }
1562
1563     public List<FlowConfig> getStaticFlows() {
1564         return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0)
1565                 .intValue());
1566     }
1567
1568     // TODO: need to come out with a better algorithm for mantaining the order
1569     // of the configuration entries
1570     // with actual one, index associated to deleted entries cannot be reused and
1571     // map grows...
1572     private List<FlowConfig> getStaticFlowsOrderedList(
1573             ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1574         List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1575         for (int i = 0; i <= maxKey; i++) {
1576             FlowConfig entry = flowMap.get(i);
1577             if (entry != null) {
1578                 orderedList.add(entry);
1579             }
1580         }
1581         return orderedList;
1582     }
1583
1584     @Override
1585     public FlowConfig getStaticFlow(String name, Node node) {
1586         for (FlowConfig config : staticFlows.values()) {
1587             if (config.isByNameAndNodeIdEqual(name, node)) {
1588                 return config;
1589             }
1590         }
1591         return null;
1592     }
1593
1594     @Override
1595     public List<FlowConfig> getStaticFlows(Node node) {
1596         List<FlowConfig> list = new ArrayList<FlowConfig>();
1597         for (FlowConfig config : staticFlows.values()) {
1598             if (config.onNode(node)) {
1599                 list.add(config);
1600             }
1601         }
1602         return list;
1603     }
1604
1605     @Override
1606     public List<String> getStaticFlowNamesForNode(Node node) {
1607         List<String> list = new ArrayList<String>();
1608         for (FlowConfig config : staticFlows.values()) {
1609             if (config.onNode(node)) {
1610                 list.add(config.getName());
1611             }
1612         }
1613         return list;
1614     }
1615
1616     @Override
1617     public List<Node> getListNodeWithConfiguredFlows() {
1618         Set<Node> set = new HashSet<Node>();
1619         for (FlowConfig config : staticFlows.values()) {
1620             set.add(config.getNode());
1621         }
1622         return new ArrayList<Node>(set);
1623     }
1624
1625     @SuppressWarnings("unchecked")
1626     private void loadFlowConfiguration() {
1627         ObjectReader objReader = new ObjectReader();
1628         ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader
1629                 .read(this, frmFileName);
1630
1631         ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader
1632                 .read(this, portGroupFileName);
1633
1634         if (pgConfig != null) {
1635             for (Map.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
1636                 addPortGroupConfig(entry.getKey(), entry.getValue()
1637                         .getMatchString(), true);
1638             }
1639         }
1640
1641         if (confList == null) {
1642             return;
1643         }
1644
1645         int maxKey = 0;
1646         for (Integer key : confList.keySet()) {
1647             if (key.intValue() > maxKey)
1648                 maxKey = key.intValue();
1649         }
1650
1651         for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
1652             addStaticFlow(conf, true);
1653         }
1654     }
1655
1656     @Override
1657     public Object readObject(ObjectInputStream ois)
1658             throws FileNotFoundException, IOException, ClassNotFoundException {
1659         return ois.readObject();
1660     }
1661
1662     public Status saveConfig() {
1663         // Publish the save config event to the cluster nodes
1664         flowsSaveEvent.put(new Date().getTime(), SAVE);
1665         return saveConfigInternal();
1666     }
1667
1668     private Status saveConfigInternal() {
1669         ObjectWriter objWriter = new ObjectWriter();
1670         ConcurrentHashMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1671         for (Integer ordinal : staticFlows.keySet()) {
1672             FlowConfig config = staticFlows.get(ordinal);
1673             // Do not save dynamic and controller generated static flows
1674             if (config.isDynamic() || config.isInternalFlow()) {
1675                 continue;
1676             }
1677             nonDynamicFlows.put(ordinal, config);
1678         }
1679         objWriter.write(nonDynamicFlows, frmFileName);
1680         objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(
1681                 portGroupConfigs), portGroupFileName);
1682         return new Status(StatusCode.SUCCESS, null);
1683     }
1684
1685     @Override
1686     public void entryCreated(Long key, String cacheName, boolean local) {
1687     }
1688
1689     @Override
1690     public void entryUpdated(Long key, String new_value, String cacheName,
1691             boolean originLocal) {
1692         saveConfigInternal();
1693     }
1694
1695     @Override
1696     public void entryDeleted(Long key, String cacheName, boolean originLocal) {
1697     }
1698
1699     @Override
1700     public void subnetNotify(Subnet sub, boolean add) {
1701     }
1702
1703     private void installImplicitARPReplyPunt(Node node) {
1704
1705         if (node == null) {
1706             return;
1707         }
1708
1709         List<String> puntAction = new ArrayList<String>();
1710         puntAction.add(ActionType.CONTROLLER.toString());
1711
1712         FlowConfig allowARP = new FlowConfig();
1713         allowARP.setInstallInHw(true);
1714         allowARP.setName("**Punt ARP Reply");
1715         allowARP.setPriority("500");
1716         allowARP.setNode(node);
1717         allowARP.setEtherType("0x"
1718                 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1719         allowARP.setDstMac(HexEncode.bytesToHexString(switchManager
1720                 .getControllerMAC()));
1721         allowARP.setActions(puntAction);
1722         addStaticFlow(allowARP, false);
1723     }
1724
1725     @Override
1726     public void modeChangeNotify(Node node, boolean proactive) {
1727         List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
1728
1729         List<String> puntAction = new ArrayList<String>();
1730         puntAction.add(ActionType.CONTROLLER.toString());
1731
1732         FlowConfig allowARP = new FlowConfig();
1733         allowARP.setInstallInHw(true);
1734         allowARP.setName("**Punt ARP");
1735         allowARP.setPriority("1");
1736         allowARP.setNode(node);
1737         allowARP.setEtherType("0x"
1738                 + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
1739         allowARP.setActions(puntAction);
1740         defaultConfigs.add(allowARP);
1741
1742         FlowConfig allowLLDP = new FlowConfig();
1743         allowLLDP.setInstallInHw(true);
1744         allowLLDP.setName("**Punt LLDP");
1745         allowLLDP.setPriority("1");
1746         allowLLDP.setNode(node);
1747         allowLLDP
1748                 .setEtherType("0x"
1749                         + Integer.toHexString(EtherTypes.LLDP.intValue())
1750                                 .toUpperCase());
1751         allowLLDP.setActions(puntAction);
1752         defaultConfigs.add(allowLLDP);
1753
1754         List<String> dropAction = new ArrayList<String>();
1755         dropAction.add(ActionType.DROP.toString());
1756
1757         FlowConfig dropAllConfig = new FlowConfig();
1758         dropAllConfig.setInstallInHw(true);
1759         dropAllConfig.setName("**Catch-All Drop");
1760         dropAllConfig.setPriority("0");
1761         dropAllConfig.setNode(node);
1762         dropAllConfig.setActions(dropAction);
1763         defaultConfigs.add(dropAllConfig);
1764
1765         for (FlowConfig fc : defaultConfigs) {
1766             if (proactive) {
1767                 addStaticFlow(fc, false);
1768             } else {
1769                 removeStaticFlow(fc);
1770             }
1771         }
1772
1773         log.info("Set Switch {} Mode to {}", node, proactive);
1774     }
1775
1776     /**
1777      * Remove from the databases all the flows installed on the node
1778      * 
1779      * @param node
1780      */
1781     private synchronized void cleanDatabaseForNode(Node node) {
1782         log.info("Cleaning Flow database for Node " + node.toString());
1783
1784         // Find out which groups the node's flows are part of
1785         Set<String> affectedGroups = new HashSet<String>();
1786         Set<FlowEntryInstall> flowEntryList = nodeFlows.get(node);
1787         if (flowEntryList != null) {
1788             for (FlowEntryInstall entry : flowEntryList) {
1789                 String groupName = entry.getGroupName();
1790                 if (groupName != null) {
1791                     affectedGroups.add(groupName);
1792                 }
1793             }
1794         }
1795
1796         // Remove the node's flows from the group indexed flow database
1797         if (!affectedGroups.isEmpty()) {
1798             for (String group : affectedGroups) {
1799                 Set<FlowEntryInstall> flowList = groupFlows.get(group);
1800                 Set<FlowEntryInstall> toRemove = new HashSet<FlowEntryInstall>();
1801                 for (FlowEntryInstall entry : flowList) {
1802                     if (node.equals(entry.getNode())) {
1803                         toRemove.add(entry);
1804                     }
1805                 }
1806                 flowList.removeAll(toRemove);
1807                 if (flowList.isEmpty()) {
1808                     groupFlows.remove(group);
1809                 }
1810             }
1811         }
1812
1813         // Remove the node's flows from the node indexed flow database
1814         nodeFlows.remove(node);
1815     }
1816
1817     @Override
1818     public void notifyNode(Node node, UpdateType type,
1819             Map<String, Property> propMap) {
1820         switch (type) {
1821         case ADDED:
1822             addStaticFlowsToSwitch(node);
1823             break;
1824         case REMOVED:
1825             cleanDatabaseForNode(node);
1826             updateStaticFlowConfigsOnNodeDown(node);
1827             break;
1828         default:
1829             break;
1830         }
1831     }
1832
1833     @Override
1834     public void notifyNodeConnector(NodeConnector nodeConnector,
1835             UpdateType type, Map<String, Property> propMap) {
1836     }
1837
1838     private FlowConfig getDerivedFlowConfig(FlowConfig original,
1839             String configName, Short port) {
1840         FlowConfig derivedFlow = new FlowConfig(original);
1841         derivedFlow.setDynamic(true);
1842         derivedFlow.setPortGroup(null);
1843         derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
1844         derivedFlow.setIngressPort(port + "");
1845         return derivedFlow;
1846     }
1847
1848     private void addPortGroupFlows(PortGroupConfig config, Node node,
1849             PortGroup data) {
1850         for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
1851                 .hasNext();) {
1852             FlowConfig staticFlow = it.next();
1853             if (staticFlow.getPortGroup() == null) {
1854                 continue;
1855             }
1856             if ((staticFlow.getNode().equals(node))
1857                     && (staticFlow.getPortGroup().equals(config.getName()))) {
1858                 for (Short port : data.getPorts()) {
1859                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
1860                             config.getName(), port);
1861                     addStaticFlow(derivedFlow, false);
1862                 }
1863             }
1864         }
1865     }
1866
1867     private void removePortGroupFlows(PortGroupConfig config, Node node,
1868             PortGroup data) {
1869         for (Iterator<FlowConfig> it = staticFlows.values().iterator(); it
1870                 .hasNext();) {
1871             FlowConfig staticFlow = it.next();
1872             if (staticFlow.getPortGroup() == null) {
1873                 continue;
1874             }
1875             if ((staticFlow.getNode().equals(node))
1876                     && (staticFlow.getPortGroup().equals(config.getName()))) {
1877                 for (Short port : data.getPorts()) {
1878                     FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow,
1879                             config.getName(), port);
1880                     removeStaticFlow(derivedFlow);
1881                 }
1882             }
1883         }
1884     }
1885
1886     @Override
1887     public void portGroupChanged(PortGroupConfig config,
1888             Map<Node, PortGroup> data, boolean add) {
1889         log.info("PortGroup Changed for :" + config + " Data: " + portGroupData);
1890         Map<Node, PortGroup> existingData = portGroupData.get(config);
1891         if (existingData != null) {
1892             for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
1893                 PortGroup existingPortGroup = existingData.get(entry.getKey());
1894                 if (existingPortGroup == null) {
1895                     if (add) {
1896                         existingData.put(entry.getKey(), entry.getValue());
1897                         addPortGroupFlows(config, entry.getKey(),
1898                                 entry.getValue());
1899                     }
1900                 } else {
1901                     if (add) {
1902                         existingPortGroup.getPorts().addAll(
1903                                 entry.getValue().getPorts());
1904                         addPortGroupFlows(config, entry.getKey(),
1905                                 entry.getValue());
1906                     } else {
1907                         existingPortGroup.getPorts().removeAll(
1908                                 entry.getValue().getPorts());
1909                         removePortGroupFlows(config, entry.getKey(),
1910                                 entry.getValue());
1911                     }
1912                 }
1913             }
1914         } else {
1915             if (add) {
1916                 portGroupData.put(config, data);
1917                 for (Node swid : data.keySet()) {
1918                     addPortGroupFlows(config, swid, data.get(swid));
1919                 }
1920             }
1921         }
1922     }
1923
1924     public boolean addPortGroupConfig(String name, String regex, boolean restore) {
1925         PortGroupConfig config = portGroupConfigs.get(name);
1926         if (config != null)
1927             return false;
1928
1929         if ((portGroupProvider == null) && !restore) {
1930             return false;
1931         }
1932         if ((portGroupProvider != null)
1933                 && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
1934             return false;
1935         }
1936
1937         config = new PortGroupConfig(name, regex);
1938         portGroupConfigs.put(name, config);
1939         if (portGroupProvider != null) {
1940             portGroupProvider.createPortGroupConfig(config);
1941         }
1942         return true;
1943     }
1944
1945     public boolean delPortGroupConfig(String name) {
1946         PortGroupConfig config = portGroupConfigs.get(name);
1947         if (config == null) {
1948             return false;
1949         }
1950
1951         if (portGroupProvider != null) {
1952             portGroupProvider.deletePortGroupConfig(config);
1953         }
1954         portGroupConfigs.remove(name);
1955         return true;
1956     }
1957
1958     private void usePortGroupConfig(String name) {
1959         PortGroupConfig config = portGroupConfigs.get(name);
1960         if (config == null) {
1961             return;
1962         }
1963         if (portGroupProvider != null) {
1964             Map<Node, PortGroup> data = portGroupProvider
1965                     .getPortGroupData(config);
1966             portGroupData.put(config, data);
1967         }
1968     }
1969
1970     @Override
1971     public Map<String, PortGroupConfig> getPortGroupConfigs() {
1972         return portGroupConfigs;
1973     }
1974
1975     public boolean isPortGroupSupported() {
1976         if (portGroupProvider == null) {
1977             return false;
1978         }
1979         return true;
1980     }
1981
1982     // Fir PortGroupProvider to use regular Dependency Manager
1983     /* @SuppressWarnings("rawtypes") */
1984     /* public void bind(Object arg0, Map arg1) throws Exception { */
1985     /* if (arg0 instanceof PortGroupProvider) { */
1986     /* setPortGroupProvider((PortGroupProvider)arg0); */
1987     /* } */
1988     /* } */
1989
1990     /* @SuppressWarnings("rawtypes") */
1991     /* @Override */
1992     /* public void unbind(Object arg0, Map arg1) throws Exception { */
1993     /* if (arg0 instanceof PortGroupProvider) { */
1994     /* portGroupProvider = null; */
1995     /* } */
1996     /* } */
1997
1998     public void setIContainer(IContainer s) {
1999         this.container = s;
2000     }
2001
2002     public void unsetIContainer(IContainer s) {
2003         if (this.container == s) {
2004             this.container = null;
2005         }
2006     }
2007
2008     public PortGroupProvider getPortGroupProvider() {
2009         return portGroupProvider;
2010     }
2011
2012     public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2013         this.portGroupProvider = null;
2014     }
2015
2016     public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2017         this.portGroupProvider = portGroupProvider;
2018         portGroupProvider.registerPortGroupChange(this);
2019         for (PortGroupConfig config : portGroupConfigs.values()) {
2020             portGroupProvider.createPortGroupConfig(config);
2021         }
2022     }
2023
2024     public void setHostFinder(IfIptoHost hostFinder) {
2025         this.hostFinder = hostFinder;
2026     }
2027
2028     public void unsetHostFinder(IfIptoHost hostFinder) {
2029         if (this.hostFinder == hostFinder) {
2030             this.hostFinder = null;
2031         }
2032     }
2033
2034     public void setFrmAware(IForwardingRulesManagerAware obj) {
2035         this.frmAware.add(obj);
2036     }
2037
2038     public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2039         this.frmAware.remove(obj);
2040     }
2041
2042     void setClusterContainerService(IClusterContainerServices s) {
2043         log.debug("Cluster Service set");
2044         this.clusterContainerService = s;
2045     }
2046
2047     void unsetClusterContainerService(IClusterContainerServices s) {
2048         if (this.clusterContainerService == s) {
2049             log.debug("Cluster Service removed!");
2050             this.clusterContainerService = null;
2051         }
2052     }
2053
2054     private String getContainerName() {
2055         if (container == null) {
2056             return GlobalConstants.DEFAULT.toString();
2057         }
2058         return container.getName();
2059     }
2060
2061     /**
2062      * Function called by the dependency manager when all the required
2063      * dependencies are satisfied
2064      * 
2065      */
2066     void init() {
2067         frmAware = Collections
2068                 .synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
2069         frmFileName = GlobalConstants.STARTUPHOME.toString()
2070                 + "frm_staticflows_" + this.getContainerName() + ".conf";
2071         portGroupFileName = GlobalConstants.STARTUPHOME.toString()
2072                 + "portgroup_" + this.getContainerName() + ".conf";
2073
2074         inContainerMode = false;
2075
2076         if (portGroupProvider != null) {
2077             portGroupProvider.registerPortGroupChange(this);
2078         }
2079
2080         nonClusterObjectCreate();
2081
2082         cacheStartup();
2083
2084         registerWithOSGIConsole();
2085
2086         /*
2087          * If we are not the first cluster node to come up, do not initialize
2088          * the static flow entries ordinal
2089          */
2090         if (staticFlowsOrdinal.size() == 0) {
2091             staticFlowsOrdinal.put(0, Integer.valueOf(0));
2092         }
2093     }
2094
2095     /**
2096      * Function called by the dependency manager when at least one dependency
2097      * become unsatisfied or when the component is shutting down because for
2098      * example bundle is being stopped.
2099      * 
2100      */
2101     void destroy() {
2102         destroyCaches();
2103     }
2104
2105     /**
2106      * Function called by dependency manager after "init ()" is called and after
2107      * the services provided by the class are registered in the service registry
2108      * 
2109      */
2110     void start() {
2111         /*
2112          * Read startup and build database if we have not already gotten the
2113          * configurations synced from another node
2114          */
2115         if (staticFlows.isEmpty()) {
2116             loadFlowConfiguration();
2117         }
2118     }
2119
2120     /**
2121      * Function called by the dependency manager before the services exported by
2122      * the component are unregistered, this will be followed by a "destroy ()"
2123      * calls
2124      * 
2125      */
2126     void stop() {
2127     }
2128
2129     public void setFlowProgrammerService(IFlowProgrammerService service) {
2130         this.programmer = service;
2131     }
2132
2133     public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2134         if (this.programmer == service) {
2135             this.programmer = null;
2136         }
2137     }
2138
2139     public void setSwitchManager(ISwitchManager switchManager) {
2140         this.switchManager = switchManager;
2141     }
2142
2143     public void unsetSwitchManager(ISwitchManager switchManager) {
2144         if (this.switchManager == switchManager) {
2145             this.switchManager = null;
2146         }
2147     }
2148
2149     @Override
2150     public void tagUpdated(String containerName, Node n, short oldTag,
2151             short newTag, UpdateType t) {
2152
2153     }
2154
2155     @Override
2156     public void containerFlowUpdated(String containerName,
2157             ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) {
2158         /*
2159          * Whether it is an addition or removal, we have to recompute the merged
2160          * flows entries taking into account all the current container flows
2161          * because flow merging is not an injective function
2162          */
2163         updateFlowsContainerFlow();
2164     }
2165
2166     @Override
2167     public void nodeConnectorUpdated(String containerName, NodeConnector p,
2168             UpdateType t) {
2169         // No action
2170     }
2171
2172     @Override
2173     public void containerModeUpdated(UpdateType update) {
2174         switch (update) {
2175         case ADDED:
2176             this.inContainerMode = true;
2177             this.uninstallAllFlowEntries();
2178             break;
2179         case REMOVED:
2180             this.inContainerMode = false;
2181             this.reinstallAllFlowEntries();
2182             break;
2183         default:
2184         }
2185
2186         // Update our configuration DB
2187         updateStaticFlowConfigsOnContainerModeChange(update);
2188     }
2189
2190     /*
2191      * OSGI COMMANDS
2192      */
2193     @Override
2194     public String getHelp() {
2195         StringBuffer help = new StringBuffer();
2196         help.append("---FRM Matrix Application---\n");
2197         help.append("\t printMatrixData        - Prints the Matrix Configs\n");
2198         help.append("\t addMatrixConfig <name> <regex>\n");
2199         help.append("\t delMatrixConfig <name>\n");
2200         help.append("\t useMatrixConfig <name>\n");
2201         return help.toString();
2202     }
2203
2204     public void _printMatrixData(CommandInterpreter ci) {
2205         ci.println("Configs : ");
2206         ci.println("---------");
2207         ci.println(portGroupConfigs);
2208
2209         ci.println("Data : ");
2210         ci.println("------");
2211         ci.println(portGroupData);
2212     }
2213
2214     public void _addMatrixConfig(CommandInterpreter ci) {
2215         String name = ci.nextArgument();
2216         String regex = ci.nextArgument();
2217         addPortGroupConfig(name, regex, false);
2218     }
2219
2220     public void _delMatrixConfig(CommandInterpreter ci) {
2221         String name = ci.nextArgument();
2222         delPortGroupConfig(name);
2223     }
2224
2225     public void _useMatrixConfig(CommandInterpreter ci) {
2226         String name = ci.nextArgument();
2227         usePortGroupConfig(name);
2228     }
2229
2230     public void _arpPunt(CommandInterpreter ci) {
2231         String switchId = ci.nextArgument();
2232         long swid = HexEncode.stringToLong(switchId);
2233         Node node = NodeCreator.createOFNode(swid);
2234         installImplicitARPReplyPunt(node);
2235     }
2236
2237     public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2238         Node node = null;
2239         String nodeId = ci.nextArgument();
2240         if (nodeId == null) {
2241             ci.print("Node id not specified");
2242             return;
2243         }
2244         try {
2245             node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2246         } catch (NumberFormatException e) {
2247             log.error("",e);
2248         }
2249         ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2250     }
2251
2252     public void _frmremoveflow(CommandInterpreter ci)
2253             throws UnknownHostException {
2254         Node node = null;
2255         String nodeId = ci.nextArgument();
2256         if (nodeId == null) {
2257             ci.print("Node id not specified");
2258             return;
2259         }
2260         try {
2261             node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2262         } catch (NumberFormatException e) {
2263             log.error("",e);
2264         }
2265         ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2266     }
2267
2268     private Flow getSampleFlow(Node node) throws UnknownHostException {
2269         NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
2270                 (short) 24, node);
2271         NodeConnector oport = NodeConnectorCreator.createOFNodeConnector(
2272                 (short) 30, node);
2273         byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,
2274                 (byte) 0x9a, (byte) 0xbc };
2275         byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d,
2276                 (byte) 0x5e, (byte) 0x6f };
2277         InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2278         InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2279         InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2280         InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2281         short ethertype = EtherTypes.IPv4.shortValue();
2282         short vlan = (short) 27;
2283         byte vlanPr = 3;
2284         Byte tos = 4;
2285         byte proto = IPProtocols.TCP.byteValue();
2286         short src = (short) 55000;
2287         short dst = 80;
2288
2289         /*
2290          * Create a SAL Flow aFlow
2291          */
2292         Match match = new Match();
2293         match.setField(MatchType.IN_PORT, port);
2294         match.setField(MatchType.DL_SRC, srcMac);
2295         match.setField(MatchType.DL_DST, dstMac);
2296         match.setField(MatchType.DL_TYPE, ethertype);
2297         match.setField(MatchType.DL_VLAN, vlan);
2298         match.setField(MatchType.DL_VLAN_PR, vlanPr);
2299         match.setField(MatchType.NW_SRC, srcIP, ipMask);
2300         match.setField(MatchType.NW_DST, dstIP, ipMask2);
2301         match.setField(MatchType.NW_TOS, tos);
2302         match.setField(MatchType.NW_PROTO, proto);
2303         match.setField(MatchType.TP_SRC, src);
2304         match.setField(MatchType.TP_DST, dst);
2305
2306         List<Action> actions = new ArrayList<Action>();
2307         actions.add(new Output(oport));
2308         actions.add(new PopVlan());
2309         actions.add(new Flood());
2310         actions.add(new Controller());
2311         return new Flow(match, actions);
2312     }
2313
2314     @Override
2315     public Status saveConfiguration() {
2316         return saveConfig();
2317     }
2318
2319     public void _frmNodeFlows(CommandInterpreter ci) {
2320         boolean verbose = false;
2321         String verboseCheck = ci.nextArgument();
2322         if (verboseCheck != null) {
2323             verbose = verboseCheck.equals("true");
2324         }
2325
2326         // Dump per node database
2327         for (Entry<Node, Set<FlowEntryInstall>> entry : this.nodeFlows
2328                 .entrySet()) {
2329             Node node = entry.getKey();
2330             for (FlowEntryInstall flow : entry.getValue()) {
2331                 if (!verbose) {
2332                     ci.println(node + " " + flow.getFlowName());
2333                 } else {
2334                     ci.println(node + " " + flow.toString());
2335                 }
2336             }
2337         }
2338     }
2339
2340     public void _frmGroupFlows(CommandInterpreter ci) {
2341         boolean verbose = false;
2342         String verboseCheck = ci.nextArgument();
2343         if (verboseCheck != null) {
2344             verbose = verboseCheck.equalsIgnoreCase("true");
2345         }
2346
2347         // Dump per node database
2348         for (Entry<String, Set<FlowEntryInstall>> entry : this.groupFlows
2349                 .entrySet()) {
2350             String group = entry.getKey();
2351             ci.println("Group " + group + ":");
2352             for (FlowEntryInstall flow : entry.getValue()) {
2353                 if (!verbose) {
2354                     ci.println(flow.getNode() + " " + flow.getFlowName());
2355                 } else {
2356                     ci.println(flow.getNode() + " " + flow.toString());
2357                 }
2358             }
2359         }
2360     }
2361
2362     @Override
2363     public void flowRemoved(Node node, Flow flow) {
2364         log.trace("Received flow removed notification on {} for {}", node, flow);
2365         // For flow entry identification, only match and priority matter
2366         FlowEntry toFind = new FlowEntry("any", "any", flow, node);
2367         FlowEntryInstall installedEntry = this.findMatch(toFind, false);
2368         if (installedEntry == null) {
2369             log.trace("Entry is not know to us");
2370             return;
2371         }
2372
2373         // Update Static flow status
2374         for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2375             FlowConfig conf = entry.getValue();
2376             if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
2377                 // Update Configuration database
2378                 conf.toggleStatus();
2379                 break;
2380             }
2381         }
2382         // Update software views
2383         this.updateLocalDatabase(installedEntry, false);
2384     }
2385
2386 }