2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.forwardingrulesmanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.UnknownHostException;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.EnumSet;
19 import java.util.HashSet;
20 import java.util.List;
22 import java.util.Map.Entry;
24 import java.util.concurrent.BlockingQueue;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.LinkedBlockingQueue;
33 import org.eclipse.osgi.framework.console.CommandInterpreter;
34 import org.eclipse.osgi.framework.console.CommandProvider;
35 import org.opendaylight.controller.clustering.services.CacheConfigException;
36 import org.opendaylight.controller.clustering.services.CacheExistException;
37 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
38 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
39 import org.opendaylight.controller.clustering.services.IClusterServices;
40 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
41 import org.opendaylight.controller.connectionmanager.IConnectionManager;
42 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
43 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
44 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
45 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
46 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
47 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
48 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
50 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
51 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
52 import org.opendaylight.controller.sal.action.Action;
53 import org.opendaylight.controller.sal.action.ActionType;
54 import org.opendaylight.controller.sal.action.Controller;
55 import org.opendaylight.controller.sal.action.Flood;
56 import org.opendaylight.controller.sal.action.Output;
57 import org.opendaylight.controller.sal.action.PopVlan;
58 import org.opendaylight.controller.sal.connection.ConnectionLocality;
59 import org.opendaylight.controller.sal.core.Config;
60 import org.opendaylight.controller.sal.core.ContainerFlow;
61 import org.opendaylight.controller.sal.core.IContainer;
62 import org.opendaylight.controller.sal.core.IContainerLocalListener;
63 import org.opendaylight.controller.sal.core.Node;
64 import org.opendaylight.controller.sal.core.NodeConnector;
65 import org.opendaylight.controller.sal.core.Property;
66 import org.opendaylight.controller.sal.core.UpdateType;
67 import org.opendaylight.controller.sal.flowprogrammer.Flow;
68 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
69 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
70 import org.opendaylight.controller.sal.match.Match;
71 import org.opendaylight.controller.sal.match.MatchType;
72 import org.opendaylight.controller.sal.utils.EtherTypes;
73 import org.opendaylight.controller.sal.utils.GlobalConstants;
74 import org.opendaylight.controller.sal.utils.HexEncode;
75 import org.opendaylight.controller.sal.utils.IObjectReader;
76 import org.opendaylight.controller.sal.utils.IPProtocols;
77 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
78 import org.opendaylight.controller.sal.utils.NodeCreator;
79 import org.opendaylight.controller.sal.utils.ObjectReader;
80 import org.opendaylight.controller.sal.utils.ObjectWriter;
81 import org.opendaylight.controller.sal.utils.Status;
82 import org.opendaylight.controller.sal.utils.StatusCode;
83 import org.opendaylight.controller.switchmanager.IInventoryListener;
84 import org.opendaylight.controller.switchmanager.ISwitchManager;
85 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
86 import org.opendaylight.controller.switchmanager.Subnet;
87 import org.osgi.framework.BundleContext;
88 import org.osgi.framework.FrameworkUtil;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * Class that manages forwarding rule installation and removal per container of
94 * the network. It also maintains the central repository of all the forwarding
95 * rules installed on the network nodes.
97 public class ForwardingRulesManager implements
98 IForwardingRulesManager,
99 PortGroupChangeListener,
100 IContainerLocalListener,
102 IConfigurationContainerAware,
105 ICacheUpdateAware<Object,Object>,
107 IFlowProgrammerListener {
108 private static final String NODEDOWN = "Node is Down";
109 private static final String SUCCESS = StatusCode.SUCCESS.toString();
110 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
111 private static final String PORTREMOVED = "Port removed";
112 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
113 private String frmFileName;
114 private String portGroupFileName;
115 private ConcurrentMap<Integer, FlowConfig> staticFlows;
116 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
117 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
118 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
119 private ConcurrentMap<String, Object> TSPolicies;
120 private boolean inContainerMode; // being used by global instance only
121 protected boolean stopping;
124 * Flow database. It's the software view of what was requested to install
125 * and what is installed on the switch. It is indexed by the entry itself.
126 * The entry's hashcode resumes the network node index, the flow's priority
127 * and the flow's match. The value element is a class which contains the
128 * flow entry pushed by the applications modules and the respective
129 * container flow merged version. In absence of container flows, the two
130 * flow entries are the same.
132 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
133 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
135 * Per node and per group indexing
137 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
138 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
141 * Inactive flow list. This is for the global instance of FRM It will
142 * contain all the flow entries which were installed on the global container
143 * when the first container is created.
145 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
147 private IContainer container;
148 private Set<IForwardingRulesManagerAware> frmAware =
149 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
150 private PortGroupProvider portGroupProvider;
151 private IFlowProgrammerService programmer;
152 private IClusterContainerServices clusterContainerService = null;
153 private ISwitchManager switchManager;
154 private Thread frmEventHandler;
155 protected BlockingQueue<FRMEvent> pendingEvents;
157 // Distributes FRM programming in the cluster
158 private IConnectionManager connectionManager;
161 * Name clustered caches used to support FRM entry distribution these are by
162 * necessity non-transactional as long as need to be able to synchronize
163 * states also while a transaction is in progress
165 static final String WORKORDERCACHE = "frm.workOrder";
166 static final String WORKSTATUSCACHE = "frm.workStatus";
169 * Data structure responsible for distributing the FlowEntryInstall requests
170 * in the cluster. The key value is entry that is being either Installed or
171 * Updated or Delete. The value field is the same of the key value in case
172 * of Installation or Deletion, it's the new entry in case of Modification,
173 * this because the clustering caches don't allow null values.
175 * The logic behind this data structure is that the controller that initiate
176 * the request will place the order here, someone will pick it and then will
177 * remove from this data structure because is being served.
179 * TODO: We need to have a way to cleanup this data structure if entries are
180 * not picked by anyone, which is always a case can happen especially on
181 * Node disconnect cases.
183 protected ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
186 * Data structure responsible for retrieving the results of the workOrder
187 * submitted to the cluster.
189 * The logic behind this data structure is that the controller that has
190 * executed the order will then place the result in workStatus signaling
191 * that there was a success or a failure.
193 * TODO: The workStatus entries need to have a lifetime associated in case
194 * of requestor controller leaving the cluster.
196 protected ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
199 * Local Map used to hold the Future which a caller can use to monitor for
202 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
203 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
206 * Max pool size for the executor
208 private static final int maxPoolSize = 10;
212 * Entry being installed/updated/removed
214 * New entry will be placed after the update operation. Valid
215 * only for UpdateType.CHANGED, null for all the other cases
218 * @return a Future object for monitoring the progress of the result, or
219 * null in case the processing should take place locally
221 private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
223 // A null entry it's an unexpected condition, anyway it's safe to keep
224 // the handling local
229 Node n = e.getNode();
230 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
231 // Create the work order and distribute it
232 FlowEntryDistributionOrder fe =
233 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
234 // First create the monitor job
235 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
236 logsync.trace("Node {} not local so sending fe {}", n, fe);
237 workMonitor.put(fe, ret);
238 if (t.equals(UpdateType.CHANGED)) {
239 // Then distribute the work
240 workOrder.put(fe, u);
242 // Then distribute the work
243 workOrder.put(fe, e);
245 logsync.trace("WorkOrder requested");
246 // Now create an Handle to monitor the execution of the operation
250 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
255 * Adds a flow entry onto the network node It runs various validity checks
256 * and derive the final container flows merged entries that will be
257 * attempted to be installed
260 * the original flow entry application requested to add
262 * the flag indicating if this is a asynchronous request
263 * @return the status of this request. In case of asynchronous call, it will
264 * contain the unique id assigned to this request
266 private Status addEntry(FlowEntry flowEntry, boolean async) {
269 if (flowEntry == null || flowEntry.getNode() == null) {
270 String msg = "Invalid FlowEntry";
271 String logMsg = msg + ": {}";
272 log.warn(logMsg, flowEntry);
273 return new Status(StatusCode.NOTACCEPTABLE, msg);
277 * Derive the container flow merged entries to install In presence of N
278 * container flows, we may end up with N different entries to install...
280 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
282 // Container Flow conflict Check
283 if (toInstallList.isEmpty()) {
284 String msg = "Flow Entry conflicts with all Container Flows";
285 String logMsg = msg + ": {}";
286 log.warn(logMsg, flowEntry);
287 return new Status(StatusCode.CONFLICT, msg);
290 // Derive the list of entries good to be installed
291 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
292 for (FlowEntryInstall entry : toInstallList) {
293 // Conflict Check: Verify new entry would not overwrite existing
295 if (this.installedSwView.containsKey(entry)) {
296 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
297 log.trace("Aborting to install {}", entry);
300 toInstallSafe.add(entry);
303 // Declare failure if all the container flow merged entries clash with
305 if (toInstallSafe.size() == 0) {
306 String msg = "A flow with same match and priority exists on the target node";
307 String logMsg = msg + ": {}";
308 log.warn(logMsg, flowEntry);
309 return new Status(StatusCode.CONFLICT, msg);
312 // Try to install an entry at the time
313 Status error = new Status(null, null);
314 Status succeded = null;
315 boolean oneSucceded = false;
316 for (FlowEntryInstall installEntry : toInstallSafe) {
318 // Install and update database
319 Status ret = addEntriesInternal(installEntry, async);
321 if (ret.isSuccess()) {
324 * The first successful status response will be returned For the
325 * asynchronous call, we can discard the container flow
326 * complication for now and assume we will always deal with one
327 * flow only per request
332 log.warn("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
336 return (oneSucceded) ? succeded : error;
340 * Given a flow entry and the list of container flows, it returns the list
341 * of container flow merged flow entries good to be installed on this
342 * container. If the list of container flows is null or empty, the install
343 * entry list will contain only one entry, the original flow entry. If the
344 * flow entry is congruent with all the N container flows, then the output
345 * install entry list will contain N entries. If the output list is empty,
346 * it means the passed flow entry conflicts with all the container flows.
349 * The list of container flows
350 * @return the list of container flow merged entries good to be installed on
353 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
354 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
356 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
357 // No container flows => entry good to be installed unchanged
358 toInstallList.add(new FlowEntryInstall(request.clone(), null));
360 // Create the list of entries to be installed. If the flow entry is
361 // not congruent with any container flow, no install entries will be
363 for (ContainerFlow cFlow : container.getContainerFlows()) {
364 if (cFlow.allowsFlow(request.getFlow())) {
365 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
369 return toInstallList;
373 * Modify a flow entry with a new one It runs various validity check and
374 * derive the final container flows merged flow entries to work with
376 * @param currentFlowEntry
377 * @param newFlowEntry
379 * the flag indicating if this is a asynchronous request
380 * @return the status of this request. In case of asynchronous call, it will
381 * contain the unique id assigned to this request
383 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
387 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
388 || newFlowEntry.getNode() == null) {
389 String msg = "Modify: Invalid FlowEntry";
390 String logMsg = msg + ": {} or {}";
391 log.warn(logMsg, currentFlowEntry, newFlowEntry);
392 return new Status(StatusCode.NOTACCEPTABLE, msg);
394 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
395 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
396 String msg = "Modify: Incompatible Flow Entries";
397 String logMsg = msg + ": {} and {}";
398 log.warn(logMsg, currentFlowEntry, newFlowEntry);
399 return new Status(StatusCode.NOTACCEPTABLE, msg);
403 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
404 String msg = "Modify skipped as flows are the same";
405 String logMsg = msg + ": {} and {}";
406 log.debug(logMsg, currentFlowEntry, newFlowEntry);
407 return new Status(StatusCode.SUCCESS, msg);
411 * Conflict Check: Verify the new entry would not conflict with an
412 * existing one. This is a loose check on the previous original flow
413 * entry requests. No check on the container flow merged flow entries
416 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
417 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
418 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
419 String logMsg = msg + ": {}";
420 log.warn(logMsg, currentFlowEntry);
421 return new Status(StatusCode.CONFLICT, msg);
424 // Derive the installed and toInstall entries
425 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
426 container.getContainerFlows());
427 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
429 if (toInstallList.isEmpty()) {
430 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
431 String logMsg = msg + ": {}";
432 log.warn(logMsg, newFlowEntry);
434 return new Status(StatusCode.CONFLICT, msg);
438 * If the two list sizes differ, it means the new flow entry does not
439 * satisfy the same number of container flows the current entry does.
440 * This is only possible when the new entry and current entry have
441 * different match. In this scenario the modification would ultimately
442 * be handled as a remove and add operations in the protocol plugin.
444 * Also, if any of the new flow entries would clash with an existing
445 * one, we cannot proceed with the modify operation, because it would
446 * fail for some entries and leave stale entries on the network node.
447 * Modify path can be taken only if it can be performed completely, for
450 * So, for the above two cases, to simplify, let's decouple the modify
451 * in: 1) remove current entries 2) install new entries
453 Status succeeded = null;
454 boolean decouple = false;
455 if (installedList.size() != toInstallList.size()) {
456 log.info("Modify: New flow entry does not satisfy the same "
457 + "number of container flows as the original entry does");
460 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
461 for (FlowEntryInstall installEntry : toInstallList) {
463 * Conflict Check: Verify the new entry would not overwrite another
466 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
467 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
468 log.info("Modify: new container flow merged flow entry clashes with existing flow");
471 toInstallSafe.add(installEntry);
476 // Remove current entries
477 for (FlowEntryInstall currEntry : installedList) {
478 this.removeEntryInternal(currEntry, async);
480 // Install new entries
481 for (FlowEntryInstall newEntry : toInstallSafe) {
482 succeeded = this.addEntriesInternal(newEntry, async);
486 * The two list have the same size and the entries to install do not
487 * clash with any existing flow on the network node. We assume here
488 * (and might be wrong) that the same container flows that were
489 * satisfied by the current entries are the same that are satisfied
490 * by the new entries. Let's take the risk for now.
492 * Note: modification has to be complete. If any entry modification
493 * fails, we need to stop, restore the already modified entries, and
496 Status retModify = null;
498 int size = toInstallList.size();
500 // Modify and update database
501 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
502 if (retModify.isSuccess()) {
508 // Check if uncompleted modify
510 log.warn("Unable to perform a complete modify for all the container flows merged entries");
511 // Restore original entries
514 log.info("Attempting to restore initial entries");
515 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
516 if (retExt.isSuccess()) {
522 // Fatal error, recovery failed
524 String msg = "Flow recovery failed ! Unrecoverable Error";
526 return new Status(StatusCode.INTERNALERROR, msg);
529 succeeded = retModify;
532 * The first successful status response will be returned. For the
533 * asynchronous call, we can discard the container flow complication for
534 * now and assume we will always deal with one flow only per request
540 * This is the function that modifies the final container flows merged
541 * entries on the network node and update the database. It expects that all
542 * the validity checks are passed
544 * @param currentEntries
547 * the flag indicating if this is a asynchronous request
548 * @return the status of this request. In case of asynchronous call, it will
549 * contain the unique id assigned to this request
551 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
552 FlowEntryDistributionOrderFutureTask futureStatus =
553 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
554 if (futureStatus != null) {
555 Status retStatus = new Status(StatusCode.UNDEFINED);
557 retStatus = futureStatus.get();
558 if (retStatus.getCode()
559 .equals(StatusCode.TIMEOUT)) {
560 // A timeout happened, lets cleanup the workMonitor
561 workMonitor.remove(futureStatus.getOrder());
563 } catch (InterruptedException e) {
565 } catch (ExecutionException e) {
570 // Modify the flow on the network node
571 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
572 .getFlow(), newEntries.getInstall()
573 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
574 .getFlow(), newEntries.getInstall()
577 if (!status.isSuccess()) {
578 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
579 status.getDescription());
583 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
586 newEntries.setRequestId(status.getRequestId());
587 updateLocalDatabase(currentEntries, false);
588 updateLocalDatabase(newEntries, true);
595 * Remove a flow entry. If the entry is not present in the software view
596 * (entry or node not present), it return successfully
599 * the flow entry to remove
601 * the flag indicating if this is a asynchronous request
602 * @return the status of this request. In case of asynchronous call, it will
603 * contain the unique id assigned to this request
605 private Status removeEntry(FlowEntry flowEntry, boolean async) {
606 Status error = new Status(null, null);
609 if (flowEntry == null || flowEntry.getNode() == null) {
610 String msg = "Invalid FlowEntry";
611 String logMsg = msg + ": {}";
612 log.warn(logMsg, flowEntry);
613 return new Status(StatusCode.NOTACCEPTABLE, msg);
616 // Derive the container flows merged installed entries
617 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
619 Status succeeded = null;
620 boolean atLeastOneRemoved = false;
621 for (FlowEntryInstall entry : installedList) {
622 if (!installedSwView.containsKey(entry)) {
623 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
624 log.debug(logMsg, flowEntry);
625 if (installedList.size() == 1) {
626 // If we had only one entry to remove, we are done
627 return new Status(StatusCode.SUCCESS);
633 // Remove and update DB
634 Status ret = removeEntryInternal(entry, async);
636 if (!ret.isSuccess()) {
638 log.warn("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
639 if (installedList.size() == 1) {
640 // If we had only one entry to remove, this is fatal failure
645 atLeastOneRemoved = true;
650 * No worries if full removal failed. Consistency checker will take care
651 * of removing the stale entries later, or adjusting the software
652 * database if not in sync with hardware
654 return (atLeastOneRemoved) ? succeeded : error;
658 * This is the function that removes the final container flows merged entry
659 * from the network node and update the database. It expects that all the
660 * validity checks are passed
663 * the flow entry to remove
665 * the flag indicating if this is a asynchronous request
666 * @return the status of this request. In case of asynchronous call, it will
667 * contain the unique id assigned to this request
669 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
670 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
671 if (futureStatus != null) {
672 Status retStatus = new Status(StatusCode.UNDEFINED);
674 retStatus = futureStatus.get();
675 if (retStatus.getCode()
676 .equals(StatusCode.TIMEOUT)) {
677 // A timeout happened, lets cleanup the workMonitor
678 workMonitor.remove(futureStatus.getOrder());
680 } catch (InterruptedException e) {
682 } catch (ExecutionException e) {
687 // Mark the entry to be deleted (for CC just in case we fail)
691 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
692 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
695 if (!status.isSuccess()) {
696 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
697 status.getDescription());
700 log.trace("Removed {}", entry.getInstall());
703 updateLocalDatabase(entry, false);
710 * This is the function that installs the final container flow merged entry
711 * on the network node and updates the database. It expects that all the
712 * validity and conflict checks are passed. That means it does not check
713 * whether this flow would conflict or overwrite an existing one.
716 * the flow entry to install
718 * the flag indicating if this is a asynchronous request
719 * @return the status of this request. In case of asynchronous call, it will
720 * contain the unique id assigned to this request
722 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
723 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
724 if (futureStatus != null) {
725 Status retStatus = new Status(StatusCode.UNDEFINED);
727 retStatus = futureStatus.get();
728 if (retStatus.getCode()
729 .equals(StatusCode.TIMEOUT)) {
730 // A timeout happened, lets cleanup the workMonitor
731 workMonitor.remove(futureStatus.getOrder());
733 } catch (InterruptedException e) {
735 } catch (ExecutionException e) {
740 // Install the flow on the network node
741 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
742 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
745 if (!status.isSuccess()) {
746 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
747 status.getDescription());
751 log.trace("Added {}", entry.getInstall());
754 entry.setRequestId(status.getRequestId());
755 updateLocalDatabase(entry, true);
762 * Returns true if the flow conflicts with all the container's flows. This
763 * means that if the function returns true, the passed flow entry is
764 * congruent with at least one container flow, hence it is good to be
765 * installed on this container.
768 * @return true if flow conflicts with all the container flows, false
771 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
772 List<ContainerFlow> cFlowList = container.getContainerFlows();
774 // Validity check and avoid unnecessary computation
775 // Also takes care of default container where no container flows are
777 if (cFlowList == null || cFlowList.isEmpty()) {
781 for (ContainerFlow cFlow : cFlowList) {
782 if (cFlow.allowsFlow(flowEntry.getFlow())) {
783 // Entry is allowed by at least one container flow: good to go
790 private ConcurrentMap.Entry<Integer, FlowConfig> getStaticFlowEntry(String name, Node node) {
791 for (ConcurrentMap.Entry<Integer, FlowConfig> flowEntry : staticFlows.entrySet()) {
792 FlowConfig flowConfig = flowEntry.getValue();
793 if (flowConfig.isByNameAndNodeIdEqual(name, node)) {
800 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
801 // Update the software view
802 updateSwViewes(entry, add);
804 // Update node indexed flow database
805 updateNodeFlowsDB(entry, add);
807 // Update group indexed flow database
808 updateGroupFlowsDB(entry, add);
812 * Update the node mapped flows database
814 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
816 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
817 installedSwView.put(flowEntries, flowEntries);
819 originalSwView.remove(flowEntries.getOriginal());
820 installedSwView.remove(flowEntries);
825 * Update the node mapped flows database
827 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
828 Node node = flowEntries.getNode();
830 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
831 if (nodeIndeces == null) {
835 nodeIndeces = new ArrayList<FlowEntryInstall>();
840 nodeIndeces.add(flowEntries);
842 nodeIndeces.remove(flowEntries);
845 // Update cache across cluster
846 if (nodeIndeces.isEmpty()) {
847 this.nodeFlows.remove(node);
849 this.nodeFlows.put(node, nodeIndeces);
854 * Update the group name mapped flows database
856 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
857 String groupName = flowEntries.getGroupName();
859 // Flow may not be part of a group
860 if (groupName == null) {
864 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
865 if (indices == null) {
869 indices = new ArrayList<FlowEntryInstall>();
874 indices.add(flowEntries);
876 indices.remove(flowEntries);
879 // Update cache across cluster
880 if (indices.isEmpty()) {
881 this.groupFlows.remove(groupName);
883 this.groupFlows.put(groupName, indices);
888 * Remove a flow entry that has been added previously First checks if the
889 * entry is effectively present in the local database
891 @SuppressWarnings("unused")
892 private Status removeEntry(Node node, String flowName) {
893 FlowEntryInstall target = null;
896 for (FlowEntryInstall entry : installedSwView.values()) {
897 if (entry.equalsByNodeAndName(node, flowName)) {
903 // If it is not there, stop any further processing
904 if (target == null) {
905 return new Status(StatusCode.SUCCESS, "Entry is not present");
909 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
912 if (status.isSuccess()) {
913 updateLocalDatabase(target, false);
916 log.warn("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
917 status.getDescription());
924 public Status installFlowEntry(FlowEntry flowEntry) {
926 if (isContainerModeAllowed(flowEntry)) {
927 status = addEntry(flowEntry, false);
929 String msg = "Controller in container mode: Install Refused";
930 String logMsg = msg + ": {}";
931 status = new Status(StatusCode.NOTACCEPTABLE, msg);
932 log.warn(logMsg, flowEntry);
938 public Status installFlowEntryAsync(FlowEntry flowEntry) {
940 if (isContainerModeAllowed(flowEntry)) {
941 status = addEntry(flowEntry, true);
943 String msg = "Controller in container mode: Install Refused";
944 status = new Status(StatusCode.NOTACCEPTABLE, msg);
951 public Status uninstallFlowEntry(FlowEntry flowEntry) {
953 if (isContainerModeAllowed(flowEntry)) {
954 status = removeEntry(flowEntry, false);
956 String msg = "Controller in container mode: Uninstall Refused";
957 String logMsg = msg + ": {}";
958 status = new Status(StatusCode.NOTACCEPTABLE, msg);
959 log.warn(logMsg, flowEntry);
965 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
967 if (isContainerModeAllowed(flowEntry)) {
968 status = removeEntry(flowEntry, true);
970 String msg = "Controller in container mode: Uninstall Refused";
971 status = new Status(StatusCode.NOTACCEPTABLE, msg);
978 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
979 Status status = null;
980 if (isContainerModeAllowed(currentFlowEntry)) {
981 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
983 String msg = "Controller in container mode: Modify Refused";
984 String logMsg = msg + ": {}";
985 status = new Status(StatusCode.NOTACCEPTABLE, msg);
986 log.warn(logMsg, newFlowEntry);
992 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
993 Status status = null;
994 if (isContainerModeAllowed(currentFlowEntry)) {
995 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
997 String msg = "Controller in container mode: Modify Refused";
998 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1005 * Returns whether the specified flow entry is allowed to be
1006 * installed/removed/modified based on the current container mode status.
1007 * This call always returns true in the container instance of forwarding
1008 * rules manager. It is meant for the global instance only (default
1009 * container) of forwarding rules manager. Idea is that for assuring
1010 * container isolation of traffic, flow installation in default container is
1011 * blocked when in container mode (containers are present). The only flows
1012 * that are allowed in container mode in the default container are the
1013 * proactive flows, the ones automatically installed on the network node
1014 * which forwarding mode has been configured to "proactive". These flows are
1015 * needed by controller to discover the nodes topology and to discover the
1016 * attached hosts for some SDN switches.
1019 * The flow entry to be installed/removed/modified
1020 * @return true if not in container mode or if flowEntry is internally
1023 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1024 return (!inContainerMode) ? true : flowEntry.isInternal();
1028 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1030 * Run a check on the original entries to decide whether to go with a
1031 * add or modify method. A loose check means only check against the
1032 * original flow entry requests and not against the installed flow
1033 * entries which are the result of the original entry merged with the
1034 * container flow(s) (if any). The modifyFlowEntry method in presence of
1035 * conflicts with the Container flows (if any) would revert back to a
1036 * delete + add pattern
1038 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1040 if (currentFlowEntry != null) {
1041 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1043 return installFlowEntry(newFlowEntry);
1048 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1050 * Run a check on the original entries to decide whether to go with a
1051 * add or modify method. A loose check means only check against the
1052 * original flow entry requests and not against the installed flow
1053 * entries which are the result of the original entry merged with the
1054 * container flow(s) (if any). The modifyFlowEntry method in presence of
1055 * conflicts with the Container flows (if any) would revert back to a
1056 * delete + add pattern
1058 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1060 if (currentFlowEntry != null) {
1061 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1063 return installFlowEntryAsync(newFlowEntry);
1068 public Status uninstallFlowEntryGroup(String groupName) {
1069 if (groupName == null || groupName.isEmpty()) {
1070 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1072 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1073 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1075 if (inContainerMode) {
1076 String msg = "Controller in container mode: Group Uninstall Refused";
1077 String logMsg = msg + ": {}";
1078 log.warn(logMsg, groupName);
1079 return new Status(StatusCode.NOTACCEPTABLE, msg);
1081 int toBeRemoved = 0;
1083 if (groupFlows.containsKey(groupName)) {
1084 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1085 toBeRemoved = list.size();
1086 for (FlowEntryInstall entry : list) {
1087 Status status = this.removeEntry(entry.getOriginal(), false);
1088 if (status.isSuccess()) {
1091 error = status.getDescription();
1095 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1096 "Not all the flows were removed: " + error);
1100 public Status uninstallFlowEntryGroupAsync(String groupName) {
1101 if (groupName == null || groupName.isEmpty()) {
1102 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1104 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1105 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1107 if (inContainerMode) {
1108 String msg = "Controller in container mode: Group Uninstall Refused";
1109 String logMsg = msg + ": {}";
1110 log.warn(logMsg, groupName);
1111 return new Status(StatusCode.NOTACCEPTABLE, msg);
1113 if (groupFlows.containsKey(groupName)) {
1114 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1115 for (FlowEntryInstall entry : list) {
1116 this.removeEntry(entry.getOriginal(), true);
1119 return new Status(StatusCode.SUCCESS);
1123 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1124 return entryConflictsWithContainerFlows(flowEntry);
1128 * Updates all installed flows because the container flow got updated This
1129 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1130 * Reinstall of all flows This is needed because a new container flows
1131 * merged flow may conflict with an existing old container flows merged flow
1132 * on the network node
1134 protected void updateFlowsContainerFlow() {
1135 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1136 // First remove all installed entries
1137 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1138 FlowEntryInstall current = entry.getValue();
1139 // Store the original entry
1140 toReInstall.add(current.getOriginal());
1141 // Remove the old couples. No validity checks to be run, use the
1143 this.removeEntryInternal(current, false);
1145 // Then reinstall the original entries
1146 for (FlowEntry entry : toReInstall) {
1147 // Reinstall the original flow entries, via the regular path: new
1148 // cFlow merge + validations
1149 this.installFlowEntry(entry);
1153 private void nonClusterObjectCreate() {
1154 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1155 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1156 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
1157 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
1158 TSPolicies = new ConcurrentHashMap<String, Object>();
1159 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1160 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1161 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1162 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1163 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1166 private void registerWithOSGIConsole() {
1167 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1168 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1172 public void setTSPolicyData(String policyname, Object o, boolean add) {
1175 /* Check if this policy already exists */
1176 if (!(TSPolicies.containsKey(policyname))) {
1177 TSPolicies.put(policyname, o);
1180 TSPolicies.remove(policyname);
1182 if (frmAware != null) {
1183 synchronized (frmAware) {
1184 for (IForwardingRulesManagerAware frma : frmAware) {
1186 frma.policyUpdate(policyname, add);
1187 } catch (Exception e) {
1188 log.warn("Exception on callback", e);
1196 public Map<String, Object> getTSPolicyData() {
1201 public Object getTSPolicyData(String policyName) {
1202 if (TSPolicies.containsKey(policyName)) {
1203 return TSPolicies.get(policyName);
1210 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1211 List<FlowEntry> list = new ArrayList<FlowEntry>();
1212 if (policyName != null && !policyName.trim().isEmpty()) {
1213 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1214 if (policyName.equals(entry.getKey().getGroupName())) {
1215 list.add(entry.getKey().clone());
1223 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1224 List<FlowEntry> list = new ArrayList<FlowEntry>();
1225 if (policyName != null && !policyName.trim().isEmpty()) {
1226 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1227 if (policyName.equals(entry.getKey().getGroupName())) {
1228 list.add(entry.getKey().getInstall().clone());
1236 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1238 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1239 if (flow.getFlowName().equals(flowName)) {
1240 FlowEntry currentFlowEntry = flow.getOriginal();
1241 FlowEntry newFlowEntry = currentFlowEntry.clone();
1242 for (NodeConnector dstPort : portList) {
1243 newFlowEntry.getFlow().addAction(new Output(dstPort));
1245 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1246 if (error.isSuccess()) {
1247 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1249 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1250 currentFlowEntry.toString(), error.getDescription());
1255 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1259 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1260 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1261 FlowEntryInstall flow = this.installedSwView.get(index);
1262 if (flow.getFlowName().equals(flowName)) {
1263 FlowEntry currentFlowEntry = flow.getOriginal();
1264 FlowEntry newFlowEntry = currentFlowEntry.clone();
1265 for (NodeConnector dstPort : portList) {
1266 Action action = new Output(dstPort);
1267 newFlowEntry.getFlow().removeAction(action);
1269 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1270 if (status.isSuccess()) {
1271 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1273 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1274 currentFlowEntry.toString(), status.getDescription());
1279 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1283 * This function assumes the target flow has only one output port
1286 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1287 FlowEntry currentFlowEntry = null;
1288 FlowEntry newFlowEntry = null;
1291 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1292 FlowEntryInstall flow = this.installedSwView.get(index);
1293 if (flow.getFlowName().equals(flowName)) {
1294 currentFlowEntry = flow.getOriginal();
1298 if (currentFlowEntry == null) {
1299 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1303 // Create a flow copy with the new output port
1304 newFlowEntry = currentFlowEntry.clone();
1305 Action target = null;
1306 for (Action action : newFlowEntry.getFlow().getActions()) {
1307 if (action.getType() == ActionType.OUTPUT) {
1312 newFlowEntry.getFlow().removeAction(target);
1313 newFlowEntry.getFlow().addAction(new Output(outPort));
1315 // Modify on network node
1316 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1318 if (status.isSuccess()) {
1319 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1321 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1322 status.getDescription());
1328 public NodeConnector getOutputPort(Node node, String flowName) {
1329 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1330 FlowEntryInstall flow = this.installedSwView.get(index);
1331 if (flow.getFlowName().equals(flowName)) {
1332 for (Action action : flow.getOriginal().getFlow().getActions()) {
1333 if (action.getType() == ActionType.OUTPUT) {
1334 return ((Output) action).getPort();
1342 private void cacheStartup() {
1347 private void allocateCaches() {
1348 if (this.clusterContainerService == null) {
1349 log.warn("Un-initialized clusterContainerService, can't create cache");
1353 log.debug("Allocating caches for Container {}", container.getName());
1356 clusterContainerService.createCache("frm.originalSwView",
1357 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1359 clusterContainerService.createCache("frm.installedSwView",
1360 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1362 clusterContainerService.createCache("frm.inactiveFlows",
1363 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1365 clusterContainerService.createCache("frm.nodeFlows",
1366 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1368 clusterContainerService.createCache("frm.groupFlows",
1369 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1371 clusterContainerService.createCache("frm.staticFlows",
1372 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1374 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1375 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1377 clusterContainerService.createCache("frm.portGroupConfigs",
1378 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1380 clusterContainerService.createCache("frm.portGroupData",
1381 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1383 clusterContainerService.createCache("frm.TSPolicies",
1384 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1386 clusterContainerService.createCache(WORKSTATUSCACHE,
1387 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1389 clusterContainerService.createCache(WORKORDERCACHE,
1390 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1392 } catch (CacheConfigException cce) {
1393 log.error("CacheConfigException");
1394 } catch (CacheExistException cce) {
1395 log.error("CacheExistException");
1399 @SuppressWarnings({ "unchecked" })
1400 private void retrieveCaches() {
1401 ConcurrentMap<?, ?> map;
1403 if (this.clusterContainerService == null) {
1404 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1405 nonClusterObjectCreate();
1409 log.debug("Retrieving Caches for Container {}", container.getName());
1411 map = clusterContainerService.getCache("frm.originalSwView");
1413 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1415 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1418 map = clusterContainerService.getCache("frm.installedSwView");
1420 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1422 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1425 map = clusterContainerService.getCache("frm.inactiveFlows");
1427 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1429 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1432 map = clusterContainerService.getCache("frm.nodeFlows");
1434 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1436 log.error("Retrieval of cache failed for Container {}", container.getName());
1439 map = clusterContainerService.getCache("frm.groupFlows");
1441 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1443 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1446 map = clusterContainerService.getCache("frm.staticFlows");
1448 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1450 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1453 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1455 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1457 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1460 map = clusterContainerService.getCache("frm.portGroupConfigs");
1462 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1464 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1467 map = clusterContainerService.getCache("frm.portGroupData");
1469 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1471 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1474 map = clusterContainerService.getCache("frm.TSPolicies");
1476 TSPolicies = (ConcurrentMap<String, Object>) map;
1478 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1481 map = clusterContainerService.getCache(WORKORDERCACHE);
1483 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1485 log.error("Retrieval of " + WORKORDERCACHE + " cache failed for Container {}", container.getName());
1488 map = clusterContainerService.getCache(WORKSTATUSCACHE);
1490 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1492 log.error("Retrieval of " + WORKSTATUSCACHE + " cache failed for Container {}", container.getName());
1496 private boolean flowConfigExists(FlowConfig config) {
1497 // Flow name has to be unique on per node id basis
1498 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1499 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1507 public Status addStaticFlow(FlowConfig config) {
1508 // Configuration object validation
1509 Status status = config.validate(container);
1510 if (!status.isSuccess()) {
1511 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1512 String error = "Invalid Configuration (" + status.getDescription() + ")";
1513 config.setStatus(error);
1514 return new Status(StatusCode.BADREQUEST, error);
1516 return addStaticFlowInternal(config, false);
1520 * Private method to add a static flow configuration which does not run any
1521 * validation on the passed FlowConfig object. If restore is set to true,
1522 * configuration is stored in configuration database regardless the
1523 * installation on the network node was successful. This is useful at boot
1524 * when static flows are present in startup configuration and are read
1525 * before the switches connects.
1528 * The static flow configuration
1530 * if true, the configuration is stored regardless the
1531 * installation on the network node was successful
1532 * @return The status of this request
1534 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1535 boolean multipleFlowPush = false;
1538 config.setStatus(SUCCESS);
1541 if (flowConfigExists(config)) {
1542 error = "Entry with this name on specified switch already exists";
1543 log.warn("Entry with this name on specified switch already exists: {}", config);
1544 config.setStatus(error);
1545 return new Status(StatusCode.CONFLICT, error);
1548 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1549 for (String portGroupName : portGroupConfigs.keySet()) {
1550 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1551 multipleFlowPush = true;
1555 if (!multipleFlowPush) {
1556 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1557 error = "Invalid Configuration (Invalid PortGroup Name)";
1558 config.setStatus(error);
1559 return new Status(StatusCode.BADREQUEST, error);
1564 * If requested program the entry in hardware first before updating the
1567 if (!multipleFlowPush) {
1569 if (config.installInHw()) {
1570 FlowEntry entry = config.getFlowEntry();
1571 status = this.installFlowEntry(entry);
1572 if (!status.isSuccess()) {
1573 config.setStatus(status.getDescription());
1582 * When the control reaches this point, either of the following
1583 * conditions is true 1. This is a single entry configuration (non
1584 * PortGroup) and the hardware installation is successful 2. This is a
1585 * multiple entry configuration (PortGroup) and hardware installation is
1586 * NOT done directly on this event. 3. The User prefers to retain the
1587 * configuration in Controller and skip hardware installation.
1589 * Hence it is safe to update the StaticFlow DB at this point.
1591 * Note : For the case of PortGrouping, it is essential to have this DB
1592 * populated before the PortGroupListeners can query for the DB
1593 * triggered using portGroupChanged event...
1595 Integer ordinal = staticFlowsOrdinal.get(0);
1596 staticFlowsOrdinal.put(0, ++ordinal);
1597 staticFlows.put(ordinal, config);
1599 if (multipleFlowPush) {
1600 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1601 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1602 if (existingData != null) {
1603 portGroupChanged(pgconfig, existingData, true);
1606 return new Status(StatusCode.SUCCESS);
1609 private void addStaticFlowsToSwitch(Node node) {
1610 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1611 FlowConfig config = entry.getValue();
1612 if (config.isPortGroupEnabled()) {
1615 if (config.getNode().equals(node)) {
1616 if (config.installInHw() && !config.getStatus().equals(SUCCESS)) {
1617 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1618 config.setStatus(status.getDescription());
1622 // Update cluster cache
1623 refreshClusterStaticFlowsStatus(node);
1626 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1627 log.trace("Updating Static Flow configs on node down: {}", node);
1629 List<Integer> toRemove = new ArrayList<Integer>();
1630 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1632 FlowConfig config = entry.getValue();
1634 if (config.isPortGroupEnabled()) {
1638 if (config.installInHw() && config.getNode().equals(node)) {
1639 if (config.isInternalFlow()) {
1640 // Take note of this controller generated static flow
1641 toRemove.add(entry.getKey());
1643 config.setStatus(NODEDOWN);
1647 // Remove controller generated static flows for this node
1648 for (Integer index : toRemove) {
1649 staticFlows.remove(index);
1651 // Update cluster cache
1652 refreshClusterStaticFlowsStatus(node);
1656 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1657 log.trace("Updating Static Flow configs on container mode change: {}", update);
1659 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1660 FlowConfig config = entry.getValue();
1661 if (config.isPortGroupEnabled()) {
1664 if (config.installInHw() && !config.isInternalFlow()) {
1667 config.setStatus("Removed from node because in container mode");
1670 config.setStatus(SUCCESS);
1676 // Update cluster cache
1677 refreshClusterStaticFlowsStatus(null);
1681 public Status removeStaticFlow(FlowConfig config) {
1683 * No config.isInternal() check as NB does not take this path and GUI
1684 * cannot issue a delete on an internal generated flow. We need this
1685 * path to be accessible when switch mode is changed from proactive to
1686 * reactive, so that we can remove the internal generated LLDP and ARP
1690 // Look for the target configuration entry
1692 FlowConfig target = null;
1693 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1694 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1695 key = entry.getKey();
1696 target = entry.getValue();
1700 if (target == null) {
1701 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1704 // Program the network node
1705 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1707 // Update configuration database if programming was successful
1708 if (status.isSuccess()) {
1709 staticFlows.remove(key);
1716 public Status removeStaticFlow(String name, Node node) {
1717 // Look for the target configuration entry
1719 FlowConfig target = null;
1720 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1721 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1722 key = mapEntry.getKey();
1723 target = mapEntry.getValue();
1727 if (target == null) {
1728 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1731 // Validity check for api3 entry point
1732 if (target.isInternalFlow()) {
1733 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1734 String logMsg = msg + ": {}";
1735 log.warn(logMsg, name);
1736 return new Status(StatusCode.NOTACCEPTABLE, msg);
1739 if (target.isPortGroupEnabled()) {
1740 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1741 String logMsg = msg + ": {}";
1742 log.warn(logMsg, name);
1743 return new Status(StatusCode.NOTACCEPTABLE, msg);
1746 // Program the network node
1747 Status status = this.removeEntry(target.getFlowEntry(), false);
1749 // Update configuration database if programming was successful
1750 if (status.isSuccess()) {
1751 staticFlows.remove(key);
1758 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1759 // Validity check for api3 entry point
1760 if (newFlowConfig.isInternalFlow()) {
1761 String msg = "Invalid operation: Controller generated flow cannot be modified";
1762 String logMsg = msg + ": {}";
1763 log.warn(logMsg, newFlowConfig);
1764 return new Status(StatusCode.NOTACCEPTABLE, msg);
1768 Status status = newFlowConfig.validate(container);
1769 if (!status.isSuccess()) {
1770 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1771 newFlowConfig.setStatus(msg);
1772 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1773 return new Status(StatusCode.BADREQUEST, msg);
1776 FlowConfig oldFlowConfig = null;
1777 Integer index = null;
1778 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1779 FlowConfig entry = mapEntry.getValue();
1780 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1781 oldFlowConfig = entry;
1782 index = mapEntry.getKey();
1787 if (oldFlowConfig == null) {
1788 String msg = "Attempt to modify a non existing static flow";
1789 String logMsg = msg + ": {}";
1790 log.warn(logMsg, newFlowConfig);
1791 return new Status(StatusCode.NOTFOUND, msg);
1794 // Do not attempt to reinstall the flow, warn user
1795 if (newFlowConfig.equals(oldFlowConfig)) {
1796 String msg = "No modification detected";
1797 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1798 return new Status(StatusCode.SUCCESS, msg);
1801 // If flow is installed, program the network node
1802 status = new Status(StatusCode.SUCCESS, "Saved in config");
1803 if (oldFlowConfig.installInHw()) {
1804 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1807 // Update configuration database if programming was successful
1808 if (status.isSuccess()) {
1809 newFlowConfig.setStatus(status.getDescription());
1810 staticFlows.put(index, newFlowConfig);
1817 public Status toggleStaticFlowStatus(String name, Node node) {
1818 return toggleStaticFlowStatus(getStaticFlow(name, node));
1822 public Status toggleStaticFlowStatus(FlowConfig config) {
1823 if (config == null) {
1824 String msg = "Invalid request: null flow config";
1826 return new Status(StatusCode.BADREQUEST, msg);
1828 // Validity check for api3 entry point
1829 if (config.isInternalFlow()) {
1830 String msg = "Invalid operation: Controller generated flow cannot be modified";
1831 String logMsg = msg + ": {}";
1832 log.warn(logMsg, config);
1833 return new Status(StatusCode.NOTACCEPTABLE, msg);
1836 // Find the config entry
1838 FlowConfig target = null;
1839 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1840 FlowConfig conf = entry.getValue();
1841 if (conf.isByNameAndNodeIdEqual(config)) {
1842 key = entry.getKey();
1847 if (target != null) {
1848 Status status = target.validate(container);
1849 if (!status.isSuccess()) {
1850 log.warn(status.getDescription());
1853 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1854 .installFlowEntry(target.getFlowEntry());
1855 if (status.isSuccess()) {
1856 // Update Configuration database
1857 target.setStatus(SUCCESS);
1858 target.toggleInstallation();
1859 staticFlows.put(key, target);
1864 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1868 * Reinsert all static flows entries in the cache to force cache updates in
1869 * the cluster. This is useful when only some parameters were changed in the
1870 * entries, like the status.
1873 * The node for which the static flow configurations have to be
1874 * refreshed. If null, all nodes static flows will be refreshed.
1876 private void refreshClusterStaticFlowsStatus(Node node) {
1877 // Refresh cluster cache
1878 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1879 if (node == null || entry.getValue().getNode().equals(node)) {
1880 staticFlows.put(entry.getKey(), entry.getValue());
1886 * Uninstall all the non-internal Flow Entries present in the software view.
1887 * If requested, a copy of each original flow entry will be stored in the
1888 * inactive list so that it can be re-applied when needed (This is typically
1889 * the case when running in the default container and controller moved to
1890 * container mode) NOTE WELL: The routine as long as does a bulk change will
1891 * operate only on the entries for nodes locally attached so to avoid
1892 * redundant operations initiated by multiple nodes
1894 * @param preserveFlowEntries
1895 * if true, a copy of each original entry is stored in the
1898 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1899 log.info("Uninstalling all non-internal flows");
1901 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1903 // Store entries / create target list
1904 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1905 FlowEntryInstall flowEntries = mapEntry.getValue();
1906 // Skip internal generated static flows
1907 if (!flowEntries.isInternal()) {
1908 toRemove.add(flowEntries);
1909 // Store the original entries if requested
1910 if (preserveFlowEntries) {
1911 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1916 // Now remove the entries
1917 for (FlowEntryInstall flowEntryHw : toRemove) {
1918 Node n = flowEntryHw.getNode();
1919 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
1920 Status status = this.removeEntryInternal(flowEntryHw, false);
1921 if (!status.isSuccess()) {
1922 log.warn("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1925 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
1932 * Re-install all the Flow Entries present in the inactive list The inactive
1933 * list will be empty at the end of this call This function is called on the
1934 * default container instance of FRM only when the last container is deleted
1936 private void reinstallAllFlowEntries() {
1937 log.info("Reinstalling all inactive flows");
1939 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1940 this.addEntry(flowEntry, false);
1943 // Empty inactive list in any case
1944 inactiveFlows.clear();
1948 public List<FlowConfig> getStaticFlows() {
1949 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1952 // TODO: need to come out with a better algorithm for maintaining the order
1953 // of the configuration entries
1954 // with actual one, index associated to deleted entries cannot be reused and
1956 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1957 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1958 for (int i = 0; i <= maxKey; i++) {
1959 FlowConfig entry = flowMap.get(i);
1960 if (entry != null) {
1961 orderedList.add(entry);
1968 public FlowConfig getStaticFlow(String name, Node node) {
1969 ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
1971 return entry.getValue();
1977 public List<FlowConfig> getStaticFlows(Node node) {
1978 List<FlowConfig> list = new ArrayList<FlowConfig>();
1979 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1980 if (entry.getValue().onNode(node)) {
1981 list.add(entry.getValue());
1988 public List<String> getStaticFlowNamesForNode(Node node) {
1989 List<String> list = new ArrayList<String>();
1990 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1991 if (entry.getValue().onNode(node)) {
1992 list.add(entry.getValue().getName());
1999 public List<Node> getListNodeWithConfiguredFlows() {
2000 Set<Node> set = new HashSet<Node>();
2001 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2002 set.add(entry.getValue().getNode());
2004 return new ArrayList<Node>(set);
2007 @SuppressWarnings("unchecked")
2008 private void loadFlowConfiguration() {
2009 ObjectReader objReader = new ObjectReader();
2010 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2013 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2016 if (pgConfig != null) {
2017 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2018 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2022 if (confList == null) {
2027 for (Integer key : confList.keySet()) {
2028 if (key.intValue() > maxKey) {
2029 maxKey = key.intValue();
2033 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2034 addStaticFlowInternal(conf, true);
2039 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2040 return ois.readObject();
2044 public Status saveConfig() {
2045 return saveConfigInternal();
2048 private Status saveConfigInternal() {
2049 ObjectWriter objWriter = new ObjectWriter();
2050 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2051 for (Integer ordinal : staticFlows.keySet()) {
2052 FlowConfig config = staticFlows.get(ordinal);
2053 // Do not save dynamic and controller generated static flows
2054 if (config.isDynamic() || config.isInternalFlow()) {
2057 nonDynamicFlows.put(ordinal, config);
2059 objWriter.write(nonDynamicFlows, frmFileName);
2060 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2061 return new Status(StatusCode.SUCCESS, null);
2065 public void subnetNotify(Subnet sub, boolean add) {
2068 private void installImplicitARPReplyPunt(Node node) {
2074 List<String> puntAction = new ArrayList<String>();
2075 puntAction.add(ActionType.CONTROLLER.toString());
2077 FlowConfig allowARP = new FlowConfig();
2078 allowARP.setInstallInHw(true);
2079 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
2080 allowARP.setPriority("500");
2081 allowARP.setNode(node);
2082 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2083 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
2084 allowARP.setActions(puntAction);
2085 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
2091 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2094 * This method can be called from within the OSGi framework context,
2095 * given the programming operation can take sometime, it not good
2096 * pratice to have in it's context operations that can take time,
2097 * hence moving off to a different thread for async processing.
2099 private ExecutorService executor;
2101 public void modeChangeNotify(final Node node, final boolean proactive) {
2102 Callable<Status> modeChangeCallable = new Callable<Status>() {
2104 public Status call() throws Exception {
2105 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2107 List<String> puntAction = new ArrayList<String>();
2108 puntAction.add(ActionType.CONTROLLER.toString());
2110 FlowConfig allowARP = new FlowConfig();
2111 allowARP.setInstallInHw(true);
2112 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2113 allowARP.setPriority("1");
2114 allowARP.setNode(node);
2115 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2117 allowARP.setActions(puntAction);
2118 defaultConfigs.add(allowARP);
2120 FlowConfig allowLLDP = new FlowConfig();
2121 allowLLDP.setInstallInHw(true);
2122 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2123 allowLLDP.setPriority("1");
2124 allowLLDP.setNode(node);
2125 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2127 allowLLDP.setActions(puntAction);
2128 defaultConfigs.add(allowLLDP);
2130 List<String> dropAction = new ArrayList<String>();
2131 dropAction.add(ActionType.DROP.toString());
2133 FlowConfig dropAllConfig = new FlowConfig();
2134 dropAllConfig.setInstallInHw(true);
2135 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2136 + FlowConfig.INTERNALSTATICFLOWEND);
2137 dropAllConfig.setPriority("0");
2138 dropAllConfig.setNode(node);
2139 dropAllConfig.setActions(dropAction);
2140 defaultConfigs.add(dropAllConfig);
2142 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2143 for (FlowConfig fc : defaultConfigs) {
2144 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2145 if (status.isSuccess()) {
2146 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2148 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2152 return new Status(StatusCode.SUCCESS);
2157 * Execute the work outside the caller context, this could be an
2158 * expensive operation and we don't want to block the caller for it.
2160 this.executor.submit(modeChangeCallable);
2164 * Remove from the databases all the flows installed on the node
2168 private void cleanDatabaseForNode(Node node) {
2169 log.info("Cleaning Flow database for Node {}", node);
2170 if (nodeFlows.containsKey(node)) {
2171 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2173 for (FlowEntryInstall entry : toRemove) {
2174 updateLocalDatabase(entry, false);
2179 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2184 Match match = flow.getMatch();
2185 if (match.isPresent(MatchType.IN_PORT)) {
2186 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2187 if (matchPort.equals(nc)) {
2191 List<Action> actionsList = flow.getActions();
2192 if (actionsList != null) {
2193 for (Action action : actionsList) {
2194 if (action instanceof Output) {
2195 NodeConnector actionPort = ((Output) action).getPort();
2196 if (actionPort.equals(nc)) {
2206 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2207 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2211 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2212 boolean updateStaticFlowCluster = false;
2218 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2219 if (config != null) {
2220 switch (config.getValue()) {
2221 case Config.ADMIN_DOWN:
2222 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2223 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2225 case Config.ADMIN_UP:
2226 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2227 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2229 case Config.ADMIN_UNDEF:
2236 // This is the case where a switch port is removed from the SDN agent space
2237 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2238 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2244 if (updateStaticFlowCluster) {
2245 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2250 * It goes through the static flows configuration, it identifies the ones
2251 * which have the specified node connector as input or output port and
2252 * install them on the network node if they are marked to be installed in
2253 * hardware and their status shows they were not installed yet
2255 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2256 boolean updated = false;
2257 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2258 for (FlowConfig flowConfig : flowConfigForNode) {
2259 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2260 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(SUCCESS)) {
2261 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2262 if (!status.isSuccess()) {
2263 flowConfig.setStatus(status.getDescription());
2265 flowConfig.setStatus(SUCCESS);
2275 * Remove from the network node all the flows which have the specified node
2276 * connector as input or output port. If any of the flow entry is a static
2277 * flow, it updates the correspondent configuration.
2279 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2280 boolean updated = false;
2281 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2282 if (nodeFlowEntries == null) {
2285 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2286 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2287 Status status = this.removeEntryInternal(fei, true);
2288 if (!status.isSuccess()) {
2292 * If the flow entry is a static flow, then update its
2295 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2296 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2297 if (flowConfig != null) {
2298 flowConfig.setStatus(PORTREMOVED);
2307 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2308 FlowConfig derivedFlow = new FlowConfig(original);
2309 derivedFlow.setDynamic(true);
2310 derivedFlow.setPortGroup(null);
2311 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2312 derivedFlow.setIngressPort(port + "");
2316 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2317 for (FlowConfig staticFlow : staticFlows.values()) {
2318 if (staticFlow.getPortGroup() == null) {
2321 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2322 for (Short port : data.getPorts()) {
2323 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2324 addStaticFlowInternal(derivedFlow, false);
2330 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2331 for (FlowConfig staticFlow : staticFlows.values()) {
2332 if (staticFlow.getPortGroup() == null) {
2335 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2336 for (Short port : data.getPorts()) {
2337 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2338 removeStaticFlow(derivedFlow);
2345 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2346 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2347 Map<Node, PortGroup> existingData = portGroupData.get(config);
2348 if (existingData != null) {
2349 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2350 PortGroup existingPortGroup = existingData.get(entry.getKey());
2351 if (existingPortGroup == null) {
2353 existingData.put(entry.getKey(), entry.getValue());
2354 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2358 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2359 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2361 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2362 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2368 portGroupData.put(config, data);
2369 for (Node swid : data.keySet()) {
2370 addPortGroupFlows(config, swid, data.get(swid));
2377 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2378 PortGroupConfig config = portGroupConfigs.get(name);
2379 if (config != null) {
2383 if ((portGroupProvider == null) && !restore) {
2386 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2390 config = new PortGroupConfig(name, regex);
2391 portGroupConfigs.put(name, config);
2392 if (portGroupProvider != null) {
2393 portGroupProvider.createPortGroupConfig(config);
2399 public boolean delPortGroupConfig(String name) {
2400 PortGroupConfig config = portGroupConfigs.get(name);
2401 if (config == null) {
2405 if (portGroupProvider != null) {
2406 portGroupProvider.deletePortGroupConfig(config);
2408 portGroupConfigs.remove(name);
2412 private void usePortGroupConfig(String name) {
2413 PortGroupConfig config = portGroupConfigs.get(name);
2414 if (config == null) {
2417 if (portGroupProvider != null) {
2418 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2419 portGroupData.put(config, data);
2424 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2425 return portGroupConfigs;
2428 public boolean isPortGroupSupported() {
2429 if (portGroupProvider == null) {
2435 public void setIContainer(IContainer s) {
2439 public void unsetIContainer(IContainer s) {
2440 if (this.container == s) {
2441 this.container = null;
2446 public PortGroupProvider getPortGroupProvider() {
2447 return portGroupProvider;
2450 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2451 this.portGroupProvider = null;
2454 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2455 this.portGroupProvider = portGroupProvider;
2456 portGroupProvider.registerPortGroupChange(this);
2457 for (PortGroupConfig config : portGroupConfigs.values()) {
2458 portGroupProvider.createPortGroupConfig(config);
2462 public void setFrmAware(IForwardingRulesManagerAware obj) {
2463 this.frmAware.add(obj);
2466 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2467 this.frmAware.remove(obj);
2470 void setClusterContainerService(IClusterContainerServices s) {
2471 log.debug("Cluster Service set");
2472 this.clusterContainerService = s;
2475 void unsetClusterContainerService(IClusterContainerServices s) {
2476 if (this.clusterContainerService == s) {
2477 log.debug("Cluster Service removed!");
2478 this.clusterContainerService = null;
2482 private String getContainerName() {
2483 if (container == null) {
2484 return GlobalConstants.DEFAULT.toString();
2486 return container.getName();
2490 * Function called by the dependency manager when all the required
2491 * dependencies are satisfied
2495 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2496 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2498 inContainerMode = false;
2500 if (portGroupProvider != null) {
2501 portGroupProvider.registerPortGroupChange(this);
2506 registerWithOSGIConsole();
2509 * If we are not the first cluster node to come up, do not initialize
2510 * the static flow entries ordinal
2512 if (staticFlowsOrdinal.size() == 0) {
2513 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2516 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2518 // Initialize the event handler thread
2519 frmEventHandler = new Thread(new Runnable() {
2524 final FRMEvent event = pendingEvents.take();
2525 if (event == null) {
2526 log.warn("Dequeued null event");
2529 log.trace("Dequeued {} event", event.getClass().getSimpleName());
2530 if (event instanceof NodeUpdateEvent) {
2531 NodeUpdateEvent update = (NodeUpdateEvent) event;
2532 Node node = update.getNode();
2533 switch (update.getUpdateType()) {
2535 addStaticFlowsToSwitch(node);
2538 cleanDatabaseForNode(node);
2539 updateStaticFlowConfigsOnNodeDown(node);
2543 } else if (event instanceof ErrorReportedEvent) {
2544 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2545 processErrorEvent(errEvent);
2546 } else if (event instanceof WorkOrderEvent) {
2548 * Take care of handling the remote Work request
2550 Runnable r = new Runnable() {
2553 WorkOrderEvent work = (WorkOrderEvent) event;
2554 FlowEntryDistributionOrder fe = work.getFe();
2556 logsync.trace("Executing the workOrder {}", fe);
2557 Status gotStatus = null;
2558 FlowEntryInstall feiCurrent = fe.getEntry();
2559 FlowEntryInstall feiNew = workOrder.get(fe);
2560 switch (fe.getUpType()) {
2562 gotStatus = addEntriesInternal(feiCurrent, false);
2565 gotStatus = modifyEntryInternal(feiCurrent, feiNew, false);
2568 gotStatus = removeEntryInternal(feiCurrent, false);
2572 workOrder.remove(fe);
2574 "The workOrder has been executed and now the status is being returned {}", fe);
2576 workStatus.put(fe, gotStatus);
2578 log.warn("Not expected null WorkOrder", work);
2582 if(executor != null) {
2583 executor.execute(r);
2585 } else if (event instanceof WorkStatusCleanup) {
2587 * Take care of handling the remote Work request
2589 WorkStatusCleanup work = (WorkStatusCleanup) event;
2590 FlowEntryDistributionOrder fe = work.getFe();
2592 logsync.trace("The workStatus {} is being removed", fe);
2593 workStatus.remove(fe);
2595 log.warn("Not expected null WorkStatus", work);
2597 } else if (event instanceof ContainerFlowChangeEvent) {
2599 * Whether it is an addition or removal, we have to
2600 * recompute the merged flows entries taking into
2601 * account all the current container flows because
2602 * flow merging is not an injective function
2604 updateFlowsContainerFlow();
2606 log.warn("Dequeued unknown event {}", event.getClass()
2609 } catch (InterruptedException e) {
2610 // clear pending events
2611 pendingEvents.clear();
2615 }, "FRM EventHandler Collector");
2619 * Function called by the dependency manager when at least one dependency
2620 * become unsatisfied or when the component is shutting down because for
2621 * example bundle is being stopped.
2625 // Interrupt the thread
2626 frmEventHandler.interrupt();
2627 // Clear the pendingEvents queue
2628 pendingEvents.clear();
2630 workMonitor.clear();
2634 * Function called by dependency manager after "init ()" is called and after
2635 * the services provided by the class are registered in the service registry
2639 // Initialize graceful stop flag
2642 // Allocate the executor service
2643 this.executor = Executors.newFixedThreadPool(maxPoolSize);
2645 // Start event handler thread
2646 frmEventHandler.start();
2649 * Read startup and build database if we have not already gotten the
2650 * configurations synced from another node
2652 if (staticFlows.isEmpty()) {
2653 loadFlowConfiguration();
2658 * Function called by the dependency manager before the services exported by
2659 * the component are unregistered, this will be followed by a "destroy ()"
2664 uninstallAllFlowEntries(false);
2665 // Shutdown executor
2666 this.executor.shutdownNow();
2667 // Now walk all the workMonitor and wake up the one sleeping because
2668 // destruction is happening
2669 for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2670 FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2675 public void setFlowProgrammerService(IFlowProgrammerService service) {
2676 this.programmer = service;
2679 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2680 if (this.programmer == service) {
2681 this.programmer = null;
2685 public void setSwitchManager(ISwitchManager switchManager) {
2686 this.switchManager = switchManager;
2689 public void unsetSwitchManager(ISwitchManager switchManager) {
2690 if (this.switchManager == switchManager) {
2691 this.switchManager = null;
2696 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2697 if (!container.getName().equals(containerName)) {
2703 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2704 if (!container.getName().equals(containerName)) {
2707 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2708 container.getName(), t, current);
2709 ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2710 pendingEvents.offer(ev);
2714 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2715 if (!container.getName().equals(containerName)) {
2719 boolean updateStaticFlowCluster = false;
2723 log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2724 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2727 log.trace("Port {} was added to container: reinstall interested flows", nc);
2728 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2736 if (updateStaticFlowCluster) {
2737 refreshClusterStaticFlowsStatus(nc.getNode());
2742 public void containerModeUpdated(UpdateType update) {
2743 // Only default container instance reacts on this event
2744 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2750 * Controller is moving to container mode. We are in the default
2751 * container context, we need to remove all our non-internal flows
2752 * to prevent any container isolation breakage. We also need to
2753 * preserve our flow so that they can be re-installed if we move
2754 * back to non container mode (no containers).
2756 this.inContainerMode = true;
2757 this.uninstallAllFlowEntries(true);
2760 this.inContainerMode = false;
2761 this.reinstallAllFlowEntries();
2766 // Update our configuration DB
2767 updateStaticFlowConfigsOnContainerModeChange(update);
2770 protected abstract class FRMEvent {
2774 private class NodeUpdateEvent extends FRMEvent {
2775 private final Node node;
2776 private final UpdateType update;
2778 public NodeUpdateEvent(UpdateType update, Node node) {
2779 this.update = update;
2783 public UpdateType getUpdateType() {
2787 public Node getNode() {
2792 private class ErrorReportedEvent extends FRMEvent {
2793 private final long rid;
2794 private final Node node;
2795 private final Object error;
2797 public ErrorReportedEvent(long rid, Node node, Object error) {
2803 public long getRequestId() {
2807 public Object getError() {
2811 public Node getNode() {
2816 private class WorkOrderEvent extends FRMEvent {
2817 private FlowEntryDistributionOrder fe;
2818 private FlowEntryInstall newEntry;
2824 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2826 this.newEntry = newEntry;
2832 public FlowEntryDistributionOrder getFe() {
2837 * @return the newEntry
2839 public FlowEntryInstall getNewEntry() {
2843 private class ContainerFlowChangeEvent extends FRMEvent {
2844 private final ContainerFlow previous;
2845 private final ContainerFlow current;
2846 private final UpdateType type;
2848 public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2849 this.previous = previous;
2850 this.current = current;
2854 public ContainerFlow getPrevious() {
2855 return this.previous;
2858 public ContainerFlow getCurrent() {
2859 return this.current;
2862 public UpdateType getType() {
2868 private class WorkStatusCleanup extends FRMEvent {
2869 private FlowEntryDistributionOrder fe;
2874 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2881 public FlowEntryDistributionOrder getFe() {
2890 public String getHelp() {
2891 StringBuffer help = new StringBuffer();
2892 help.append("---FRM Matrix Application---\n");
2893 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2894 help.append("\t addMatrixConfig <name> <regex>\n");
2895 help.append("\t delMatrixConfig <name>\n");
2896 help.append("\t useMatrixConfig <name>\n");
2897 return help.toString();
2900 public void _printMatrixData(CommandInterpreter ci) {
2901 ci.println("Configs : ");
2902 ci.println("---------");
2903 ci.println(portGroupConfigs);
2905 ci.println("Data : ");
2906 ci.println("------");
2907 ci.println(portGroupData);
2910 public void _addMatrixConfig(CommandInterpreter ci) {
2911 String name = ci.nextArgument();
2912 String regex = ci.nextArgument();
2913 addPortGroupConfig(name, regex, false);
2916 public void _delMatrixConfig(CommandInterpreter ci) {
2917 String name = ci.nextArgument();
2918 delPortGroupConfig(name);
2921 public void _useMatrixConfig(CommandInterpreter ci) {
2922 String name = ci.nextArgument();
2923 usePortGroupConfig(name);
2926 public void _arpPunt(CommandInterpreter ci) {
2927 String switchId = ci.nextArgument();
2928 long swid = HexEncode.stringToLong(switchId);
2929 Node node = NodeCreator.createOFNode(swid);
2930 installImplicitARPReplyPunt(node);
2933 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2935 String nodeId = ci.nextArgument();
2936 if (nodeId == null) {
2937 ci.print("Node id not specified");
2941 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2942 } catch (NumberFormatException e) {
2943 ci.print("Node id not a number");
2946 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2949 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2951 String nodeId = ci.nextArgument();
2952 if (nodeId == null) {
2953 ci.print("Node id not specified");
2957 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2958 } catch (NumberFormatException e) {
2959 ci.print("Node id not a number");
2962 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2965 private Flow getSampleFlow(Node node) throws UnknownHostException {
2966 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2967 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2968 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2969 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2970 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2971 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2972 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2973 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2974 short ethertype = EtherTypes.IPv4.shortValue();
2975 short vlan = (short) 27;
2978 byte proto = IPProtocols.TCP.byteValue();
2979 short src = (short) 55000;
2983 * Create a SAL Flow aFlow
2985 Match match = new Match();
2986 match.setField(MatchType.IN_PORT, port);
2987 match.setField(MatchType.DL_SRC, srcMac);
2988 match.setField(MatchType.DL_DST, dstMac);
2989 match.setField(MatchType.DL_TYPE, ethertype);
2990 match.setField(MatchType.DL_VLAN, vlan);
2991 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2992 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2993 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2994 match.setField(MatchType.NW_TOS, tos);
2995 match.setField(MatchType.NW_PROTO, proto);
2996 match.setField(MatchType.TP_SRC, src);
2997 match.setField(MatchType.TP_DST, dst);
2999 List<Action> actions = new ArrayList<Action>();
3000 actions.add(new Output(oport));
3001 actions.add(new PopVlan());
3002 actions.add(new Flood());
3003 actions.add(new Controller());
3004 return new Flow(match, actions);
3008 public Status saveConfiguration() {
3009 return saveConfig();
3012 public void _frmNodeFlows(CommandInterpreter ci) {
3013 String nodeId = ci.nextArgument();
3014 Node node = Node.fromString(nodeId);
3016 ci.println("frmNodeFlows <node> [verbose]");
3019 boolean verbose = false;
3020 String verboseCheck = ci.nextArgument();
3021 if (verboseCheck != null) {
3022 verbose = verboseCheck.equals("true");
3025 if (!nodeFlows.containsKey(node)) {
3028 // Dump per node database
3029 for (FlowEntryInstall entry : nodeFlows.get(node)) {
3031 ci.println(node + " " + installedSwView.get(entry).getFlowName());
3033 ci.println(node + " " + installedSwView.get(entry).toString());
3038 public void _frmGroupFlows(CommandInterpreter ci) {
3039 String group = ci.nextArgument();
3040 if (group == null) {
3041 ci.println("frmGroupFlows <group> [verbose]");
3044 boolean verbose = false;
3045 String verboseCheck = ci.nextArgument();
3046 if (verboseCheck != null) {
3047 verbose = verboseCheck.equalsIgnoreCase("true");
3050 if (!groupFlows.containsKey(group)) {
3053 // Dump per node database
3054 ci.println("Group " + group + ":\n");
3055 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
3057 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
3059 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
3064 public void _frmProcessErrorEvent(CommandInterpreter ci) throws UnknownHostException {
3067 String nodeId = ci.nextArgument();
3068 if (nodeId == null) {
3069 ci.print("Node id not specified");
3072 String requestId = ci.nextArgument();
3073 if (requestId == null) {
3074 ci.print("Request id not specified");
3078 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
3079 } catch (NumberFormatException e) {
3080 ci.print("Node id not a number");
3084 reqId = Long.parseLong(requestId);
3085 } catch (NumberFormatException e) {
3086 ci.print("Request id not a number");
3089 // null for error object is good enough for now
3090 ErrorReportedEvent event = new ErrorReportedEvent(reqId, node, null);
3091 this.processErrorEvent(event);
3095 public void flowRemoved(Node node, Flow flow) {
3096 log.trace("Received flow removed notification on {} for {}", node, flow);
3098 // For flow entry identification, only node, match and priority matter
3099 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
3100 FlowEntryInstall installedEntry = this.installedSwView.get(test);
3101 if (installedEntry == null) {
3102 log.trace("Entry is not known to us");
3106 // Update Static flow status
3108 FlowConfig target = null;
3109 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3110 FlowConfig conf = entry.getValue();
3111 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3112 key = entry.getKey();
3117 if (target != null) {
3118 // Update Configuration database
3119 target.toggleInstallation();
3120 target.setStatus(SUCCESS);
3121 staticFlows.put(key, target);
3124 // Update software views
3125 this.updateLocalDatabase(installedEntry, false);
3129 public void flowErrorReported(Node node, long rid, Object err) {
3130 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3131 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3134 private void processErrorEvent(ErrorReportedEvent event) {
3135 Node node = event.getNode();
3136 long rid = event.getRequestId();
3137 Object error = event.getError();
3138 String errorString = (error == null) ? "Not provided" : error.toString();
3140 * If this was for a flow install, remove the corresponding entry from
3141 * the software view. If it was a Looking for the rid going through the
3142 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3143 * mapping will have to be added in future
3145 FlowEntryInstall target = null;
3146 List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3147 // flowEntryInstallList could be null.
3149 if(flowEntryInstallList != null) {
3150 for (FlowEntryInstall index : flowEntryInstallList) {
3151 FlowEntryInstall entry = installedSwView.get(index);
3153 if (entry.getRequestId() == rid) {
3160 if (target != null) {
3161 // This was a flow install, update database
3162 this.updateLocalDatabase(target, false);
3163 // also update the config
3164 if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3165 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3166 // staticFlowEntry should never be null.
3167 // the null check is just an extra defensive check.
3168 if(staticFlowEntry != null) {
3169 staticFlows.remove(staticFlowEntry.getKey());
3175 if (frmAware != null) {
3176 synchronized (frmAware) {
3177 for (IForwardingRulesManagerAware frma : frmAware) {
3179 frma.requestFailed(rid, errorString);
3180 } catch (Exception e) {
3181 log.warn("Failed to notify {}", frma);
3189 public Status solicitStatusResponse(Node node, boolean blocking) {
3190 Status rv = new Status(StatusCode.INTERNALERROR);
3192 if (this.programmer != null) {
3194 rv = programmer.syncSendBarrierMessage(node);
3196 rv = programmer.asyncSendBarrierMessage(node);
3203 public void unsetIConnectionManager(IConnectionManager s) {
3204 if (s == this.connectionManager) {
3205 this.connectionManager = null;
3209 public void setIConnectionManager(IConnectionManager s) {
3210 this.connectionManager = s;
3214 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3221 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3224 * Local updates are of no interest
3228 if (cacheName.equals(WORKORDERCACHE)) {
3229 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3231 * This is the case of one workOrder becoming available, so we need
3232 * to dispatch the work to the appropriate handler
3234 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3235 FlowEntryInstall fei = fe.getEntry();
3239 Node n = fei.getNode();
3240 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3241 logsync.trace("workOrder for fe {} processed locally", fe);
3242 // I'm the controller in charge for the request, queue it for
3244 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3246 } else if (cacheName.equals(WORKSTATUSCACHE)) {
3247 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3249 * This is the case of one workOrder being completed and a status
3252 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3254 * Check if the order was initiated by this controller in that case
3255 * we need to actually look at the status returned
3257 if (fe.getRequestorController()
3258 .equals(clusterContainerService.getMyAddress())) {
3259 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3261 logsync.trace("workStatus response is for us {}", fe);
3262 // Signal we got the status
3263 fet.gotStatus(fe, workStatus.get(fe));
3264 pendingEvents.offer(new WorkStatusCleanup(fe));
3271 public void entryDeleted(Object key, String cacheName, boolean originLocal) {