2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.forwardingrulesmanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.UnknownHostException;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.EnumSet;
19 import java.util.HashSet;
20 import java.util.List;
22 import java.util.Map.Entry;
24 import java.util.concurrent.BlockingQueue;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.LinkedBlockingQueue;
33 import org.eclipse.osgi.framework.console.CommandInterpreter;
34 import org.eclipse.osgi.framework.console.CommandProvider;
35 import org.opendaylight.controller.clustering.services.CacheConfigException;
36 import org.opendaylight.controller.clustering.services.CacheExistException;
37 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
38 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
39 import org.opendaylight.controller.clustering.services.IClusterServices;
40 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
41 import org.opendaylight.controller.connectionmanager.IConnectionManager;
42 import org.opendaylight.controller.containermanager.IContainerManager;
43 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
44 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
45 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
46 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
47 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
48 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
50 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
51 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
52 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
53 import org.opendaylight.controller.sal.action.Action;
54 import org.opendaylight.controller.sal.action.ActionType;
55 import org.opendaylight.controller.sal.action.Controller;
56 import org.opendaylight.controller.sal.action.Flood;
57 import org.opendaylight.controller.sal.action.Output;
58 import org.opendaylight.controller.sal.action.PopVlan;
59 import org.opendaylight.controller.sal.connection.ConnectionLocality;
60 import org.opendaylight.controller.sal.core.Config;
61 import org.opendaylight.controller.sal.core.ContainerFlow;
62 import org.opendaylight.controller.sal.core.IContainer;
63 import org.opendaylight.controller.sal.core.IContainerLocalListener;
64 import org.opendaylight.controller.sal.core.Node;
65 import org.opendaylight.controller.sal.core.NodeConnector;
66 import org.opendaylight.controller.sal.core.Property;
67 import org.opendaylight.controller.sal.core.UpdateType;
68 import org.opendaylight.controller.sal.flowprogrammer.Flow;
69 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
70 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
71 import org.opendaylight.controller.sal.match.Match;
72 import org.opendaylight.controller.sal.match.MatchType;
73 import org.opendaylight.controller.sal.utils.EtherTypes;
74 import org.opendaylight.controller.sal.utils.GlobalConstants;
75 import org.opendaylight.controller.sal.utils.HexEncode;
76 import org.opendaylight.controller.sal.utils.IObjectReader;
77 import org.opendaylight.controller.sal.utils.IPProtocols;
78 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
79 import org.opendaylight.controller.sal.utils.NodeCreator;
80 import org.opendaylight.controller.sal.utils.ObjectReader;
81 import org.opendaylight.controller.sal.utils.ObjectWriter;
82 import org.opendaylight.controller.sal.utils.Status;
83 import org.opendaylight.controller.sal.utils.StatusCode;
84 import org.opendaylight.controller.switchmanager.IInventoryListener;
85 import org.opendaylight.controller.switchmanager.ISwitchManager;
86 import org.opendaylight.controller.switchmanager.ISwitchManagerAware;
87 import org.opendaylight.controller.switchmanager.Subnet;
88 import org.osgi.framework.BundleContext;
89 import org.osgi.framework.FrameworkUtil;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
94 * Class that manages forwarding rule installation and removal per container of
95 * the network. It also maintains the central repository of all the forwarding
96 * rules installed on the network nodes.
98 public class ForwardingRulesManager implements
99 IForwardingRulesManager,
100 PortGroupChangeListener,
101 IContainerLocalListener,
103 IConfigurationContainerAware,
106 ICacheUpdateAware<Object,Object>,
108 IFlowProgrammerListener {
109 private static final String NODEDOWN = "Node is Down";
110 private static final String SUCCESS = StatusCode.SUCCESS.toString();
111 private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class);
112 private static final String PORTREMOVED = "Port removed";
113 private static final Logger logsync = LoggerFactory.getLogger("FRMsync");
114 private String frmFileName;
115 private String portGroupFileName;
116 private ConcurrentMap<Integer, FlowConfig> staticFlows;
117 private ConcurrentMap<Integer, Integer> staticFlowsOrdinal;
118 private ConcurrentMap<String, PortGroupConfig> portGroupConfigs;
119 private ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>> portGroupData;
120 private ConcurrentMap<String, Object> TSPolicies;
121 private IContainerManager containerManager;
122 private boolean inContainerMode; // being used by global instance only
123 protected boolean stopping;
126 * Flow database. It's the software view of what was requested to install
127 * and what is installed on the switch. It is indexed by the entry itself.
128 * The entry's hashcode resumes the network node index, the flow's priority
129 * and the flow's match. The value element is a class which contains the
130 * flow entry pushed by the applications modules and the respective
131 * container flow merged version. In absence of container flows, the two
132 * flow entries are the same.
134 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
135 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
137 * Per node and per group indexing
139 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
140 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
143 * Inactive flow list. This is for the global instance of FRM It will
144 * contain all the flow entries which were installed on the global container
145 * when the first container is created.
147 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
149 private IContainer container;
150 private Set<IForwardingRulesManagerAware> frmAware =
151 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
152 private PortGroupProvider portGroupProvider;
153 private IFlowProgrammerService programmer;
154 private IClusterContainerServices clusterContainerService = null;
155 private ISwitchManager switchManager;
156 private Thread frmEventHandler;
157 protected BlockingQueue<FRMEvent> pendingEvents;
159 // Distributes FRM programming in the cluster
160 private IConnectionManager connectionManager;
163 * Name clustered caches used to support FRM entry distribution these are by
164 * necessity non-transactional as long as need to be able to synchronize
165 * states also while a transaction is in progress
167 static final String WORKORDERCACHE = "frm.workOrder";
168 static final String WORKSTATUSCACHE = "frm.workStatus";
171 * Data structure responsible for distributing the FlowEntryInstall requests
172 * in the cluster. The key value is entry that is being either Installed or
173 * Updated or Delete. The value field is the same of the key value in case
174 * of Installation or Deletion, it's the new entry in case of Modification,
175 * this because the clustering caches don't allow null values.
177 * The logic behind this data structure is that the controller that initiate
178 * the request will place the order here, someone will pick it and then will
179 * remove from this data structure because is being served.
181 * TODO: We need to have a way to cleanup this data structure if entries are
182 * not picked by anyone, which is always a case can happen especially on
183 * Node disconnect cases.
185 protected ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
188 * Data structure responsible for retrieving the results of the workOrder
189 * submitted to the cluster.
191 * The logic behind this data structure is that the controller that has
192 * executed the order will then place the result in workStatus signaling
193 * that there was a success or a failure.
195 * TODO: The workStatus entries need to have a lifetime associated in case
196 * of requestor controller leaving the cluster.
198 protected ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
201 * Local Map used to hold the Future which a caller can use to monitor for
204 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
205 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
208 * Max pool size for the executor
210 private static final int maxPoolSize = 10;
214 * Entry being installed/updated/removed
216 * New entry will be placed after the update operation. Valid
217 * only for UpdateType.CHANGED, null for all the other cases
220 * @return a Future object for monitoring the progress of the result, or
221 * null in case the processing should take place locally
223 private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
225 // A null entry it's an unexpected condition, anyway it's safe to keep
226 // the handling local
231 Node n = e.getNode();
232 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
233 // Create the work order and distribute it
234 FlowEntryDistributionOrder fe =
235 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
236 // First create the monitor job
237 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
238 logsync.trace("Node {} not local so sending fe {}", n, fe);
239 workMonitor.put(fe, ret);
240 if (t.equals(UpdateType.CHANGED)) {
241 // Then distribute the work
242 workOrder.put(fe, u);
244 // Then distribute the work
245 workOrder.put(fe, e);
247 logsync.trace("WorkOrder requested");
248 // Now create an Handle to monitor the execution of the operation
252 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
257 * Adds a flow entry onto the network node It runs various validity checks
258 * and derive the final container flows merged entries that will be
259 * attempted to be installed
262 * the original flow entry application requested to add
264 * the flag indicating if this is a asynchronous request
265 * @return the status of this request. In case of asynchronous call, it will
266 * contain the unique id assigned to this request
268 private Status addEntry(FlowEntry flowEntry, boolean async) {
271 if (flowEntry == null || flowEntry.getNode() == null) {
272 String msg = "Invalid FlowEntry";
273 String logMsg = msg + ": {}";
274 log.warn(logMsg, flowEntry);
275 return new Status(StatusCode.NOTACCEPTABLE, msg);
279 * Derive the container flow merged entries to install In presence of N
280 * container flows, we may end up with N different entries to install...
282 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
284 // Container Flow conflict Check
285 if (toInstallList.isEmpty()) {
286 String msg = "Flow Entry conflicts with all Container Flows";
287 String logMsg = msg + ": {}";
288 log.warn(logMsg, flowEntry);
289 return new Status(StatusCode.CONFLICT, msg);
292 // Derive the list of entries good to be installed
293 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
294 for (FlowEntryInstall entry : toInstallList) {
295 // Conflict Check: Verify new entry would not overwrite existing
297 if (this.installedSwView.containsKey(entry)) {
298 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
299 log.trace("Aborting to install {}", entry);
302 toInstallSafe.add(entry);
305 // Declare failure if all the container flow merged entries clash with
307 if (toInstallSafe.size() == 0) {
308 String msg = "A flow with same match and priority exists on the target node";
309 String logMsg = msg + ": {}";
310 log.warn(logMsg, flowEntry);
311 return new Status(StatusCode.CONFLICT, msg);
314 // Try to install an entry at the time
315 Status error = new Status(null, null);
316 Status succeded = null;
317 boolean oneSucceded = false;
318 for (FlowEntryInstall installEntry : toInstallSafe) {
320 // Install and update database
321 Status ret = addEntriesInternal(installEntry, async);
323 if (ret.isSuccess()) {
326 * The first successful status response will be returned For the
327 * asynchronous call, we can discard the container flow
328 * complication for now and assume we will always deal with one
329 * flow only per request
334 log.warn("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
338 return (oneSucceded) ? succeded : error;
342 * Given a flow entry and the list of container flows, it returns the list
343 * of container flow merged flow entries good to be installed on this
344 * container. If the list of container flows is null or empty, the install
345 * entry list will contain only one entry, the original flow entry. If the
346 * flow entry is congruent with all the N container flows, then the output
347 * install entry list will contain N entries. If the output list is empty,
348 * it means the passed flow entry conflicts with all the container flows.
351 * The list of container flows
352 * @return the list of container flow merged entries good to be installed on
355 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
356 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
358 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
359 // No container flows => entry good to be installed unchanged
360 toInstallList.add(new FlowEntryInstall(request.clone(), null));
362 // Create the list of entries to be installed. If the flow entry is
363 // not congruent with any container flow, no install entries will be
365 for (ContainerFlow cFlow : container.getContainerFlows()) {
366 if (cFlow.allowsFlow(request.getFlow())) {
367 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
371 return toInstallList;
375 * Modify a flow entry with a new one It runs various validity check and
376 * derive the final container flows merged flow entries to work with
378 * @param currentFlowEntry
379 * @param newFlowEntry
381 * the flag indicating if this is a asynchronous request
382 * @return the status of this request. In case of asynchronous call, it will
383 * contain the unique id assigned to this request
385 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
389 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
390 || newFlowEntry.getNode() == null) {
391 String msg = "Modify: Invalid FlowEntry";
392 String logMsg = msg + ": {} or {}";
393 log.warn(logMsg, currentFlowEntry, newFlowEntry);
394 return new Status(StatusCode.NOTACCEPTABLE, msg);
396 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
397 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
398 String msg = "Modify: Incompatible Flow Entries";
399 String logMsg = msg + ": {} and {}";
400 log.warn(logMsg, currentFlowEntry, newFlowEntry);
401 return new Status(StatusCode.NOTACCEPTABLE, msg);
405 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
406 String msg = "Modify skipped as flows are the same";
407 String logMsg = msg + ": {} and {}";
408 log.debug(logMsg, currentFlowEntry, newFlowEntry);
409 return new Status(StatusCode.SUCCESS, msg);
413 * Conflict Check: Verify the new entry would not conflict with an
414 * existing one. This is a loose check on the previous original flow
415 * entry requests. No check on the container flow merged flow entries
418 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
419 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
420 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
421 String logMsg = msg + ": {}";
422 log.warn(logMsg, currentFlowEntry);
423 return new Status(StatusCode.CONFLICT, msg);
426 // Derive the installed and toInstall entries
427 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
428 container.getContainerFlows());
429 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
431 if (toInstallList.isEmpty()) {
432 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
433 String logMsg = msg + ": {}";
434 log.warn(logMsg, newFlowEntry);
436 return new Status(StatusCode.CONFLICT, msg);
440 * If the two list sizes differ, it means the new flow entry does not
441 * satisfy the same number of container flows the current entry does.
442 * This is only possible when the new entry and current entry have
443 * different match. In this scenario the modification would ultimately
444 * be handled as a remove and add operations in the protocol plugin.
446 * Also, if any of the new flow entries would clash with an existing
447 * one, we cannot proceed with the modify operation, because it would
448 * fail for some entries and leave stale entries on the network node.
449 * Modify path can be taken only if it can be performed completely, for
452 * So, for the above two cases, to simplify, let's decouple the modify
453 * in: 1) remove current entries 2) install new entries
455 Status succeeded = null;
456 boolean decouple = false;
457 if (installedList.size() != toInstallList.size()) {
458 log.info("Modify: New flow entry does not satisfy the same "
459 + "number of container flows as the original entry does");
462 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
463 for (FlowEntryInstall installEntry : toInstallList) {
465 * Conflict Check: Verify the new entry would not overwrite another
468 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
469 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
470 log.info("Modify: new container flow merged flow entry clashes with existing flow");
473 toInstallSafe.add(installEntry);
478 // Remove current entries
479 for (FlowEntryInstall currEntry : installedList) {
480 this.removeEntryInternal(currEntry, async);
482 // Install new entries
483 for (FlowEntryInstall newEntry : toInstallSafe) {
484 succeeded = this.addEntriesInternal(newEntry, async);
488 * The two list have the same size and the entries to install do not
489 * clash with any existing flow on the network node. We assume here
490 * (and might be wrong) that the same container flows that were
491 * satisfied by the current entries are the same that are satisfied
492 * by the new entries. Let's take the risk for now.
494 * Note: modification has to be complete. If any entry modification
495 * fails, we need to stop, restore the already modified entries, and
498 Status retModify = null;
500 int size = toInstallList.size();
502 // Modify and update database
503 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
504 if (retModify.isSuccess()) {
510 // Check if uncompleted modify
512 log.warn("Unable to perform a complete modify for all the container flows merged entries");
513 // Restore original entries
516 log.info("Attempting to restore initial entries");
517 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
518 if (retExt.isSuccess()) {
524 // Fatal error, recovery failed
526 String msg = "Flow recovery failed ! Unrecoverable Error";
528 return new Status(StatusCode.INTERNALERROR, msg);
531 succeeded = retModify;
534 * The first successful status response will be returned. For the
535 * asynchronous call, we can discard the container flow complication for
536 * now and assume we will always deal with one flow only per request
542 * This is the function that modifies the final container flows merged
543 * entries on the network node and update the database. It expects that all
544 * the validity checks are passed
546 * @param currentEntries
549 * the flag indicating if this is a asynchronous request
550 * @return the status of this request. In case of asynchronous call, it will
551 * contain the unique id assigned to this request
553 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
554 FlowEntryDistributionOrderFutureTask futureStatus =
555 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
556 if (futureStatus != null) {
557 Status retStatus = new Status(StatusCode.UNDEFINED);
559 retStatus = futureStatus.get();
560 if (retStatus.getCode()
561 .equals(StatusCode.TIMEOUT)) {
562 // A timeout happened, lets cleanup the workMonitor
563 workMonitor.remove(futureStatus.getOrder());
565 } catch (InterruptedException e) {
567 } catch (ExecutionException e) {
572 // Modify the flow on the network node
573 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
574 .getFlow(), newEntries.getInstall()
575 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
576 .getFlow(), newEntries.getInstall()
579 if (!status.isSuccess()) {
580 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
581 status.getDescription());
585 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
588 newEntries.setRequestId(status.getRequestId());
589 updateLocalDatabase(currentEntries, false);
590 updateLocalDatabase(newEntries, true);
597 * Remove a flow entry. If the entry is not present in the software view
598 * (entry or node not present), it return successfully
601 * the flow entry to remove
603 * the flag indicating if this is a asynchronous request
604 * @return the status of this request. In case of asynchronous call, it will
605 * contain the unique id assigned to this request
607 private Status removeEntry(FlowEntry flowEntry, boolean async) {
608 Status error = new Status(null, null);
611 if (flowEntry == null || flowEntry.getNode() == null) {
612 String msg = "Invalid FlowEntry";
613 String logMsg = msg + ": {}";
614 log.warn(logMsg, flowEntry);
615 return new Status(StatusCode.NOTACCEPTABLE, msg);
618 // Derive the container flows merged installed entries
619 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
621 Status succeeded = null;
622 boolean atLeastOneRemoved = false;
623 for (FlowEntryInstall entry : installedList) {
624 if (!installedSwView.containsKey(entry)) {
625 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
626 log.debug(logMsg, flowEntry);
627 if (installedList.size() == 1) {
628 // If we had only one entry to remove, we are done
629 return new Status(StatusCode.SUCCESS);
635 // Remove and update DB
636 Status ret = removeEntryInternal(entry, async);
638 if (!ret.isSuccess()) {
640 log.warn("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
641 if (installedList.size() == 1) {
642 // If we had only one entry to remove, this is fatal failure
647 atLeastOneRemoved = true;
652 * No worries if full removal failed. Consistency checker will take care
653 * of removing the stale entries later, or adjusting the software
654 * database if not in sync with hardware
656 return (atLeastOneRemoved) ? succeeded : error;
660 * This is the function that removes the final container flows merged entry
661 * from the network node and update the database. It expects that all the
662 * validity checks are passed
665 * the flow entry to remove
667 * the flag indicating if this is a asynchronous request
668 * @return the status of this request. In case of asynchronous call, it will
669 * contain the unique id assigned to this request
671 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
672 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
673 if (futureStatus != null) {
674 Status retStatus = new Status(StatusCode.UNDEFINED);
676 retStatus = futureStatus.get();
677 if (retStatus.getCode()
678 .equals(StatusCode.TIMEOUT)) {
679 // A timeout happened, lets cleanup the workMonitor
680 workMonitor.remove(futureStatus.getOrder());
682 } catch (InterruptedException e) {
684 } catch (ExecutionException e) {
689 // Mark the entry to be deleted (for CC just in case we fail)
693 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
694 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
697 if (!status.isSuccess()) {
698 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
699 status.getDescription());
702 log.trace("Removed {}", entry.getInstall());
705 updateLocalDatabase(entry, false);
712 * This is the function that installs the final container flow merged entry
713 * on the network node and updates the database. It expects that all the
714 * validity and conflict checks are passed. That means it does not check
715 * whether this flow would conflict or overwrite an existing one.
718 * the flow entry to install
720 * the flag indicating if this is a asynchronous request
721 * @return the status of this request. In case of asynchronous call, it will
722 * contain the unique id assigned to this request
724 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
725 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
726 if (futureStatus != null) {
727 Status retStatus = new Status(StatusCode.UNDEFINED);
729 retStatus = futureStatus.get();
730 if (retStatus.getCode()
731 .equals(StatusCode.TIMEOUT)) {
732 // A timeout happened, lets cleanup the workMonitor
733 workMonitor.remove(futureStatus.getOrder());
735 } catch (InterruptedException e) {
737 } catch (ExecutionException e) {
742 // Install the flow on the network node
743 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
744 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
747 if (!status.isSuccess()) {
748 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
749 status.getDescription());
753 log.trace("Added {}", entry.getInstall());
756 entry.setRequestId(status.getRequestId());
757 updateLocalDatabase(entry, true);
764 * Returns true if the flow conflicts with all the container's flows. This
765 * means that if the function returns true, the passed flow entry is
766 * congruent with at least one container flow, hence it is good to be
767 * installed on this container.
770 * @return true if flow conflicts with all the container flows, false
773 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
774 List<ContainerFlow> cFlowList = container.getContainerFlows();
776 // Validity check and avoid unnecessary computation
777 // Also takes care of default container where no container flows are
779 if (cFlowList == null || cFlowList.isEmpty()) {
783 for (ContainerFlow cFlow : cFlowList) {
784 if (cFlow.allowsFlow(flowEntry.getFlow())) {
785 // Entry is allowed by at least one container flow: good to go
792 private ConcurrentMap.Entry<Integer, FlowConfig> getStaticFlowEntry(String name, Node node) {
793 for (ConcurrentMap.Entry<Integer, FlowConfig> flowEntry : staticFlows.entrySet()) {
794 FlowConfig flowConfig = flowEntry.getValue();
795 if (flowConfig.isByNameAndNodeIdEqual(name, node)) {
802 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
803 // Update the software view
804 updateSwViewes(entry, add);
806 // Update node indexed flow database
807 updateNodeFlowsDB(entry, add);
809 // Update group indexed flow database
810 updateGroupFlowsDB(entry, add);
814 * Update the node mapped flows database
816 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
818 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
819 installedSwView.put(flowEntries, flowEntries);
821 originalSwView.remove(flowEntries.getOriginal());
822 installedSwView.remove(flowEntries);
827 * Update the node mapped flows database
829 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
830 Node node = flowEntries.getNode();
832 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
833 if (nodeIndeces == null) {
837 nodeIndeces = new ArrayList<FlowEntryInstall>();
842 nodeIndeces.add(flowEntries);
844 nodeIndeces.remove(flowEntries);
847 // Update cache across cluster
848 if (nodeIndeces.isEmpty()) {
849 this.nodeFlows.remove(node);
851 this.nodeFlows.put(node, nodeIndeces);
856 * Update the group name mapped flows database
858 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
859 String groupName = flowEntries.getGroupName();
861 // Flow may not be part of a group
862 if (groupName == null) {
866 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
867 if (indices == null) {
871 indices = new ArrayList<FlowEntryInstall>();
876 indices.add(flowEntries);
878 indices.remove(flowEntries);
881 // Update cache across cluster
882 if (indices.isEmpty()) {
883 this.groupFlows.remove(groupName);
885 this.groupFlows.put(groupName, indices);
890 * Remove a flow entry that has been added previously First checks if the
891 * entry is effectively present in the local database
893 @SuppressWarnings("unused")
894 private Status removeEntry(Node node, String flowName) {
895 FlowEntryInstall target = null;
898 for (FlowEntryInstall entry : installedSwView.values()) {
899 if (entry.equalsByNodeAndName(node, flowName)) {
905 // If it is not there, stop any further processing
906 if (target == null) {
907 return new Status(StatusCode.SUCCESS, "Entry is not present");
911 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
914 if (status.isSuccess()) {
915 updateLocalDatabase(target, false);
918 log.warn("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
919 status.getDescription());
926 public Status installFlowEntry(FlowEntry flowEntry) {
928 if (isContainerModeAllowed(flowEntry)) {
929 status = addEntry(flowEntry, false);
931 String msg = "Controller in container mode: Install Refused";
932 String logMsg = msg + ": {}";
933 status = new Status(StatusCode.NOTACCEPTABLE, msg);
934 log.warn(logMsg, flowEntry);
940 public Status installFlowEntryAsync(FlowEntry flowEntry) {
942 if (isContainerModeAllowed(flowEntry)) {
943 status = addEntry(flowEntry, true);
945 String msg = "Controller in container mode: Install Refused";
946 status = new Status(StatusCode.NOTACCEPTABLE, msg);
953 public Status uninstallFlowEntry(FlowEntry flowEntry) {
955 if (isContainerModeAllowed(flowEntry)) {
956 status = removeEntry(flowEntry, false);
958 String msg = "Controller in container mode: Uninstall Refused";
959 String logMsg = msg + ": {}";
960 status = new Status(StatusCode.NOTACCEPTABLE, msg);
961 log.warn(logMsg, flowEntry);
967 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
969 if (isContainerModeAllowed(flowEntry)) {
970 status = removeEntry(flowEntry, true);
972 String msg = "Controller in container mode: Uninstall Refused";
973 status = new Status(StatusCode.NOTACCEPTABLE, msg);
980 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
981 Status status = null;
982 if (isContainerModeAllowed(currentFlowEntry)) {
983 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
985 String msg = "Controller in container mode: Modify Refused";
986 String logMsg = msg + ": {}";
987 status = new Status(StatusCode.NOTACCEPTABLE, msg);
988 log.warn(logMsg, newFlowEntry);
994 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
995 Status status = null;
996 if (isContainerModeAllowed(currentFlowEntry)) {
997 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
999 String msg = "Controller in container mode: Modify Refused";
1000 status = new Status(StatusCode.NOTACCEPTABLE, msg);
1007 * Returns whether the specified flow entry is allowed to be
1008 * installed/removed/modified based on the current container mode status.
1009 * This call always returns true in the container instance of forwarding
1010 * rules manager. It is meant for the global instance only (default
1011 * container) of forwarding rules manager. Idea is that for assuring
1012 * container isolation of traffic, flow installation in default container is
1013 * blocked when in container mode (containers are present). The only flows
1014 * that are allowed in container mode in the default container are the
1015 * proactive flows, the ones automatically installed on the network node
1016 * which forwarding mode has been configured to "proactive". These flows are
1017 * needed by controller to discover the nodes topology and to discover the
1018 * attached hosts for some SDN switches.
1021 * The flow entry to be installed/removed/modified
1022 * @return true if not in container mode or if flowEntry is internally
1025 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1026 return (!inContainerMode) ? true : flowEntry.isInternal();
1030 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1032 * Run a check on the original entries to decide whether to go with a
1033 * add or modify method. A loose check means only check against the
1034 * original flow entry requests and not against the installed flow
1035 * entries which are the result of the original entry merged with the
1036 * container flow(s) (if any). The modifyFlowEntry method in presence of
1037 * conflicts with the Container flows (if any) would revert back to a
1038 * delete + add pattern
1040 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1042 if (currentFlowEntry != null) {
1043 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1045 return installFlowEntry(newFlowEntry);
1050 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1052 * Run a check on the original entries to decide whether to go with a
1053 * add or modify method. A loose check means only check against the
1054 * original flow entry requests and not against the installed flow
1055 * entries which are the result of the original entry merged with the
1056 * container flow(s) (if any). The modifyFlowEntry method in presence of
1057 * conflicts with the Container flows (if any) would revert back to a
1058 * delete + add pattern
1060 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1062 if (currentFlowEntry != null) {
1063 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1065 return installFlowEntryAsync(newFlowEntry);
1070 public Status uninstallFlowEntryGroup(String groupName) {
1071 if (groupName == null || groupName.isEmpty()) {
1072 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1074 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1075 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1077 if (inContainerMode) {
1078 String msg = "Controller in container mode: Group Uninstall Refused";
1079 String logMsg = msg + ": {}";
1080 log.warn(logMsg, groupName);
1081 return new Status(StatusCode.NOTACCEPTABLE, msg);
1083 int toBeRemoved = 0;
1085 if (groupFlows.containsKey(groupName)) {
1086 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1087 toBeRemoved = list.size();
1088 for (FlowEntryInstall entry : list) {
1089 Status status = this.removeEntry(entry.getOriginal(), false);
1090 if (status.isSuccess()) {
1093 error = status.getDescription();
1097 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1098 "Not all the flows were removed: " + error);
1102 public Status uninstallFlowEntryGroupAsync(String groupName) {
1103 if (groupName == null || groupName.isEmpty()) {
1104 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1106 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1107 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1109 if (inContainerMode) {
1110 String msg = "Controller in container mode: Group Uninstall Refused";
1111 String logMsg = msg + ": {}";
1112 log.warn(logMsg, groupName);
1113 return new Status(StatusCode.NOTACCEPTABLE, msg);
1115 if (groupFlows.containsKey(groupName)) {
1116 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1117 for (FlowEntryInstall entry : list) {
1118 this.removeEntry(entry.getOriginal(), true);
1121 return new Status(StatusCode.SUCCESS);
1125 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1126 return entryConflictsWithContainerFlows(flowEntry);
1130 * Updates all installed flows because the container flow got updated This
1131 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1132 * Reinstall of all flows This is needed because a new container flows
1133 * merged flow may conflict with an existing old container flows merged flow
1134 * on the network node
1136 protected void updateFlowsContainerFlow() {
1137 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1138 // First remove all installed entries
1139 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1140 FlowEntryInstall current = entry.getValue();
1141 // Store the original entry
1142 toReInstall.add(current.getOriginal());
1143 // Remove the old couples. No validity checks to be run, use the
1145 this.removeEntryInternal(current, false);
1147 // Then reinstall the original entries
1148 for (FlowEntry entry : toReInstall) {
1149 // Reinstall the original flow entries, via the regular path: new
1150 // cFlow merge + validations
1151 this.installFlowEntry(entry);
1155 private void nonClusterObjectCreate() {
1156 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1157 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1158 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
1159 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
1160 TSPolicies = new ConcurrentHashMap<String, Object>();
1161 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1162 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1163 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1164 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1165 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1168 private void registerWithOSGIConsole() {
1169 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1170 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1174 public void setTSPolicyData(String policyname, Object o, boolean add) {
1177 /* Check if this policy already exists */
1178 if (!(TSPolicies.containsKey(policyname))) {
1179 TSPolicies.put(policyname, o);
1182 TSPolicies.remove(policyname);
1184 if (frmAware != null) {
1185 synchronized (frmAware) {
1186 for (IForwardingRulesManagerAware frma : frmAware) {
1188 frma.policyUpdate(policyname, add);
1189 } catch (Exception e) {
1190 log.warn("Exception on callback", e);
1198 public Map<String, Object> getTSPolicyData() {
1203 public Object getTSPolicyData(String policyName) {
1204 if (TSPolicies.containsKey(policyName)) {
1205 return TSPolicies.get(policyName);
1212 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1213 List<FlowEntry> list = new ArrayList<FlowEntry>();
1214 if (policyName != null && !policyName.trim().isEmpty()) {
1215 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1216 if (policyName.equals(entry.getKey().getGroupName())) {
1217 list.add(entry.getKey().clone());
1225 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1226 List<FlowEntry> list = new ArrayList<FlowEntry>();
1227 if (policyName != null && !policyName.trim().isEmpty()) {
1228 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1229 if (policyName.equals(entry.getKey().getGroupName())) {
1230 list.add(entry.getKey().getInstall().clone());
1238 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1240 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1241 if (flow.getFlowName().equals(flowName)) {
1242 FlowEntry currentFlowEntry = flow.getOriginal();
1243 FlowEntry newFlowEntry = currentFlowEntry.clone();
1244 for (NodeConnector dstPort : portList) {
1245 newFlowEntry.getFlow().addAction(new Output(dstPort));
1247 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1248 if (error.isSuccess()) {
1249 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1251 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1252 currentFlowEntry.toString(), error.getDescription());
1257 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1261 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1262 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1263 FlowEntryInstall flow = this.installedSwView.get(index);
1264 if (flow.getFlowName().equals(flowName)) {
1265 FlowEntry currentFlowEntry = flow.getOriginal();
1266 FlowEntry newFlowEntry = currentFlowEntry.clone();
1267 for (NodeConnector dstPort : portList) {
1268 Action action = new Output(dstPort);
1269 newFlowEntry.getFlow().removeAction(action);
1271 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1272 if (status.isSuccess()) {
1273 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1275 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1276 currentFlowEntry.toString(), status.getDescription());
1281 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1285 * This function assumes the target flow has only one output port
1288 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1289 FlowEntry currentFlowEntry = null;
1290 FlowEntry newFlowEntry = null;
1293 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1294 FlowEntryInstall flow = this.installedSwView.get(index);
1295 if (flow.getFlowName().equals(flowName)) {
1296 currentFlowEntry = flow.getOriginal();
1300 if (currentFlowEntry == null) {
1301 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1305 // Create a flow copy with the new output port
1306 newFlowEntry = currentFlowEntry.clone();
1307 Action target = null;
1308 for (Action action : newFlowEntry.getFlow().getActions()) {
1309 if (action.getType() == ActionType.OUTPUT) {
1314 newFlowEntry.getFlow().removeAction(target);
1315 newFlowEntry.getFlow().addAction(new Output(outPort));
1317 // Modify on network node
1318 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1320 if (status.isSuccess()) {
1321 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1323 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1324 status.getDescription());
1330 public NodeConnector getOutputPort(Node node, String flowName) {
1331 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1332 FlowEntryInstall flow = this.installedSwView.get(index);
1333 if (flow.getFlowName().equals(flowName)) {
1334 for (Action action : flow.getOriginal().getFlow().getActions()) {
1335 if (action.getType() == ActionType.OUTPUT) {
1336 return ((Output) action).getPort();
1344 private void cacheStartup() {
1349 private void allocateCaches() {
1350 if (this.clusterContainerService == null) {
1351 log.warn("Un-initialized clusterContainerService, can't create cache");
1355 log.debug("Allocating caches for Container {}", container.getName());
1358 clusterContainerService.createCache("frm.originalSwView",
1359 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1361 clusterContainerService.createCache("frm.installedSwView",
1362 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1364 clusterContainerService.createCache("frm.inactiveFlows",
1365 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1367 clusterContainerService.createCache("frm.nodeFlows",
1368 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1370 clusterContainerService.createCache("frm.groupFlows",
1371 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1373 clusterContainerService.createCache("frm.staticFlows",
1374 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1376 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1377 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1379 clusterContainerService.createCache("frm.portGroupConfigs",
1380 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1382 clusterContainerService.createCache("frm.portGroupData",
1383 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1385 clusterContainerService.createCache("frm.TSPolicies",
1386 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1388 clusterContainerService.createCache(WORKSTATUSCACHE,
1389 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1391 clusterContainerService.createCache(WORKORDERCACHE,
1392 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC));
1394 } catch (CacheConfigException cce) {
1395 log.error("CacheConfigException");
1396 } catch (CacheExistException cce) {
1397 log.error("CacheExistException");
1401 @SuppressWarnings({ "unchecked" })
1402 private void retrieveCaches() {
1403 ConcurrentMap<?, ?> map;
1405 if (this.clusterContainerService == null) {
1406 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1407 nonClusterObjectCreate();
1411 log.debug("Retrieving Caches for Container {}", container.getName());
1413 map = clusterContainerService.getCache("frm.originalSwView");
1415 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1417 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1420 map = clusterContainerService.getCache("frm.installedSwView");
1422 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1424 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1427 map = clusterContainerService.getCache("frm.inactiveFlows");
1429 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1431 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1434 map = clusterContainerService.getCache("frm.nodeFlows");
1436 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1438 log.error("Retrieval of cache failed for Container {}", container.getName());
1441 map = clusterContainerService.getCache("frm.groupFlows");
1443 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1445 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1448 map = clusterContainerService.getCache("frm.staticFlows");
1450 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1452 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1455 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1457 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1459 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1462 map = clusterContainerService.getCache("frm.portGroupConfigs");
1464 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1466 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1469 map = clusterContainerService.getCache("frm.portGroupData");
1471 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1473 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1476 map = clusterContainerService.getCache("frm.TSPolicies");
1478 TSPolicies = (ConcurrentMap<String, Object>) map;
1480 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1483 map = clusterContainerService.getCache(WORKORDERCACHE);
1485 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1487 log.error("Retrieval of " + WORKORDERCACHE + " cache failed for Container {}", container.getName());
1490 map = clusterContainerService.getCache(WORKSTATUSCACHE);
1492 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1494 log.error("Retrieval of " + WORKSTATUSCACHE + " cache failed for Container {}", container.getName());
1498 private boolean flowConfigExists(FlowConfig config) {
1499 // Flow name has to be unique on per node id basis
1500 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1501 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1509 public Status addStaticFlow(FlowConfig config) {
1510 // Configuration object validation
1511 Status status = config.validate(container);
1512 if (!status.isSuccess()) {
1513 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1514 String error = "Invalid Configuration (" + status.getDescription() + ")";
1515 config.setStatus(error);
1516 return new Status(StatusCode.BADREQUEST, error);
1518 return addStaticFlowInternal(config, false);
1522 * Private method to add a static flow configuration which does not run any
1523 * validation on the passed FlowConfig object. If restore is set to true,
1524 * configuration is stored in configuration database regardless the
1525 * installation on the network node was successful. This is useful at boot
1526 * when static flows are present in startup configuration and are read
1527 * before the switches connects.
1530 * The static flow configuration
1532 * if true, the configuration is stored regardless the
1533 * installation on the network node was successful
1534 * @return The status of this request
1536 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1537 boolean multipleFlowPush = false;
1540 config.setStatus(SUCCESS);
1543 if (flowConfigExists(config)) {
1544 error = "Entry with this name on specified switch already exists";
1545 log.warn("Entry with this name on specified switch already exists: {}", config);
1546 config.setStatus(error);
1547 return new Status(StatusCode.CONFLICT, error);
1550 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1551 for (String portGroupName : portGroupConfigs.keySet()) {
1552 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1553 multipleFlowPush = true;
1557 if (!multipleFlowPush) {
1558 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1559 error = "Invalid Configuration (Invalid PortGroup Name)";
1560 config.setStatus(error);
1561 return new Status(StatusCode.BADREQUEST, error);
1566 * If requested program the entry in hardware first before updating the
1569 if (!multipleFlowPush) {
1571 if (config.installInHw()) {
1572 FlowEntry entry = config.getFlowEntry();
1573 status = this.installFlowEntry(entry);
1574 if (!status.isSuccess()) {
1575 config.setStatus(status.getDescription());
1584 * When the control reaches this point, either of the following
1585 * conditions is true 1. This is a single entry configuration (non
1586 * PortGroup) and the hardware installation is successful 2. This is a
1587 * multiple entry configuration (PortGroup) and hardware installation is
1588 * NOT done directly on this event. 3. The User prefers to retain the
1589 * configuration in Controller and skip hardware installation.
1591 * Hence it is safe to update the StaticFlow DB at this point.
1593 * Note : For the case of PortGrouping, it is essential to have this DB
1594 * populated before the PortGroupListeners can query for the DB
1595 * triggered using portGroupChanged event...
1597 Integer ordinal = staticFlowsOrdinal.get(0);
1598 staticFlowsOrdinal.put(0, ++ordinal);
1599 staticFlows.put(ordinal, config);
1601 if (multipleFlowPush) {
1602 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1603 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1604 if (existingData != null) {
1605 portGroupChanged(pgconfig, existingData, true);
1608 return new Status(StatusCode.SUCCESS);
1611 private void addStaticFlowsToSwitch(Node node) {
1612 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1613 FlowConfig config = entry.getValue();
1614 if (config.isPortGroupEnabled()) {
1617 if (config.getNode().equals(node)) {
1618 if (config.installInHw() && !config.getStatus().equals(SUCCESS)) {
1619 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1620 config.setStatus(status.getDescription());
1624 // Update cluster cache
1625 refreshClusterStaticFlowsStatus(node);
1628 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1629 log.trace("Updating Static Flow configs on node down: {}", node);
1631 List<Integer> toRemove = new ArrayList<Integer>();
1632 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1634 FlowConfig config = entry.getValue();
1636 if (config.isPortGroupEnabled()) {
1640 if (config.installInHw() && config.getNode().equals(node)) {
1641 if (config.isInternalFlow()) {
1642 // Take note of this controller generated static flow
1643 toRemove.add(entry.getKey());
1645 config.setStatus(NODEDOWN);
1649 // Remove controller generated static flows for this node
1650 for (Integer index : toRemove) {
1651 staticFlows.remove(index);
1653 // Update cluster cache
1654 refreshClusterStaticFlowsStatus(node);
1658 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1659 log.trace("Updating Static Flow configs on container mode change: {}", update);
1661 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1662 FlowConfig config = entry.getValue();
1663 if (config.isPortGroupEnabled()) {
1666 if (config.installInHw() && !config.isInternalFlow()) {
1669 config.setStatus("Removed from node because in container mode");
1672 config.setStatus(SUCCESS);
1678 // Update cluster cache
1679 refreshClusterStaticFlowsStatus(null);
1683 public Status removeStaticFlow(FlowConfig config) {
1685 * No config.isInternal() check as NB does not take this path and GUI
1686 * cannot issue a delete on an internal generated flow. We need this
1687 * path to be accessible when switch mode is changed from proactive to
1688 * reactive, so that we can remove the internal generated LLDP and ARP
1692 // Look for the target configuration entry
1694 FlowConfig target = null;
1695 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1696 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1697 key = entry.getKey();
1698 target = entry.getValue();
1702 if (target == null) {
1703 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1706 // Program the network node
1707 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1709 // Update configuration database if programming was successful
1710 if (status.isSuccess()) {
1711 staticFlows.remove(key);
1718 public Status removeStaticFlow(String name, Node node) {
1719 // Look for the target configuration entry
1721 FlowConfig target = null;
1722 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1723 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1724 key = mapEntry.getKey();
1725 target = mapEntry.getValue();
1729 if (target == null) {
1730 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1733 // Validity check for api3 entry point
1734 if (target.isInternalFlow()) {
1735 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1736 String logMsg = msg + ": {}";
1737 log.warn(logMsg, name);
1738 return new Status(StatusCode.NOTACCEPTABLE, msg);
1741 if (target.isPortGroupEnabled()) {
1742 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1743 String logMsg = msg + ": {}";
1744 log.warn(logMsg, name);
1745 return new Status(StatusCode.NOTACCEPTABLE, msg);
1748 // Program the network node
1749 Status status = this.removeEntry(target.getFlowEntry(), false);
1751 // Update configuration database if programming was successful
1752 if (status.isSuccess()) {
1753 staticFlows.remove(key);
1760 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1761 // Validity check for api3 entry point
1762 if (newFlowConfig.isInternalFlow()) {
1763 String msg = "Invalid operation: Controller generated flow cannot be modified";
1764 String logMsg = msg + ": {}";
1765 log.warn(logMsg, newFlowConfig);
1766 return new Status(StatusCode.NOTACCEPTABLE, msg);
1770 Status status = newFlowConfig.validate(container);
1771 if (!status.isSuccess()) {
1772 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1773 newFlowConfig.setStatus(msg);
1774 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1775 return new Status(StatusCode.BADREQUEST, msg);
1778 FlowConfig oldFlowConfig = null;
1779 Integer index = null;
1780 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1781 FlowConfig entry = mapEntry.getValue();
1782 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1783 oldFlowConfig = entry;
1784 index = mapEntry.getKey();
1789 if (oldFlowConfig == null) {
1790 String msg = "Attempt to modify a non existing static flow";
1791 String logMsg = msg + ": {}";
1792 log.warn(logMsg, newFlowConfig);
1793 return new Status(StatusCode.NOTFOUND, msg);
1796 // Do not attempt to reinstall the flow, warn user
1797 if (newFlowConfig.equals(oldFlowConfig)) {
1798 String msg = "No modification detected";
1799 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1800 return new Status(StatusCode.SUCCESS, msg);
1803 // If flow is installed, program the network node
1804 status = new Status(StatusCode.SUCCESS, "Saved in config");
1805 if (oldFlowConfig.installInHw()) {
1806 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1809 // Update configuration database if programming was successful
1810 if (status.isSuccess()) {
1811 newFlowConfig.setStatus(status.getDescription());
1812 staticFlows.put(index, newFlowConfig);
1819 public Status toggleStaticFlowStatus(String name, Node node) {
1820 return toggleStaticFlowStatus(getStaticFlow(name, node));
1824 public Status toggleStaticFlowStatus(FlowConfig config) {
1825 if (config == null) {
1826 String msg = "Invalid request: null flow config";
1828 return new Status(StatusCode.BADREQUEST, msg);
1830 // Validity check for api3 entry point
1831 if (config.isInternalFlow()) {
1832 String msg = "Invalid operation: Controller generated flow cannot be modified";
1833 String logMsg = msg + ": {}";
1834 log.warn(logMsg, config);
1835 return new Status(StatusCode.NOTACCEPTABLE, msg);
1838 // Find the config entry
1840 FlowConfig target = null;
1841 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1842 FlowConfig conf = entry.getValue();
1843 if (conf.isByNameAndNodeIdEqual(config)) {
1844 key = entry.getKey();
1849 if (target != null) {
1850 Status status = target.validate(container);
1851 if (!status.isSuccess()) {
1852 log.warn(status.getDescription());
1855 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1856 .installFlowEntry(target.getFlowEntry());
1857 if (status.isSuccess()) {
1858 // Update Configuration database
1859 target.setStatus(SUCCESS);
1860 target.toggleInstallation();
1861 staticFlows.put(key, target);
1866 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1870 * Reinsert all static flows entries in the cache to force cache updates in
1871 * the cluster. This is useful when only some parameters were changed in the
1872 * entries, like the status.
1875 * The node for which the static flow configurations have to be
1876 * refreshed. If null, all nodes static flows will be refreshed.
1878 private void refreshClusterStaticFlowsStatus(Node node) {
1879 // Refresh cluster cache
1880 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1881 if (node == null || entry.getValue().getNode().equals(node)) {
1882 staticFlows.put(entry.getKey(), entry.getValue());
1888 * Uninstall all the non-internal Flow Entries present in the software view.
1889 * If requested, a copy of each original flow entry will be stored in the
1890 * inactive list so that it can be re-applied when needed (This is typically
1891 * the case when running in the default container and controller moved to
1892 * container mode) NOTE WELL: The routine as long as does a bulk change will
1893 * operate only on the entries for nodes locally attached so to avoid
1894 * redundant operations initiated by multiple nodes
1896 * @param preserveFlowEntries
1897 * if true, a copy of each original entry is stored in the
1900 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1901 log.info("Uninstalling all non-internal flows");
1903 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1905 // Store entries / create target list
1906 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1907 FlowEntryInstall flowEntries = mapEntry.getValue();
1908 // Skip internal generated static flows
1909 if (!flowEntries.isInternal()) {
1910 toRemove.add(flowEntries);
1911 // Store the original entries if requested
1912 if (preserveFlowEntries) {
1913 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1918 // Now remove the entries
1919 for (FlowEntryInstall flowEntryHw : toRemove) {
1920 Node n = flowEntryHw.getNode();
1921 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
1922 Status status = this.removeEntryInternal(flowEntryHw, false);
1923 if (!status.isSuccess()) {
1924 log.warn("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1927 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
1934 * Re-install all the Flow Entries present in the inactive list The inactive
1935 * list will be empty at the end of this call This function is called on the
1936 * default container instance of FRM only when the last container is deleted
1938 private void reinstallAllFlowEntries() {
1939 log.info("Reinstalling all inactive flows");
1941 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1942 this.addEntry(flowEntry, false);
1945 // Empty inactive list in any case
1946 inactiveFlows.clear();
1950 public List<FlowConfig> getStaticFlows() {
1951 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1954 // TODO: need to come out with a better algorithm for maintaining the order
1955 // of the configuration entries
1956 // with actual one, index associated to deleted entries cannot be reused and
1958 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1959 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1960 for (int i = 0; i <= maxKey; i++) {
1961 FlowConfig entry = flowMap.get(i);
1962 if (entry != null) {
1963 orderedList.add(entry);
1970 public FlowConfig getStaticFlow(String name, Node node) {
1971 ConcurrentMap.Entry<Integer, FlowConfig> entry = getStaticFlowEntry(name, node);
1973 return entry.getValue();
1979 public List<FlowConfig> getStaticFlows(Node node) {
1980 List<FlowConfig> list = new ArrayList<FlowConfig>();
1981 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1982 if (entry.getValue().onNode(node)) {
1983 list.add(entry.getValue());
1990 public List<String> getStaticFlowNamesForNode(Node node) {
1991 List<String> list = new ArrayList<String>();
1992 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1993 if (entry.getValue().onNode(node)) {
1994 list.add(entry.getValue().getName());
2001 public List<Node> getListNodeWithConfiguredFlows() {
2002 Set<Node> set = new HashSet<Node>();
2003 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
2004 set.add(entry.getValue().getNode());
2006 return new ArrayList<Node>(set);
2009 @SuppressWarnings("unchecked")
2010 private void loadFlowConfiguration() {
2011 ObjectReader objReader = new ObjectReader();
2012 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2015 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2018 if (pgConfig != null) {
2019 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2020 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2024 if (confList == null) {
2029 for (Integer key : confList.keySet()) {
2030 if (key.intValue() > maxKey) {
2031 maxKey = key.intValue();
2035 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2036 addStaticFlowInternal(conf, true);
2041 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2042 return ois.readObject();
2046 public Status saveConfig() {
2047 return saveConfigInternal();
2050 private Status saveConfigInternal() {
2051 ObjectWriter objWriter = new ObjectWriter();
2052 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2053 for (Integer ordinal : staticFlows.keySet()) {
2054 FlowConfig config = staticFlows.get(ordinal);
2055 // Do not save dynamic and controller generated static flows
2056 if (config.isDynamic() || config.isInternalFlow()) {
2059 nonDynamicFlows.put(ordinal, config);
2061 objWriter.write(nonDynamicFlows, frmFileName);
2062 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2063 return new Status(StatusCode.SUCCESS, null);
2067 public void subnetNotify(Subnet sub, boolean add) {
2070 private void installImplicitARPReplyPunt(Node node) {
2076 List<String> puntAction = new ArrayList<String>();
2077 puntAction.add(ActionType.CONTROLLER.toString());
2079 FlowConfig allowARP = new FlowConfig();
2080 allowARP.setInstallInHw(true);
2081 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
2082 allowARP.setPriority("500");
2083 allowARP.setNode(node);
2084 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2085 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
2086 allowARP.setActions(puntAction);
2087 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
2093 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2096 * This method can be called from within the OSGi framework context,
2097 * given the programming operation can take sometime, it not good
2098 * pratice to have in it's context operations that can take time,
2099 * hence moving off to a different thread for async processing.
2101 private ExecutorService executor;
2103 public void modeChangeNotify(final Node node, final boolean proactive) {
2104 Callable<Status> modeChangeCallable = new Callable<Status>() {
2106 public Status call() throws Exception {
2107 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2109 List<String> puntAction = new ArrayList<String>();
2110 puntAction.add(ActionType.CONTROLLER.toString());
2112 FlowConfig allowARP = new FlowConfig();
2113 allowARP.setInstallInHw(true);
2114 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2115 allowARP.setPriority("1");
2116 allowARP.setNode(node);
2117 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2119 allowARP.setActions(puntAction);
2120 defaultConfigs.add(allowARP);
2122 FlowConfig allowLLDP = new FlowConfig();
2123 allowLLDP.setInstallInHw(true);
2124 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2125 allowLLDP.setPriority("1");
2126 allowLLDP.setNode(node);
2127 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2129 allowLLDP.setActions(puntAction);
2130 defaultConfigs.add(allowLLDP);
2132 List<String> dropAction = new ArrayList<String>();
2133 dropAction.add(ActionType.DROP.toString());
2135 FlowConfig dropAllConfig = new FlowConfig();
2136 dropAllConfig.setInstallInHw(true);
2137 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2138 + FlowConfig.INTERNALSTATICFLOWEND);
2139 dropAllConfig.setPriority("0");
2140 dropAllConfig.setNode(node);
2141 dropAllConfig.setActions(dropAction);
2142 defaultConfigs.add(dropAllConfig);
2144 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2145 for (FlowConfig fc : defaultConfigs) {
2146 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2147 if (status.isSuccess()) {
2148 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2150 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2154 return new Status(StatusCode.SUCCESS);
2159 * Execute the work outside the caller context, this could be an
2160 * expensive operation and we don't want to block the caller for it.
2162 this.executor.submit(modeChangeCallable);
2166 * Remove from the databases all the flows installed on the node
2170 private void cleanDatabaseForNode(Node node) {
2171 log.info("Cleaning Flow database for Node {}", node);
2172 if (nodeFlows.containsKey(node)) {
2173 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2175 for (FlowEntryInstall entry : toRemove) {
2176 updateLocalDatabase(entry, false);
2181 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2186 Match match = flow.getMatch();
2187 if (match.isPresent(MatchType.IN_PORT)) {
2188 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2189 if (matchPort.equals(nc)) {
2193 List<Action> actionsList = flow.getActions();
2194 if (actionsList != null) {
2195 for (Action action : actionsList) {
2196 if (action instanceof Output) {
2197 NodeConnector actionPort = ((Output) action).getPort();
2198 if (actionPort.equals(nc)) {
2208 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2209 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2213 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2214 boolean updateStaticFlowCluster = false;
2220 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2221 if (config != null) {
2222 switch (config.getValue()) {
2223 case Config.ADMIN_DOWN:
2224 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2225 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2227 case Config.ADMIN_UP:
2228 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2229 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2231 case Config.ADMIN_UNDEF:
2238 // This is the case where a switch port is removed from the SDN agent space
2239 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2240 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2246 if (updateStaticFlowCluster) {
2247 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2252 * It goes through the static flows configuration, it identifies the ones
2253 * which have the specified node connector as input or output port and
2254 * install them on the network node if they are marked to be installed in
2255 * hardware and their status shows they were not installed yet
2257 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2258 boolean updated = false;
2259 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2260 for (FlowConfig flowConfig : flowConfigForNode) {
2261 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2262 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(SUCCESS)) {
2263 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2264 if (!status.isSuccess()) {
2265 flowConfig.setStatus(status.getDescription());
2267 flowConfig.setStatus(SUCCESS);
2277 * Remove from the network node all the flows which have the specified node
2278 * connector as input or output port. If any of the flow entry is a static
2279 * flow, it updates the correspondent configuration.
2281 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2282 boolean updated = false;
2283 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2284 if (nodeFlowEntries == null) {
2287 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2288 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2289 Status status = this.removeEntryInternal(fei, true);
2290 if (!status.isSuccess()) {
2294 * If the flow entry is a static flow, then update its
2297 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2298 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2299 if (flowConfig != null) {
2300 flowConfig.setStatus(PORTREMOVED);
2309 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2310 FlowConfig derivedFlow = new FlowConfig(original);
2311 derivedFlow.setDynamic(true);
2312 derivedFlow.setPortGroup(null);
2313 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2314 derivedFlow.setIngressPort(port + "");
2318 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2319 for (FlowConfig staticFlow : staticFlows.values()) {
2320 if (staticFlow.getPortGroup() == null) {
2323 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2324 for (Short port : data.getPorts()) {
2325 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2326 addStaticFlowInternal(derivedFlow, false);
2332 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2333 for (FlowConfig staticFlow : staticFlows.values()) {
2334 if (staticFlow.getPortGroup() == null) {
2337 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2338 for (Short port : data.getPorts()) {
2339 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2340 removeStaticFlow(derivedFlow);
2347 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2348 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2349 Map<Node, PortGroup> existingData = portGroupData.get(config);
2350 if (existingData != null) {
2351 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2352 PortGroup existingPortGroup = existingData.get(entry.getKey());
2353 if (existingPortGroup == null) {
2355 existingData.put(entry.getKey(), entry.getValue());
2356 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2360 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2361 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2363 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2364 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2370 portGroupData.put(config, data);
2371 for (Node swid : data.keySet()) {
2372 addPortGroupFlows(config, swid, data.get(swid));
2379 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2380 PortGroupConfig config = portGroupConfigs.get(name);
2381 if (config != null) {
2385 if ((portGroupProvider == null) && !restore) {
2388 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2392 config = new PortGroupConfig(name, regex);
2393 portGroupConfigs.put(name, config);
2394 if (portGroupProvider != null) {
2395 portGroupProvider.createPortGroupConfig(config);
2401 public boolean delPortGroupConfig(String name) {
2402 PortGroupConfig config = portGroupConfigs.get(name);
2403 if (config == null) {
2407 if (portGroupProvider != null) {
2408 portGroupProvider.deletePortGroupConfig(config);
2410 portGroupConfigs.remove(name);
2414 private void usePortGroupConfig(String name) {
2415 PortGroupConfig config = portGroupConfigs.get(name);
2416 if (config == null) {
2419 if (portGroupProvider != null) {
2420 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2421 portGroupData.put(config, data);
2426 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2427 return portGroupConfigs;
2430 public boolean isPortGroupSupported() {
2431 if (portGroupProvider == null) {
2437 public void setIContainer(IContainer s) {
2441 public void unsetIContainer(IContainer s) {
2442 if (this.container == s) {
2443 this.container = null;
2448 public PortGroupProvider getPortGroupProvider() {
2449 return portGroupProvider;
2452 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2453 this.portGroupProvider = null;
2456 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2457 this.portGroupProvider = portGroupProvider;
2458 portGroupProvider.registerPortGroupChange(this);
2459 for (PortGroupConfig config : portGroupConfigs.values()) {
2460 portGroupProvider.createPortGroupConfig(config);
2464 public void setFrmAware(IForwardingRulesManagerAware obj) {
2465 this.frmAware.add(obj);
2468 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2469 this.frmAware.remove(obj);
2472 void setClusterContainerService(IClusterContainerServices s) {
2473 log.debug("Cluster Service set");
2474 this.clusterContainerService = s;
2477 void unsetClusterContainerService(IClusterContainerServices s) {
2478 if (this.clusterContainerService == s) {
2479 log.debug("Cluster Service removed!");
2480 this.clusterContainerService = null;
2484 private String getContainerName() {
2485 if (container == null) {
2486 return GlobalConstants.DEFAULT.toString();
2488 return container.getName();
2492 * Function called by the dependency manager when all the required
2493 * dependencies are satisfied
2497 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2498 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2500 inContainerMode = false;
2502 if (portGroupProvider != null) {
2503 portGroupProvider.registerPortGroupChange(this);
2508 registerWithOSGIConsole();
2511 * If we are not the first cluster node to come up, do not initialize
2512 * the static flow entries ordinal
2514 if (staticFlowsOrdinal.size() == 0) {
2515 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2518 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2520 // Initialize the event handler thread
2521 frmEventHandler = new Thread(new Runnable() {
2526 final FRMEvent event = pendingEvents.take();
2527 if (event == null) {
2528 log.warn("Dequeued null event");
2531 log.trace("Dequeued {} event", event.getClass().getSimpleName());
2532 if (event instanceof NodeUpdateEvent) {
2533 NodeUpdateEvent update = (NodeUpdateEvent) event;
2534 Node node = update.getNode();
2535 switch (update.getUpdateType()) {
2537 addStaticFlowsToSwitch(node);
2540 cleanDatabaseForNode(node);
2541 updateStaticFlowConfigsOnNodeDown(node);
2545 } else if (event instanceof ErrorReportedEvent) {
2546 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2547 processErrorEvent(errEvent);
2548 } else if (event instanceof WorkOrderEvent) {
2550 * Take care of handling the remote Work request
2552 Runnable r = new Runnable() {
2555 WorkOrderEvent work = (WorkOrderEvent) event;
2556 FlowEntryDistributionOrder fe = work.getFe();
2558 logsync.trace("Executing the workOrder {}", fe);
2559 Status gotStatus = null;
2560 FlowEntryInstall feiCurrent = fe.getEntry();
2561 FlowEntryInstall feiNew = workOrder.get(fe);
2562 switch (fe.getUpType()) {
2564 gotStatus = addEntriesInternal(feiCurrent, false);
2567 gotStatus = modifyEntryInternal(feiCurrent, feiNew, false);
2570 gotStatus = removeEntryInternal(feiCurrent, false);
2574 workOrder.remove(fe);
2576 "The workOrder has been executed and now the status is being returned {}", fe);
2578 workStatus.put(fe, gotStatus);
2580 log.warn("Not expected null WorkOrder", work);
2584 if(executor != null) {
2585 executor.execute(r);
2587 } else if (event instanceof WorkStatusCleanup) {
2589 * Take care of handling the remote Work request
2591 WorkStatusCleanup work = (WorkStatusCleanup) event;
2592 FlowEntryDistributionOrder fe = work.getFe();
2594 logsync.trace("The workStatus {} is being removed", fe);
2595 workStatus.remove(fe);
2597 log.warn("Not expected null WorkStatus", work);
2599 } else if (event instanceof ContainerFlowChangeEvent) {
2601 * Whether it is an addition or removal, we have to
2602 * recompute the merged flows entries taking into
2603 * account all the current container flows because
2604 * flow merging is not an injective function
2606 updateFlowsContainerFlow();
2608 log.warn("Dequeued unknown event {}", event.getClass()
2611 } catch (InterruptedException e) {
2612 // clear pending events
2613 pendingEvents.clear();
2617 }, "FRM EventHandler Collector");
2621 * Function called by the dependency manager when at least one dependency
2622 * become unsatisfied or when the component is shutting down because for
2623 * example bundle is being stopped.
2627 // Interrupt the thread
2628 frmEventHandler.interrupt();
2629 // Clear the pendingEvents queue
2630 pendingEvents.clear();
2632 workMonitor.clear();
2636 * Function called by dependency manager after "init ()" is called and after
2637 * the services provided by the class are registered in the service registry
2642 * If running in default container, need to know if controller is in
2645 if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) {
2646 inContainerMode = containerManager.inContainerMode();
2649 // Initialize graceful stop flag
2652 // Allocate the executor service
2653 this.executor = Executors.newFixedThreadPool(maxPoolSize);
2655 // Start event handler thread
2656 frmEventHandler.start();
2659 * Read startup and build database if we have not already gotten the
2660 * configurations synced from another node
2662 if (staticFlows.isEmpty()) {
2663 loadFlowConfiguration();
2668 * Function called by the dependency manager before the services exported by
2669 * the component are unregistered, this will be followed by a "destroy ()"
2674 uninstallAllFlowEntries(false);
2675 // Shutdown executor
2676 this.executor.shutdownNow();
2677 // Now walk all the workMonitor and wake up the one sleeping because
2678 // destruction is happening
2679 for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2680 FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2685 public void setFlowProgrammerService(IFlowProgrammerService service) {
2686 this.programmer = service;
2689 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2690 if (this.programmer == service) {
2691 this.programmer = null;
2695 public void setSwitchManager(ISwitchManager switchManager) {
2696 this.switchManager = switchManager;
2699 public void unsetSwitchManager(ISwitchManager switchManager) {
2700 if (this.switchManager == switchManager) {
2701 this.switchManager = null;
2706 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2707 if (!container.getName().equals(containerName)) {
2713 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2714 if (!container.getName().equals(containerName)) {
2717 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2718 container.getName(), t, current);
2719 ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2720 pendingEvents.offer(ev);
2724 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2725 if (!container.getName().equals(containerName)) {
2729 boolean updateStaticFlowCluster = false;
2733 log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2734 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2737 log.trace("Port {} was added to container: reinstall interested flows", nc);
2738 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2746 if (updateStaticFlowCluster) {
2747 refreshClusterStaticFlowsStatus(nc.getNode());
2752 public void containerModeUpdated(UpdateType update) {
2753 // Only default container instance reacts on this event
2754 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2760 * Controller is moving to container mode. We are in the default
2761 * container context, we need to remove all our non-internal flows
2762 * to prevent any container isolation breakage. We also need to
2763 * preserve our flow so that they can be re-installed if we move
2764 * back to non container mode (no containers).
2766 this.inContainerMode = true;
2767 this.uninstallAllFlowEntries(true);
2770 this.inContainerMode = false;
2771 this.reinstallAllFlowEntries();
2776 // Update our configuration DB
2777 updateStaticFlowConfigsOnContainerModeChange(update);
2780 protected abstract class FRMEvent {
2784 private class NodeUpdateEvent extends FRMEvent {
2785 private final Node node;
2786 private final UpdateType update;
2788 public NodeUpdateEvent(UpdateType update, Node node) {
2789 this.update = update;
2793 public UpdateType getUpdateType() {
2797 public Node getNode() {
2802 private class ErrorReportedEvent extends FRMEvent {
2803 private final long rid;
2804 private final Node node;
2805 private final Object error;
2807 public ErrorReportedEvent(long rid, Node node, Object error) {
2813 public long getRequestId() {
2817 public Object getError() {
2821 public Node getNode() {
2826 private class WorkOrderEvent extends FRMEvent {
2827 private FlowEntryDistributionOrder fe;
2828 private FlowEntryInstall newEntry;
2834 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2836 this.newEntry = newEntry;
2842 public FlowEntryDistributionOrder getFe() {
2847 * @return the newEntry
2849 public FlowEntryInstall getNewEntry() {
2853 private class ContainerFlowChangeEvent extends FRMEvent {
2854 private final ContainerFlow previous;
2855 private final ContainerFlow current;
2856 private final UpdateType type;
2858 public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2859 this.previous = previous;
2860 this.current = current;
2864 public ContainerFlow getPrevious() {
2865 return this.previous;
2868 public ContainerFlow getCurrent() {
2869 return this.current;
2872 public UpdateType getType() {
2878 private class WorkStatusCleanup extends FRMEvent {
2879 private FlowEntryDistributionOrder fe;
2884 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2891 public FlowEntryDistributionOrder getFe() {
2900 public String getHelp() {
2901 StringBuffer help = new StringBuffer();
2902 help.append("---FRM Matrix Application---\n");
2903 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2904 help.append("\t addMatrixConfig <name> <regex>\n");
2905 help.append("\t delMatrixConfig <name>\n");
2906 help.append("\t useMatrixConfig <name>\n");
2907 return help.toString();
2910 public void _printMatrixData(CommandInterpreter ci) {
2911 ci.println("Configs : ");
2912 ci.println("---------");
2913 ci.println(portGroupConfigs);
2915 ci.println("Data : ");
2916 ci.println("------");
2917 ci.println(portGroupData);
2920 public void _addMatrixConfig(CommandInterpreter ci) {
2921 String name = ci.nextArgument();
2922 String regex = ci.nextArgument();
2923 addPortGroupConfig(name, regex, false);
2926 public void _delMatrixConfig(CommandInterpreter ci) {
2927 String name = ci.nextArgument();
2928 delPortGroupConfig(name);
2931 public void _useMatrixConfig(CommandInterpreter ci) {
2932 String name = ci.nextArgument();
2933 usePortGroupConfig(name);
2936 public void _arpPunt(CommandInterpreter ci) {
2937 String switchId = ci.nextArgument();
2938 long swid = HexEncode.stringToLong(switchId);
2939 Node node = NodeCreator.createOFNode(swid);
2940 installImplicitARPReplyPunt(node);
2943 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2945 String nodeId = ci.nextArgument();
2946 if (nodeId == null) {
2947 ci.print("Node id not specified");
2951 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2952 } catch (NumberFormatException e) {
2953 ci.print("Node id not a number");
2956 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2959 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2961 String nodeId = ci.nextArgument();
2962 if (nodeId == null) {
2963 ci.print("Node id not specified");
2967 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2968 } catch (NumberFormatException e) {
2969 ci.print("Node id not a number");
2972 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2975 private Flow getSampleFlow(Node node) throws UnknownHostException {
2976 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2977 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2978 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2979 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2980 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2981 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2982 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2983 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2984 short ethertype = EtherTypes.IPv4.shortValue();
2985 short vlan = (short) 27;
2988 byte proto = IPProtocols.TCP.byteValue();
2989 short src = (short) 55000;
2993 * Create a SAL Flow aFlow
2995 Match match = new Match();
2996 match.setField(MatchType.IN_PORT, port);
2997 match.setField(MatchType.DL_SRC, srcMac);
2998 match.setField(MatchType.DL_DST, dstMac);
2999 match.setField(MatchType.DL_TYPE, ethertype);
3000 match.setField(MatchType.DL_VLAN, vlan);
3001 match.setField(MatchType.DL_VLAN_PR, vlanPr);
3002 match.setField(MatchType.NW_SRC, srcIP, ipMask);
3003 match.setField(MatchType.NW_DST, dstIP, ipMask2);
3004 match.setField(MatchType.NW_TOS, tos);
3005 match.setField(MatchType.NW_PROTO, proto);
3006 match.setField(MatchType.TP_SRC, src);
3007 match.setField(MatchType.TP_DST, dst);
3009 List<Action> actions = new ArrayList<Action>();
3010 actions.add(new Output(oport));
3011 actions.add(new PopVlan());
3012 actions.add(new Flood());
3013 actions.add(new Controller());
3014 return new Flow(match, actions);
3018 public Status saveConfiguration() {
3019 return saveConfig();
3022 public void _frmNodeFlows(CommandInterpreter ci) {
3023 String nodeId = ci.nextArgument();
3024 Node node = Node.fromString(nodeId);
3026 ci.println("frmNodeFlows <node> [verbose]");
3029 boolean verbose = false;
3030 String verboseCheck = ci.nextArgument();
3031 if (verboseCheck != null) {
3032 verbose = verboseCheck.equals("true");
3035 if (!nodeFlows.containsKey(node)) {
3038 // Dump per node database
3039 for (FlowEntryInstall entry : nodeFlows.get(node)) {
3041 ci.println(node + " " + installedSwView.get(entry).getFlowName());
3043 ci.println(node + " " + installedSwView.get(entry).toString());
3048 public void _frmGroupFlows(CommandInterpreter ci) {
3049 String group = ci.nextArgument();
3050 if (group == null) {
3051 ci.println("frmGroupFlows <group> [verbose]");
3054 boolean verbose = false;
3055 String verboseCheck = ci.nextArgument();
3056 if (verboseCheck != null) {
3057 verbose = verboseCheck.equalsIgnoreCase("true");
3060 if (!groupFlows.containsKey(group)) {
3063 // Dump per node database
3064 ci.println("Group " + group + ":\n");
3065 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
3067 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
3069 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
3074 public void _frmProcessErrorEvent(CommandInterpreter ci) throws UnknownHostException {
3077 String nodeId = ci.nextArgument();
3078 if (nodeId == null) {
3079 ci.print("Node id not specified");
3082 String requestId = ci.nextArgument();
3083 if (requestId == null) {
3084 ci.print("Request id not specified");
3088 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
3089 } catch (NumberFormatException e) {
3090 ci.print("Node id not a number");
3094 reqId = Long.parseLong(requestId);
3095 } catch (NumberFormatException e) {
3096 ci.print("Request id not a number");
3099 // null for error object is good enough for now
3100 ErrorReportedEvent event = new ErrorReportedEvent(reqId, node, null);
3101 this.processErrorEvent(event);
3105 public void flowRemoved(Node node, Flow flow) {
3106 log.trace("Received flow removed notification on {} for {}", node, flow);
3108 // For flow entry identification, only node, match and priority matter
3109 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
3110 FlowEntryInstall installedEntry = this.installedSwView.get(test);
3111 if (installedEntry == null) {
3112 log.trace("Entry is not known to us");
3116 // Update Static flow status
3118 FlowConfig target = null;
3119 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3120 FlowConfig conf = entry.getValue();
3121 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3122 key = entry.getKey();
3127 if (target != null) {
3128 // Update Configuration database
3129 target.toggleInstallation();
3130 target.setStatus(SUCCESS);
3131 staticFlows.put(key, target);
3134 // Update software views
3135 this.updateLocalDatabase(installedEntry, false);
3139 public void flowErrorReported(Node node, long rid, Object err) {
3140 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3141 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3144 private void processErrorEvent(ErrorReportedEvent event) {
3145 Node node = event.getNode();
3146 long rid = event.getRequestId();
3147 Object error = event.getError();
3148 String errorString = (error == null) ? "Not provided" : error.toString();
3150 * If this was for a flow install, remove the corresponding entry from
3151 * the software view. If it was a Looking for the rid going through the
3152 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3153 * mapping will have to be added in future
3155 FlowEntryInstall target = null;
3156 List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3157 // flowEntryInstallList could be null.
3159 if(flowEntryInstallList != null) {
3160 for (FlowEntryInstall index : flowEntryInstallList) {
3161 FlowEntryInstall entry = installedSwView.get(index);
3163 if (entry.getRequestId() == rid) {
3170 if (target != null) {
3171 // This was a flow install, update database
3172 this.updateLocalDatabase(target, false);
3173 // also update the config
3174 if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) {
3175 ConcurrentMap.Entry<Integer, FlowConfig> staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode());
3176 // staticFlowEntry should never be null.
3177 // the null check is just an extra defensive check.
3178 if(staticFlowEntry != null) {
3179 staticFlows.remove(staticFlowEntry.getKey());
3185 if (frmAware != null) {
3186 synchronized (frmAware) {
3187 for (IForwardingRulesManagerAware frma : frmAware) {
3189 frma.requestFailed(rid, errorString);
3190 } catch (Exception e) {
3191 log.warn("Failed to notify {}", frma);
3199 public Status solicitStatusResponse(Node node, boolean blocking) {
3200 Status rv = new Status(StatusCode.INTERNALERROR);
3202 if (this.programmer != null) {
3204 rv = programmer.syncSendBarrierMessage(node);
3206 rv = programmer.asyncSendBarrierMessage(node);
3213 public void unsetIConnectionManager(IConnectionManager s) {
3214 if (s == this.connectionManager) {
3215 this.connectionManager = null;
3219 public void setIConnectionManager(IConnectionManager s) {
3220 this.connectionManager = s;
3223 public void unsetIContainerManager(IContainerManager s) {
3224 if (s == this.containerManager) {
3225 this.containerManager = null;
3229 public void setIContainerManager(IContainerManager s) {
3230 this.containerManager = s;
3234 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3241 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3244 * Local updates are of no interest
3248 if (cacheName.equals(WORKORDERCACHE)) {
3249 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3251 * This is the case of one workOrder becoming available, so we need
3252 * to dispatch the work to the appropriate handler
3254 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3255 FlowEntryInstall fei = fe.getEntry();
3259 Node n = fei.getNode();
3260 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3261 logsync.trace("workOrder for fe {} processed locally", fe);
3262 // I'm the controller in charge for the request, queue it for
3264 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3266 } else if (cacheName.equals(WORKSTATUSCACHE)) {
3267 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3269 * This is the case of one workOrder being completed and a status
3272 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3274 * Check if the order was initiated by this controller in that case
3275 * we need to actually look at the status returned
3277 if (fe.getRequestorController()
3278 .equals(clusterContainerService.getMyAddress())) {
3279 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3281 logsync.trace("workStatus response is for us {}", fe);
3282 // Signal we got the status
3283 fet.gotStatus(fe, workStatus.get(fe));
3284 pendingEvents.offer(new WorkStatusCleanup(fe));
3291 public void entryDeleted(Object key, String cacheName, boolean originLocal) {