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.util.ArrayList;
15 import java.util.Collections;
16 import java.util.EnumSet;
17 import java.util.HashSet;
18 import java.util.List;
20 import java.util.Map.Entry;
22 import java.util.concurrent.BlockingQueue;
23 import java.util.concurrent.Callable;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.LinkedBlockingQueue;
31 import org.opendaylight.controller.clustering.services.CacheConfigException;
32 import org.opendaylight.controller.clustering.services.CacheExistException;
33 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
34 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
35 import org.opendaylight.controller.clustering.services.IClusterServices;
36 import org.opendaylight.controller.configuration.ConfigurationObject;
37 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
38 import org.opendaylight.controller.configuration.IConfigurationContainerService;
39 import org.opendaylight.controller.connectionmanager.IConnectionManager;
40 import org.opendaylight.controller.containermanager.IContainerManager;
41 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
42 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
43 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
44 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
45 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
46 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
47 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
48 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
50 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
51 import org.opendaylight.controller.sal.action.Action;
52 import org.opendaylight.controller.sal.action.ActionType;
53 import org.opendaylight.controller.sal.action.Enqueue;
54 import org.opendaylight.controller.sal.action.Flood;
55 import org.opendaylight.controller.sal.action.FloodAll;
56 import org.opendaylight.controller.sal.action.Output;
57 import org.opendaylight.controller.sal.connection.ConnectionLocality;
58 import org.opendaylight.controller.sal.core.Config;
59 import org.opendaylight.controller.sal.core.ContainerFlow;
60 import org.opendaylight.controller.sal.core.IContainer;
61 import org.opendaylight.controller.sal.core.IContainerLocalListener;
62 import org.opendaylight.controller.sal.core.Node;
63 import org.opendaylight.controller.sal.core.NodeConnector;
64 import org.opendaylight.controller.sal.core.Property;
65 import org.opendaylight.controller.sal.core.UpdateType;
66 import org.opendaylight.controller.sal.flowprogrammer.Flow;
67 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
68 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
69 import org.opendaylight.controller.sal.match.Match;
70 import org.opendaylight.controller.sal.match.MatchType;
71 import org.opendaylight.controller.sal.utils.EtherTypes;
72 import org.opendaylight.controller.sal.utils.GlobalConstants;
73 import org.opendaylight.controller.sal.utils.IObjectReader;
74 import org.opendaylight.controller.sal.utils.Status;
75 import org.opendaylight.controller.sal.utils.StatusCode;
76 import org.opendaylight.controller.switchmanager.IInventoryListener;
77 import org.opendaylight.controller.switchmanager.ISwitchManager;
78 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
79 import org.opendaylight.controller.switchmanager.Subnet;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 * Class that manages forwarding rule installation and removal per container of
85 * the network. It also maintains the central repository of all the forwarding
86 * rules installed on the network nodes.
88 public class ForwardingRulesManager implements
89 IForwardingRulesManager,
90 PortGroupChangeListener,
91 IContainerLocalListener,
93 IConfigurationContainerAware,
96 ICacheUpdateAware<Object,Object>,
97 IFlowProgrammerListener {
99 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
100 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
101 private static final String PORT_REMOVED = "Port removed";
102 private static final String NODE_DOWN = "Node is Down";
103 private static final String INVALID_FLOW_ENTRY = "Invalid FlowEntry";
104 private static final String STATIC_FLOWS_FILE_NAME = "frm_staticflows.conf";
105 private static final String PORT_GROUP_FILE_NAME = "portgroup.conf";
106 private ConcurrentMap<Integer, FlowConfig> staticFlows;
107 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
108 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
109 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
110 private ConcurrentMap<String, Object> TSPolicies;
111 private IContainerManager containerManager;
112 private IConfigurationContainerService configurationService;
113 private boolean inContainerMode; // being used by global instance only
114 protected boolean stopping;
117 * Flow database. It's the software view of what was requested to install
118 * and what is installed on the switch. It is indexed by the entry itself.
119 * The entry's hashcode resumes the network node index, the flow's priority
120 * and the flow's match. The value element is a class which contains the
121 * flow entry pushed by the applications modules and the respective
122 * container flow merged version. In absence of container flows, the two
123 * flow entries are the same.
125 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
126 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
128 * Per node and per group indexing
130 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
131 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
134 * Inactive flow list. This is for the global instance of FRM It will
135 * contain all the flow entries which were installed on the global container
136 * when the first container is created.
138 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
140 private IContainer container;
141 private Set<IForwardingRulesManagerAware> frmAware =
142 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
143 private PortGroupProvider portGroupProvider;
144 private IFlowProgrammerService programmer;
145 private IClusterContainerServices clusterContainerService = null;
146 private ISwitchManager switchManager;
147 private Thread frmEventHandler;
148 protected BlockingQueue<FRMEvent> pendingEvents;
150 // Distributes FRM programming in the cluster
151 private IConnectionManager connectionManager;
154 * Name clustered caches used to support FRM entry distribution these are by
155 * necessity non-transactional as long as need to be able to synchronize
156 * states also while a transaction is in progress
158 static final String WORK_ORDER_CACHE = "frm.workOrder";
159 static final String WORK_STATUS_CACHE = "frm.workStatus";
160 static final String ORIGINAL_SW_VIEW_CACHE = "frm.originalSwView";
161 static final String INSTALLED_SW_VIEW_CACHE = "frm.installedSwView";
164 * Data structure responsible for distributing the FlowEntryInstall requests
165 * in the cluster. The key value is entry that is being either Installed or
166 * Updated or Delete. The value field is the same of the key value in case
167 * of Installation or Deletion, it's the new entry in case of Modification,
168 * this because the clustering caches don't allow null values.
170 * The logic behind this data structure is that the controller that initiate
171 * the request will place the order here, someone will pick it and then will
172 * remove from this data structure because is being served.
174 * TODO: We need to have a way to cleanup this data structure if entries are
175 * not picked by anyone, which is always a case can happen especially on
176 * Node disconnect cases.
178 protected ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
181 * Data structure responsible for retrieving the results of the workOrder
182 * submitted to the cluster.
184 * The logic behind this data structure is that the controller that has
185 * executed the order will then place the result in workStatus signaling
186 * that there was a success or a failure.
188 * TODO: The workStatus entries need to have a lifetime associated in case
189 * of requestor controller leaving the cluster.
191 protected ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
194 * Local Map used to hold the Future which a caller can use to monitor for
197 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
198 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
201 * Max pool size for the executor
203 private static final int maxPoolSize = 10;
207 * Entry being installed/updated/removed
209 * New entry will be placed after the update operation. Valid
210 * only for UpdateType.CHANGED, null for all the other cases
213 * @return a Future object for monitoring the progress of the result, or
214 * null in case the processing should take place locally
216 private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
218 // A null entry it's an unexpected condition, anyway it's safe to keep
219 // the handling local
224 Node n = e.getNode();
225 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
226 // Create the work order and distribute it
227 FlowEntryDistributionOrder fe =
228 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
229 // First create the monitor job
230 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
231 logsync.trace("Node {} not local so sending fe {}", n, fe);
232 workMonitor.put(fe, ret);
233 if (t.equals(UpdateType.CHANGED)) {
234 // Then distribute the work
235 workOrder.put(fe, u);
237 // Then distribute the work
238 workOrder.put(fe, e);
240 logsync.trace("WorkOrder requested");
241 // Now create an Handle to monitor the execution of the operation
245 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
250 * Checks if the FlowEntry targets are valid for this container
253 * The flow entry to test
254 * @return a Status object representing the result of the validation
256 private Status validateEntry(FlowEntry flowEntry) {
257 // Node presence check
258 Node node = flowEntry.getNode();
259 if (!switchManager.getNodes().contains(node)) {
260 return new Status(StatusCode.BADREQUEST, String.format("Node %s is not present in this container", node));
263 // Ports and actions validation check
264 Flow flow = flowEntry.getFlow();
265 Match match = flow.getMatch();
266 if (match.isPresent(MatchType.IN_PORT)) {
267 NodeConnector inputPort = (NodeConnector)match.getField(MatchType.IN_PORT).getValue();
268 if (!switchManager.getNodeConnectors(node).contains(inputPort)) {
269 String msg = String.format("Ingress port %s is not present on this container", inputPort);
270 return new Status(StatusCode.BADREQUEST, msg);
273 for (Action action : flow.getActions()) {
274 if (action instanceof Flood && !GlobalConstants.DEFAULT.toString().equals(getContainerName())) {
275 return new Status(StatusCode.BADREQUEST, String.format("Flood is only allowed in default container"));
277 if (action instanceof FloodAll && !GlobalConstants.DEFAULT.toString().equals(getContainerName())) {
278 return new Status(StatusCode.BADREQUEST, String.format("FloodAll is only allowed in default container"));
280 if (action instanceof Output) {
281 Output out = (Output)action;
282 NodeConnector outputPort = out.getPort();
283 if (!switchManager.getNodeConnectors(node).contains(outputPort)) {
284 String msg = String.format("Output port %s is not present on this container", outputPort);
285 return new Status(StatusCode.BADREQUEST, msg);
288 if (action instanceof Enqueue) {
289 Enqueue out = (Enqueue)action;
290 NodeConnector outputPort = out.getPort();
291 if (!switchManager.getNodeConnectors(node).contains(outputPort)) {
292 String msg = String.format("Enqueue port %s is not present on this container", outputPort);
293 return new Status(StatusCode.BADREQUEST, msg);
297 return new Status(StatusCode.SUCCESS);
301 * Adds a flow entry onto the network node It runs various validity checks
302 * and derive the final container flows merged entries that will be
303 * attempted to be installed
306 * the original flow entry application requested to add
308 * the flag indicating if this is a asynchronous request
309 * @return the status of this request. In case of asynchronous call, it will
310 * contain the unique id assigned to this request
312 private Status addEntry(FlowEntry flowEntry, boolean async) {
315 if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
316 String logMsg = INVALID_FLOW_ENTRY + ": {}";
317 log.warn(logMsg, flowEntry);
318 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
321 // Operational check: input, output and queue ports presence check and
322 // action validation for this container
323 Status status = validateEntry(flowEntry);
324 if (!status.isSuccess()) {
325 String msg = String.format("%s: %s", INVALID_FLOW_ENTRY, status.getDescription());
326 log.warn("{}: {}", msg, flowEntry);
327 return new Status(StatusCode.NOTACCEPTABLE, msg);
331 * Redundant Check: Check if the request is a redundant one from the
332 * same application the flowEntry is equal to an existing one. Given we
333 * do not have an application signature in the requested FlowEntry yet,
334 * we are here detecting the above condition by comparing the flow
335 * names, if set. If they are equal to the installed flow, most likely
336 * this is a redundant installation request from the same application
337 * and we can silently return success
339 * TODO: in future a sort of application reference list mechanism will
340 * be added to the FlowEntry so that exact flow can be used by different
343 FlowEntry present = this.originalSwView.get(flowEntry);
344 if (present != null) {
345 boolean sameFlow = present.getFlow().equals(flowEntry.getFlow());
346 boolean sameApp = present.getFlowName() != null && present.getFlowName().equals(flowEntry.getFlowName());
347 if (sameFlow && sameApp) {
348 log.trace("Skipping redundant request for flow {} on node {}", flowEntry.getFlowName(),
349 flowEntry.getNode());
350 return new Status(StatusCode.SUCCESS, "Entry is already present");
355 * Derive the container flow merged entries to install In presence of N
356 * container flows, we may end up with N different entries to install...
358 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
360 // Container Flow conflict Check
361 if (toInstallList.isEmpty()) {
362 String msg = "Flow Entry conflicts with all Container Flows";
363 String logMsg = msg + ": {}";
364 log.warn(logMsg, flowEntry);
365 return new Status(StatusCode.CONFLICT, msg);
368 // Derive the list of entries good to be installed
369 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
370 for (FlowEntryInstall entry : toInstallList) {
371 // Conflict Check: Verify new entry would not overwrite existing
373 if (this.installedSwView.containsKey(entry)) {
374 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
375 log.trace("Aborting to install {}", entry);
378 toInstallSafe.add(entry);
381 // Declare failure if all the container flow merged entries clash with
383 if (toInstallSafe.size() == 0) {
384 String msg = "A flow with same match and priority exists on the target node";
385 String logMsg = msg + ": {}";
386 log.warn(logMsg, flowEntry);
387 return new Status(StatusCode.CONFLICT, msg);
390 // Try to install an entry at the time
391 Status error = new Status(null, null);
392 Status succeded = null;
393 boolean oneSucceded = false;
394 for (FlowEntryInstall installEntry : toInstallSafe) {
396 // Install and update database
397 Status ret = addEntryInternal(installEntry, async);
399 if (ret.isSuccess()) {
402 * The first successful status response will be returned For the
403 * asynchronous call, we can discard the container flow
404 * complication for now and assume we will always deal with one
405 * flow only per request
410 log.trace("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
414 return (oneSucceded) ? succeded : error;
418 * Given a flow entry and the list of container flows, it returns the list
419 * of container flow merged flow entries good to be installed on this
420 * container. If the list of container flows is null or empty, the install
421 * entry list will contain only one entry, the original flow entry. If the
422 * flow entry is congruent with all the N container flows, then the output
423 * install entry list will contain N entries. If the output list is empty,
424 * it means the passed flow entry conflicts with all the container flows.
427 * The list of container flows
428 * @return the list of container flow merged entries good to be installed on
431 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
432 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
434 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
435 // No container flows => entry good to be installed unchanged
436 toInstallList.add(new FlowEntryInstall(request.clone(), null));
438 // Create the list of entries to be installed. If the flow entry is
439 // not congruent with any container flow, no install entries will be
441 for (ContainerFlow cFlow : container.getContainerFlows()) {
442 if (cFlow.allowsFlow(request.getFlow())) {
443 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
447 return toInstallList;
451 * Modify a flow entry with a new one It runs various validity check and
452 * derive the final container flows merged flow entries to work with
454 * @param currentFlowEntry
455 * @param newFlowEntry
457 * the flag indicating if this is a asynchronous request
458 * @return the status of this request. In case of asynchronous call, it will
459 * contain the unique id assigned to this request
461 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
465 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
466 || newFlowEntry.getNode() == null || newFlowEntry.getFlow() == null) {
467 String msg = "Modify: " + INVALID_FLOW_ENTRY;
468 String logMsg = msg + ": {} or {}";
469 log.warn(logMsg, currentFlowEntry, newFlowEntry);
470 return new Status(StatusCode.NOTACCEPTABLE, msg);
472 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
473 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
474 String msg = "Modify: Incompatible Flow Entries";
475 String logMsg = msg + ": {} and {}";
476 log.warn(logMsg, currentFlowEntry, newFlowEntry);
477 return new Status(StatusCode.NOTACCEPTABLE, msg);
481 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
482 String msg = "Modify skipped as flows are the same";
483 String logMsg = msg + ": {} and {}";
484 log.debug(logMsg, currentFlowEntry, newFlowEntry);
485 return new Status(StatusCode.SUCCESS, msg);
488 // Operational check: input, output and queue ports presence check and
489 // action validation for this container
490 Status status = validateEntry(newFlowEntry);
491 if (!status.isSuccess()) {
492 String msg = String.format("Modify: %s: %s", INVALID_FLOW_ENTRY, status.getDescription());
493 log.warn("{}: {}", msg, newFlowEntry);
494 return new Status(StatusCode.NOTACCEPTABLE, msg);
498 * Conflict Check: Verify the new entry would not conflict with an
499 * existing one. This is a loose check on the previous original flow
500 * entry requests. No check on the container flow merged flow entries
503 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
504 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
505 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
506 String logMsg = msg + ": {}";
507 log.warn(logMsg, currentFlowEntry);
508 return new Status(StatusCode.CONFLICT, msg);
511 // Derive the installed and toInstall entries
512 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
513 container.getContainerFlows());
514 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
516 if (toInstallList.isEmpty()) {
517 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
518 String logMsg = msg + ": {}";
519 log.warn(logMsg, newFlowEntry);
521 return new Status(StatusCode.CONFLICT, msg);
525 * If the two list sizes differ, it means the new flow entry does not
526 * satisfy the same number of container flows the current entry does.
527 * This is only possible when the new entry and current entry have
528 * different match. In this scenario the modification would ultimately
529 * be handled as a remove and add operations in the protocol plugin.
531 * Also, if any of the new flow entries would clash with an existing
532 * one, we cannot proceed with the modify operation, because it would
533 * fail for some entries and leave stale entries on the network node.
534 * Modify path can be taken only if it can be performed completely, for
537 * So, for the above two cases, to simplify, let's decouple the modify
538 * in: 1) remove current entries 2) install new entries
540 Status succeeded = null;
541 boolean decouple = false;
542 if (installedList.size() != toInstallList.size()) {
543 log.trace("Modify: New flow entry does not satisfy the same "
544 + "number of container flows as the original entry does");
547 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
548 for (FlowEntryInstall installEntry : toInstallList) {
550 * Conflict Check: Verify the new entry would not overwrite another
553 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
554 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
555 log.trace("Modify: new container flow merged flow entry clashes with existing flow");
558 toInstallSafe.add(installEntry);
563 // Remove current entries
564 for (FlowEntryInstall currEntry : installedList) {
565 this.removeEntryInternal(currEntry, async);
567 // Install new entries
568 for (FlowEntryInstall newEntry : toInstallSafe) {
569 succeeded = this.addEntryInternal(newEntry, async);
573 * The two list have the same size and the entries to install do not
574 * clash with any existing flow on the network node. We assume here
575 * (and might be wrong) that the same container flows that were
576 * satisfied by the current entries are the same that are satisfied
577 * by the new entries. Let's take the risk for now.
579 * Note: modification has to be complete. If any entry modification
580 * fails, we need to stop, restore the already modified entries, and
583 Status retModify = null;
585 int size = toInstallList.size();
587 // Modify and update database
588 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
589 if (retModify.isSuccess()) {
595 // Check if uncompleted modify
597 log.warn("Unable to perform a complete modify for all the container flows merged entries");
598 // Restore original entries
601 log.info("Attempting to restore initial entries");
602 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
603 if (retExt.isSuccess()) {
609 // Fatal error, recovery failed
611 String msg = "Flow recovery failed ! Unrecoverable Error";
613 return new Status(StatusCode.INTERNALERROR, msg);
616 succeeded = retModify;
619 * The first successful status response will be returned. For the
620 * asynchronous call, we can discard the container flow complication for
621 * now and assume we will always deal with one flow only per request
627 * This is the function that modifies the final container flows merged
628 * entries on the network node and update the database. It expects that all
629 * the validity checks are passed.
630 * This function is supposed to be called only on the controller on which
631 * the IFRM call is executed.
633 * @param currentEntries
636 * the flag indicating if this is a asynchronous request
637 * @return the status of this request. In case of asynchronous call, it will
638 * contain the unique id assigned to this request
640 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
641 Status status = new Status(StatusCode.UNDEFINED);
642 FlowEntryDistributionOrderFutureTask futureStatus =
643 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
644 if (futureStatus != null) {
646 status = futureStatus.get();
648 .equals(StatusCode.TIMEOUT)) {
649 // A timeout happened, lets cleanup the workMonitor
650 workMonitor.remove(futureStatus.getOrder());
652 } catch (InterruptedException e) {
654 } catch (ExecutionException e) {
658 // Modify the flow on the network node
659 status = modifyEntryInHw(currentEntries, newEntries, async);
662 if (!status.isSuccess()) {
663 log.trace("{} SDN Plugin failed to program the flow: {}. The failure is: {}",
664 (futureStatus != null) ? "Remote" : "Local", newEntries.getInstall(), status.getDescription());
668 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
671 newEntries.setRequestId(status.getRequestId());
672 updateSwViews(currentEntries, false);
673 updateSwViews(newEntries, true);
678 private Status modifyEntryInHw(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
679 return async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall().getFlow(),
680 newEntries.getInstall().getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries
681 .getInstall().getFlow(), newEntries.getInstall().getFlow());
685 * Remove a flow entry. If the entry is not present in the software view
686 * (entry or node not present), it return successfully
689 * the flow entry to remove
691 * the flag indicating if this is a asynchronous request
692 * @return the status of this request. In case of asynchronous call, it will
693 * contain the unique id assigned to this request
695 private Status removeEntry(FlowEntry flowEntry, boolean async) {
696 Status error = new Status(null, null);
699 if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
700 String logMsg = INVALID_FLOW_ENTRY + ": {}";
701 log.warn(logMsg, flowEntry);
702 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
705 // Derive the container flows merged installed entries
706 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
708 Status succeeded = null;
709 boolean atLeastOneRemoved = false;
710 for (FlowEntryInstall entry : installedList) {
711 if (!installedSwView.containsKey(entry)) {
712 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
713 log.debug(logMsg, flowEntry);
714 if (installedList.size() == 1) {
715 // If we had only one entry to remove, we are done
716 return new Status(StatusCode.SUCCESS);
722 // Remove and update DB
723 Status ret = removeEntryInternal(entry, async);
725 if (!ret.isSuccess()) {
727 log.trace("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
728 if (installedList.size() == 1) {
729 // If we had only one entry to remove, this is fatal failure
734 atLeastOneRemoved = true;
739 * No worries if full removal failed. Consistency checker will take care
740 * of removing the stale entries later, or adjusting the software
741 * database if not in sync with hardware
743 return (atLeastOneRemoved) ? succeeded : error;
747 * This is the function that removes the final container flows merged entry
748 * from the network node and update the database. It expects that all the
749 * validity checks are passed
750 * This function is supposed to be called only on the controller on which
751 * the IFRM call is executed.
754 * the flow entry to remove
756 * the flag indicating if this is a asynchronous request
757 * @return the status of this request. In case of asynchronous call, it will
758 * contain the unique id assigned to this request
760 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
761 Status status = new Status(StatusCode.UNDEFINED);
762 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
763 if (futureStatus != null) {
765 status = futureStatus.get();
766 if (status.getCode().equals(StatusCode.TIMEOUT)) {
767 // A timeout happened, lets cleanup the workMonitor
768 workMonitor.remove(futureStatus.getOrder());
770 } catch (InterruptedException e) {
772 } catch (ExecutionException e) {
776 // Mark the entry to be deleted (for CC just in case we fail)
780 status = removeEntryInHw(entry, async);
783 if (!status.isSuccess()) {
784 log.trace("{} SDN Plugin failed to remove the flow: {}. The failure is: {}",
785 (futureStatus != null) ? "Remote" : "Local", entry.getInstall(), status.getDescription());
789 log.trace("Removed {}", entry.getInstall());
792 updateSwViews(entry, false);
797 private Status removeEntryInHw(FlowEntryInstall entry, boolean async) {
798 return async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall().getFlow()) : programmer
799 .removeFlow(entry.getNode(), entry.getInstall().getFlow());
803 * This is the function that installs the final container flow merged entry
804 * on the network node and updates the database. It expects that all the
805 * validity and conflict checks are passed. That means it does not check
806 * whether this flow would conflict or overwrite an existing one.
807 * This function is supposed to be called only on the controller on which
808 * the IFRM call is executed.
811 * the flow entry to install
813 * the flag indicating if this is a asynchronous request
814 * @return the status of this request. In case of asynchronous call, it will
815 * contain the unique id assigned to this request
817 private Status addEntryInternal(FlowEntryInstall entry, boolean async) {
818 Status status = new Status(StatusCode.UNDEFINED);
819 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
820 if (futureStatus != null) {
822 status = futureStatus.get();
823 if (status.getCode().equals(StatusCode.TIMEOUT)) {
824 // A timeout happened, lets cleanup the workMonitor
825 workMonitor.remove(futureStatus.getOrder());
827 } catch (InterruptedException e) {
829 } catch (ExecutionException e) {
833 status = addEntryInHw(entry, async);
836 if (!status.isSuccess()) {
837 log.trace("{} SDN Plugin failed to program the flow: {}. The failure is: {}",
838 (futureStatus != null) ? "Remote" : "Local", entry.getInstall(), status.getDescription());
842 log.trace("Added {}", entry.getInstall());
845 entry.setRequestId(status.getRequestId());
846 updateSwViews(entry, true);
851 private Status addEntryInHw(FlowEntryInstall entry, boolean async) {
852 // Install the flow on the network node
853 return async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall().getFlow()) : programmer.addFlow(
854 entry.getNode(), entry.getInstall().getFlow());
858 * Returns true if the flow conflicts with all the container's flows. This
859 * means that if the function returns true, the passed flow entry is
860 * congruent with at least one container flow, hence it is good to be
861 * installed on this container.
864 * @return true if flow conflicts with all the container flows, false
867 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
868 List<ContainerFlow> cFlowList = container.getContainerFlows();
870 // Validity check and avoid unnecessary computation
871 // Also takes care of default container where no container flows are
873 if (cFlowList == null || cFlowList.isEmpty()) {
877 for (ContainerFlow cFlow : cFlowList) {
878 if (cFlow.allowsFlow(flowEntry.getFlow())) {
879 // Entry is allowed by at least one container flow: good to go
886 private ConcurrentMap.Entry<Integer, FlowConfig> getStaticFlowEntry(String name, Node node) {
887 for (ConcurrentMap.Entry<Integer, FlowConfig> flowEntry : staticFlows.entrySet()) {
888 FlowConfig flowConfig = flowEntry.getValue();
889 if (flowConfig.isByNameAndNodeIdEqual(name, node)) {
896 private void updateIndexDatabase(FlowEntryInstall entry, boolean add) {
897 // Update node indexed flow database
898 updateNodeFlowsDB(entry, add);
900 // Update group indexed flow database
901 updateGroupFlowsDB(entry, add);
905 * Update the node mapped flows database
907 private void updateSwViews(FlowEntryInstall flowEntries, boolean add) {
909 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
910 installedSwView.put(flowEntries, flowEntries);
912 originalSwView.remove(flowEntries.getOriginal());
913 installedSwView.remove(flowEntries);
918 * Update the node mapped flows database
920 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
921 Node node = flowEntries.getNode();
923 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
924 if (nodeIndeces == null) {
928 nodeIndeces = new ArrayList<FlowEntryInstall>();
933 // there may be an already existing entry.
934 // remove it before adding the new one.
935 // This is necessary since we have observed that in some cases
936 // Infinispan does aggregation for operations (eg:- remove and then put a different value)
937 // related to the same key within the same transaction.
938 // Need this defensive code as the new FlowEntryInstall may be different
939 // than the old one even though the equals method returns true. This is because
940 // the equals method does not take into account the action list.
941 if(nodeIndeces.contains(flowEntries)) {
942 nodeIndeces.remove(flowEntries);
944 nodeIndeces.add(flowEntries);
946 nodeIndeces.remove(flowEntries);
949 // Update cache across cluster
950 if (nodeIndeces.isEmpty()) {
951 this.nodeFlows.remove(node);
953 this.nodeFlows.put(node, nodeIndeces);
958 * Update the group name mapped flows database
960 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
961 String groupName = flowEntries.getGroupName();
963 // Flow may not be part of a group
964 if (groupName == null) {
968 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
969 if (indices == null) {
973 indices = new ArrayList<FlowEntryInstall>();
978 // same comments in the similar code section in
979 // updateNodeFlowsDB method apply here too
980 if(indices.contains(flowEntries)) {
981 indices.remove(flowEntries);
983 indices.add(flowEntries);
985 indices.remove(flowEntries);
988 // Update cache across cluster
989 if (indices.isEmpty()) {
990 this.groupFlows.remove(groupName);
992 this.groupFlows.put(groupName, indices);
997 * Remove a flow entry that has been added previously First checks if the
998 * entry is effectively present in the local database
1000 @SuppressWarnings("unused")
1001 private Status removeEntry(Node node, String flowName) {
1002 FlowEntryInstall target = null;
1005 for (FlowEntryInstall entry : installedSwView.values()) {
1006 if (entry.equalsByNodeAndName(node, flowName)) {
1012 // If it is not there, stop any further processing
1013 if (target == null) {
1014 return new Status(StatusCode.SUCCESS, "Entry is not present");
1018 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
1021 if (status.isSuccess()) {
1022 updateSwViews(target, false);
1025 log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
1026 status.getDescription());
1033 public Status installFlowEntry(FlowEntry flowEntry) {
1035 if (isContainerModeAllowed(flowEntry)) {
1036 status = addEntry(flowEntry, false);
1038 String msg = "Controller in container mode: Install Refused";
1039 String logMsg = msg + ": {}";
1040 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1041 log.warn(logMsg, flowEntry);
1047 public Status installFlowEntryAsync(FlowEntry flowEntry) {
1049 if (isContainerModeAllowed(flowEntry)) {
1050 status = addEntry(flowEntry, true);
1052 String msg = "Controller in container mode: Install Refused";
1053 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1060 public Status uninstallFlowEntry(FlowEntry flowEntry) {
1062 if (isContainerModeAllowed(flowEntry)) {
1063 status = removeEntry(flowEntry, false);
1065 String msg = "Controller in container mode: Uninstall Refused";
1066 String logMsg = msg + ": {}";
1067 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1068 log.warn(logMsg, flowEntry);
1074 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
1076 if (isContainerModeAllowed(flowEntry)) {
1077 status = removeEntry(flowEntry, true);
1079 String msg = "Controller in container mode: Uninstall Refused";
1080 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1087 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1088 Status status = null;
1089 if (isContainerModeAllowed(currentFlowEntry)) {
1090 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1092 String msg = "Controller in container mode: Modify Refused";
1093 String logMsg = msg + ": {}";
1094 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1095 log.warn(logMsg, newFlowEntry);
1101 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1102 Status status = null;
1103 if (isContainerModeAllowed(currentFlowEntry)) {
1104 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
1106 String msg = "Controller in container mode: Modify Refused";
1107 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1114 * Returns whether the specified flow entry is allowed to be
1115 * installed/removed/modified based on the current container mode status.
1116 * This call always returns true in the container instance of forwarding
1117 * rules manager. It is meant for the global instance only (default
1118 * container) of forwarding rules manager. Idea is that for assuring
1119 * container isolation of traffic, flow installation in default container is
1120 * blocked when in container mode (containers are present). The only flows
1121 * that are allowed in container mode in the default container are the
1122 * proactive flows, the ones automatically installed on the network node
1123 * which forwarding mode has been configured to "proactive". These flows are
1124 * needed by controller to discover the nodes topology and to discover the
1125 * attached hosts for some SDN switches.
1128 * The flow entry to be installed/removed/modified
1129 * @return true if not in container mode or if flowEntry is internally
1132 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1133 return (!inContainerMode) ? true : flowEntry.isInternal();
1137 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1139 * Run a check on the original entries to decide whether to go with a
1140 * add or modify method. A loose check means only check against the
1141 * original flow entry requests and not against the installed flow
1142 * entries which are the result of the original entry merged with the
1143 * container flow(s) (if any). The modifyFlowEntry method in presence of
1144 * conflicts with the Container flows (if any) would revert back to a
1145 * delete + add pattern
1147 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1149 if (currentFlowEntry != null) {
1150 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1152 return installFlowEntry(newFlowEntry);
1157 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1159 * Run a check on the original entries to decide whether to go with a
1160 * add or modify method. A loose check means only check against the
1161 * original flow entry requests and not against the installed flow
1162 * entries which are the result of the original entry merged with the
1163 * container flow(s) (if any). The modifyFlowEntry method in presence of
1164 * conflicts with the Container flows (if any) would revert back to a
1165 * delete + add pattern
1167 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1169 if (currentFlowEntry != null) {
1170 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1172 return installFlowEntryAsync(newFlowEntry);
1177 public Status uninstallFlowEntryGroup(String groupName) {
1178 if (groupName == null || groupName.isEmpty()) {
1179 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1181 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1182 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1184 if (inContainerMode) {
1185 String msg = "Controller in container mode: Group Uninstall Refused";
1186 String logMsg = msg + ": {}";
1187 log.warn(logMsg, groupName);
1188 return new Status(StatusCode.NOTACCEPTABLE, msg);
1190 int toBeRemoved = 0;
1192 if (groupFlows.containsKey(groupName)) {
1193 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1194 toBeRemoved = list.size();
1195 for (FlowEntryInstall entry : list) {
1196 Status status = this.removeEntry(entry.getOriginal(), false);
1197 if (status.isSuccess()) {
1200 error = status.getDescription();
1204 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1205 "Not all the flows were removed: " + error);
1209 public Status uninstallFlowEntryGroupAsync(String groupName) {
1210 if (groupName == null || groupName.isEmpty()) {
1211 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1213 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1214 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1216 if (inContainerMode) {
1217 String msg = "Controller in container mode: Group Uninstall Refused";
1218 String logMsg = msg + ": {}";
1219 log.warn(logMsg, groupName);
1220 return new Status(StatusCode.NOTACCEPTABLE, msg);
1222 if (groupFlows.containsKey(groupName)) {
1223 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1224 for (FlowEntryInstall entry : list) {
1225 this.removeEntry(entry.getOriginal(), true);
1228 return new Status(StatusCode.SUCCESS);
1232 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1233 return entryConflictsWithContainerFlows(flowEntry);
1237 * Updates all installed flows because the container flow got updated This
1238 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1239 * Reinstall of all flows This is needed because a new container flows
1240 * merged flow may conflict with an existing old container flows merged flow
1241 * on the network node
1243 protected void updateFlowsContainerFlow() {
1244 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1245 // First remove all installed entries
1246 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1247 FlowEntryInstall current = entry.getValue();
1248 // Store the original entry
1249 toReInstall.add(current.getOriginal());
1250 // Remove the old couples. No validity checks to be run, use the
1252 this.removeEntryInternal(current, false);
1254 // Then reinstall the original entries
1255 for (FlowEntry entry : toReInstall) {
1256 // Reinstall the original flow entries, via the regular path: new
1257 // cFlow merge + validations
1258 this.installFlowEntry(entry);
1262 private void nonClusterObjectCreate() {
1263 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1264 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1265 TSPolicies = new ConcurrentHashMap<String, Object>();
1266 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1267 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1268 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1269 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1270 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1274 public void setTSPolicyData(String policyname, Object o, boolean add) {
1277 /* Check if this policy already exists */
1278 if (!(TSPolicies.containsKey(policyname))) {
1279 TSPolicies.put(policyname, o);
1282 TSPolicies.remove(policyname);
1284 if (frmAware != null) {
1285 synchronized (frmAware) {
1286 for (IForwardingRulesManagerAware frma : frmAware) {
1288 frma.policyUpdate(policyname, add);
1289 } catch (Exception e) {
1290 log.warn("Exception on callback", e);
1298 public Map<String, Object> getTSPolicyData() {
1303 public Object getTSPolicyData(String policyName) {
1304 if (TSPolicies.containsKey(policyName)) {
1305 return TSPolicies.get(policyName);
1312 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1313 List<FlowEntry> list = new ArrayList<FlowEntry>();
1314 if (policyName != null && !policyName.trim().isEmpty()) {
1315 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1316 if (policyName.equals(entry.getKey().getGroupName())) {
1317 list.add(entry.getValue().clone());
1325 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1326 List<FlowEntry> list = new ArrayList<FlowEntry>();
1327 if (policyName != null && !policyName.trim().isEmpty()) {
1328 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1329 if (policyName.equals(entry.getKey().getGroupName())) {
1330 list.add(entry.getValue().getInstall().clone());
1338 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1340 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1341 if (flow.getFlowName().equals(flowName)) {
1342 FlowEntry currentFlowEntry = flow.getOriginal();
1343 FlowEntry newFlowEntry = currentFlowEntry.clone();
1344 for (NodeConnector dstPort : portList) {
1345 newFlowEntry.getFlow().addAction(new Output(dstPort));
1347 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1348 if (error.isSuccess()) {
1349 log.trace("Ports {} added to FlowEntry {}", portList, flowName);
1351 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1352 currentFlowEntry.toString(), error.getDescription());
1357 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1361 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1362 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1363 FlowEntryInstall flow = this.installedSwView.get(index);
1364 if (flow.getFlowName().equals(flowName)) {
1365 FlowEntry currentFlowEntry = flow.getOriginal();
1366 FlowEntry newFlowEntry = currentFlowEntry.clone();
1367 for (NodeConnector dstPort : portList) {
1368 Action action = new Output(dstPort);
1369 newFlowEntry.getFlow().removeAction(action);
1371 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1372 if (status.isSuccess()) {
1373 log.trace("Ports {} removed from FlowEntry {}", portList, flowName);
1375 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1376 currentFlowEntry.toString(), status.getDescription());
1381 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1385 * This function assumes the target flow has only one output port
1388 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1389 FlowEntry currentFlowEntry = null;
1390 FlowEntry newFlowEntry = null;
1393 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1394 FlowEntryInstall flow = this.installedSwView.get(index);
1395 if (flow.getFlowName().equals(flowName)) {
1396 currentFlowEntry = flow.getOriginal();
1400 if (currentFlowEntry == null) {
1401 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1405 // Create a flow copy with the new output port
1406 newFlowEntry = currentFlowEntry.clone();
1407 Action target = null;
1408 for (Action action : newFlowEntry.getFlow().getActions()) {
1409 if (action.getType() == ActionType.OUTPUT) {
1414 newFlowEntry.getFlow().removeAction(target);
1415 newFlowEntry.getFlow().addAction(new Output(outPort));
1417 // Modify on network node
1418 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1420 if (status.isSuccess()) {
1421 log.trace("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1423 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1424 status.getDescription());
1430 public NodeConnector getOutputPort(Node node, String flowName) {
1431 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1432 FlowEntryInstall flow = this.installedSwView.get(index);
1433 if (flow.getFlowName().equals(flowName)) {
1434 for (Action action : flow.getOriginal().getFlow().getActions()) {
1435 if (action.getType() == ActionType.OUTPUT) {
1436 return ((Output) action).getPort();
1444 private void cacheStartup() {
1449 private void allocateCaches() {
1450 if (this.clusterContainerService == null) {
1451 log.warn("Un-initialized clusterContainerService, can't create cache");
1455 log.debug("Allocating caches for Container {}", container.getName());
1458 clusterContainerService.createCache(ORIGINAL_SW_VIEW_CACHE,
1459 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1461 clusterContainerService.createCache(INSTALLED_SW_VIEW_CACHE,
1462 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1464 clusterContainerService.createCache("frm.inactiveFlows",
1465 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1467 clusterContainerService.createCache("frm.staticFlows",
1468 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1470 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1471 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1473 clusterContainerService.createCache("frm.portGroupConfigs",
1474 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1476 clusterContainerService.createCache("frm.portGroupData",
1477 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1479 clusterContainerService.createCache("frm.TSPolicies",
1480 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1482 clusterContainerService.createCache(WORK_STATUS_CACHE,
1483 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1485 clusterContainerService.createCache(WORK_ORDER_CACHE,
1486 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1488 } catch (CacheConfigException cce) {
1489 log.error("CacheConfigException");
1490 } catch (CacheExistException cce) {
1491 log.error("CacheExistException");
1495 @SuppressWarnings({ "unchecked" })
1496 private void retrieveCaches() {
1497 ConcurrentMap<?, ?> map;
1499 if (this.clusterContainerService == null) {
1500 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1501 nonClusterObjectCreate();
1505 log.debug("Retrieving Caches for Container {}", container.getName());
1507 map = clusterContainerService.getCache(ORIGINAL_SW_VIEW_CACHE);
1509 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1511 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1514 map = clusterContainerService.getCache(INSTALLED_SW_VIEW_CACHE);
1516 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1518 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1521 map = clusterContainerService.getCache("frm.inactiveFlows");
1523 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1525 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1528 map = clusterContainerService.getCache("frm.staticFlows");
1530 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1532 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1535 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1537 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1539 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1542 map = clusterContainerService.getCache("frm.portGroupConfigs");
1544 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1546 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1549 map = clusterContainerService.getCache("frm.portGroupData");
1551 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1553 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1556 map = clusterContainerService.getCache("frm.TSPolicies");
1558 TSPolicies = (ConcurrentMap<String, Object>) map;
1560 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1563 map = clusterContainerService.getCache(WORK_ORDER_CACHE);
1565 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1567 log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName());
1570 map = clusterContainerService.getCache(WORK_STATUS_CACHE);
1572 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1574 log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName());
1578 private boolean flowConfigExists(FlowConfig config) {
1579 // Flow name has to be unique on per node id basis
1580 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1581 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1589 public Status addStaticFlow(FlowConfig config) {
1590 // Configuration object validation
1591 Status status = config.validate();
1592 if (!status.isSuccess()) {
1593 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1594 String error = "Invalid Configuration (" + status.getDescription() + ")";
1595 config.setStatus(error);
1596 return new Status(StatusCode.BADREQUEST, error);
1598 return addStaticFlowInternal(config, false);
1602 * Private method to add a static flow configuration which does not run any
1603 * validation on the passed FlowConfig object. If restore is set to true,
1604 * configuration is stored in configuration database regardless the
1605 * installation on the network node was successful. This is useful at boot
1606 * when static flows are present in startup configuration and are read
1607 * before the switches connects.
1610 * The static flow configuration
1612 * if true, the configuration is stored regardless the
1613 * installation on the network node was successful
1614 * @return The status of this request
1616 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1617 boolean multipleFlowPush = false;
1620 config.setStatus(StatusCode.SUCCESS.toString());
1623 if (flowConfigExists(config)) {
1624 error = "Entry with this name on specified switch already exists";
1625 log.warn("Entry with this name on specified switch already exists: {}", config);
1626 config.setStatus(error);
1627 return new Status(StatusCode.CONFLICT, error);
1630 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1631 for (String portGroupName : portGroupConfigs.keySet()) {
1632 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1633 multipleFlowPush = true;
1637 if (!multipleFlowPush) {
1638 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1639 error = "Invalid Configuration (Invalid PortGroup Name)";
1640 config.setStatus(error);
1641 return new Status(StatusCode.BADREQUEST, error);
1646 * If requested program the entry in hardware first before updating the
1649 if (!multipleFlowPush) {
1651 if (config.installInHw()) {
1652 FlowEntry entry = config.getFlowEntry();
1653 status = this.installFlowEntry(entry);
1654 if (!status.isSuccess()) {
1655 config.setStatus(status.getDescription());
1664 * When the control reaches this point, either of the following
1665 * conditions is true 1. This is a single entry configuration (non
1666 * PortGroup) and the hardware installation is successful 2. This is a
1667 * multiple entry configuration (PortGroup) and hardware installation is
1668 * NOT done directly on this event. 3. The User prefers to retain the
1669 * configuration in Controller and skip hardware installation.
1671 * Hence it is safe to update the StaticFlow DB at this point.
1673 * Note : For the case of PortGrouping, it is essential to have this DB
1674 * populated before the PortGroupListeners can query for the DB
1675 * triggered using portGroupChanged event...
1677 Integer ordinal = staticFlowsOrdinal.get(0);
1678 staticFlowsOrdinal.put(0, ++ordinal);
1679 staticFlows.put(ordinal, config);
1681 if (multipleFlowPush) {
1682 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1683 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1684 if (existingData != null) {
1685 portGroupChanged(pgconfig, existingData, true);
1688 return new Status(StatusCode.SUCCESS);
1691 private void addStaticFlowsToSwitch(Node node) {
1692 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1693 FlowConfig config = entry.getValue();
1694 if (config.isPortGroupEnabled()) {
1697 if (config.getNode().equals(node)) {
1698 if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) {
1699 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1700 config.setStatus(status.getDescription());
1704 // Update cluster cache
1705 refreshClusterStaticFlowsStatus(node);
1708 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1709 log.trace("Updating Static Flow configs on node down: {}", node);
1711 List<Integer> toRemove = new ArrayList<Integer>();
1712 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1714 FlowConfig config = entry.getValue();
1716 if (config.isPortGroupEnabled()) {
1720 if (config.installInHw() && config.getNode().equals(node)) {
1721 if (config.isInternalFlow()) {
1722 // Take note of this controller generated static flow
1723 toRemove.add(entry.getKey());
1725 config.setStatus(NODE_DOWN);
1729 // Remove controller generated static flows for this node
1730 for (Integer index : toRemove) {
1731 staticFlows.remove(index);
1733 // Update cluster cache
1734 refreshClusterStaticFlowsStatus(node);
1738 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1739 log.trace("Updating Static Flow configs on container mode change: {}", update);
1741 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1742 FlowConfig config = entry.getValue();
1743 if (config.isPortGroupEnabled()) {
1746 if (config.installInHw() && !config.isInternalFlow()) {
1749 config.setStatus("Removed from node because in container mode");
1752 config.setStatus(StatusCode.SUCCESS.toString());
1759 // Update cluster cache
1760 refreshClusterStaticFlowsStatus(null);
1764 public Status removeStaticFlow(FlowConfig config) {
1766 * No config.isInternal() check as NB does not take this path and GUI
1767 * cannot issue a delete on an internal generated flow. We need this
1768 * path to be accessible when switch mode is changed from proactive to
1769 * reactive, so that we can remove the internal generated LLDP and ARP
1773 // Look for the target configuration entry
1775 FlowConfig target = null;
1776 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1777 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1778 key = entry.getKey();
1779 target = entry.getValue();
1783 if (target == null) {
1784 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1787 // Program the network node
1788 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1790 // Update configuration database if programming was successful
1791 if (status.isSuccess()) {
1792 staticFlows.remove(key);
1799 public Status removeStaticFlow(String name, Node node) {
1800 // Look for the target configuration entry
1802 FlowConfig target = null;
1803 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1804 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1805 key = mapEntry.getKey();
1806 target = mapEntry.getValue();
1810 if (target == null) {
1811 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1814 // Validity check for api3 entry point
1815 if (target.isInternalFlow()) {
1816 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1817 String logMsg = msg + ": {}";
1818 log.warn(logMsg, name);
1819 return new Status(StatusCode.NOTACCEPTABLE, msg);
1822 if (target.isPortGroupEnabled()) {
1823 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1824 String logMsg = msg + ": {}";
1825 log.warn(logMsg, name);
1826 return new Status(StatusCode.NOTACCEPTABLE, msg);
1829 // Program the network node
1830 Status status = this.removeEntry(target.getFlowEntry(), false);
1832 // Update configuration database if programming was successful
1833 if (status.isSuccess()) {
1834 staticFlows.remove(key);
1841 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1842 // Validity check for api3 entry point
1843 if (newFlowConfig.isInternalFlow()) {
1844 String msg = "Invalid operation: Controller generated flow cannot be modified";
1845 String logMsg = msg + ": {}";
1846 log.warn(logMsg, newFlowConfig);
1847 return new Status(StatusCode.NOTACCEPTABLE, msg);
1851 Status status = newFlowConfig.validate();
1852 if (!status.isSuccess()) {
1853 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1854 newFlowConfig.setStatus(msg);
1855 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1856 return new Status(StatusCode.BADREQUEST, msg);
1859 FlowConfig oldFlowConfig = null;
1860 Integer index = null;
1861 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1862 FlowConfig entry = mapEntry.getValue();
1863 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1864 oldFlowConfig = entry;
1865 index = mapEntry.getKey();
1870 if (oldFlowConfig == null) {
1871 String msg = "Attempt to modify a non existing static flow";
1872 String logMsg = msg + ": {}";
1873 log.warn(logMsg, newFlowConfig);
1874 return new Status(StatusCode.NOTFOUND, msg);
1877 // Do not attempt to reinstall the flow, warn user
1878 if (newFlowConfig.equals(oldFlowConfig)) {
1879 String msg = "No modification detected";
1880 log.trace("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1881 return new Status(StatusCode.SUCCESS, msg);
1884 // If flow is installed, program the network node
1885 status = new Status(StatusCode.SUCCESS, "Saved in config");
1886 if (oldFlowConfig.installInHw()) {
1887 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1890 // Update configuration database if programming was successful
1891 if (status.isSuccess()) {
1892 newFlowConfig.setStatus(status.getDescription());
1893 staticFlows.put(index, newFlowConfig);
1900 public Status toggleStaticFlowStatus(String name, Node node) {
1901 return toggleStaticFlowStatus(getStaticFlow(name, node));
1905 public Status toggleStaticFlowStatus(FlowConfig config) {
1906 if (config == null) {
1907 String msg = "Invalid request: null flow config";
1909 return new Status(StatusCode.BADREQUEST, msg);
1911 // Validity check for api3 entry point
1912 if (config.isInternalFlow()) {
1913 String msg = "Invalid operation: Controller generated flow cannot be modified";
1914 String logMsg = msg + ": {}";
1915 log.warn(logMsg, config);
1916 return new Status(StatusCode.NOTACCEPTABLE, msg);
1919 // Find the config entry
1921 FlowConfig target = null;
1922 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1923 FlowConfig conf = entry.getValue();
1924 if (conf.isByNameAndNodeIdEqual(config)) {
1925 key = entry.getKey();
1930 if (target != null) {
1931 Status status = target.validate();
1932 if (!status.isSuccess()) {
1933 log.warn(status.getDescription());
1936 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1937 .installFlowEntry(target.getFlowEntry());
1938 if (status.isSuccess()) {
1939 // Update Configuration database
1940 target.setStatus(StatusCode.SUCCESS.toString());
1941 target.toggleInstallation();
1942 staticFlows.put(key, target);
1947 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1951 * Reinsert all static flows entries in the cache to force cache updates in
1952 * the cluster. This is useful when only some parameters were changed in the
1953 * entries, like the status.
1956 * The node for which the static flow configurations have to be
1957 * refreshed. If null, all nodes static flows will be refreshed.
1959 private void refreshClusterStaticFlowsStatus(Node node) {
1960 // Refresh cluster cache
1961 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1962 if (node == null || entry.getValue().getNode().equals(node)) {
1963 staticFlows.put(entry.getKey(), entry.getValue());
1969 * Uninstall all the non-internal Flow Entries present in the software view.
1970 * If requested, a copy of each original flow entry will be stored in the
1971 * inactive list so that it can be re-applied when needed (This is typically
1972 * the case when running in the default container and controller moved to
1973 * container mode) NOTE WELL: The routine as long as does a bulk change will
1974 * operate only on the entries for nodes locally attached so to avoid
1975 * redundant operations initiated by multiple nodes
1977 * @param preserveFlowEntries
1978 * if true, a copy of each original entry is stored in the
1981 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1982 log.trace("Uninstalling all non-internal flows");
1984 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1986 // Store entries / create target list
1987 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1988 FlowEntryInstall flowEntries = mapEntry.getValue();
1989 // Skip internal generated static flows
1990 if (!flowEntries.isInternal()) {
1991 toRemove.add(flowEntries);
1992 // Store the original entries if requested
1993 if (preserveFlowEntries) {
1994 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1999 // Now remove the entries
2000 for (FlowEntryInstall flowEntryHw : toRemove) {
2001 Node n = flowEntryHw.getNode();
2002 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
2003 Status status = this.removeEntryInternal(flowEntryHw, false);
2004 if (!status.isSuccess()) {
2005 log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
2008 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
2015 * Re-install all the Flow Entries present in the inactive list The inactive
2016 * list will be empty at the end of this call This function is called on the
2017 * default container instance of FRM only when the last container is deleted
2019 private void reinstallAllFlowEntries() {
2020 log.trace("Reinstalling all inactive flows");
2022 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
2023 this.addEntry(flowEntry, false);
2026 // Empty inactive list in any case
2027 inactiveFlows.clear();
2031 public List<FlowConfig> getStaticFlows() {
2032 return new ArrayList<FlowConfig>(staticFlows.values());
2036 public FlowConfig getStaticFlow(String name, Node node) {
2037 ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
2039 return entry.getValue();
2045 public List<FlowConfig> getStaticFlows(Node node) {
2046 List<FlowConfig> list = new ArrayList<FlowConfig>();
2047 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2048 if (entry.getValue().onNode(node)) {
2049 list.add(entry.getValue());
2056 public List<String> getStaticFlowNamesForNode(Node node) {
2057 List<String> list = new ArrayList<String>();
2058 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2059 if (entry.getValue().onNode(node)) {
2060 list.add(entry.getValue().getName());
2067 public List<Node> getListNodeWithConfiguredFlows() {
2068 Set<Node> set = new HashSet<Node>();
2069 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2070 set.add(entry.getValue().getNode());
2072 return new ArrayList<Node>(set);
2075 private void loadFlowConfiguration() {
2076 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, PORT_GROUP_FILE_NAME)) {
2077 addPortGroupConfig(((PortGroupConfig) conf).getName(), ((PortGroupConfig) conf).getMatchString(), true);
2080 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, STATIC_FLOWS_FILE_NAME)) {
2081 addStaticFlowInternal((FlowConfig) conf, true);
2086 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2087 return ois.readObject();
2091 public Status saveConfig() {
2092 return saveConfigInternal();
2095 private Status saveConfigInternal() {
2096 List<ConfigurationObject> nonDynamicFlows = new ArrayList<ConfigurationObject>();
2098 for (Integer ordinal : staticFlows.keySet()) {
2099 FlowConfig config = staticFlows.get(ordinal);
2100 // Do not save dynamic and controller generated static flows
2101 if (config.isDynamic() || config.isInternalFlow()) {
2104 nonDynamicFlows.add(config);
2107 configurationService.persistConfiguration(nonDynamicFlows, STATIC_FLOWS_FILE_NAME);
2108 configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(portGroupConfigs.values()),
2109 PORT_GROUP_FILE_NAME);
2111 return new Status(StatusCode.SUCCESS);
2115 public void subnetNotify(Subnet sub, boolean add) {
2118 private boolean programInternalFlow(boolean proactive, FlowConfig fc) {
2119 boolean retVal = true; // program flows unless determined otherwise
2121 // if the flow already exists do not program
2122 if(flowConfigExists(fc)) {
2126 // if the flow does not exist do not program
2127 if(!flowConfigExists(fc)) {
2137 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2140 * This method can be called from within the OSGi framework context,
2141 * given the programming operation can take sometime, it not good
2142 * pratice to have in it's context operations that can take time,
2143 * hence moving off to a different thread for async processing.
2145 private ExecutorService executor;
2147 public void modeChangeNotify(final Node node, final boolean proactive) {
2148 Callable<Status> modeChangeCallable = new Callable<Status>() {
2150 public Status call() throws Exception {
2151 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2153 List<String> puntAction = new ArrayList<String>();
2154 puntAction.add(ActionType.CONTROLLER.toString());
2156 FlowConfig allowARP = new FlowConfig();
2157 allowARP.setInstallInHw(true);
2158 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2159 allowARP.setPriority("1");
2160 allowARP.setNode(node);
2161 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2163 allowARP.setActions(puntAction);
2164 defaultConfigs.add(allowARP);
2166 FlowConfig allowLLDP = new FlowConfig();
2167 allowLLDP.setInstallInHw(true);
2168 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2169 allowLLDP.setPriority("1");
2170 allowLLDP.setNode(node);
2171 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2173 allowLLDP.setActions(puntAction);
2174 defaultConfigs.add(allowLLDP);
2176 List<String> dropAction = new ArrayList<String>();
2177 dropAction.add(ActionType.DROP.toString());
2179 FlowConfig dropAllConfig = new FlowConfig();
2180 dropAllConfig.setInstallInHw(true);
2181 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2182 + FlowConfig.INTERNALSTATICFLOWEND);
2183 dropAllConfig.setPriority("0");
2184 dropAllConfig.setNode(node);
2185 dropAllConfig.setActions(dropAction);
2186 defaultConfigs.add(dropAllConfig);
2188 log.trace("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2189 for (FlowConfig fc : defaultConfigs) {
2190 // check if the frm really needs to act on the notification.
2191 // this is to check against duplicate notifications
2192 if(programInternalFlow(proactive, fc)) {
2193 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2194 if (status.isSuccess()) {
2195 log.trace("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2197 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2201 log.debug("Got redundant install request for internal flow: {} on node: {}. Request not sent to FRM.", fc.getName(), node);
2204 return new Status(StatusCode.SUCCESS);
2209 * Execute the work outside the caller context, this could be an
2210 * expensive operation and we don't want to block the caller for it.
2212 this.executor.submit(modeChangeCallable);
2216 * Remove from the databases all the flows installed on the node
2220 private void cleanDatabaseForNode(Node node) {
2221 log.trace("Cleaning Flow database for Node {}", node);
2222 if (nodeFlows.containsKey(node)) {
2223 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2225 for (FlowEntryInstall entry : toRemove) {
2226 updateSwViews(entry, false);
2231 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2236 Match match = flow.getMatch();
2237 if (match.isPresent(MatchType.IN_PORT)) {
2238 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2239 if (matchPort.equals(nc)) {
2243 List<Action> actionsList = flow.getActions();
2244 if (actionsList != null) {
2245 for (Action action : actionsList) {
2246 if (action instanceof Output) {
2247 NodeConnector actionPort = ((Output) action).getPort();
2248 if (actionPort.equals(nc)) {
2258 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2259 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2263 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2264 boolean updateStaticFlowCluster = false;
2270 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2271 if (config != null) {
2272 switch (config.getValue()) {
2273 case Config.ADMIN_DOWN:
2274 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2275 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2277 case Config.ADMIN_UP:
2278 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2279 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2281 case Config.ADMIN_UNDEF:
2288 // This is the case where a switch port is removed from the SDN agent space
2289 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2290 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2296 if (updateStaticFlowCluster) {
2297 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2302 * It goes through the static flows configuration, it identifies the ones
2303 * which have the specified node connector as input or output port and
2304 * install them on the network node if they are marked to be installed in
2305 * hardware and their status shows they were not installed yet
2307 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2308 boolean updated = false;
2309 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2310 for (FlowConfig flowConfig : flowConfigForNode) {
2311 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2312 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) {
2313 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2314 if (!status.isSuccess()) {
2315 flowConfig.setStatus(status.getDescription());
2317 flowConfig.setStatus(StatusCode.SUCCESS.toString());
2327 * Remove from the network node all the flows which have the specified node
2328 * connector as input or output port. If any of the flow entry is a static
2329 * flow, it updates the correspondent configuration.
2331 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2332 boolean updated = false;
2333 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2334 if (nodeFlowEntries == null) {
2337 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2338 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2339 Status status = this.removeEntryInternal(fei, true);
2340 if (!status.isSuccess()) {
2344 * If the flow entry is a static flow, then update its
2347 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2348 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2349 if (flowConfig != null) {
2350 flowConfig.setStatus(PORT_REMOVED);
2359 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2360 FlowConfig derivedFlow = new FlowConfig(original);
2361 derivedFlow.setDynamic(true);
2362 derivedFlow.setPortGroup(null);
2363 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2364 derivedFlow.setIngressPort(port + "");
2368 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2369 for (FlowConfig staticFlow : staticFlows.values()) {
2370 if (staticFlow.getPortGroup() == null) {
2373 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2374 for (Short port : data.getPorts()) {
2375 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2376 addStaticFlowInternal(derivedFlow, false);
2382 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2383 for (FlowConfig staticFlow : staticFlows.values()) {
2384 if (staticFlow.getPortGroup() == null) {
2387 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2388 for (Short port : data.getPorts()) {
2389 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2390 removeStaticFlow(derivedFlow);
2397 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2398 log.trace("PortGroup Changed for: {} Data: {}", config, portGroupData);
2399 Map<Node, PortGroup> existingData = portGroupData.get(config);
2400 if (existingData != null) {
2401 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2402 PortGroup existingPortGroup = existingData.get(entry.getKey());
2403 if (existingPortGroup == null) {
2405 existingData.put(entry.getKey(), entry.getValue());
2406 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2410 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2411 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2413 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2414 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2420 portGroupData.put(config, data);
2421 for (Node swid : data.keySet()) {
2422 addPortGroupFlows(config, swid, data.get(swid));
2429 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2430 PortGroupConfig config = portGroupConfigs.get(name);
2431 if (config != null) {
2435 if ((portGroupProvider == null) && !restore) {
2438 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2442 config = new PortGroupConfig(name, regex);
2443 portGroupConfigs.put(name, config);
2444 if (portGroupProvider != null) {
2445 portGroupProvider.createPortGroupConfig(config);
2451 public boolean delPortGroupConfig(String name) {
2452 PortGroupConfig config = portGroupConfigs.get(name);
2453 if (config == null) {
2457 if (portGroupProvider != null) {
2458 portGroupProvider.deletePortGroupConfig(config);
2460 portGroupConfigs.remove(name);
2465 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2466 return portGroupConfigs;
2469 public boolean isPortGroupSupported() {
2470 if (portGroupProvider == null) {
2476 public void setIContainer(IContainer s) {
2480 public void unsetIContainer(IContainer s) {
2481 if (this.container == s) {
2482 this.container = null;
2486 public void setConfigurationContainerService(IConfigurationContainerService service) {
2487 log.trace("Got configuration service set request {}", service);
2488 this.configurationService = service;
2491 public void unsetConfigurationContainerService(IConfigurationContainerService service) {
2492 log.trace("Got configuration service UNset request");
2493 this.configurationService = null;
2497 public PortGroupProvider getPortGroupProvider() {
2498 return portGroupProvider;
2501 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2502 this.portGroupProvider = null;
2505 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2506 this.portGroupProvider = portGroupProvider;
2507 portGroupProvider.registerPortGroupChange(this);
2508 for (PortGroupConfig config : portGroupConfigs.values()) {
2509 portGroupProvider.createPortGroupConfig(config);
2513 public void setFrmAware(IForwardingRulesManagerAware obj) {
2514 this.frmAware.add(obj);
2517 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2518 this.frmAware.remove(obj);
2521 void setClusterContainerService(IClusterContainerServices s) {
2522 log.debug("Cluster Service set");
2523 this.clusterContainerService = s;
2526 void unsetClusterContainerService(IClusterContainerServices s) {
2527 if (this.clusterContainerService == s) {
2528 log.debug("Cluster Service removed!");
2529 this.clusterContainerService = null;
2533 private String getContainerName() {
2534 if (container == null) {
2535 return GlobalConstants.DEFAULT.toString();
2537 return container.getName();
2541 * Function called by the dependency manager when all the required
2542 * dependencies are satisfied
2547 inContainerMode = false;
2549 if (portGroupProvider != null) {
2550 portGroupProvider.registerPortGroupChange(this);
2553 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
2554 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
2559 * If we are not the first cluster node to come up, do not initialize
2560 * the static flow entries ordinal
2562 if (staticFlowsOrdinal.size() == 0) {
2563 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2566 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2568 // Initialize the event handler thread
2569 frmEventHandler = new Thread(new Runnable() {
2574 final FRMEvent event = pendingEvents.take();
2575 if (event == null) {
2576 log.warn("Dequeued null event");
2579 log.trace("Dequeued {} event", event.getClass().getSimpleName());
2580 if (event instanceof NodeUpdateEvent) {
2581 NodeUpdateEvent update = (NodeUpdateEvent) event;
2582 Node node = update.getNode();
2583 switch (update.getUpdateType()) {
2585 addStaticFlowsToSwitch(node);
2588 cleanDatabaseForNode(node);
2589 updateStaticFlowConfigsOnNodeDown(node);
2593 } else if (event instanceof ErrorReportedEvent) {
2594 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2595 processErrorEvent(errEvent);
2596 } else if (event instanceof WorkOrderEvent) {
2598 * Take care of handling the remote Work request
2600 Runnable r = new Runnable() {
2603 WorkOrderEvent work = (WorkOrderEvent) event;
2604 FlowEntryDistributionOrder fe = work.getFe();
2606 logsync.trace("Executing the workOrder {}", fe);
2607 Status gotStatus = null;
2608 FlowEntryInstall feiCurrent = fe.getEntry();
2609 FlowEntryInstall feiNew = workOrder.get(fe);
2610 switch (fe.getUpType()) {
2612 gotStatus = addEntryInHw(feiCurrent, false);
2615 gotStatus = modifyEntryInHw(feiCurrent, feiNew, false);
2618 gotStatus = removeEntryInHw(feiCurrent, false);
2622 workOrder.remove(fe);
2624 "The workOrder has been executed and now the status is being returned {}", fe);
2626 workStatus.put(fe, gotStatus);
2628 log.warn("Not expected null WorkOrder", work);
2632 if(executor != null) {
2633 executor.execute(r);
2635 } else if (event instanceof WorkStatusCleanup) {
2637 * Take care of handling the remote Work request
2639 WorkStatusCleanup work = (WorkStatusCleanup) event;
2640 FlowEntryDistributionOrder fe = work.getFe();
2642 logsync.trace("The workStatus {} is being removed", fe);
2643 workStatus.remove(fe);
2645 log.warn("Not expected null WorkStatus", work);
2647 } else if (event instanceof ContainerFlowChangeEvent) {
2649 * Whether it is an addition or removal, we have to
2650 * recompute the merged flows entries taking into
2651 * account all the current container flows because
2652 * flow merging is not an injective function
2654 updateFlowsContainerFlow();
2655 } else if (event instanceof UpdateIndexDBs) {
2656 UpdateIndexDBs update = (UpdateIndexDBs)event;
2657 updateIndexDatabase(update.getFei(), update.isAddition());
2659 log.warn("Dequeued unknown event {}", event.getClass().getSimpleName());
2661 } catch (InterruptedException e) {
2662 // clear pending events
2663 pendingEvents.clear();
2667 }, "FRM EventHandler Collector");
2671 * Function called by the dependency manager when at least one dependency
2672 * become unsatisfied or when the component is shutting down because for
2673 * example bundle is being stopped.
2677 // Interrupt the thread
2678 frmEventHandler.interrupt();
2679 // Clear the pendingEvents queue
2680 pendingEvents.clear();
2682 workMonitor.clear();
2686 * Function called by dependency manager after "init ()" is called and after
2687 * the services provided by the class are registered in the service registry
2692 * If running in default container, need to know if controller is in
2695 if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) {
2696 inContainerMode = containerManager.inContainerMode();
2699 // Initialize graceful stop flag
2702 // Allocate the executor service
2703 this.executor = Executors.newFixedThreadPool(maxPoolSize);
2705 // Start event handler thread
2706 frmEventHandler.start();
2708 // replay the installedSwView data structure to populate
2709 // node flows and group flows
2710 for (FlowEntryInstall fei : installedSwView.values()) {
2711 pendingEvents.offer(new UpdateIndexDBs(fei, true));
2715 * Read startup and build database if we are the coordinator
2717 loadFlowConfiguration();
2721 * Function called by the dependency manager before Container is Stopped and Destroyed.
2723 public void containerStop() {
2724 uninstallAllFlowEntries(false);
2728 * Function called by the dependency manager before the services exported by
2729 * the component are unregistered, this will be followed by a "destroy ()"
2734 // Shutdown executor
2735 this.executor.shutdownNow();
2736 // Now walk all the workMonitor and wake up the one sleeping because
2737 // destruction is happening
2738 for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2739 FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2744 public void setFlowProgrammerService(IFlowProgrammerService service) {
2745 this.programmer = service;
2748 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2749 if (this.programmer == service) {
2750 this.programmer = null;
2754 public void setSwitchManager(ISwitchManager switchManager) {
2755 this.switchManager = switchManager;
2758 public void unsetSwitchManager(ISwitchManager switchManager) {
2759 if (this.switchManager == switchManager) {
2760 this.switchManager = null;
2765 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2766 if (!container.getName().equals(containerName)) {
2772 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2773 if (!container.getName().equals(containerName)) {
2776 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2777 container.getName(), t, current);
2778 ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2779 pendingEvents.offer(ev);
2783 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2784 if (!container.getName().equals(containerName)) {
2788 boolean updateStaticFlowCluster = false;
2792 log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2793 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2796 log.trace("Port {} was added to container: reinstall interested flows", nc);
2797 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2805 if (updateStaticFlowCluster) {
2806 refreshClusterStaticFlowsStatus(nc.getNode());
2811 public void containerModeUpdated(UpdateType update) {
2812 // Only default container instance reacts on this event
2813 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2819 * Controller is moving to container mode. We are in the default
2820 * container context, we need to remove all our non-internal flows
2821 * to prevent any container isolation breakage. We also need to
2822 * preserve our flow so that they can be re-installed if we move
2823 * back to non container mode (no containers).
2825 this.inContainerMode = true;
2826 this.uninstallAllFlowEntries(true);
2829 this.inContainerMode = false;
2830 this.reinstallAllFlowEntries();
2836 // Update our configuration DB
2837 updateStaticFlowConfigsOnContainerModeChange(update);
2840 protected abstract class FRMEvent {
2844 private class NodeUpdateEvent extends FRMEvent {
2845 private final Node node;
2846 private final UpdateType update;
2848 public NodeUpdateEvent(UpdateType update, Node node) {
2849 this.update = update;
2853 public UpdateType getUpdateType() {
2857 public Node getNode() {
2862 private class ErrorReportedEvent extends FRMEvent {
2863 private final long rid;
2864 private final Node node;
2865 private final Object error;
2867 public ErrorReportedEvent(long rid, Node node, Object error) {
2873 public long getRequestId() {
2877 public Object getError() {
2881 public Node getNode() {
2886 private class WorkOrderEvent extends FRMEvent {
2887 private FlowEntryDistributionOrder fe;
2888 private FlowEntryInstall newEntry;
2894 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2896 this.newEntry = newEntry;
2902 public FlowEntryDistributionOrder getFe() {
2907 * @return the newEntry
2909 public FlowEntryInstall getNewEntry() {
2913 private class ContainerFlowChangeEvent extends FRMEvent {
2914 private final ContainerFlow previous;
2915 private final ContainerFlow current;
2916 private final UpdateType type;
2918 public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2919 this.previous = previous;
2920 this.current = current;
2924 public ContainerFlow getPrevious() {
2925 return this.previous;
2928 public ContainerFlow getCurrent() {
2929 return this.current;
2932 public UpdateType getType() {
2938 private class WorkStatusCleanup extends FRMEvent {
2939 private FlowEntryDistributionOrder fe;
2944 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2951 public FlowEntryDistributionOrder getFe() {
2956 private class UpdateIndexDBs extends FRMEvent {
2957 private FlowEntryInstall fei;
2958 private boolean add;
2962 * @param fei the flow entry which was installed/removed on the netwrok node
2965 UpdateIndexDBs(FlowEntryInstall fei, boolean add) {
2972 * @return the flowEntryInstall object which was added/removed
2973 * to/from the installed software view cache
2975 public FlowEntryInstall getFei() {
2981 * @return whether this was an flow addition or removal
2983 public boolean isAddition() {
2989 public Status saveConfiguration() {
2990 return saveConfig();
2994 public void flowRemoved(Node node, Flow flow) {
2995 log.trace("Received flow removed notification on {} for {}", node, flow);
2997 // For flow entry identification, only node, match and priority matter
2998 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2999 FlowEntryInstall installedEntry = this.installedSwView.get(test);
3000 if (installedEntry == null) {
3001 log.trace("Entry is not known to us");
3005 // Update Static flow status
3007 FlowConfig target = null;
3008 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3009 FlowConfig conf = entry.getValue();
3010 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3011 key = entry.getKey();
3016 if (target != null) {
3017 // Update Configuration database
3018 if (target.getHardTimeout() != null || target.getIdleTimeout() != null) {
3020 * No need for checking if actual values: these strings were
3021 * validated at configuration creation. Also, after a switch
3022 * down scenario, no use to reinstall a timed flow. Mark it as
3023 * "do not install". User can manually toggle it.
3025 target.toggleInstallation();
3027 target.setStatus(StatusCode.GONE.toString());
3028 staticFlows.put(key, target);
3031 // Update software views
3032 this.updateSwViews(installedEntry, false);
3036 public void flowErrorReported(Node node, long rid, Object err) {
3037 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3038 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3041 private void processErrorEvent(ErrorReportedEvent event) {
3042 Node node = event.getNode();
3043 long rid = event.getRequestId();
3044 Object error = event.getError();
3045 String errorString = (error == null) ? "Not provided" : error.toString();
3047 * If this was for a flow install, remove the corresponding entry from
3048 * the software view. If it was a Looking for the rid going through the
3049 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3050 * mapping will have to be added in future
3052 FlowEntryInstall target = null;
3053 List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3054 // flowEntryInstallList could be null.
3056 if(flowEntryInstallList != null) {
3057 for (FlowEntryInstall index : flowEntryInstallList) {
3058 FlowEntryInstall entry = installedSwView.get(index);
3060 if (entry.getRequestId() == rid) {
3067 if (target != null) {
3068 // This was a flow install, update database
3069 this.updateSwViews(target, false);
3070 // also update the config
3071 if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3072 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3073 // staticFlowEntry should never be null.
3074 // the null check is just an extra defensive check.
3075 if(staticFlowEntry != null) {
3076 // Modify status and update cluster cache
3077 log.debug("Updating static flow configuration on async error event");
3078 String status = String.format("Cannot be installed on node. reason: %s", errorString);
3079 staticFlowEntry.getValue().setStatus(status);
3080 refreshClusterStaticFlowsStatus(node);
3086 if (frmAware != null) {
3087 synchronized (frmAware) {
3088 for (IForwardingRulesManagerAware frma : frmAware) {
3090 frma.requestFailed(rid, errorString);
3091 } catch (Exception e) {
3092 log.warn("Failed to notify {}", frma);
3100 public Status solicitStatusResponse(Node node, boolean blocking) {
3101 Status rv = new Status(StatusCode.INTERNALERROR);
3103 if (this.programmer != null) {
3105 rv = programmer.syncSendBarrierMessage(node);
3107 rv = programmer.asyncSendBarrierMessage(node);
3114 public void unsetIConnectionManager(IConnectionManager s) {
3115 if (s == this.connectionManager) {
3116 this.connectionManager = null;
3120 public void setIConnectionManager(IConnectionManager s) {
3121 this.connectionManager = s;
3124 public void unsetIContainerManager(IContainerManager s) {
3125 if (s == this.containerManager) {
3126 this.containerManager = null;
3130 public void setIContainerManager(IContainerManager s) {
3131 this.containerManager = s;
3135 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3142 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3144 * Streamline the updates for the per node and per group index databases
3146 if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3147 pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)new_value, true));
3152 * Local updates are of no interest
3156 if (cacheName.equals(WORK_ORDER_CACHE)) {
3157 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3159 * This is the case of one workOrder becoming available, so we need
3160 * to dispatch the work to the appropriate handler
3162 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3163 FlowEntryInstall fei = fe.getEntry();
3167 Node n = fei.getNode();
3168 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3169 logsync.trace("workOrder for fe {} processed locally", fe);
3170 // I'm the controller in charge for the request, queue it for
3172 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3174 } else if (cacheName.equals(WORK_STATUS_CACHE)) {
3175 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3177 * This is the case of one workOrder being completed and a status
3180 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3182 * Check if the order was initiated by this controller in that case
3183 * we need to actually look at the status returned
3185 if (fe.getRequestorController()
3186 .equals(clusterContainerService.getMyAddress())) {
3187 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3189 logsync.trace("workStatus response is for us {}", fe);
3190 // Signal we got the status
3191 fet.gotStatus(fe, workStatus.get(fe));
3192 pendingEvents.offer(new WorkStatusCleanup(fe));
3199 public void entryDeleted(Object key, String cacheName, boolean originLocal) {
3201 * Streamline the updates for the per node and per group index databases
3203 if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3204 pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)key, false));
3212 public List<FlowEntry> getFlowEntriesForNode(Node node) {
3213 List<FlowEntry> list = new ArrayList<FlowEntry>();
3215 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
3216 if (node.equals(entry.getKey().getNode())) {
3217 list.add(entry.getValue().clone());
3228 public List<FlowEntry> getInstalledFlowEntriesForNode(Node node) {
3229 List<FlowEntry> list = new ArrayList<FlowEntry>();
3231 List<FlowEntryInstall> flowEntryInstallList = this.nodeFlows.get(node);
3232 if(flowEntryInstallList != null) {
3233 for(FlowEntryInstall fi: flowEntryInstallList) {
3234 list.add(fi.getInstall().clone());