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.ConnectionLocality;
43 import org.opendaylight.controller.connectionmanager.IConnectionManager;
44 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
45 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
46 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
47 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
48 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
50 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
51 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
52 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
53 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
54 import org.opendaylight.controller.sal.action.Action;
55 import org.opendaylight.controller.sal.action.ActionType;
56 import org.opendaylight.controller.sal.action.Controller;
57 import org.opendaylight.controller.sal.action.Flood;
58 import org.opendaylight.controller.sal.action.Output;
59 import org.opendaylight.controller.sal.action.PopVlan;
60 import org.opendaylight.controller.sal.core.ContainerFlow;
61 import org.opendaylight.controller.sal.core.IContainer;
62 import org.opendaylight.controller.sal.core.IContainerListener;
63 import org.opendaylight.controller.sal.core.Node;
64 import org.opendaylight.controller.sal.core.NodeConnector;
65 import org.opendaylight.controller.sal.core.Property;
66 import org.opendaylight.controller.sal.core.UpdateType;
67 import org.opendaylight.controller.sal.flowprogrammer.Flow;
68 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
69 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
70 import org.opendaylight.controller.sal.match.Match;
71 import org.opendaylight.controller.sal.match.MatchType;
72 import org.opendaylight.controller.sal.utils.EtherTypes;
73 import org.opendaylight.controller.sal.utils.GlobalConstants;
74 import org.opendaylight.controller.sal.utils.HexEncode;
75 import org.opendaylight.controller.sal.utils.IObjectReader;
76 import org.opendaylight.controller.sal.utils.IPProtocols;
77 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
78 import org.opendaylight.controller.sal.utils.NodeCreator;
79 import org.opendaylight.controller.sal.utils.ObjectReader;
80 import org.opendaylight.controller.sal.utils.ObjectWriter;
81 import org.opendaylight.controller.sal.utils.Status;
82 import org.opendaylight.controller.sal.utils.StatusCode;
83 import org.opendaylight.controller.switchmanager.IInventoryListener;
84 import org.opendaylight.controller.switchmanager.ISwitchManager;
85 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
86 import org.opendaylight.controller.switchmanager.Subnet;
87 import org.osgi.framework.BundleContext;
88 import org.osgi.framework.FrameworkUtil;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * Class that manages forwarding rule installation and removal per container of
94 * the network. It also maintains the central repository of all the forwarding
95 * rules installed on the network nodes.
97 public class ForwardingRulesManager implements
98 IForwardingRulesManager,
99 PortGroupChangeListener,
102 IConfigurationContainerAware,
107 IFlowProgrammerListener {
108 private static final String NODEDOWN = "Node is Down";
109 private static final String SUCCESS = StatusCode.SUCCESS.toString();
110 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
111 private static final String PORTREMOVED = "Port removed";
112 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
113 private String frmFileName;
114 private String portGroupFileName;
115 private ConcurrentMap<Integer, FlowConfig> staticFlows;
116 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
117 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
118 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
119 private ConcurrentMap<String, Object> TSPolicies;
120 private boolean inContainerMode; // being used by global instance only
121 private boolean stopping;
124 * Flow database. It's the software view of what was requested to install
125 * and what is installed on the switch. It is indexed by the entry itself.
126 * The entry's hashcode resumes the network node index, the flow's priority
127 * and the flow's match. The value element is a class which contains the
128 * flow entry pushed by the applications modules and the respective
129 * container flow merged version. In absence of container flows, the two
130 * flow entries are the same.
132 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
133 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
135 * Per node and per group indexing
137 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
138 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
141 * Inactive flow list. This is for the global instance of FRM It will
142 * contain all the flow entries which were installed on the global container
143 * when the first container is created.
145 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
147 private IContainer container;
148 private Set<IForwardingRulesManagerAware> frmAware =
149 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
150 private PortGroupProvider portGroupProvider;
151 private IFlowProgrammerService programmer;
152 private IClusterContainerServices clusterContainerService = null;
153 private ISwitchManager switchManager;
154 private Thread frmEventHandler;
155 protected BlockingQueue<FRMEvent> pendingEvents;
157 // Distributes FRM programming in the cluster
158 private IConnectionManager connectionManager;
161 * Name clustered caches used to support FRM entry distribution these are by
162 * necessity non-transactional as long as need to be able to synchronize
163 * states also while a transaction is in progress
165 static final String WORKORDERCACHE = "frm.workOrder";
166 static final String WORKSTATUSCACHE = "frm.workStatus";
169 * Data structure responsible for distributing the FlowEntryInstall requests
170 * in the cluster. The key value is entry that is being either Installed or
171 * Updated or Delete. The value field is the same of the key value in case
172 * of Installation or Deletion, it's the new entry in case of Modification,
173 * this because the clustering caches don't allow null values.
175 * The logic behind this data structure is that the controller that initiate
176 * the request will place the order here, someone will pick it and then will
177 * remove from this data structure because is being served.
179 * TODO: We need to have a way to cleanup this data structure if entries are
180 * not picked by anyone, which is always a case can happen especially on
181 * Node disconnect cases.
183 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
186 * Data structure responsible for retrieving the results of the workOrder
187 * submitted to the cluster.
189 * The logic behind this data structure is that the controller that has
190 * executed the order will then place the result in workStatus signaling
191 * that there was a success or a failure.
193 * TODO: The workStatus entries need to have a lifetime associated in case
194 * of requestor controller leaving the cluster.
196 private ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
199 * Local Map used to hold the Future which a caller can use to monitor for
202 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
203 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
206 * Create an executor pool to create the distributionOrder, this is a stop
207 * gap solution caused by an issue with non-transactional caches in the
208 * implementation we use, being currently worked on. It has been noticed in
209 * fact that when non-transactional caches are being used sometime the key
210 * are no distributed to all the nodes properly. To workaround the issue
211 * transactional caches are being used, but there was a reason for using
212 * non-transactional caches to start with, in fact we needed to be able in
213 * the context of a northbound transaction to program the FRM entries
214 * irrespective of the fact that transaction would commit or no else we
215 * would not be able to achieve the entry programming and implement the
216 * scheme for recovery from network element failures. Bottom line, now in
217 * order to make sure an update on a transactional cache goes out while in a
218 * transaction that need to be initiated by a different thread.
220 private ExecutorService executor;
222 class DistributeOrderCallable implements Callable<Future<Status>> {
223 private FlowEntryInstall e;
224 private FlowEntryInstall u;
225 private UpdateType t;
226 DistributeOrderCallable(FlowEntryInstall e, FlowEntryInstall u, UpdateType t) {
233 public Future<Status> call() throws Exception {
234 if (e == null || t == null) {
235 logsync.error("Unexpected null Entry up update type");
238 // Create the work order and distribute it
239 FlowEntryDistributionOrder fe =
240 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
241 // First create the monitor job
242 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
243 logsync.trace("Node {} not local so sending fe {}", e.getNode(), fe);
244 workMonitor.put(fe, ret);
245 if (t.equals(UpdateType.CHANGED)) {
246 // Then distribute the work
247 workOrder.put(fe, u);
249 // Then distribute the work
250 workOrder.put(fe, e);
252 logsync.trace("WorkOrder requested");
253 // Now create an Handle to monitor the execution of the operation
260 * Entry being installed/updated/removed
262 * New entry will be placed after the update operation. Valid
263 * only for UpdateType.CHANGED, null for all the other cases
266 * @return a Future object for monitoring the progress of the result, or
267 * null in case the processing should take place locally
269 private Future<Status> distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u, UpdateType t) {
270 // A null entry it's an unexpected condition, anyway it's safe to keep
271 // the handling local
276 Node n = e.getNode();
277 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
278 Callable<Future<Status>> worker = new DistributeOrderCallable(e, u, t);
279 if (worker != null) {
280 Future<Future<Status>> workerRes = this.executor.submit(worker);
282 return workerRes.get();
283 } catch (InterruptedException e1) {
284 // we where interrupted, not a big deal.
286 } catch (ExecutionException e1) {
288 "We got an execution exception {} we cannot much, so returning we don't have nothing to wait for",
295 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
300 * Adds a flow entry onto the network node It runs various validity checks
301 * and derive the final container flows merged entries that will be
302 * attempted to be installed
305 * the original flow entry application requested to add
307 * the flag indicating if this is a asynchronous request
308 * @return the status of this request. In case of asynchronous call, it will
309 * contain the unique id assigned to this request
311 private Status addEntry(FlowEntry flowEntry, boolean async) {
314 if (flowEntry == null || flowEntry.getNode() == null) {
315 String msg = "Invalid FlowEntry";
316 String logMsg = msg + ": {}";
317 log.warn(logMsg, flowEntry);
318 return new Status(StatusCode.NOTACCEPTABLE, msg);
322 * Derive the container flow merged entries to install In presence of N
323 * container flows, we may end up with N different entries to install...
325 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
327 // Container Flow conflict Check
328 if (toInstallList.isEmpty()) {
329 String msg = "Flow Entry conflicts with all Container Flows";
330 String logMsg = msg + ": {}";
331 log.warn(logMsg, flowEntry);
332 return new Status(StatusCode.CONFLICT, msg);
335 // Derive the list of entries good to be installed
336 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
337 for (FlowEntryInstall entry : toInstallList) {
338 // Conflict Check: Verify new entry would not overwrite existing
340 if (this.installedSwView.containsKey(entry)) {
341 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
342 log.trace("Aborting to install {}", entry);
345 toInstallSafe.add(entry);
348 // Declare failure if all the container flow merged entries clash with
350 if (toInstallSafe.size() == 0) {
351 String msg = "A flow with same match and priority exists on the target node";
352 String logMsg = msg + ": {}";
353 log.warn(logMsg, flowEntry);
354 return new Status(StatusCode.CONFLICT, msg);
357 // Try to install an entry at the time
358 Status error = new Status(null, null);
359 Status succeded = null;
360 boolean oneSucceded = false;
361 for (FlowEntryInstall installEntry : toInstallSafe) {
363 // Install and update database
364 Status ret = addEntriesInternal(installEntry, async);
366 if (ret.isSuccess()) {
369 * The first successful status response will be returned For the
370 * asynchronous call, we can discard the container flow
371 * complication for now and assume we will always deal with one
372 * flow only per request
377 log.warn("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
381 return (oneSucceded) ? succeded : error;
385 * Given a flow entry and the list of container flows, it returns the list
386 * of container flow merged flow entries good to be installed on this
387 * container. If the list of container flows is null or empty, the install
388 * entry list will contain only one entry, the original flow entry. If the
389 * flow entry is congruent with all the N container flows, then the output
390 * install entry list will contain N entries. If the output list is empty,
391 * it means the passed flow entry conflicts with all the container flows.
394 * The list of container flows
395 * @return the list of container flow merged entries good to be installed on
398 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
399 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
401 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
402 // No container flows => entry good to be installed unchanged
403 toInstallList.add(new FlowEntryInstall(request.clone(), null));
405 // Create the list of entries to be installed. If the flow entry is
406 // not congruent with any container flow, no install entries will be
408 for (ContainerFlow cFlow : container.getContainerFlows()) {
409 if (cFlow.allowsFlow(request.getFlow())) {
410 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
414 return toInstallList;
418 * Modify a flow entry with a new one It runs various validity check and
419 * derive the final container flows merged flow entries to work with
421 * @param currentFlowEntry
422 * @param newFlowEntry
424 * the flag indicating if this is a asynchronous request
425 * @return the status of this request. In case of asynchronous call, it will
426 * contain the unique id assigned to this request
428 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
432 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
433 || newFlowEntry.getNode() == null) {
434 String msg = "Modify: Invalid FlowEntry";
435 String logMsg = msg + ": {} or {}";
436 log.warn(logMsg, currentFlowEntry, newFlowEntry);
437 return new Status(StatusCode.NOTACCEPTABLE, msg);
439 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
440 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
441 String msg = "Modify: Incompatible Flow Entries";
442 String logMsg = msg + ": {} and {}";
443 log.warn(logMsg, currentFlowEntry, newFlowEntry);
444 return new Status(StatusCode.NOTACCEPTABLE, msg);
448 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
449 String msg = "Modify skipped as flows are the same";
450 String logMsg = msg + ": {} and {}";
451 log.debug(logMsg, currentFlowEntry, newFlowEntry);
452 return new Status(StatusCode.SUCCESS, msg);
456 * Conflict Check: Verify the new entry would not conflict with an
457 * existing one. This is a loose check on the previous original flow
458 * entry requests. No check on the container flow merged flow entries
461 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
462 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
463 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
464 String logMsg = msg + ": {}";
465 log.warn(logMsg, currentFlowEntry);
466 return new Status(StatusCode.CONFLICT, msg);
469 // Derive the installed and toInstall entries
470 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
471 container.getContainerFlows());
472 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
474 if (toInstallList.isEmpty()) {
475 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
476 String logMsg = msg + ": {}";
477 log.warn(logMsg, newFlowEntry);
479 return new Status(StatusCode.CONFLICT, msg);
483 * If the two list sizes differ, it means the new flow entry does not
484 * satisfy the same number of container flows the current entry does.
485 * This is only possible when the new entry and current entry have
486 * different match. In this scenario the modification would ultimately
487 * be handled as a remove and add operations in the protocol plugin.
489 * Also, if any of the new flow entries would clash with an existing
490 * one, we cannot proceed with the modify operation, because it would
491 * fail for some entries and leave stale entries on the network node.
492 * Modify path can be taken only if it can be performed completely, for
495 * So, for the above two cases, to simplify, let's decouple the modify
496 * in: 1) remove current entries 2) install new entries
498 Status succeeded = null;
499 boolean decouple = false;
500 if (installedList.size() != toInstallList.size()) {
501 log.info("Modify: New flow entry does not satisfy the same "
502 + "number of container flows as the original entry does");
505 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
506 for (FlowEntryInstall installEntry : toInstallList) {
508 * Conflict Check: Verify the new entry would not overwrite another
511 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
512 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
513 log.info("Modify: new container flow merged flow entry clashes with existing flow");
516 toInstallSafe.add(installEntry);
521 // Remove current entries
522 for (FlowEntryInstall currEntry : installedList) {
523 this.removeEntryInternal(currEntry, async);
525 // Install new entries
526 for (FlowEntryInstall newEntry : toInstallSafe) {
527 succeeded = this.addEntriesInternal(newEntry, async);
531 * The two list have the same size and the entries to install do not
532 * clash with any existing flow on the network node. We assume here
533 * (and might be wrong) that the same container flows that were
534 * satisfied by the current entries are the same that are satisfied
535 * by the new entries. Let's take the risk for now.
537 * Note: modification has to be complete. If any entry modification
538 * fails, we need to stop, restore the already modified entries, and
541 Status retModify = null;
543 int size = toInstallList.size();
545 // Modify and update database
546 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
547 if (retModify.isSuccess()) {
553 // Check if uncompleted modify
555 log.warn("Unable to perform a complete modify for all the container flows merged entries");
556 // Restore original entries
559 log.info("Attempting to restore initial entries");
560 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
561 if (retExt.isSuccess()) {
567 // Fatal error, recovery failed
569 String msg = "Flow recovery failed ! Unrecoverable Error";
571 return new Status(StatusCode.INTERNALERROR, msg);
574 succeeded = retModify;
577 * The first successful status response will be returned. For the
578 * asynchronous call, we can discard the container flow complication for
579 * now and assume we will always deal with one flow only per request
585 * This is the function that modifies the final container flows merged
586 * entries on the network node and update the database. It expects that all
587 * the validity checks are passed
589 * @param currentEntries
592 * the flag indicating if this is a asynchronous request
593 * @return the status of this request. In case of asynchronous call, it will
594 * contain the unique id assigned to this request
596 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
597 Future<Status> futureStatus = distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
598 if (futureStatus != null) {
599 Status retStatus = new Status(StatusCode.UNDEFINED);
601 retStatus = futureStatus.get();
602 } catch (InterruptedException e) {
604 } catch (ExecutionException e) {
609 // Modify the flow on the network node
610 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
611 .getFlow(), newEntries.getInstall()
612 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
613 .getFlow(), newEntries.getInstall()
616 if (!status.isSuccess()) {
617 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
618 status.getDescription());
622 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
625 newEntries.setRequestId(status.getRequestId());
626 updateLocalDatabase(currentEntries, false);
627 updateLocalDatabase(newEntries, true);
634 * Remove a flow entry. If the entry is not present in the software view
635 * (entry or node not present), it return successfully
638 * the flow entry to remove
640 * the flag indicating if this is a asynchronous request
641 * @return the status of this request. In case of asynchronous call, it will
642 * contain the unique id assigned to this request
644 private Status removeEntry(FlowEntry flowEntry, boolean async) {
645 Status error = new Status(null, null);
648 if (flowEntry == null || flowEntry.getNode() == null) {
649 String msg = "Invalid FlowEntry";
650 String logMsg = msg + ": {}";
651 log.warn(logMsg, flowEntry);
652 return new Status(StatusCode.NOTACCEPTABLE, msg);
655 // Derive the container flows merged installed entries
656 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
658 Status succeeded = null;
659 boolean atLeastOneRemoved = false;
660 for (FlowEntryInstall entry : installedList) {
661 if (!installedSwView.containsKey(entry)) {
662 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
663 log.debug(logMsg, flowEntry);
664 if (installedList.size() == 1) {
665 // If we had only one entry to remove, we are done
666 return new Status(StatusCode.SUCCESS);
672 // Remove and update DB
673 Status ret = removeEntryInternal(entry, async);
675 if (!ret.isSuccess()) {
677 log.warn("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
678 if (installedList.size() == 1) {
679 // If we had only one entry to remove, this is fatal failure
684 atLeastOneRemoved = true;
689 * No worries if full removal failed. Consistency checker will take care
690 * of removing the stale entries later, or adjusting the software
691 * database if not in sync with hardware
693 return (atLeastOneRemoved) ? succeeded : error;
697 * This is the function that removes the final container flows merged entry
698 * from the network node and update the database. It expects that all the
699 * validity checks are passed
702 * the flow entry to remove
704 * the flag indicating if this is a asynchronous request
705 * @return the status of this request. In case of asynchronous call, it will
706 * contain the unique id assigned to this request
708 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
709 Future<Status> futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
710 if (futureStatus != null) {
711 Status retStatus = new Status(StatusCode.UNDEFINED);
713 retStatus = futureStatus.get();
714 } catch (InterruptedException e) {
716 } catch (ExecutionException e) {
721 // Mark the entry to be deleted (for CC just in case we fail)
725 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
726 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
729 if (!status.isSuccess()) {
730 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
731 status.getDescription());
734 log.trace("Removed {}", entry.getInstall());
737 updateLocalDatabase(entry, false);
744 * This is the function that installs the final container flow merged entry
745 * on the network node and updates the database. It expects that all the
746 * validity and conflict checks are passed. That means it does not check
747 * whether this flow would conflict or overwrite an existing one.
750 * the flow entry to install
752 * the flag indicating if this is a asynchronous request
753 * @return the status of this request. In case of asynchronous call, it will
754 * contain the unique id assigned to this request
756 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
757 Future<Status> futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
758 if (futureStatus != null) {
759 Status retStatus = new Status(StatusCode.UNDEFINED);
761 retStatus = futureStatus.get();
762 } catch (InterruptedException e) {
764 } catch (ExecutionException e) {
769 // Install the flow on the network node
770 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
771 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
774 if (!status.isSuccess()) {
775 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
776 status.getDescription());
780 log.trace("Added {}", entry.getInstall());
783 entry.setRequestId(status.getRequestId());
784 updateLocalDatabase(entry, true);
791 * Returns true if the flow conflicts with all the container's flows. This
792 * means that if the function returns true, the passed flow entry is
793 * congruent with at least one container flow, hence it is good to be
794 * installed on this container.
797 * @return true if flow conflicts with all the container flows, false
800 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
801 List<ContainerFlow> cFlowList = container.getContainerFlows();
803 // Validity check and avoid unnecessary computation
804 // Also takes care of default container where no container flows are
806 if (cFlowList == null || cFlowList.isEmpty()) {
810 for (ContainerFlow cFlow : cFlowList) {
811 if (cFlow.allowsFlow(flowEntry.getFlow())) {
812 // Entry is allowed by at least one container flow: good to go
819 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
820 // Update the software view
821 updateSwViewes(entry, add);
823 // Update node indexed flow database
824 updateNodeFlowsDB(entry, add);
826 // Update group indexed flow database
827 updateGroupFlowsDB(entry, add);
831 * Update the node mapped flows database
833 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
835 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
836 installedSwView.put(flowEntries, flowEntries);
838 originalSwView.remove(flowEntries.getOriginal());
839 installedSwView.remove(flowEntries);
844 * Update the node mapped flows database
846 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
847 Node node = flowEntries.getNode();
849 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
850 if (nodeIndeces == null) {
854 nodeIndeces = new ArrayList<FlowEntryInstall>();
859 nodeIndeces.add(flowEntries);
861 nodeIndeces.remove(flowEntries);
864 // Update cache across cluster
865 if (nodeIndeces.isEmpty()) {
866 this.nodeFlows.remove(node);
868 this.nodeFlows.put(node, nodeIndeces);
873 * Update the group name mapped flows database
875 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
876 String groupName = flowEntries.getGroupName();
878 // Flow may not be part of a group
879 if (groupName == null) {
883 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
884 if (indices == null) {
888 indices = new ArrayList<FlowEntryInstall>();
893 indices.add(flowEntries);
895 indices.remove(flowEntries);
898 // Update cache across cluster
899 if (indices.isEmpty()) {
900 this.groupFlows.remove(groupName);
902 this.groupFlows.put(groupName, indices);
907 * Remove a flow entry that has been added previously First checks if the
908 * entry is effectively present in the local database
910 @SuppressWarnings("unused")
911 private Status removeEntry(Node node, String flowName) {
912 FlowEntryInstall target = null;
915 for (FlowEntryInstall entry : installedSwView.values()) {
916 if (entry.equalsByNodeAndName(node, flowName)) {
922 // If it is not there, stop any further processing
923 if (target == null) {
924 return new Status(StatusCode.SUCCESS, "Entry is not present");
928 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
931 if (status.isSuccess()) {
932 updateLocalDatabase(target, false);
935 log.warn("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
936 status.getDescription());
943 public Status installFlowEntry(FlowEntry flowEntry) {
945 if (isContainerModeAllowed(flowEntry)) {
946 status = addEntry(flowEntry, false);
948 String msg = "Controller in container mode: Install Refused";
949 String logMsg = msg + ": {}";
950 status = new Status(StatusCode.NOTACCEPTABLE, msg);
951 log.warn(logMsg, flowEntry);
957 public Status installFlowEntryAsync(FlowEntry flowEntry) {
959 if (isContainerModeAllowed(flowEntry)) {
960 status = addEntry(flowEntry, true);
962 String msg = "Controller in container mode: Install Refused";
963 status = new Status(StatusCode.NOTACCEPTABLE, msg);
970 public Status uninstallFlowEntry(FlowEntry flowEntry) {
972 if (isContainerModeAllowed(flowEntry)) {
973 status = removeEntry(flowEntry, false);
975 String msg = "Controller in container mode: Uninstall Refused";
976 String logMsg = msg + ": {}";
977 status = new Status(StatusCode.NOTACCEPTABLE, msg);
978 log.warn(logMsg, flowEntry);
984 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
986 if (isContainerModeAllowed(flowEntry)) {
987 status = removeEntry(flowEntry, true);
989 String msg = "Controller in container mode: Uninstall Refused";
990 status = new Status(StatusCode.NOTACCEPTABLE, msg);
997 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
998 Status status = null;
999 if (isContainerModeAllowed(currentFlowEntry)) {
1000 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1002 String msg = "Controller in container mode: Modify Refused";
1003 String logMsg = msg + ": {}";
1004 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1005 log.warn(logMsg, newFlowEntry);
1011 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1012 Status status = null;
1013 if (isContainerModeAllowed(currentFlowEntry)) {
1014 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
1016 String msg = "Controller in container mode: Modify Refused";
1017 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1024 * Returns whether the specified flow entry is allowed to be
1025 * installed/removed/modified based on the current container mode status.
1026 * This call always returns true in the container instance of forwarding
1027 * rules manager. It is meant for the global instance only (default
1028 * container) of forwarding rules manager. Idea is that for assuring
1029 * container isolation of traffic, flow installation in default container is
1030 * blocked when in container mode (containers are present). The only flows
1031 * that are allowed in container mode in the default container are the
1032 * proactive flows, the ones automatically installed on the network node
1033 * which forwarding mode has been configured to "proactive". These flows are
1034 * needed by controller to discover the nodes topology and to discover the
1035 * attached hosts for some SDN switches.
1038 * The flow entry to be installed/removed/modified
1039 * @return true if not in container mode or if flowEntry is internally
1042 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1043 return (!inContainerMode) ? true : flowEntry.isInternal();
1047 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1049 * Run a check on the original entries to decide whether to go with a
1050 * add or modify method. A loose check means only check against the
1051 * original flow entry requests and not against the installed flow
1052 * entries which are the result of the original entry merged with the
1053 * container flow(s) (if any). The modifyFlowEntry method in presence of
1054 * conflicts with the Container flows (if any) would revert back to a
1055 * delete + add pattern
1057 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1059 if (currentFlowEntry != null) {
1060 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1062 return installFlowEntry(newFlowEntry);
1067 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1069 * Run a check on the original entries to decide whether to go with a
1070 * add or modify method. A loose check means only check against the
1071 * original flow entry requests and not against the installed flow
1072 * entries which are the result of the original entry merged with the
1073 * container flow(s) (if any). The modifyFlowEntry method in presence of
1074 * conflicts with the Container flows (if any) would revert back to a
1075 * delete + add pattern
1077 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1079 if (currentFlowEntry != null) {
1080 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1082 return installFlowEntryAsync(newFlowEntry);
1087 public Status uninstallFlowEntryGroup(String groupName) {
1088 if (groupName == null || groupName.isEmpty()) {
1089 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1091 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1092 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1094 if (inContainerMode) {
1095 String msg = "Controller in container mode: Group Uninstall Refused";
1096 String logMsg = msg + ": {}";
1097 log.warn(logMsg, groupName);
1098 return new Status(StatusCode.NOTACCEPTABLE, msg);
1100 int toBeRemoved = 0;
1102 if (groupFlows.containsKey(groupName)) {
1103 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1104 toBeRemoved = list.size();
1105 for (FlowEntryInstall entry : list) {
1106 Status status = this.removeEntry(entry.getOriginal(), false);
1107 if (status.isSuccess()) {
1110 error = status.getDescription();
1114 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1115 "Not all the flows were removed: " + error);
1119 public Status uninstallFlowEntryGroupAsync(String groupName) {
1120 if (groupName == null || groupName.isEmpty()) {
1121 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1123 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1124 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1126 if (inContainerMode) {
1127 String msg = "Controller in container mode: Group Uninstall Refused";
1128 String logMsg = msg + ": {}";
1129 log.warn(logMsg, groupName);
1130 return new Status(StatusCode.NOTACCEPTABLE, msg);
1132 if (groupFlows.containsKey(groupName)) {
1133 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1134 for (FlowEntryInstall entry : list) {
1135 this.removeEntry(entry.getOriginal(), true);
1138 return new Status(StatusCode.SUCCESS);
1142 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1143 return entryConflictsWithContainerFlows(flowEntry);
1147 * Updates all installed flows because the container flow got updated This
1148 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1149 * Reinstall of all flows This is needed because a new container flows
1150 * merged flow may conflict with an existing old container flows merged flow
1151 * on the network node
1153 private void updateFlowsContainerFlow() {
1154 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1155 // First remove all installed entries
1156 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1157 FlowEntryInstall current = entry.getValue();
1158 // Store the original entry
1159 toReInstall.add(current.getOriginal());
1160 // Remove the old couples. No validity checks to be run, use the
1162 this.removeEntryInternal(current, false);
1164 // Then reinstall the original entries
1165 for (FlowEntry entry : toReInstall) {
1166 // Reinstall the original flow entries, via the regular path: new
1167 // cFlow merge + validations
1168 this.installFlowEntry(entry);
1172 private void nonClusterObjectCreate() {
1173 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1174 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1175 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
1176 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
1177 TSPolicies = new ConcurrentHashMap<String, Object>();
1178 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1179 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1180 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1181 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1182 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1185 private void registerWithOSGIConsole() {
1186 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1187 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1191 public void setTSPolicyData(String policyname, Object o, boolean add) {
1194 /* Check if this policy already exists */
1195 if (!(TSPolicies.containsKey(policyname))) {
1196 TSPolicies.put(policyname, o);
1199 TSPolicies.remove(policyname);
1201 if (frmAware != null) {
1202 synchronized (frmAware) {
1203 for (IForwardingRulesManagerAware frma : frmAware) {
1205 frma.policyUpdate(policyname, add);
1206 } catch (Exception e) {
1207 log.warn("Exception on callback", e);
1215 public Map<String, Object> getTSPolicyData() {
1220 public Object getTSPolicyData(String policyName) {
1221 if (TSPolicies.containsKey(policyName)) {
1222 return TSPolicies.get(policyName);
1229 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1230 List<FlowEntry> list = new ArrayList<FlowEntry>();
1231 if (policyName != null && !policyName.trim().isEmpty()) {
1232 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1233 if (policyName.equals(entry.getKey().getGroupName())) {
1234 list.add(entry.getKey().clone());
1242 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1243 List<FlowEntry> list = new ArrayList<FlowEntry>();
1244 if (policyName != null && !policyName.trim().isEmpty()) {
1245 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1246 if (policyName.equals(entry.getKey().getGroupName())) {
1247 list.add(entry.getKey().getInstall().clone());
1255 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1257 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1258 if (flow.getFlowName().equals(flowName)) {
1259 FlowEntry currentFlowEntry = flow.getOriginal();
1260 FlowEntry newFlowEntry = currentFlowEntry.clone();
1261 for (NodeConnector dstPort : portList) {
1262 newFlowEntry.getFlow().addAction(new Output(dstPort));
1264 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1265 if (error.isSuccess()) {
1266 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1268 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1269 currentFlowEntry.toString(), error.getDescription());
1274 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1278 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1279 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1280 FlowEntryInstall flow = this.installedSwView.get(index);
1281 if (flow.getFlowName().equals(flowName)) {
1282 FlowEntry currentFlowEntry = flow.getOriginal();
1283 FlowEntry newFlowEntry = currentFlowEntry.clone();
1284 for (NodeConnector dstPort : portList) {
1285 Action action = new Output(dstPort);
1286 newFlowEntry.getFlow().removeAction(action);
1288 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1289 if (status.isSuccess()) {
1290 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1292 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1293 currentFlowEntry.toString(), status.getDescription());
1298 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1302 * This function assumes the target flow has only one output port
1305 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1306 FlowEntry currentFlowEntry = null;
1307 FlowEntry newFlowEntry = null;
1310 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1311 FlowEntryInstall flow = this.installedSwView.get(index);
1312 if (flow.getFlowName().equals(flowName)) {
1313 currentFlowEntry = flow.getOriginal();
1317 if (currentFlowEntry == null) {
1318 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1322 // Create a flow copy with the new output port
1323 newFlowEntry = currentFlowEntry.clone();
1324 Action target = null;
1325 for (Action action : newFlowEntry.getFlow().getActions()) {
1326 if (action.getType() == ActionType.OUTPUT) {
1331 newFlowEntry.getFlow().removeAction(target);
1332 newFlowEntry.getFlow().addAction(new Output(outPort));
1334 // Modify on network node
1335 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1337 if (status.isSuccess()) {
1338 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1340 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1341 status.getDescription());
1347 public NodeConnector getOutputPort(Node node, String flowName) {
1348 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1349 FlowEntryInstall flow = this.installedSwView.get(index);
1350 if (flow.getFlowName().equals(flowName)) {
1351 for (Action action : flow.getOriginal().getFlow().getActions()) {
1352 if (action.getType() == ActionType.OUTPUT) {
1353 return ((Output) action).getPort();
1361 private void cacheStartup() {
1366 @SuppressWarnings("deprecation")
1367 private void allocateCaches() {
1368 if (this.clusterContainerService == null) {
1369 log.warn("Un-initialized clusterContainerService, can't create cache");
1373 log.debug("Allocating caches for Container {}", container.getName());
1376 clusterContainerService.createCache("frm.originalSwView",
1377 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1379 clusterContainerService.createCache("frm.installedSwView",
1380 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1382 clusterContainerService.createCache("frm.inactiveFlows",
1383 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1385 clusterContainerService.createCache("frm.nodeFlows",
1386 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1388 clusterContainerService.createCache("frm.groupFlows",
1389 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1391 clusterContainerService.createCache("frm.staticFlows",
1392 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1394 clusterContainerService.createCache("frm.flowsSaveEvent",
1395 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1397 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1398 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1400 clusterContainerService.createCache("frm.portGroupConfigs",
1401 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1403 clusterContainerService.createCache("frm.portGroupData",
1404 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1406 clusterContainerService.createCache("frm.TSPolicies",
1407 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1409 clusterContainerService.createCache(WORKSTATUSCACHE,
1410 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1412 clusterContainerService.createCache(WORKORDERCACHE,
1413 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1415 } catch (CacheConfigException cce) {
1416 log.error("CacheConfigException");
1417 } catch (CacheExistException cce) {
1418 log.error("CacheExistException");
1422 @SuppressWarnings({ "unchecked", "deprecation" })
1423 private void retrieveCaches() {
1424 ConcurrentMap<?, ?> map;
1426 if (this.clusterContainerService == null) {
1427 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1428 nonClusterObjectCreate();
1432 log.debug("Retrieving Caches for Container {}", container.getName());
1434 map = clusterContainerService.getCache("frm.originalSwView");
1436 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1438 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1441 map = clusterContainerService.getCache("frm.installedSwView");
1443 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1445 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1448 map = clusterContainerService.getCache("frm.inactiveFlows");
1450 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1452 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1455 map = clusterContainerService.getCache("frm.nodeFlows");
1457 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1459 log.error("Retrieval of cache failed for Container {}", container.getName());
1462 map = clusterContainerService.getCache("frm.groupFlows");
1464 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1466 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1469 map = clusterContainerService.getCache("frm.staticFlows");
1471 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1473 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1476 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1478 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1480 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1483 map = clusterContainerService.getCache("frm.portGroupConfigs");
1485 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1487 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1490 map = clusterContainerService.getCache("frm.portGroupData");
1492 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1494 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1497 map = clusterContainerService.getCache("frm.TSPolicies");
1499 TSPolicies = (ConcurrentMap<String, Object>) map;
1501 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1504 map = clusterContainerService.getCache(WORKORDERCACHE);
1506 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1508 log.error("Retrieval of " + WORKORDERCACHE + " cache failed for Container {}", container.getName());
1511 map = clusterContainerService.getCache(WORKSTATUSCACHE);
1513 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1515 log.error("Retrieval of " + WORKSTATUSCACHE + " cache failed for Container {}", container.getName());
1519 private boolean flowConfigExists(FlowConfig config) {
1520 // Flow name has to be unique on per node id basis
1521 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1522 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1530 public Status addStaticFlow(FlowConfig config) {
1531 // Configuration object validation
1532 Status status = config.validate(container);
1533 if (!status.isSuccess()) {
1534 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1535 String error = "Invalid Configuration (" + status.getDescription() + ")";
1536 config.setStatus(error);
1537 return new Status(StatusCode.BADREQUEST, error);
1539 return addStaticFlowInternal(config, false);
1543 * Private method to add a static flow configuration which does not run any
1544 * validation on the passed FlowConfig object. If restore is set to true,
1545 * configuration is stored in configuration database regardless the
1546 * installation on the network node was successful. This is useful at boot
1547 * when static flows are present in startup configuration and are read
1548 * before the switches connects.
1551 * The static flow configuration
1553 * if true, the configuration is stored regardless the
1554 * installation on the network node was successful
1555 * @return The status of this request
1557 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1558 boolean multipleFlowPush = false;
1561 config.setStatus(SUCCESS);
1564 if (flowConfigExists(config)) {
1565 error = "Entry with this name on specified switch already exists";
1566 log.warn("Entry with this name on specified switch already exists: {}", config);
1567 config.setStatus(error);
1568 return new Status(StatusCode.CONFLICT, error);
1571 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1572 for (String portGroupName : portGroupConfigs.keySet()) {
1573 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1574 multipleFlowPush = true;
1578 if (!multipleFlowPush) {
1579 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1580 error = "Invalid Configuration (Invalid PortGroup Name)";
1581 config.setStatus(error);
1582 return new Status(StatusCode.BADREQUEST, error);
1587 * If requested program the entry in hardware first before updating the
1590 if (!multipleFlowPush) {
1592 if (config.installInHw()) {
1593 FlowEntry entry = config.getFlowEntry();
1594 status = this.installFlowEntry(entry);
1595 if (!status.isSuccess()) {
1596 config.setStatus(status.getDescription());
1605 * When the control reaches this point, either of the following
1606 * conditions is true 1. This is a single entry configuration (non
1607 * PortGroup) and the hardware installation is successful 2. This is a
1608 * multiple entry configuration (PortGroup) and hardware installation is
1609 * NOT done directly on this event. 3. The User prefers to retain the
1610 * configuration in Controller and skip hardware installation.
1612 * Hence it is safe to update the StaticFlow DB at this point.
1614 * Note : For the case of PortGrouping, it is essential to have this DB
1615 * populated before the PortGroupListeners can query for the DB
1616 * triggered using portGroupChanged event...
1618 Integer ordinal = staticFlowsOrdinal.get(0);
1619 staticFlowsOrdinal.put(0, ++ordinal);
1620 staticFlows.put(ordinal, config);
1622 if (multipleFlowPush) {
1623 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1624 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1625 if (existingData != null) {
1626 portGroupChanged(pgconfig, existingData, true);
1629 return new Status(StatusCode.SUCCESS);
1632 private void addStaticFlowsToSwitch(Node node) {
1633 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1634 FlowConfig config = entry.getValue();
1635 if (config.isPortGroupEnabled()) {
1638 if (config.getNode().equals(node)) {
1639 if (config.installInHw() && !config.getStatus().equals(SUCCESS)) {
1640 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1641 config.setStatus(status.getDescription());
1645 // Update cluster cache
1646 refreshClusterStaticFlowsStatus(node);
1649 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1650 log.trace("Updating Static Flow configs on node down: {}", node);
1652 List<Integer> toRemove = new ArrayList<Integer>();
1653 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1655 FlowConfig config = entry.getValue();
1657 if (config.isPortGroupEnabled()) {
1661 if (config.installInHw() && config.getNode().equals(node)) {
1662 if (config.isInternalFlow()) {
1663 // Take note of this controller generated static flow
1664 toRemove.add(entry.getKey());
1666 config.setStatus(NODEDOWN);
1670 // Remove controller generated static flows for this node
1671 for (Integer index : toRemove) {
1672 staticFlows.remove(index);
1674 // Update cluster cache
1675 refreshClusterStaticFlowsStatus(node);
1679 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1680 log.trace("Updating Static Flow configs on container mode change: {}", update);
1682 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1683 FlowConfig config = entry.getValue();
1684 if (config.isPortGroupEnabled()) {
1687 if (config.installInHw() && !config.isInternalFlow()) {
1690 config.setStatus("Removed from node because in container mode");
1693 config.setStatus(SUCCESS);
1699 // Update cluster cache
1700 refreshClusterStaticFlowsStatus(null);
1704 public Status removeStaticFlow(FlowConfig config) {
1706 * No config.isInternal() check as NB does not take this path and GUI
1707 * cannot issue a delete on an internal generated flow. We need this
1708 * path to be accessible when switch mode is changed from proactive to
1709 * reactive, so that we can remove the internal generated LLDP and ARP
1713 // Look for the target configuration entry
1715 FlowConfig target = null;
1716 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1717 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1718 key = entry.getKey();
1719 target = entry.getValue();
1723 if (target == null) {
1724 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1727 // Program the network node
1728 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1730 // Update configuration database if programming was successful
1731 if (status.isSuccess()) {
1732 staticFlows.remove(key);
1739 public Status removeStaticFlow(String name, Node node) {
1740 // Look for the target configuration entry
1742 FlowConfig target = null;
1743 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1744 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1745 key = mapEntry.getKey();
1746 target = mapEntry.getValue();
1750 if (target == null) {
1751 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1754 // Validity check for api3 entry point
1755 if (target.isInternalFlow()) {
1756 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1757 String logMsg = msg + ": {}";
1758 log.warn(logMsg, name);
1759 return new Status(StatusCode.NOTACCEPTABLE, msg);
1762 if (target.isPortGroupEnabled()) {
1763 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1764 String logMsg = msg + ": {}";
1765 log.warn(logMsg, name);
1766 return new Status(StatusCode.NOTACCEPTABLE, msg);
1769 // Program the network node
1770 Status status = this.removeEntry(target.getFlowEntry(), false);
1772 // Update configuration database if programming was successful
1773 if (status.isSuccess()) {
1774 staticFlows.remove(key);
1781 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1782 // Validity check for api3 entry point
1783 if (newFlowConfig.isInternalFlow()) {
1784 String msg = "Invalid operation: Controller generated flow cannot be modified";
1785 String logMsg = msg + ": {}";
1786 log.warn(logMsg, newFlowConfig);
1787 return new Status(StatusCode.NOTACCEPTABLE, msg);
1791 Status status = newFlowConfig.validate(container);
1792 if (!status.isSuccess()) {
1793 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1794 newFlowConfig.setStatus(msg);
1795 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1796 return new Status(StatusCode.BADREQUEST, msg);
1799 FlowConfig oldFlowConfig = null;
1800 Integer index = null;
1801 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1802 FlowConfig entry = mapEntry.getValue();
1803 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1804 oldFlowConfig = entry;
1805 index = mapEntry.getKey();
1810 if (oldFlowConfig == null) {
1811 String msg = "Attempt to modify a non existing static flow";
1812 String logMsg = msg + ": {}";
1813 log.warn(logMsg, newFlowConfig);
1814 return new Status(StatusCode.NOTFOUND, msg);
1817 // Do not attempt to reinstall the flow, warn user
1818 if (newFlowConfig.equals(oldFlowConfig)) {
1819 String msg = "No modification detected";
1820 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1821 return new Status(StatusCode.SUCCESS, msg);
1824 // If flow is installed, program the network node
1825 status = new Status(StatusCode.SUCCESS, "Saved in config");
1826 if (oldFlowConfig.installInHw()) {
1827 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1830 // Update configuration database if programming was successful
1831 if (status.isSuccess()) {
1832 newFlowConfig.setStatus(status.getDescription());
1833 staticFlows.put(index, newFlowConfig);
1840 public Status toggleStaticFlowStatus(String name, Node node) {
1841 return toggleStaticFlowStatus(getStaticFlow(name, node));
1845 public Status toggleStaticFlowStatus(FlowConfig config) {
1846 if (config == null) {
1847 String msg = "Invalid request: null flow config";
1849 return new Status(StatusCode.BADREQUEST, msg);
1851 // Validity check for api3 entry point
1852 if (config.isInternalFlow()) {
1853 String msg = "Invalid operation: Controller generated flow cannot be modified";
1854 String logMsg = msg + ": {}";
1855 log.warn(logMsg, config);
1856 return new Status(StatusCode.NOTACCEPTABLE, msg);
1859 // Find the config entry
1861 FlowConfig target = null;
1862 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1863 FlowConfig conf = entry.getValue();
1864 if (conf.isByNameAndNodeIdEqual(config)) {
1865 key = entry.getKey();
1870 if (target != null) {
1871 Status status = target.validate(container);
1872 if (!status.isSuccess()) {
1873 log.warn(status.getDescription());
1876 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1877 .installFlowEntry(target.getFlowEntry());
1878 if (status.isSuccess()) {
1879 // Update Configuration database
1880 target.setStatus(SUCCESS);
1881 target.toggleInstallation();
1882 staticFlows.put(key, target);
1887 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1891 * Reinsert all static flows entries in the cache to force cache updates in
1892 * the cluster. This is useful when only some parameters were changed in the
1893 * entries, like the status.
1896 * The node for which the static flow configurations have to be
1897 * refreshed. If null, all nodes static flows will be refreshed.
1899 private void refreshClusterStaticFlowsStatus(Node node) {
1900 // Refresh cluster cache
1901 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1902 if (node == null || entry.getValue().getNode().equals(node)) {
1903 staticFlows.put(entry.getKey(), entry.getValue());
1909 * Uninstall all the non-internal Flow Entries present in the software view.
1910 * If requested, a copy of each original flow entry will be stored in the
1911 * inactive list so that it can be re-applied when needed (This is typically
1912 * the case when running in the default container and controller moved to
1915 * @param preserveFlowEntries
1916 * if true, a copy of each original entry is stored in the
1919 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1920 log.info("Uninstalling all non-internal flows");
1922 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1924 // Store entries / create target list
1925 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1926 FlowEntryInstall flowEntries = mapEntry.getValue();
1927 // Skip internal generated static flows
1928 if (!flowEntries.isInternal()) {
1929 toRemove.add(flowEntries);
1930 // Store the original entries if requested
1931 if (preserveFlowEntries) {
1932 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1937 // Now remove the entries
1938 for (FlowEntryInstall flowEntryHw : toRemove) {
1939 Status status = this.removeEntryInternal(flowEntryHw, false);
1940 if (!status.isSuccess()) {
1941 log.warn("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1947 * Re-install all the Flow Entries present in the inactive list The inactive
1948 * list will be empty at the end of this call This function is called on the
1949 * default container instance of FRM only when the last container is deleted
1951 private void reinstallAllFlowEntries() {
1952 log.info("Reinstalling all inactive flows");
1954 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1955 this.addEntry(flowEntry, false);
1958 // Empty inactive list in any case
1959 inactiveFlows.clear();
1963 public List<FlowConfig> getStaticFlows() {
1964 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1967 // TODO: need to come out with a better algorithm for maintaining the order
1968 // of the configuration entries
1969 // with actual one, index associated to deleted entries cannot be reused and
1971 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1972 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1973 for (int i = 0; i <= maxKey; i++) {
1974 FlowConfig entry = flowMap.get(i);
1975 if (entry != null) {
1976 orderedList.add(entry);
1983 public FlowConfig getStaticFlow(String name, Node node) {
1984 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1985 if (entry.getValue().isByNameAndNodeIdEqual(name, node)) {
1986 return entry.getValue();
1993 public List<FlowConfig> getStaticFlows(Node node) {
1994 List<FlowConfig> list = new ArrayList<FlowConfig>();
1995 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1996 if (entry.getValue().onNode(node)) {
1997 list.add(entry.getValue());
2004 public List<String> getStaticFlowNamesForNode(Node node) {
2005 List<String> list = new ArrayList<String>();
2006 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2007 if (entry.getValue().onNode(node)) {
2008 list.add(entry.getValue().getName());
2015 public List<Node> getListNodeWithConfiguredFlows() {
2016 Set<Node> set = new HashSet<Node>();
2017 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2018 set.add(entry.getValue().getNode());
2020 return new ArrayList<Node>(set);
2023 @SuppressWarnings("unchecked")
2024 private void loadFlowConfiguration() {
2025 ObjectReader objReader = new ObjectReader();
2026 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2029 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2032 if (pgConfig != null) {
2033 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2034 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2038 if (confList == null) {
2043 for (Integer key : confList.keySet()) {
2044 if (key.intValue() > maxKey) {
2045 maxKey = key.intValue();
2049 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2050 addStaticFlowInternal(conf, true);
2055 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2056 return ois.readObject();
2060 public Status saveConfig() {
2061 return saveConfigInternal();
2064 private Status saveConfigInternal() {
2065 ObjectWriter objWriter = new ObjectWriter();
2066 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2067 for (Integer ordinal : staticFlows.keySet()) {
2068 FlowConfig config = staticFlows.get(ordinal);
2069 // Do not save dynamic and controller generated static flows
2070 if (config.isDynamic() || config.isInternalFlow()) {
2073 nonDynamicFlows.put(ordinal, config);
2075 objWriter.write(nonDynamicFlows, frmFileName);
2076 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2077 return new Status(StatusCode.SUCCESS, null);
2081 public void subnetNotify(Subnet sub, boolean add) {
2084 private void installImplicitARPReplyPunt(Node node) {
2090 List<String> puntAction = new ArrayList<String>();
2091 puntAction.add(ActionType.CONTROLLER.toString());
2093 FlowConfig allowARP = new FlowConfig();
2094 allowARP.setInstallInHw(true);
2095 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
2096 allowARP.setPriority("500");
2097 allowARP.setNode(node);
2098 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2099 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
2100 allowARP.setActions(puntAction);
2101 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
2107 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2110 * This method can be called from within the OSGi framework context,
2111 * given the programming operation can take sometime, it not good
2112 * pratice to have in it's context operations that can take time,
2113 * hence moving off to a different thread for async processing.
2116 public void modeChangeNotify(final Node node, final boolean proactive) {
2117 Callable<Status> modeChangeCallable = new Callable<Status>() {
2119 public Status call() throws Exception {
2120 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2122 List<String> puntAction = new ArrayList<String>();
2123 puntAction.add(ActionType.CONTROLLER.toString());
2125 FlowConfig allowARP = new FlowConfig();
2126 allowARP.setInstallInHw(true);
2127 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2128 allowARP.setPriority("1");
2129 allowARP.setNode(node);
2130 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2132 allowARP.setActions(puntAction);
2133 defaultConfigs.add(allowARP);
2135 FlowConfig allowLLDP = new FlowConfig();
2136 allowLLDP.setInstallInHw(true);
2137 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2138 allowLLDP.setPriority("1");
2139 allowLLDP.setNode(node);
2140 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2142 allowLLDP.setActions(puntAction);
2143 defaultConfigs.add(allowLLDP);
2145 List<String> dropAction = new ArrayList<String>();
2146 dropAction.add(ActionType.DROP.toString());
2148 FlowConfig dropAllConfig = new FlowConfig();
2149 dropAllConfig.setInstallInHw(true);
2150 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2151 + FlowConfig.INTERNALSTATICFLOWEND);
2152 dropAllConfig.setPriority("0");
2153 dropAllConfig.setNode(node);
2154 dropAllConfig.setActions(dropAction);
2155 defaultConfigs.add(dropAllConfig);
2157 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2158 for (FlowConfig fc : defaultConfigs) {
2159 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2160 if (status.isSuccess()) {
2161 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2163 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2167 return new Status(StatusCode.SUCCESS);
2172 * Execute the work outside the caller context, this could be an
2173 * expensive operation and we don't want to block the caller for it.
2175 this.executor.submit(modeChangeCallable);
2179 * Remove from the databases all the flows installed on the node
2183 private void cleanDatabaseForNode(Node node) {
2184 log.info("Cleaning Flow database for Node {}", node);
2185 if (nodeFlows.containsKey(node)) {
2186 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2188 for (FlowEntryInstall entry : toRemove) {
2189 updateLocalDatabase(entry, false);
2194 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2199 Match match = flow.getMatch();
2200 if (match.isPresent(MatchType.IN_PORT)) {
2201 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2202 if (matchPort.equals(nc)) {
2206 List<Action> actionsList = flow.getActions();
2207 if (actionsList != null) {
2208 for (Action action : actionsList) {
2209 if (action instanceof Output) {
2210 NodeConnector actionPort = ((Output) action).getPort();
2211 if (actionPort.equals(nc)) {
2221 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2222 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2226 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2230 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2231 FlowConfig derivedFlow = new FlowConfig(original);
2232 derivedFlow.setDynamic(true);
2233 derivedFlow.setPortGroup(null);
2234 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2235 derivedFlow.setIngressPort(port + "");
2239 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2240 for (FlowConfig staticFlow : staticFlows.values()) {
2241 if (staticFlow.getPortGroup() == null) {
2244 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2245 for (Short port : data.getPorts()) {
2246 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2247 addStaticFlowInternal(derivedFlow, false);
2253 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2254 for (FlowConfig staticFlow : staticFlows.values()) {
2255 if (staticFlow.getPortGroup() == null) {
2258 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2259 for (Short port : data.getPorts()) {
2260 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2261 removeStaticFlow(derivedFlow);
2268 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2269 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2270 Map<Node, PortGroup> existingData = portGroupData.get(config);
2271 if (existingData != null) {
2272 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2273 PortGroup existingPortGroup = existingData.get(entry.getKey());
2274 if (existingPortGroup == null) {
2276 existingData.put(entry.getKey(), entry.getValue());
2277 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2281 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2282 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2284 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2285 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2291 portGroupData.put(config, data);
2292 for (Node swid : data.keySet()) {
2293 addPortGroupFlows(config, swid, data.get(swid));
2300 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2301 PortGroupConfig config = portGroupConfigs.get(name);
2302 if (config != null) {
2306 if ((portGroupProvider == null) && !restore) {
2309 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2313 config = new PortGroupConfig(name, regex);
2314 portGroupConfigs.put(name, config);
2315 if (portGroupProvider != null) {
2316 portGroupProvider.createPortGroupConfig(config);
2322 public boolean delPortGroupConfig(String name) {
2323 PortGroupConfig config = portGroupConfigs.get(name);
2324 if (config == null) {
2328 if (portGroupProvider != null) {
2329 portGroupProvider.deletePortGroupConfig(config);
2331 portGroupConfigs.remove(name);
2335 private void usePortGroupConfig(String name) {
2336 PortGroupConfig config = portGroupConfigs.get(name);
2337 if (config == null) {
2340 if (portGroupProvider != null) {
2341 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2342 portGroupData.put(config, data);
2347 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2348 return portGroupConfigs;
2351 public boolean isPortGroupSupported() {
2352 if (portGroupProvider == null) {
2358 public void setIContainer(IContainer s) {
2362 public void unsetIContainer(IContainer s) {
2363 if (this.container == s) {
2364 this.container = null;
2369 public PortGroupProvider getPortGroupProvider() {
2370 return portGroupProvider;
2373 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2374 this.portGroupProvider = null;
2377 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2378 this.portGroupProvider = portGroupProvider;
2379 portGroupProvider.registerPortGroupChange(this);
2380 for (PortGroupConfig config : portGroupConfigs.values()) {
2381 portGroupProvider.createPortGroupConfig(config);
2385 public void setFrmAware(IForwardingRulesManagerAware obj) {
2386 this.frmAware.add(obj);
2389 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2390 this.frmAware.remove(obj);
2393 void setClusterContainerService(IClusterContainerServices s) {
2394 log.debug("Cluster Service set");
2395 this.clusterContainerService = s;
2398 void unsetClusterContainerService(IClusterContainerServices s) {
2399 if (this.clusterContainerService == s) {
2400 log.debug("Cluster Service removed!");
2401 this.clusterContainerService = null;
2405 private String getContainerName() {
2406 if (container == null) {
2407 return GlobalConstants.DEFAULT.toString();
2409 return container.getName();
2413 * Function called by the dependency manager when all the required
2414 * dependencies are satisfied
2418 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2419 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2421 inContainerMode = false;
2423 if (portGroupProvider != null) {
2424 portGroupProvider.registerPortGroupChange(this);
2429 registerWithOSGIConsole();
2432 * If we are not the first cluster node to come up, do not initialize
2433 * the static flow entries ordinal
2435 if (staticFlowsOrdinal.size() == 0) {
2436 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2439 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2441 // Initialize the event handler thread
2442 frmEventHandler = new Thread(new Runnable() {
2447 FRMEvent event = pendingEvents.take();
2448 if (event == null) {
2449 log.warn("Dequeued null event");
2452 if (event instanceof NodeUpdateEvent) {
2453 NodeUpdateEvent update = (NodeUpdateEvent) event;
2454 Node node = update.getNode();
2455 switch (update.getUpdateType()) {
2457 addStaticFlowsToSwitch(node);
2460 cleanDatabaseForNode(node);
2461 updateStaticFlowConfigsOnNodeDown(node);
2465 } else if (event instanceof ErrorReportedEvent) {
2466 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2467 processErrorEvent(errEvent);
2468 } else if (event instanceof WorkOrderEvent) {
2470 * Take care of handling the remote Work request
2472 WorkOrderEvent work = (WorkOrderEvent) event;
2473 FlowEntryDistributionOrder fe = work.getFe();
2475 logsync.trace("Executing the workOrder {}", fe);
2476 Status gotStatus = null;
2477 FlowEntryInstall feiCurrent = fe.getEntry();
2478 FlowEntryInstall feiNew = workOrder.get(fe.getEntry());
2479 switch (fe.getUpType()) {
2482 * TODO: Not still sure how to handle the
2485 gotStatus = addEntriesInternal(feiCurrent, true);
2488 gotStatus = modifyEntryInternal(feiCurrent, feiNew, true);
2491 gotStatus = removeEntryInternal(feiCurrent, true);
2495 workOrder.remove(fe);
2497 "The workOrder has been executed and now the status is being returned {}", fe);
2499 workStatus.put(fe, gotStatus);
2501 log.warn("Not expected null WorkOrder", work);
2503 } else if (event instanceof WorkStatusCleanup) {
2505 * Take care of handling the remote Work request
2507 WorkStatusCleanup work = (WorkStatusCleanup) event;
2508 FlowEntryDistributionOrder fe = work.getFe();
2510 logsync.trace("The workStatus {} is being removed", fe);
2511 workStatus.remove(fe);
2513 log.warn("Not expected null WorkStatus", work);
2516 log.warn("Dequeued unknown event {}", event.getClass()
2519 } catch (InterruptedException e) {
2520 // clear pending events
2521 pendingEvents.clear();
2525 }, "FRM EventHandler Collector");
2529 * Function called by the dependency manager when at least one dependency
2530 * become unsatisfied or when the component is shutting down because for
2531 * example bundle is being stopped.
2535 // Interrupt the thread
2536 frmEventHandler.interrupt();
2537 // Clear the pendingEvents queue
2538 pendingEvents.clear();
2540 workMonitor.clear();
2544 * Function called by dependency manager after "init ()" is called and after
2545 * the services provided by the class are registered in the service registry
2549 // Initialize graceful stop flag
2552 // Allocate the executor service
2553 this.executor = Executors.newSingleThreadExecutor();
2555 // Start event handler thread
2556 frmEventHandler.start();
2559 * Read startup and build database if we have not already gotten the
2560 * configurations synced from another node
2562 if (staticFlows.isEmpty()) {
2563 loadFlowConfiguration();
2568 * Function called by the dependency manager before the services exported by
2569 * the component are unregistered, this will be followed by a "destroy ()"
2574 uninstallAllFlowEntries(false);
2575 // Shutdown executor
2576 this.executor.shutdownNow();
2579 public void setFlowProgrammerService(IFlowProgrammerService service) {
2580 this.programmer = service;
2583 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2584 if (this.programmer == service) {
2585 this.programmer = null;
2589 public void setSwitchManager(ISwitchManager switchManager) {
2590 this.switchManager = switchManager;
2593 public void unsetSwitchManager(ISwitchManager switchManager) {
2594 if (this.switchManager == switchManager) {
2595 this.switchManager = null;
2600 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2601 if (!container.getName().equals(containerName)) {
2607 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2608 if (!container.getName().equals(containerName)) {
2611 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2612 container.getName(), t, current);
2614 * Whether it is an addition or removal, we have to recompute the merged
2615 * flows entries taking into account all the current container flows
2616 * because flow merging is not an injective function
2618 updateFlowsContainerFlow();
2622 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2623 if (!container.getName().equals(containerName)) {
2627 boolean updateStaticFlowCluster = false;
2632 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nc.getNode());
2633 if (nodeFlowEntries == null) {
2636 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2637 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nc)) {
2638 Status status = this.removeEntryInternal(fei, true);
2639 if (!status.isSuccess()) {
2643 * If the flow entry is a static flow, then update its
2646 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2647 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2648 if (flowConfig != null) {
2649 flowConfig.setStatus(PORTREMOVED);
2650 updateStaticFlowCluster = true;
2655 if (updateStaticFlowCluster) {
2656 refreshClusterStaticFlowsStatus(nc.getNode());
2660 List<FlowConfig> flowConfigForNode = getStaticFlows(nc.getNode());
2661 for (FlowConfig flowConfig : flowConfigForNode) {
2662 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nc)) {
2663 if (flowConfig.installInHw()) {
2664 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2665 if (!status.isSuccess()) {
2666 flowConfig.setStatus(status.getDescription());
2668 flowConfig.setStatus(SUCCESS);
2670 updateStaticFlowCluster = true;
2674 if (updateStaticFlowCluster) {
2675 refreshClusterStaticFlowsStatus(nc.getNode());
2685 public void containerModeUpdated(UpdateType update) {
2686 // Only default container instance reacts on this event
2687 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2693 * Controller is moving to container mode. We are in the default
2694 * container context, we need to remove all our non-internal flows
2695 * to prevent any container isolation breakage. We also need to
2696 * preserve our flow so that they can be re-installed if we move
2697 * back to non container mode (no containers).
2699 this.inContainerMode = true;
2700 this.uninstallAllFlowEntries(true);
2703 this.inContainerMode = false;
2704 this.reinstallAllFlowEntries();
2709 // Update our configuration DB
2710 updateStaticFlowConfigsOnContainerModeChange(update);
2713 protected abstract class FRMEvent {
2717 private class NodeUpdateEvent extends FRMEvent {
2718 private final Node node;
2719 private final UpdateType update;
2721 public NodeUpdateEvent(UpdateType update, Node node) {
2722 this.update = update;
2726 public UpdateType getUpdateType() {
2730 public Node getNode() {
2735 private class ErrorReportedEvent extends FRMEvent {
2736 private final long rid;
2737 private final Node node;
2738 private final Object error;
2740 public ErrorReportedEvent(long rid, Node node, Object error) {
2746 public long getRequestId() {
2750 public Object getError() {
2754 public Node getNode() {
2759 private class WorkOrderEvent extends FRMEvent {
2760 private FlowEntryDistributionOrder fe;
2761 private FlowEntryInstall newEntry;
2767 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2769 this.newEntry = newEntry;
2775 public FlowEntryDistributionOrder getFe() {
2780 * @return the newEntry
2782 public FlowEntryInstall getNewEntry() {
2787 private class WorkStatusCleanup extends FRMEvent {
2788 private FlowEntryDistributionOrder fe;
2793 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2800 public FlowEntryDistributionOrder getFe() {
2809 public String getHelp() {
2810 StringBuffer help = new StringBuffer();
2811 help.append("---FRM Matrix Application---\n");
2812 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2813 help.append("\t addMatrixConfig <name> <regex>\n");
2814 help.append("\t delMatrixConfig <name>\n");
2815 help.append("\t useMatrixConfig <name>\n");
2816 return help.toString();
2819 public void _printMatrixData(CommandInterpreter ci) {
2820 ci.println("Configs : ");
2821 ci.println("---------");
2822 ci.println(portGroupConfigs);
2824 ci.println("Data : ");
2825 ci.println("------");
2826 ci.println(portGroupData);
2829 public void _addMatrixConfig(CommandInterpreter ci) {
2830 String name = ci.nextArgument();
2831 String regex = ci.nextArgument();
2832 addPortGroupConfig(name, regex, false);
2835 public void _delMatrixConfig(CommandInterpreter ci) {
2836 String name = ci.nextArgument();
2837 delPortGroupConfig(name);
2840 public void _useMatrixConfig(CommandInterpreter ci) {
2841 String name = ci.nextArgument();
2842 usePortGroupConfig(name);
2845 public void _arpPunt(CommandInterpreter ci) {
2846 String switchId = ci.nextArgument();
2847 long swid = HexEncode.stringToLong(switchId);
2848 Node node = NodeCreator.createOFNode(swid);
2849 installImplicitARPReplyPunt(node);
2852 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2854 String nodeId = ci.nextArgument();
2855 if (nodeId == null) {
2856 ci.print("Node id not specified");
2860 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2861 } catch (NumberFormatException e) {
2862 ci.print("Node id not a number");
2865 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2868 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2870 String nodeId = ci.nextArgument();
2871 if (nodeId == null) {
2872 ci.print("Node id not specified");
2876 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2877 } catch (NumberFormatException e) {
2878 ci.print("Node id not a number");
2881 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2884 private Flow getSampleFlow(Node node) throws UnknownHostException {
2885 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2886 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2887 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2888 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2889 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2890 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2891 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2892 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2893 short ethertype = EtherTypes.IPv4.shortValue();
2894 short vlan = (short) 27;
2897 byte proto = IPProtocols.TCP.byteValue();
2898 short src = (short) 55000;
2902 * Create a SAL Flow aFlow
2904 Match match = new Match();
2905 match.setField(MatchType.IN_PORT, port);
2906 match.setField(MatchType.DL_SRC, srcMac);
2907 match.setField(MatchType.DL_DST, dstMac);
2908 match.setField(MatchType.DL_TYPE, ethertype);
2909 match.setField(MatchType.DL_VLAN, vlan);
2910 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2911 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2912 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2913 match.setField(MatchType.NW_TOS, tos);
2914 match.setField(MatchType.NW_PROTO, proto);
2915 match.setField(MatchType.TP_SRC, src);
2916 match.setField(MatchType.TP_DST, dst);
2918 List<Action> actions = new ArrayList<Action>();
2919 actions.add(new Output(oport));
2920 actions.add(new PopVlan());
2921 actions.add(new Flood());
2922 actions.add(new Controller());
2923 return new Flow(match, actions);
2927 public Status saveConfiguration() {
2928 return saveConfig();
2931 public void _frmNodeFlows(CommandInterpreter ci) {
2932 String nodeId = ci.nextArgument();
2933 Node node = Node.fromString(nodeId);
2935 ci.println("frmNodeFlows <node> [verbose]");
2938 boolean verbose = false;
2939 String verboseCheck = ci.nextArgument();
2940 if (verboseCheck != null) {
2941 verbose = verboseCheck.equals("true");
2944 if (!nodeFlows.containsKey(node)) {
2947 // Dump per node database
2948 for (FlowEntryInstall entry : nodeFlows.get(node)) {
2950 ci.println(node + " " + installedSwView.get(entry).getFlowName());
2952 ci.println(node + " " + installedSwView.get(entry).toString());
2957 public void _frmGroupFlows(CommandInterpreter ci) {
2958 String group = ci.nextArgument();
2959 if (group == null) {
2960 ci.println("frmGroupFlows <group> [verbose]");
2963 boolean verbose = false;
2964 String verboseCheck = ci.nextArgument();
2965 if (verboseCheck != null) {
2966 verbose = verboseCheck.equalsIgnoreCase("true");
2969 if (!groupFlows.containsKey(group)) {
2972 // Dump per node database
2973 ci.println("Group " + group + ":\n");
2974 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
2976 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
2978 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
2984 public void flowRemoved(Node node, Flow flow) {
2985 log.trace("Received flow removed notification on {} for {}", node, flow);
2987 // For flow entry identification, only node, match and priority matter
2988 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2989 FlowEntryInstall installedEntry = this.installedSwView.get(test);
2990 if (installedEntry == null) {
2991 log.trace("Entry is not known to us");
2995 // Update Static flow status
2997 FlowConfig target = null;
2998 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2999 FlowConfig conf = entry.getValue();
3000 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3001 key = entry.getKey();
3006 if (target != null) {
3007 // Update Configuration database
3008 target.toggleInstallation();
3009 target.setStatus(SUCCESS);
3010 staticFlows.put(key, target);
3013 // Update software views
3014 this.updateLocalDatabase(installedEntry, false);
3018 public void flowErrorReported(Node node, long rid, Object err) {
3019 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3020 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3023 private void processErrorEvent(ErrorReportedEvent event) {
3024 Node node = event.getNode();
3025 long rid = event.getRequestId();
3026 Object error = event.getError();
3027 String errorString = (error == null) ? "Not provided" : error.toString();
3029 * If this was for a flow install, remove the corresponding entry from
3030 * the software view. If it was a Looking for the rid going through the
3031 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3032 * mapping will have to be added in future
3034 FlowEntryInstall target = null;
3035 for (FlowEntryInstall index : nodeFlows.get(node)) {
3036 FlowEntryInstall entry = installedSwView.get(index);
3037 if (entry.getRequestId() == rid) {
3042 if (target != null) {
3043 // This was a flow install, update database
3044 this.updateLocalDatabase(target, false);
3048 if (frmAware != null) {
3049 synchronized (frmAware) {
3050 for (IForwardingRulesManagerAware frma : frmAware) {
3052 frma.requestFailed(rid, errorString);
3053 } catch (Exception e) {
3054 log.warn("Failed to notify {}", frma);
3062 public Status solicitStatusResponse(Node node, boolean blocking) {
3063 Status rv = new Status(StatusCode.INTERNALERROR);
3065 if (this.programmer != null) {
3067 rv = programmer.syncSendBarrierMessage(node);
3069 rv = programmer.asyncSendBarrierMessage(node);
3076 public void unsetIConnectionManager(IConnectionManager s) {
3077 if (s == this.connectionManager) {
3078 this.connectionManager = null;
3082 public void setIConnectionManager(IConnectionManager s) {
3083 this.connectionManager = s;
3087 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3094 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3097 * Local updates are of no interest
3101 if (cacheName.equals(WORKORDERCACHE)) {
3102 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3104 * This is the case of one workOrder becoming available, so we need
3105 * to dispatch the work to the appropriate handler
3107 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3108 FlowEntryInstall fei = fe.getEntry();
3112 Node n = fei.getNode();
3113 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3114 logsync.trace("workOrder for fe {} processed locally", fe);
3115 // I'm the controller in charge for the request, queue it for
3117 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3119 } else if (cacheName.equals(WORKSTATUSCACHE)) {
3120 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3122 * This is the case of one workOrder being completed and a status
3125 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3127 * Check if the order was initiated by this controller in that case
3128 * we need to actually look at the status returned
3130 if (fe.getRequestorController()
3131 .equals(clusterContainerService.getMyAddress())) {
3132 FlowEntryDistributionOrderFutureTask fet = workMonitor.get(fe);
3134 logsync.trace("workStatus response is for us {}", fe);
3135 // Signal we got the status
3136 fet.gotStatus(fe, workStatus.get(fe));
3137 pendingEvents.offer(new WorkStatusCleanup(fe));
3144 public void entryDeleted(Object key, String cacheName, boolean originLocal) {