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.containermanager.IContainerManager;
43 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
44 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
45 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
46 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
47 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
48 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
50 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
51 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
52 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
53 import org.opendaylight.controller.sal.action.Action;
54 import org.opendaylight.controller.sal.action.ActionType;
55 import org.opendaylight.controller.sal.action.Controller;
56 import org.opendaylight.controller.sal.action.Flood;
57 import org.opendaylight.controller.sal.action.Output;
58 import org.opendaylight.controller.sal.action.PopVlan;
59 import org.opendaylight.controller.sal.connection.ConnectionLocality;
60 import org.opendaylight.controller.sal.core.Config;
61 import org.opendaylight.controller.sal.core.ContainerFlow;
62 import org.opendaylight.controller.sal.core.IContainer;
63 import org.opendaylight.controller.sal.core.IContainerLocalListener;
64 import org.opendaylight.controller.sal.core.Node;
65 import org.opendaylight.controller.sal.core.NodeConnector;
66 import org.opendaylight.controller.sal.core.Property;
67 import org.opendaylight.controller.sal.core.UpdateType;
68 import org.opendaylight.controller.sal.flowprogrammer.Flow;
69 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
70 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
71 import org.opendaylight.controller.sal.match.Match;
72 import org.opendaylight.controller.sal.match.MatchType;
73 import org.opendaylight.controller.sal.utils.EtherTypes;
74 import org.opendaylight.controller.sal.utils.GlobalConstants;
75 import org.opendaylight.controller.sal.utils.HexEncode;
76 import org.opendaylight.controller.sal.utils.IObjectReader;
77 import org.opendaylight.controller.sal.utils.IPProtocols;
78 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
79 import org.opendaylight.controller.sal.utils.NodeCreator;
80 import org.opendaylight.controller.sal.utils.ObjectReader;
81 import org.opendaylight.controller.sal.utils.ObjectWriter;
82 import org.opendaylight.controller.sal.utils.Status;
83 import org.opendaylight.controller.sal.utils.StatusCode;
84 import org.opendaylight.controller.switchmanager.IInventoryListener;
85 import org.opendaylight.controller.switchmanager.ISwitchManager;
86 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
87 import org.opendaylight.controller.switchmanager.Subnet;
88 import org.osgi.framework.BundleContext;
89 import org.osgi.framework.FrameworkUtil;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
94 * Class that manages forwarding rule installation and removal per container of
95 * the network. It also maintains the central repository of all the forwarding
96 * rules installed on the network nodes.
98 public class ForwardingRulesManager implements
99 IForwardingRulesManager,
100 PortGroupChangeListener,
101 IContainerLocalListener,
103 IConfigurationContainerAware,
106 ICacheUpdateAware<Object,Object>,
108 IFlowProgrammerListener {
110 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
111 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
112 private static final String PORTREMOVED = "Port removed";
113 private static final String NODEDOWN = "Node is Down";
114 private static final String INVALID_FLOW_ENTRY = "Invalid FlowEntry";
115 private String frmFileName;
116 private String portGroupFileName;
117 private ConcurrentMap<Integer, FlowConfig> staticFlows;
118 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
119 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
120 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
121 private ConcurrentMap<String, Object> TSPolicies;
122 private IContainerManager containerManager;
123 private boolean inContainerMode; // being used by global instance only
124 protected boolean stopping;
127 * Flow database. It's the software view of what was requested to install
128 * and what is installed on the switch. It is indexed by the entry itself.
129 * The entry's hashcode resumes the network node index, the flow's priority
130 * and the flow's match. The value element is a class which contains the
131 * flow entry pushed by the applications modules and the respective
132 * container flow merged version. In absence of container flows, the two
133 * flow entries are the same.
135 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
136 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
138 * Per node and per group indexing
140 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
141 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
144 * Inactive flow list. This is for the global instance of FRM It will
145 * contain all the flow entries which were installed on the global container
146 * when the first container is created.
148 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
150 private IContainer container;
151 private Set<IForwardingRulesManagerAware> frmAware =
152 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
153 private PortGroupProvider portGroupProvider;
154 private IFlowProgrammerService programmer;
155 private IClusterContainerServices clusterContainerService = null;
156 private ISwitchManager switchManager;
157 private Thread frmEventHandler;
158 protected BlockingQueue<FRMEvent> pendingEvents;
160 // Distributes FRM programming in the cluster
161 private IConnectionManager connectionManager;
164 * Name clustered caches used to support FRM entry distribution these are by
165 * necessity non-transactional as long as need to be able to synchronize
166 * states also while a transaction is in progress
168 static final String WORK_ORDER_CACHE = "frm.workOrder";
169 static final String WORK_STATUS_CACHE = "frm.workStatus";
172 * Data structure responsible for distributing the FlowEntryInstall requests
173 * in the cluster. The key value is entry that is being either Installed or
174 * Updated or Delete. The value field is the same of the key value in case
175 * of Installation or Deletion, it's the new entry in case of Modification,
176 * this because the clustering caches don't allow null values.
178 * The logic behind this data structure is that the controller that initiate
179 * the request will place the order here, someone will pick it and then will
180 * remove from this data structure because is being served.
182 * TODO: We need to have a way to cleanup this data structure if entries are
183 * not picked by anyone, which is always a case can happen especially on
184 * Node disconnect cases.
186 protected ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
189 * Data structure responsible for retrieving the results of the workOrder
190 * submitted to the cluster.
192 * The logic behind this data structure is that the controller that has
193 * executed the order will then place the result in workStatus signaling
194 * that there was a success or a failure.
196 * TODO: The workStatus entries need to have a lifetime associated in case
197 * of requestor controller leaving the cluster.
199 protected ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
202 * Local Map used to hold the Future which a caller can use to monitor for
205 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
206 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
209 * Max pool size for the executor
211 private static final int maxPoolSize = 10;
215 * Entry being installed/updated/removed
217 * New entry will be placed after the update operation. Valid
218 * only for UpdateType.CHANGED, null for all the other cases
221 * @return a Future object for monitoring the progress of the result, or
222 * null in case the processing should take place locally
224 private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
226 // A null entry it's an unexpected condition, anyway it's safe to keep
227 // the handling local
232 Node n = e.getNode();
233 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
234 // Create the work order and distribute it
235 FlowEntryDistributionOrder fe =
236 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
237 // First create the monitor job
238 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
239 logsync.trace("Node {} not local so sending fe {}", n, fe);
240 workMonitor.put(fe, ret);
241 if (t.equals(UpdateType.CHANGED)) {
242 // Then distribute the work
243 workOrder.put(fe, u);
245 // Then distribute the work
246 workOrder.put(fe, e);
248 logsync.trace("WorkOrder requested");
249 // Now create an Handle to monitor the execution of the operation
253 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
258 * Adds a flow entry onto the network node It runs various validity checks
259 * and derive the final container flows merged entries that will be
260 * attempted to be installed
263 * the original flow entry application requested to add
265 * the flag indicating if this is a asynchronous request
266 * @return the status of this request. In case of asynchronous call, it will
267 * contain the unique id assigned to this request
269 private Status addEntry(FlowEntry flowEntry, boolean async) {
272 if (flowEntry == null || flowEntry.getNode() == null) {
273 String logMsg = INVALID_FLOW_ENTRY + ": {}";
274 log.warn(logMsg, flowEntry);
275 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
279 * Derive the container flow merged entries to install In presence of N
280 * container flows, we may end up with N different entries to install...
282 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
284 // Container Flow conflict Check
285 if (toInstallList.isEmpty()) {
286 String msg = "Flow Entry conflicts with all Container Flows";
287 String logMsg = msg + ": {}";
288 log.warn(logMsg, flowEntry);
289 return new Status(StatusCode.CONFLICT, msg);
292 // Derive the list of entries good to be installed
293 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
294 for (FlowEntryInstall entry : toInstallList) {
295 // Conflict Check: Verify new entry would not overwrite existing
297 if (this.installedSwView.containsKey(entry)) {
298 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
299 log.trace("Aborting to install {}", entry);
302 toInstallSafe.add(entry);
305 // Declare failure if all the container flow merged entries clash with
307 if (toInstallSafe.size() == 0) {
308 String msg = "A flow with same match and priority exists on the target node";
309 String logMsg = msg + ": {}";
310 log.warn(logMsg, flowEntry);
311 return new Status(StatusCode.CONFLICT, msg);
314 // Try to install an entry at the time
315 Status error = new Status(null, null);
316 Status succeded = null;
317 boolean oneSucceded = false;
318 for (FlowEntryInstall installEntry : toInstallSafe) {
320 // Install and update database
321 Status ret = addEntriesInternal(installEntry, async);
323 if (ret.isSuccess()) {
326 * The first successful status response will be returned For the
327 * asynchronous call, we can discard the container flow
328 * complication for now and assume we will always deal with one
329 * flow only per request
334 log.trace("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
338 return (oneSucceded) ? succeded : error;
342 * Given a flow entry and the list of container flows, it returns the list
343 * of container flow merged flow entries good to be installed on this
344 * container. If the list of container flows is null or empty, the install
345 * entry list will contain only one entry, the original flow entry. If the
346 * flow entry is congruent with all the N container flows, then the output
347 * install entry list will contain N entries. If the output list is empty,
348 * it means the passed flow entry conflicts with all the container flows.
351 * The list of container flows
352 * @return the list of container flow merged entries good to be installed on
355 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
356 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
358 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
359 // No container flows => entry good to be installed unchanged
360 toInstallList.add(new FlowEntryInstall(request.clone(), null));
362 // Create the list of entries to be installed. If the flow entry is
363 // not congruent with any container flow, no install entries will be
365 for (ContainerFlow cFlow : container.getContainerFlows()) {
366 if (cFlow.allowsFlow(request.getFlow())) {
367 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
371 return toInstallList;
375 * Modify a flow entry with a new one It runs various validity check and
376 * derive the final container flows merged flow entries to work with
378 * @param currentFlowEntry
379 * @param newFlowEntry
381 * the flag indicating if this is a asynchronous request
382 * @return the status of this request. In case of asynchronous call, it will
383 * contain the unique id assigned to this request
385 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
389 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
390 || newFlowEntry.getNode() == null) {
391 String msg = "Modify: " + INVALID_FLOW_ENTRY;
392 String logMsg = msg + ": {} or {}";
393 log.warn(logMsg, currentFlowEntry, newFlowEntry);
394 return new Status(StatusCode.NOTACCEPTABLE, msg);
396 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
397 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
398 String msg = "Modify: Incompatible Flow Entries";
399 String logMsg = msg + ": {} and {}";
400 log.warn(logMsg, currentFlowEntry, newFlowEntry);
401 return new Status(StatusCode.NOTACCEPTABLE, msg);
405 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
406 String msg = "Modify skipped as flows are the same";
407 String logMsg = msg + ": {} and {}";
408 log.debug(logMsg, currentFlowEntry, newFlowEntry);
409 return new Status(StatusCode.SUCCESS, msg);
413 * Conflict Check: Verify the new entry would not conflict with an
414 * existing one. This is a loose check on the previous original flow
415 * entry requests. No check on the container flow merged flow entries
418 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
419 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
420 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
421 String logMsg = msg + ": {}";
422 log.warn(logMsg, currentFlowEntry);
423 return new Status(StatusCode.CONFLICT, msg);
426 // Derive the installed and toInstall entries
427 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
428 container.getContainerFlows());
429 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
431 if (toInstallList.isEmpty()) {
432 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
433 String logMsg = msg + ": {}";
434 log.warn(logMsg, newFlowEntry);
436 return new Status(StatusCode.CONFLICT, msg);
440 * If the two list sizes differ, it means the new flow entry does not
441 * satisfy the same number of container flows the current entry does.
442 * This is only possible when the new entry and current entry have
443 * different match. In this scenario the modification would ultimately
444 * be handled as a remove and add operations in the protocol plugin.
446 * Also, if any of the new flow entries would clash with an existing
447 * one, we cannot proceed with the modify operation, because it would
448 * fail for some entries and leave stale entries on the network node.
449 * Modify path can be taken only if it can be performed completely, for
452 * So, for the above two cases, to simplify, let's decouple the modify
453 * in: 1) remove current entries 2) install new entries
455 Status succeeded = null;
456 boolean decouple = false;
457 if (installedList.size() != toInstallList.size()) {
458 log.info("Modify: New flow entry does not satisfy the same "
459 + "number of container flows as the original entry does");
462 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
463 for (FlowEntryInstall installEntry : toInstallList) {
465 * Conflict Check: Verify the new entry would not overwrite another
468 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
469 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
470 log.info("Modify: new container flow merged flow entry clashes with existing flow");
473 toInstallSafe.add(installEntry);
478 // Remove current entries
479 for (FlowEntryInstall currEntry : installedList) {
480 this.removeEntryInternal(currEntry, async);
482 // Install new entries
483 for (FlowEntryInstall newEntry : toInstallSafe) {
484 succeeded = this.addEntriesInternal(newEntry, async);
488 * The two list have the same size and the entries to install do not
489 * clash with any existing flow on the network node. We assume here
490 * (and might be wrong) that the same container flows that were
491 * satisfied by the current entries are the same that are satisfied
492 * by the new entries. Let's take the risk for now.
494 * Note: modification has to be complete. If any entry modification
495 * fails, we need to stop, restore the already modified entries, and
498 Status retModify = null;
500 int size = toInstallList.size();
502 // Modify and update database
503 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
504 if (retModify.isSuccess()) {
510 // Check if uncompleted modify
512 log.warn("Unable to perform a complete modify for all the container flows merged entries");
513 // Restore original entries
516 log.info("Attempting to restore initial entries");
517 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
518 if (retExt.isSuccess()) {
524 // Fatal error, recovery failed
526 String msg = "Flow recovery failed ! Unrecoverable Error";
528 return new Status(StatusCode.INTERNALERROR, msg);
531 succeeded = retModify;
534 * The first successful status response will be returned. For the
535 * asynchronous call, we can discard the container flow complication for
536 * now and assume we will always deal with one flow only per request
542 * This is the function that modifies the final container flows merged
543 * entries on the network node and update the database. It expects that all
544 * the validity checks are passed
546 * @param currentEntries
549 * the flag indicating if this is a asynchronous request
550 * @return the status of this request. In case of asynchronous call, it will
551 * contain the unique id assigned to this request
553 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
554 FlowEntryDistributionOrderFutureTask futureStatus =
555 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
556 if (futureStatus != null) {
557 Status retStatus = new Status(StatusCode.UNDEFINED);
559 retStatus = futureStatus.get();
560 if (retStatus.getCode()
561 .equals(StatusCode.TIMEOUT)) {
562 // A timeout happened, lets cleanup the workMonitor
563 workMonitor.remove(futureStatus.getOrder());
565 } catch (InterruptedException e) {
567 } catch (ExecutionException e) {
572 // Modify the flow on the network node
573 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
574 .getFlow(), newEntries.getInstall()
575 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
576 .getFlow(), newEntries.getInstall()
579 if (!status.isSuccess()) {
580 log.trace("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
581 status.getDescription());
585 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
588 newEntries.setRequestId(status.getRequestId());
589 updateLocalDatabase(currentEntries, false);
590 updateLocalDatabase(newEntries, true);
597 * Remove a flow entry. If the entry is not present in the software view
598 * (entry or node not present), it return successfully
601 * the flow entry to remove
603 * the flag indicating if this is a asynchronous request
604 * @return the status of this request. In case of asynchronous call, it will
605 * contain the unique id assigned to this request
607 private Status removeEntry(FlowEntry flowEntry, boolean async) {
608 Status error = new Status(null, null);
611 if (flowEntry == null || flowEntry.getNode() == null) {
612 String logMsg = INVALID_FLOW_ENTRY + ": {}";
613 log.warn(logMsg, flowEntry);
614 return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY);
617 // Derive the container flows merged installed entries
618 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
620 Status succeeded = null;
621 boolean atLeastOneRemoved = false;
622 for (FlowEntryInstall entry : installedList) {
623 if (!installedSwView.containsKey(entry)) {
624 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
625 log.debug(logMsg, flowEntry);
626 if (installedList.size() == 1) {
627 // If we had only one entry to remove, we are done
628 return new Status(StatusCode.SUCCESS);
634 // Remove and update DB
635 Status ret = removeEntryInternal(entry, async);
637 if (!ret.isSuccess()) {
639 log.trace("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
640 if (installedList.size() == 1) {
641 // If we had only one entry to remove, this is fatal failure
646 atLeastOneRemoved = true;
651 * No worries if full removal failed. Consistency checker will take care
652 * of removing the stale entries later, or adjusting the software
653 * database if not in sync with hardware
655 return (atLeastOneRemoved) ? succeeded : error;
659 * This is the function that removes the final container flows merged entry
660 * from the network node and update the database. It expects that all the
661 * validity checks are passed
664 * the flow entry to remove
666 * the flag indicating if this is a asynchronous request
667 * @return the status of this request. In case of asynchronous call, it will
668 * contain the unique id assigned to this request
670 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
671 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
672 if (futureStatus != null) {
673 Status retStatus = new Status(StatusCode.UNDEFINED);
675 retStatus = futureStatus.get();
676 if (retStatus.getCode()
677 .equals(StatusCode.TIMEOUT)) {
678 // A timeout happened, lets cleanup the workMonitor
679 workMonitor.remove(futureStatus.getOrder());
681 } catch (InterruptedException e) {
683 } catch (ExecutionException e) {
688 // Mark the entry to be deleted (for CC just in case we fail)
692 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
693 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
696 if (!status.isSuccess()) {
697 log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", entry.getInstall(),
698 status.getDescription());
701 log.trace("Removed {}", entry.getInstall());
704 updateLocalDatabase(entry, false);
711 * This is the function that installs the final container flow merged entry
712 * on the network node and updates the database. It expects that all the
713 * validity and conflict checks are passed. That means it does not check
714 * whether this flow would conflict or overwrite an existing one.
717 * the flow entry to install
719 * the flag indicating if this is a asynchronous request
720 * @return the status of this request. In case of asynchronous call, it will
721 * contain the unique id assigned to this request
723 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
724 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
725 if (futureStatus != null) {
726 Status retStatus = new Status(StatusCode.UNDEFINED);
728 retStatus = futureStatus.get();
729 if (retStatus.getCode()
730 .equals(StatusCode.TIMEOUT)) {
731 // A timeout happened, lets cleanup the workMonitor
732 workMonitor.remove(futureStatus.getOrder());
734 } catch (InterruptedException e) {
736 } catch (ExecutionException e) {
741 // Install the flow on the network node
742 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
743 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
746 if (!status.isSuccess()) {
747 log.trace("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
748 status.getDescription());
752 log.trace("Added {}", entry.getInstall());
755 entry.setRequestId(status.getRequestId());
756 updateLocalDatabase(entry, true);
763 * Returns true if the flow conflicts with all the container's flows. This
764 * means that if the function returns true, the passed flow entry is
765 * congruent with at least one container flow, hence it is good to be
766 * installed on this container.
769 * @return true if flow conflicts with all the container flows, false
772 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
773 List<ContainerFlow> cFlowList = container.getContainerFlows();
775 // Validity check and avoid unnecessary computation
776 // Also takes care of default container where no container flows are
778 if (cFlowList == null || cFlowList.isEmpty()) {
782 for (ContainerFlow cFlow : cFlowList) {
783 if (cFlow.allowsFlow(flowEntry.getFlow())) {
784 // Entry is allowed by at least one container flow: good to go
791 private ConcurrentMap.Entry<Integer, FlowConfig> getStaticFlowEntry(String name, Node node) {
792 for (ConcurrentMap.Entry<Integer, FlowConfig> flowEntry : staticFlows.entrySet()) {
793 FlowConfig flowConfig = flowEntry.getValue();
794 if (flowConfig.isByNameAndNodeIdEqual(name, node)) {
801 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
802 // Update the software view
803 updateSwViewes(entry, add);
805 // Update node indexed flow database
806 updateNodeFlowsDB(entry, add);
808 // Update group indexed flow database
809 updateGroupFlowsDB(entry, add);
813 * Update the node mapped flows database
815 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
817 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
818 installedSwView.put(flowEntries, flowEntries);
820 originalSwView.remove(flowEntries.getOriginal());
821 installedSwView.remove(flowEntries);
826 * Update the node mapped flows database
828 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
829 Node node = flowEntries.getNode();
831 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
832 if (nodeIndeces == null) {
836 nodeIndeces = new ArrayList<FlowEntryInstall>();
841 nodeIndeces.add(flowEntries);
843 nodeIndeces.remove(flowEntries);
846 // Update cache across cluster
847 if (nodeIndeces.isEmpty()) {
848 this.nodeFlows.remove(node);
850 this.nodeFlows.put(node, nodeIndeces);
855 * Update the group name mapped flows database
857 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
858 String groupName = flowEntries.getGroupName();
860 // Flow may not be part of a group
861 if (groupName == null) {
865 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
866 if (indices == null) {
870 indices = new ArrayList<FlowEntryInstall>();
875 indices.add(flowEntries);
877 indices.remove(flowEntries);
880 // Update cache across cluster
881 if (indices.isEmpty()) {
882 this.groupFlows.remove(groupName);
884 this.groupFlows.put(groupName, indices);
889 * Remove a flow entry that has been added previously First checks if the
890 * entry is effectively present in the local database
892 @SuppressWarnings("unused")
893 private Status removeEntry(Node node, String flowName) {
894 FlowEntryInstall target = null;
897 for (FlowEntryInstall entry : installedSwView.values()) {
898 if (entry.equalsByNodeAndName(node, flowName)) {
904 // If it is not there, stop any further processing
905 if (target == null) {
906 return new Status(StatusCode.SUCCESS, "Entry is not present");
910 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
913 if (status.isSuccess()) {
914 updateLocalDatabase(target, false);
917 log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
918 status.getDescription());
925 public Status installFlowEntry(FlowEntry flowEntry) {
927 if (isContainerModeAllowed(flowEntry)) {
928 status = addEntry(flowEntry, false);
930 String msg = "Controller in container mode: Install Refused";
931 String logMsg = msg + ": {}";
932 status = new Status(StatusCode.NOTACCEPTABLE, msg);
933 log.warn(logMsg, flowEntry);
939 public Status installFlowEntryAsync(FlowEntry flowEntry) {
941 if (isContainerModeAllowed(flowEntry)) {
942 status = addEntry(flowEntry, true);
944 String msg = "Controller in container mode: Install Refused";
945 status = new Status(StatusCode.NOTACCEPTABLE, msg);
952 public Status uninstallFlowEntry(FlowEntry flowEntry) {
954 if (isContainerModeAllowed(flowEntry)) {
955 status = removeEntry(flowEntry, false);
957 String msg = "Controller in container mode: Uninstall Refused";
958 String logMsg = msg + ": {}";
959 status = new Status(StatusCode.NOTACCEPTABLE, msg);
960 log.warn(logMsg, flowEntry);
966 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
968 if (isContainerModeAllowed(flowEntry)) {
969 status = removeEntry(flowEntry, true);
971 String msg = "Controller in container mode: Uninstall Refused";
972 status = new Status(StatusCode.NOTACCEPTABLE, msg);
979 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
980 Status status = null;
981 if (isContainerModeAllowed(currentFlowEntry)) {
982 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
984 String msg = "Controller in container mode: Modify Refused";
985 String logMsg = msg + ": {}";
986 status = new Status(StatusCode.NOTACCEPTABLE, msg);
987 log.warn(logMsg, newFlowEntry);
993 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
994 Status status = null;
995 if (isContainerModeAllowed(currentFlowEntry)) {
996 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
998 String msg = "Controller in container mode: Modify Refused";
999 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1006 * Returns whether the specified flow entry is allowed to be
1007 * installed/removed/modified based on the current container mode status.
1008 * This call always returns true in the container instance of forwarding
1009 * rules manager. It is meant for the global instance only (default
1010 * container) of forwarding rules manager. Idea is that for assuring
1011 * container isolation of traffic, flow installation in default container is
1012 * blocked when in container mode (containers are present). The only flows
1013 * that are allowed in container mode in the default container are the
1014 * proactive flows, the ones automatically installed on the network node
1015 * which forwarding mode has been configured to "proactive". These flows are
1016 * needed by controller to discover the nodes topology and to discover the
1017 * attached hosts for some SDN switches.
1020 * The flow entry to be installed/removed/modified
1021 * @return true if not in container mode or if flowEntry is internally
1024 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1025 return (!inContainerMode) ? true : flowEntry.isInternal();
1029 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1031 * Run a check on the original entries to decide whether to go with a
1032 * add or modify method. A loose check means only check against the
1033 * original flow entry requests and not against the installed flow
1034 * entries which are the result of the original entry merged with the
1035 * container flow(s) (if any). The modifyFlowEntry method in presence of
1036 * conflicts with the Container flows (if any) would revert back to a
1037 * delete + add pattern
1039 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1041 if (currentFlowEntry != null) {
1042 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1044 return installFlowEntry(newFlowEntry);
1049 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1051 * Run a check on the original entries to decide whether to go with a
1052 * add or modify method. A loose check means only check against the
1053 * original flow entry requests and not against the installed flow
1054 * entries which are the result of the original entry merged with the
1055 * container flow(s) (if any). The modifyFlowEntry method in presence of
1056 * conflicts with the Container flows (if any) would revert back to a
1057 * delete + add pattern
1059 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1061 if (currentFlowEntry != null) {
1062 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1064 return installFlowEntryAsync(newFlowEntry);
1069 public Status uninstallFlowEntryGroup(String groupName) {
1070 if (groupName == null || groupName.isEmpty()) {
1071 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1073 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1074 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1076 if (inContainerMode) {
1077 String msg = "Controller in container mode: Group Uninstall Refused";
1078 String logMsg = msg + ": {}";
1079 log.warn(logMsg, groupName);
1080 return new Status(StatusCode.NOTACCEPTABLE, msg);
1082 int toBeRemoved = 0;
1084 if (groupFlows.containsKey(groupName)) {
1085 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1086 toBeRemoved = list.size();
1087 for (FlowEntryInstall entry : list) {
1088 Status status = this.removeEntry(entry.getOriginal(), false);
1089 if (status.isSuccess()) {
1092 error = status.getDescription();
1096 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1097 "Not all the flows were removed: " + error);
1101 public Status uninstallFlowEntryGroupAsync(String groupName) {
1102 if (groupName == null || groupName.isEmpty()) {
1103 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1105 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1106 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1108 if (inContainerMode) {
1109 String msg = "Controller in container mode: Group Uninstall Refused";
1110 String logMsg = msg + ": {}";
1111 log.warn(logMsg, groupName);
1112 return new Status(StatusCode.NOTACCEPTABLE, msg);
1114 if (groupFlows.containsKey(groupName)) {
1115 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1116 for (FlowEntryInstall entry : list) {
1117 this.removeEntry(entry.getOriginal(), true);
1120 return new Status(StatusCode.SUCCESS);
1124 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1125 return entryConflictsWithContainerFlows(flowEntry);
1129 * Updates all installed flows because the container flow got updated This
1130 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1131 * Reinstall of all flows This is needed because a new container flows
1132 * merged flow may conflict with an existing old container flows merged flow
1133 * on the network node
1135 protected void updateFlowsContainerFlow() {
1136 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1137 // First remove all installed entries
1138 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1139 FlowEntryInstall current = entry.getValue();
1140 // Store the original entry
1141 toReInstall.add(current.getOriginal());
1142 // Remove the old couples. No validity checks to be run, use the
1144 this.removeEntryInternal(current, false);
1146 // Then reinstall the original entries
1147 for (FlowEntry entry : toReInstall) {
1148 // Reinstall the original flow entries, via the regular path: new
1149 // cFlow merge + validations
1150 this.installFlowEntry(entry);
1154 private void nonClusterObjectCreate() {
1155 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1156 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1157 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
1158 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
1159 TSPolicies = new ConcurrentHashMap<String, Object>();
1160 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1161 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1162 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1163 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1164 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1167 private void registerWithOSGIConsole() {
1168 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1169 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1173 public void setTSPolicyData(String policyname, Object o, boolean add) {
1176 /* Check if this policy already exists */
1177 if (!(TSPolicies.containsKey(policyname))) {
1178 TSPolicies.put(policyname, o);
1181 TSPolicies.remove(policyname);
1183 if (frmAware != null) {
1184 synchronized (frmAware) {
1185 for (IForwardingRulesManagerAware frma : frmAware) {
1187 frma.policyUpdate(policyname, add);
1188 } catch (Exception e) {
1189 log.warn("Exception on callback", e);
1197 public Map<String, Object> getTSPolicyData() {
1202 public Object getTSPolicyData(String policyName) {
1203 if (TSPolicies.containsKey(policyName)) {
1204 return TSPolicies.get(policyName);
1211 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1212 List<FlowEntry> list = new ArrayList<FlowEntry>();
1213 if (policyName != null && !policyName.trim().isEmpty()) {
1214 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1215 if (policyName.equals(entry.getKey().getGroupName())) {
1216 list.add(entry.getKey().clone());
1224 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1225 List<FlowEntry> list = new ArrayList<FlowEntry>();
1226 if (policyName != null && !policyName.trim().isEmpty()) {
1227 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1228 if (policyName.equals(entry.getKey().getGroupName())) {
1229 list.add(entry.getKey().getInstall().clone());
1237 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1239 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1240 if (flow.getFlowName().equals(flowName)) {
1241 FlowEntry currentFlowEntry = flow.getOriginal();
1242 FlowEntry newFlowEntry = currentFlowEntry.clone();
1243 for (NodeConnector dstPort : portList) {
1244 newFlowEntry.getFlow().addAction(new Output(dstPort));
1246 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1247 if (error.isSuccess()) {
1248 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1250 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1251 currentFlowEntry.toString(), error.getDescription());
1256 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1260 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1261 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1262 FlowEntryInstall flow = this.installedSwView.get(index);
1263 if (flow.getFlowName().equals(flowName)) {
1264 FlowEntry currentFlowEntry = flow.getOriginal();
1265 FlowEntry newFlowEntry = currentFlowEntry.clone();
1266 for (NodeConnector dstPort : portList) {
1267 Action action = new Output(dstPort);
1268 newFlowEntry.getFlow().removeAction(action);
1270 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1271 if (status.isSuccess()) {
1272 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1274 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1275 currentFlowEntry.toString(), status.getDescription());
1280 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1284 * This function assumes the target flow has only one output port
1287 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1288 FlowEntry currentFlowEntry = null;
1289 FlowEntry newFlowEntry = null;
1292 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1293 FlowEntryInstall flow = this.installedSwView.get(index);
1294 if (flow.getFlowName().equals(flowName)) {
1295 currentFlowEntry = flow.getOriginal();
1299 if (currentFlowEntry == null) {
1300 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1304 // Create a flow copy with the new output port
1305 newFlowEntry = currentFlowEntry.clone();
1306 Action target = null;
1307 for (Action action : newFlowEntry.getFlow().getActions()) {
1308 if (action.getType() == ActionType.OUTPUT) {
1313 newFlowEntry.getFlow().removeAction(target);
1314 newFlowEntry.getFlow().addAction(new Output(outPort));
1316 // Modify on network node
1317 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1319 if (status.isSuccess()) {
1320 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1322 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1323 status.getDescription());
1329 public NodeConnector getOutputPort(Node node, String flowName) {
1330 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1331 FlowEntryInstall flow = this.installedSwView.get(index);
1332 if (flow.getFlowName().equals(flowName)) {
1333 for (Action action : flow.getOriginal().getFlow().getActions()) {
1334 if (action.getType() == ActionType.OUTPUT) {
1335 return ((Output) action).getPort();
1343 private void cacheStartup() {
1348 private void allocateCaches() {
1349 if (this.clusterContainerService == null) {
1350 log.warn("Un-initialized clusterContainerService, can't create cache");
1354 log.debug("Allocating caches for Container {}", container.getName());
1357 clusterContainerService.createCache("frm.originalSwView",
1358 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1360 clusterContainerService.createCache("frm.installedSwView",
1361 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1363 clusterContainerService.createCache("frm.inactiveFlows",
1364 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1366 clusterContainerService.createCache("frm.nodeFlows",
1367 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1369 clusterContainerService.createCache("frm.groupFlows",
1370 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1372 clusterContainerService.createCache("frm.staticFlows",
1373 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1375 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1376 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1378 clusterContainerService.createCache("frm.portGroupConfigs",
1379 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1381 clusterContainerService.createCache("frm.portGroupData",
1382 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1384 clusterContainerService.createCache("frm.TSPolicies",
1385 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1387 clusterContainerService.createCache(WORK_STATUS_CACHE,
1388 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1390 clusterContainerService.createCache(WORK_ORDER_CACHE,
1391 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1393 } catch (CacheConfigException cce) {
1394 log.error("CacheConfigException");
1395 } catch (CacheExistException cce) {
1396 log.error("CacheExistException");
1400 @SuppressWarnings({ "unchecked" })
1401 private void retrieveCaches() {
1402 ConcurrentMap<?, ?> map;
1404 if (this.clusterContainerService == null) {
1405 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1406 nonClusterObjectCreate();
1410 log.debug("Retrieving Caches for Container {}", container.getName());
1412 map = clusterContainerService.getCache("frm.originalSwView");
1414 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1416 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1419 map = clusterContainerService.getCache("frm.installedSwView");
1421 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1423 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1426 map = clusterContainerService.getCache("frm.inactiveFlows");
1428 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1430 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1433 map = clusterContainerService.getCache("frm.nodeFlows");
1435 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1437 log.error("Retrieval of cache failed for Container {}", container.getName());
1440 map = clusterContainerService.getCache("frm.groupFlows");
1442 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1444 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1447 map = clusterContainerService.getCache("frm.staticFlows");
1449 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1451 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1454 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1456 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1458 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1461 map = clusterContainerService.getCache("frm.portGroupConfigs");
1463 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1465 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1468 map = clusterContainerService.getCache("frm.portGroupData");
1470 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1472 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1475 map = clusterContainerService.getCache("frm.TSPolicies");
1477 TSPolicies = (ConcurrentMap<String, Object>) map;
1479 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1482 map = clusterContainerService.getCache(WORK_ORDER_CACHE);
1484 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1486 log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName());
1489 map = clusterContainerService.getCache(WORK_STATUS_CACHE);
1491 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1493 log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName());
1497 private boolean flowConfigExists(FlowConfig config) {
1498 // Flow name has to be unique on per node id basis
1499 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1500 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1508 public Status addStaticFlow(FlowConfig config) {
1509 // Configuration object validation
1510 Status status = config.validate(container);
1511 if (!status.isSuccess()) {
1512 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1513 String error = "Invalid Configuration (" + status.getDescription() + ")";
1514 config.setStatus(error);
1515 return new Status(StatusCode.BADREQUEST, error);
1517 return addStaticFlowInternal(config, false);
1521 * Private method to add a static flow configuration which does not run any
1522 * validation on the passed FlowConfig object. If restore is set to true,
1523 * configuration is stored in configuration database regardless the
1524 * installation on the network node was successful. This is useful at boot
1525 * when static flows are present in startup configuration and are read
1526 * before the switches connects.
1529 * The static flow configuration
1531 * if true, the configuration is stored regardless the
1532 * installation on the network node was successful
1533 * @return The status of this request
1535 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1536 boolean multipleFlowPush = false;
1539 config.setStatus(StatusCode.SUCCESS.toString());
1542 if (flowConfigExists(config)) {
1543 error = "Entry with this name on specified switch already exists";
1544 log.warn("Entry with this name on specified switch already exists: {}", config);
1545 config.setStatus(error);
1546 return new Status(StatusCode.CONFLICT, error);
1549 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1550 for (String portGroupName : portGroupConfigs.keySet()) {
1551 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1552 multipleFlowPush = true;
1556 if (!multipleFlowPush) {
1557 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1558 error = "Invalid Configuration (Invalid PortGroup Name)";
1559 config.setStatus(error);
1560 return new Status(StatusCode.BADREQUEST, error);
1565 * If requested program the entry in hardware first before updating the
1568 if (!multipleFlowPush) {
1570 if (config.installInHw()) {
1571 FlowEntry entry = config.getFlowEntry();
1572 status = this.installFlowEntry(entry);
1573 if (!status.isSuccess()) {
1574 config.setStatus(status.getDescription());
1583 * When the control reaches this point, either of the following
1584 * conditions is true 1. This is a single entry configuration (non
1585 * PortGroup) and the hardware installation is successful 2. This is a
1586 * multiple entry configuration (PortGroup) and hardware installation is
1587 * NOT done directly on this event. 3. The User prefers to retain the
1588 * configuration in Controller and skip hardware installation.
1590 * Hence it is safe to update the StaticFlow DB at this point.
1592 * Note : For the case of PortGrouping, it is essential to have this DB
1593 * populated before the PortGroupListeners can query for the DB
1594 * triggered using portGroupChanged event...
1596 Integer ordinal = staticFlowsOrdinal.get(0);
1597 staticFlowsOrdinal.put(0, ++ordinal);
1598 staticFlows.put(ordinal, config);
1600 if (multipleFlowPush) {
1601 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1602 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1603 if (existingData != null) {
1604 portGroupChanged(pgconfig, existingData, true);
1607 return new Status(StatusCode.SUCCESS);
1610 private void addStaticFlowsToSwitch(Node node) {
1611 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1612 FlowConfig config = entry.getValue();
1613 if (config.isPortGroupEnabled()) {
1616 if (config.getNode().equals(node)) {
1617 if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) {
1618 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1619 config.setStatus(status.getDescription());
1623 // Update cluster cache
1624 refreshClusterStaticFlowsStatus(node);
1627 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1628 log.trace("Updating Static Flow configs on node down: {}", node);
1630 List<Integer> toRemove = new ArrayList<Integer>();
1631 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1633 FlowConfig config = entry.getValue();
1635 if (config.isPortGroupEnabled()) {
1639 if (config.installInHw() && config.getNode().equals(node)) {
1640 if (config.isInternalFlow()) {
1641 // Take note of this controller generated static flow
1642 toRemove.add(entry.getKey());
1644 config.setStatus(NODEDOWN);
1648 // Remove controller generated static flows for this node
1649 for (Integer index : toRemove) {
1650 staticFlows.remove(index);
1652 // Update cluster cache
1653 refreshClusterStaticFlowsStatus(node);
1657 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1658 log.trace("Updating Static Flow configs on container mode change: {}", update);
1660 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1661 FlowConfig config = entry.getValue();
1662 if (config.isPortGroupEnabled()) {
1665 if (config.installInHw() && !config.isInternalFlow()) {
1668 config.setStatus("Removed from node because in container mode");
1671 config.setStatus(StatusCode.SUCCESS.toString());
1677 // Update cluster cache
1678 refreshClusterStaticFlowsStatus(null);
1682 public Status removeStaticFlow(FlowConfig config) {
1684 * No config.isInternal() check as NB does not take this path and GUI
1685 * cannot issue a delete on an internal generated flow. We need this
1686 * path to be accessible when switch mode is changed from proactive to
1687 * reactive, so that we can remove the internal generated LLDP and ARP
1691 // Look for the target configuration entry
1693 FlowConfig target = null;
1694 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1695 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1696 key = entry.getKey();
1697 target = entry.getValue();
1701 if (target == null) {
1702 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1705 // Program the network node
1706 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1708 // Update configuration database if programming was successful
1709 if (status.isSuccess()) {
1710 staticFlows.remove(key);
1717 public Status removeStaticFlow(String name, Node node) {
1718 // Look for the target configuration entry
1720 FlowConfig target = null;
1721 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1722 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1723 key = mapEntry.getKey();
1724 target = mapEntry.getValue();
1728 if (target == null) {
1729 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1732 // Validity check for api3 entry point
1733 if (target.isInternalFlow()) {
1734 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1735 String logMsg = msg + ": {}";
1736 log.warn(logMsg, name);
1737 return new Status(StatusCode.NOTACCEPTABLE, msg);
1740 if (target.isPortGroupEnabled()) {
1741 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1742 String logMsg = msg + ": {}";
1743 log.warn(logMsg, name);
1744 return new Status(StatusCode.NOTACCEPTABLE, msg);
1747 // Program the network node
1748 Status status = this.removeEntry(target.getFlowEntry(), false);
1750 // Update configuration database if programming was successful
1751 if (status.isSuccess()) {
1752 staticFlows.remove(key);
1759 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1760 // Validity check for api3 entry point
1761 if (newFlowConfig.isInternalFlow()) {
1762 String msg = "Invalid operation: Controller generated flow cannot be modified";
1763 String logMsg = msg + ": {}";
1764 log.warn(logMsg, newFlowConfig);
1765 return new Status(StatusCode.NOTACCEPTABLE, msg);
1769 Status status = newFlowConfig.validate(container);
1770 if (!status.isSuccess()) {
1771 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1772 newFlowConfig.setStatus(msg);
1773 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1774 return new Status(StatusCode.BADREQUEST, msg);
1777 FlowConfig oldFlowConfig = null;
1778 Integer index = null;
1779 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1780 FlowConfig entry = mapEntry.getValue();
1781 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1782 oldFlowConfig = entry;
1783 index = mapEntry.getKey();
1788 if (oldFlowConfig == null) {
1789 String msg = "Attempt to modify a non existing static flow";
1790 String logMsg = msg + ": {}";
1791 log.warn(logMsg, newFlowConfig);
1792 return new Status(StatusCode.NOTFOUND, msg);
1795 // Do not attempt to reinstall the flow, warn user
1796 if (newFlowConfig.equals(oldFlowConfig)) {
1797 String msg = "No modification detected";
1798 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1799 return new Status(StatusCode.SUCCESS, msg);
1802 // If flow is installed, program the network node
1803 status = new Status(StatusCode.SUCCESS, "Saved in config");
1804 if (oldFlowConfig.installInHw()) {
1805 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1808 // Update configuration database if programming was successful
1809 if (status.isSuccess()) {
1810 newFlowConfig.setStatus(status.getDescription());
1811 staticFlows.put(index, newFlowConfig);
1818 public Status toggleStaticFlowStatus(String name, Node node) {
1819 return toggleStaticFlowStatus(getStaticFlow(name, node));
1823 public Status toggleStaticFlowStatus(FlowConfig config) {
1824 if (config == null) {
1825 String msg = "Invalid request: null flow config";
1827 return new Status(StatusCode.BADREQUEST, msg);
1829 // Validity check for api3 entry point
1830 if (config.isInternalFlow()) {
1831 String msg = "Invalid operation: Controller generated flow cannot be modified";
1832 String logMsg = msg + ": {}";
1833 log.warn(logMsg, config);
1834 return new Status(StatusCode.NOTACCEPTABLE, msg);
1837 // Find the config entry
1839 FlowConfig target = null;
1840 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1841 FlowConfig conf = entry.getValue();
1842 if (conf.isByNameAndNodeIdEqual(config)) {
1843 key = entry.getKey();
1848 if (target != null) {
1849 Status status = target.validate(container);
1850 if (!status.isSuccess()) {
1851 log.warn(status.getDescription());
1854 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1855 .installFlowEntry(target.getFlowEntry());
1856 if (status.isSuccess()) {
1857 // Update Configuration database
1858 target.setStatus(StatusCode.SUCCESS.toString());
1859 target.toggleInstallation();
1860 staticFlows.put(key, target);
1865 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1869 * Reinsert all static flows entries in the cache to force cache updates in
1870 * the cluster. This is useful when only some parameters were changed in the
1871 * entries, like the status.
1874 * The node for which the static flow configurations have to be
1875 * refreshed. If null, all nodes static flows will be refreshed.
1877 private void refreshClusterStaticFlowsStatus(Node node) {
1878 // Refresh cluster cache
1879 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1880 if (node == null || entry.getValue().getNode().equals(node)) {
1881 staticFlows.put(entry.getKey(), entry.getValue());
1887 * Uninstall all the non-internal Flow Entries present in the software view.
1888 * If requested, a copy of each original flow entry will be stored in the
1889 * inactive list so that it can be re-applied when needed (This is typically
1890 * the case when running in the default container and controller moved to
1891 * container mode) NOTE WELL: The routine as long as does a bulk change will
1892 * operate only on the entries for nodes locally attached so to avoid
1893 * redundant operations initiated by multiple nodes
1895 * @param preserveFlowEntries
1896 * if true, a copy of each original entry is stored in the
1899 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1900 log.info("Uninstalling all non-internal flows");
1902 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1904 // Store entries / create target list
1905 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1906 FlowEntryInstall flowEntries = mapEntry.getValue();
1907 // Skip internal generated static flows
1908 if (!flowEntries.isInternal()) {
1909 toRemove.add(flowEntries);
1910 // Store the original entries if requested
1911 if (preserveFlowEntries) {
1912 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1917 // Now remove the entries
1918 for (FlowEntryInstall flowEntryHw : toRemove) {
1919 Node n = flowEntryHw.getNode();
1920 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
1921 Status status = this.removeEntryInternal(flowEntryHw, false);
1922 if (!status.isSuccess()) {
1923 log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1926 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
1933 * Re-install all the Flow Entries present in the inactive list The inactive
1934 * list will be empty at the end of this call This function is called on the
1935 * default container instance of FRM only when the last container is deleted
1937 private void reinstallAllFlowEntries() {
1938 log.info("Reinstalling all inactive flows");
1940 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1941 this.addEntry(flowEntry, false);
1944 // Empty inactive list in any case
1945 inactiveFlows.clear();
1949 public List<FlowConfig> getStaticFlows() {
1950 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1953 // TODO: need to come out with a better algorithm for maintaining the order
1954 // of the configuration entries
1955 // with actual one, index associated to deleted entries cannot be reused and
1957 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1958 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1959 for (int i = 0; i <= maxKey; i++) {
1960 FlowConfig entry = flowMap.get(i);
1961 if (entry != null) {
1962 orderedList.add(entry);
1969 public FlowConfig getStaticFlow(String name, Node node) {
1970 ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
1972 return entry.getValue();
1978 public List<FlowConfig> getStaticFlows(Node node) {
1979 List<FlowConfig> list = new ArrayList<FlowConfig>();
1980 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1981 if (entry.getValue().onNode(node)) {
1982 list.add(entry.getValue());
1989 public List<String> getStaticFlowNamesForNode(Node node) {
1990 List<String> list = new ArrayList<String>();
1991 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1992 if (entry.getValue().onNode(node)) {
1993 list.add(entry.getValue().getName());
2000 public List<Node> getListNodeWithConfiguredFlows() {
2001 Set<Node> set = new HashSet<Node>();
2002 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2003 set.add(entry.getValue().getNode());
2005 return new ArrayList<Node>(set);
2008 @SuppressWarnings("unchecked")
2009 private void loadFlowConfiguration() {
2010 ObjectReader objReader = new ObjectReader();
2011 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2014 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2017 if (pgConfig != null) {
2018 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2019 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2023 if (confList == null) {
2028 for (Integer key : confList.keySet()) {
2029 if (key.intValue() > maxKey) {
2030 maxKey = key.intValue();
2034 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2035 addStaticFlowInternal(conf, true);
2040 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2041 return ois.readObject();
2045 public Status saveConfig() {
2046 return saveConfigInternal();
2049 private Status saveConfigInternal() {
2050 ObjectWriter objWriter = new ObjectWriter();
2051 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2052 for (Integer ordinal : staticFlows.keySet()) {
2053 FlowConfig config = staticFlows.get(ordinal);
2054 // Do not save dynamic and controller generated static flows
2055 if (config.isDynamic() || config.isInternalFlow()) {
2058 nonDynamicFlows.put(ordinal, config);
2060 objWriter.write(nonDynamicFlows, frmFileName);
2061 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2062 return new Status(StatusCode.SUCCESS, null);
2066 public void subnetNotify(Subnet sub, boolean add) {
2069 private void installImplicitARPReplyPunt(Node node) {
2075 List<String> puntAction = new ArrayList<String>();
2076 puntAction.add(ActionType.CONTROLLER.toString());
2078 FlowConfig allowARP = new FlowConfig();
2079 allowARP.setInstallInHw(true);
2080 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
2081 allowARP.setPriority("500");
2082 allowARP.setNode(node);
2083 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2084 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
2085 allowARP.setActions(puntAction);
2086 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
2092 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2095 * This method can be called from within the OSGi framework context,
2096 * given the programming operation can take sometime, it not good
2097 * pratice to have in it's context operations that can take time,
2098 * hence moving off to a different thread for async processing.
2100 private ExecutorService executor;
2102 public void modeChangeNotify(final Node node, final boolean proactive) {
2103 Callable<Status> modeChangeCallable = new Callable<Status>() {
2105 public Status call() throws Exception {
2106 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2108 List<String> puntAction = new ArrayList<String>();
2109 puntAction.add(ActionType.CONTROLLER.toString());
2111 FlowConfig allowARP = new FlowConfig();
2112 allowARP.setInstallInHw(true);
2113 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2114 allowARP.setPriority("1");
2115 allowARP.setNode(node);
2116 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2118 allowARP.setActions(puntAction);
2119 defaultConfigs.add(allowARP);
2121 FlowConfig allowLLDP = new FlowConfig();
2122 allowLLDP.setInstallInHw(true);
2123 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2124 allowLLDP.setPriority("1");
2125 allowLLDP.setNode(node);
2126 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2128 allowLLDP.setActions(puntAction);
2129 defaultConfigs.add(allowLLDP);
2131 List<String> dropAction = new ArrayList<String>();
2132 dropAction.add(ActionType.DROP.toString());
2134 FlowConfig dropAllConfig = new FlowConfig();
2135 dropAllConfig.setInstallInHw(true);
2136 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2137 + FlowConfig.INTERNALSTATICFLOWEND);
2138 dropAllConfig.setPriority("0");
2139 dropAllConfig.setNode(node);
2140 dropAllConfig.setActions(dropAction);
2141 defaultConfigs.add(dropAllConfig);
2143 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2144 for (FlowConfig fc : defaultConfigs) {
2145 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2146 if (status.isSuccess()) {
2147 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2149 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2153 return new Status(StatusCode.SUCCESS);
2158 * Execute the work outside the caller context, this could be an
2159 * expensive operation and we don't want to block the caller for it.
2161 this.executor.submit(modeChangeCallable);
2165 * Remove from the databases all the flows installed on the node
2169 private void cleanDatabaseForNode(Node node) {
2170 log.info("Cleaning Flow database for Node {}", node);
2171 if (nodeFlows.containsKey(node)) {
2172 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2174 for (FlowEntryInstall entry : toRemove) {
2175 updateLocalDatabase(entry, false);
2180 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2185 Match match = flow.getMatch();
2186 if (match.isPresent(MatchType.IN_PORT)) {
2187 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2188 if (matchPort.equals(nc)) {
2192 List<Action> actionsList = flow.getActions();
2193 if (actionsList != null) {
2194 for (Action action : actionsList) {
2195 if (action instanceof Output) {
2196 NodeConnector actionPort = ((Output) action).getPort();
2197 if (actionPort.equals(nc)) {
2207 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2208 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2212 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2213 boolean updateStaticFlowCluster = false;
2219 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2220 if (config != null) {
2221 switch (config.getValue()) {
2222 case Config.ADMIN_DOWN:
2223 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2224 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2226 case Config.ADMIN_UP:
2227 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2228 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2230 case Config.ADMIN_UNDEF:
2237 // This is the case where a switch port is removed from the SDN agent space
2238 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2239 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2245 if (updateStaticFlowCluster) {
2246 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2251 * It goes through the static flows configuration, it identifies the ones
2252 * which have the specified node connector as input or output port and
2253 * install them on the network node if they are marked to be installed in
2254 * hardware and their status shows they were not installed yet
2256 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2257 boolean updated = false;
2258 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2259 for (FlowConfig flowConfig : flowConfigForNode) {
2260 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2261 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) {
2262 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2263 if (!status.isSuccess()) {
2264 flowConfig.setStatus(status.getDescription());
2266 flowConfig.setStatus(StatusCode.SUCCESS.toString());
2276 * Remove from the network node all the flows which have the specified node
2277 * connector as input or output port. If any of the flow entry is a static
2278 * flow, it updates the correspondent configuration.
2280 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2281 boolean updated = false;
2282 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2283 if (nodeFlowEntries == null) {
2286 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2287 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2288 Status status = this.removeEntryInternal(fei, true);
2289 if (!status.isSuccess()) {
2293 * If the flow entry is a static flow, then update its
2296 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2297 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2298 if (flowConfig != null) {
2299 flowConfig.setStatus(PORTREMOVED);
2308 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2309 FlowConfig derivedFlow = new FlowConfig(original);
2310 derivedFlow.setDynamic(true);
2311 derivedFlow.setPortGroup(null);
2312 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2313 derivedFlow.setIngressPort(port + "");
2317 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2318 for (FlowConfig staticFlow : staticFlows.values()) {
2319 if (staticFlow.getPortGroup() == null) {
2322 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2323 for (Short port : data.getPorts()) {
2324 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2325 addStaticFlowInternal(derivedFlow, false);
2331 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2332 for (FlowConfig staticFlow : staticFlows.values()) {
2333 if (staticFlow.getPortGroup() == null) {
2336 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2337 for (Short port : data.getPorts()) {
2338 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2339 removeStaticFlow(derivedFlow);
2346 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2347 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2348 Map<Node, PortGroup> existingData = portGroupData.get(config);
2349 if (existingData != null) {
2350 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2351 PortGroup existingPortGroup = existingData.get(entry.getKey());
2352 if (existingPortGroup == null) {
2354 existingData.put(entry.getKey(), entry.getValue());
2355 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2359 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2360 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2362 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2363 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2369 portGroupData.put(config, data);
2370 for (Node swid : data.keySet()) {
2371 addPortGroupFlows(config, swid, data.get(swid));
2378 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2379 PortGroupConfig config = portGroupConfigs.get(name);
2380 if (config != null) {
2384 if ((portGroupProvider == null) && !restore) {
2387 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2391 config = new PortGroupConfig(name, regex);
2392 portGroupConfigs.put(name, config);
2393 if (portGroupProvider != null) {
2394 portGroupProvider.createPortGroupConfig(config);
2400 public boolean delPortGroupConfig(String name) {
2401 PortGroupConfig config = portGroupConfigs.get(name);
2402 if (config == null) {
2406 if (portGroupProvider != null) {
2407 portGroupProvider.deletePortGroupConfig(config);
2409 portGroupConfigs.remove(name);
2413 private void usePortGroupConfig(String name) {
2414 PortGroupConfig config = portGroupConfigs.get(name);
2415 if (config == null) {
2418 if (portGroupProvider != null) {
2419 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2420 portGroupData.put(config, data);
2425 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2426 return portGroupConfigs;
2429 public boolean isPortGroupSupported() {
2430 if (portGroupProvider == null) {
2436 public void setIContainer(IContainer s) {
2440 public void unsetIContainer(IContainer s) {
2441 if (this.container == s) {
2442 this.container = null;
2447 public PortGroupProvider getPortGroupProvider() {
2448 return portGroupProvider;
2451 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2452 this.portGroupProvider = null;
2455 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2456 this.portGroupProvider = portGroupProvider;
2457 portGroupProvider.registerPortGroupChange(this);
2458 for (PortGroupConfig config : portGroupConfigs.values()) {
2459 portGroupProvider.createPortGroupConfig(config);
2463 public void setFrmAware(IForwardingRulesManagerAware obj) {
2464 this.frmAware.add(obj);
2467 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2468 this.frmAware.remove(obj);
2471 void setClusterContainerService(IClusterContainerServices s) {
2472 log.debug("Cluster Service set");
2473 this.clusterContainerService = s;
2476 void unsetClusterContainerService(IClusterContainerServices s) {
2477 if (this.clusterContainerService == s) {
2478 log.debug("Cluster Service removed!");
2479 this.clusterContainerService = null;
2483 private String getContainerName() {
2484 if (container == null) {
2485 return GlobalConstants.DEFAULT.toString();
2487 return container.getName();
2491 * Function called by the dependency manager when all the required
2492 * dependencies are satisfied
2496 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2497 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2499 inContainerMode = false;
2501 if (portGroupProvider != null) {
2502 portGroupProvider.registerPortGroupChange(this);
2507 registerWithOSGIConsole();
2510 * If we are not the first cluster node to come up, do not initialize
2511 * the static flow entries ordinal
2513 if (staticFlowsOrdinal.size() == 0) {
2514 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2517 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2519 // Initialize the event handler thread
2520 frmEventHandler = new Thread(new Runnable() {
2525 final FRMEvent event = pendingEvents.take();
2526 if (event == null) {
2527 log.warn("Dequeued null event");
2530 log.trace("Dequeued {} event", event.getClass().getSimpleName());
2531 if (event instanceof NodeUpdateEvent) {
2532 NodeUpdateEvent update = (NodeUpdateEvent) event;
2533 Node node = update.getNode();
2534 switch (update.getUpdateType()) {
2536 addStaticFlowsToSwitch(node);
2539 cleanDatabaseForNode(node);
2540 updateStaticFlowConfigsOnNodeDown(node);
2544 } else if (event instanceof ErrorReportedEvent) {
2545 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2546 processErrorEvent(errEvent);
2547 } else if (event instanceof WorkOrderEvent) {
2549 * Take care of handling the remote Work request
2551 Runnable r = new Runnable() {
2554 WorkOrderEvent work = (WorkOrderEvent) event;
2555 FlowEntryDistributionOrder fe = work.getFe();
2557 logsync.trace("Executing the workOrder {}", fe);
2558 Status gotStatus = null;
2559 FlowEntryInstall feiCurrent = fe.getEntry();
2560 FlowEntryInstall feiNew = workOrder.get(fe);
2561 switch (fe.getUpType()) {
2563 gotStatus = addEntriesInternal(feiCurrent, false);
2566 gotStatus = modifyEntryInternal(feiCurrent, feiNew, false);
2569 gotStatus = removeEntryInternal(feiCurrent, false);
2573 workOrder.remove(fe);
2575 "The workOrder has been executed and now the status is being returned {}", fe);
2577 workStatus.put(fe, gotStatus);
2579 log.warn("Not expected null WorkOrder", work);
2583 if(executor != null) {
2584 executor.execute(r);
2586 } else if (event instanceof WorkStatusCleanup) {
2588 * Take care of handling the remote Work request
2590 WorkStatusCleanup work = (WorkStatusCleanup) event;
2591 FlowEntryDistributionOrder fe = work.getFe();
2593 logsync.trace("The workStatus {} is being removed", fe);
2594 workStatus.remove(fe);
2596 log.warn("Not expected null WorkStatus", work);
2598 } else if (event instanceof ContainerFlowChangeEvent) {
2600 * Whether it is an addition or removal, we have to
2601 * recompute the merged flows entries taking into
2602 * account all the current container flows because
2603 * flow merging is not an injective function
2605 updateFlowsContainerFlow();
2607 log.warn("Dequeued unknown event {}", event.getClass()
2610 } catch (InterruptedException e) {
2611 // clear pending events
2612 pendingEvents.clear();
2616 }, "FRM EventHandler Collector");
2620 * Function called by the dependency manager when at least one dependency
2621 * become unsatisfied or when the component is shutting down because for
2622 * example bundle is being stopped.
2626 // Interrupt the thread
2627 frmEventHandler.interrupt();
2628 // Clear the pendingEvents queue
2629 pendingEvents.clear();
2631 workMonitor.clear();
2635 * Function called by dependency manager after "init ()" is called and after
2636 * the services provided by the class are registered in the service registry
2641 * If running in default container, need to know if controller is in
2644 if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) {
2645 inContainerMode = containerManager.inContainerMode();
2648 // Initialize graceful stop flag
2651 // Allocate the executor service
2652 this.executor = Executors.newFixedThreadPool(maxPoolSize);
2654 // Start event handler thread
2655 frmEventHandler.start();
2658 * Read startup and build database if we have not already gotten the
2659 * configurations synced from another node
2661 if (staticFlows.isEmpty()) {
2662 loadFlowConfiguration();
2667 * Function called by the dependency manager before the services exported by
2668 * the component are unregistered, this will be followed by a "destroy ()"
2673 uninstallAllFlowEntries(false);
2674 // Shutdown executor
2675 this.executor.shutdownNow();
2676 // Now walk all the workMonitor and wake up the one sleeping because
2677 // destruction is happening
2678 for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2679 FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2684 public void setFlowProgrammerService(IFlowProgrammerService service) {
2685 this.programmer = service;
2688 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2689 if (this.programmer == service) {
2690 this.programmer = null;
2694 public void setSwitchManager(ISwitchManager switchManager) {
2695 this.switchManager = switchManager;
2698 public void unsetSwitchManager(ISwitchManager switchManager) {
2699 if (this.switchManager == switchManager) {
2700 this.switchManager = null;
2705 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2706 if (!container.getName().equals(containerName)) {
2712 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2713 if (!container.getName().equals(containerName)) {
2716 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2717 container.getName(), t, current);
2718 ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2719 pendingEvents.offer(ev);
2723 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2724 if (!container.getName().equals(containerName)) {
2728 boolean updateStaticFlowCluster = false;
2732 log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2733 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2736 log.trace("Port {} was added to container: reinstall interested flows", nc);
2737 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2745 if (updateStaticFlowCluster) {
2746 refreshClusterStaticFlowsStatus(nc.getNode());
2751 public void containerModeUpdated(UpdateType update) {
2752 // Only default container instance reacts on this event
2753 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2759 * Controller is moving to container mode. We are in the default
2760 * container context, we need to remove all our non-internal flows
2761 * to prevent any container isolation breakage. We also need to
2762 * preserve our flow so that they can be re-installed if we move
2763 * back to non container mode (no containers).
2765 this.inContainerMode = true;
2766 this.uninstallAllFlowEntries(true);
2769 this.inContainerMode = false;
2770 this.reinstallAllFlowEntries();
2775 // Update our configuration DB
2776 updateStaticFlowConfigsOnContainerModeChange(update);
2779 protected abstract class FRMEvent {
2783 private class NodeUpdateEvent extends FRMEvent {
2784 private final Node node;
2785 private final UpdateType update;
2787 public NodeUpdateEvent(UpdateType update, Node node) {
2788 this.update = update;
2792 public UpdateType getUpdateType() {
2796 public Node getNode() {
2801 private class ErrorReportedEvent extends FRMEvent {
2802 private final long rid;
2803 private final Node node;
2804 private final Object error;
2806 public ErrorReportedEvent(long rid, Node node, Object error) {
2812 public long getRequestId() {
2816 public Object getError() {
2820 public Node getNode() {
2825 private class WorkOrderEvent extends FRMEvent {
2826 private FlowEntryDistributionOrder fe;
2827 private FlowEntryInstall newEntry;
2833 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2835 this.newEntry = newEntry;
2841 public FlowEntryDistributionOrder getFe() {
2846 * @return the newEntry
2848 public FlowEntryInstall getNewEntry() {
2852 private class ContainerFlowChangeEvent extends FRMEvent {
2853 private final ContainerFlow previous;
2854 private final ContainerFlow current;
2855 private final UpdateType type;
2857 public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2858 this.previous = previous;
2859 this.current = current;
2863 public ContainerFlow getPrevious() {
2864 return this.previous;
2867 public ContainerFlow getCurrent() {
2868 return this.current;
2871 public UpdateType getType() {
2877 private class WorkStatusCleanup extends FRMEvent {
2878 private FlowEntryDistributionOrder fe;
2883 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2890 public FlowEntryDistributionOrder getFe() {
2899 public String getHelp() {
2900 StringBuffer help = new StringBuffer();
2901 help.append("---FRM Matrix Application---\n");
2902 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2903 help.append("\t addMatrixConfig <name> <regex>\n");
2904 help.append("\t delMatrixConfig <name>\n");
2905 help.append("\t useMatrixConfig <name>\n");
2906 return help.toString();
2909 public void _printMatrixData(CommandInterpreter ci) {
2910 ci.println("Configs : ");
2911 ci.println("---------");
2912 ci.println(portGroupConfigs);
2914 ci.println("Data : ");
2915 ci.println("------");
2916 ci.println(portGroupData);
2919 public void _addMatrixConfig(CommandInterpreter ci) {
2920 String name = ci.nextArgument();
2921 String regex = ci.nextArgument();
2922 addPortGroupConfig(name, regex, false);
2925 public void _delMatrixConfig(CommandInterpreter ci) {
2926 String name = ci.nextArgument();
2927 delPortGroupConfig(name);
2930 public void _useMatrixConfig(CommandInterpreter ci) {
2931 String name = ci.nextArgument();
2932 usePortGroupConfig(name);
2935 public void _arpPunt(CommandInterpreter ci) {
2936 String switchId = ci.nextArgument();
2937 long swid = HexEncode.stringToLong(switchId);
2938 Node node = NodeCreator.createOFNode(swid);
2939 installImplicitARPReplyPunt(node);
2942 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2944 String nodeId = ci.nextArgument();
2945 if (nodeId == null) {
2946 ci.print("Node id not specified");
2950 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2951 } catch (NumberFormatException e) {
2952 ci.print("Node id not a number");
2955 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2958 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2960 String nodeId = ci.nextArgument();
2961 if (nodeId == null) {
2962 ci.print("Node id not specified");
2966 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2967 } catch (NumberFormatException e) {
2968 ci.print("Node id not a number");
2971 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2974 private Flow getSampleFlow(Node node) throws UnknownHostException {
2975 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2976 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2977 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2978 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2979 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2980 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2981 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2982 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2983 short ethertype = EtherTypes.IPv4.shortValue();
2984 short vlan = (short) 27;
2987 byte proto = IPProtocols.TCP.byteValue();
2988 short src = (short) 55000;
2992 * Create a SAL Flow aFlow
2994 Match match = new Match();
2995 match.setField(MatchType.IN_PORT, port);
2996 match.setField(MatchType.DL_SRC, srcMac);
2997 match.setField(MatchType.DL_DST, dstMac);
2998 match.setField(MatchType.DL_TYPE, ethertype);
2999 match.setField(MatchType.DL_VLAN, vlan);
3000 match.setField(MatchType.DL_VLAN_PR, vlanPr);
3001 match.setField(MatchType.NW_SRC, srcIP, ipMask);
3002 match.setField(MatchType.NW_DST, dstIP, ipMask2);
3003 match.setField(MatchType.NW_TOS, tos);
3004 match.setField(MatchType.NW_PROTO, proto);
3005 match.setField(MatchType.TP_SRC, src);
3006 match.setField(MatchType.TP_DST, dst);
3008 List<Action> actions = new ArrayList<Action>();
3009 actions.add(new Output(oport));
3010 actions.add(new PopVlan());
3011 actions.add(new Flood());
3012 actions.add(new Controller());
3013 return new Flow(match, actions);
3017 public Status saveConfiguration() {
3018 return saveConfig();
3021 public void _frmNodeFlows(CommandInterpreter ci) {
3022 String nodeId = ci.nextArgument();
3023 Node node = Node.fromString(nodeId);
3025 ci.println("frmNodeFlows <node> [verbose]");
3028 boolean verbose = false;
3029 String verboseCheck = ci.nextArgument();
3030 if (verboseCheck != null) {
3031 verbose = verboseCheck.equals("true");
3034 if (!nodeFlows.containsKey(node)) {
3037 // Dump per node database
3038 for (FlowEntryInstall entry : nodeFlows.get(node)) {
3040 ci.println(node + " " + installedSwView.get(entry).getFlowName());
3042 ci.println(node + " " + installedSwView.get(entry).toString());
3047 public void _frmGroupFlows(CommandInterpreter ci) {
3048 String group = ci.nextArgument();
3049 if (group == null) {
3050 ci.println("frmGroupFlows <group> [verbose]");
3053 boolean verbose = false;
3054 String verboseCheck = ci.nextArgument();
3055 if (verboseCheck != null) {
3056 verbose = verboseCheck.equalsIgnoreCase("true");
3059 if (!groupFlows.containsKey(group)) {
3062 // Dump per node database
3063 ci.println("Group " + group + ":\n");
3064 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
3066 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
3068 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
3073 public void _frmProcessErrorEvent(CommandInterpreter ci) throws UnknownHostException {
3076 String nodeId = ci.nextArgument();
3077 if (nodeId == null) {
3078 ci.print("Node id not specified");
3081 String requestId = ci.nextArgument();
3082 if (requestId == null) {
3083 ci.print("Request id not specified");
3087 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
3088 } catch (NumberFormatException e) {
3089 ci.print("Node id not a number");
3093 reqId = Long.parseLong(requestId);
3094 } catch (NumberFormatException e) {
3095 ci.print("Request id not a number");
3098 // null for error object is good enough for now
3099 ErrorReportedEvent event = new ErrorReportedEvent(reqId, node, null);
3100 this.processErrorEvent(event);
3104 public void flowRemoved(Node node, Flow flow) {
3105 log.trace("Received flow removed notification on {} for {}", node, flow);
3107 // For flow entry identification, only node, match and priority matter
3108 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
3109 FlowEntryInstall installedEntry = this.installedSwView.get(test);
3110 if (installedEntry == null) {
3111 log.trace("Entry is not known to us");
3115 // Update Static flow status
3117 FlowConfig target = null;
3118 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3119 FlowConfig conf = entry.getValue();
3120 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3121 key = entry.getKey();
3126 if (target != null) {
3127 // Update Configuration database
3128 target.toggleInstallation();
3129 target.setStatus(StatusCode.SUCCESS.toString());
3130 staticFlows.put(key, target);
3133 // Update software views
3134 this.updateLocalDatabase(installedEntry, false);
3138 public void flowErrorReported(Node node, long rid, Object err) {
3139 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3140 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3143 private void processErrorEvent(ErrorReportedEvent event) {
3144 Node node = event.getNode();
3145 long rid = event.getRequestId();
3146 Object error = event.getError();
3147 String errorString = (error == null) ? "Not provided" : error.toString();
3149 * If this was for a flow install, remove the corresponding entry from
3150 * the software view. If it was a Looking for the rid going through the
3151 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3152 * mapping will have to be added in future
3154 FlowEntryInstall target = null;
3155 List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3156 // flowEntryInstallList could be null.
3158 if(flowEntryInstallList != null) {
3159 for (FlowEntryInstall index : flowEntryInstallList) {
3160 FlowEntryInstall entry = installedSwView.get(index);
3162 if (entry.getRequestId() == rid) {
3169 if (target != null) {
3170 // This was a flow install, update database
3171 this.updateLocalDatabase(target, false);
3172 // also update the config
3173 if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3174 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3175 // staticFlowEntry should never be null.
3176 // the null check is just an extra defensive check.
3177 if(staticFlowEntry != null) {
3178 staticFlows.remove(staticFlowEntry.getKey());
3184 if (frmAware != null) {
3185 synchronized (frmAware) {
3186 for (IForwardingRulesManagerAware frma : frmAware) {
3188 frma.requestFailed(rid, errorString);
3189 } catch (Exception e) {
3190 log.warn("Failed to notify {}", frma);
3198 public Status solicitStatusResponse(Node node, boolean blocking) {
3199 Status rv = new Status(StatusCode.INTERNALERROR);
3201 if (this.programmer != null) {
3203 rv = programmer.syncSendBarrierMessage(node);
3205 rv = programmer.asyncSendBarrierMessage(node);
3212 public void unsetIConnectionManager(IConnectionManager s) {
3213 if (s == this.connectionManager) {
3214 this.connectionManager = null;
3218 public void setIConnectionManager(IConnectionManager s) {
3219 this.connectionManager = s;
3222 public void unsetIContainerManager(IContainerManager s) {
3223 if (s == this.containerManager) {
3224 this.containerManager = null;
3228 public void setIContainerManager(IContainerManager s) {
3229 this.containerManager = s;
3233 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3240 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3243 * Local updates are of no interest
3247 if (cacheName.equals(WORK_ORDER_CACHE)) {
3248 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3250 * This is the case of one workOrder becoming available, so we need
3251 * to dispatch the work to the appropriate handler
3253 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3254 FlowEntryInstall fei = fe.getEntry();
3258 Node n = fei.getNode();
3259 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3260 logsync.trace("workOrder for fe {} processed locally", fe);
3261 // I'm the controller in charge for the request, queue it for
3263 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3265 } else if (cacheName.equals(WORK_STATUS_CACHE)) {
3266 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3268 * This is the case of one workOrder being completed and a status
3271 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3273 * Check if the order was initiated by this controller in that case
3274 * we need to actually look at the status returned
3276 if (fe.getRequestorController()
3277 .equals(clusterContainerService.getMyAddress())) {
3278 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3280 logsync.trace("workStatus response is for us {}", fe);
3281 // Signal we got the status
3282 fet.gotStatus(fe, workStatus.get(fe));
3283 pendingEvents.offer(new WorkStatusCleanup(fe));
3290 public void entryDeleted(Object key, String cacheName, boolean originLocal) {