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.IConfigurationContainerAware;
37 import org.opendaylight.controller.connectionmanager.IConnectionManager;
38 import org.opendaylight.controller.containermanager.IContainerManager;
39 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
40 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
41 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
42 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
43 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
44 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
45 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
46 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
47 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
48 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
49 import org.opendaylight.controller.sal.action.Action;
50 import org.opendaylight.controller.sal.action.ActionType;
51 import org.opendaylight.controller.sal.action.Output;
52 import org.opendaylight.controller.sal.connection.ConnectionLocality;
53 import org.opendaylight.controller.sal.core.Config;
54 import org.opendaylight.controller.sal.core.ContainerFlow;
55 import org.opendaylight.controller.sal.core.IContainer;
56 import org.opendaylight.controller.sal.core.IContainerLocalListener;
57 import org.opendaylight.controller.sal.core.Node;
58 import org.opendaylight.controller.sal.core.NodeConnector;
59 import org.opendaylight.controller.sal.core.Property;
60 import org.opendaylight.controller.sal.core.UpdateType;
61 import org.opendaylight.controller.sal.flowprogrammer.Flow;
62 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
63 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
64 import org.opendaylight.controller.sal.match.Match;
65 import org.opendaylight.controller.sal.match.MatchType;
66 import org.opendaylight.controller.sal.utils.EtherTypes;
67 import org.opendaylight.controller.sal.utils.GlobalConstants;
68 import org.opendaylight.controller.sal.utils.IObjectReader;
69 import org.opendaylight.controller.sal.utils.ObjectReader;
70 import org.opendaylight.controller.sal.utils.ObjectWriter;
71 import org.opendaylight.controller.sal.utils.Status;
72 import org.opendaylight.controller.sal.utils.StatusCode;
73 import org.opendaylight.controller.switchmanager.IInventoryListener;
74 import org.opendaylight.controller.switchmanager.ISwitchManager;
75 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
76 import org.opendaylight.controller.switchmanager.Subnet;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * Class that manages forwarding rule installation and removal per container of
82 * the network. It also maintains the central repository of all the forwarding
83 * rules installed on the network nodes.
85 public class ForwardingRulesManager implements
86 IForwardingRulesManager,
87 PortGroupChangeListener,
88 IContainerLocalListener,
90 IConfigurationContainerAware,
93 ICacheUpdateAware<Object,Object>,
94 IFlowProgrammerListener {
96 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
97 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
98 private static final String PORT_REMOVED = "Port removed";
99 private static final String NODE_DOWN = "Node is Down";
100 private static final String INVALID_FLOW_ENTRY = "Invalid FlowEntry";
101 private String frmFileName;
102 private String portGroupFileName;
103 private ConcurrentMap<Integer, FlowConfig> staticFlows;
104 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
105 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
106 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
107 private ConcurrentMap<String, Object> TSPolicies;
108 private IContainerManager containerManager;
109 private boolean inContainerMode; // being used by global instance only
110 protected boolean stopping;
113 * Flow database. It's the software view of what was requested to install
114 * and what is installed on the switch. It is indexed by the entry itself.
115 * The entry's hashcode resumes the network node index, the flow's priority
116 * and the flow's match. The value element is a class which contains the
117 * flow entry pushed by the applications modules and the respective
118 * container flow merged version. In absence of container flows, the two
119 * flow entries are the same.
121 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
122 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
124 * Per node and per group indexing
126 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
127 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
130 * Inactive flow list. This is for the global instance of FRM It will
131 * contain all the flow entries which were installed on the global container
132 * when the first container is created.
134 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
136 private IContainer container;
137 private Set<IForwardingRulesManagerAware> frmAware =
138 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
139 private PortGroupProvider portGroupProvider;
140 private IFlowProgrammerService programmer;
141 private IClusterContainerServices clusterContainerService = null;
142 private ISwitchManager switchManager;
143 private Thread frmEventHandler;
144 protected BlockingQueue<FRMEvent> pendingEvents;
146 // Distributes FRM programming in the cluster
147 private IConnectionManager connectionManager;
150 * Name clustered caches used to support FRM entry distribution these are by
151 * necessity non-transactional as long as need to be able to synchronize
152 * states also while a transaction is in progress
154 static final String WORK_ORDER_CACHE = "frm.workOrder";
155 static final String WORK_STATUS_CACHE = "frm.workStatus";
156 static final String ORIGINAL_SW_VIEW_CACHE = "frm.originalSwView";
157 static final String INSTALLED_SW_VIEW_CACHE = "frm.installedSwView";
160 * Data structure responsible for distributing the FlowEntryInstall requests
161 * in the cluster. The key value is entry that is being either Installed or
162 * Updated or Delete. The value field is the same of the key value in case
163 * of Installation or Deletion, it's the new entry in case of Modification,
164 * this because the clustering caches don't allow null values.
166 * The logic behind this data structure is that the controller that initiate
167 * the request will place the order here, someone will pick it and then will
168 * remove from this data structure because is being served.
170 * TODO: We need to have a way to cleanup this data structure if entries are
171 * not picked by anyone, which is always a case can happen especially on
172 * Node disconnect cases.
174 protected ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
177 * Data structure responsible for retrieving the results of the workOrder
178 * submitted to the cluster.
180 * The logic behind this data structure is that the controller that has
181 * executed the order will then place the result in workStatus signaling
182 * that there was a success or a failure.
184 * TODO: The workStatus entries need to have a lifetime associated in case
185 * of requestor controller leaving the cluster.
187 protected ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
190 * Local Map used to hold the Future which a caller can use to monitor for
193 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
194 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
197 * Max pool size for the executor
199 private static final int maxPoolSize = 10;
203 * Entry being installed/updated/removed
205 * New entry will be placed after the update operation. Valid
206 * only for UpdateType.CHANGED, null for all the other cases
209 * @return a Future object for monitoring the progress of the result, or
210 * null in case the processing should take place locally
212 private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
214 // A null entry it's an unexpected condition, anyway it's safe to keep
215 // the handling local
220 Node n = e.getNode();
221 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
222 // Create the work order and distribute it
223 FlowEntryDistributionOrder fe =
224 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
225 // First create the monitor job
226 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
227 logsync.trace("Node {} not local so sending fe {}", n, fe);
228 workMonitor.put(fe, ret);
229 if (t.equals(UpdateType.CHANGED)) {
230 // Then distribute the work
231 workOrder.put(fe, u);
233 // Then distribute the work
234 workOrder.put(fe, e);
236 logsync.trace("WorkOrder requested");
237 // Now create an Handle to monitor the execution of the operation
241 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
246 * Adds a flow entry onto the network node It runs various validity checks
247 * and derive the final container flows merged entries that will be
248 * attempted to be installed
251 * the original flow entry application requested to add
253 * the flag indicating if this is a asynchronous request
254 * @return the status of this request. In case of asynchronous call, it will
255 * contain the unique id assigned to this request
257 private Status addEntry(FlowEntry flowEntry, boolean async) {
260 if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
261 String logMsg = INVALID_FLOW_ENTRY + ": {}";
262 log.warn(logMsg, flowEntry);
263 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
267 * Redundant Check: Check if the request is a redundant one from the
268 * same application the flowEntry is equal to an existing one. Given we
269 * do not have an application signature in the requested FlowEntry yet,
270 * we are here detecting the above condition by comparing the flow
271 * names, if set. If they are equal to the installed flow, most likely
272 * this is a redundant installation request from the same application
273 * and we can silently return success
275 * TODO: in future a sort of application reference list mechanism will
276 * be added to the FlowEntry so that exact flow can be used by different
279 FlowEntry present = this.originalSwView.get(flowEntry);
280 if (present != null) {
281 boolean sameFlow = present.getFlow().equals(flowEntry.getFlow());
282 boolean sameApp = present.getFlowName() != null && present.getFlowName().equals(flowEntry.getFlowName());
283 if (sameFlow && sameApp) {
284 log.trace("Skipping redundant request for flow {} on node {}", flowEntry.getFlowName(),
285 flowEntry.getNode());
286 return new Status(StatusCode.SUCCESS, "Entry is already present");
291 * Derive the container flow merged entries to install In presence of N
292 * container flows, we may end up with N different entries to install...
294 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
296 // Container Flow conflict Check
297 if (toInstallList.isEmpty()) {
298 String msg = "Flow Entry conflicts with all Container Flows";
299 String logMsg = msg + ": {}";
300 log.warn(logMsg, flowEntry);
301 return new Status(StatusCode.CONFLICT, msg);
304 // Derive the list of entries good to be installed
305 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
306 for (FlowEntryInstall entry : toInstallList) {
307 // Conflict Check: Verify new entry would not overwrite existing
309 if (this.installedSwView.containsKey(entry)) {
310 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
311 log.trace("Aborting to install {}", entry);
314 toInstallSafe.add(entry);
317 // Declare failure if all the container flow merged entries clash with
319 if (toInstallSafe.size() == 0) {
320 String msg = "A flow with same match and priority exists on the target node";
321 String logMsg = msg + ": {}";
322 log.warn(logMsg, flowEntry);
323 return new Status(StatusCode.CONFLICT, msg);
326 // Try to install an entry at the time
327 Status error = new Status(null, null);
328 Status succeded = null;
329 boolean oneSucceded = false;
330 for (FlowEntryInstall installEntry : toInstallSafe) {
332 // Install and update database
333 Status ret = addEntriesInternal(installEntry, async);
335 if (ret.isSuccess()) {
338 * The first successful status response will be returned For the
339 * asynchronous call, we can discard the container flow
340 * complication for now and assume we will always deal with one
341 * flow only per request
346 log.trace("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
350 return (oneSucceded) ? succeded : error;
354 * Given a flow entry and the list of container flows, it returns the list
355 * of container flow merged flow entries good to be installed on this
356 * container. If the list of container flows is null or empty, the install
357 * entry list will contain only one entry, the original flow entry. If the
358 * flow entry is congruent with all the N container flows, then the output
359 * install entry list will contain N entries. If the output list is empty,
360 * it means the passed flow entry conflicts with all the container flows.
363 * The list of container flows
364 * @return the list of container flow merged entries good to be installed on
367 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
368 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
370 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
371 // No container flows => entry good to be installed unchanged
372 toInstallList.add(new FlowEntryInstall(request.clone(), null));
374 // Create the list of entries to be installed. If the flow entry is
375 // not congruent with any container flow, no install entries will be
377 for (ContainerFlow cFlow : container.getContainerFlows()) {
378 if (cFlow.allowsFlow(request.getFlow())) {
379 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
383 return toInstallList;
387 * Modify a flow entry with a new one It runs various validity check and
388 * derive the final container flows merged flow entries to work with
390 * @param currentFlowEntry
391 * @param newFlowEntry
393 * the flag indicating if this is a asynchronous request
394 * @return the status of this request. In case of asynchronous call, it will
395 * contain the unique id assigned to this request
397 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
401 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
402 || newFlowEntry.getNode() == null || newFlowEntry.getFlow() == null) {
403 String msg = "Modify: " + INVALID_FLOW_ENTRY;
404 String logMsg = msg + ": {} or {}";
405 log.warn(logMsg, currentFlowEntry, newFlowEntry);
406 return new Status(StatusCode.NOTACCEPTABLE, msg);
408 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
409 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
410 String msg = "Modify: Incompatible Flow Entries";
411 String logMsg = msg + ": {} and {}";
412 log.warn(logMsg, currentFlowEntry, newFlowEntry);
413 return new Status(StatusCode.NOTACCEPTABLE, msg);
417 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
418 String msg = "Modify skipped as flows are the same";
419 String logMsg = msg + ": {} and {}";
420 log.debug(logMsg, currentFlowEntry, newFlowEntry);
421 return new Status(StatusCode.SUCCESS, msg);
425 * Conflict Check: Verify the new entry would not conflict with an
426 * existing one. This is a loose check on the previous original flow
427 * entry requests. No check on the container flow merged flow entries
430 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
431 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
432 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
433 String logMsg = msg + ": {}";
434 log.warn(logMsg, currentFlowEntry);
435 return new Status(StatusCode.CONFLICT, msg);
438 // Derive the installed and toInstall entries
439 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
440 container.getContainerFlows());
441 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
443 if (toInstallList.isEmpty()) {
444 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
445 String logMsg = msg + ": {}";
446 log.warn(logMsg, newFlowEntry);
448 return new Status(StatusCode.CONFLICT, msg);
452 * If the two list sizes differ, it means the new flow entry does not
453 * satisfy the same number of container flows the current entry does.
454 * This is only possible when the new entry and current entry have
455 * different match. In this scenario the modification would ultimately
456 * be handled as a remove and add operations in the protocol plugin.
458 * Also, if any of the new flow entries would clash with an existing
459 * one, we cannot proceed with the modify operation, because it would
460 * fail for some entries and leave stale entries on the network node.
461 * Modify path can be taken only if it can be performed completely, for
464 * So, for the above two cases, to simplify, let's decouple the modify
465 * in: 1) remove current entries 2) install new entries
467 Status succeeded = null;
468 boolean decouple = false;
469 if (installedList.size() != toInstallList.size()) {
470 log.info("Modify: New flow entry does not satisfy the same "
471 + "number of container flows as the original entry does");
474 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
475 for (FlowEntryInstall installEntry : toInstallList) {
477 * Conflict Check: Verify the new entry would not overwrite another
480 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
481 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
482 log.info("Modify: new container flow merged flow entry clashes with existing flow");
485 toInstallSafe.add(installEntry);
490 // Remove current entries
491 for (FlowEntryInstall currEntry : installedList) {
492 this.removeEntryInternal(currEntry, async);
494 // Install new entries
495 for (FlowEntryInstall newEntry : toInstallSafe) {
496 succeeded = this.addEntriesInternal(newEntry, async);
500 * The two list have the same size and the entries to install do not
501 * clash with any existing flow on the network node. We assume here
502 * (and might be wrong) that the same container flows that were
503 * satisfied by the current entries are the same that are satisfied
504 * by the new entries. Let's take the risk for now.
506 * Note: modification has to be complete. If any entry modification
507 * fails, we need to stop, restore the already modified entries, and
510 Status retModify = null;
512 int size = toInstallList.size();
514 // Modify and update database
515 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
516 if (retModify.isSuccess()) {
522 // Check if uncompleted modify
524 log.warn("Unable to perform a complete modify for all the container flows merged entries");
525 // Restore original entries
528 log.info("Attempting to restore initial entries");
529 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
530 if (retExt.isSuccess()) {
536 // Fatal error, recovery failed
538 String msg = "Flow recovery failed ! Unrecoverable Error";
540 return new Status(StatusCode.INTERNALERROR, msg);
543 succeeded = retModify;
546 * The first successful status response will be returned. For the
547 * asynchronous call, we can discard the container flow complication for
548 * now and assume we will always deal with one flow only per request
554 * This is the function that modifies the final container flows merged
555 * entries on the network node and update the database. It expects that all
556 * the validity checks are passed
558 * @param currentEntries
561 * the flag indicating if this is a asynchronous request
562 * @return the status of this request. In case of asynchronous call, it will
563 * contain the unique id assigned to this request
565 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
566 FlowEntryDistributionOrderFutureTask futureStatus =
567 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
568 if (futureStatus != null) {
569 Status retStatus = new Status(StatusCode.UNDEFINED);
571 retStatus = futureStatus.get();
572 if (retStatus.getCode()
573 .equals(StatusCode.TIMEOUT)) {
574 // A timeout happened, lets cleanup the workMonitor
575 workMonitor.remove(futureStatus.getOrder());
577 } catch (InterruptedException e) {
579 } catch (ExecutionException e) {
584 // Modify the flow on the network node
585 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
586 .getFlow(), newEntries.getInstall()
587 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
588 .getFlow(), newEntries.getInstall()
591 if (!status.isSuccess()) {
592 log.trace("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
593 status.getDescription());
597 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
600 newEntries.setRequestId(status.getRequestId());
601 updateSwViews(currentEntries, false);
602 updateSwViews(newEntries, true);
609 * Remove a flow entry. If the entry is not present in the software view
610 * (entry or node not present), it return successfully
613 * the flow entry to remove
615 * the flag indicating if this is a asynchronous request
616 * @return the status of this request. In case of asynchronous call, it will
617 * contain the unique id assigned to this request
619 private Status removeEntry(FlowEntry flowEntry, boolean async) {
620 Status error = new Status(null, null);
623 if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) {
624 String logMsg = INVALID_FLOW_ENTRY + ": {}";
625 log.warn(logMsg, flowEntry);
626 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
629 // Derive the container flows merged installed entries
630 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
632 Status succeeded = null;
633 boolean atLeastOneRemoved = false;
634 for (FlowEntryInstall entry : installedList) {
635 if (!installedSwView.containsKey(entry)) {
636 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
637 log.debug(logMsg, flowEntry);
638 if (installedList.size() == 1) {
639 // If we had only one entry to remove, we are done
640 return new Status(StatusCode.SUCCESS);
646 // Remove and update DB
647 Status ret = removeEntryInternal(entry, async);
649 if (!ret.isSuccess()) {
651 log.trace("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
652 if (installedList.size() == 1) {
653 // If we had only one entry to remove, this is fatal failure
658 atLeastOneRemoved = true;
663 * No worries if full removal failed. Consistency checker will take care
664 * of removing the stale entries later, or adjusting the software
665 * database if not in sync with hardware
667 return (atLeastOneRemoved) ? succeeded : error;
671 * This is the function that removes the final container flows merged entry
672 * from the network node and update the database. It expects that all the
673 * validity checks are passed
676 * the flow entry to remove
678 * the flag indicating if this is a asynchronous request
679 * @return the status of this request. In case of asynchronous call, it will
680 * contain the unique id assigned to this request
682 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
683 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
684 if (futureStatus != null) {
685 Status retStatus = new Status(StatusCode.UNDEFINED);
687 retStatus = futureStatus.get();
688 if (retStatus.getCode()
689 .equals(StatusCode.TIMEOUT)) {
690 // A timeout happened, lets cleanup the workMonitor
691 workMonitor.remove(futureStatus.getOrder());
693 } catch (InterruptedException e) {
695 } catch (ExecutionException e) {
700 // Mark the entry to be deleted (for CC just in case we fail)
704 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
705 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
708 if (!status.isSuccess()) {
709 log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", entry.getInstall(),
710 status.getDescription());
713 log.trace("Removed {}", entry.getInstall());
716 updateSwViews(entry, false);
723 * This is the function that installs the final container flow merged entry
724 * on the network node and updates the database. It expects that all the
725 * validity and conflict checks are passed. That means it does not check
726 * whether this flow would conflict or overwrite an existing one.
729 * the flow entry to install
731 * the flag indicating if this is a asynchronous request
732 * @return the status of this request. In case of asynchronous call, it will
733 * contain the unique id assigned to this request
735 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
736 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
737 if (futureStatus != null) {
738 Status retStatus = new Status(StatusCode.UNDEFINED);
740 retStatus = futureStatus.get();
741 if (retStatus.getCode()
742 .equals(StatusCode.TIMEOUT)) {
743 // A timeout happened, lets cleanup the workMonitor
744 workMonitor.remove(futureStatus.getOrder());
746 } catch (InterruptedException e) {
748 } catch (ExecutionException e) {
753 // Install the flow on the network node
754 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
755 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
758 if (!status.isSuccess()) {
759 log.trace("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
760 status.getDescription());
764 log.trace("Added {}", entry.getInstall());
767 entry.setRequestId(status.getRequestId());
768 updateSwViews(entry, true);
775 * Returns true if the flow conflicts with all the container's flows. This
776 * means that if the function returns true, the passed flow entry is
777 * congruent with at least one container flow, hence it is good to be
778 * installed on this container.
781 * @return true if flow conflicts with all the container flows, false
784 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
785 List<ContainerFlow> cFlowList = container.getContainerFlows();
787 // Validity check and avoid unnecessary computation
788 // Also takes care of default container where no container flows are
790 if (cFlowList == null || cFlowList.isEmpty()) {
794 for (ContainerFlow cFlow : cFlowList) {
795 if (cFlow.allowsFlow(flowEntry.getFlow())) {
796 // Entry is allowed by at least one container flow: good to go
803 private ConcurrentMap.Entry<Integer, FlowConfig> getStaticFlowEntry(String name, Node node) {
804 for (ConcurrentMap.Entry<Integer, FlowConfig> flowEntry : staticFlows.entrySet()) {
805 FlowConfig flowConfig = flowEntry.getValue();
806 if (flowConfig.isByNameAndNodeIdEqual(name, node)) {
813 private void updateIndexDatabase(FlowEntryInstall entry, boolean add) {
814 // Update node indexed flow database
815 updateNodeFlowsDB(entry, add);
817 // Update group indexed flow database
818 updateGroupFlowsDB(entry, add);
822 * Update the node mapped flows database
824 private void updateSwViews(FlowEntryInstall flowEntries, boolean add) {
826 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
827 installedSwView.put(flowEntries, flowEntries);
829 originalSwView.remove(flowEntries.getOriginal());
830 installedSwView.remove(flowEntries);
835 * Update the node mapped flows database
837 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
838 Node node = flowEntries.getNode();
840 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
841 if (nodeIndeces == null) {
845 nodeIndeces = new ArrayList<FlowEntryInstall>();
850 // there may be an already existing entry.
851 // remove it before adding the new one.
852 // This is necessary since we have observed that in some cases
853 // Infinispan does aggregation for operations (eg:- remove and then put a different value)
854 // related to the same key within the same transaction.
855 // Need this defensive code as the new FlowEntryInstall may be different
856 // than the old one even though the equals method returns true. This is because
857 // the equals method does not take into account the action list.
858 if(nodeIndeces.contains(flowEntries)) {
859 nodeIndeces.remove(flowEntries);
861 nodeIndeces.add(flowEntries);
863 nodeIndeces.remove(flowEntries);
866 // Update cache across cluster
867 if (nodeIndeces.isEmpty()) {
868 this.nodeFlows.remove(node);
870 this.nodeFlows.put(node, nodeIndeces);
875 * Update the group name mapped flows database
877 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
878 String groupName = flowEntries.getGroupName();
880 // Flow may not be part of a group
881 if (groupName == null) {
885 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
886 if (indices == null) {
890 indices = new ArrayList<FlowEntryInstall>();
895 // same comments in the similar code section in
896 // updateNodeFlowsDB method apply here too
897 if(indices.contains(flowEntries)) {
898 indices.remove(flowEntries);
900 indices.add(flowEntries);
902 indices.remove(flowEntries);
905 // Update cache across cluster
906 if (indices.isEmpty()) {
907 this.groupFlows.remove(groupName);
909 this.groupFlows.put(groupName, indices);
914 * Remove a flow entry that has been added previously First checks if the
915 * entry is effectively present in the local database
917 @SuppressWarnings("unused")
918 private Status removeEntry(Node node, String flowName) {
919 FlowEntryInstall target = null;
922 for (FlowEntryInstall entry : installedSwView.values()) {
923 if (entry.equalsByNodeAndName(node, flowName)) {
929 // If it is not there, stop any further processing
930 if (target == null) {
931 return new Status(StatusCode.SUCCESS, "Entry is not present");
935 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
938 if (status.isSuccess()) {
939 updateSwViews(target, false);
942 log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
943 status.getDescription());
950 public Status installFlowEntry(FlowEntry flowEntry) {
952 if (isContainerModeAllowed(flowEntry)) {
953 status = addEntry(flowEntry, false);
955 String msg = "Controller in container mode: Install Refused";
956 String logMsg = msg + ": {}";
957 status = new Status(StatusCode.NOTACCEPTABLE, msg);
958 log.warn(logMsg, flowEntry);
964 public Status installFlowEntryAsync(FlowEntry flowEntry) {
966 if (isContainerModeAllowed(flowEntry)) {
967 status = addEntry(flowEntry, true);
969 String msg = "Controller in container mode: Install Refused";
970 status = new Status(StatusCode.NOTACCEPTABLE, msg);
977 public Status uninstallFlowEntry(FlowEntry flowEntry) {
979 if (isContainerModeAllowed(flowEntry)) {
980 status = removeEntry(flowEntry, false);
982 String msg = "Controller in container mode: Uninstall Refused";
983 String logMsg = msg + ": {}";
984 status = new Status(StatusCode.NOTACCEPTABLE, msg);
985 log.warn(logMsg, flowEntry);
991 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
993 if (isContainerModeAllowed(flowEntry)) {
994 status = removeEntry(flowEntry, true);
996 String msg = "Controller in container mode: Uninstall Refused";
997 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1004 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1005 Status status = null;
1006 if (isContainerModeAllowed(currentFlowEntry)) {
1007 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1009 String msg = "Controller in container mode: Modify Refused";
1010 String logMsg = msg + ": {}";
1011 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1012 log.warn(logMsg, newFlowEntry);
1018 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
1019 Status status = null;
1020 if (isContainerModeAllowed(currentFlowEntry)) {
1021 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
1023 String msg = "Controller in container mode: Modify Refused";
1024 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1031 * Returns whether the specified flow entry is allowed to be
1032 * installed/removed/modified based on the current container mode status.
1033 * This call always returns true in the container instance of forwarding
1034 * rules manager. It is meant for the global instance only (default
1035 * container) of forwarding rules manager. Idea is that for assuring
1036 * container isolation of traffic, flow installation in default container is
1037 * blocked when in container mode (containers are present). The only flows
1038 * that are allowed in container mode in the default container are the
1039 * proactive flows, the ones automatically installed on the network node
1040 * which forwarding mode has been configured to "proactive". These flows are
1041 * needed by controller to discover the nodes topology and to discover the
1042 * attached hosts for some SDN switches.
1045 * The flow entry to be installed/removed/modified
1046 * @return true if not in container mode or if flowEntry is internally
1049 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1050 return (!inContainerMode) ? true : flowEntry.isInternal();
1054 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1056 * Run a check on the original entries to decide whether to go with a
1057 * add or modify method. A loose check means only check against the
1058 * original flow entry requests and not against the installed flow
1059 * entries which are the result of the original entry merged with the
1060 * container flow(s) (if any). The modifyFlowEntry method in presence of
1061 * conflicts with the Container flows (if any) would revert back to a
1062 * delete + add pattern
1064 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1066 if (currentFlowEntry != null) {
1067 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1069 return installFlowEntry(newFlowEntry);
1074 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1076 * Run a check on the original entries to decide whether to go with a
1077 * add or modify method. A loose check means only check against the
1078 * original flow entry requests and not against the installed flow
1079 * entries which are the result of the original entry merged with the
1080 * container flow(s) (if any). The modifyFlowEntry method in presence of
1081 * conflicts with the Container flows (if any) would revert back to a
1082 * delete + add pattern
1084 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1086 if (currentFlowEntry != null) {
1087 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1089 return installFlowEntryAsync(newFlowEntry);
1094 public Status uninstallFlowEntryGroup(String groupName) {
1095 if (groupName == null || groupName.isEmpty()) {
1096 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1098 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1099 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1101 if (inContainerMode) {
1102 String msg = "Controller in container mode: Group Uninstall Refused";
1103 String logMsg = msg + ": {}";
1104 log.warn(logMsg, groupName);
1105 return new Status(StatusCode.NOTACCEPTABLE, msg);
1107 int toBeRemoved = 0;
1109 if (groupFlows.containsKey(groupName)) {
1110 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1111 toBeRemoved = list.size();
1112 for (FlowEntryInstall entry : list) {
1113 Status status = this.removeEntry(entry.getOriginal(), false);
1114 if (status.isSuccess()) {
1117 error = status.getDescription();
1121 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1122 "Not all the flows were removed: " + error);
1126 public Status uninstallFlowEntryGroupAsync(String groupName) {
1127 if (groupName == null || groupName.isEmpty()) {
1128 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1130 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1131 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1133 if (inContainerMode) {
1134 String msg = "Controller in container mode: Group Uninstall Refused";
1135 String logMsg = msg + ": {}";
1136 log.warn(logMsg, groupName);
1137 return new Status(StatusCode.NOTACCEPTABLE, msg);
1139 if (groupFlows.containsKey(groupName)) {
1140 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1141 for (FlowEntryInstall entry : list) {
1142 this.removeEntry(entry.getOriginal(), true);
1145 return new Status(StatusCode.SUCCESS);
1149 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1150 return entryConflictsWithContainerFlows(flowEntry);
1154 * Updates all installed flows because the container flow got updated This
1155 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1156 * Reinstall of all flows This is needed because a new container flows
1157 * merged flow may conflict with an existing old container flows merged flow
1158 * on the network node
1160 protected void updateFlowsContainerFlow() {
1161 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1162 // First remove all installed entries
1163 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1164 FlowEntryInstall current = entry.getValue();
1165 // Store the original entry
1166 toReInstall.add(current.getOriginal());
1167 // Remove the old couples. No validity checks to be run, use the
1169 this.removeEntryInternal(current, false);
1171 // Then reinstall the original entries
1172 for (FlowEntry entry : toReInstall) {
1173 // Reinstall the original flow entries, via the regular path: new
1174 // cFlow merge + validations
1175 this.installFlowEntry(entry);
1179 private void nonClusterObjectCreate() {
1180 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1181 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1182 TSPolicies = new ConcurrentHashMap<String, Object>();
1183 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1184 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1185 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1186 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1187 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1191 public void setTSPolicyData(String policyname, Object o, boolean add) {
1194 /* Check if this policy already exists */
1195 if (!(TSPolicies.containsKey(policyname))) {
1196 TSPolicies.put(policyname, o);
1199 TSPolicies.remove(policyname);
1201 if (frmAware != null) {
1202 synchronized (frmAware) {
1203 for (IForwardingRulesManagerAware frma : frmAware) {
1205 frma.policyUpdate(policyname, add);
1206 } catch (Exception e) {
1207 log.warn("Exception on callback", e);
1215 public Map<String, Object> getTSPolicyData() {
1220 public Object getTSPolicyData(String policyName) {
1221 if (TSPolicies.containsKey(policyName)) {
1222 return TSPolicies.get(policyName);
1229 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1230 List<FlowEntry> list = new ArrayList<FlowEntry>();
1231 if (policyName != null && !policyName.trim().isEmpty()) {
1232 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1233 if (policyName.equals(entry.getKey().getGroupName())) {
1234 list.add(entry.getValue().clone());
1242 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1243 List<FlowEntry> list = new ArrayList<FlowEntry>();
1244 if (policyName != null && !policyName.trim().isEmpty()) {
1245 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1246 if (policyName.equals(entry.getKey().getGroupName())) {
1247 list.add(entry.getValue().getInstall().clone());
1255 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1257 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1258 if (flow.getFlowName().equals(flowName)) {
1259 FlowEntry currentFlowEntry = flow.getOriginal();
1260 FlowEntry newFlowEntry = currentFlowEntry.clone();
1261 for (NodeConnector dstPort : portList) {
1262 newFlowEntry.getFlow().addAction(new Output(dstPort));
1264 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1265 if (error.isSuccess()) {
1266 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1268 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1269 currentFlowEntry.toString(), error.getDescription());
1274 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1278 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1279 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1280 FlowEntryInstall flow = this.installedSwView.get(index);
1281 if (flow.getFlowName().equals(flowName)) {
1282 FlowEntry currentFlowEntry = flow.getOriginal();
1283 FlowEntry newFlowEntry = currentFlowEntry.clone();
1284 for (NodeConnector dstPort : portList) {
1285 Action action = new Output(dstPort);
1286 newFlowEntry.getFlow().removeAction(action);
1288 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1289 if (status.isSuccess()) {
1290 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1292 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1293 currentFlowEntry.toString(), status.getDescription());
1298 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1302 * This function assumes the target flow has only one output port
1305 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1306 FlowEntry currentFlowEntry = null;
1307 FlowEntry newFlowEntry = null;
1310 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1311 FlowEntryInstall flow = this.installedSwView.get(index);
1312 if (flow.getFlowName().equals(flowName)) {
1313 currentFlowEntry = flow.getOriginal();
1317 if (currentFlowEntry == null) {
1318 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1322 // Create a flow copy with the new output port
1323 newFlowEntry = currentFlowEntry.clone();
1324 Action target = null;
1325 for (Action action : newFlowEntry.getFlow().getActions()) {
1326 if (action.getType() == ActionType.OUTPUT) {
1331 newFlowEntry.getFlow().removeAction(target);
1332 newFlowEntry.getFlow().addAction(new Output(outPort));
1334 // Modify on network node
1335 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1337 if (status.isSuccess()) {
1338 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1340 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1341 status.getDescription());
1347 public NodeConnector getOutputPort(Node node, String flowName) {
1348 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1349 FlowEntryInstall flow = this.installedSwView.get(index);
1350 if (flow.getFlowName().equals(flowName)) {
1351 for (Action action : flow.getOriginal().getFlow().getActions()) {
1352 if (action.getType() == ActionType.OUTPUT) {
1353 return ((Output) action).getPort();
1361 private void cacheStartup() {
1366 private void allocateCaches() {
1367 if (this.clusterContainerService == null) {
1368 log.warn("Un-initialized clusterContainerService, can't create cache");
1372 log.debug("Allocating caches for Container {}", container.getName());
1375 clusterContainerService.createCache(ORIGINAL_SW_VIEW_CACHE,
1376 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1378 clusterContainerService.createCache(INSTALLED_SW_VIEW_CACHE,
1379 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1381 clusterContainerService.createCache("frm.inactiveFlows",
1382 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1384 clusterContainerService.createCache("frm.staticFlows",
1385 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1387 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1388 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1390 clusterContainerService.createCache("frm.portGroupConfigs",
1391 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1393 clusterContainerService.createCache("frm.portGroupData",
1394 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1396 clusterContainerService.createCache("frm.TSPolicies",
1397 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1399 clusterContainerService.createCache(WORK_STATUS_CACHE,
1400 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1402 clusterContainerService.createCache(WORK_ORDER_CACHE,
1403 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1405 } catch (CacheConfigException cce) {
1406 log.error("CacheConfigException");
1407 } catch (CacheExistException cce) {
1408 log.error("CacheExistException");
1412 @SuppressWarnings({ "unchecked" })
1413 private void retrieveCaches() {
1414 ConcurrentMap<?, ?> map;
1416 if (this.clusterContainerService == null) {
1417 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1418 nonClusterObjectCreate();
1422 log.debug("Retrieving Caches for Container {}", container.getName());
1424 map = clusterContainerService.getCache(ORIGINAL_SW_VIEW_CACHE);
1426 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1428 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1431 map = clusterContainerService.getCache(INSTALLED_SW_VIEW_CACHE);
1433 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1435 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1438 map = clusterContainerService.getCache("frm.inactiveFlows");
1440 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1442 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1445 map = clusterContainerService.getCache("frm.staticFlows");
1447 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1449 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1452 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1454 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1456 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1459 map = clusterContainerService.getCache("frm.portGroupConfigs");
1461 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1463 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1466 map = clusterContainerService.getCache("frm.portGroupData");
1468 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1470 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1473 map = clusterContainerService.getCache("frm.TSPolicies");
1475 TSPolicies = (ConcurrentMap<String, Object>) map;
1477 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1480 map = clusterContainerService.getCache(WORK_ORDER_CACHE);
1482 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1484 log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName());
1487 map = clusterContainerService.getCache(WORK_STATUS_CACHE);
1489 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1491 log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName());
1495 private boolean flowConfigExists(FlowConfig config) {
1496 // Flow name has to be unique on per node id basis
1497 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1498 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1506 public Status addStaticFlow(FlowConfig config) {
1507 // Configuration object validation
1508 Status status = config.validate(container);
1509 if (!status.isSuccess()) {
1510 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1511 String error = "Invalid Configuration (" + status.getDescription() + ")";
1512 config.setStatus(error);
1513 return new Status(StatusCode.BADREQUEST, error);
1515 return addStaticFlowInternal(config, false);
1519 * Private method to add a static flow configuration which does not run any
1520 * validation on the passed FlowConfig object. If restore is set to true,
1521 * configuration is stored in configuration database regardless the
1522 * installation on the network node was successful. This is useful at boot
1523 * when static flows are present in startup configuration and are read
1524 * before the switches connects.
1527 * The static flow configuration
1529 * if true, the configuration is stored regardless the
1530 * installation on the network node was successful
1531 * @return The status of this request
1533 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1534 boolean multipleFlowPush = false;
1537 config.setStatus(StatusCode.SUCCESS.toString());
1540 if (flowConfigExists(config)) {
1541 error = "Entry with this name on specified switch already exists";
1542 log.warn("Entry with this name on specified switch already exists: {}", config);
1543 config.setStatus(error);
1544 return new Status(StatusCode.CONFLICT, error);
1547 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1548 for (String portGroupName : portGroupConfigs.keySet()) {
1549 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1550 multipleFlowPush = true;
1554 if (!multipleFlowPush) {
1555 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1556 error = "Invalid Configuration (Invalid PortGroup Name)";
1557 config.setStatus(error);
1558 return new Status(StatusCode.BADREQUEST, error);
1563 * If requested program the entry in hardware first before updating the
1566 if (!multipleFlowPush) {
1568 if (config.installInHw()) {
1569 FlowEntry entry = config.getFlowEntry();
1570 status = this.installFlowEntry(entry);
1571 if (!status.isSuccess()) {
1572 config.setStatus(status.getDescription());
1581 * When the control reaches this point, either of the following
1582 * conditions is true 1. This is a single entry configuration (non
1583 * PortGroup) and the hardware installation is successful 2. This is a
1584 * multiple entry configuration (PortGroup) and hardware installation is
1585 * NOT done directly on this event. 3. The User prefers to retain the
1586 * configuration in Controller and skip hardware installation.
1588 * Hence it is safe to update the StaticFlow DB at this point.
1590 * Note : For the case of PortGrouping, it is essential to have this DB
1591 * populated before the PortGroupListeners can query for the DB
1592 * triggered using portGroupChanged event...
1594 Integer ordinal = staticFlowsOrdinal.get(0);
1595 staticFlowsOrdinal.put(0, ++ordinal);
1596 staticFlows.put(ordinal, config);
1598 if (multipleFlowPush) {
1599 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1600 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1601 if (existingData != null) {
1602 portGroupChanged(pgconfig, existingData, true);
1605 return new Status(StatusCode.SUCCESS);
1608 private void addStaticFlowsToSwitch(Node node) {
1609 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1610 FlowConfig config = entry.getValue();
1611 if (config.isPortGroupEnabled()) {
1614 if (config.getNode().equals(node)) {
1615 if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) {
1616 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1617 config.setStatus(status.getDescription());
1621 // Update cluster cache
1622 refreshClusterStaticFlowsStatus(node);
1625 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1626 log.trace("Updating Static Flow configs on node down: {}", node);
1628 List<Integer> toRemove = new ArrayList<Integer>();
1629 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1631 FlowConfig config = entry.getValue();
1633 if (config.isPortGroupEnabled()) {
1637 if (config.installInHw() && config.getNode().equals(node)) {
1638 if (config.isInternalFlow()) {
1639 // Take note of this controller generated static flow
1640 toRemove.add(entry.getKey());
1642 config.setStatus(NODE_DOWN);
1646 // Remove controller generated static flows for this node
1647 for (Integer index : toRemove) {
1648 staticFlows.remove(index);
1650 // Update cluster cache
1651 refreshClusterStaticFlowsStatus(node);
1655 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1656 log.trace("Updating Static Flow configs on container mode change: {}", update);
1658 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1659 FlowConfig config = entry.getValue();
1660 if (config.isPortGroupEnabled()) {
1663 if (config.installInHw() && !config.isInternalFlow()) {
1666 config.setStatus("Removed from node because in container mode");
1669 config.setStatus(StatusCode.SUCCESS.toString());
1675 // Update cluster cache
1676 refreshClusterStaticFlowsStatus(null);
1680 public Status removeStaticFlow(FlowConfig config) {
1682 * No config.isInternal() check as NB does not take this path and GUI
1683 * cannot issue a delete on an internal generated flow. We need this
1684 * path to be accessible when switch mode is changed from proactive to
1685 * reactive, so that we can remove the internal generated LLDP and ARP
1689 // Look for the target configuration entry
1691 FlowConfig target = null;
1692 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1693 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1694 key = entry.getKey();
1695 target = entry.getValue();
1699 if (target == null) {
1700 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1703 // Program the network node
1704 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1706 // Update configuration database if programming was successful
1707 if (status.isSuccess()) {
1708 staticFlows.remove(key);
1715 public Status removeStaticFlow(String name, Node node) {
1716 // Look for the target configuration entry
1718 FlowConfig target = null;
1719 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1720 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1721 key = mapEntry.getKey();
1722 target = mapEntry.getValue();
1726 if (target == null) {
1727 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1730 // Validity check for api3 entry point
1731 if (target.isInternalFlow()) {
1732 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1733 String logMsg = msg + ": {}";
1734 log.warn(logMsg, name);
1735 return new Status(StatusCode.NOTACCEPTABLE, msg);
1738 if (target.isPortGroupEnabled()) {
1739 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1740 String logMsg = msg + ": {}";
1741 log.warn(logMsg, name);
1742 return new Status(StatusCode.NOTACCEPTABLE, msg);
1745 // Program the network node
1746 Status status = this.removeEntry(target.getFlowEntry(), false);
1748 // Update configuration database if programming was successful
1749 if (status.isSuccess()) {
1750 staticFlows.remove(key);
1757 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1758 // Validity check for api3 entry point
1759 if (newFlowConfig.isInternalFlow()) {
1760 String msg = "Invalid operation: Controller generated flow cannot be modified";
1761 String logMsg = msg + ": {}";
1762 log.warn(logMsg, newFlowConfig);
1763 return new Status(StatusCode.NOTACCEPTABLE, msg);
1767 Status status = newFlowConfig.validate(container);
1768 if (!status.isSuccess()) {
1769 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1770 newFlowConfig.setStatus(msg);
1771 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1772 return new Status(StatusCode.BADREQUEST, msg);
1775 FlowConfig oldFlowConfig = null;
1776 Integer index = null;
1777 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1778 FlowConfig entry = mapEntry.getValue();
1779 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1780 oldFlowConfig = entry;
1781 index = mapEntry.getKey();
1786 if (oldFlowConfig == null) {
1787 String msg = "Attempt to modify a non existing static flow";
1788 String logMsg = msg + ": {}";
1789 log.warn(logMsg, newFlowConfig);
1790 return new Status(StatusCode.NOTFOUND, msg);
1793 // Do not attempt to reinstall the flow, warn user
1794 if (newFlowConfig.equals(oldFlowConfig)) {
1795 String msg = "No modification detected";
1796 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1797 return new Status(StatusCode.SUCCESS, msg);
1800 // If flow is installed, program the network node
1801 status = new Status(StatusCode.SUCCESS, "Saved in config");
1802 if (oldFlowConfig.installInHw()) {
1803 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1806 // Update configuration database if programming was successful
1807 if (status.isSuccess()) {
1808 newFlowConfig.setStatus(status.getDescription());
1809 staticFlows.put(index, newFlowConfig);
1816 public Status toggleStaticFlowStatus(String name, Node node) {
1817 return toggleStaticFlowStatus(getStaticFlow(name, node));
1821 public Status toggleStaticFlowStatus(FlowConfig config) {
1822 if (config == null) {
1823 String msg = "Invalid request: null flow config";
1825 return new Status(StatusCode.BADREQUEST, msg);
1827 // Validity check for api3 entry point
1828 if (config.isInternalFlow()) {
1829 String msg = "Invalid operation: Controller generated flow cannot be modified";
1830 String logMsg = msg + ": {}";
1831 log.warn(logMsg, config);
1832 return new Status(StatusCode.NOTACCEPTABLE, msg);
1835 // Find the config entry
1837 FlowConfig target = null;
1838 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1839 FlowConfig conf = entry.getValue();
1840 if (conf.isByNameAndNodeIdEqual(config)) {
1841 key = entry.getKey();
1846 if (target != null) {
1847 Status status = target.validate(container);
1848 if (!status.isSuccess()) {
1849 log.warn(status.getDescription());
1852 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1853 .installFlowEntry(target.getFlowEntry());
1854 if (status.isSuccess()) {
1855 // Update Configuration database
1856 target.setStatus(StatusCode.SUCCESS.toString());
1857 target.toggleInstallation();
1858 staticFlows.put(key, target);
1863 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1867 * Reinsert all static flows entries in the cache to force cache updates in
1868 * the cluster. This is useful when only some parameters were changed in the
1869 * entries, like the status.
1872 * The node for which the static flow configurations have to be
1873 * refreshed. If null, all nodes static flows will be refreshed.
1875 private void refreshClusterStaticFlowsStatus(Node node) {
1876 // Refresh cluster cache
1877 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1878 if (node == null || entry.getValue().getNode().equals(node)) {
1879 staticFlows.put(entry.getKey(), entry.getValue());
1885 * Uninstall all the non-internal Flow Entries present in the software view.
1886 * If requested, a copy of each original flow entry will be stored in the
1887 * inactive list so that it can be re-applied when needed (This is typically
1888 * the case when running in the default container and controller moved to
1889 * container mode) NOTE WELL: The routine as long as does a bulk change will
1890 * operate only on the entries for nodes locally attached so to avoid
1891 * redundant operations initiated by multiple nodes
1893 * @param preserveFlowEntries
1894 * if true, a copy of each original entry is stored in the
1897 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1898 log.info("Uninstalling all non-internal flows");
1900 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1902 // Store entries / create target list
1903 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1904 FlowEntryInstall flowEntries = mapEntry.getValue();
1905 // Skip internal generated static flows
1906 if (!flowEntries.isInternal()) {
1907 toRemove.add(flowEntries);
1908 // Store the original entries if requested
1909 if (preserveFlowEntries) {
1910 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1915 // Now remove the entries
1916 for (FlowEntryInstall flowEntryHw : toRemove) {
1917 Node n = flowEntryHw.getNode();
1918 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
1919 Status status = this.removeEntryInternal(flowEntryHw, false);
1920 if (!status.isSuccess()) {
1921 log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1924 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
1931 * Re-install all the Flow Entries present in the inactive list The inactive
1932 * list will be empty at the end of this call This function is called on the
1933 * default container instance of FRM only when the last container is deleted
1935 private void reinstallAllFlowEntries() {
1936 log.info("Reinstalling all inactive flows");
1938 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1939 this.addEntry(flowEntry, false);
1942 // Empty inactive list in any case
1943 inactiveFlows.clear();
1947 public List<FlowConfig> getStaticFlows() {
1948 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1951 // TODO: need to come out with a better algorithm for maintaining the order
1952 // of the configuration entries
1953 // with actual one, index associated to deleted entries cannot be reused and
1955 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1956 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1957 for (int i = 0; i <= maxKey; i++) {
1958 FlowConfig entry = flowMap.get(i);
1959 if (entry != null) {
1960 orderedList.add(entry);
1967 public FlowConfig getStaticFlow(String name, Node node) {
1968 ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
1970 return entry.getValue();
1976 public List<FlowConfig> getStaticFlows(Node node) {
1977 List<FlowConfig> list = new ArrayList<FlowConfig>();
1978 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1979 if (entry.getValue().onNode(node)) {
1980 list.add(entry.getValue());
1987 public List<String> getStaticFlowNamesForNode(Node node) {
1988 List<String> list = new ArrayList<String>();
1989 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1990 if (entry.getValue().onNode(node)) {
1991 list.add(entry.getValue().getName());
1998 public List<Node> getListNodeWithConfiguredFlows() {
1999 Set<Node> set = new HashSet<Node>();
2000 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2001 set.add(entry.getValue().getNode());
2003 return new ArrayList<Node>(set);
2006 @SuppressWarnings("unchecked")
2007 private void loadFlowConfiguration() {
2008 ObjectReader objReader = new ObjectReader();
2009 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2012 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2015 if (pgConfig != null) {
2016 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2017 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2021 if (confList == null) {
2026 for (Integer key : confList.keySet()) {
2027 if (key.intValue() > maxKey) {
2028 maxKey = key.intValue();
2032 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2033 addStaticFlowInternal(conf, true);
2038 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2039 return ois.readObject();
2043 public Status saveConfig() {
2044 return saveConfigInternal();
2047 private Status saveConfigInternal() {
2048 ObjectWriter objWriter = new ObjectWriter();
2049 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2050 for (Integer ordinal : staticFlows.keySet()) {
2051 FlowConfig config = staticFlows.get(ordinal);
2052 // Do not save dynamic and controller generated static flows
2053 if (config.isDynamic() || config.isInternalFlow()) {
2056 nonDynamicFlows.put(ordinal, config);
2058 objWriter.write(nonDynamicFlows, frmFileName);
2059 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2060 return new Status(StatusCode.SUCCESS, null);
2064 public void subnetNotify(Subnet sub, boolean add) {
2070 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2073 * This method can be called from within the OSGi framework context,
2074 * given the programming operation can take sometime, it not good
2075 * pratice to have in it's context operations that can take time,
2076 * hence moving off to a different thread for async processing.
2078 private ExecutorService executor;
2080 public void modeChangeNotify(final Node node, final boolean proactive) {
2081 Callable<Status> modeChangeCallable = new Callable<Status>() {
2083 public Status call() throws Exception {
2084 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2086 List<String> puntAction = new ArrayList<String>();
2087 puntAction.add(ActionType.CONTROLLER.toString());
2089 FlowConfig allowARP = new FlowConfig();
2090 allowARP.setInstallInHw(true);
2091 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2092 allowARP.setPriority("1");
2093 allowARP.setNode(node);
2094 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2096 allowARP.setActions(puntAction);
2097 defaultConfigs.add(allowARP);
2099 FlowConfig allowLLDP = new FlowConfig();
2100 allowLLDP.setInstallInHw(true);
2101 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2102 allowLLDP.setPriority("1");
2103 allowLLDP.setNode(node);
2104 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2106 allowLLDP.setActions(puntAction);
2107 defaultConfigs.add(allowLLDP);
2109 List<String> dropAction = new ArrayList<String>();
2110 dropAction.add(ActionType.DROP.toString());
2112 FlowConfig dropAllConfig = new FlowConfig();
2113 dropAllConfig.setInstallInHw(true);
2114 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2115 + FlowConfig.INTERNALSTATICFLOWEND);
2116 dropAllConfig.setPriority("0");
2117 dropAllConfig.setNode(node);
2118 dropAllConfig.setActions(dropAction);
2119 defaultConfigs.add(dropAllConfig);
2121 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2122 for (FlowConfig fc : defaultConfigs) {
2123 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2124 if (status.isSuccess()) {
2125 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2127 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2131 return new Status(StatusCode.SUCCESS);
2136 * Execute the work outside the caller context, this could be an
2137 * expensive operation and we don't want to block the caller for it.
2139 this.executor.submit(modeChangeCallable);
2143 * Remove from the databases all the flows installed on the node
2147 private void cleanDatabaseForNode(Node node) {
2148 log.info("Cleaning Flow database for Node {}", node);
2149 if (nodeFlows.containsKey(node)) {
2150 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2152 for (FlowEntryInstall entry : toRemove) {
2153 updateSwViews(entry, false);
2158 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2163 Match match = flow.getMatch();
2164 if (match.isPresent(MatchType.IN_PORT)) {
2165 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2166 if (matchPort.equals(nc)) {
2170 List<Action> actionsList = flow.getActions();
2171 if (actionsList != null) {
2172 for (Action action : actionsList) {
2173 if (action instanceof Output) {
2174 NodeConnector actionPort = ((Output) action).getPort();
2175 if (actionPort.equals(nc)) {
2185 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2186 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2190 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2191 boolean updateStaticFlowCluster = false;
2197 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2198 if (config != null) {
2199 switch (config.getValue()) {
2200 case Config.ADMIN_DOWN:
2201 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2202 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2204 case Config.ADMIN_UP:
2205 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2206 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2208 case Config.ADMIN_UNDEF:
2215 // This is the case where a switch port is removed from the SDN agent space
2216 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2217 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2223 if (updateStaticFlowCluster) {
2224 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2229 * It goes through the static flows configuration, it identifies the ones
2230 * which have the specified node connector as input or output port and
2231 * install them on the network node if they are marked to be installed in
2232 * hardware and their status shows they were not installed yet
2234 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2235 boolean updated = false;
2236 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2237 for (FlowConfig flowConfig : flowConfigForNode) {
2238 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2239 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) {
2240 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2241 if (!status.isSuccess()) {
2242 flowConfig.setStatus(status.getDescription());
2244 flowConfig.setStatus(StatusCode.SUCCESS.toString());
2254 * Remove from the network node all the flows which have the specified node
2255 * connector as input or output port. If any of the flow entry is a static
2256 * flow, it updates the correspondent configuration.
2258 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2259 boolean updated = false;
2260 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2261 if (nodeFlowEntries == null) {
2264 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2265 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2266 Status status = this.removeEntryInternal(fei, true);
2267 if (!status.isSuccess()) {
2271 * If the flow entry is a static flow, then update its
2274 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2275 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2276 if (flowConfig != null) {
2277 flowConfig.setStatus(PORT_REMOVED);
2286 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2287 FlowConfig derivedFlow = new FlowConfig(original);
2288 derivedFlow.setDynamic(true);
2289 derivedFlow.setPortGroup(null);
2290 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2291 derivedFlow.setIngressPort(port + "");
2295 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2296 for (FlowConfig staticFlow : staticFlows.values()) {
2297 if (staticFlow.getPortGroup() == null) {
2300 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2301 for (Short port : data.getPorts()) {
2302 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2303 addStaticFlowInternal(derivedFlow, false);
2309 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2310 for (FlowConfig staticFlow : staticFlows.values()) {
2311 if (staticFlow.getPortGroup() == null) {
2314 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2315 for (Short port : data.getPorts()) {
2316 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2317 removeStaticFlow(derivedFlow);
2324 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2325 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2326 Map<Node, PortGroup> existingData = portGroupData.get(config);
2327 if (existingData != null) {
2328 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2329 PortGroup existingPortGroup = existingData.get(entry.getKey());
2330 if (existingPortGroup == null) {
2332 existingData.put(entry.getKey(), entry.getValue());
2333 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2337 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2338 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2340 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2341 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2347 portGroupData.put(config, data);
2348 for (Node swid : data.keySet()) {
2349 addPortGroupFlows(config, swid, data.get(swid));
2356 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2357 PortGroupConfig config = portGroupConfigs.get(name);
2358 if (config != null) {
2362 if ((portGroupProvider == null) && !restore) {
2365 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2369 config = new PortGroupConfig(name, regex);
2370 portGroupConfigs.put(name, config);
2371 if (portGroupProvider != null) {
2372 portGroupProvider.createPortGroupConfig(config);
2378 public boolean delPortGroupConfig(String name) {
2379 PortGroupConfig config = portGroupConfigs.get(name);
2380 if (config == null) {
2384 if (portGroupProvider != null) {
2385 portGroupProvider.deletePortGroupConfig(config);
2387 portGroupConfigs.remove(name);
2392 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2393 return portGroupConfigs;
2396 public boolean isPortGroupSupported() {
2397 if (portGroupProvider == null) {
2403 public void setIContainer(IContainer s) {
2407 public void unsetIContainer(IContainer s) {
2408 if (this.container == s) {
2409 this.container = null;
2414 public PortGroupProvider getPortGroupProvider() {
2415 return portGroupProvider;
2418 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2419 this.portGroupProvider = null;
2422 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2423 this.portGroupProvider = portGroupProvider;
2424 portGroupProvider.registerPortGroupChange(this);
2425 for (PortGroupConfig config : portGroupConfigs.values()) {
2426 portGroupProvider.createPortGroupConfig(config);
2430 public void setFrmAware(IForwardingRulesManagerAware obj) {
2431 this.frmAware.add(obj);
2434 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2435 this.frmAware.remove(obj);
2438 void setClusterContainerService(IClusterContainerServices s) {
2439 log.debug("Cluster Service set");
2440 this.clusterContainerService = s;
2443 void unsetClusterContainerService(IClusterContainerServices s) {
2444 if (this.clusterContainerService == s) {
2445 log.debug("Cluster Service removed!");
2446 this.clusterContainerService = null;
2450 private String getContainerName() {
2451 if (container == null) {
2452 return GlobalConstants.DEFAULT.toString();
2454 return container.getName();
2458 * Function called by the dependency manager when all the required
2459 * dependencies are satisfied
2463 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2464 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2466 inContainerMode = false;
2468 if (portGroupProvider != null) {
2469 portGroupProvider.registerPortGroupChange(this);
2472 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
2473 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
2478 * If we are not the first cluster node to come up, do not initialize
2479 * the static flow entries ordinal
2481 if (staticFlowsOrdinal.size() == 0) {
2482 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2485 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2487 // Initialize the event handler thread
2488 frmEventHandler = new Thread(new Runnable() {
2493 final FRMEvent event = pendingEvents.take();
2494 if (event == null) {
2495 log.warn("Dequeued null event");
2498 log.trace("Dequeued {} event", event.getClass().getSimpleName());
2499 if (event instanceof NodeUpdateEvent) {
2500 NodeUpdateEvent update = (NodeUpdateEvent) event;
2501 Node node = update.getNode();
2502 switch (update.getUpdateType()) {
2504 addStaticFlowsToSwitch(node);
2507 cleanDatabaseForNode(node);
2508 updateStaticFlowConfigsOnNodeDown(node);
2512 } else if (event instanceof ErrorReportedEvent) {
2513 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2514 processErrorEvent(errEvent);
2515 } else if (event instanceof WorkOrderEvent) {
2517 * Take care of handling the remote Work request
2519 Runnable r = new Runnable() {
2522 WorkOrderEvent work = (WorkOrderEvent) event;
2523 FlowEntryDistributionOrder fe = work.getFe();
2525 logsync.trace("Executing the workOrder {}", fe);
2526 Status gotStatus = null;