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 // since this is the entry that was stored in groupFlows
1197 // it is already validated and merged
1198 // so can call removeEntryInternal directly
1199 Status status = this.removeEntryInternal(entry, false);
1200 if (status.isSuccess()) {
1203 error = status.getDescription();
1207 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1208 "Not all the flows were removed: " + error);
1212 public Status uninstallFlowEntryGroupAsync(String groupName) {
1213 if (groupName == null || groupName.isEmpty()) {
1214 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1216 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1217 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1219 if (inContainerMode) {
1220 String msg = "Controller in container mode: Group Uninstall Refused";
1221 String logMsg = msg + ": {}";
1222 log.warn(logMsg, groupName);
1223 return new Status(StatusCode.NOTACCEPTABLE, msg);
1225 if (groupFlows.containsKey(groupName)) {
1226 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1227 for (FlowEntryInstall entry : list) {
1228 this.removeEntry(entry.getOriginal(), true);
1231 return new Status(StatusCode.SUCCESS);
1235 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1236 return entryConflictsWithContainerFlows(flowEntry);
1240 * Updates all installed flows because the container flow got updated This
1241 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1242 * Reinstall of all flows This is needed because a new container flows
1243 * merged flow may conflict with an existing old container flows merged flow
1244 * on the network node
1246 protected void updateFlowsContainerFlow() {
1247 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1248 // First remove all installed entries
1249 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1250 FlowEntryInstall current = entry.getValue();
1251 // Store the original entry
1252 toReInstall.add(current.getOriginal());
1253 // Remove the old couples. No validity checks to be run, use the
1255 this.removeEntryInternal(current, false);
1257 // Then reinstall the original entries
1258 for (FlowEntry entry : toReInstall) {
1259 // Reinstall the original flow entries, via the regular path: new
1260 // cFlow merge + validations
1261 this.installFlowEntry(entry);
1265 private void nonClusterObjectCreate() {
1266 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1267 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1268 TSPolicies = new ConcurrentHashMap<String, Object>();
1269 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1270 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1271 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1272 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1273 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1277 public void setTSPolicyData(String policyname, Object o, boolean add) {
1280 /* Check if this policy already exists */
1281 if (!(TSPolicies.containsKey(policyname))) {
1282 TSPolicies.put(policyname, o);
1285 TSPolicies.remove(policyname);
1287 if (frmAware != null) {
1288 synchronized (frmAware) {
1289 for (IForwardingRulesManagerAware frma : frmAware) {
1291 frma.policyUpdate(policyname, add);
1292 } catch (Exception e) {
1293 log.warn("Exception on callback", e);
1301 public Map<String, Object> getTSPolicyData() {
1306 public Object getTSPolicyData(String policyName) {
1307 if (TSPolicies.containsKey(policyName)) {
1308 return TSPolicies.get(policyName);
1315 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1316 List<FlowEntry> list = new ArrayList<FlowEntry>();
1317 if (policyName != null && !policyName.trim().isEmpty()) {
1318 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1319 if (policyName.equals(entry.getKey().getGroupName())) {
1320 list.add(entry.getValue().clone());
1328 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1329 List<FlowEntry> list = new ArrayList<FlowEntry>();
1330 if (policyName != null && !policyName.trim().isEmpty()) {
1331 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1332 if (policyName.equals(entry.getKey().getGroupName())) {
1333 list.add(entry.getValue().getInstall().clone());
1341 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1343 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1344 if (flow.getFlowName().equals(flowName)) {
1345 FlowEntry currentFlowEntry = flow.getOriginal();
1346 FlowEntry newFlowEntry = currentFlowEntry.clone();
1347 for (NodeConnector dstPort : portList) {
1348 newFlowEntry.getFlow().addAction(new Output(dstPort));
1350 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1351 if (error.isSuccess()) {
1352 log.trace("Ports {} added to FlowEntry {}", portList, flowName);
1354 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1355 currentFlowEntry.toString(), error.getDescription());
1360 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1364 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1365 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1366 FlowEntryInstall flow = this.installedSwView.get(index);
1367 if (flow.getFlowName().equals(flowName)) {
1368 FlowEntry currentFlowEntry = flow.getOriginal();
1369 FlowEntry newFlowEntry = currentFlowEntry.clone();
1370 for (NodeConnector dstPort : portList) {
1371 Action action = new Output(dstPort);
1372 newFlowEntry.getFlow().removeAction(action);
1374 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1375 if (status.isSuccess()) {
1376 log.trace("Ports {} removed from FlowEntry {}", portList, flowName);
1378 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1379 currentFlowEntry.toString(), status.getDescription());
1384 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1388 * This function assumes the target flow has only one output port
1391 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1392 FlowEntry currentFlowEntry = null;
1393 FlowEntry newFlowEntry = null;
1396 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1397 FlowEntryInstall flow = this.installedSwView.get(index);
1398 if (flow.getFlowName().equals(flowName)) {
1399 currentFlowEntry = flow.getOriginal();
1403 if (currentFlowEntry == null) {
1404 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1408 // Create a flow copy with the new output port
1409 newFlowEntry = currentFlowEntry.clone();
1410 Action target = null;
1411 for (Action action : newFlowEntry.getFlow().getActions()) {
1412 if (action.getType() == ActionType.OUTPUT) {
1417 newFlowEntry.getFlow().removeAction(target);
1418 newFlowEntry.getFlow().addAction(new Output(outPort));
1420 // Modify on network node
1421 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1423 if (status.isSuccess()) {
1424 log.trace("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1426 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1427 status.getDescription());
1433 public NodeConnector getOutputPort(Node node, String flowName) {
1434 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1435 FlowEntryInstall flow = this.installedSwView.get(index);
1436 if (flow.getFlowName().equals(flowName)) {
1437 for (Action action : flow.getOriginal().getFlow().getActions()) {
1438 if (action.getType() == ActionType.OUTPUT) {
1439 return ((Output) action).getPort();
1447 private void cacheStartup() {
1452 private void allocateCaches() {
1453 if (this.clusterContainerService == null) {
1454 log.warn("Un-initialized clusterContainerService, can't create cache");
1458 log.debug("Allocating caches for Container {}", container.getName());
1461 clusterContainerService.createCache(ORIGINAL_SW_VIEW_CACHE,
1462 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1464 clusterContainerService.createCache(INSTALLED_SW_VIEW_CACHE,
1465 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1467 clusterContainerService.createCache("frm.inactiveFlows",
1468 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1470 clusterContainerService.createCache("frm.staticFlows",
1471 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1473 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1474 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1476 clusterContainerService.createCache("frm.portGroupConfigs",
1477 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1479 clusterContainerService.createCache("frm.portGroupData",
1480 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1482 clusterContainerService.createCache("frm.TSPolicies",
1483 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1485 clusterContainerService.createCache(WORK_STATUS_CACHE,
1486 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1488 clusterContainerService.createCache(WORK_ORDER_CACHE,
1489 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1491 } catch (CacheConfigException cce) {
1492 log.error("CacheConfigException");
1493 } catch (CacheExistException cce) {
1494 log.error("CacheExistException");
1498 @SuppressWarnings({ "unchecked" })
1499 private void retrieveCaches() {
1500 ConcurrentMap<?, ?> map;
1502 if (this.clusterContainerService == null) {
1503 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1504 nonClusterObjectCreate();
1508 log.debug("Retrieving Caches for Container {}", container.getName());
1510 map = clusterContainerService.getCache(ORIGINAL_SW_VIEW_CACHE);
1512 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1514 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1517 map = clusterContainerService.getCache(INSTALLED_SW_VIEW_CACHE);
1519 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1521 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1524 map = clusterContainerService.getCache("frm.inactiveFlows");
1526 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1528 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1531 map = clusterContainerService.getCache("frm.staticFlows");
1533 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1535 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1538 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1540 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1542 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1545 map = clusterContainerService.getCache("frm.portGroupConfigs");
1547 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1549 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1552 map = clusterContainerService.getCache("frm.portGroupData");
1554 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1556 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1559 map = clusterContainerService.getCache("frm.TSPolicies");
1561 TSPolicies = (ConcurrentMap<String, Object>) map;
1563 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1566 map = clusterContainerService.getCache(WORK_ORDER_CACHE);
1568 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1570 log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName());
1573 map = clusterContainerService.getCache(WORK_STATUS_CACHE);
1575 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1577 log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName());
1581 private boolean flowConfigExists(FlowConfig config) {
1582 // Flow name has to be unique on per node id basis
1583 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1584 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1592 public Status addStaticFlow(FlowConfig config) {
1593 return addStaticFlow(config, false);
1596 private Status addStaticFlow(FlowConfig config, boolean async) {
1597 // Configuration object validation
1598 Status status = config.validate();
1599 if (!status.isSuccess()) {
1600 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1601 String error = "Invalid Configuration (" + status.getDescription() + ")";
1602 config.setStatus(error);
1603 return new Status(StatusCode.BADREQUEST, error);
1605 return addStaticFlowInternal(config, async, false);
1610 public Status addStaticFlowAsync(FlowConfig config) {
1611 return addStaticFlow(config, true);
1615 * Private method to add a static flow configuration which does not run any
1616 * validation on the passed FlowConfig object. If restore is set to true,
1617 * configuration is stored in configuration database regardless the
1618 * installation on the network node was successful. This is useful at boot
1619 * when static flows are present in startup configuration and are read
1620 * before the switches connects.
1623 * The static flow configuration
1625 * if true, the configuration is stored regardless the
1626 * installation on the network node was successful
1627 * @return The status of this request
1629 private Status addStaticFlowInternal(FlowConfig config, boolean async, boolean restore) {
1630 boolean multipleFlowPush = false;
1633 config.setStatus(StatusCode.SUCCESS.toString());
1636 if (flowConfigExists(config)) {
1637 error = "Entry with this name on specified switch already exists";
1638 log.warn("Entry with this name on specified switch already exists: {}", config);
1639 config.setStatus(error);
1640 return new Status(StatusCode.CONFLICT, error);
1643 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1644 for (String portGroupName : portGroupConfigs.keySet()) {
1645 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1646 multipleFlowPush = true;
1650 if (!multipleFlowPush) {
1651 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1652 error = "Invalid Configuration (Invalid PortGroup Name)";
1653 config.setStatus(error);
1654 return new Status(StatusCode.BADREQUEST, error);
1659 * If requested program the entry in hardware first before updating the
1662 if (!multipleFlowPush) {
1664 if (config.installInHw()) {
1665 FlowEntry entry = config.getFlowEntry();
1666 status = async ? this.installFlowEntryAsync(entry) : this.installFlowEntry(entry);
1667 if (!status.isSuccess()) {
1668 config.setStatus(status.getDescription());
1677 * When the control reaches this point, either of the following
1678 * conditions is true 1. This is a single entry configuration (non
1679 * PortGroup) and the hardware installation is successful 2. This is a
1680 * multiple entry configuration (PortGroup) and hardware installation is
1681 * NOT done directly on this event. 3. The User prefers to retain the
1682 * configuration in Controller and skip hardware installation.
1684 * Hence it is safe to update the StaticFlow DB at this point.
1686 * Note : For the case of PortGrouping, it is essential to have this DB
1687 * populated before the PortGroupListeners can query for the DB
1688 * triggered using portGroupChanged event...
1690 Integer ordinal = staticFlowsOrdinal.get(0);
1691 staticFlowsOrdinal.put(0, ++ordinal);
1692 staticFlows.put(ordinal, config);
1694 if (multipleFlowPush) {
1695 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1696 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1697 if (existingData != null) {
1698 portGroupChanged(pgconfig, existingData, true);
1701 return new Status(StatusCode.SUCCESS);
1704 private void addStaticFlowsToSwitch(Node node) {
1705 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1706 FlowConfig config = entry.getValue();
1707 if (config.isPortGroupEnabled()) {
1710 if (config.getNode().equals(node)) {
1711 if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) {
1712 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1713 config.setStatus(status.getDescription());
1717 // Update cluster cache
1718 refreshClusterStaticFlowsStatus(node);
1721 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1722 log.trace("Updating Static Flow configs on node down: {}", node);
1724 List<Integer> toRemove = new ArrayList<Integer>();
1725 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1727 FlowConfig config = entry.getValue();
1729 if (config.isPortGroupEnabled()) {
1733 if (config.installInHw() && config.getNode().equals(node)) {
1734 if (config.isInternalFlow()) {
1735 // Take note of this controller generated static flow
1736 toRemove.add(entry.getKey());
1738 config.setStatus(NODE_DOWN);
1742 // Remove controller generated static flows for this node
1743 for (Integer index : toRemove) {
1744 staticFlows.remove(index);
1746 // Update cluster cache
1747 refreshClusterStaticFlowsStatus(node);
1751 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1752 log.trace("Updating Static Flow configs on container mode change: {}", update);
1754 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1755 FlowConfig config = entry.getValue();
1756 if (config.isPortGroupEnabled()) {
1759 if (config.installInHw() && !config.isInternalFlow()) {
1762 config.setStatus("Removed from node because in container mode");
1765 config.setStatus(StatusCode.SUCCESS.toString());
1772 // Update cluster cache
1773 refreshClusterStaticFlowsStatus(null);
1777 public Status removeStaticFlow(FlowConfig config) {
1778 return removeStaticFlow(config, false);
1782 public Status removeStaticFlowAsync(FlowConfig config) {
1783 return removeStaticFlow(config, true);
1786 private Status removeStaticFlow(FlowConfig config, boolean async) {
1788 * No config.isInternal() check as NB does not take this path and GUI
1789 * cannot issue a delete on an internal generated flow. We need this
1790 * path to be accessible when switch mode is changed from proactive to
1791 * reactive, so that we can remove the internal generated LLDP and ARP
1795 // Look for the target configuration entry
1797 FlowConfig target = null;
1798 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1799 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1800 key = entry.getKey();
1801 target = entry.getValue();
1805 if (target == null) {
1806 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1809 // Program the network node
1810 Status status = async ? this.uninstallFlowEntryAsync(config.getFlowEntry()) : this.uninstallFlowEntry(config
1813 // Update configuration database if programming was successful
1814 if (status.isSuccess()) {
1815 staticFlows.remove(key);
1822 public Status removeStaticFlow(String name, Node node) {
1823 return removeStaticFlow(name, node, false);
1827 public Status removeStaticFlowAsync(String name, Node node) {
1828 return removeStaticFlow(name, node, true);
1831 private Status removeStaticFlow(String name, Node node, boolean async) {
1832 // Look for the target configuration entry
1834 FlowConfig target = null;
1835 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1836 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1837 key = mapEntry.getKey();
1838 target = mapEntry.getValue();
1842 if (target == null) {
1843 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1846 // Validity check for api3 entry point
1847 if (target.isInternalFlow()) {
1848 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1849 String logMsg = msg + ": {}";
1850 log.warn(logMsg, name);
1851 return new Status(StatusCode.NOTACCEPTABLE, msg);
1854 if (target.isPortGroupEnabled()) {
1855 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1856 String logMsg = msg + ": {}";
1857 log.warn(logMsg, name);
1858 return new Status(StatusCode.NOTACCEPTABLE, msg);
1861 // Program the network node
1862 Status status = this.removeEntry(target.getFlowEntry(), async);
1864 // Update configuration database if programming was successful
1865 if (status.isSuccess()) {
1866 staticFlows.remove(key);
1873 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1874 // Validity check for api3 entry point
1875 if (newFlowConfig.isInternalFlow()) {
1876 String msg = "Invalid operation: Controller generated flow cannot be modified";
1877 String logMsg = msg + ": {}";
1878 log.warn(logMsg, newFlowConfig);
1879 return new Status(StatusCode.NOTACCEPTABLE, msg);
1883 Status status = newFlowConfig.validate();
1884 if (!status.isSuccess()) {
1885 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1886 newFlowConfig.setStatus(msg);
1887 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1888 return new Status(StatusCode.BADREQUEST, msg);
1891 FlowConfig oldFlowConfig = null;
1892 Integer index = null;
1893 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1894 FlowConfig entry = mapEntry.getValue();
1895 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1896 oldFlowConfig = entry;
1897 index = mapEntry.getKey();
1902 if (oldFlowConfig == null) {
1903 String msg = "Attempt to modify a non existing static flow";
1904 String logMsg = msg + ": {}";
1905 log.warn(logMsg, newFlowConfig);
1906 return new Status(StatusCode.NOTFOUND, msg);
1909 // Do not attempt to reinstall the flow, warn user
1910 if (newFlowConfig.equals(oldFlowConfig)) {
1911 String msg = "No modification detected";
1912 log.trace("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1913 return new Status(StatusCode.SUCCESS, msg);
1916 // If flow is installed, program the network node
1917 status = new Status(StatusCode.SUCCESS, "Saved in config");
1918 if (oldFlowConfig.installInHw()) {
1919 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1922 // Update configuration database if programming was successful
1923 if (status.isSuccess()) {
1924 newFlowConfig.setStatus(status.getDescription());
1925 staticFlows.put(index, newFlowConfig);
1932 public Status toggleStaticFlowStatus(String name, Node node) {
1933 return toggleStaticFlowStatus(getStaticFlow(name, node));
1937 public Status toggleStaticFlowStatus(FlowConfig config) {
1938 if (config == null) {
1939 String msg = "Invalid request: null flow config";
1941 return new Status(StatusCode.BADREQUEST, msg);
1943 // Validity check for api3 entry point
1944 if (config.isInternalFlow()) {
1945 String msg = "Invalid operation: Controller generated flow cannot be modified";
1946 String logMsg = msg + ": {}";
1947 log.warn(logMsg, config);
1948 return new Status(StatusCode.NOTACCEPTABLE, msg);
1951 // Find the config entry
1953 FlowConfig target = null;
1954 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1955 FlowConfig conf = entry.getValue();
1956 if (conf.isByNameAndNodeIdEqual(config)) {
1957 key = entry.getKey();
1962 if (target != null) {
1963 Status status = target.validate();
1964 if (!status.isSuccess()) {
1965 log.warn(status.getDescription());
1968 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1969 .installFlowEntry(target.getFlowEntry());
1970 if (status.isSuccess()) {
1971 // Update Configuration database
1972 target.setStatus(StatusCode.SUCCESS.toString());
1973 target.toggleInstallation();
1974 staticFlows.put(key, target);
1979 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1983 * Reinsert all static flows entries in the cache to force cache updates in
1984 * the cluster. This is useful when only some parameters were changed in the
1985 * entries, like the status.
1988 * The node for which the static flow configurations have to be
1989 * refreshed. If null, all nodes static flows will be refreshed.
1991 private void refreshClusterStaticFlowsStatus(Node node) {
1992 // Refresh cluster cache
1993 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1994 if (node == null || entry.getValue().getNode().equals(node)) {
1995 staticFlows.put(entry.getKey(), entry.getValue());
2001 * Uninstall all the non-internal Flow Entries present in the software view.
2002 * If requested, a copy of each original flow entry will be stored in the
2003 * inactive list so that it can be re-applied when needed (This is typically
2004 * the case when running in the default container and controller moved to
2005 * container mode) NOTE WELL: The routine as long as does a bulk change will
2006 * operate only on the entries for nodes locally attached so to avoid
2007 * redundant operations initiated by multiple nodes
2009 * @param preserveFlowEntries
2010 * if true, a copy of each original entry is stored in the
2013 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
2014 log.trace("Uninstalling all non-internal flows");
2016 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
2018 // Store entries / create target list
2019 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
2020 FlowEntryInstall flowEntries = mapEntry.getValue();
2021 // Skip internal generated static flows
2022 if (!flowEntries.isInternal()) {
2023 toRemove.add(flowEntries);
2024 // Store the original entries if requested
2025 if (preserveFlowEntries) {
2026 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
2031 // Now remove the entries
2032 for (FlowEntryInstall flowEntryHw : toRemove) {
2033 Node n = flowEntryHw.getNode();
2034 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
2035 Status status = this.removeEntryInternal(flowEntryHw, false);
2036 if (!status.isSuccess()) {
2037 log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
2040 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
2047 * Re-install all the Flow Entries present in the inactive list The inactive
2048 * list will be empty at the end of this call This function is called on the
2049 * default container instance of FRM only when the last container is deleted
2051 private void reinstallAllFlowEntries() {
2052 log.trace("Reinstalling all inactive flows");
2054 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
2055 this.addEntry(flowEntry, false);
2058 // Empty inactive list in any case
2059 inactiveFlows.clear();
2063 public List<FlowConfig> getStaticFlows() {
2064 return new ArrayList<FlowConfig>(staticFlows.values());
2068 public FlowConfig getStaticFlow(String name, Node node) {
2069 ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
2071 return entry.getValue();
2077 public List<FlowConfig> getStaticFlows(Node node) {
2078 List<FlowConfig> list = new ArrayList<FlowConfig>();
2079 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2080 if (entry.getValue().onNode(node)) {
2081 list.add(entry.getValue());
2088 public List<String> getStaticFlowNamesForNode(Node node) {
2089 List<String> list = new ArrayList<String>();
2090 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2091 if (entry.getValue().onNode(node)) {
2092 list.add(entry.getValue().getName());
2099 public List<Node> getListNodeWithConfiguredFlows() {
2100 Set<Node> set = new HashSet<Node>();
2101 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2102 set.add(entry.getValue().getNode());
2104 return new ArrayList<Node>(set);
2107 private void loadFlowConfiguration() {
2108 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, PORT_GROUP_FILE_NAME)) {
2109 addPortGroupConfig(((PortGroupConfig) conf).getName(), ((PortGroupConfig) conf).getMatchString(), true);
2112 for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, STATIC_FLOWS_FILE_NAME)) {
2113 addStaticFlowInternal((FlowConfig) conf, false, true);
2118 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2119 return ois.readObject();
2123 public Status saveConfig() {
2124 return saveConfigInternal();
2127 private Status saveConfigInternal() {
2128 List<ConfigurationObject> nonDynamicFlows = new ArrayList<ConfigurationObject>();
2130 for (Integer ordinal : staticFlows.keySet()) {
2131 FlowConfig config = staticFlows.get(ordinal);
2132 // Do not save dynamic and controller generated static flows
2133 if (config.isDynamic() || config.isInternalFlow()) {
2136 nonDynamicFlows.add(config);
2139 configurationService.persistConfiguration(nonDynamicFlows, STATIC_FLOWS_FILE_NAME);
2140 configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(portGroupConfigs.values()),
2141 PORT_GROUP_FILE_NAME);
2143 return new Status(StatusCode.SUCCESS);
2147 public void subnetNotify(Subnet sub, boolean add) {
2150 private boolean programInternalFlow(boolean proactive, FlowConfig fc) {
2151 boolean retVal = true; // program flows unless determined otherwise
2153 // if the flow already exists do not program
2154 if(flowConfigExists(fc)) {
2158 // if the flow does not exist do not program
2159 if(!flowConfigExists(fc)) {
2169 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2172 * This method can be called from within the OSGi framework context,
2173 * given the programming operation can take sometime, it not good
2174 * pratice to have in it's context operations that can take time,
2175 * hence moving off to a different thread for async processing.
2177 private ExecutorService executor;
2179 public void modeChangeNotify(final Node node, final boolean proactive) {
2180 Callable<Status> modeChangeCallable = new Callable<Status>() {
2182 public Status call() throws Exception {
2183 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2185 List<String> puntAction = new ArrayList<String>();
2186 puntAction.add(ActionType.CONTROLLER.toString());
2188 FlowConfig allowARP = new FlowConfig();
2189 allowARP.setInstallInHw(true);
2190 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2191 allowARP.setPriority("1");
2192 allowARP.setNode(node);
2193 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2195 allowARP.setActions(puntAction);
2196 defaultConfigs.add(allowARP);
2198 FlowConfig allowLLDP = new FlowConfig();
2199 allowLLDP.setInstallInHw(true);
2200 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2201 allowLLDP.setPriority("1");
2202 allowLLDP.setNode(node);
2203 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2205 allowLLDP.setActions(puntAction);
2206 defaultConfigs.add(allowLLDP);
2208 List<String> dropAction = new ArrayList<String>();
2209 dropAction.add(ActionType.DROP.toString());
2211 FlowConfig dropAllConfig = new FlowConfig();
2212 dropAllConfig.setInstallInHw(true);
2213 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2214 + FlowConfig.INTERNALSTATICFLOWEND);
2215 dropAllConfig.setPriority("0");
2216 dropAllConfig.setNode(node);
2217 dropAllConfig.setActions(dropAction);
2218 defaultConfigs.add(dropAllConfig);
2220 log.trace("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2221 for (FlowConfig fc : defaultConfigs) {
2222 // check if the frm really needs to act on the notification.
2223 // this is to check against duplicate notifications
2224 if(programInternalFlow(proactive, fc)) {
2225 Status status = (proactive) ? addStaticFlowInternal(fc, false, false) : removeStaticFlow(fc);
2226 if (status.isSuccess()) {
2227 log.trace("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2229 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2233 log.debug("Got redundant install request for internal flow: {} on node: {}. Request not sent to FRM.", fc.getName(), node);
2236 return new Status(StatusCode.SUCCESS);
2241 * Execute the work outside the caller context, this could be an
2242 * expensive operation and we don't want to block the caller for it.
2244 this.executor.submit(modeChangeCallable);
2248 * Remove from the databases all the flows installed on the node
2252 private void cleanDatabaseForNode(Node node) {
2253 log.trace("Cleaning Flow database for Node {}", node);
2254 if (nodeFlows.containsKey(node)) {
2255 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2257 for (FlowEntryInstall entry : toRemove) {
2258 updateSwViews(entry, false);
2263 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2268 Match match = flow.getMatch();
2269 if (match.isPresent(MatchType.IN_PORT)) {
2270 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2271 if (matchPort.equals(nc)) {
2275 List<Action> actionsList = flow.getActions();
2276 if (actionsList != null) {
2277 for (Action action : actionsList) {
2278 if (action instanceof Output) {
2279 NodeConnector actionPort = ((Output) action).getPort();
2280 if (actionPort.equals(nc)) {
2290 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2291 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2295 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2296 boolean updateStaticFlowCluster = false;
2302 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2303 if (config != null) {
2304 switch (config.getValue()) {
2305 case Config.ADMIN_DOWN:
2306 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2307 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2309 case Config.ADMIN_UP:
2310 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2311 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2313 case Config.ADMIN_UNDEF:
2320 // This is the case where a switch port is removed from the SDN agent space
2321 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2322 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2328 if (updateStaticFlowCluster) {
2329 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2334 * It goes through the static flows configuration, it identifies the ones
2335 * which have the specified node connector as input or output port and
2336 * install them on the network node if they are marked to be installed in
2337 * hardware and their status shows they were not installed yet
2339 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2340 boolean updated = false;
2341 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2342 for (FlowConfig flowConfig : flowConfigForNode) {
2343 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2344 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) {
2345 Status status = this.installFlowEntryAsync(flowConfig.getFlowEntry());
2346 if (!status.isSuccess()) {
2347 flowConfig.setStatus(status.getDescription());
2349 flowConfig.setStatus(StatusCode.SUCCESS.toString());
2359 * Remove from the network node all the flows which have the specified node
2360 * connector as input or output port. If any of the flow entry is a static
2361 * flow, it updates the correspondent configuration.
2363 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2364 boolean updated = false;
2365 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2366 if (nodeFlowEntries == null) {
2369 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2370 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2371 Status status = this.removeEntryInternal(fei, true);
2372 if (!status.isSuccess()) {
2376 * If the flow entry is a static flow, then update its
2379 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2380 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2381 if (flowConfig != null) {
2382 flowConfig.setStatus(PORT_REMOVED);
2391 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2392 FlowConfig derivedFlow = new FlowConfig(original);
2393 derivedFlow.setDynamic(true);
2394 derivedFlow.setPortGroup(null);
2395 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2396 derivedFlow.setIngressPort(port + "");
2400 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2401 for (FlowConfig staticFlow : staticFlows.values()) {
2402 if (staticFlow.getPortGroup() == null) {
2405 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2406 for (Short port : data.getPorts()) {
2407 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2408 addStaticFlowInternal(derivedFlow, false, false);
2414 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2415 for (FlowConfig staticFlow : staticFlows.values()) {
2416 if (staticFlow.getPortGroup() == null) {
2419 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2420 for (Short port : data.getPorts()) {
2421 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2422 removeStaticFlow(derivedFlow);
2429 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2430 log.trace("PortGroup Changed for: {} Data: {}", config, portGroupData);
2431 Map<Node, PortGroup> existingData = portGroupData.get(config);
2432 if (existingData != null) {
2433 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2434 PortGroup existingPortGroup = existingData.get(entry.getKey());
2435 if (existingPortGroup == null) {
2437 existingData.put(entry.getKey(), entry.getValue());
2438 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2442 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2443 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2445 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2446 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2452 portGroupData.put(config, data);
2453 for (Node swid : data.keySet()) {
2454 addPortGroupFlows(config, swid, data.get(swid));
2461 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2462 PortGroupConfig config = portGroupConfigs.get(name);
2463 if (config != null) {
2467 if ((portGroupProvider == null) && !restore) {
2470 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2474 config = new PortGroupConfig(name, regex);
2475 portGroupConfigs.put(name, config);
2476 if (portGroupProvider != null) {
2477 portGroupProvider.createPortGroupConfig(config);
2483 public boolean delPortGroupConfig(String name) {
2484 PortGroupConfig config = portGroupConfigs.get(name);
2485 if (config == null) {
2489 if (portGroupProvider != null) {
2490 portGroupProvider.deletePortGroupConfig(config);
2492 portGroupConfigs.remove(name);
2497 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2498 return portGroupConfigs;
2501 public boolean isPortGroupSupported() {
2502 if (portGroupProvider == null) {
2508 public void setIContainer(IContainer s) {
2512 public void unsetIContainer(IContainer s) {
2513 if (this.container == s) {
2514 this.container = null;
2518 public void setConfigurationContainerService(IConfigurationContainerService service) {
2519 log.trace("Got configuration service set request {}", service);
2520 this.configurationService = service;
2523 public void unsetConfigurationContainerService(IConfigurationContainerService service) {
2524 log.trace("Got configuration service UNset request");
2525 this.configurationService = null;
2529 public PortGroupProvider getPortGroupProvider() {
2530 return portGroupProvider;
2533 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2534 this.portGroupProvider = null;
2537 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2538 this.portGroupProvider = portGroupProvider;
2539 portGroupProvider.registerPortGroupChange(this);
2540 for (PortGroupConfig config : portGroupConfigs.values()) {
2541 portGroupProvider.createPortGroupConfig(config);
2545 public void setFrmAware(IForwardingRulesManagerAware obj) {
2546 this.frmAware.add(obj);
2549 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2550 this.frmAware.remove(obj);
2553 void setClusterContainerService(IClusterContainerServices s) {
2554 log.debug("Cluster Service set");
2555 this.clusterContainerService = s;
2558 void unsetClusterContainerService(IClusterContainerServices s) {
2559 if (this.clusterContainerService == s) {
2560 log.debug("Cluster Service removed!");
2561 this.clusterContainerService = null;
2565 private String getContainerName() {
2566 if (container == null) {
2567 return GlobalConstants.DEFAULT.toString();
2569 return container.getName();
2573 * Function called by the dependency manager when all the required
2574 * dependencies are satisfied
2579 inContainerMode = false;
2581 if (portGroupProvider != null) {
2582 portGroupProvider.registerPortGroupChange(this);
2585 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
2586 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
2591 * If we are not the first cluster node to come up, do not initialize
2592 * the static flow entries ordinal
2594 if (staticFlowsOrdinal.size() == 0) {
2595 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2598 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2600 // Initialize the event handler thread
2601 frmEventHandler = new Thread(new Runnable() {
2606 final FRMEvent event = pendingEvents.take();
2607 if (event == null) {
2608 log.warn("Dequeued null event");
2611 log.trace("Dequeued {} event", event.getClass().getSimpleName());
2612 if (event instanceof NodeUpdateEvent) {
2613 NodeUpdateEvent update = (NodeUpdateEvent) event;
2614 Node node = update.getNode();
2615 switch (update.getUpdateType()) {
2617 addStaticFlowsToSwitch(node);
2620 cleanDatabaseForNode(node);
2621 updateStaticFlowConfigsOnNodeDown(node);
2625 } else if (event instanceof ErrorReportedEvent) {
2626 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2627 processErrorEvent(errEvent);
2628 } else if (event instanceof WorkOrderEvent) {
2630 * Take care of handling the remote Work request
2632 Runnable r = new Runnable() {
2635 WorkOrderEvent work = (WorkOrderEvent) event;
2636 FlowEntryDistributionOrder fe = work.getFe();
2638 logsync.trace("Executing the workOrder {}", fe);
2639 Status gotStatus = null;
2640 FlowEntryInstall feiCurrent = fe.getEntry();
2641 FlowEntryInstall feiNew = workOrder.get(fe);
2642 switch (fe.getUpType()) {
2644 gotStatus = addEntryInHw(feiCurrent, false);
2647 gotStatus = modifyEntryInHw(feiCurrent, feiNew, false);
2650 gotStatus = removeEntryInHw(feiCurrent, false);
2654 workOrder.remove(fe);
2656 "The workOrder has been executed and now the status is being returned {}", fe);
2658 workStatus.put(fe, gotStatus);
2660 log.warn("Not expected null WorkOrder", work);
2664 if(executor != null) {
2665 executor.execute(r);
2667 } else if (event instanceof WorkStatusCleanup) {
2669 * Take care of handling the remote Work request
2671 WorkStatusCleanup work = (WorkStatusCleanup) event;
2672 FlowEntryDistributionOrder fe = work.getFe();
2674 logsync.trace("The workStatus {} is being removed", fe);
2675 workStatus.remove(fe);
2677 log.warn("Not expected null WorkStatus", work);
2679 } else if (event instanceof ContainerFlowChangeEvent) {
2681 * Whether it is an addition or removal, we have to
2682 * recompute the merged flows entries taking into
2683 * account all the current container flows because
2684 * flow merging is not an injective function
2686 updateFlowsContainerFlow();
2687 } else if (event instanceof UpdateIndexDBs) {
2688 UpdateIndexDBs update = (UpdateIndexDBs)event;
2689 updateIndexDatabase(update.getFei(), update.isAddition());
2691 log.warn("Dequeued unknown event {}", event.getClass().getSimpleName());
2693 } catch (InterruptedException e) {
2694 // clear pending events
2695 pendingEvents.clear();
2699 }, "FRM EventHandler Collector");
2703 * Function called by the dependency manager when at least one dependency
2704 * become unsatisfied or when the component is shutting down because for
2705 * example bundle is being stopped.
2709 // Interrupt the thread
2710 frmEventHandler.interrupt();
2711 // Clear the pendingEvents queue
2712 pendingEvents.clear();
2714 workMonitor.clear();
2718 * Function called by dependency manager after "init ()" is called and after
2719 * the services provided by the class are registered in the service registry
2724 * If running in default container, need to know if controller is in
2727 if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) {
2728 inContainerMode = containerManager.inContainerMode();
2731 // Initialize graceful stop flag
2734 // Allocate the executor service
2735 this.executor = Executors.newFixedThreadPool(maxPoolSize);
2737 // Start event handler thread
2738 frmEventHandler.start();
2740 // replay the installedSwView data structure to populate
2741 // node flows and group flows
2742 for (FlowEntryInstall fei : installedSwView.values()) {
2743 pendingEvents.offer(new UpdateIndexDBs(fei, true));
2747 * Read startup and build database if we are the coordinator
2749 loadFlowConfiguration();
2753 * Function called by the dependency manager before Container is Stopped and Destroyed.
2755 public void containerStop() {
2756 uninstallAllFlowEntries(false);
2760 * Function called by the dependency manager before the services exported by
2761 * the component are unregistered, this will be followed by a "destroy ()"
2766 // Shutdown executor
2767 this.executor.shutdownNow();
2768 // Now walk all the workMonitor and wake up the one sleeping because
2769 // destruction is happening
2770 for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2771 FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2776 public void setFlowProgrammerService(IFlowProgrammerService service) {
2777 this.programmer = service;
2780 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2781 if (this.programmer == service) {
2782 this.programmer = null;
2786 public void setSwitchManager(ISwitchManager switchManager) {
2787 this.switchManager = switchManager;
2790 public void unsetSwitchManager(ISwitchManager switchManager) {
2791 if (this.switchManager == switchManager) {
2792 this.switchManager = null;
2797 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2798 if (!container.getName().equals(containerName)) {
2804 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2805 if (!container.getName().equals(containerName)) {
2808 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2809 container.getName(), t, current);
2810 ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2811 pendingEvents.offer(ev);
2815 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2816 if (!container.getName().equals(containerName)) {
2820 boolean updateStaticFlowCluster = false;
2824 log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2825 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2828 log.trace("Port {} was added to container: reinstall interested flows", nc);
2829 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2837 if (updateStaticFlowCluster) {
2838 refreshClusterStaticFlowsStatus(nc.getNode());
2843 public void containerModeUpdated(UpdateType update) {
2844 // Only default container instance reacts on this event
2845 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2851 * Controller is moving to container mode. We are in the default
2852 * container context, we need to remove all our non-internal flows
2853 * to prevent any container isolation breakage. We also need to
2854 * preserve our flow so that they can be re-installed if we move
2855 * back to non container mode (no containers).
2857 this.inContainerMode = true;
2858 this.uninstallAllFlowEntries(true);
2861 this.inContainerMode = false;
2862 this.reinstallAllFlowEntries();
2868 // Update our configuration DB
2869 updateStaticFlowConfigsOnContainerModeChange(update);
2872 protected abstract class FRMEvent {
2876 private class NodeUpdateEvent extends FRMEvent {
2877 private final Node node;
2878 private final UpdateType update;
2880 public NodeUpdateEvent(UpdateType update, Node node) {
2881 this.update = update;
2885 public UpdateType getUpdateType() {
2889 public Node getNode() {
2894 private class ErrorReportedEvent extends FRMEvent {
2895 private final long rid;
2896 private final Node node;
2897 private final Object error;
2899 public ErrorReportedEvent(long rid, Node node, Object error) {
2905 public long getRequestId() {
2909 public Object getError() {
2913 public Node getNode() {
2918 private class WorkOrderEvent extends FRMEvent {
2919 private FlowEntryDistributionOrder fe;
2920 private FlowEntryInstall newEntry;
2926 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2928 this.newEntry = newEntry;
2934 public FlowEntryDistributionOrder getFe() {
2939 * @return the newEntry
2941 public FlowEntryInstall getNewEntry() {
2945 private class ContainerFlowChangeEvent extends FRMEvent {
2946 private final ContainerFlow previous;
2947 private final ContainerFlow current;
2948 private final UpdateType type;
2950 public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2951 this.previous = previous;
2952 this.current = current;
2956 public ContainerFlow getPrevious() {
2957 return this.previous;
2960 public ContainerFlow getCurrent() {
2961 return this.current;
2964 public UpdateType getType() {
2970 private class WorkStatusCleanup extends FRMEvent {
2971 private FlowEntryDistributionOrder fe;
2976 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2983 public FlowEntryDistributionOrder getFe() {
2988 private class UpdateIndexDBs extends FRMEvent {
2989 private FlowEntryInstall fei;
2990 private boolean add;
2994 * @param fei the flow entry which was installed/removed on the netwrok node
2997 UpdateIndexDBs(FlowEntryInstall fei, boolean add) {
3004 * @return the flowEntryInstall object which was added/removed
3005 * to/from the installed software view cache
3007 public FlowEntryInstall getFei() {
3013 * @return whether this was an flow addition or removal
3015 public boolean isAddition() {
3021 public Status saveConfiguration() {
3022 return saveConfig();
3026 public void flowRemoved(Node node, Flow flow) {
3027 log.trace("Received flow removed notification on {} for {}", node, flow);
3029 // For flow entry identification, only node, match and priority matter
3030 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
3031 FlowEntryInstall installedEntry = this.installedSwView.get(test);
3032 if (installedEntry == null) {
3033 log.trace("Entry is not known to us");
3037 // Update Static flow status
3039 FlowConfig target = null;
3040 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3041 FlowConfig conf = entry.getValue();
3042 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3043 key = entry.getKey();
3048 if (target != null) {
3049 // Update Configuration database
3050 if (target.getHardTimeout() != null || target.getIdleTimeout() != null) {
3052 * No need for checking if actual values: these strings were
3053 * validated at configuration creation. Also, after a switch
3054 * down scenario, no use to reinstall a timed flow. Mark it as
3055 * "do not install". User can manually toggle it.
3057 target.toggleInstallation();
3059 target.setStatus(StatusCode.GONE.toString());
3060 staticFlows.put(key, target);
3063 // Update software views
3064 this.updateSwViews(installedEntry, false);
3068 public void flowErrorReported(Node node, long rid, Object err) {
3069 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3070 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3073 private void processErrorEvent(ErrorReportedEvent event) {
3074 Node node = event.getNode();
3075 long rid = event.getRequestId();
3076 Object error = event.getError();
3077 String errorString = (error == null) ? "Not provided" : error.toString();
3079 * If this was for a flow install, remove the corresponding entry from
3080 * the software view. If it was a Looking for the rid going through the
3081 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3082 * mapping will have to be added in future
3084 FlowEntryInstall target = null;
3085 List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3086 // flowEntryInstallList could be null.
3088 if(flowEntryInstallList != null) {
3089 for (FlowEntryInstall index : flowEntryInstallList) {
3090 FlowEntryInstall entry = installedSwView.get(index);
3092 if (entry.getRequestId() == rid) {
3099 if (target != null) {
3100 // This was a flow install, update database
3101 this.updateSwViews(target, false);
3102 // also update the config
3103 if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3104 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3105 // staticFlowEntry should never be null.
3106 // the null check is just an extra defensive check.
3107 if(staticFlowEntry != null) {
3108 // Modify status and update cluster cache
3109 log.debug("Updating static flow configuration on async error event");
3110 String status = String.format("Cannot be installed on node. reason: %s", errorString);
3111 staticFlowEntry.getValue().setStatus(status);
3112 refreshClusterStaticFlowsStatus(node);
3118 if (frmAware != null) {
3119 synchronized (frmAware) {
3120 for (IForwardingRulesManagerAware frma : frmAware) {
3122 frma.requestFailed(rid, errorString);
3123 } catch (Exception e) {
3124 log.warn("Failed to notify {}", frma);
3132 public Status solicitStatusResponse(Node node, boolean blocking) {
3133 Status rv = new Status(StatusCode.INTERNALERROR);
3135 if (this.programmer != null) {
3137 rv = programmer.syncSendBarrierMessage(node);
3139 rv = programmer.asyncSendBarrierMessage(node);
3146 public void unsetIConnectionManager(IConnectionManager s) {
3147 if (s == this.connectionManager) {
3148 this.connectionManager = null;
3152 public void setIConnectionManager(IConnectionManager s) {
3153 this.connectionManager = s;
3156 public void unsetIContainerManager(IContainerManager s) {
3157 if (s == this.containerManager) {
3158 this.containerManager = null;
3162 public void setIContainerManager(IContainerManager s) {
3163 this.containerManager = s;
3167 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3174 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3176 * Streamline the updates for the per node and per group index databases
3178 if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3179 pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)new_value, true));
3184 * Local updates are of no interest
3188 if (cacheName.equals(WORK_ORDER_CACHE)) {
3189 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3191 * This is the case of one workOrder becoming available, so we need
3192 * to dispatch the work to the appropriate handler
3194 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3195 FlowEntryInstall fei = fe.getEntry();
3199 Node n = fei.getNode();
3200 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3201 logsync.trace("workOrder for fe {} processed locally", fe);
3202 // I'm the controller in charge for the request, queue it for
3204 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3206 } else if (cacheName.equals(WORK_STATUS_CACHE)) {
3207 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3209 * This is the case of one workOrder being completed and a status
3212 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3214 * Check if the order was initiated by this controller in that case
3215 * we need to actually look at the status returned
3217 if (fe.getRequestorController()
3218 .equals(clusterContainerService.getMyAddress())) {
3219 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3221 logsync.trace("workStatus response is for us {}", fe);
3222 // Signal we got the status
3223 fet.gotStatus(fe, workStatus.get(fe));
3224 pendingEvents.offer(new WorkStatusCleanup(fe));
3231 public void entryDeleted(Object key, String cacheName, boolean originLocal) {
3233 * Streamline the updates for the per node and per group index databases
3235 if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) {
3236 pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)key, false));
3244 public List<FlowEntry> getFlowEntriesForNode(Node node) {
3245 List<FlowEntry> list = new ArrayList<FlowEntry>();
3247 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
3248 if (node.equals(entry.getKey().getNode())) {
3249 list.add(entry.getValue().clone());
3260 public List<FlowEntry> getInstalledFlowEntriesForNode(Node node) {
3261 List<FlowEntry> list = new ArrayList<FlowEntry>();
3263 List<FlowEntryInstall> flowEntryInstallList = this.nodeFlows.get(node);
3264 if(flowEntryInstallList != null) {
3265 for(FlowEntryInstall fi: flowEntryInstallList) {
3266 list.add(fi.getInstall().clone());