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.Future;
32 import java.util.concurrent.LinkedBlockingQueue;
34 import org.eclipse.osgi.framework.console.CommandInterpreter;
35 import org.eclipse.osgi.framework.console.CommandProvider;
36 import org.opendaylight.controller.clustering.services.CacheConfigException;
37 import org.opendaylight.controller.clustering.services.CacheExistException;
38 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
39 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
40 import org.opendaylight.controller.clustering.services.IClusterServices;
41 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
42 import org.opendaylight.controller.connectionmanager.ConnectionLocality;
43 import org.opendaylight.controller.connectionmanager.IConnectionManager;
44 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
45 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
46 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
47 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
48 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
50 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
51 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
52 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
53 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
54 import org.opendaylight.controller.sal.action.Action;
55 import org.opendaylight.controller.sal.action.ActionType;
56 import org.opendaylight.controller.sal.action.Controller;
57 import org.opendaylight.controller.sal.action.Flood;
58 import org.opendaylight.controller.sal.action.Output;
59 import org.opendaylight.controller.sal.action.PopVlan;
60 import org.opendaylight.controller.sal.core.ContainerFlow;
61 import org.opendaylight.controller.sal.core.IContainer;
62 import org.opendaylight.controller.sal.core.IContainerListener;
63 import org.opendaylight.controller.sal.core.Node;
64 import org.opendaylight.controller.sal.core.NodeConnector;
65 import org.opendaylight.controller.sal.core.Property;
66 import org.opendaylight.controller.sal.core.UpdateType;
67 import org.opendaylight.controller.sal.flowprogrammer.Flow;
68 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
69 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
70 import org.opendaylight.controller.sal.match.Match;
71 import org.opendaylight.controller.sal.match.MatchType;
72 import org.opendaylight.controller.sal.utils.EtherTypes;
73 import org.opendaylight.controller.sal.utils.GlobalConstants;
74 import org.opendaylight.controller.sal.utils.HexEncode;
75 import org.opendaylight.controller.sal.utils.IObjectReader;
76 import org.opendaylight.controller.sal.utils.IPProtocols;
77 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
78 import org.opendaylight.controller.sal.utils.NodeCreator;
79 import org.opendaylight.controller.sal.utils.ObjectReader;
80 import org.opendaylight.controller.sal.utils.ObjectWriter;
81 import org.opendaylight.controller.sal.utils.Status;
82 import org.opendaylight.controller.sal.utils.StatusCode;
83 import org.opendaylight.controller.switchmanager.IInventoryListener;
84 import org.opendaylight.controller.switchmanager.ISwitchManager;
85 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
86 import org.opendaylight.controller.switchmanager.Subnet;
87 import org.osgi.framework.BundleContext;
88 import org.osgi.framework.FrameworkUtil;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * Class that manages forwarding rule installation and removal per container of
94 * the network. It also maintains the central repository of all the forwarding
95 * rules installed on the network nodes.
97 public class ForwardingRulesManager implements
98 IForwardingRulesManager,
99 PortGroupChangeListener,
102 IConfigurationContainerAware,
107 IFlowProgrammerListener {
108 private static final String NODEDOWN = "Node is Down";
109 private static final String SUCCESS = StatusCode.SUCCESS.toString();
110 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
111 private static final String PORTREMOVED = "Port removed";
112 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
113 private String frmFileName;
114 private String portGroupFileName;
115 private ConcurrentMap<Integer, FlowConfig> staticFlows;
116 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
117 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
118 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
119 private ConcurrentMap<String, Object> TSPolicies;
120 private boolean inContainerMode; // being used by global instance only
121 private boolean stopping;
124 * Flow database. It's the software view of what was requested to install
125 * and what is installed on the switch. It is indexed by the entry itself.
126 * The entry's hashcode resumes the network node index, the flow's priority
127 * and the flow's match. The value element is a class which contains the
128 * flow entry pushed by the applications modules and the respective
129 * container flow merged version. In absence of container flows, the two
130 * flow entries are the same.
132 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
133 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
135 * Per node and per group indexing
137 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
138 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
141 * Inactive flow list. This is for the global instance of FRM It will
142 * contain all the flow entries which were installed on the global container
143 * when the first container is created.
145 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
147 private IContainer container;
148 private Set<IForwardingRulesManagerAware> frmAware =
149 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
150 private PortGroupProvider portGroupProvider;
151 private IFlowProgrammerService programmer;
152 private IClusterContainerServices clusterContainerService = null;
153 private ISwitchManager switchManager;
154 private Thread frmEventHandler;
155 protected BlockingQueue<FRMEvent> pendingEvents;
157 // Distributes FRM programming in the cluster
158 private IConnectionManager connectionManager;
161 * Name clustered caches used to support FRM entry distribution these are by
162 * necessity non-transactional as long as need to be able to synchronize
163 * states also while a transaction is in progress
165 static final String WORKORDERCACHE = "frm.workOrder";
166 static final String WORKSTATUSCACHE = "frm.workStatus";
169 * Data structure responsible for distributing the FlowEntryInstall requests
170 * in the cluster. The key value is entry that is being either Installed or
171 * Updated or Delete. The value field is the same of the key value in case
172 * of Installation or Deletion, it's the new entry in case of Modification,
173 * this because the clustering caches don't allow null values.
175 * The logic behind this data structure is that the controller that initiate
176 * the request will place the order here, someone will pick it and then will
177 * remove from this data structure because is being served.
179 * TODO: We need to have a way to cleanup this data structure if entries are
180 * not picked by anyone, which is always a case can happen especially on
181 * Node disconnect cases.
183 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
186 * Data structure responsible for retrieving the results of the workOrder
187 * submitted to the cluster.
189 * The logic behind this data structure is that the controller that has
190 * executed the order will then place the result in workStatus signaling
191 * that there was a success or a failure.
193 * TODO: The workStatus entries need to have a lifetime associated in case
194 * of requestor controller leaving the cluster.
196 private ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
199 * Local Map used to hold the Future which a caller can use to monitor for
202 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
203 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
207 * Entry being installed/updated/removed
209 * New entry will be placed after the update operation. Valid
210 * only for UpdateType.CHANGED, null for all the other cases
213 * @return a Future object for monitoring the progress of the result, or
214 * null in case the processing should take place locally
216 private Future<Status> distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u, UpdateType t) {
217 // A null entry it's an unexpected condition, anyway it's safe to keep
218 // the handling local
223 Node n = e.getNode();
224 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
225 // Create the work order and distribute it
226 FlowEntryDistributionOrder fe =
227 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
228 // First create the monitor job
229 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
230 logsync.trace("Node {} not local so sending fe {}", n, fe);
231 workMonitor.put(fe, ret);
232 if (t.equals(UpdateType.CHANGED)) {
233 // Then distribute the work
234 workOrder.put(fe, u);
236 // Then distribute the work
237 workOrder.put(fe, e);
239 logsync.trace("WorkOrder requested");
240 // Now create an Handle to monitor the execution of the operation
244 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
249 * Adds a flow entry onto the network node It runs various validity checks
250 * and derive the final container flows merged entries that will be
251 * attempted to be installed
254 * the original flow entry application requested to add
256 * the flag indicating if this is a asynchronous request
257 * @return the status of this request. In case of asynchronous call, it will
258 * contain the unique id assigned to this request
260 private Status addEntry(FlowEntry flowEntry, boolean async) {
263 if (flowEntry == null || flowEntry.getNode() == null) {
264 String msg = "Invalid FlowEntry";
265 String logMsg = msg + ": {}";
266 log.warn(logMsg, flowEntry);
267 return new Status(StatusCode.NOTACCEPTABLE, msg);
271 * Derive the container flow merged entries to install In presence of N
272 * container flows, we may end up with N different entries to install...
274 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
276 // Container Flow conflict Check
277 if (toInstallList.isEmpty()) {
278 String msg = "Flow Entry conflicts with all Container Flows";
279 String logMsg = msg + ": {}";
280 log.warn(logMsg, flowEntry);
281 return new Status(StatusCode.CONFLICT, msg);
284 // Derive the list of entries good to be installed
285 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
286 for (FlowEntryInstall entry : toInstallList) {
287 // Conflict Check: Verify new entry would not overwrite existing
289 if (this.installedSwView.containsKey(entry)) {
290 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
291 log.trace("Aborting to install {}", entry);
294 toInstallSafe.add(entry);
297 // Declare failure if all the container flow merged entries clash with
299 if (toInstallSafe.size() == 0) {
300 String msg = "A flow with same match and priority exists on the target node";
301 String logMsg = msg + ": {}";
302 log.warn(logMsg, flowEntry);
303 return new Status(StatusCode.CONFLICT, msg);
306 // Try to install an entry at the time
307 Status error = new Status(null, null);
308 Status succeded = null;
309 boolean oneSucceded = false;
310 for (FlowEntryInstall installEntry : toInstallSafe) {
312 // Install and update database
313 Status ret = addEntriesInternal(installEntry, async);
315 if (ret.isSuccess()) {
318 * The first successful status response will be returned For the
319 * asynchronous call, we can discard the container flow
320 * complication for now and assume we will always deal with one
321 * flow only per request
326 log.warn("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
330 return (oneSucceded) ? succeded : error;
334 * Given a flow entry and the list of container flows, it returns the list
335 * of container flow merged flow entries good to be installed on this
336 * container. If the list of container flows is null or empty, the install
337 * entry list will contain only one entry, the original flow entry. If the
338 * flow entry is congruent with all the N container flows, then the output
339 * install entry list will contain N entries. If the output list is empty,
340 * it means the passed flow entry conflicts with all the container flows.
343 * The list of container flows
344 * @return the list of container flow merged entries good to be installed on
347 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
348 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
350 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
351 // No container flows => entry good to be installed unchanged
352 toInstallList.add(new FlowEntryInstall(request.clone(), null));
354 // Create the list of entries to be installed. If the flow entry is
355 // not congruent with any container flow, no install entries will be
357 for (ContainerFlow cFlow : container.getContainerFlows()) {
358 if (cFlow.allowsFlow(request.getFlow())) {
359 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
363 return toInstallList;
367 * Modify a flow entry with a new one It runs various validity check and
368 * derive the final container flows merged flow entries to work with
370 * @param currentFlowEntry
371 * @param newFlowEntry
373 * the flag indicating if this is a asynchronous request
374 * @return the status of this request. In case of asynchronous call, it will
375 * contain the unique id assigned to this request
377 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
381 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
382 || newFlowEntry.getNode() == null) {
383 String msg = "Modify: Invalid FlowEntry";
384 String logMsg = msg + ": {} or {}";
385 log.warn(logMsg, currentFlowEntry, newFlowEntry);
386 return new Status(StatusCode.NOTACCEPTABLE, msg);
388 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
389 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
390 String msg = "Modify: Incompatible Flow Entries";
391 String logMsg = msg + ": {} and {}";
392 log.warn(logMsg, currentFlowEntry, newFlowEntry);
393 return new Status(StatusCode.NOTACCEPTABLE, msg);
397 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
398 String msg = "Modify skipped as flows are the same";
399 String logMsg = msg + ": {} and {}";
400 log.debug(logMsg, currentFlowEntry, newFlowEntry);
401 return new Status(StatusCode.SUCCESS, msg);
405 * Conflict Check: Verify the new entry would not conflict with an
406 * existing one. This is a loose check on the previous original flow
407 * entry requests. No check on the container flow merged flow entries
410 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
411 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
412 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
413 String logMsg = msg + ": {}";
414 log.warn(logMsg, currentFlowEntry);
415 return new Status(StatusCode.CONFLICT, msg);
418 // Derive the installed and toInstall entries
419 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
420 container.getContainerFlows());
421 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
423 if (toInstallList.isEmpty()) {
424 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
425 String logMsg = msg + ": {}";
426 log.warn(logMsg, newFlowEntry);
428 return new Status(StatusCode.CONFLICT, msg);
432 * If the two list sizes differ, it means the new flow entry does not
433 * satisfy the same number of container flows the current entry does.
434 * This is only possible when the new entry and current entry have
435 * different match. In this scenario the modification would ultimately
436 * be handled as a remove and add operations in the protocol plugin.
438 * Also, if any of the new flow entries would clash with an existing
439 * one, we cannot proceed with the modify operation, because it would
440 * fail for some entries and leave stale entries on the network node.
441 * Modify path can be taken only if it can be performed completely, for
444 * So, for the above two cases, to simplify, let's decouple the modify
445 * in: 1) remove current entries 2) install new entries
447 Status succeeded = null;
448 boolean decouple = false;
449 if (installedList.size() != toInstallList.size()) {
450 log.info("Modify: New flow entry does not satisfy the same "
451 + "number of container flows as the original entry does");
454 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
455 for (FlowEntryInstall installEntry : toInstallList) {
457 * Conflict Check: Verify the new entry would not overwrite another
460 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
461 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
462 log.info("Modify: new container flow merged flow entry clashes with existing flow");
465 toInstallSafe.add(installEntry);
470 // Remove current entries
471 for (FlowEntryInstall currEntry : installedList) {
472 this.removeEntryInternal(currEntry, async);
474 // Install new entries
475 for (FlowEntryInstall newEntry : toInstallSafe) {
476 succeeded = this.addEntriesInternal(newEntry, async);
480 * The two list have the same size and the entries to install do not
481 * clash with any existing flow on the network node. We assume here
482 * (and might be wrong) that the same container flows that were
483 * satisfied by the current entries are the same that are satisfied
484 * by the new entries. Let's take the risk for now.
486 * Note: modification has to be complete. If any entry modification
487 * fails, we need to stop, restore the already modified entries, and
490 Status retModify = null;
492 int size = toInstallList.size();
494 // Modify and update database
495 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
496 if (retModify.isSuccess()) {
502 // Check if uncompleted modify
504 log.warn("Unable to perform a complete modify for all the container flows merged entries");
505 // Restore original entries
508 log.info("Attempting to restore initial entries");
509 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
510 if (retExt.isSuccess()) {
516 // Fatal error, recovery failed
518 String msg = "Flow recovery failed ! Unrecoverable Error";
520 return new Status(StatusCode.INTERNALERROR, msg);
523 succeeded = retModify;
526 * The first successful status response will be returned. For the
527 * asynchronous call, we can discard the container flow complication for
528 * now and assume we will always deal with one flow only per request
534 * This is the function that modifies the final container flows merged
535 * entries on the network node and update the database. It expects that all
536 * the validity checks are passed
538 * @param currentEntries
541 * the flag indicating if this is a asynchronous request
542 * @return the status of this request. In case of asynchronous call, it will
543 * contain the unique id assigned to this request
545 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
546 Future<Status> futureStatus = distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
547 if (futureStatus != null) {
548 Status retStatus = new Status(StatusCode.UNDEFINED);
550 retStatus = futureStatus.get();
551 } catch (InterruptedException e) {
553 } catch (ExecutionException e) {
558 // Modify the flow on the network node
559 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
560 .getFlow(), newEntries.getInstall()
561 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
562 .getFlow(), newEntries.getInstall()
565 if (!status.isSuccess()) {
566 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
567 status.getDescription());
571 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
574 newEntries.setRequestId(status.getRequestId());
575 updateLocalDatabase(currentEntries, false);
576 updateLocalDatabase(newEntries, true);
583 * Remove a flow entry. If the entry is not present in the software view
584 * (entry or node not present), it return successfully
587 * the flow entry to remove
589 * the flag indicating if this is a asynchronous request
590 * @return the status of this request. In case of asynchronous call, it will
591 * contain the unique id assigned to this request
593 private Status removeEntry(FlowEntry flowEntry, boolean async) {
594 Status error = new Status(null, null);
597 if (flowEntry == null || flowEntry.getNode() == null) {
598 String msg = "Invalid FlowEntry";
599 String logMsg = msg + ": {}";
600 log.warn(logMsg, flowEntry);
601 return new Status(StatusCode.NOTACCEPTABLE, msg);
604 // Derive the container flows merged installed entries
605 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
607 Status succeeded = null;
608 boolean atLeastOneRemoved = false;
609 for (FlowEntryInstall entry : installedList) {
610 if (!installedSwView.containsKey(entry)) {
611 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
612 log.debug(logMsg, flowEntry);
613 if (installedList.size() == 1) {
614 // If we had only one entry to remove, we are done
615 return new Status(StatusCode.SUCCESS);
621 // Remove and update DB
622 Status ret = removeEntryInternal(entry, async);
624 if (!ret.isSuccess()) {
626 log.warn("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
627 if (installedList.size() == 1) {
628 // If we had only one entry to remove, this is fatal failure
633 atLeastOneRemoved = true;
638 * No worries if full removal failed. Consistency checker will take care
639 * of removing the stale entries later, or adjusting the software
640 * database if not in sync with hardware
642 return (atLeastOneRemoved) ? succeeded : error;
646 * This is the function that removes the final container flows merged entry
647 * from the network node and update the database. It expects that all the
648 * validity checks are passed
651 * the flow entry to remove
653 * the flag indicating if this is a asynchronous request
654 * @return the status of this request. In case of asynchronous call, it will
655 * contain the unique id assigned to this request
657 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
658 Future<Status> futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
659 if (futureStatus != null) {
660 Status retStatus = new Status(StatusCode.UNDEFINED);
662 retStatus = futureStatus.get();
663 } catch (InterruptedException e) {
665 } catch (ExecutionException e) {
670 // Mark the entry to be deleted (for CC just in case we fail)
674 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
675 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
678 if (!status.isSuccess()) {
679 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
680 status.getDescription());
683 log.trace("Removed {}", entry.getInstall());
686 updateLocalDatabase(entry, false);
693 * This is the function that installs the final container flow merged entry
694 * on the network node and updates the database. It expects that all the
695 * validity and conflict checks are passed. That means it does not check
696 * whether this flow would conflict or overwrite an existing one.
699 * the flow entry to install
701 * the flag indicating if this is a asynchronous request
702 * @return the status of this request. In case of asynchronous call, it will
703 * contain the unique id assigned to this request
705 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
706 Future<Status> futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
707 if (futureStatus != null) {
708 Status retStatus = new Status(StatusCode.UNDEFINED);
710 retStatus = futureStatus.get();
711 } catch (InterruptedException e) {
713 } catch (ExecutionException e) {
718 // Install the flow on the network node
719 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
720 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
723 if (!status.isSuccess()) {
724 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
725 status.getDescription());
729 log.trace("Added {}", entry.getInstall());
732 entry.setRequestId(status.getRequestId());
733 updateLocalDatabase(entry, true);
740 * Returns true if the flow conflicts with all the container's flows. This
741 * means that if the function returns true, the passed flow entry is
742 * congruent with at least one container flow, hence it is good to be
743 * installed on this container.
746 * @return true if flow conflicts with all the container flows, false
749 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
750 List<ContainerFlow> cFlowList = container.getContainerFlows();
752 // Validity check and avoid unnecessary computation
753 // Also takes care of default container where no container flows are
755 if (cFlowList == null || cFlowList.isEmpty()) {
759 for (ContainerFlow cFlow : cFlowList) {
760 if (cFlow.allowsFlow(flowEntry.getFlow())) {
761 // Entry is allowed by at least one container flow: good to go
768 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
769 // Update the software view
770 updateSwViewes(entry, add);
772 // Update node indexed flow database
773 updateNodeFlowsDB(entry, add);
775 // Update group indexed flow database
776 updateGroupFlowsDB(entry, add);
780 * Update the node mapped flows database
782 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
784 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
785 installedSwView.put(flowEntries, flowEntries);
787 originalSwView.remove(flowEntries.getOriginal());
788 installedSwView.remove(flowEntries);
793 * Update the node mapped flows database
795 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
796 Node node = flowEntries.getNode();
798 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
799 if (nodeIndeces == null) {
803 nodeIndeces = new ArrayList<FlowEntryInstall>();
808 nodeIndeces.add(flowEntries);
810 nodeIndeces.remove(flowEntries);
813 // Update cache across cluster
814 if (nodeIndeces.isEmpty()) {
815 this.nodeFlows.remove(node);
817 this.nodeFlows.put(node, nodeIndeces);
822 * Update the group name mapped flows database
824 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
825 String groupName = flowEntries.getGroupName();
827 // Flow may not be part of a group
828 if (groupName == null) {
832 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
833 if (indices == null) {
837 indices = new ArrayList<FlowEntryInstall>();
842 indices.add(flowEntries);
844 indices.remove(flowEntries);
847 // Update cache across cluster
848 if (indices.isEmpty()) {
849 this.groupFlows.remove(groupName);
851 this.groupFlows.put(groupName, indices);
856 * Remove a flow entry that has been added previously First checks if the
857 * entry is effectively present in the local database
859 @SuppressWarnings("unused")
860 private Status removeEntry(Node node, String flowName) {
861 FlowEntryInstall target = null;
864 for (FlowEntryInstall entry : installedSwView.values()) {
865 if (entry.equalsByNodeAndName(node, flowName)) {
871 // If it is not there, stop any further processing
872 if (target == null) {
873 return new Status(StatusCode.SUCCESS, "Entry is not present");
877 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
880 if (status.isSuccess()) {
881 updateLocalDatabase(target, false);
884 log.warn("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
885 status.getDescription());
892 public Status installFlowEntry(FlowEntry flowEntry) {
894 if (isContainerModeAllowed(flowEntry)) {
895 status = addEntry(flowEntry, false);
897 String msg = "Controller in container mode: Install Refused";
898 String logMsg = msg + ": {}";
899 status = new Status(StatusCode.NOTACCEPTABLE, msg);
900 log.warn(logMsg, flowEntry);
906 public Status installFlowEntryAsync(FlowEntry flowEntry) {
908 if (isContainerModeAllowed(flowEntry)) {
909 status = addEntry(flowEntry, true);
911 String msg = "Controller in container mode: Install Refused";
912 status = new Status(StatusCode.NOTACCEPTABLE, msg);
919 public Status uninstallFlowEntry(FlowEntry flowEntry) {
921 if (isContainerModeAllowed(flowEntry)) {
922 status = removeEntry(flowEntry, false);
924 String msg = "Controller in container mode: Uninstall Refused";
925 String logMsg = msg + ": {}";
926 status = new Status(StatusCode.NOTACCEPTABLE, msg);
927 log.warn(logMsg, flowEntry);
933 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
935 if (isContainerModeAllowed(flowEntry)) {
936 status = removeEntry(flowEntry, true);
938 String msg = "Controller in container mode: Uninstall Refused";
939 status = new Status(StatusCode.NOTACCEPTABLE, msg);
946 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
947 Status status = null;
948 if (isContainerModeAllowed(currentFlowEntry)) {
949 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
951 String msg = "Controller in container mode: Modify Refused";
952 String logMsg = msg + ": {}";
953 status = new Status(StatusCode.NOTACCEPTABLE, msg);
954 log.warn(logMsg, newFlowEntry);
960 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
961 Status status = null;
962 if (isContainerModeAllowed(currentFlowEntry)) {
963 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
965 String msg = "Controller in container mode: Modify Refused";
966 status = new Status(StatusCode.NOTACCEPTABLE, msg);
973 * Returns whether the specified flow entry is allowed to be
974 * installed/removed/modified based on the current container mode status.
975 * This call always returns true in the container instance of forwarding
976 * rules manager. It is meant for the global instance only (default
977 * container) of forwarding rules manager. Idea is that for assuring
978 * container isolation of traffic, flow installation in default container is
979 * blocked when in container mode (containers are present). The only flows
980 * that are allowed in container mode in the default container are the
981 * proactive flows, the ones automatically installed on the network node
982 * which forwarding mode has been configured to "proactive". These flows are
983 * needed by controller to discover the nodes topology and to discover the
984 * attached hosts for some SDN switches.
987 * The flow entry to be installed/removed/modified
988 * @return true if not in container mode or if flowEntry is internally
991 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
992 return (!inContainerMode) ? true : flowEntry.isInternal();
996 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
998 * Run a check on the original entries to decide whether to go with a
999 * add or modify method. A loose check means only check against the
1000 * original flow entry requests and not against the installed flow
1001 * entries which are the result of the original entry merged with the
1002 * container flow(s) (if any). The modifyFlowEntry method in presence of
1003 * conflicts with the Container flows (if any) would revert back to a
1004 * delete + add pattern
1006 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1008 if (currentFlowEntry != null) {
1009 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1011 return installFlowEntry(newFlowEntry);
1016 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1018 * Run a check on the original entries to decide whether to go with a
1019 * add or modify method. A loose check means only check against the
1020 * original flow entry requests and not against the installed flow
1021 * entries which are the result of the original entry merged with the
1022 * container flow(s) (if any). The modifyFlowEntry method in presence of
1023 * conflicts with the Container flows (if any) would revert back to a
1024 * delete + add pattern
1026 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1028 if (currentFlowEntry != null) {
1029 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1031 return installFlowEntryAsync(newFlowEntry);
1036 public Status uninstallFlowEntryGroup(String groupName) {
1037 if (groupName == null || groupName.isEmpty()) {
1038 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1040 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1041 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1043 if (inContainerMode) {
1044 String msg = "Controller in container mode: Group Uninstall Refused";
1045 String logMsg = msg + ": {}";
1046 log.warn(logMsg, groupName);
1047 return new Status(StatusCode.NOTACCEPTABLE, msg);
1049 int toBeRemoved = 0;
1051 if (groupFlows.containsKey(groupName)) {
1052 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1053 toBeRemoved = list.size();
1054 for (FlowEntryInstall entry : list) {
1055 Status status = this.removeEntry(entry.getOriginal(), false);
1056 if (status.isSuccess()) {
1059 error = status.getDescription();
1063 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1064 "Not all the flows were removed: " + error);
1068 public Status uninstallFlowEntryGroupAsync(String groupName) {
1069 if (groupName == null || groupName.isEmpty()) {
1070 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1072 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1073 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1075 if (inContainerMode) {
1076 String msg = "Controller in container mode: Group Uninstall Refused";
1077 String logMsg = msg + ": {}";
1078 log.warn(logMsg, groupName);
1079 return new Status(StatusCode.NOTACCEPTABLE, msg);
1081 if (groupFlows.containsKey(groupName)) {
1082 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1083 for (FlowEntryInstall entry : list) {
1084 this.removeEntry(entry.getOriginal(), true);
1087 return new Status(StatusCode.SUCCESS);
1091 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1092 return entryConflictsWithContainerFlows(flowEntry);
1096 * Updates all installed flows because the container flow got updated This
1097 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1098 * Reinstall of all flows This is needed because a new container flows
1099 * merged flow may conflict with an existing old container flows merged flow
1100 * on the network node
1102 private void updateFlowsContainerFlow() {
1103 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1104 // First remove all installed entries
1105 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1106 FlowEntryInstall current = entry.getValue();
1107 // Store the original entry
1108 toReInstall.add(current.getOriginal());
1109 // Remove the old couples. No validity checks to be run, use the
1111 this.removeEntryInternal(current, false);
1113 // Then reinstall the original entries
1114 for (FlowEntry entry : toReInstall) {
1115 // Reinstall the original flow entries, via the regular path: new
1116 // cFlow merge + validations
1117 this.installFlowEntry(entry);
1121 private void nonClusterObjectCreate() {
1122 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1123 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1124 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
1125 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
1126 TSPolicies = new ConcurrentHashMap<String, Object>();
1127 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1128 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1129 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1130 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1131 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1134 private void registerWithOSGIConsole() {
1135 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1136 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1140 public void setTSPolicyData(String policyname, Object o, boolean add) {
1143 /* Check if this policy already exists */
1144 if (!(TSPolicies.containsKey(policyname))) {
1145 TSPolicies.put(policyname, o);
1148 TSPolicies.remove(policyname);
1150 if (frmAware != null) {
1151 synchronized (frmAware) {
1152 for (IForwardingRulesManagerAware frma : frmAware) {
1154 frma.policyUpdate(policyname, add);
1155 } catch (Exception e) {
1156 log.warn("Exception on callback", e);
1164 public Map<String, Object> getTSPolicyData() {
1169 public Object getTSPolicyData(String policyName) {
1170 if (TSPolicies.containsKey(policyName)) {
1171 return TSPolicies.get(policyName);
1178 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1179 List<FlowEntry> list = new ArrayList<FlowEntry>();
1180 if (policyName != null && !policyName.trim().isEmpty()) {
1181 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1182 if (policyName.equals(entry.getKey().getGroupName())) {
1183 list.add(entry.getKey().clone());
1191 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1192 List<FlowEntry> list = new ArrayList<FlowEntry>();
1193 if (policyName != null && !policyName.trim().isEmpty()) {
1194 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1195 if (policyName.equals(entry.getKey().getGroupName())) {
1196 list.add(entry.getKey().getInstall().clone());
1204 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1206 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1207 if (flow.getFlowName().equals(flowName)) {
1208 FlowEntry currentFlowEntry = flow.getOriginal();
1209 FlowEntry newFlowEntry = currentFlowEntry.clone();
1210 for (NodeConnector dstPort : portList) {
1211 newFlowEntry.getFlow().addAction(new Output(dstPort));
1213 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1214 if (error.isSuccess()) {
1215 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1217 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1218 currentFlowEntry.toString(), error.getDescription());
1223 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1227 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1228 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1229 FlowEntryInstall flow = this.installedSwView.get(index);
1230 if (flow.getFlowName().equals(flowName)) {
1231 FlowEntry currentFlowEntry = flow.getOriginal();
1232 FlowEntry newFlowEntry = currentFlowEntry.clone();
1233 for (NodeConnector dstPort : portList) {
1234 Action action = new Output(dstPort);
1235 newFlowEntry.getFlow().removeAction(action);
1237 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1238 if (status.isSuccess()) {
1239 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1241 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1242 currentFlowEntry.toString(), status.getDescription());
1247 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1251 * This function assumes the target flow has only one output port
1254 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1255 FlowEntry currentFlowEntry = null;
1256 FlowEntry newFlowEntry = null;
1259 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1260 FlowEntryInstall flow = this.installedSwView.get(index);
1261 if (flow.getFlowName().equals(flowName)) {
1262 currentFlowEntry = flow.getOriginal();
1266 if (currentFlowEntry == null) {
1267 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1271 // Create a flow copy with the new output port
1272 newFlowEntry = currentFlowEntry.clone();
1273 Action target = null;
1274 for (Action action : newFlowEntry.getFlow().getActions()) {
1275 if (action.getType() == ActionType.OUTPUT) {
1280 newFlowEntry.getFlow().removeAction(target);
1281 newFlowEntry.getFlow().addAction(new Output(outPort));
1283 // Modify on network node
1284 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1286 if (status.isSuccess()) {
1287 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1289 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1290 status.getDescription());
1296 public NodeConnector getOutputPort(Node node, String flowName) {
1297 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1298 FlowEntryInstall flow = this.installedSwView.get(index);
1299 if (flow.getFlowName().equals(flowName)) {
1300 for (Action action : flow.getOriginal().getFlow().getActions()) {
1301 if (action.getType() == ActionType.OUTPUT) {
1302 return ((Output) action).getPort();
1310 private void cacheStartup() {
1315 @SuppressWarnings("deprecation")
1316 private void allocateCaches() {
1317 if (this.clusterContainerService == null) {
1318 log.warn("Un-initialized clusterContainerService, can't create cache");
1322 log.debug("Allocating caches for Container {}", container.getName());
1325 clusterContainerService.createCache("frm.originalSwView",
1326 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1328 clusterContainerService.createCache("frm.installedSwView",
1329 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1331 clusterContainerService.createCache("frm.inactiveFlows",
1332 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1334 clusterContainerService.createCache("frm.nodeFlows",
1335 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1337 clusterContainerService.createCache("frm.groupFlows",
1338 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1340 clusterContainerService.createCache("frm.staticFlows",
1341 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1343 clusterContainerService.createCache("frm.flowsSaveEvent",
1344 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1346 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1347 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1349 clusterContainerService.createCache("frm.portGroupConfigs",
1350 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1352 clusterContainerService.createCache("frm.portGroupData",
1353 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1355 clusterContainerService.createCache("frm.TSPolicies",
1356 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1358 clusterContainerService.createCache(WORKSTATUSCACHE,
1359 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1361 clusterContainerService.createCache(WORKORDERCACHE,
1362 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1364 } catch (CacheConfigException cce) {
1365 log.error("CacheConfigException");
1366 } catch (CacheExistException cce) {
1367 log.error("CacheExistException");
1371 @SuppressWarnings({ "unchecked", "deprecation" })
1372 private void retrieveCaches() {
1373 ConcurrentMap<?, ?> map;
1375 if (this.clusterContainerService == null) {
1376 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1377 nonClusterObjectCreate();
1381 log.debug("Retrieving Caches for Container {}", container.getName());
1383 map = clusterContainerService.getCache("frm.originalSwView");
1385 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1387 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1390 map = clusterContainerService.getCache("frm.installedSwView");
1392 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1394 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1397 map = clusterContainerService.getCache("frm.inactiveFlows");
1399 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1401 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1404 map = clusterContainerService.getCache("frm.nodeFlows");
1406 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1408 log.error("Retrieval of cache failed for Container {}", container.getName());
1411 map = clusterContainerService.getCache("frm.groupFlows");
1413 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1415 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1418 map = clusterContainerService.getCache("frm.staticFlows");
1420 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1422 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1425 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1427 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1429 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1432 map = clusterContainerService.getCache("frm.portGroupConfigs");
1434 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1436 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1439 map = clusterContainerService.getCache("frm.portGroupData");
1441 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1443 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1446 map = clusterContainerService.getCache("frm.TSPolicies");
1448 TSPolicies = (ConcurrentMap<String, Object>) map;
1450 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1453 map = clusterContainerService.getCache(WORKORDERCACHE);
1455 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1457 log.error("Retrieval of " + WORKORDERCACHE + " cache failed for Container {}", container.getName());
1460 map = clusterContainerService.getCache(WORKSTATUSCACHE);
1462 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1464 log.error("Retrieval of " + WORKSTATUSCACHE + " cache failed for Container {}", container.getName());
1468 private boolean flowConfigExists(FlowConfig config) {
1469 // Flow name has to be unique on per node id basis
1470 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1471 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1479 public Status addStaticFlow(FlowConfig config) {
1480 // Configuration object validation
1481 Status status = config.validate(container);
1482 if (!status.isSuccess()) {
1483 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1484 String error = "Invalid Configuration (" + status.getDescription() + ")";
1485 config.setStatus(error);
1486 return new Status(StatusCode.BADREQUEST, error);
1488 return addStaticFlowInternal(config, false);
1492 * Private method to add a static flow configuration which does not run any
1493 * validation on the passed FlowConfig object. If restore is set to true,
1494 * configuration is stored in configuration database regardless the
1495 * installation on the network node was successful. This is useful at boot
1496 * when static flows are present in startup configuration and are read
1497 * before the switches connects.
1500 * The static flow configuration
1502 * if true, the configuration is stored regardless the
1503 * installation on the network node was successful
1504 * @return The status of this request
1506 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1507 boolean multipleFlowPush = false;
1510 config.setStatus(SUCCESS);
1513 if (flowConfigExists(config)) {
1514 error = "Entry with this name on specified switch already exists";
1515 log.warn("Entry with this name on specified switch already exists: {}", config);
1516 config.setStatus(error);
1517 return new Status(StatusCode.CONFLICT, error);
1520 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1521 for (String portGroupName : portGroupConfigs.keySet()) {
1522 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1523 multipleFlowPush = true;
1527 if (!multipleFlowPush) {
1528 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1529 error = "Invalid Configuration (Invalid PortGroup Name)";
1530 config.setStatus(error);
1531 return new Status(StatusCode.BADREQUEST, error);
1536 * If requested program the entry in hardware first before updating the
1539 if (!multipleFlowPush) {
1541 if (config.installInHw()) {
1542 FlowEntry entry = config.getFlowEntry();
1543 status = this.installFlowEntry(entry);
1544 if (!status.isSuccess()) {
1545 config.setStatus(status.getDescription());
1554 * When the control reaches this point, either of the following
1555 * conditions is true 1. This is a single entry configuration (non
1556 * PortGroup) and the hardware installation is successful 2. This is a
1557 * multiple entry configuration (PortGroup) and hardware installation is
1558 * NOT done directly on this event. 3. The User prefers to retain the
1559 * configuration in Controller and skip hardware installation.
1561 * Hence it is safe to update the StaticFlow DB at this point.
1563 * Note : For the case of PortGrouping, it is essential to have this DB
1564 * populated before the PortGroupListeners can query for the DB
1565 * triggered using portGroupChanged event...
1567 Integer ordinal = staticFlowsOrdinal.get(0);
1568 staticFlowsOrdinal.put(0, ++ordinal);
1569 staticFlows.put(ordinal, config);
1571 if (multipleFlowPush) {
1572 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1573 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1574 if (existingData != null) {
1575 portGroupChanged(pgconfig, existingData, true);
1578 return new Status(StatusCode.SUCCESS);
1581 private void addStaticFlowsToSwitch(Node node) {
1582 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1583 FlowConfig config = entry.getValue();
1584 if (config.isPortGroupEnabled()) {
1587 if (config.getNode().equals(node)) {
1588 if (config.installInHw() && !config.getStatus().equals(SUCCESS)) {
1589 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1590 config.setStatus(status.getDescription());
1594 // Update cluster cache
1595 refreshClusterStaticFlowsStatus(node);
1598 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1599 log.trace("Updating Static Flow configs on node down: {}", node);
1601 List<Integer> toRemove = new ArrayList<Integer>();
1602 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1604 FlowConfig config = entry.getValue();
1606 if (config.isPortGroupEnabled()) {
1610 if (config.installInHw() && config.getNode().equals(node)) {
1611 if (config.isInternalFlow()) {
1612 // Take note of this controller generated static flow
1613 toRemove.add(entry.getKey());
1615 config.setStatus(NODEDOWN);
1619 // Remove controller generated static flows for this node
1620 for (Integer index : toRemove) {
1621 staticFlows.remove(index);
1623 // Update cluster cache
1624 refreshClusterStaticFlowsStatus(node);
1628 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1629 log.trace("Updating Static Flow configs on container mode change: {}", update);
1631 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1632 FlowConfig config = entry.getValue();
1633 if (config.isPortGroupEnabled()) {
1636 if (config.installInHw() && !config.isInternalFlow()) {
1639 config.setStatus("Removed from node because in container mode");
1642 config.setStatus(SUCCESS);
1648 // Update cluster cache
1649 refreshClusterStaticFlowsStatus(null);
1653 public Status removeStaticFlow(FlowConfig config) {
1655 * No config.isInternal() check as NB does not take this path and GUI
1656 * cannot issue a delete on an internal generated flow. We need this
1657 * path to be accessible when switch mode is changed from proactive to
1658 * reactive, so that we can remove the internal generated LLDP and ARP
1662 // Look for the target configuration entry
1664 FlowConfig target = null;
1665 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1666 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1667 key = entry.getKey();
1668 target = entry.getValue();
1672 if (target == null) {
1673 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1676 // Program the network node
1677 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1679 // Update configuration database if programming was successful
1680 if (status.isSuccess()) {
1681 staticFlows.remove(key);
1688 public Status removeStaticFlow(String name, Node node) {
1689 // Look for the target configuration entry
1691 FlowConfig target = null;
1692 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1693 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1694 key = mapEntry.getKey();
1695 target = mapEntry.getValue();
1699 if (target == null) {
1700 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1703 // Validity check for api3 entry point
1704 if (target.isInternalFlow()) {
1705 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1706 String logMsg = msg + ": {}";
1707 log.warn(logMsg, name);
1708 return new Status(StatusCode.NOTACCEPTABLE, msg);
1711 if (target.isPortGroupEnabled()) {
1712 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1713 String logMsg = msg + ": {}";
1714 log.warn(logMsg, name);
1715 return new Status(StatusCode.NOTACCEPTABLE, msg);
1718 // Program the network node
1719 Status status = this.removeEntry(target.getFlowEntry(), false);
1721 // Update configuration database if programming was successful
1722 if (status.isSuccess()) {
1723 staticFlows.remove(key);
1730 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1731 // Validity check for api3 entry point
1732 if (newFlowConfig.isInternalFlow()) {
1733 String msg = "Invalid operation: Controller generated flow cannot be modified";
1734 String logMsg = msg + ": {}";
1735 log.warn(logMsg, newFlowConfig);
1736 return new Status(StatusCode.NOTACCEPTABLE, msg);
1740 Status status = newFlowConfig.validate(container);
1741 if (!status.isSuccess()) {
1742 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1743 newFlowConfig.setStatus(msg);
1744 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1745 return new Status(StatusCode.BADREQUEST, msg);
1748 FlowConfig oldFlowConfig = null;
1749 Integer index = null;
1750 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1751 FlowConfig entry = mapEntry.getValue();
1752 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1753 oldFlowConfig = entry;
1754 index = mapEntry.getKey();
1759 if (oldFlowConfig == null) {
1760 String msg = "Attempt to modify a non existing static flow";
1761 String logMsg = msg + ": {}";
1762 log.warn(logMsg, newFlowConfig);
1763 return new Status(StatusCode.NOTFOUND, msg);
1766 // Do not attempt to reinstall the flow, warn user
1767 if (newFlowConfig.equals(oldFlowConfig)) {
1768 String msg = "No modification detected";
1769 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1770 return new Status(StatusCode.SUCCESS, msg);
1773 // If flow is installed, program the network node
1774 status = new Status(StatusCode.SUCCESS, "Saved in config");
1775 if (oldFlowConfig.installInHw()) {
1776 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1779 // Update configuration database if programming was successful
1780 if (status.isSuccess()) {
1781 newFlowConfig.setStatus(status.getDescription());
1782 staticFlows.put(index, newFlowConfig);
1789 public Status toggleStaticFlowStatus(String name, Node node) {
1790 return toggleStaticFlowStatus(getStaticFlow(name, node));
1794 public Status toggleStaticFlowStatus(FlowConfig config) {
1795 if (config == null) {
1796 String msg = "Invalid request: null flow config";
1798 return new Status(StatusCode.BADREQUEST, msg);
1800 // Validity check for api3 entry point
1801 if (config.isInternalFlow()) {
1802 String msg = "Invalid operation: Controller generated flow cannot be modified";
1803 String logMsg = msg + ": {}";
1804 log.warn(logMsg, config);
1805 return new Status(StatusCode.NOTACCEPTABLE, msg);
1808 // Find the config entry
1810 FlowConfig target = null;
1811 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1812 FlowConfig conf = entry.getValue();
1813 if (conf.isByNameAndNodeIdEqual(config)) {
1814 key = entry.getKey();
1819 if (target != null) {
1820 Status status = target.validate(container);
1821 if (!status.isSuccess()) {
1822 log.warn(status.getDescription());
1825 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1826 .installFlowEntry(target.getFlowEntry());
1827 if (status.isSuccess()) {
1828 // Update Configuration database
1829 target.setStatus(SUCCESS);
1830 target.toggleInstallation();
1831 staticFlows.put(key, target);
1836 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1840 * Reinsert all static flows entries in the cache to force cache updates in
1841 * the cluster. This is useful when only some parameters were changed in the
1842 * entries, like the status.
1845 * The node for which the static flow configurations have to be
1846 * refreshed. If null, all nodes static flows will be refreshed.
1848 private void refreshClusterStaticFlowsStatus(Node node) {
1849 // Refresh cluster cache
1850 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1851 if (node == null || entry.getValue().getNode().equals(node)) {
1852 staticFlows.put(entry.getKey(), entry.getValue());
1858 * Uninstall all the non-internal Flow Entries present in the software view.
1859 * If requested, a copy of each original flow entry will be stored in the
1860 * inactive list so that it can be re-applied when needed (This is typically
1861 * the case when running in the default container and controller moved to
1864 * @param preserveFlowEntries
1865 * if true, a copy of each original entry is stored in the
1868 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1869 log.info("Uninstalling all non-internal flows");
1871 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1873 // Store entries / create target list
1874 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1875 FlowEntryInstall flowEntries = mapEntry.getValue();
1876 // Skip internal generated static flows
1877 if (!flowEntries.isInternal()) {
1878 toRemove.add(flowEntries);
1879 // Store the original entries if requested
1880 if (preserveFlowEntries) {
1881 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1886 // Now remove the entries
1887 for (FlowEntryInstall flowEntryHw : toRemove) {
1888 Status status = this.removeEntryInternal(flowEntryHw, false);
1889 if (!status.isSuccess()) {
1890 log.warn("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1896 * Re-install all the Flow Entries present in the inactive list The inactive
1897 * list will be empty at the end of this call This function is called on the
1898 * default container instance of FRM only when the last container is deleted
1900 private void reinstallAllFlowEntries() {
1901 log.info("Reinstalling all inactive flows");
1903 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1904 this.addEntry(flowEntry, false);
1907 // Empty inactive list in any case
1908 inactiveFlows.clear();
1912 public List<FlowConfig> getStaticFlows() {
1913 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1916 // TODO: need to come out with a better algorithm for maintaining the order
1917 // of the configuration entries
1918 // with actual one, index associated to deleted entries cannot be reused and
1920 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1921 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1922 for (int i = 0; i <= maxKey; i++) {
1923 FlowConfig entry = flowMap.get(i);
1924 if (entry != null) {
1925 orderedList.add(entry);
1932 public FlowConfig getStaticFlow(String name, Node node) {
1933 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1934 if (entry.getValue().isByNameAndNodeIdEqual(name, node)) {
1935 return entry.getValue();
1942 public List<FlowConfig> getStaticFlows(Node node) {
1943 List<FlowConfig> list = new ArrayList<FlowConfig>();
1944 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1945 if (entry.getValue().onNode(node)) {
1946 list.add(entry.getValue());
1953 public List<String> getStaticFlowNamesForNode(Node node) {
1954 List<String> list = new ArrayList<String>();
1955 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1956 if (entry.getValue().onNode(node)) {
1957 list.add(entry.getValue().getName());
1964 public List<Node> getListNodeWithConfiguredFlows() {
1965 Set<Node> set = new HashSet<Node>();
1966 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1967 set.add(entry.getValue().getNode());
1969 return new ArrayList<Node>(set);
1972 @SuppressWarnings("unchecked")
1973 private void loadFlowConfiguration() {
1974 ObjectReader objReader = new ObjectReader();
1975 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
1978 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
1981 if (pgConfig != null) {
1982 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
1983 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
1987 if (confList == null) {
1992 for (Integer key : confList.keySet()) {
1993 if (key.intValue() > maxKey) {
1994 maxKey = key.intValue();
1998 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
1999 addStaticFlowInternal(conf, true);
2004 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2005 return ois.readObject();
2009 public Status saveConfig() {
2010 return saveConfigInternal();
2013 private Status saveConfigInternal() {
2014 ObjectWriter objWriter = new ObjectWriter();
2015 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2016 for (Integer ordinal : staticFlows.keySet()) {
2017 FlowConfig config = staticFlows.get(ordinal);
2018 // Do not save dynamic and controller generated static flows
2019 if (config.isDynamic() || config.isInternalFlow()) {
2022 nonDynamicFlows.put(ordinal, config);
2024 objWriter.write(nonDynamicFlows, frmFileName);
2025 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2026 return new Status(StatusCode.SUCCESS, null);
2030 public void subnetNotify(Subnet sub, boolean add) {
2033 private void installImplicitARPReplyPunt(Node node) {
2039 List<String> puntAction = new ArrayList<String>();
2040 puntAction.add(ActionType.CONTROLLER.toString());
2042 FlowConfig allowARP = new FlowConfig();
2043 allowARP.setInstallInHw(true);
2044 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
2045 allowARP.setPriority("500");
2046 allowARP.setNode(node);
2047 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2048 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
2049 allowARP.setActions(puntAction);
2050 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
2056 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2059 * This method can be called from within the OSGi framework context,
2060 * given the programming operation can take sometime, it not good
2061 * pratice to have in it's context operations that can take time,
2062 * hence moving off to a different thread for async processing.
2064 private ExecutorService executor;
2066 public void modeChangeNotify(final Node node, final boolean proactive) {
2067 Callable<Status> modeChangeCallable = new Callable<Status>() {
2069 public Status call() throws Exception {
2070 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2072 List<String> puntAction = new ArrayList<String>();
2073 puntAction.add(ActionType.CONTROLLER.toString());
2075 FlowConfig allowARP = new FlowConfig();
2076 allowARP.setInstallInHw(true);
2077 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2078 allowARP.setPriority("1");
2079 allowARP.setNode(node);
2080 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2082 allowARP.setActions(puntAction);
2083 defaultConfigs.add(allowARP);
2085 FlowConfig allowLLDP = new FlowConfig();
2086 allowLLDP.setInstallInHw(true);
2087 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2088 allowLLDP.setPriority("1");
2089 allowLLDP.setNode(node);
2090 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2092 allowLLDP.setActions(puntAction);
2093 defaultConfigs.add(allowLLDP);
2095 List<String> dropAction = new ArrayList<String>();
2096 dropAction.add(ActionType.DROP.toString());
2098 FlowConfig dropAllConfig = new FlowConfig();
2099 dropAllConfig.setInstallInHw(true);
2100 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2101 + FlowConfig.INTERNALSTATICFLOWEND);
2102 dropAllConfig.setPriority("0");
2103 dropAllConfig.setNode(node);
2104 dropAllConfig.setActions(dropAction);
2105 defaultConfigs.add(dropAllConfig);
2107 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2108 for (FlowConfig fc : defaultConfigs) {
2109 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2110 if (status.isSuccess()) {
2111 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2113 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2117 return new Status(StatusCode.SUCCESS);
2122 * Execute the work outside the caller context, this could be an
2123 * expensive operation and we don't want to block the caller for it.
2125 this.executor.submit(modeChangeCallable);
2129 * Remove from the databases all the flows installed on the node
2133 private void cleanDatabaseForNode(Node node) {
2134 log.info("Cleaning Flow database for Node {}", node);
2135 if (nodeFlows.containsKey(node)) {
2136 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2138 for (FlowEntryInstall entry : toRemove) {
2139 updateLocalDatabase(entry, false);
2144 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2149 Match match = flow.getMatch();
2150 if (match.isPresent(MatchType.IN_PORT)) {
2151 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2152 if (matchPort.equals(nc)) {
2156 List<Action> actionsList = flow.getActions();
2157 if (actionsList != null) {
2158 for (Action action : actionsList) {
2159 if (action instanceof Output) {
2160 NodeConnector actionPort = ((Output) action).getPort();
2161 if (actionPort.equals(nc)) {
2171 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2172 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2176 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2180 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2181 FlowConfig derivedFlow = new FlowConfig(original);
2182 derivedFlow.setDynamic(true);
2183 derivedFlow.setPortGroup(null);
2184 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2185 derivedFlow.setIngressPort(port + "");
2189 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2190 for (FlowConfig staticFlow : staticFlows.values()) {
2191 if (staticFlow.getPortGroup() == null) {
2194 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2195 for (Short port : data.getPorts()) {
2196 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2197 addStaticFlowInternal(derivedFlow, false);
2203 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2204 for (FlowConfig staticFlow : staticFlows.values()) {
2205 if (staticFlow.getPortGroup() == null) {
2208 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2209 for (Short port : data.getPorts()) {
2210 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2211 removeStaticFlow(derivedFlow);
2218 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2219 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2220 Map<Node, PortGroup> existingData = portGroupData.get(config);
2221 if (existingData != null) {
2222 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2223 PortGroup existingPortGroup = existingData.get(entry.getKey());
2224 if (existingPortGroup == null) {
2226 existingData.put(entry.getKey(), entry.getValue());
2227 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2231 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2232 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2234 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2235 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2241 portGroupData.put(config, data);
2242 for (Node swid : data.keySet()) {
2243 addPortGroupFlows(config, swid, data.get(swid));
2250 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2251 PortGroupConfig config = portGroupConfigs.get(name);
2252 if (config != null) {
2256 if ((portGroupProvider == null) && !restore) {
2259 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2263 config = new PortGroupConfig(name, regex);
2264 portGroupConfigs.put(name, config);
2265 if (portGroupProvider != null) {
2266 portGroupProvider.createPortGroupConfig(config);
2272 public boolean delPortGroupConfig(String name) {
2273 PortGroupConfig config = portGroupConfigs.get(name);
2274 if (config == null) {
2278 if (portGroupProvider != null) {
2279 portGroupProvider.deletePortGroupConfig(config);
2281 portGroupConfigs.remove(name);
2285 private void usePortGroupConfig(String name) {
2286 PortGroupConfig config = portGroupConfigs.get(name);
2287 if (config == null) {
2290 if (portGroupProvider != null) {
2291 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2292 portGroupData.put(config, data);
2297 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2298 return portGroupConfigs;
2301 public boolean isPortGroupSupported() {
2302 if (portGroupProvider == null) {
2308 public void setIContainer(IContainer s) {
2312 public void unsetIContainer(IContainer s) {
2313 if (this.container == s) {
2314 this.container = null;
2319 public PortGroupProvider getPortGroupProvider() {
2320 return portGroupProvider;
2323 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2324 this.portGroupProvider = null;
2327 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2328 this.portGroupProvider = portGroupProvider;
2329 portGroupProvider.registerPortGroupChange(this);
2330 for (PortGroupConfig config : portGroupConfigs.values()) {
2331 portGroupProvider.createPortGroupConfig(config);
2335 public void setFrmAware(IForwardingRulesManagerAware obj) {
2336 this.frmAware.add(obj);
2339 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2340 this.frmAware.remove(obj);
2343 void setClusterContainerService(IClusterContainerServices s) {
2344 log.debug("Cluster Service set");
2345 this.clusterContainerService = s;
2348 void unsetClusterContainerService(IClusterContainerServices s) {
2349 if (this.clusterContainerService == s) {
2350 log.debug("Cluster Service removed!");
2351 this.clusterContainerService = null;
2355 private String getContainerName() {
2356 if (container == null) {
2357 return GlobalConstants.DEFAULT.toString();
2359 return container.getName();
2363 * Function called by the dependency manager when all the required
2364 * dependencies are satisfied
2368 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2369 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2371 inContainerMode = false;
2373 if (portGroupProvider != null) {
2374 portGroupProvider.registerPortGroupChange(this);
2379 registerWithOSGIConsole();
2382 * If we are not the first cluster node to come up, do not initialize
2383 * the static flow entries ordinal
2385 if (staticFlowsOrdinal.size() == 0) {
2386 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2389 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2391 // Initialize the event handler thread
2392 frmEventHandler = new Thread(new Runnable() {
2397 FRMEvent event = pendingEvents.take();
2398 if (event == null) {
2399 log.warn("Dequeued null event");
2402 if (event instanceof NodeUpdateEvent) {
2403 NodeUpdateEvent update = (NodeUpdateEvent) event;
2404 Node node = update.getNode();
2405 switch (update.getUpdateType()) {
2407 addStaticFlowsToSwitch(node);
2410 cleanDatabaseForNode(node);
2411 updateStaticFlowConfigsOnNodeDown(node);
2415 } else if (event instanceof ErrorReportedEvent) {
2416 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2417 processErrorEvent(errEvent);
2418 } else if (event instanceof WorkOrderEvent) {
2420 * Take care of handling the remote Work request
2422 WorkOrderEvent work = (WorkOrderEvent) event;
2423 FlowEntryDistributionOrder fe = work.getFe();
2425 logsync.trace("Executing the workOrder {}", fe);
2426 Status gotStatus = null;
2427 FlowEntryInstall feiCurrent = fe.getEntry();
2428 FlowEntryInstall feiNew = workOrder.get(fe.getEntry());
2429 switch (fe.getUpType()) {
2432 * TODO: Not still sure how to handle the
2435 gotStatus = addEntriesInternal(feiCurrent, true);
2438 gotStatus = modifyEntryInternal(feiCurrent, feiNew, true);
2441 gotStatus = removeEntryInternal(feiCurrent, true);
2445 workOrder.remove(fe);
2447 "The workOrder has been executed and now the status is being returned {}", fe);
2449 workStatus.put(fe, gotStatus);
2451 log.warn("Not expected null WorkOrder", work);
2453 } else if (event instanceof WorkStatusCleanup) {
2455 * Take care of handling the remote Work request
2457 WorkStatusCleanup work = (WorkStatusCleanup) event;
2458 FlowEntryDistributionOrder fe = work.getFe();
2460 logsync.trace("The workStatus {} is being removed", fe);
2461 workStatus.remove(fe);
2463 log.warn("Not expected null WorkStatus", work);
2466 log.warn("Dequeued unknown event {}", event.getClass()
2469 } catch (InterruptedException e) {
2470 // clear pending events
2471 pendingEvents.clear();
2475 }, "FRM EventHandler Collector");
2479 * Function called by the dependency manager when at least one dependency
2480 * become unsatisfied or when the component is shutting down because for
2481 * example bundle is being stopped.
2485 // Interrupt the thread
2486 frmEventHandler.interrupt();
2487 // Clear the pendingEvents queue
2488 pendingEvents.clear();
2490 workMonitor.clear();
2494 * Function called by dependency manager after "init ()" is called and after
2495 * the services provided by the class are registered in the service registry
2499 // Initialize graceful stop flag
2502 // Allocate the executor service
2503 this.executor = Executors.newSingleThreadExecutor();
2505 // Start event handler thread
2506 frmEventHandler.start();
2509 * Read startup and build database if we have not already gotten the
2510 * configurations synced from another node
2512 if (staticFlows.isEmpty()) {
2513 loadFlowConfiguration();
2518 * Function called by the dependency manager before the services exported by
2519 * the component are unregistered, this will be followed by a "destroy ()"
2524 uninstallAllFlowEntries(false);
2525 // Shutdown executor
2526 this.executor.shutdownNow();
2529 public void setFlowProgrammerService(IFlowProgrammerService service) {
2530 this.programmer = service;
2533 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2534 if (this.programmer == service) {
2535 this.programmer = null;
2539 public void setSwitchManager(ISwitchManager switchManager) {
2540 this.switchManager = switchManager;
2543 public void unsetSwitchManager(ISwitchManager switchManager) {
2544 if (this.switchManager == switchManager) {
2545 this.switchManager = null;
2550 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2551 if (!container.getName().equals(containerName)) {
2557 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2558 if (!container.getName().equals(containerName)) {
2561 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2562 container.getName(), t, current);
2564 * Whether it is an addition or removal, we have to recompute the merged
2565 * flows entries taking into account all the current container flows
2566 * because flow merging is not an injective function
2568 updateFlowsContainerFlow();
2572 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2573 if (!container.getName().equals(containerName)) {
2577 boolean updateStaticFlowCluster = false;
2582 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nc.getNode());
2583 if (nodeFlowEntries == null) {
2586 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2587 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nc)) {
2588 Status status = this.removeEntryInternal(fei, true);
2589 if (!status.isSuccess()) {
2593 * If the flow entry is a static flow, then update its
2596 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2597 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2598 if (flowConfig != null) {
2599 flowConfig.setStatus(PORTREMOVED);
2600 updateStaticFlowCluster = true;
2605 if (updateStaticFlowCluster) {
2606 refreshClusterStaticFlowsStatus(nc.getNode());
2610 List<FlowConfig> flowConfigForNode = getStaticFlows(nc.getNode());
2611 for (FlowConfig flowConfig : flowConfigForNode) {
2612 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nc)) {
2613 if (flowConfig.installInHw()) {
2614 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2615 if (!status.isSuccess()) {
2616 flowConfig.setStatus(status.getDescription());
2618 flowConfig.setStatus(SUCCESS);
2620 updateStaticFlowCluster = true;
2624 if (updateStaticFlowCluster) {
2625 refreshClusterStaticFlowsStatus(nc.getNode());
2635 public void containerModeUpdated(UpdateType update) {
2636 // Only default container instance reacts on this event
2637 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2643 * Controller is moving to container mode. We are in the default
2644 * container context, we need to remove all our non-internal flows
2645 * to prevent any container isolation breakage. We also need to
2646 * preserve our flow so that they can be re-installed if we move
2647 * back to non container mode (no containers).
2649 this.inContainerMode = true;
2650 this.uninstallAllFlowEntries(true);
2653 this.inContainerMode = false;
2654 this.reinstallAllFlowEntries();
2659 // Update our configuration DB
2660 updateStaticFlowConfigsOnContainerModeChange(update);
2663 protected abstract class FRMEvent {
2667 private class NodeUpdateEvent extends FRMEvent {
2668 private final Node node;
2669 private final UpdateType update;
2671 public NodeUpdateEvent(UpdateType update, Node node) {
2672 this.update = update;
2676 public UpdateType getUpdateType() {
2680 public Node getNode() {
2685 private class ErrorReportedEvent extends FRMEvent {
2686 private final long rid;
2687 private final Node node;
2688 private final Object error;
2690 public ErrorReportedEvent(long rid, Node node, Object error) {
2696 public long getRequestId() {
2700 public Object getError() {
2704 public Node getNode() {
2709 private class WorkOrderEvent extends FRMEvent {
2710 private FlowEntryDistributionOrder fe;
2711 private FlowEntryInstall newEntry;
2717 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2719 this.newEntry = newEntry;
2725 public FlowEntryDistributionOrder getFe() {
2730 * @return the newEntry
2732 public FlowEntryInstall getNewEntry() {
2737 private class WorkStatusCleanup extends FRMEvent {
2738 private FlowEntryDistributionOrder fe;
2743 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2750 public FlowEntryDistributionOrder getFe() {
2759 public String getHelp() {
2760 StringBuffer help = new StringBuffer();
2761 help.append("---FRM Matrix Application---\n");
2762 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2763 help.append("\t addMatrixConfig <name> <regex>\n");
2764 help.append("\t delMatrixConfig <name>\n");
2765 help.append("\t useMatrixConfig <name>\n");
2766 return help.toString();
2769 public void _printMatrixData(CommandInterpreter ci) {
2770 ci.println("Configs : ");
2771 ci.println("---------");
2772 ci.println(portGroupConfigs);
2774 ci.println("Data : ");
2775 ci.println("------");
2776 ci.println(portGroupData);
2779 public void _addMatrixConfig(CommandInterpreter ci) {
2780 String name = ci.nextArgument();
2781 String regex = ci.nextArgument();
2782 addPortGroupConfig(name, regex, false);
2785 public void _delMatrixConfig(CommandInterpreter ci) {
2786 String name = ci.nextArgument();
2787 delPortGroupConfig(name);
2790 public void _useMatrixConfig(CommandInterpreter ci) {
2791 String name = ci.nextArgument();
2792 usePortGroupConfig(name);
2795 public void _arpPunt(CommandInterpreter ci) {
2796 String switchId = ci.nextArgument();
2797 long swid = HexEncode.stringToLong(switchId);
2798 Node node = NodeCreator.createOFNode(swid);
2799 installImplicitARPReplyPunt(node);
2802 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2804 String nodeId = ci.nextArgument();
2805 if (nodeId == null) {
2806 ci.print("Node id not specified");
2810 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2811 } catch (NumberFormatException e) {
2812 ci.print("Node id not a number");
2815 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2818 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2820 String nodeId = ci.nextArgument();
2821 if (nodeId == null) {
2822 ci.print("Node id not specified");
2826 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2827 } catch (NumberFormatException e) {
2828 ci.print("Node id not a number");
2831 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2834 private Flow getSampleFlow(Node node) throws UnknownHostException {
2835 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2836 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2837 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2838 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2839 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2840 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2841 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2842 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2843 short ethertype = EtherTypes.IPv4.shortValue();
2844 short vlan = (short) 27;
2847 byte proto = IPProtocols.TCP.byteValue();
2848 short src = (short) 55000;
2852 * Create a SAL Flow aFlow
2854 Match match = new Match();
2855 match.setField(MatchType.IN_PORT, port);
2856 match.setField(MatchType.DL_SRC, srcMac);
2857 match.setField(MatchType.DL_DST, dstMac);
2858 match.setField(MatchType.DL_TYPE, ethertype);
2859 match.setField(MatchType.DL_VLAN, vlan);
2860 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2861 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2862 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2863 match.setField(MatchType.NW_TOS, tos);
2864 match.setField(MatchType.NW_PROTO, proto);
2865 match.setField(MatchType.TP_SRC, src);
2866 match.setField(MatchType.TP_DST, dst);
2868 List<Action> actions = new ArrayList<Action>();
2869 actions.add(new Output(oport));
2870 actions.add(new PopVlan());
2871 actions.add(new Flood());
2872 actions.add(new Controller());
2873 return new Flow(match, actions);
2877 public Status saveConfiguration() {
2878 return saveConfig();
2881 public void _frmNodeFlows(CommandInterpreter ci) {
2882 String nodeId = ci.nextArgument();
2883 Node node = Node.fromString(nodeId);
2885 ci.println("frmNodeFlows <node> [verbose]");
2888 boolean verbose = false;
2889 String verboseCheck = ci.nextArgument();
2890 if (verboseCheck != null) {
2891 verbose = verboseCheck.equals("true");
2894 if (!nodeFlows.containsKey(node)) {
2897 // Dump per node database
2898 for (FlowEntryInstall entry : nodeFlows.get(node)) {
2900 ci.println(node + " " + installedSwView.get(entry).getFlowName());
2902 ci.println(node + " " + installedSwView.get(entry).toString());
2907 public void _frmGroupFlows(CommandInterpreter ci) {
2908 String group = ci.nextArgument();
2909 if (group == null) {
2910 ci.println("frmGroupFlows <group> [verbose]");
2913 boolean verbose = false;
2914 String verboseCheck = ci.nextArgument();
2915 if (verboseCheck != null) {
2916 verbose = verboseCheck.equalsIgnoreCase("true");
2919 if (!groupFlows.containsKey(group)) {
2922 // Dump per node database
2923 ci.println("Group " + group + ":\n");
2924 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
2926 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
2928 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
2934 public void flowRemoved(Node node, Flow flow) {
2935 log.trace("Received flow removed notification on {} for {}", node, flow);
2937 // For flow entry identification, only node, match and priority matter
2938 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
2939 FlowEntryInstall installedEntry = this.installedSwView.get(test);
2940 if (installedEntry == null) {
2941 log.trace("Entry is not known to us");
2945 // Update Static flow status
2947 FlowConfig target = null;
2948 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2949 FlowConfig conf = entry.getValue();
2950 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
2951 key = entry.getKey();
2956 if (target != null) {
2957 // Update Configuration database
2958 target.toggleInstallation();
2959 target.setStatus(SUCCESS);
2960 staticFlows.put(key, target);
2963 // Update software views
2964 this.updateLocalDatabase(installedEntry, false);
2968 public void flowErrorReported(Node node, long rid, Object err) {
2969 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
2970 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
2973 private void processErrorEvent(ErrorReportedEvent event) {
2974 Node node = event.getNode();
2975 long rid = event.getRequestId();
2976 Object error = event.getError();
2977 String errorString = (error == null) ? "Not provided" : error.toString();
2979 * If this was for a flow install, remove the corresponding entry from
2980 * the software view. If it was a Looking for the rid going through the
2981 * software database. TODO: A more efficient rid <-> FlowEntryInstall
2982 * mapping will have to be added in future
2984 FlowEntryInstall target = null;
2985 for (FlowEntryInstall index : nodeFlows.get(node)) {
2986 FlowEntryInstall entry = installedSwView.get(index);
2987 if (entry.getRequestId() == rid) {
2992 if (target != null) {
2993 // This was a flow install, update database
2994 this.updateLocalDatabase(target, false);
2998 if (frmAware != null) {
2999 synchronized (frmAware) {
3000 for (IForwardingRulesManagerAware frma : frmAware) {
3002 frma.requestFailed(rid, errorString);
3003 } catch (Exception e) {
3004 log.warn("Failed to notify {}", frma);
3012 public Status solicitStatusResponse(Node node, boolean blocking) {
3013 Status rv = new Status(StatusCode.INTERNALERROR);
3015 if (this.programmer != null) {
3017 rv = programmer.syncSendBarrierMessage(node);
3019 rv = programmer.asyncSendBarrierMessage(node);
3026 public void unsetIConnectionManager(IConnectionManager s) {
3027 if (s == this.connectionManager) {
3028 this.connectionManager = null;
3032 public void setIConnectionManager(IConnectionManager s) {
3033 this.connectionManager = s;
3037 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3044 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3047 * Local updates are of no interest
3051 if (cacheName.equals(WORKORDERCACHE)) {
3052 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3054 * This is the case of one workOrder becoming available, so we need
3055 * to dispatch the work to the appropriate handler
3057 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3058 FlowEntryInstall fei = fe.getEntry();
3062 Node n = fei.getNode();
3063 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3064 logsync.trace("workOrder for fe {} processed locally", fe);
3065 // I'm the controller in charge for the request, queue it for
3067 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3069 } else if (cacheName.equals(WORKSTATUSCACHE)) {
3070 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3072 * This is the case of one workOrder being completed and a status
3075 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3077 * Check if the order was initiated by this controller in that case
3078 * we need to actually look at the status returned
3080 if (fe.getRequestorController()
3081 .equals(clusterContainerService.getMyAddress())) {
3082 FlowEntryDistributionOrderFutureTask fet = workMonitor.get(fe);
3084 logsync.trace("workStatus response is for us {}", fe);
3085 // Signal we got the status
3086 fet.gotStatus(fe, workStatus.get(fe));
3087 pendingEvents.offer(new WorkStatusCleanup(fe));
3094 public void entryDeleted(Object key, String cacheName, boolean originLocal) {