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