2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.forwardingrulesmanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.UnknownHostException;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.EnumSet;
19 import java.util.HashSet;
20 import java.util.List;
22 import java.util.Map.Entry;
24 import java.util.concurrent.BlockingQueue;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.Future;
32 import java.util.concurrent.LinkedBlockingQueue;
34 import org.eclipse.osgi.framework.console.CommandInterpreter;
35 import org.eclipse.osgi.framework.console.CommandProvider;
36 import org.opendaylight.controller.clustering.services.CacheConfigException;
37 import org.opendaylight.controller.clustering.services.CacheExistException;
38 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
39 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
40 import org.opendaylight.controller.clustering.services.IClusterServices;
41 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
42 import org.opendaylight.controller.connectionmanager.IConnectionManager;
43 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
44 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
45 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
46 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
47 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
48 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
50 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
51 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
52 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
53 import org.opendaylight.controller.sal.action.Action;
54 import org.opendaylight.controller.sal.action.ActionType;
55 import org.opendaylight.controller.sal.action.Controller;
56 import org.opendaylight.controller.sal.action.Flood;
57 import org.opendaylight.controller.sal.action.Output;
58 import org.opendaylight.controller.sal.action.PopVlan;
59 import org.opendaylight.controller.sal.core.ContainerFlow;
60 import org.opendaylight.controller.sal.core.IContainer;
61 import org.opendaylight.controller.sal.core.IContainerListener;
62 import org.opendaylight.controller.sal.core.Node;
63 import org.opendaylight.controller.sal.core.NodeConnector;
64 import org.opendaylight.controller.sal.core.Property;
65 import org.opendaylight.controller.sal.core.UpdateType;
66 import org.opendaylight.controller.sal.flowprogrammer.Flow;
67 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
68 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
69 import org.opendaylight.controller.sal.match.Match;
70 import org.opendaylight.controller.sal.match.MatchType;
71 import org.opendaylight.controller.sal.utils.EtherTypes;
72 import org.opendaylight.controller.sal.utils.GlobalConstants;
73 import org.opendaylight.controller.sal.utils.HexEncode;
74 import org.opendaylight.controller.sal.utils.IObjectReader;
75 import org.opendaylight.controller.sal.utils.IPProtocols;
76 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
77 import org.opendaylight.controller.sal.utils.NodeCreator;
78 import org.opendaylight.controller.sal.utils.ObjectReader;
79 import org.opendaylight.controller.sal.utils.ObjectWriter;
80 import org.opendaylight.controller.sal.utils.Status;
81 import org.opendaylight.controller.sal.utils.StatusCode;
82 import org.opendaylight.controller.switchmanager.IInventoryListener;
83 import org.opendaylight.controller.switchmanager.ISwitchManager;
84 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
85 import org.opendaylight.controller.switchmanager.Subnet;
86 import org.osgi.framework.BundleContext;
87 import org.osgi.framework.FrameworkUtil;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 * Class that manages forwarding rule installation and removal per container of
93 * the network. It also maintains the central repository of all the forwarding
94 * rules installed on the network nodes.
96 public class ForwardingRulesManager implements
97 IForwardingRulesManager,
98 PortGroupChangeListener,
101 IConfigurationContainerAware,
106 IFlowProgrammerListener {
107 private static final String NODEDOWN = "Node is Down";
108 private static final String SUCCESS = StatusCode.SUCCESS.toString();
109 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
110 private static final String PORTREMOVED = "Port removed";
111 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
112 private String frmFileName;
113 private String portGroupFileName;
114 private ConcurrentMap<Integer, FlowConfig> staticFlows;
115 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
116 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
117 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
118 private ConcurrentMap<String, Object> TSPolicies;
119 private boolean inContainerMode; // being used by global instance only
120 private boolean stopping;
123 * Flow database. It's the software view of what was requested to install
124 * and what is installed on the switch. It is indexed by the entry itself.
125 * The entry's hashcode resumes the network node index, the flow's priority
126 * and the flow's match. The value element is a class which contains the
127 * flow entry pushed by the applications modules and the respective
128 * container flow merged version. In absence of container flows, the two
129 * flow entries are the same.
131 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
132 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
134 * Per node and per group indexing
136 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
137 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
140 * Inactive flow list. This is for the global instance of FRM It will
141 * contain all the flow entries which were installed on the global container
142 * when the first container is created.
144 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
146 private IContainer container;
147 private Set<IForwardingRulesManagerAware> frmAware =
148 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
149 private PortGroupProvider portGroupProvider;
150 private IFlowProgrammerService programmer;
151 private IClusterContainerServices clusterContainerService = null;
152 private ISwitchManager switchManager;
153 private Thread frmEventHandler;
154 protected BlockingQueue<FRMEvent> pendingEvents;
156 // Distributes FRM programming in the cluster
157 private IConnectionManager connectionManager;
160 * Name clustered caches used to support FRM entry distribution these are by
161 * necessity non-transactional as long as need to be able to synchronize
162 * states also while a transaction is in progress
164 static final String WORKORDERCACHE = "frm.workOrder";
165 static final String WORKSTATUSCACHE = "frm.workStatus";
168 * Data structure responsible for distributing the FlowEntryInstall requests
169 * in the cluster. The key value is entry that is being either Installed or
170 * Updated or Delete. The value field is the same of the key value in case
171 * of Installation or Deletion, it's the new entry in case of Modification,
172 * this because the clustering caches don't allow null values.
174 * The logic behind this data structure is that the controller that initiate
175 * the request will place the order here, someone will pick it and then will
176 * remove from this data structure because is being served.
178 * TODO: We need to have a way to cleanup this data structure if entries are
179 * not picked by anyone, which is always a case can happen especially on
180 * Node disconnect cases.
182 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
185 * Data structure responsible for retrieving the results of the workOrder
186 * submitted to the cluster.
188 * The logic behind this data structure is that the controller that has
189 * executed the order will then place the result in workStatus signaling
190 * that there was a success or a failure.
192 * TODO: The workStatus entries need to have a lifetime associated in case
193 * of requestor controller leaving the cluster.
195 private ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
198 * Local Map used to hold the Future which a caller can use to monitor for
201 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
202 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
205 * Create an executor pool to create the distributionOrder, this is a stop
206 * gap solution caused by an issue with non-transactional caches in the
207 * implementation we use, being currently worked on. It has been noticed in
208 * fact that when non-transactional caches are being used sometime the key
209 * are no distributed to all the nodes properly. To workaround the issue
210 * transactional caches are being used, but there was a reason for using
211 * non-transactional caches to start with, in fact we needed to be able in
212 * the context of a northbound transaction to program the FRM entries
213 * irrespective of the fact that transaction would commit or no else we
214 * would not be able to achieve the entry programming and implement the
215 * scheme for recovery from network element failures. Bottom line, now in
216 * order to make sure an update on a transactional cache goes out while in a
217 * transaction that need to be initiated by a different thread.
219 private ExecutorService executor;
221 class DistributeOrderCallable implements Callable<Future<Status>> {
222 private FlowEntryInstall e;
223 private FlowEntryInstall u;
224 private UpdateType t;
225 DistributeOrderCallable(FlowEntryInstall e, FlowEntryInstall u, UpdateType t) {
232 public Future<Status> call() throws Exception {
233 if (e == null || t == null) {
234 logsync.error("Unexpected null Entry up update type");
237 // Create the work order and distribute it
238 FlowEntryDistributionOrder fe =
239 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
240 // First create the monitor job
241 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
242 logsync.trace("Node {} not local so sending fe {}", e.getNode(), fe);
243 workMonitor.put(fe, ret);
244 if (t.equals(UpdateType.CHANGED)) {
245 // Then distribute the work
246 workOrder.put(fe, u);
248 // Then distribute the work
249 workOrder.put(fe, e);
251 logsync.trace("WorkOrder requested");
252 // Now create an Handle to monitor the execution of the operation
259 * Entry being installed/updated/removed
261 * New entry will be placed after the update operation. Valid
262 * only for UpdateType.CHANGED, null for all the other cases
265 * @return a Future object for monitoring the progress of the result, or
266 * null in case the processing should take place locally
268 private Future<Status> distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u, UpdateType t) {
269 // A null entry it's an unexpected condition, anyway it's safe to keep
270 // the handling local
275 Node n = e.getNode();
276 if (!connectionManager.isLocal(n)) {
277 Callable<Future<Status>> worker = new DistributeOrderCallable(e, u, t);
278 if (worker != null) {
279 Future<Future<Status>> workerRes = this.executor.submit(worker);
281 return workerRes.get();
282 } catch (InterruptedException e1) {
283 // we where interrupted, not a big deal.
285 } catch (ExecutionException e1) {
287 "We got an execution exception {} we cannot much, so returning we don't have nothing to wait for",
294 logsync.trace("LOCAL Node {} so processing Entry:{} UpdateType:{}", n, e, t);
299 * Adds a flow entry onto the network node It runs various validity checks
300 * and derive the final container flows merged entries that will be
301 * attempted to be installed
304 * the original flow entry application requested to add
306 * the flag indicating if this is a asynchronous request
307 * @return the status of this request. In case of asynchronous call, it will
308 * contain the unique id assigned to this request
310 private Status addEntry(FlowEntry flowEntry, boolean async) {
313 if (flowEntry == null || flowEntry.getNode() == null) {
314 String msg = "Invalid FlowEntry";
315 String logMsg = msg + ": {}";
316 log.warn(logMsg, flowEntry);
317 return new Status(StatusCode.NOTACCEPTABLE, msg);
321 * Derive the container flow merged entries to install In presence of N
322 * container flows, we may end up with N different entries to install...
324 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
326 // Container Flow conflict Check
327 if (toInstallList.isEmpty()) {
328 String msg = "Flow Entry conflicts with all Container Flows";
329 String logMsg = msg + ": {}";
330 log.warn(logMsg, flowEntry);
331 return new Status(StatusCode.CONFLICT, msg);
334 // Derive the list of entries good to be installed
335 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
336 for (FlowEntryInstall entry : toInstallList) {
337 // Conflict Check: Verify new entry would not overwrite existing
339 if (this.installedSwView.containsKey(entry)) {
340 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
341 log.trace("Aborting to install {}", entry);
344 toInstallSafe.add(entry);
347 // Declare failure if all the container flow merged entries clash with
349 if (toInstallSafe.size() == 0) {
350 String msg = "A flow with same match and priority exists on the target node";
351 String logMsg = msg + ": {}";
352 log.warn(logMsg, flowEntry);
353 return new Status(StatusCode.CONFLICT, msg);
356 // Try to install an entry at the time
357 Status error = new Status(null, null);
358 Status succeded = null;
359 boolean oneSucceded = false;
360 for (FlowEntryInstall installEntry : toInstallSafe) {
362 // Install and update database
363 Status ret = addEntriesInternal(installEntry, async);
365 if (ret.isSuccess()) {
368 * The first successful status response will be returned For the
369 * asynchronous call, we can discard the container flow
370 * complication for now and assume we will always deal with one
371 * flow only per request
376 log.warn("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
380 return (oneSucceded) ? succeded : error;
384 * Given a flow entry and the list of container flows, it returns the list
385 * of container flow merged flow entries good to be installed on this
386 * container. If the list of container flows is null or empty, the install
387 * entry list will contain only one entry, the original flow entry. If the
388 * flow entry is congruent with all the N container flows, then the output
389 * install entry list will contain N entries. If the output list is empty,
390 * it means the passed flow entry conflicts with all the container flows.
393 * The list of container flows
394 * @return the list of container flow merged entries good to be installed on
397 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
398 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
400 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
401 // No container flows => entry good to be installed unchanged
402 toInstallList.add(new FlowEntryInstall(request.clone(), null));
404 // Create the list of entries to be installed. If the flow entry is
405 // not congruent with any container flow, no install entries will be
407 for (ContainerFlow cFlow : container.getContainerFlows()) {
408 if (cFlow.allowsFlow(request.getFlow())) {
409 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
413 return toInstallList;
417 * Modify a flow entry with a new one It runs various validity check and
418 * derive the final container flows merged flow entries to work with
420 * @param currentFlowEntry
421 * @param newFlowEntry
423 * the flag indicating if this is a asynchronous request
424 * @return the status of this request. In case of asynchronous call, it will
425 * contain the unique id assigned to this request
427 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
431 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
432 || newFlowEntry.getNode() == null) {
433 String msg = "Modify: Invalid FlowEntry";
434 String logMsg = msg + ": {} or {}";
435 log.warn(logMsg, currentFlowEntry, newFlowEntry);
436 return new Status(StatusCode.NOTACCEPTABLE, msg);
438 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
439 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
440 String msg = "Modify: Incompatible Flow Entries";
441 String logMsg = msg + ": {} and {}";
442 log.warn(logMsg, currentFlowEntry, newFlowEntry);
443 return new Status(StatusCode.NOTACCEPTABLE, msg);
447 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
448 String msg = "Modify skipped as flows are the same";
449 String logMsg = msg + ": {} and {}";
450 log.debug(logMsg, currentFlowEntry, newFlowEntry);
451 return new Status(StatusCode.SUCCESS, msg);
455 * Conflict Check: Verify the new entry would not conflict with an
456 * existing one. This is a loose check on the previous original flow
457 * entry requests. No check on the container flow merged flow entries
460 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
461 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
462 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
463 String logMsg = msg + ": {}";
464 log.warn(logMsg, currentFlowEntry);
465 return new Status(StatusCode.CONFLICT, msg);
468 // Derive the installed and toInstall entries
469 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
470 container.getContainerFlows());
471 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
473 if (toInstallList.isEmpty()) {
474 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
475 String logMsg = msg + ": {}";
476 log.warn(logMsg, newFlowEntry);
478 return new Status(StatusCode.CONFLICT, msg);
482 * If the two list sizes differ, it means the new flow entry does not
483 * satisfy the same number of container flows the current entry does.
484 * This is only possible when the new entry and current entry have
485 * different match. In this scenario the modification would ultimately
486 * be handled as a remove and add operations in the protocol plugin.
488 * Also, if any of the new flow entries would clash with an existing
489 * one, we cannot proceed with the modify operation, because it would
490 * fail for some entries and leave stale entries on the network node.
491 * Modify path can be taken only if it can be performed completely, for
494 * So, for the above two cases, to simplify, let's decouple the modify
495 * in: 1) remove current entries 2) install new entries
497 Status succeeded = null;
498 boolean decouple = false;
499 if (installedList.size() != toInstallList.size()) {
500 log.info("Modify: New flow entry does not satisfy the same "
501 + "number of container flows as the original entry does");
504 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
505 for (FlowEntryInstall installEntry : toInstallList) {
507 * Conflict Check: Verify the new entry would not overwrite another
510 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
511 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
512 log.info("Modify: new container flow merged flow entry clashes with existing flow");
515 toInstallSafe.add(installEntry);
520 // Remove current entries
521 for (FlowEntryInstall currEntry : installedList) {
522 this.removeEntryInternal(currEntry, async);
524 // Install new entries
525 for (FlowEntryInstall newEntry : toInstallSafe) {
526 succeeded = this.addEntriesInternal(newEntry, async);
530 * The two list have the same size and the entries to install do not
531 * clash with any existing flow on the network node. We assume here
532 * (and might be wrong) that the same container flows that were
533 * satisfied by the current entries are the same that are satisfied
534 * by the new entries. Let's take the risk for now.
536 * Note: modification has to be complete. If any entry modification
537 * fails, we need to stop, restore the already modified entries, and
540 Status retModify = null;
542 int size = toInstallList.size();
544 // Modify and update database
545 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
546 if (retModify.isSuccess()) {
552 // Check if uncompleted modify
554 log.warn("Unable to perform a complete modify for all the container flows merged entries");
555 // Restore original entries
558 log.info("Attempting to restore initial entries");
559 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
560 if (retExt.isSuccess()) {
566 // Fatal error, recovery failed
568 String msg = "Flow recovery failed ! Unrecoverable Error";
570 return new Status(StatusCode.INTERNALERROR, msg);
573 succeeded = retModify;
576 * The first successful status response will be returned. For the
577 * asynchronous call, we can discard the container flow complication for
578 * now and assume we will always deal with one flow only per request
584 * This is the function that modifies the final container flows merged
585 * entries on the network node and update the database. It expects that all
586 * the validity checks are passed
588 * @param currentEntries
591 * the flag indicating if this is a asynchronous request
592 * @return the status of this request. In case of asynchronous call, it will
593 * contain the unique id assigned to this request
595 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
596 Future<Status> futureStatus = distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
597 if (futureStatus != null) {
598 Status retStatus = new Status(StatusCode.UNDEFINED);
600 retStatus = futureStatus.get();
601 } catch (InterruptedException e) {
603 } catch (ExecutionException e) {
608 // Modify the flow on the network node
609 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
610 .getFlow(), newEntries.getInstall()
611 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
612 .getFlow(), newEntries.getInstall()
615 if (!status.isSuccess()) {
616 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
617 status.getDescription());
621 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
624 newEntries.setRequestId(status.getRequestId());
625 updateLocalDatabase(currentEntries, false);
626 updateLocalDatabase(newEntries, true);
633 * Remove a flow entry. If the entry is not present in the software view
634 * (entry or node not present), it return successfully
637 * the flow entry to remove
639 * the flag indicating if this is a asynchronous request
640 * @return the status of this request. In case of asynchronous call, it will
641 * contain the unique id assigned to this request
643 private Status removeEntry(FlowEntry flowEntry, boolean async) {
644 Status error = new Status(null, null);
647 if (flowEntry == null || flowEntry.getNode() == null) {
648 String msg = "Invalid FlowEntry";
649 String logMsg = msg + ": {}";
650 log.warn(logMsg, flowEntry);
651 return new Status(StatusCode.NOTACCEPTABLE, msg);
654 // Derive the container flows merged installed entries
655 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
657 Status succeeded = null;
658 boolean atLeastOneRemoved = false;
659 for (FlowEntryInstall entry : installedList) {
660 if (!installedSwView.containsKey(entry)) {
661 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
662 log.debug(logMsg, flowEntry);
663 if (installedList.size() == 1) {
664 // If we had only one entry to remove, we are done
665 return new Status(StatusCode.SUCCESS);
671 // Remove and update DB
672 Status ret = removeEntryInternal(entry, async);
674 if (!ret.isSuccess()) {
676 log.warn("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
677 if (installedList.size() == 1) {
678 // If we had only one entry to remove, this is fatal failure
683 atLeastOneRemoved = true;
688 * No worries if full removal failed. Consistency checker will take care
689 * of removing the stale entries later, or adjusting the software
690 * database if not in sync with hardware
692 return (atLeastOneRemoved) ? succeeded : error;
696 * This is the function that removes the final container flows merged entry
697 * from the network node and update the database. It expects that all the
698 * validity checks are passed
701 * the flow entry to remove
703 * the flag indicating if this is a asynchronous request
704 * @return the status of this request. In case of asynchronous call, it will
705 * contain the unique id assigned to this request
707 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
708 Future<Status> futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
709 if (futureStatus != null) {
710 Status retStatus = new Status(StatusCode.UNDEFINED);
712 retStatus = futureStatus.get();
713 } catch (InterruptedException e) {
715 } catch (ExecutionException e) {
720 // Mark the entry to be deleted (for CC just in case we fail)
724 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
725 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
728 if (!status.isSuccess()) {
729 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
730 status.getDescription());
733 log.trace("Removed {}", entry.getInstall());
736 updateLocalDatabase(entry, false);
743 * This is the function that installs the final container flow merged entry
744 * on the network node and updates the database. It expects that all the
745 * validity and conflict checks are passed. That means it does not check
746 * whether this flow would conflict or overwrite an existing one.
749 * the flow entry to install
751 * the flag indicating if this is a asynchronous request
752 * @return the status of this request. In case of asynchronous call, it will
753 * contain the unique id assigned to this request
755 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
756 Future<Status> futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
757 if (futureStatus != null) {
758 Status retStatus = new Status(StatusCode.UNDEFINED);
760 retStatus = futureStatus.get();
761 } catch (InterruptedException e) {
763 } catch (ExecutionException e) {
768 // Install the flow on the network node
769 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
770 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
773 if (!status.isSuccess()) {
774 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
775 status.getDescription());
779 log.trace("Added {}", entry.getInstall());
782 entry.setRequestId(status.getRequestId());
783 updateLocalDatabase(entry, true);
790 * Returns true if the flow conflicts with all the container's flows. This
791 * means that if the function returns true, the passed flow entry is
792 * congruent with at least one container flow, hence it is good to be
793 * installed on this container.
796 * @return true if flow conflicts with all the container flows, false
799 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
800 List<ContainerFlow> cFlowList = container.getContainerFlows();
802 // Validity check and avoid unnecessary computation
803 // Also takes care of default container where no container flows are
805 if (cFlowList == null || cFlowList.isEmpty()) {
809 for (ContainerFlow cFlow : cFlowList) {
810 if (cFlow.allowsFlow(flowEntry.getFlow())) {
811 // Entry is allowed by at least one container flow: good to go
818 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
819 // Update the software view
820 updateSwViewes(entry, add);
822 // Update node indexed flow database
823 updateNodeFlowsDB(entry, add);
825 // Update group indexed flow database
826 updateGroupFlowsDB(entry, add);
830 * Update the node mapped flows database
832 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
834 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
835 installedSwView.put(flowEntries, flowEntries);
837 originalSwView.remove(flowEntries.getOriginal());
838 installedSwView.remove(flowEntries);
843 * Update the node mapped flows database
845 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
846 Node node = flowEntries.getNode();
848 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
849 if (nodeIndeces == null) {
853 nodeIndeces = new ArrayList<FlowEntryInstall>();
858 nodeIndeces.add(flowEntries);
860 nodeIndeces.remove(flowEntries);
863 // Update cache across cluster
864 if (nodeIndeces.isEmpty()) {
865 this.nodeFlows.remove(node);
867 this.nodeFlows.put(node, nodeIndeces);
872 * Update the group name mapped flows database
874 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
875 String groupName = flowEntries.getGroupName();
877 // Flow may not be part of a group
878 if (groupName == null) {
882 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
883 if (indices == null) {
887 indices = new ArrayList<FlowEntryInstall>();
892 indices.add(flowEntries);
894 indices.remove(flowEntries);
897 // Update cache across cluster
898 if (indices.isEmpty()) {
899 this.groupFlows.remove(groupName);
901 this.groupFlows.put(groupName, indices);
906 * Remove a flow entry that has been added previously First checks if the
907 * entry is effectively present in the local database
909 @SuppressWarnings("unused")
910 private Status removeEntry(Node node, String flowName) {
911 FlowEntryInstall target = null;
914 for (FlowEntryInstall entry : installedSwView.values()) {
915 if (entry.equalsByNodeAndName(node, flowName)) {
921 // If it is not there, stop any further processing
922 if (target == null) {
923 return new Status(StatusCode.SUCCESS, "Entry is not present");
927 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
930 if (status.isSuccess()) {
931 updateLocalDatabase(target, false);
934 log.warn("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
935 status.getDescription());
942 public Status installFlowEntry(FlowEntry flowEntry) {
944 if (isContainerModeAllowed(flowEntry)) {
945 status = addEntry(flowEntry, false);
947 String msg = "Controller in container mode: Install Refused";
948 String logMsg = msg + ": {}";
949 status = new Status(StatusCode.NOTACCEPTABLE, msg);
950 log.warn(logMsg, flowEntry);
956 public Status installFlowEntryAsync(FlowEntry flowEntry) {
958 if (isContainerModeAllowed(flowEntry)) {
959 status = addEntry(flowEntry, true);
961 String msg = "Controller in container mode: Install Refused";
962 status = new Status(StatusCode.NOTACCEPTABLE, msg);
969 public Status uninstallFlowEntry(FlowEntry flowEntry) {
971 if (isContainerModeAllowed(flowEntry)) {
972 status = removeEntry(flowEntry, false);
974 String msg = "Controller in container mode: Uninstall Refused";
975 String logMsg = msg + ": {}";
976 status = new Status(StatusCode.NOTACCEPTABLE, msg);
977 log.warn(logMsg, flowEntry);
983 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
985 if (isContainerModeAllowed(flowEntry)) {
986 status = removeEntry(flowEntry, true);
988 String msg = "Controller in container mode: Uninstall Refused";
989 status = new Status(StatusCode.NOTACCEPTABLE, msg);
996 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
997 Status status = null;
998 if (isContainerModeAllowed(currentFlowEntry)) {
999 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1001 String msg = "Controller in container mode: Modify Refused";
1002 String logMsg = msg + ": {}";
1003 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1004 log.warn(logMsg, newFlowEntry);
1010 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1011 Status status = null;
1012 if (isContainerModeAllowed(currentFlowEntry)) {
1013 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
1015 String msg = "Controller in container mode: Modify Refused";
1016 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1023 * Returns whether the specified flow entry is allowed to be
1024 * installed/removed/modified based on the current container mode status.
1025 * This call always returns true in the container instance of forwarding
1026 * rules manager. It is meant for the global instance only (default
1027 * container) of forwarding rules manager. Idea is that for assuring
1028 * container isolation of traffic, flow installation in default container is
1029 * blocked when in container mode (containers are present). The only flows
1030 * that are allowed in container mode in the default container are the
1031 * proactive flows, the ones automatically installed on the network node
1032 * which forwarding mode has been configured to "proactive". These flows are
1033 * needed by controller to discover the nodes topology and to discover the
1034 * attached hosts for some SDN switches.
1037 * The flow entry to be installed/removed/modified
1038 * @return true if not in container mode or if flowEntry is internally
1041 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1042 return (!inContainerMode) ? true : flowEntry.isInternal();
1046 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1048 * Run a check on the original entries to decide whether to go with a
1049 * add or modify method. A loose check means only check against the
1050 * original flow entry requests and not against the installed flow
1051 * entries which are the result of the original entry merged with the
1052 * container flow(s) (if any). The modifyFlowEntry method in presence of
1053 * conflicts with the Container flows (if any) would revert back to a
1054 * delete + add pattern
1056 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1058 if (currentFlowEntry != null) {
1059 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1061 return installFlowEntry(newFlowEntry);
1066 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1068 * Run a check on the original entries to decide whether to go with a
1069 * add or modify method. A loose check means only check against the
1070 * original flow entry requests and not against the installed flow
1071 * entries which are the result of the original entry merged with the
1072 * container flow(s) (if any). The modifyFlowEntry method in presence of
1073 * conflicts with the Container flows (if any) would revert back to a
1074 * delete + add pattern
1076 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1078 if (currentFlowEntry != null) {
1079 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1081 return installFlowEntryAsync(newFlowEntry);
1086 public Status uninstallFlowEntryGroup(String groupName) {
1087 if (groupName == null || groupName.isEmpty()) {
1088 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1090 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1091 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1093 if (inContainerMode) {
1094 String msg = "Controller in container mode: Group Uninstall Refused";
1095 String logMsg = msg + ": {}";
1096 log.warn(logMsg, groupName);
1097 return new Status(StatusCode.NOTACCEPTABLE, msg);
1099 int toBeRemoved = 0;
1101 if (groupFlows.containsKey(groupName)) {
1102 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1103 toBeRemoved = list.size();
1104 for (FlowEntryInstall entry : list) {
1105 Status status = this.removeEntry(entry.getOriginal(), false);
1106 if (status.isSuccess()) {
1109 error = status.getDescription();
1113 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1114 "Not all the flows were removed: " + error);
1118 public Status uninstallFlowEntryGroupAsync(String groupName) {
1119 if (groupName == null || groupName.isEmpty()) {
1120 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1122 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1123 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1125 if (inContainerMode) {
1126 String msg = "Controller in container mode: Group Uninstall Refused";
1127 String logMsg = msg + ": {}";
1128 log.warn(logMsg, groupName);
1129 return new Status(StatusCode.NOTACCEPTABLE, msg);
1131 if (groupFlows.containsKey(groupName)) {
1132 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1133 for (FlowEntryInstall entry : list) {
1134 this.removeEntry(entry.getOriginal(), true);
1137 return new Status(StatusCode.SUCCESS);
1141 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1142 return entryConflictsWithContainerFlows(flowEntry);
1146 * Updates all installed flows because the container flow got updated This
1147 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1148 * Reinstall of all flows This is needed because a new container flows
1149 * merged flow may conflict with an existing old container flows merged flow
1150 * on the network node
1152 private void updateFlowsContainerFlow() {
1153 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1154 // First remove all installed entries
1155 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1156 FlowEntryInstall current = entry.getValue();
1157 // Store the original entry
1158 toReInstall.add(current.getOriginal());
1159 // Remove the old couples. No validity checks to be run, use the
1161 this.removeEntryInternal(current, false);
1163 // Then reinstall the original entries
1164 for (FlowEntry entry : toReInstall) {
1165 // Reinstall the original flow entries, via the regular path: new
1166 // cFlow merge + validations
1167 this.installFlowEntry(entry);
1171 private void nonClusterObjectCreate() {
1172 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1173 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1174 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
1175 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
1176 TSPolicies = new ConcurrentHashMap<String, Object>();
1177 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1178 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1179 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1180 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1181 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1184 private void registerWithOSGIConsole() {
1185 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1186 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1190 public void setTSPolicyData(String policyname, Object o, boolean add) {
1193 /* Check if this policy already exists */
1194 if (!(TSPolicies.containsKey(policyname))) {
1195 TSPolicies.put(policyname, o);
1198 TSPolicies.remove(policyname);
1200 if (frmAware != null) {
1201 synchronized (frmAware) {
1202 for (IForwardingRulesManagerAware frma : frmAware) {
1204 frma.policyUpdate(policyname, add);
1205 } catch (Exception e) {
1206 log.warn("Exception on callback", e);
1214 public Map<String, Object> getTSPolicyData() {
1219 public Object getTSPolicyData(String policyName) {
1220 if (TSPolicies.containsKey(policyName)) {
1221 return TSPolicies.get(policyName);
1228 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1229 List<FlowEntry> list = new ArrayList<FlowEntry>();
1230 if (policyName != null && !policyName.trim().isEmpty()) {
1231 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1232 if (policyName.equals(entry.getKey().getGroupName())) {
1233 list.add(entry.getKey().clone());
1241 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1242 List<FlowEntry> list = new ArrayList<FlowEntry>();
1243 if (policyName != null && !policyName.trim().isEmpty()) {
1244 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1245 if (policyName.equals(entry.getKey().getGroupName())) {
1246 list.add(entry.getKey().getInstall().clone());
1254 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1256 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1257 if (flow.getFlowName().equals(flowName)) {
1258 FlowEntry currentFlowEntry = flow.getOriginal();
1259 FlowEntry newFlowEntry = currentFlowEntry.clone();
1260 for (NodeConnector dstPort : portList) {
1261 newFlowEntry.getFlow().addAction(new Output(dstPort));
1263 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1264 if (error.isSuccess()) {
1265 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1267 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1268 currentFlowEntry.toString(), error.getDescription());
1273 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1277 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1278 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1279 FlowEntryInstall flow = this.installedSwView.get(index);
1280 if (flow.getFlowName().equals(flowName)) {
1281 FlowEntry currentFlowEntry = flow.getOriginal();
1282 FlowEntry newFlowEntry = currentFlowEntry.clone();
1283 for (NodeConnector dstPort : portList) {
1284 Action action = new Output(dstPort);
1285 newFlowEntry.getFlow().removeAction(action);
1287 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1288 if (status.isSuccess()) {
1289 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1291 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1292 currentFlowEntry.toString(), status.getDescription());
1297 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1301 * This function assumes the target flow has only one output port
1304 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1305 FlowEntry currentFlowEntry = null;
1306 FlowEntry newFlowEntry = null;
1309 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1310 FlowEntryInstall flow = this.installedSwView.get(index);
1311 if (flow.getFlowName().equals(flowName)) {
1312 currentFlowEntry = flow.getOriginal();
1316 if (currentFlowEntry == null) {
1317 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1321 // Create a flow copy with the new output port
1322 newFlowEntry = currentFlowEntry.clone();
1323 Action target = null;
1324 for (Action action : newFlowEntry.getFlow().getActions()) {
1325 if (action.getType() == ActionType.OUTPUT) {
1330 newFlowEntry.getFlow().removeAction(target);
1331 newFlowEntry.getFlow().addAction(new Output(outPort));
1333 // Modify on network node
1334 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1336 if (status.isSuccess()) {
1337 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1339 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1340 status.getDescription());
1346 public NodeConnector getOutputPort(Node node, String flowName) {
1347 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1348 FlowEntryInstall flow = this.installedSwView.get(index);
1349 if (flow.getFlowName().equals(flowName)) {
1350 for (Action action : flow.getOriginal().getFlow().getActions()) {
1351 if (action.getType() == ActionType.OUTPUT) {
1352 return ((Output) action).getPort();
1360 private void cacheStartup() {
1365 @SuppressWarnings("deprecation")
1366 private void allocateCaches() {
1367 if (this.clusterContainerService == null) {
1368 log.warn("Un-initialized clusterContainerService, can't create cache");
1372 log.debug("Allocating caches for Container {}", container.getName());
1375 clusterContainerService.createCache("frm.originalSwView",
1376 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1378 clusterContainerService.createCache("frm.installedSwView",
1379 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1381 clusterContainerService.createCache("frm.inactiveFlows",
1382 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1384 clusterContainerService.createCache("frm.nodeFlows",
1385 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1387 clusterContainerService.createCache("frm.groupFlows",
1388 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1390 clusterContainerService.createCache("frm.staticFlows",
1391 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1393 clusterContainerService.createCache("frm.flowsSaveEvent",
1394 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1396 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1397 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1399 clusterContainerService.createCache("frm.portGroupConfigs",
1400 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1402 clusterContainerService.createCache("frm.portGroupData",
1403 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1405 clusterContainerService.createCache("frm.TSPolicies",
1406 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1408 clusterContainerService.createCache(WORKSTATUSCACHE,
1409 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1411 clusterContainerService.createCache(WORKORDERCACHE,
1412 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1414 } catch (CacheConfigException cce) {
1415 log.error("CacheConfigException");
1416 } catch (CacheExistException cce) {
1417 log.error("CacheExistException");
1421 @SuppressWarnings({ "unchecked", "deprecation" })
1422 private void retrieveCaches() {
1423 ConcurrentMap<?, ?> map;
1425 if (this.clusterContainerService == null) {
1426 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1427 nonClusterObjectCreate();
1431 log.debug("Retrieving Caches for Container {}", container.getName());
1433 map = clusterContainerService.getCache("frm.originalSwView");
1435 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1437 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1440 map = clusterContainerService.getCache("frm.installedSwView");
1442 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1444 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1447 map = clusterContainerService.getCache("frm.inactiveFlows");
1449 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1451 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1454 map = clusterContainerService.getCache("frm.nodeFlows");
1456 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1458 log.error("Retrieval of cache failed for Container {}", container.getName());
1461 map = clusterContainerService.getCache("frm.groupFlows");
1463 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1465 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1468 map = clusterContainerService.getCache("frm.staticFlows");
1470 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1472 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1475 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1477 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1479 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1482 map = clusterContainerService.getCache("frm.portGroupConfigs");
1484 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1486 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1489 map = clusterContainerService.getCache("frm.portGroupData");
1491 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1493 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1496 map = clusterContainerService.getCache("frm.TSPolicies");
1498 TSPolicies = (ConcurrentMap<String, Object>) map;
1500 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1503 map = clusterContainerService.getCache(WORKORDERCACHE);
1505 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1507 log.error("Retrieval of " + WORKORDERCACHE + " cache failed for Container {}", container.getName());
1510 map = clusterContainerService.getCache(WORKSTATUSCACHE);
1512 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1514 log.error("Retrieval of " + WORKSTATUSCACHE + " cache failed for Container {}", container.getName());
1518 private boolean flowConfigExists(FlowConfig config) {
1519 // Flow name has to be unique on per node id basis
1520 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1521 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1529 public Status addStaticFlow(FlowConfig config) {
1530 // Configuration object validation
1531 Status status = config.validate(container);
1532 if (!status.isSuccess()) {
1533 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1534 String error = "Invalid Configuration (" + status.getDescription() + ")";
1535 config.setStatus(error);
1536 return new Status(StatusCode.BADREQUEST, error);
1538 return addStaticFlowInternal(config, false);
1542 * Private method to add a static flow configuration which does not run any
1543 * validation on the passed FlowConfig object. If restore is set to true,
1544 * configuration is stored in configuration database regardless the
1545 * installation on the network node was successful. This is useful at boot
1546 * when static flows are present in startup configuration and are read
1547 * before the switches connects.
1550 * The static flow configuration
1552 * if true, the configuration is stored regardless the
1553 * installation on the network node was successful
1554 * @return The status of this request
1556 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1557 boolean multipleFlowPush = false;
1560 config.setStatus(SUCCESS);
1563 if (flowConfigExists(config)) {
1564 error = "Entry with this name on specified switch already exists";
1565 log.warn("Entry with this name on specified switch already exists: {}", config);
1566 config.setStatus(error);
1567 return new Status(StatusCode.CONFLICT, error);
1570 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1571 for (String portGroupName : portGroupConfigs.keySet()) {
1572 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1573 multipleFlowPush = true;
1577 if (!multipleFlowPush) {
1578 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1579 error = "Invalid Configuration (Invalid PortGroup Name)";
1580 config.setStatus(error);
1581 return new Status(StatusCode.BADREQUEST, error);
1586 * If requested program the entry in hardware first before updating the
1589 if (!multipleFlowPush) {
1591 if (config.installInHw()) {
1592 FlowEntry entry = config.getFlowEntry();
1593 status = this.installFlowEntry(entry);
1594 if (!status.isSuccess()) {
1595 config.setStatus(status.getDescription());
1604 * When the control reaches this point, either of the following
1605 * conditions is true 1. This is a single entry configuration (non
1606 * PortGroup) and the hardware installation is successful 2. This is a
1607 * multiple entry configuration (PortGroup) and hardware installation is
1608 * NOT done directly on this event. 3. The User prefers to retain the
1609 * configuration in Controller and skip hardware installation.
1611 * Hence it is safe to update the StaticFlow DB at this point.
1613 * Note : For the case of PortGrouping, it is essential to have this DB
1614 * populated before the PortGroupListeners can query for the DB
1615 * triggered using portGroupChanged event...
1617 Integer ordinal = staticFlowsOrdinal.get(0);
1618 staticFlowsOrdinal.put(0, ++ordinal);
1619 staticFlows.put(ordinal, config);
1621 if (multipleFlowPush) {
1622 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1623 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1624 if (existingData != null) {
1625 portGroupChanged(pgconfig, existingData, true);
1628 return new Status(StatusCode.SUCCESS);
1631 private void addStaticFlowsToSwitch(Node node) {
1632 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1633 FlowConfig config = entry.getValue();
1634 if (config.isPortGroupEnabled()) {
1637 if (config.getNode().equals(node)) {
1638 if (config.installInHw() && !config.getStatus().equals(SUCCESS)) {
1639 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1640 config.setStatus(status.getDescription());
1644 // Update cluster cache
1645 refreshClusterStaticFlowsStatus(node);
1648 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1649 log.trace("Updating Static Flow configs on node down: {}", node);
1651 List<Integer> toRemove = new ArrayList<Integer>();
1652 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1654 FlowConfig config = entry.getValue();
1656 if (config.isPortGroupEnabled()) {
1660 if (config.installInHw() && config.getNode().equals(node)) {
1661 if (config.isInternalFlow()) {
1662 // Take note of this controller generated static flow
1663 toRemove.add(entry.getKey());
1665 config.setStatus(NODEDOWN);
1669 // Remove controller generated static flows for this node
1670 for (Integer index : toRemove) {
1671 staticFlows.remove(index);
1673 // Update cluster cache
1674 refreshClusterStaticFlowsStatus(node);
1678 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1679 log.trace("Updating Static Flow configs on container mode change: {}", update);
1681 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1682 FlowConfig config = entry.getValue();
1683 if (config.isPortGroupEnabled()) {
1686 if (config.installInHw() && !config.isInternalFlow()) {
1689 config.setStatus("Removed from node because in container mode");
1692 config.setStatus(SUCCESS);
1698 // Update cluster cache
1699 refreshClusterStaticFlowsStatus(null);
1703 public Status removeStaticFlow(FlowConfig config) {
1705 * No config.isInternal() check as NB does not take this path and GUI
1706 * cannot issue a delete on an internal generated flow. We need this
1707 * path to be accessible when switch mode is changed from proactive to
1708 * reactive, so that we can remove the internal generated LLDP and ARP
1712 // Look for the target configuration entry
1714 FlowConfig target = null;
1715 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1716 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1717 key = entry.getKey();
1718 target = entry.getValue();
1722 if (target == null) {
1723 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1726 // Program the network node
1727 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1729 // Update configuration database if programming was successful
1730 if (status.isSuccess()) {
1731 staticFlows.remove(key);
1738 public Status removeStaticFlow(String name, Node node) {
1739 // Look for the target configuration entry
1741 FlowConfig target = null;
1742 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1743 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1744 key = mapEntry.getKey();
1745 target = mapEntry.getValue();
1749 if (target == null) {
1750 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1753 // Validity check for api3 entry point
1754 if (target.isInternalFlow()) {
1755 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1756 String logMsg = msg + ": {}";
1757 log.warn(logMsg, name);
1758 return new Status(StatusCode.NOTACCEPTABLE, msg);
1761 if (target.isPortGroupEnabled()) {
1762 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1763 String logMsg = msg + ": {}";
1764 log.warn(logMsg, name);
1765 return new Status(StatusCode.NOTACCEPTABLE, msg);
1768 // Program the network node
1769 Status status = this.removeEntry(target.getFlowEntry(), false);
1771 // Update configuration database if programming was successful
1772 if (status.isSuccess()) {
1773 staticFlows.remove(key);
1780 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1781 // Validity check for api3 entry point
1782 if (newFlowConfig.isInternalFlow()) {
1783 String msg = "Invalid operation: Controller generated flow cannot be modified";
1784 String logMsg = msg + ": {}";
1785 log.warn(logMsg, newFlowConfig);
1786 return new Status(StatusCode.NOTACCEPTABLE, msg);
1790 Status status = newFlowConfig.validate(container);
1791 if (!status.isSuccess()) {
1792 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1793 newFlowConfig.setStatus(msg);
1794 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1795 return new Status(StatusCode.BADREQUEST, msg);
1798 FlowConfig oldFlowConfig = null;
1799 Integer index = null;
1800 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1801 FlowConfig entry = mapEntry.getValue();
1802 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1803 oldFlowConfig = entry;
1804 index = mapEntry.getKey();
1809 if (oldFlowConfig == null) {
1810 String msg = "Attempt to modify a non existing static flow";
1811 String logMsg = msg + ": {}";
1812 log.warn(logMsg, newFlowConfig);
1813 return new Status(StatusCode.NOTFOUND, msg);
1816 // Do not attempt to reinstall the flow, warn user
1817 if (newFlowConfig.equals(oldFlowConfig)) {
1818 String msg = "No modification detected";
1819 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1820 return new Status(StatusCode.SUCCESS, msg);
1823 // If flow is installed, program the network node
1824 status = new Status(StatusCode.SUCCESS, "Saved in config");
1825 if (oldFlowConfig.installInHw()) {
1826 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1829 // Update configuration database if programming was successful
1830 if (status.isSuccess()) {
1831 newFlowConfig.setStatus(status.getDescription());
1832 staticFlows.put(index, newFlowConfig);
1839 public Status toggleStaticFlowStatus(String name, Node node) {
1840 return toggleStaticFlowStatus(getStaticFlow(name, node));
1844 public Status toggleStaticFlowStatus(FlowConfig config) {
1845 if (config == null) {
1846 String msg = "Invalid request: null flow config";
1848 return new Status(StatusCode.BADREQUEST, msg);
1850 // Validity check for api3 entry point
1851 if (config.isInternalFlow()) {
1852 String msg = "Invalid operation: Controller generated flow cannot be modified";
1853 String logMsg = msg + ": {}";
1854 log.warn(logMsg, config);
1855 return new Status(StatusCode.NOTACCEPTABLE, msg);
1858 // Find the config entry
1860 FlowConfig target = null;
1861 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1862 FlowConfig conf = entry.getValue();
1863 if (conf.isByNameAndNodeIdEqual(config)) {
1864 key = entry.getKey();
1869 if (target != null) {
1870 Status status = target.validate(container);
1871 if (!status.isSuccess()) {
1872 log.warn(status.getDescription());
1875 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1876 .installFlowEntry(target.getFlowEntry());
1877 if (status.isSuccess()) {
1878 // Update Configuration database
1879 target.setStatus(SUCCESS);
1880 target.toggleInstallation();
1881 staticFlows.put(key, target);
1886 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1890 * Reinsert all static flows entries in the cache to force cache updates in
1891 * the cluster. This is useful when only some parameters were changed in the
1892 * entries, like the status.
1895 * The node for which the static flow configurations have to be
1896 * refreshed. If null, all nodes static flows will be refreshed.
1898 private void refreshClusterStaticFlowsStatus(Node node) {
1899 // Refresh cluster cache
1900 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1901 if (node == null || entry.getValue().getNode().equals(node)) {
1902 staticFlows.put(entry.getKey(), entry.getValue());
1908 * Uninstall all the non-internal Flow Entries present in the software view.
1909 * If requested, a copy of each original flow entry will be stored in the
1910 * inactive list so that it can be re-applied when needed (This is typically
1911 * the case when running in the default container and controller moved to
1914 * @param preserveFlowEntries
1915 * if true, a copy of each original entry is stored in the
1918 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1919 log.info("Uninstalling all non-internal flows");
1921 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1923 // Store entries / create target list
1924 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1925 FlowEntryInstall flowEntries = mapEntry.getValue();
1926 // Skip internal generated static flows
1927 if (!flowEntries.isInternal()) {
1928 toRemove.add(flowEntries);
1929 // Store the original entries if requested
1930 if (preserveFlowEntries) {
1931 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1936 // Now remove the entries
1937 for (FlowEntryInstall flowEntryHw : toRemove) {
1938 Status status = this.removeEntryInternal(flowEntryHw, false);
1939 if (!status.isSuccess()) {
1940 log.warn("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1946 * Re-install all the Flow Entries present in the inactive list The inactive
1947 * list will be empty at the end of this call This function is called on the
1948 * default container instance of FRM only when the last container is deleted
1950 private void reinstallAllFlowEntries() {
1951 log.info("Reinstalling all inactive flows");
1953 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1954 this.addEntry(flowEntry, false);
1957 // Empty inactive list in any case
1958 inactiveFlows.clear();
1962 public List<FlowConfig> getStaticFlows() {
1963 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1966 // TODO: need to come out with a better algorithm for maintaining the order
1967 // of the configuration entries
1968 // with actual one, index associated to deleted entries cannot be reused and
1970 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1971 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1972 for (int i = 0; i <= maxKey; i++) {
1973 FlowConfig entry = flowMap.get(i);
1974 if (entry != null) {
1975 orderedList.add(entry);
1982 public FlowConfig getStaticFlow(String name, Node node) {
1983 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1984 if (entry.getValue().isByNameAndNodeIdEqual(name, node)) {
1985 return entry.getValue();
1992 public List<FlowConfig> getStaticFlows(Node node) {
1993 List<FlowConfig> list = new ArrayList<FlowConfig>();
1994 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1995 if (entry.getValue().onNode(node)) {
1996 list.add(entry.getValue());
2003 public List<String> getStaticFlowNamesForNode(Node node) {
2004 List<String> list = new ArrayList<String>();
2005 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2006 if (entry.getValue().onNode(node)) {
2007 list.add(entry.getValue().getName());
2014 public List<Node> getListNodeWithConfiguredFlows() {
2015 Set<Node> set = new HashSet<Node>();
2016 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2017 set.add(entry.getValue().getNode());
2019 return new ArrayList<Node>(set);
2022 @SuppressWarnings("unchecked")
2023 private void loadFlowConfiguration() {
2024 ObjectReader objReader = new ObjectReader();
2025 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2028 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2031 if (pgConfig != null) {
2032 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2033 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2037 if (confList == null) {
2042 for (Integer key : confList.keySet()) {
2043 if (key.intValue() > maxKey) {
2044 maxKey = key.intValue();
2048 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2049 addStaticFlowInternal(conf, true);
2054 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2055 return ois.readObject();
2059 public Status saveConfig() {
2060 return saveConfigInternal();
2063 private Status saveConfigInternal() {
2064 ObjectWriter objWriter = new ObjectWriter();
2065 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2066 for (Integer ordinal : staticFlows.keySet()) {
2067 FlowConfig config = staticFlows.get(ordinal);
2068 // Do not save dynamic and controller generated static flows
2069 if (config.isDynamic() || config.isInternalFlow()) {
2072 nonDynamicFlows.put(ordinal, config);
2074 objWriter.write(nonDynamicFlows, frmFileName);
2075 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2076 return new Status(StatusCode.SUCCESS, null);
2080 public void subnetNotify(Subnet sub, boolean add) {
2083 private void installImplicitARPReplyPunt(Node node) {
2089 List<String> puntAction = new ArrayList<String>();
2090 puntAction.add(ActionType.CONTROLLER.toString());
2092 FlowConfig allowARP = new FlowConfig();
2093 allowARP.setInstallInHw(true);
2094 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
2095 allowARP.setPriority("500");
2096 allowARP.setNode(node);
2097 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2098 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
2099 allowARP.setActions(puntAction);
2100 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
2106 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2109 * This method can be called from within the OSGi framework context,
2110 * given the programming operation can take sometime, it not good
2111 * pratice to have in it's context operations that can take time,
2112 * hence moving off to a different thread for async processing.
2115 public void modeChangeNotify(final Node node, final boolean proactive) {
2116 Callable<Status> modeChangeCallable = new Callable<Status>() {
2118 public Status call() throws Exception {
2119 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2121 List<String> puntAction = new ArrayList<String>();
2122 puntAction.add(ActionType.CONTROLLER.toString());
2124 FlowConfig allowARP = new FlowConfig();
2125 allowARP.setInstallInHw(true);
2126 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2127 allowARP.setPriority("1");
2128 allowARP.setNode(node);
2129 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2131 allowARP.setActions(puntAction);
2132 defaultConfigs.add(allowARP);
2134 FlowConfig allowLLDP = new FlowConfig();
2135 allowLLDP.setInstallInHw(true);
2136 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2137 allowLLDP.setPriority("1");
2138 allowLLDP.setNode(node);
2139 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2141 allowLLDP.setActions(puntAction);
2142 defaultConfigs.add(allowLLDP);
2144 List<String> dropAction = new ArrayList<String>();
2145 dropAction.add(ActionType.DROP.toString());
2147 FlowConfig dropAllConfig = new FlowConfig();
2148 dropAllConfig.setInstallInHw(true);
2149 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2150 + FlowConfig.INTERNALSTATICFLOWEND);
2151 dropAllConfig.setPriority("0");
2152 dropAllConfig.setNode(node);
2153 dropAllConfig.setActions(dropAction);
2154 defaultConfigs.add(dropAllConfig);
2156 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2157 for (FlowConfig fc : defaultConfigs) {
2158 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2159 if (status.isSuccess()) {
2160 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2162 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2166 return new Status(StatusCode.SUCCESS);
2171 * Execute the work outside the caller context, this could be an
2172 * expensive operation and we don't want to block the caller for it.
2174 this.executor.submit(modeChangeCallable);
2178 * Remove from the databases all the flows installed on the node
2182 private void cleanDatabaseForNode(Node node) {
2183 log.info("Cleaning Flow database for Node {}", node);
2184 if (nodeFlows.containsKey(node)) {
2185 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2187 for (FlowEntryInstall entry : toRemove) {
2188 updateLocalDatabase(entry, false);
2193 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2198 Match match = flow.getMatch();
2199 if (match.isPresent(MatchType.IN_PORT)) {
2200 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2201 if (matchPort.equals(nc)) {
2205 List<Action> actionsList = flow.getActions();
2206 if (actionsList != null) {
2207 for (Action action : actionsList) {
2208 if (action instanceof Output) {
2209 NodeConnector actionPort = ((Output) action).getPort();
2210 if (actionPort.equals(nc)) {
2220 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2221 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2225 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2229 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2230 FlowConfig derivedFlow = new FlowConfig(original);
2231 derivedFlow.setDynamic(true);
2232 derivedFlow.setPortGroup(null);
2233 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2234 derivedFlow.setIngressPort(port + "");
2238 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2239 for (FlowConfig staticFlow : staticFlows.values()) {
2240 if (staticFlow.getPortGroup() == null) {
2243 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2244 for (Short port : data.getPorts()) {
2245 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2246 addStaticFlowInternal(derivedFlow, false);
2252 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2253 for (FlowConfig staticFlow : staticFlows.values()) {
2254 if (staticFlow.getPortGroup() == null) {
2257 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2258 for (Short port : data.getPorts()) {
2259 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2260 removeStaticFlow(derivedFlow);
2267 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2268 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2269 Map<Node, PortGroup> existingData = portGroupData.get(config);
2270 if (existingData != null) {
2271 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2272 PortGroup existingPortGroup = existingData.get(entry.getKey());
2273 if (existingPortGroup == null) {
2275 existingData.put(entry.getKey(), entry.getValue());
2276 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2280 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2281 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2283 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2284 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2290 portGroupData.put(config, data);
2291 for (Node swid : data.keySet()) {
2292 addPortGroupFlows(config, swid, data.get(swid));
2299 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2300 PortGroupConfig config = portGroupConfigs.get(name);
2301 if (config != null) {
2305 if ((portGroupProvider == null) && !restore) {
2308 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2312 config = new PortGroupConfig(name, regex);
2313 portGroupConfigs.put(name, config);
2314 if (portGroupProvider != null) {
2315 portGroupProvider.createPortGroupConfig(config);
2321 public boolean delPortGroupConfig(String name) {
2322 PortGroupConfig config = portGroupConfigs.get(name);
2323 if (config == null) {
2327 if (portGroupProvider != null) {
2328 portGroupProvider.deletePortGroupConfig(config);
2330 portGroupConfigs.remove(name);
2334 private void usePortGroupConfig(String name) {
2335 PortGroupConfig config = portGroupConfigs.get(name);
2336 if (config == null) {
2339 if (portGroupProvider != null) {
2340 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2341 portGroupData.put(config, data);
2346 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2347 return portGroupConfigs;
2350 public boolean isPortGroupSupported() {
2351 if (portGroupProvider == null) {
2357 public void setIContainer(IContainer s) {
2361 public void unsetIContainer(IContainer s) {
2362 if (this.container == s) {
2363 this.container = null;
2368 public PortGroupProvider getPortGroupProvider() {
2369 return portGroupProvider;
2372 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2373 this.portGroupProvider = null;
2376 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2377 this.portGroupProvider = portGroupProvider;
2378 portGroupProvider.registerPortGroupChange(this);
2379 for (PortGroupConfig config : portGroupConfigs.values()) {
2380 portGroupProvider.createPortGroupConfig(config);
2384 public void setFrmAware(IForwardingRulesManagerAware obj) {
2385 this.frmAware.add(obj);
2388 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2389 this.frmAware.remove(obj);
2392 void setClusterContainerService(IClusterContainerServices s) {
2393 log.debug("Cluster Service set");
2394 this.clusterContainerService = s;
2397 void unsetClusterContainerService(IClusterContainerServices s) {
2398 if (this.clusterContainerService == s) {
2399 log.debug("Cluster Service removed!");
2400 this.clusterContainerService = null;
2404 private String getContainerName() {
2405 if (container == null) {
2406 return GlobalConstants.DEFAULT.toString();
2408 return container.getName();
2412 * Function called by the dependency manager when all the required
2413 * dependencies are satisfied
2417 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2418 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2420 inContainerMode = false;
2422 if (portGroupProvider != null) {
2423 portGroupProvider.registerPortGroupChange(this);
2428 registerWithOSGIConsole();
2431 * If we are not the first cluster node to come up, do not initialize
2432 * the static flow entries ordinal
2434 if (staticFlowsOrdinal.size() == 0) {
2435 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2438 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2440 // Initialize the event handler thread
2441 frmEventHandler = new Thread(new Runnable() {
2446 FRMEvent event = pendingEvents.take();
2447 if (event == null) {
2448 log.warn("Dequeued null event");
2451 if (event instanceof NodeUpdateEvent) {
2452 NodeUpdateEvent update = (NodeUpdateEvent) event;
2453 Node node = update.getNode();
2454 switch (update.getUpdateType()) {
2456 addStaticFlowsToSwitch(node);
2459 cleanDatabaseForNode(node);
2460 updateStaticFlowConfigsOnNodeDown(node);
2464 } else if (event instanceof ErrorReportedEvent) {
2465 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2466 processErrorEvent(errEvent);
2467 } else if (event instanceof WorkOrderEvent) {
2469 * Take care of handling the remote Work request
2471 WorkOrderEvent work = (WorkOrderEvent) event;
2472 FlowEntryDistributionOrder fe = work.getFe();
2474 logsync.trace("Executing the workOrder {}", fe);
2475 Status gotStatus = null;
2476 FlowEntryInstall feiCurrent = fe.getEntry();
2477 FlowEntryInstall feiNew = workOrder.get(fe.getEntry());
2478 switch (fe.getUpType()) {
2481 * TODO: Not still sure how to handle the
2484 gotStatus = addEntriesInternal(feiCurrent, true);
2487 gotStatus = modifyEntryInternal(feiCurrent, feiNew, true);
2490 gotStatus = removeEntryInternal(feiCurrent, true);
2494 workOrder.remove(fe);
2496 "The workOrder has been executed and now the status is being returned {}", fe);
2498 workStatus.put(fe, gotStatus);
2500 log.warn("Not expected null WorkOrder", work);
2502 } else if (event instanceof WorkStatusCleanup) {
2504 * Take care of handling the remote Work request
2506 WorkStatusCleanup work = (WorkStatusCleanup) event;
2507 FlowEntryDistributionOrder fe = work.getFe();
2509 logsync.trace("The workStatus {} is being removed", fe);
2510 workStatus.remove(fe);
2512 log.warn("Not expected null WorkStatus", work);
2515 log.warn("Dequeued unknown event {}", event.getClass()
2518 } catch (InterruptedException e) {
2519 // clear pending events
2520 pendingEvents.clear();
2524 }, "FRM EventHandler Collector");
2528 * Function called by the dependency manager when at least one dependency
2529 * become unsatisfied or when the component is shutting down because for
2530 * example bundle is being stopped.
2534 // Interrupt the thread
2535 frmEventHandler.interrupt();
2536 // Clear the pendingEvents queue
2537 pendingEvents.clear();
2539 workMonitor.clear();
2543 * Function called by dependency manager after "init ()" is called and after
2544 * the services provided by the class are registered in the service registry
2548 // Initialize graceful stop flag
2551 // Allocate the executor service
2552 this.executor = Executors.newSingleThreadExecutor();
2554 // Start event handler thread
2555 frmEventHandler.start();
2558 * Read startup and build database if we have not already gotten the
2559 * configurations synced from another node
2561 if (staticFlows.isEmpty()) {
2562 loadFlowConfiguration();
2567 * Function called by the dependency manager before the services exported by
2568 * the component are unregistered, this will be followed by a "destroy ()"
2573 uninstallAllFlowEntries(false);
2574 // Shutdown executor
2575 this.executor.shutdownNow();
2578 public void setFlowProgrammerService(IFlowProgrammerService service) {
2579 this.programmer = service;
2582 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2583 if (this.programmer == service) {
2584 this.programmer = null;
2588 public void setSwitchManager(ISwitchManager switchManager) {
2589 this.switchManager = switchManager;
2592 public void unsetSwitchManager(ISwitchManager switchManager) {
2593 if (this.switchManager == switchManager) {
2594 this.switchManager = null;
2599 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2600 if (!container.getName().equals(containerName)) {
2606 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2607 if (!container.getName().equals(containerName)) {
2610 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2611 container.getName(), t, current);
2613 * Whether it is an addition or removal, we have to recompute the merged
2614 * flows entries taking into account all the current container flows
2615 * because flow merging is not an injective function
2617 updateFlowsContainerFlow();
2621 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2622 if (!container.getName().equals(containerName)) {
2626 boolean updateStaticFlowCluster = false;
2631 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nc.getNode());
2632 if (nodeFlowEntries == null) {
2635 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2636 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nc)) {
2637 Status status = this.removeEntryInternal(fei, true);
2638 if (!status.isSuccess()) {
2642 * If the flow entry is a static flow, then update its
2645 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2646 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2647 if (flowConfig != null) {
2648 flowConfig.setStatus(PORTREMOVED);
2649 updateStaticFlowCluster = true;
2654 if (updateStaticFlowCluster) {
2655 refreshClusterStaticFlowsStatus(nc.getNode());
2659 List<FlowConfig> flowConfigForNode = getStaticFlows(nc.getNode());
2660 for (FlowConfig flowConfig : flowConfigForNode) {
2661 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nc)) {
2662 if (flowConfig.installInHw()) {
2663 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2664 if (!status.isSuccess()) {
2665 flowConfig.setStatus(status.getDescription());
2667 flowConfig.setStatus(SUCCESS);
2669 updateStaticFlowCluster = true;
2673 if (updateStaticFlowCluster) {
2674 refreshClusterStaticFlowsStatus(nc.getNode());
2684 public void containerModeUpdated(UpdateType update) {
2685 // Only default container instance reacts on this event
2686 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2692 * Controller is moving to container mode. We are in the default
2693 * container context, we need to remove all our non-internal flows
2694 * to prevent any container isolation breakage. We also need to
2695 * preserve our flow so that they can be re-installed if we move
2696 * back to non container mode (no containers).
2698 this.inContainerMode = true;
2699 this.uninstallAllFlowEntries(true);
2702 this.inContainerMode = false;
2703 this.reinstallAllFlowEntries();
2708 // Update our configuration DB
2709 updateStaticFlowConfigsOnContainerModeChange(update);
2712 protected abstract class FRMEvent {
2716 private class NodeUpdateEvent extends FRMEvent {
2717 private final Node node;
2718 private final UpdateType update;
2720 public NodeUpdateEvent(UpdateType update, Node node) {
2721 this.update = update;
2725 public UpdateType getUpdateType() {
2729 public Node getNode() {
2734 private class ErrorReportedEvent extends FRMEvent {
2735 private final long rid;
2736 private final Node node;
2737 private final Object error;
2739 public ErrorReportedEvent(long rid, Node node, Object error) {
2745 public long getRequestId() {
2749 public Object getError() {
2753 public Node getNode() {
2758 private class WorkOrderEvent extends FRMEvent {
2759 private FlowEntryDistributionOrder fe;
2760 private FlowEntryInstall newEntry;
2766 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2768 this.newEntry = newEntry;
2774 public FlowEntryDistributionOrder getFe() {
2779 * @return the newEntry
2781 public FlowEntryInstall getNewEntry() {
2786 private class WorkStatusCleanup extends FRMEvent {
2787 private FlowEntryDistributionOrder fe;
2792 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2799 public FlowEntryDistributionOrder getFe() {
2808 public String getHelp() {
2809 StringBuffer help = new StringBuffer();
2810 help.append("---FRM Matrix Application---\n");
2811 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2812 help.append("\t addMatrixConfig <name> <regex>\n");
2813 help.append("\t delMatrixConfig <name>\n");
2814 help.append("\t useMatrixConfig <name>\n");
2815 return help.toString();
2818 public void _printMatrixData(CommandInterpreter ci) {
2819 ci.println("Configs : ");
2820 ci.println("---------");
2821 ci.println(portGroupConfigs);
2823 ci.println("Data : ");
2824 ci.println("------");
2825 ci.println(portGroupData);
2828 public void _addMatrixConfig(CommandInterpreter ci) {
2829 String name = ci.nextArgument();
2830 String regex = ci.nextArgument();
2831 addPortGroupConfig(name, regex, false);
2834 public void _delMatrixConfig(CommandInterpreter ci) {
2835 String name = ci.nextArgument();
2836 delPortGroupConfig(name);
2839 public void _useMatrixConfig(CommandInterpreter ci) {
2840 String name = ci.nextArgument();
2841 usePortGroupConfig(name);
2844 public void _arpPunt(CommandInterpreter ci) {
2845 String switchId = ci.nextArgument();
2846 long swid = HexEncode.stringToLong(switchId);
2847 Node node = NodeCreator.createOFNode(swid);
2848 installImplicitARPReplyPunt(node);
2851 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2853 String nodeId = ci.nextArgument();
2854 if (nodeId == null) {
2855 ci.print("Node id not specified");
2859 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2860 } catch (NumberFormatException e) {
2861 ci.print("Node id not a number");
2864 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2867 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2869 String nodeId = ci.nextArgument();
2870 if (nodeId == null) {
2871 ci.print("Node id not specified");
2875 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2876 } catch (NumberFormatException e) {
2877 ci.print("Node id not a number");
2880 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2883 private Flow getSampleFlow(Node node) throws UnknownHostException {
2884 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2885 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2886 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2887 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2888 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2889 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2890 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2891 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2892 short ethertype = EtherTypes.IPv4.shortValue();
2893 short vlan = (short) 27;
2896 byte proto = IPProtocols.TCP.byteValue();
2897 short src = (short) 55000;
2901 * Create a SAL Flow aFlow
2903 Match match = new Match();
2904 match.setField(MatchType.IN_PORT, port);
2905 match.setField(MatchType.DL_SRC, srcMac);
2906 match.setField(MatchType.DL_DST, dstMac);
2907 match.setField(MatchType.DL_TYPE, ethertype);
2908 match.setField(MatchType.DL_VLAN, vlan);
2909 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2910 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2911 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2912 match.setField(MatchType.NW_TOS, tos);
2913 match.setField(MatchType.NW_PROTO, proto);
2914 match.setField(MatchType.TP_SRC, src);
2915 match.setField(MatchType.TP_DST, dst);
2917 List<Action> actions = new ArrayList<Action>();
2918 actions.add(new Output(oport));
2919 actions.add(new PopVlan());
2920 actions.add(new Flood());
2921 actions.add(new Controller());
2922 return new Flow(match, actions);
2926 public Status saveConfiguration() {
2927 return saveConfig();
2930 public void _frmNodeFlows(CommandInterpreter ci) {
2931 String nodeId = ci.nextArgument();
2932 Node node = Node.fromString(nodeId);
2934 ci.println("frmNodeFlows <node> [verbose]");
2937 boolean verbose = false;
2938 String verboseCheck = ci.nextArgument();
2939 if (verboseCheck != null) {
2940 verbose = verboseCheck.equals("true");
2943 if (!nodeFlows.containsKey(node)) {
2946 // Dump per node database
2947 for (FlowEntryInstall entry : nodeFlows.get(node)) {
2949 ci.println(node + " " + installedSwView.get(entry).getFlowName());
2951 ci.println(node + " " + installedSwView.get(entry).toString());
2956 public void _frmGroupFlows(CommandInterpreter ci) {
2957 String group = ci.nextArgument();
2958 if (group == null) {
2959 ci.println("frmGroupFlows <group> [verbose]");
2962 boolean verbose = false;
2963 String verboseCheck = ci.nextArgument();
2964 if (verboseCheck != null) {
2965 verbose = verboseCheck.equalsIgnoreCase("true");
2968 if (!groupFlows.containsKey(group)) {
2971 // Dump per node database
2972 ci.println("Group " + group + ":\n");
2973 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
2975 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
2977 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
2983 public void flowRemoved(Node node, Flow flow) {
2984 log.trace("Received flow removed notification on {} for {}", node, flow);
2986 // For flow entry identification, only node, match and priority matter
2987 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2988 FlowEntryInstall installedEntry = this.installedSwView.get(test);
2989 if (installedEntry == null) {
2990 log.trace("Entry is not known to us");
2994 // Update Static flow status
2996 FlowConfig target = null;
2997 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2998 FlowConfig conf = entry.getValue();
2999 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3000 key = entry.getKey();
3005 if (target != null) {
3006 // Update Configuration database
3007 target.toggleInstallation();
3008 target.setStatus(SUCCESS);
3009 staticFlows.put(key, target);
3012 // Update software views
3013 this.updateLocalDatabase(installedEntry, false);
3017 public void flowErrorReported(Node node, long rid, Object err) {
3018 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3019 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3022 private void processErrorEvent(ErrorReportedEvent event) {
3023 Node node = event.getNode();
3024 long rid = event.getRequestId();
3025 Object error = event.getError();
3026 String errorString = (error == null) ? "Not provided" : error.toString();
3028 * If this was for a flow install, remove the corresponding entry from
3029 * the software view. If it was a Looking for the rid going through the
3030 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3031 * mapping will have to be added in future
3033 FlowEntryInstall target = null;
3034 for (FlowEntryInstall index : nodeFlows.get(node)) {
3035 FlowEntryInstall entry = installedSwView.get(index);
3036 if (entry.getRequestId() == rid) {
3041 if (target != null) {
3042 // This was a flow install, update database
3043 this.updateLocalDatabase(target, false);
3047 if (frmAware != null) {
3048 synchronized (frmAware) {
3049 for (IForwardingRulesManagerAware frma : frmAware) {
3051 frma.requestFailed(rid, errorString);
3052 } catch (Exception e) {
3053 log.warn("Failed to notify {}", frma);
3061 public Status solicitStatusResponse(Node node, boolean blocking) {
3062 Status rv = new Status(StatusCode.INTERNALERROR);
3064 if (this.programmer != null) {
3066 rv = programmer.syncSendBarrierMessage(node);
3068 rv = programmer.asyncSendBarrierMessage(node);
3075 public void unsetIConnectionManager(IConnectionManager s) {
3076 if (s == this.connectionManager) {
3077 this.connectionManager = null;
3081 public void setIConnectionManager(IConnectionManager s) {
3082 this.connectionManager = s;
3086 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3093 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3096 * Local updates are of no interest
3100 if (cacheName.equals(WORKORDERCACHE)) {
3101 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3103 * This is the case of one workOrder becoming available, so we need
3104 * to dispatch the work to the appropriate handler
3106 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3107 FlowEntryInstall fei = fe.getEntry();
3111 Node n = fei.getNode();
3112 if (connectionManager.isLocal(n)) {
3113 logsync.trace("workOrder for fe {} processed locally", fe);
3114 // I'm the controller in charge for the request, queue it for
3116 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3118 } else if (cacheName.equals(WORKSTATUSCACHE)) {
3119 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3121 * This is the case of one workOrder being completed and a status
3124 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3126 * Check if the order was initiated by this controller in that case
3127 * we need to actually look at the status returned
3129 if (fe.getRequestorController()
3130 .equals(clusterContainerService.getMyAddress())) {
3131 FlowEntryDistributionOrderFutureTask fet = workMonitor.get(fe);
3133 logsync.trace("workStatus response is for us {}", fe);
3134 // Signal we got the status
3135 fet.gotStatus(fe, workStatus.get(fe));
3136 pendingEvents.offer(new WorkStatusCleanup(fe));
3143 public void entryDeleted(Object key, String cacheName, boolean originLocal) {