2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.forwardingrulesmanager.internal;
11 import java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.net.InetAddress;
15 import java.net.UnknownHostException;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.EnumSet;
19 import java.util.HashSet;
20 import java.util.List;
22 import java.util.Map.Entry;
24 import java.util.concurrent.BlockingQueue;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.Future;
32 import java.util.concurrent.LinkedBlockingQueue;
34 import org.eclipse.osgi.framework.console.CommandInterpreter;
35 import org.eclipse.osgi.framework.console.CommandProvider;
36 import org.opendaylight.controller.clustering.services.CacheConfigException;
37 import org.opendaylight.controller.clustering.services.CacheExistException;
38 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
39 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
40 import org.opendaylight.controller.clustering.services.IClusterServices;
41 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
42 import org.opendaylight.controller.sal.connection.ConnectionLocality;
43 import org.opendaylight.controller.connectionmanager.IConnectionManager;
44 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
45 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
46 import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall;
47 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
48 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware;
49 import org.opendaylight.controller.forwardingrulesmanager.PortGroup;
50 import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener;
51 import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig;
52 import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider;
53 import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder;
54 import org.opendaylight.controller.sal.action.Action;
55 import org.opendaylight.controller.sal.action.ActionType;
56 import org.opendaylight.controller.sal.action.Controller;
57 import org.opendaylight.controller.sal.action.Flood;
58 import org.opendaylight.controller.sal.action.Output;
59 import org.opendaylight.controller.sal.action.PopVlan;
60 import org.opendaylight.controller.sal.core.Config;
61 import org.opendaylight.controller.sal.core.ContainerFlow;
62 import org.opendaylight.controller.sal.core.IContainer;
63 import org.opendaylight.controller.sal.core.IContainerListener;
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,
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 boolean inContainerMode; // being used by global instance only
122 private boolean stopping;
125 * Flow database. It's the software view of what was requested to install
126 * and what is installed on the switch. It is indexed by the entry itself.
127 * The entry's hashcode resumes the network node index, the flow's priority
128 * and the flow's match. The value element is a class which contains the
129 * flow entry pushed by the applications modules and the respective
130 * container flow merged version. In absence of container flows, the two
131 * flow entries are the same.
133 private ConcurrentMap<FlowEntry, FlowEntry> originalSwView;
134 private ConcurrentMap<FlowEntryInstall, FlowEntryInstall> installedSwView;
136 * Per node and per group indexing
138 private ConcurrentMap<Node, List<FlowEntryInstall>> nodeFlows;
139 private ConcurrentMap<String, List<FlowEntryInstall>> groupFlows;
142 * Inactive flow list. This is for the global instance of FRM It will
143 * contain all the flow entries which were installed on the global container
144 * when the first container is created.
146 private ConcurrentMap<FlowEntry, FlowEntry> inactiveFlows;
148 private IContainer container;
149 private Set<IForwardingRulesManagerAware> frmAware =
150 Collections.synchronizedSet(new HashSet<IForwardingRulesManagerAware>());
151 private PortGroupProvider portGroupProvider;
152 private IFlowProgrammerService programmer;
153 private IClusterContainerServices clusterContainerService = null;
154 private ISwitchManager switchManager;
155 private Thread frmEventHandler;
156 protected BlockingQueue<FRMEvent> pendingEvents;
158 // Distributes FRM programming in the cluster
159 private IConnectionManager connectionManager;
162 * Name clustered caches used to support FRM entry distribution these are by
163 * necessity non-transactional as long as need to be able to synchronize
164 * states also while a transaction is in progress
166 static final String WORKORDERCACHE = "frm.workOrder";
167 static final String WORKSTATUSCACHE = "frm.workStatus";
170 * Data structure responsible for distributing the FlowEntryInstall requests
171 * in the cluster. The key value is entry that is being either Installed or
172 * Updated or Delete. The value field is the same of the key value in case
173 * of Installation or Deletion, it's the new entry in case of Modification,
174 * this because the clustering caches don't allow null values.
176 * The logic behind this data structure is that the controller that initiate
177 * the request will place the order here, someone will pick it and then will
178 * remove from this data structure because is being served.
180 * TODO: We need to have a way to cleanup this data structure if entries are
181 * not picked by anyone, which is always a case can happen especially on
182 * Node disconnect cases.
184 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall> workOrder;
187 * Data structure responsible for retrieving the results of the workOrder
188 * submitted to the cluster.
190 * The logic behind this data structure is that the controller that has
191 * executed the order will then place the result in workStatus signaling
192 * that there was a success or a failure.
194 * TODO: The workStatus entries need to have a lifetime associated in case
195 * of requestor controller leaving the cluster.
197 private ConcurrentMap<FlowEntryDistributionOrder, Status> workStatus;
200 * Local Map used to hold the Future which a caller can use to monitor for
203 private ConcurrentMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask> workMonitor =
204 new ConcurrentHashMap<FlowEntryDistributionOrder, FlowEntryDistributionOrderFutureTask>();
208 * Entry being installed/updated/removed
210 * New entry will be placed after the update operation. Valid
211 * only for UpdateType.CHANGED, null for all the other cases
214 * @return a Future object for monitoring the progress of the result, or
215 * null in case the processing should take place locally
217 private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u,
219 // A null entry it's an unexpected condition, anyway it's safe to keep
220 // the handling local
225 Node n = e.getNode();
226 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) {
227 // Create the work order and distribute it
228 FlowEntryDistributionOrder fe =
229 new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress());
230 // First create the monitor job
231 FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe);
232 logsync.trace("Node {} not local so sending fe {}", n, fe);
233 workMonitor.put(fe, ret);
234 if (t.equals(UpdateType.CHANGED)) {
235 // Then distribute the work
236 workOrder.put(fe, u);
238 // Then distribute the work
239 workOrder.put(fe, e);
241 logsync.trace("WorkOrder requested");
242 // Now create an Handle to monitor the execution of the operation
246 logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t);
251 * Adds a flow entry onto the network node It runs various validity checks
252 * and derive the final container flows merged entries that will be
253 * attempted to be installed
256 * the original flow entry application requested to add
258 * the flag indicating if this is a asynchronous request
259 * @return the status of this request. In case of asynchronous call, it will
260 * contain the unique id assigned to this request
262 private Status addEntry(FlowEntry flowEntry, boolean async) {
265 if (flowEntry == null || flowEntry.getNode() == null) {
266 String msg = "Invalid FlowEntry";
267 String logMsg = msg + ": {}";
268 log.warn(logMsg, flowEntry);
269 return new Status(StatusCode.NOTACCEPTABLE, msg);
273 * Derive the container flow merged entries to install In presence of N
274 * container flows, we may end up with N different entries to install...
276 List<FlowEntryInstall> toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
278 // Container Flow conflict Check
279 if (toInstallList.isEmpty()) {
280 String msg = "Flow Entry conflicts with all Container Flows";
281 String logMsg = msg + ": {}";
282 log.warn(logMsg, flowEntry);
283 return new Status(StatusCode.CONFLICT, msg);
286 // Derive the list of entries good to be installed
287 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
288 for (FlowEntryInstall entry : toInstallList) {
289 // Conflict Check: Verify new entry would not overwrite existing
291 if (this.installedSwView.containsKey(entry)) {
292 log.warn("Operation Rejected: A flow with same match and priority exists on the target node");
293 log.trace("Aborting to install {}", entry);
296 toInstallSafe.add(entry);
299 // Declare failure if all the container flow merged entries clash with
301 if (toInstallSafe.size() == 0) {
302 String msg = "A flow with same match and priority exists on the target node";
303 String logMsg = msg + ": {}";
304 log.warn(logMsg, flowEntry);
305 return new Status(StatusCode.CONFLICT, msg);
308 // Try to install an entry at the time
309 Status error = new Status(null, null);
310 Status succeded = null;
311 boolean oneSucceded = false;
312 for (FlowEntryInstall installEntry : toInstallSafe) {
314 // Install and update database
315 Status ret = addEntriesInternal(installEntry, async);
317 if (ret.isSuccess()) {
320 * The first successful status response will be returned For the
321 * asynchronous call, we can discard the container flow
322 * complication for now and assume we will always deal with one
323 * flow only per request
328 log.warn("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription());
332 return (oneSucceded) ? succeded : error;
336 * Given a flow entry and the list of container flows, it returns the list
337 * of container flow merged flow entries good to be installed on this
338 * container. If the list of container flows is null or empty, the install
339 * entry list will contain only one entry, the original flow entry. If the
340 * flow entry is congruent with all the N container flows, then the output
341 * install entry list will contain N entries. If the output list is empty,
342 * it means the passed flow entry conflicts with all the container flows.
345 * The list of container flows
346 * @return the list of container flow merged entries good to be installed on
349 private List<FlowEntryInstall> deriveInstallEntries(FlowEntry request, List<ContainerFlow> cFlowList) {
350 List<FlowEntryInstall> toInstallList = new ArrayList<FlowEntryInstall>(1);
352 if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) {
353 // No container flows => entry good to be installed unchanged
354 toInstallList.add(new FlowEntryInstall(request.clone(), null));
356 // Create the list of entries to be installed. If the flow entry is
357 // not congruent with any container flow, no install entries will be
359 for (ContainerFlow cFlow : container.getContainerFlows()) {
360 if (cFlow.allowsFlow(request.getFlow())) {
361 toInstallList.add(new FlowEntryInstall(request.clone(), cFlow));
365 return toInstallList;
369 * Modify a flow entry with a new one It runs various validity check and
370 * derive the final container flows merged flow entries to work with
372 * @param currentFlowEntry
373 * @param newFlowEntry
375 * the flag indicating if this is a asynchronous request
376 * @return the status of this request. In case of asynchronous call, it will
377 * contain the unique id assigned to this request
379 private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) {
383 if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null
384 || newFlowEntry.getNode() == null) {
385 String msg = "Modify: Invalid FlowEntry";
386 String logMsg = msg + ": {} or {}";
387 log.warn(logMsg, currentFlowEntry, newFlowEntry);
388 return new Status(StatusCode.NOTACCEPTABLE, msg);
390 if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode())
391 || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) {
392 String msg = "Modify: Incompatible Flow Entries";
393 String logMsg = msg + ": {} and {}";
394 log.warn(logMsg, currentFlowEntry, newFlowEntry);
395 return new Status(StatusCode.NOTACCEPTABLE, msg);
399 if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) {
400 String msg = "Modify skipped as flows are the same";
401 String logMsg = msg + ": {} and {}";
402 log.debug(logMsg, currentFlowEntry, newFlowEntry);
403 return new Status(StatusCode.SUCCESS, msg);
407 * Conflict Check: Verify the new entry would not conflict with an
408 * existing one. This is a loose check on the previous original flow
409 * entry requests. No check on the container flow merged flow entries
412 FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry);
413 if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) {
414 String msg = "Operation Rejected: Another flow with same match and priority exists on the target node";
415 String logMsg = msg + ": {}";
416 log.warn(logMsg, currentFlowEntry);
417 return new Status(StatusCode.CONFLICT, msg);
420 // Derive the installed and toInstall entries
421 List<FlowEntryInstall> installedList = deriveInstallEntries(currentFlowEntry.clone(),
422 container.getContainerFlows());
423 List<FlowEntryInstall> toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows());
425 if (toInstallList.isEmpty()) {
426 String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows";
427 String logMsg = msg + ": {}";
428 log.warn(logMsg, newFlowEntry);
430 return new Status(StatusCode.CONFLICT, msg);
434 * If the two list sizes differ, it means the new flow entry does not
435 * satisfy the same number of container flows the current entry does.
436 * This is only possible when the new entry and current entry have
437 * different match. In this scenario the modification would ultimately
438 * be handled as a remove and add operations in the protocol plugin.
440 * Also, if any of the new flow entries would clash with an existing
441 * one, we cannot proceed with the modify operation, because it would
442 * fail for some entries and leave stale entries on the network node.
443 * Modify path can be taken only if it can be performed completely, for
446 * So, for the above two cases, to simplify, let's decouple the modify
447 * in: 1) remove current entries 2) install new entries
449 Status succeeded = null;
450 boolean decouple = false;
451 if (installedList.size() != toInstallList.size()) {
452 log.info("Modify: New flow entry does not satisfy the same "
453 + "number of container flows as the original entry does");
456 List<FlowEntryInstall> toInstallSafe = new ArrayList<FlowEntryInstall>();
457 for (FlowEntryInstall installEntry : toInstallList) {
459 * Conflict Check: Verify the new entry would not overwrite another
462 FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry);
463 if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) {
464 log.info("Modify: new container flow merged flow entry clashes with existing flow");
467 toInstallSafe.add(installEntry);
472 // Remove current entries
473 for (FlowEntryInstall currEntry : installedList) {
474 this.removeEntryInternal(currEntry, async);
476 // Install new entries
477 for (FlowEntryInstall newEntry : toInstallSafe) {
478 succeeded = this.addEntriesInternal(newEntry, async);
482 * The two list have the same size and the entries to install do not
483 * clash with any existing flow on the network node. We assume here
484 * (and might be wrong) that the same container flows that were
485 * satisfied by the current entries are the same that are satisfied
486 * by the new entries. Let's take the risk for now.
488 * Note: modification has to be complete. If any entry modification
489 * fails, we need to stop, restore the already modified entries, and
492 Status retModify = null;
494 int size = toInstallList.size();
496 // Modify and update database
497 retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async);
498 if (retModify.isSuccess()) {
504 // Check if uncompleted modify
506 log.warn("Unable to perform a complete modify for all the container flows merged entries");
507 // Restore original entries
510 log.info("Attempting to restore initial entries");
511 retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async);
512 if (retExt.isSuccess()) {
518 // Fatal error, recovery failed
520 String msg = "Flow recovery failed ! Unrecoverable Error";
522 return new Status(StatusCode.INTERNALERROR, msg);
525 succeeded = retModify;
528 * The first successful status response will be returned. For the
529 * asynchronous call, we can discard the container flow complication for
530 * now and assume we will always deal with one flow only per request
536 * This is the function that modifies the final container flows merged
537 * entries on the network node and update the database. It expects that all
538 * the validity checks are passed
540 * @param currentEntries
543 * the flag indicating if this is a asynchronous request
544 * @return the status of this request. In case of asynchronous call, it will
545 * contain the unique id assigned to this request
547 private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) {
548 FlowEntryDistributionOrderFutureTask futureStatus =
549 distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED);
550 if (futureStatus != null) {
551 Status retStatus = new Status(StatusCode.UNDEFINED);
553 retStatus = futureStatus.get();
554 if (retStatus.getCode()
555 .equals(StatusCode.TIMEOUT)) {
556 // A timeout happened, lets cleanup the workMonitor
557 workMonitor.remove(futureStatus.getOrder());
559 } catch (InterruptedException e) {
561 } catch (ExecutionException e) {
566 // Modify the flow on the network node
567 Status status = async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall()
568 .getFlow(), newEntries.getInstall()
569 .getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries.getInstall()
570 .getFlow(), newEntries.getInstall()
573 if (!status.isSuccess()) {
574 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", newEntries.getInstall(),
575 status.getDescription());
579 log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall());
582 newEntries.setRequestId(status.getRequestId());
583 updateLocalDatabase(currentEntries, false);
584 updateLocalDatabase(newEntries, true);
591 * Remove a flow entry. If the entry is not present in the software view
592 * (entry or node not present), it return successfully
595 * the flow entry to remove
597 * the flag indicating if this is a asynchronous request
598 * @return the status of this request. In case of asynchronous call, it will
599 * contain the unique id assigned to this request
601 private Status removeEntry(FlowEntry flowEntry, boolean async) {
602 Status error = new Status(null, null);
605 if (flowEntry == null || flowEntry.getNode() == null) {
606 String msg = "Invalid FlowEntry";
607 String logMsg = msg + ": {}";
608 log.warn(logMsg, flowEntry);
609 return new Status(StatusCode.NOTACCEPTABLE, msg);
612 // Derive the container flows merged installed entries
613 List<FlowEntryInstall> installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows());
615 Status succeeded = null;
616 boolean atLeastOneRemoved = false;
617 for (FlowEntryInstall entry : installedList) {
618 if (!installedSwView.containsKey(entry)) {
619 String logMsg = "Removal skipped (not present in software view) for flow entry: {}";
620 log.debug(logMsg, flowEntry);
621 if (installedList.size() == 1) {
622 // If we had only one entry to remove, we are done
623 return new Status(StatusCode.SUCCESS);
629 // Remove and update DB
630 Status ret = removeEntryInternal(entry, async);
632 if (!ret.isSuccess()) {
634 log.warn("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription());
635 if (installedList.size() == 1) {
636 // If we had only one entry to remove, this is fatal failure
641 atLeastOneRemoved = true;
646 * No worries if full removal failed. Consistency checker will take care
647 * of removing the stale entries later, or adjusting the software
648 * database if not in sync with hardware
650 return (atLeastOneRemoved) ? succeeded : error;
654 * This is the function that removes the final container flows merged entry
655 * from the network node and update the database. It expects that all the
656 * validity checks are passed
659 * the flow entry to remove
661 * the flag indicating if this is a asynchronous request
662 * @return the status of this request. In case of asynchronous call, it will
663 * contain the unique id assigned to this request
665 private Status removeEntryInternal(FlowEntryInstall entry, boolean async) {
666 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED);
667 if (futureStatus != null) {
668 Status retStatus = new Status(StatusCode.UNDEFINED);
670 retStatus = futureStatus.get();
671 if (retStatus.getCode()
672 .equals(StatusCode.TIMEOUT)) {
673 // A timeout happened, lets cleanup the workMonitor
674 workMonitor.remove(futureStatus.getOrder());
676 } catch (InterruptedException e) {
678 } catch (ExecutionException e) {
683 // Mark the entry to be deleted (for CC just in case we fail)
687 Status status = async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall()
688 .getFlow()) : programmer.removeFlow(entry.getNode(), entry.getInstall()
691 if (!status.isSuccess()) {
692 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
693 status.getDescription());
696 log.trace("Removed {}", entry.getInstall());
699 updateLocalDatabase(entry, false);
706 * This is the function that installs the final container flow merged entry
707 * on the network node and updates the database. It expects that all the
708 * validity and conflict checks are passed. That means it does not check
709 * whether this flow would conflict or overwrite an existing one.
712 * the flow entry to install
714 * the flag indicating if this is a asynchronous request
715 * @return the status of this request. In case of asynchronous call, it will
716 * contain the unique id assigned to this request
718 private Status addEntriesInternal(FlowEntryInstall entry, boolean async) {
719 FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED);
720 if (futureStatus != null) {
721 Status retStatus = new Status(StatusCode.UNDEFINED);
723 retStatus = futureStatus.get();
724 if (retStatus.getCode()
725 .equals(StatusCode.TIMEOUT)) {
726 // A timeout happened, lets cleanup the workMonitor
727 workMonitor.remove(futureStatus.getOrder());
729 } catch (InterruptedException e) {
731 } catch (ExecutionException e) {
736 // Install the flow on the network node
737 Status status = async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall()
738 .getFlow()) : programmer.addFlow(entry.getNode(), entry.getInstall()
741 if (!status.isSuccess()) {
742 log.warn("SDN Plugin failed to program the flow: {}. The failure is: {}", entry.getInstall(),
743 status.getDescription());
747 log.trace("Added {}", entry.getInstall());
750 entry.setRequestId(status.getRequestId());
751 updateLocalDatabase(entry, true);
758 * Returns true if the flow conflicts with all the container's flows. This
759 * means that if the function returns true, the passed flow entry is
760 * congruent with at least one container flow, hence it is good to be
761 * installed on this container.
764 * @return true if flow conflicts with all the container flows, false
767 private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) {
768 List<ContainerFlow> cFlowList = container.getContainerFlows();
770 // Validity check and avoid unnecessary computation
771 // Also takes care of default container where no container flows are
773 if (cFlowList == null || cFlowList.isEmpty()) {
777 for (ContainerFlow cFlow : cFlowList) {
778 if (cFlow.allowsFlow(flowEntry.getFlow())) {
779 // Entry is allowed by at least one container flow: good to go
786 private void updateLocalDatabase(FlowEntryInstall entry, boolean add) {
787 // Update the software view
788 updateSwViewes(entry, add);
790 // Update node indexed flow database
791 updateNodeFlowsDB(entry, add);
793 // Update group indexed flow database
794 updateGroupFlowsDB(entry, add);
798 * Update the node mapped flows database
800 private void updateSwViewes(FlowEntryInstall flowEntries, boolean add) {
802 originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal());
803 installedSwView.put(flowEntries, flowEntries);
805 originalSwView.remove(flowEntries.getOriginal());
806 installedSwView.remove(flowEntries);
811 * Update the node mapped flows database
813 private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) {
814 Node node = flowEntries.getNode();
816 List<FlowEntryInstall> nodeIndeces = this.nodeFlows.get(node);
817 if (nodeIndeces == null) {
821 nodeIndeces = new ArrayList<FlowEntryInstall>();
826 nodeIndeces.add(flowEntries);
828 nodeIndeces.remove(flowEntries);
831 // Update cache across cluster
832 if (nodeIndeces.isEmpty()) {
833 this.nodeFlows.remove(node);
835 this.nodeFlows.put(node, nodeIndeces);
840 * Update the group name mapped flows database
842 private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) {
843 String groupName = flowEntries.getGroupName();
845 // Flow may not be part of a group
846 if (groupName == null) {
850 List<FlowEntryInstall> indices = this.groupFlows.get(groupName);
851 if (indices == null) {
855 indices = new ArrayList<FlowEntryInstall>();
860 indices.add(flowEntries);
862 indices.remove(flowEntries);
865 // Update cache across cluster
866 if (indices.isEmpty()) {
867 this.groupFlows.remove(groupName);
869 this.groupFlows.put(groupName, indices);
874 * Remove a flow entry that has been added previously First checks if the
875 * entry is effectively present in the local database
877 @SuppressWarnings("unused")
878 private Status removeEntry(Node node, String flowName) {
879 FlowEntryInstall target = null;
882 for (FlowEntryInstall entry : installedSwView.values()) {
883 if (entry.equalsByNodeAndName(node, flowName)) {
889 // If it is not there, stop any further processing
890 if (target == null) {
891 return new Status(StatusCode.SUCCESS, "Entry is not present");
895 Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow());
898 if (status.isSuccess()) {
899 updateLocalDatabase(target, false);
902 log.warn("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(),
903 status.getDescription());
910 public Status installFlowEntry(FlowEntry flowEntry) {
912 if (isContainerModeAllowed(flowEntry)) {
913 status = addEntry(flowEntry, false);
915 String msg = "Controller in container mode: Install Refused";
916 String logMsg = msg + ": {}";
917 status = new Status(StatusCode.NOTACCEPTABLE, msg);
918 log.warn(logMsg, flowEntry);
924 public Status installFlowEntryAsync(FlowEntry flowEntry) {
926 if (isContainerModeAllowed(flowEntry)) {
927 status = addEntry(flowEntry, true);
929 String msg = "Controller in container mode: Install Refused";
930 status = new Status(StatusCode.NOTACCEPTABLE, msg);
937 public Status uninstallFlowEntry(FlowEntry flowEntry) {
939 if (isContainerModeAllowed(flowEntry)) {
940 status = removeEntry(flowEntry, false);
942 String msg = "Controller in container mode: Uninstall Refused";
943 String logMsg = msg + ": {}";
944 status = new Status(StatusCode.NOTACCEPTABLE, msg);
945 log.warn(logMsg, flowEntry);
951 public Status uninstallFlowEntryAsync(FlowEntry flowEntry) {
953 if (isContainerModeAllowed(flowEntry)) {
954 status = removeEntry(flowEntry, true);
956 String msg = "Controller in container mode: Uninstall Refused";
957 status = new Status(StatusCode.NOTACCEPTABLE, msg);
964 public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
965 Status status = null;
966 if (isContainerModeAllowed(currentFlowEntry)) {
967 status = modifyEntry(currentFlowEntry, newFlowEntry, false);
969 String msg = "Controller in container mode: Modify Refused";
970 String logMsg = msg + ": {}";
971 status = new Status(StatusCode.NOTACCEPTABLE, msg);
972 log.warn(logMsg, newFlowEntry);
978 public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) {
979 Status status = null;
980 if (isContainerModeAllowed(currentFlowEntry)) {
981 status = modifyEntry(currentFlowEntry, newFlowEntry, true);
983 String msg = "Controller in container mode: Modify Refused";
984 status = new Status(StatusCode.NOTACCEPTABLE, msg);
991 * Returns whether the specified flow entry is allowed to be
992 * installed/removed/modified based on the current container mode status.
993 * This call always returns true in the container instance of forwarding
994 * rules manager. It is meant for the global instance only (default
995 * container) of forwarding rules manager. Idea is that for assuring
996 * container isolation of traffic, flow installation in default container is
997 * blocked when in container mode (containers are present). The only flows
998 * that are allowed in container mode in the default container are the
999 * proactive flows, the ones automatically installed on the network node
1000 * which forwarding mode has been configured to "proactive". These flows are
1001 * needed by controller to discover the nodes topology and to discover the
1002 * attached hosts for some SDN switches.
1005 * The flow entry to be installed/removed/modified
1006 * @return true if not in container mode or if flowEntry is internally
1009 private boolean isContainerModeAllowed(FlowEntry flowEntry) {
1010 return (!inContainerMode) ? true : flowEntry.isInternal();
1014 public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) {
1016 * Run a check on the original entries to decide whether to go with a
1017 * add or modify method. A loose check means only check against the
1018 * original flow entry requests and not against the installed flow
1019 * entries which are the result of the original entry merged with the
1020 * container flow(s) (if any). The modifyFlowEntry method in presence of
1021 * conflicts with the Container flows (if any) would revert back to a
1022 * delete + add pattern
1024 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1026 if (currentFlowEntry != null) {
1027 return modifyFlowEntry(currentFlowEntry, newFlowEntry);
1029 return installFlowEntry(newFlowEntry);
1034 public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) {
1036 * Run a check on the original entries to decide whether to go with a
1037 * add or modify method. A loose check means only check against the
1038 * original flow entry requests and not against the installed flow
1039 * entries which are the result of the original entry merged with the
1040 * container flow(s) (if any). The modifyFlowEntry method in presence of
1041 * conflicts with the Container flows (if any) would revert back to a
1042 * delete + add pattern
1044 FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry);
1046 if (currentFlowEntry != null) {
1047 return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry);
1049 return installFlowEntryAsync(newFlowEntry);
1054 public Status uninstallFlowEntryGroup(String groupName) {
1055 if (groupName == null || groupName.isEmpty()) {
1056 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1058 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1059 return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api");
1061 if (inContainerMode) {
1062 String msg = "Controller in container mode: Group Uninstall Refused";
1063 String logMsg = msg + ": {}";
1064 log.warn(logMsg, groupName);
1065 return new Status(StatusCode.NOTACCEPTABLE, msg);
1067 int toBeRemoved = 0;
1069 if (groupFlows.containsKey(groupName)) {
1070 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1071 toBeRemoved = list.size();
1072 for (FlowEntryInstall entry : list) {
1073 Status status = this.removeEntry(entry.getOriginal(), false);
1074 if (status.isSuccess()) {
1077 error = status.getDescription();
1081 return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR,
1082 "Not all the flows were removed: " + error);
1086 public Status uninstallFlowEntryGroupAsync(String groupName) {
1087 if (groupName == null || groupName.isEmpty()) {
1088 return new Status(StatusCode.BADREQUEST, "Invalid group name");
1090 if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) {
1091 return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api");
1093 if (inContainerMode) {
1094 String msg = "Controller in container mode: Group Uninstall Refused";
1095 String logMsg = msg + ": {}";
1096 log.warn(logMsg, groupName);
1097 return new Status(StatusCode.NOTACCEPTABLE, msg);
1099 if (groupFlows.containsKey(groupName)) {
1100 List<FlowEntryInstall> list = new ArrayList<FlowEntryInstall>(groupFlows.get(groupName));
1101 for (FlowEntryInstall entry : list) {
1102 this.removeEntry(entry.getOriginal(), true);
1105 return new Status(StatusCode.SUCCESS);
1109 public boolean checkFlowEntryConflict(FlowEntry flowEntry) {
1110 return entryConflictsWithContainerFlows(flowEntry);
1114 * Updates all installed flows because the container flow got updated This
1115 * is obtained in two phases on per node basis: 1) Uninstall of all flows 2)
1116 * Reinstall of all flows This is needed because a new container flows
1117 * merged flow may conflict with an existing old container flows merged flow
1118 * on the network node
1120 private void updateFlowsContainerFlow() {
1121 Set<FlowEntry> toReInstall = new HashSet<FlowEntry>();
1122 // First remove all installed entries
1123 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> entry : installedSwView.entrySet()) {
1124 FlowEntryInstall current = entry.getValue();
1125 // Store the original entry
1126 toReInstall.add(current.getOriginal());
1127 // Remove the old couples. No validity checks to be run, use the
1129 this.removeEntryInternal(current, false);
1131 // Then reinstall the original entries
1132 for (FlowEntry entry : toReInstall) {
1133 // Reinstall the original flow entries, via the regular path: new
1134 // cFlow merge + validations
1135 this.installFlowEntry(entry);
1139 private void nonClusterObjectCreate() {
1140 originalSwView = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1141 installedSwView = new ConcurrentHashMap<FlowEntryInstall, FlowEntryInstall>();
1142 nodeFlows = new ConcurrentHashMap<Node, List<FlowEntryInstall>>();
1143 groupFlows = new ConcurrentHashMap<String, List<FlowEntryInstall>>();
1144 TSPolicies = new ConcurrentHashMap<String, Object>();
1145 staticFlowsOrdinal = new ConcurrentHashMap<Integer, Integer>();
1146 portGroupConfigs = new ConcurrentHashMap<String, PortGroupConfig>();
1147 portGroupData = new ConcurrentHashMap<PortGroupConfig, Map<Node, PortGroup>>();
1148 staticFlows = new ConcurrentHashMap<Integer, FlowConfig>();
1149 inactiveFlows = new ConcurrentHashMap<FlowEntry, FlowEntry>();
1152 private void registerWithOSGIConsole() {
1153 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
1154 bundleContext.registerService(CommandProvider.class.getName(), this, null);
1158 public void setTSPolicyData(String policyname, Object o, boolean add) {
1161 /* Check if this policy already exists */
1162 if (!(TSPolicies.containsKey(policyname))) {
1163 TSPolicies.put(policyname, o);
1166 TSPolicies.remove(policyname);
1168 if (frmAware != null) {
1169 synchronized (frmAware) {
1170 for (IForwardingRulesManagerAware frma : frmAware) {
1172 frma.policyUpdate(policyname, add);
1173 } catch (Exception e) {
1174 log.warn("Exception on callback", e);
1182 public Map<String, Object> getTSPolicyData() {
1187 public Object getTSPolicyData(String policyName) {
1188 if (TSPolicies.containsKey(policyName)) {
1189 return TSPolicies.get(policyName);
1196 public List<FlowEntry> getFlowEntriesForGroup(String policyName) {
1197 List<FlowEntry> list = new ArrayList<FlowEntry>();
1198 if (policyName != null && !policyName.trim().isEmpty()) {
1199 for (Map.Entry<FlowEntry, FlowEntry> entry : this.originalSwView.entrySet()) {
1200 if (policyName.equals(entry.getKey().getGroupName())) {
1201 list.add(entry.getKey().clone());
1209 public List<FlowEntry> getInstalledFlowEntriesForGroup(String policyName) {
1210 List<FlowEntry> list = new ArrayList<FlowEntry>();
1211 if (policyName != null && !policyName.trim().isEmpty()) {
1212 for (Map.Entry<FlowEntryInstall, FlowEntryInstall> entry : this.installedSwView.entrySet()) {
1213 if (policyName.equals(entry.getKey().getGroupName())) {
1214 list.add(entry.getKey().getInstall().clone());
1222 public void addOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1224 for (FlowEntryInstall flow : this.nodeFlows.get(node)) {
1225 if (flow.getFlowName().equals(flowName)) {
1226 FlowEntry currentFlowEntry = flow.getOriginal();
1227 FlowEntry newFlowEntry = currentFlowEntry.clone();
1228 for (NodeConnector dstPort : portList) {
1229 newFlowEntry.getFlow().addAction(new Output(dstPort));
1231 Status error = modifyEntry(currentFlowEntry, newFlowEntry, false);
1232 if (error.isSuccess()) {
1233 log.info("Ports {} added to FlowEntry {}", portList, flowName);
1235 log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList,
1236 currentFlowEntry.toString(), error.getDescription());
1241 log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node);
1245 public void removeOutputPort(Node node, String flowName, List<NodeConnector> portList) {
1246 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1247 FlowEntryInstall flow = this.installedSwView.get(index);
1248 if (flow.getFlowName().equals(flowName)) {
1249 FlowEntry currentFlowEntry = flow.getOriginal();
1250 FlowEntry newFlowEntry = currentFlowEntry.clone();
1251 for (NodeConnector dstPort : portList) {
1252 Action action = new Output(dstPort);
1253 newFlowEntry.getFlow().removeAction(action);
1255 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1256 if (status.isSuccess()) {
1257 log.info("Ports {} removed from FlowEntry {}", portList, flowName);
1259 log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList,
1260 currentFlowEntry.toString(), status.getDescription());
1265 log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node);
1269 * This function assumes the target flow has only one output port
1272 public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) {
1273 FlowEntry currentFlowEntry = null;
1274 FlowEntry newFlowEntry = null;
1277 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1278 FlowEntryInstall flow = this.installedSwView.get(index);
1279 if (flow.getFlowName().equals(flowName)) {
1280 currentFlowEntry = flow.getOriginal();
1284 if (currentFlowEntry == null) {
1285 log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node);
1289 // Create a flow copy with the new output port
1290 newFlowEntry = currentFlowEntry.clone();
1291 Action target = null;
1292 for (Action action : newFlowEntry.getFlow().getActions()) {
1293 if (action.getType() == ActionType.OUTPUT) {
1298 newFlowEntry.getFlow().removeAction(target);
1299 newFlowEntry.getFlow().addAction(new Output(outPort));
1301 // Modify on network node
1302 Status status = modifyEntry(currentFlowEntry, newFlowEntry, false);
1304 if (status.isSuccess()) {
1305 log.info("Output port replaced with {} for flow {} on node {}", outPort, flowName, node);
1307 log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node,
1308 status.getDescription());
1314 public NodeConnector getOutputPort(Node node, String flowName) {
1315 for (FlowEntryInstall index : this.nodeFlows.get(node)) {
1316 FlowEntryInstall flow = this.installedSwView.get(index);
1317 if (flow.getFlowName().equals(flowName)) {
1318 for (Action action : flow.getOriginal().getFlow().getActions()) {
1319 if (action.getType() == ActionType.OUTPUT) {
1320 return ((Output) action).getPort();
1328 private void cacheStartup() {
1333 private void allocateCaches() {
1334 if (this.clusterContainerService == null) {
1335 log.warn("Un-initialized clusterContainerService, can't create cache");
1339 log.debug("Allocating caches for Container {}", container.getName());
1342 clusterContainerService.createCache("frm.originalSwView",
1343 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1345 clusterContainerService.createCache("frm.installedSwView",
1346 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1348 clusterContainerService.createCache("frm.inactiveFlows",
1349 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1351 clusterContainerService.createCache("frm.nodeFlows",
1352 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1354 clusterContainerService.createCache("frm.groupFlows",
1355 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1357 clusterContainerService.createCache("frm.staticFlows",
1358 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1360 clusterContainerService.createCache("frm.flowsSaveEvent",
1361 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1363 clusterContainerService.createCache("frm.staticFlowsOrdinal",
1364 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1366 clusterContainerService.createCache("frm.portGroupConfigs",
1367 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1369 clusterContainerService.createCache("frm.portGroupData",
1370 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1372 clusterContainerService.createCache("frm.TSPolicies",
1373 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
1375 clusterContainerService.createCache(WORKSTATUSCACHE,
1376 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1378 clusterContainerService.createCache(WORKORDERCACHE,
1379 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
1381 } catch (CacheConfigException cce) {
1382 log.error("CacheConfigException");
1383 } catch (CacheExistException cce) {
1384 log.error("CacheExistException");
1388 @SuppressWarnings({ "unchecked" })
1389 private void retrieveCaches() {
1390 ConcurrentMap<?, ?> map;
1392 if (this.clusterContainerService == null) {
1393 log.warn("un-initialized clusterContainerService, can't retrieve cache");
1394 nonClusterObjectCreate();
1398 log.debug("Retrieving Caches for Container {}", container.getName());
1400 map = clusterContainerService.getCache("frm.originalSwView");
1402 originalSwView = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1404 log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName());
1407 map = clusterContainerService.getCache("frm.installedSwView");
1409 installedSwView = (ConcurrentMap<FlowEntryInstall, FlowEntryInstall>) map;
1411 log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName());
1414 map = clusterContainerService.getCache("frm.inactiveFlows");
1416 inactiveFlows = (ConcurrentMap<FlowEntry, FlowEntry>) map;
1418 log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName());
1421 map = clusterContainerService.getCache("frm.nodeFlows");
1423 nodeFlows = (ConcurrentMap<Node, List<FlowEntryInstall>>) map;
1425 log.error("Retrieval of cache failed for Container {}", container.getName());
1428 map = clusterContainerService.getCache("frm.groupFlows");
1430 groupFlows = (ConcurrentMap<String, List<FlowEntryInstall>>) map;
1432 log.error("Retrieval of frm.groupFlows cache failed for Container {}", container.getName());
1435 map = clusterContainerService.getCache("frm.staticFlows");
1437 staticFlows = (ConcurrentMap<Integer, FlowConfig>) map;
1439 log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName());
1442 map = clusterContainerService.getCache("frm.staticFlowsOrdinal");
1444 staticFlowsOrdinal = (ConcurrentMap<Integer, Integer>) map;
1446 log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName());
1449 map = clusterContainerService.getCache("frm.portGroupConfigs");
1451 portGroupConfigs = (ConcurrentMap<String, PortGroupConfig>) map;
1453 log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName());
1456 map = clusterContainerService.getCache("frm.portGroupData");
1458 portGroupData = (ConcurrentMap<PortGroupConfig, Map<Node, PortGroup>>) map;
1460 log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName());
1463 map = clusterContainerService.getCache("frm.TSPolicies");
1465 TSPolicies = (ConcurrentMap<String, Object>) map;
1467 log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName());
1470 map = clusterContainerService.getCache(WORKORDERCACHE);
1472 workOrder = (ConcurrentMap<FlowEntryDistributionOrder, FlowEntryInstall>) map;
1474 log.error("Retrieval of " + WORKORDERCACHE + " cache failed for Container {}", container.getName());
1477 map = clusterContainerService.getCache(WORKSTATUSCACHE);
1479 workStatus = (ConcurrentMap<FlowEntryDistributionOrder, Status>) map;
1481 log.error("Retrieval of " + WORKSTATUSCACHE + " cache failed for Container {}", container.getName());
1485 private boolean flowConfigExists(FlowConfig config) {
1486 // Flow name has to be unique on per node id basis
1487 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1488 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1496 public Status addStaticFlow(FlowConfig config) {
1497 // Configuration object validation
1498 Status status = config.validate(container);
1499 if (!status.isSuccess()) {
1500 log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription());
1501 String error = "Invalid Configuration (" + status.getDescription() + ")";
1502 config.setStatus(error);
1503 return new Status(StatusCode.BADREQUEST, error);
1505 return addStaticFlowInternal(config, false);
1509 * Private method to add a static flow configuration which does not run any
1510 * validation on the passed FlowConfig object. If restore is set to true,
1511 * configuration is stored in configuration database regardless the
1512 * installation on the network node was successful. This is useful at boot
1513 * when static flows are present in startup configuration and are read
1514 * before the switches connects.
1517 * The static flow configuration
1519 * if true, the configuration is stored regardless the
1520 * installation on the network node was successful
1521 * @return The status of this request
1523 private Status addStaticFlowInternal(FlowConfig config, boolean restore) {
1524 boolean multipleFlowPush = false;
1527 config.setStatus(SUCCESS);
1530 if (flowConfigExists(config)) {
1531 error = "Entry with this name on specified switch already exists";
1532 log.warn("Entry with this name on specified switch already exists: {}", config);
1533 config.setStatus(error);
1534 return new Status(StatusCode.CONFLICT, error);
1537 if ((config.getIngressPort() == null) && config.getPortGroup() != null) {
1538 for (String portGroupName : portGroupConfigs.keySet()) {
1539 if (portGroupName.equalsIgnoreCase(config.getPortGroup())) {
1540 multipleFlowPush = true;
1544 if (!multipleFlowPush) {
1545 log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config);
1546 error = "Invalid Configuration (Invalid PortGroup Name)";
1547 config.setStatus(error);
1548 return new Status(StatusCode.BADREQUEST, error);
1553 * If requested program the entry in hardware first before updating the
1556 if (!multipleFlowPush) {
1558 if (config.installInHw()) {
1559 FlowEntry entry = config.getFlowEntry();
1560 status = this.installFlowEntry(entry);
1561 if (!status.isSuccess()) {
1562 config.setStatus(status.getDescription());
1571 * When the control reaches this point, either of the following
1572 * conditions is true 1. This is a single entry configuration (non
1573 * PortGroup) and the hardware installation is successful 2. This is a
1574 * multiple entry configuration (PortGroup) and hardware installation is
1575 * NOT done directly on this event. 3. The User prefers to retain the
1576 * configuration in Controller and skip hardware installation.
1578 * Hence it is safe to update the StaticFlow DB at this point.
1580 * Note : For the case of PortGrouping, it is essential to have this DB
1581 * populated before the PortGroupListeners can query for the DB
1582 * triggered using portGroupChanged event...
1584 Integer ordinal = staticFlowsOrdinal.get(0);
1585 staticFlowsOrdinal.put(0, ++ordinal);
1586 staticFlows.put(ordinal, config);
1588 if (multipleFlowPush) {
1589 PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup());
1590 Map<Node, PortGroup> existingData = portGroupData.get(pgconfig);
1591 if (existingData != null) {
1592 portGroupChanged(pgconfig, existingData, true);
1595 return new Status(StatusCode.SUCCESS);
1598 private void addStaticFlowsToSwitch(Node node) {
1599 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1600 FlowConfig config = entry.getValue();
1601 if (config.isPortGroupEnabled()) {
1604 if (config.getNode().equals(node)) {
1605 if (config.installInHw() && !config.getStatus().equals(SUCCESS)) {
1606 Status status = this.installFlowEntryAsync(config.getFlowEntry());
1607 config.setStatus(status.getDescription());
1611 // Update cluster cache
1612 refreshClusterStaticFlowsStatus(node);
1615 private void updateStaticFlowConfigsOnNodeDown(Node node) {
1616 log.trace("Updating Static Flow configs on node down: {}", node);
1618 List<Integer> toRemove = new ArrayList<Integer>();
1619 for (Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1621 FlowConfig config = entry.getValue();
1623 if (config.isPortGroupEnabled()) {
1627 if (config.installInHw() && config.getNode().equals(node)) {
1628 if (config.isInternalFlow()) {
1629 // Take note of this controller generated static flow
1630 toRemove.add(entry.getKey());
1632 config.setStatus(NODEDOWN);
1636 // Remove controller generated static flows for this node
1637 for (Integer index : toRemove) {
1638 staticFlows.remove(index);
1640 // Update cluster cache
1641 refreshClusterStaticFlowsStatus(node);
1645 private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) {
1646 log.trace("Updating Static Flow configs on container mode change: {}", update);
1648 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1649 FlowConfig config = entry.getValue();
1650 if (config.isPortGroupEnabled()) {
1653 if (config.installInHw() && !config.isInternalFlow()) {
1656 config.setStatus("Removed from node because in container mode");
1659 config.setStatus(SUCCESS);
1665 // Update cluster cache
1666 refreshClusterStaticFlowsStatus(null);
1670 public Status removeStaticFlow(FlowConfig config) {
1672 * No config.isInternal() check as NB does not take this path and GUI
1673 * cannot issue a delete on an internal generated flow. We need this
1674 * path to be accessible when switch mode is changed from proactive to
1675 * reactive, so that we can remove the internal generated LLDP and ARP
1679 // Look for the target configuration entry
1681 FlowConfig target = null;
1682 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1683 if (entry.getValue().isByNameAndNodeIdEqual(config)) {
1684 key = entry.getKey();
1685 target = entry.getValue();
1689 if (target == null) {
1690 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1693 // Program the network node
1694 Status status = this.uninstallFlowEntry(config.getFlowEntry());
1696 // Update configuration database if programming was successful
1697 if (status.isSuccess()) {
1698 staticFlows.remove(key);
1705 public Status removeStaticFlow(String name, Node node) {
1706 // Look for the target configuration entry
1708 FlowConfig target = null;
1709 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1710 if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) {
1711 key = mapEntry.getKey();
1712 target = mapEntry.getValue();
1716 if (target == null) {
1717 return new Status(StatusCode.NOTFOUND, "Entry Not Present");
1720 // Validity check for api3 entry point
1721 if (target.isInternalFlow()) {
1722 String msg = "Invalid operation: Controller generated flow cannot be deleted";
1723 String logMsg = msg + ": {}";
1724 log.warn(logMsg, name);
1725 return new Status(StatusCode.NOTACCEPTABLE, msg);
1728 if (target.isPortGroupEnabled()) {
1729 String msg = "Invalid operation: Port Group flows cannot be deleted through this API";
1730 String logMsg = msg + ": {}";
1731 log.warn(logMsg, name);
1732 return new Status(StatusCode.NOTACCEPTABLE, msg);
1735 // Program the network node
1736 Status status = this.removeEntry(target.getFlowEntry(), false);
1738 // Update configuration database if programming was successful
1739 if (status.isSuccess()) {
1740 staticFlows.remove(key);
1747 public Status modifyStaticFlow(FlowConfig newFlowConfig) {
1748 // Validity check for api3 entry point
1749 if (newFlowConfig.isInternalFlow()) {
1750 String msg = "Invalid operation: Controller generated flow cannot be modified";
1751 String logMsg = msg + ": {}";
1752 log.warn(logMsg, newFlowConfig);
1753 return new Status(StatusCode.NOTACCEPTABLE, msg);
1757 Status status = newFlowConfig.validate(container);
1758 if (!status.isSuccess()) {
1759 String msg = "Invalid Configuration (" + status.getDescription() + ")";
1760 newFlowConfig.setStatus(msg);
1761 log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription());
1762 return new Status(StatusCode.BADREQUEST, msg);
1765 FlowConfig oldFlowConfig = null;
1766 Integer index = null;
1767 for (ConcurrentMap.Entry<Integer, FlowConfig> mapEntry : staticFlows.entrySet()) {
1768 FlowConfig entry = mapEntry.getValue();
1769 if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) {
1770 oldFlowConfig = entry;
1771 index = mapEntry.getKey();
1776 if (oldFlowConfig == null) {
1777 String msg = "Attempt to modify a non existing static flow";
1778 String logMsg = msg + ": {}";
1779 log.warn(logMsg, newFlowConfig);
1780 return new Status(StatusCode.NOTFOUND, msg);
1783 // Do not attempt to reinstall the flow, warn user
1784 if (newFlowConfig.equals(oldFlowConfig)) {
1785 String msg = "No modification detected";
1786 log.info("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig);
1787 return new Status(StatusCode.SUCCESS, msg);
1790 // If flow is installed, program the network node
1791 status = new Status(StatusCode.SUCCESS, "Saved in config");
1792 if (oldFlowConfig.installInHw()) {
1793 status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry());
1796 // Update configuration database if programming was successful
1797 if (status.isSuccess()) {
1798 newFlowConfig.setStatus(status.getDescription());
1799 staticFlows.put(index, newFlowConfig);
1806 public Status toggleStaticFlowStatus(String name, Node node) {
1807 return toggleStaticFlowStatus(getStaticFlow(name, node));
1811 public Status toggleStaticFlowStatus(FlowConfig config) {
1812 if (config == null) {
1813 String msg = "Invalid request: null flow config";
1815 return new Status(StatusCode.BADREQUEST, msg);
1817 // Validity check for api3 entry point
1818 if (config.isInternalFlow()) {
1819 String msg = "Invalid operation: Controller generated flow cannot be modified";
1820 String logMsg = msg + ": {}";
1821 log.warn(logMsg, config);
1822 return new Status(StatusCode.NOTACCEPTABLE, msg);
1825 // Find the config entry
1827 FlowConfig target = null;
1828 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1829 FlowConfig conf = entry.getValue();
1830 if (conf.isByNameAndNodeIdEqual(config)) {
1831 key = entry.getKey();
1836 if (target != null) {
1837 Status status = target.validate(container);
1838 if (!status.isSuccess()) {
1839 log.warn(status.getDescription());
1842 status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this
1843 .installFlowEntry(target.getFlowEntry());
1844 if (status.isSuccess()) {
1845 // Update Configuration database
1846 target.setStatus(SUCCESS);
1847 target.toggleInstallation();
1848 staticFlows.put(key, target);
1853 return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status");
1857 * Reinsert all static flows entries in the cache to force cache updates in
1858 * the cluster. This is useful when only some parameters were changed in the
1859 * entries, like the status.
1862 * The node for which the static flow configurations have to be
1863 * refreshed. If null, all nodes static flows will be refreshed.
1865 private void refreshClusterStaticFlowsStatus(Node node) {
1866 // Refresh cluster cache
1867 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1868 if (node == null || entry.getValue().getNode().equals(node)) {
1869 staticFlows.put(entry.getKey(), entry.getValue());
1875 * Uninstall all the non-internal Flow Entries present in the software view.
1876 * If requested, a copy of each original flow entry will be stored in the
1877 * inactive list so that it can be re-applied when needed (This is typically
1878 * the case when running in the default container and controller moved to
1879 * container mode) NOTE WELL: The routine as long as does a bulk change will
1880 * operate only on the entries for nodes locally attached so to avoid
1881 * redundant operations initiated by multiple nodes
1883 * @param preserveFlowEntries
1884 * if true, a copy of each original entry is stored in the
1887 private void uninstallAllFlowEntries(boolean preserveFlowEntries) {
1888 log.info("Uninstalling all non-internal flows");
1890 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>();
1892 // Store entries / create target list
1893 for (ConcurrentMap.Entry<FlowEntryInstall, FlowEntryInstall> mapEntry : installedSwView.entrySet()) {
1894 FlowEntryInstall flowEntries = mapEntry.getValue();
1895 // Skip internal generated static flows
1896 if (!flowEntries.isInternal()) {
1897 toRemove.add(flowEntries);
1898 // Store the original entries if requested
1899 if (preserveFlowEntries) {
1900 inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal());
1905 // Now remove the entries
1906 for (FlowEntryInstall flowEntryHw : toRemove) {
1907 Node n = flowEntryHw.getNode();
1908 if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
1909 Status status = this.removeEntryInternal(flowEntryHw, false);
1910 if (!status.isSuccess()) {
1911 log.warn("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription());
1914 log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job",
1921 * Re-install all the Flow Entries present in the inactive list The inactive
1922 * list will be empty at the end of this call This function is called on the
1923 * default container instance of FRM only when the last container is deleted
1925 private void reinstallAllFlowEntries() {
1926 log.info("Reinstalling all inactive flows");
1928 for (FlowEntry flowEntry : this.inactiveFlows.keySet()) {
1929 this.addEntry(flowEntry, false);
1932 // Empty inactive list in any case
1933 inactiveFlows.clear();
1937 public List<FlowConfig> getStaticFlows() {
1938 return getStaticFlowsOrderedList(staticFlows, staticFlowsOrdinal.get(0).intValue());
1941 // TODO: need to come out with a better algorithm for maintaining the order
1942 // of the configuration entries
1943 // with actual one, index associated to deleted entries cannot be reused and
1945 private List<FlowConfig> getStaticFlowsOrderedList(ConcurrentMap<Integer, FlowConfig> flowMap, int maxKey) {
1946 List<FlowConfig> orderedList = new ArrayList<FlowConfig>();
1947 for (int i = 0; i <= maxKey; i++) {
1948 FlowConfig entry = flowMap.get(i);
1949 if (entry != null) {
1950 orderedList.add(entry);
1957 public FlowConfig getStaticFlow(String name, Node node) {
1958 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1959 if (entry.getValue().isByNameAndNodeIdEqual(name, node)) {
1960 return entry.getValue();
1967 public List<FlowConfig> getStaticFlows(Node node) {
1968 List<FlowConfig> list = new ArrayList<FlowConfig>();
1969 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1970 if (entry.getValue().onNode(node)) {
1971 list.add(entry.getValue());
1978 public List<String> getStaticFlowNamesForNode(Node node) {
1979 List<String> list = new ArrayList<String>();
1980 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1981 if (entry.getValue().onNode(node)) {
1982 list.add(entry.getValue().getName());
1989 public List<Node> getListNodeWithConfiguredFlows() {
1990 Set<Node> set = new HashSet<Node>();
1991 for (ConcurrentMap.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
1992 set.add(entry.getValue().getNode());
1994 return new ArrayList<Node>(set);
1997 @SuppressWarnings("unchecked")
1998 private void loadFlowConfiguration() {
1999 ObjectReader objReader = new ObjectReader();
2000 ConcurrentMap<Integer, FlowConfig> confList = (ConcurrentMap<Integer, FlowConfig>) objReader.read(this,
2003 ConcurrentMap<String, PortGroupConfig> pgConfig = (ConcurrentMap<String, PortGroupConfig>) objReader.read(this,
2006 if (pgConfig != null) {
2007 for (ConcurrentMap.Entry<String, PortGroupConfig> entry : pgConfig.entrySet()) {
2008 addPortGroupConfig(entry.getKey(), entry.getValue().getMatchString(), true);
2012 if (confList == null) {
2017 for (Integer key : confList.keySet()) {
2018 if (key.intValue() > maxKey) {
2019 maxKey = key.intValue();
2023 for (FlowConfig conf : getStaticFlowsOrderedList(confList, maxKey)) {
2024 addStaticFlowInternal(conf, true);
2029 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
2030 return ois.readObject();
2034 public Status saveConfig() {
2035 return saveConfigInternal();
2038 private Status saveConfigInternal() {
2039 ObjectWriter objWriter = new ObjectWriter();
2040 ConcurrentMap<Integer, FlowConfig> nonDynamicFlows = new ConcurrentHashMap<Integer, FlowConfig>();
2041 for (Integer ordinal : staticFlows.keySet()) {
2042 FlowConfig config = staticFlows.get(ordinal);
2043 // Do not save dynamic and controller generated static flows
2044 if (config.isDynamic() || config.isInternalFlow()) {
2047 nonDynamicFlows.put(ordinal, config);
2049 objWriter.write(nonDynamicFlows, frmFileName);
2050 objWriter.write(new ConcurrentHashMap<String, PortGroupConfig>(portGroupConfigs), portGroupFileName);
2051 return new Status(StatusCode.SUCCESS, null);
2055 public void subnetNotify(Subnet sub, boolean add) {
2058 private void installImplicitARPReplyPunt(Node node) {
2064 List<String> puntAction = new ArrayList<String>();
2065 puntAction.add(ActionType.CONTROLLER.toString());
2067 FlowConfig allowARP = new FlowConfig();
2068 allowARP.setInstallInHw(true);
2069 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP Reply" + FlowConfig.INTERNALSTATICFLOWEND);
2070 allowARP.setPriority("500");
2071 allowARP.setNode(node);
2072 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()).toUpperCase());
2073 allowARP.setDstMac(HexEncode.bytesToHexString(switchManager.getControllerMAC()));
2074 allowARP.setActions(puntAction);
2075 addStaticFlowInternal(allowARP, true); // skip validation on internal static flow name
2081 * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node,
2084 * This method can be called from within the OSGi framework context,
2085 * given the programming operation can take sometime, it not good
2086 * pratice to have in it's context operations that can take time,
2087 * hence moving off to a different thread for async processing.
2089 private ExecutorService executor;
2091 public void modeChangeNotify(final Node node, final boolean proactive) {
2092 Callable<Status> modeChangeCallable = new Callable<Status>() {
2094 public Status call() throws Exception {
2095 List<FlowConfig> defaultConfigs = new ArrayList<FlowConfig>();
2097 List<String> puntAction = new ArrayList<String>();
2098 puntAction.add(ActionType.CONTROLLER.toString());
2100 FlowConfig allowARP = new FlowConfig();
2101 allowARP.setInstallInHw(true);
2102 allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND);
2103 allowARP.setPriority("1");
2104 allowARP.setNode(node);
2105 allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue())
2107 allowARP.setActions(puntAction);
2108 defaultConfigs.add(allowARP);
2110 FlowConfig allowLLDP = new FlowConfig();
2111 allowLLDP.setInstallInHw(true);
2112 allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND);
2113 allowLLDP.setPriority("1");
2114 allowLLDP.setNode(node);
2115 allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue())
2117 allowLLDP.setActions(puntAction);
2118 defaultConfigs.add(allowLLDP);
2120 List<String> dropAction = new ArrayList<String>();
2121 dropAction.add(ActionType.DROP.toString());
2123 FlowConfig dropAllConfig = new FlowConfig();
2124 dropAllConfig.setInstallInHw(true);
2125 dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop"
2126 + FlowConfig.INTERNALSTATICFLOWEND);
2127 dropAllConfig.setPriority("0");
2128 dropAllConfig.setNode(node);
2129 dropAllConfig.setActions(dropAction);
2130 defaultConfigs.add(dropAllConfig);
2132 log.info("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive"));
2133 for (FlowConfig fc : defaultConfigs) {
2134 Status status = (proactive) ? addStaticFlowInternal(fc, false) : removeStaticFlow(fc);
2135 if (status.isSuccess()) {
2136 log.info("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName());
2138 log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"),
2142 return new Status(StatusCode.SUCCESS);
2147 * Execute the work outside the caller context, this could be an
2148 * expensive operation and we don't want to block the caller for it.
2150 this.executor.submit(modeChangeCallable);
2154 * Remove from the databases all the flows installed on the node
2158 private void cleanDatabaseForNode(Node node) {
2159 log.info("Cleaning Flow database for Node {}", node);
2160 if (nodeFlows.containsKey(node)) {
2161 List<FlowEntryInstall> toRemove = new ArrayList<FlowEntryInstall>(nodeFlows.get(node));
2163 for (FlowEntryInstall entry : toRemove) {
2164 updateLocalDatabase(entry, false);
2169 private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) {
2174 Match match = flow.getMatch();
2175 if (match.isPresent(MatchType.IN_PORT)) {
2176 NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue();
2177 if (matchPort.equals(nc)) {
2181 List<Action> actionsList = flow.getActions();
2182 if (actionsList != null) {
2183 for (Action action : actionsList) {
2184 if (action instanceof Output) {
2185 NodeConnector actionPort = ((Output) action).getPort();
2186 if (actionPort.equals(nc)) {
2196 public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
2197 this.pendingEvents.offer(new NodeUpdateEvent(type, node));
2201 public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
2202 boolean updateStaticFlowCluster = false;
2208 Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName);
2209 if (config != null) {
2210 switch (config.getValue()) {
2211 case Config.ADMIN_DOWN:
2212 log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector);
2213 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2215 case Config.ADMIN_UP:
2216 log.trace("Port {} is administratively up: installing interested flows", nodeConnector);
2217 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector);
2219 case Config.ADMIN_UNDEF:
2226 // This is the case where a switch port is removed from the SDN agent space
2227 log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector);
2228 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector);
2234 if (updateStaticFlowCluster) {
2235 refreshClusterStaticFlowsStatus(nodeConnector.getNode());
2240 * It goes through the static flows configuration, it identifies the ones
2241 * which have the specified node connector as input or output port and
2242 * install them on the network node if they are marked to be installed in
2243 * hardware and their status shows they were not installed yet
2245 private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) {
2246 boolean updated = false;
2247 List<FlowConfig> flowConfigForNode = getStaticFlows(nodeConnector.getNode());
2248 for (FlowConfig flowConfig : flowConfigForNode) {
2249 if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) {
2250 if (flowConfig.installInHw() && !flowConfig.getStatus().equals(SUCCESS)) {
2251 Status status = this.installFlowEntry(flowConfig.getFlowEntry());
2252 if (!status.isSuccess()) {
2253 flowConfig.setStatus(status.getDescription());
2255 flowConfig.setStatus(SUCCESS);
2265 * Remove from the network node all the flows which have the specified node
2266 * connector as input or output port. If any of the flow entry is a static
2267 * flow, it updates the correspondent configuration.
2269 private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) {
2270 boolean updated = false;
2271 List<FlowEntryInstall> nodeFlowEntries = nodeFlows.get(nodeConnector.getNode());
2272 if (nodeFlowEntries == null) {
2275 for (FlowEntryInstall fei : new ArrayList<FlowEntryInstall>(nodeFlowEntries)) {
2276 if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) {
2277 Status status = this.removeEntryInternal(fei, true);
2278 if (!status.isSuccess()) {
2282 * If the flow entry is a static flow, then update its
2285 if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) {
2286 FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode());
2287 if (flowConfig != null) {
2288 flowConfig.setStatus(PORTREMOVED);
2297 private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) {
2298 FlowConfig derivedFlow = new FlowConfig(original);
2299 derivedFlow.setDynamic(true);
2300 derivedFlow.setPortGroup(null);
2301 derivedFlow.setName(original.getName() + "_" + configName + "_" + port);
2302 derivedFlow.setIngressPort(port + "");
2306 private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2307 for (FlowConfig staticFlow : staticFlows.values()) {
2308 if (staticFlow.getPortGroup() == null) {
2311 if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) {
2312 for (Short port : data.getPorts()) {
2313 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2314 addStaticFlowInternal(derivedFlow, false);
2320 private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) {
2321 for (FlowConfig staticFlow : staticFlows.values()) {
2322 if (staticFlow.getPortGroup() == null) {
2325 if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) {
2326 for (Short port : data.getPorts()) {
2327 FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port);
2328 removeStaticFlow(derivedFlow);
2335 public void portGroupChanged(PortGroupConfig config, Map<Node, PortGroup> data, boolean add) {
2336 log.info("PortGroup Changed for: {} Data: {}", config, portGroupData);
2337 Map<Node, PortGroup> existingData = portGroupData.get(config);
2338 if (existingData != null) {
2339 for (Map.Entry<Node, PortGroup> entry : data.entrySet()) {
2340 PortGroup existingPortGroup = existingData.get(entry.getKey());
2341 if (existingPortGroup == null) {
2343 existingData.put(entry.getKey(), entry.getValue());
2344 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2348 existingPortGroup.getPorts().addAll(entry.getValue().getPorts());
2349 addPortGroupFlows(config, entry.getKey(), entry.getValue());
2351 existingPortGroup.getPorts().removeAll(entry.getValue().getPorts());
2352 removePortGroupFlows(config, entry.getKey(), entry.getValue());
2358 portGroupData.put(config, data);
2359 for (Node swid : data.keySet()) {
2360 addPortGroupFlows(config, swid, data.get(swid));
2367 public boolean addPortGroupConfig(String name, String regex, boolean restore) {
2368 PortGroupConfig config = portGroupConfigs.get(name);
2369 if (config != null) {
2373 if ((portGroupProvider == null) && !restore) {
2376 if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) {
2380 config = new PortGroupConfig(name, regex);
2381 portGroupConfigs.put(name, config);
2382 if (portGroupProvider != null) {
2383 portGroupProvider.createPortGroupConfig(config);
2389 public boolean delPortGroupConfig(String name) {
2390 PortGroupConfig config = portGroupConfigs.get(name);
2391 if (config == null) {
2395 if (portGroupProvider != null) {
2396 portGroupProvider.deletePortGroupConfig(config);
2398 portGroupConfigs.remove(name);
2402 private void usePortGroupConfig(String name) {
2403 PortGroupConfig config = portGroupConfigs.get(name);
2404 if (config == null) {
2407 if (portGroupProvider != null) {
2408 Map<Node, PortGroup> data = portGroupProvider.getPortGroupData(config);
2409 portGroupData.put(config, data);
2414 public Map<String, PortGroupConfig> getPortGroupConfigs() {
2415 return portGroupConfigs;
2418 public boolean isPortGroupSupported() {
2419 if (portGroupProvider == null) {
2425 public void setIContainer(IContainer s) {
2429 public void unsetIContainer(IContainer s) {
2430 if (this.container == s) {
2431 this.container = null;
2436 public PortGroupProvider getPortGroupProvider() {
2437 return portGroupProvider;
2440 public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) {
2441 this.portGroupProvider = null;
2444 public void setPortGroupProvider(PortGroupProvider portGroupProvider) {
2445 this.portGroupProvider = portGroupProvider;
2446 portGroupProvider.registerPortGroupChange(this);
2447 for (PortGroupConfig config : portGroupConfigs.values()) {
2448 portGroupProvider.createPortGroupConfig(config);
2452 public void setFrmAware(IForwardingRulesManagerAware obj) {
2453 this.frmAware.add(obj);
2456 public void unsetFrmAware(IForwardingRulesManagerAware obj) {
2457 this.frmAware.remove(obj);
2460 void setClusterContainerService(IClusterContainerServices s) {
2461 log.debug("Cluster Service set");
2462 this.clusterContainerService = s;
2465 void unsetClusterContainerService(IClusterContainerServices s) {
2466 if (this.clusterContainerService == s) {
2467 log.debug("Cluster Service removed!");
2468 this.clusterContainerService = null;
2472 private String getContainerName() {
2473 if (container == null) {
2474 return GlobalConstants.DEFAULT.toString();
2476 return container.getName();
2480 * Function called by the dependency manager when all the required
2481 * dependencies are satisfied
2485 frmFileName = GlobalConstants.STARTUPHOME.toString() + "frm_staticflows_" + this.getContainerName() + ".conf";
2486 portGroupFileName = GlobalConstants.STARTUPHOME.toString() + "portgroup_" + this.getContainerName() + ".conf";
2488 inContainerMode = false;
2490 if (portGroupProvider != null) {
2491 portGroupProvider.registerPortGroupChange(this);
2496 registerWithOSGIConsole();
2499 * If we are not the first cluster node to come up, do not initialize
2500 * the static flow entries ordinal
2502 if (staticFlowsOrdinal.size() == 0) {
2503 staticFlowsOrdinal.put(0, Integer.valueOf(0));
2506 pendingEvents = new LinkedBlockingQueue<FRMEvent>();
2508 // Initialize the event handler thread
2509 frmEventHandler = new Thread(new Runnable() {
2514 FRMEvent event = pendingEvents.take();
2515 if (event == null) {
2516 log.warn("Dequeued null event");
2519 if (event instanceof NodeUpdateEvent) {
2520 NodeUpdateEvent update = (NodeUpdateEvent) event;
2521 Node node = update.getNode();
2522 switch (update.getUpdateType()) {
2524 addStaticFlowsToSwitch(node);
2527 cleanDatabaseForNode(node);
2528 updateStaticFlowConfigsOnNodeDown(node);
2532 } else if (event instanceof ErrorReportedEvent) {
2533 ErrorReportedEvent errEvent = (ErrorReportedEvent) event;
2534 processErrorEvent(errEvent);
2535 } else if (event instanceof WorkOrderEvent) {
2537 * Take care of handling the remote Work request
2539 WorkOrderEvent work = (WorkOrderEvent) event;
2540 FlowEntryDistributionOrder fe = work.getFe();
2542 logsync.trace("Executing the workOrder {}", fe);
2543 Status gotStatus = null;
2544 FlowEntryInstall feiCurrent = fe.getEntry();
2545 FlowEntryInstall feiNew = workOrder.get(fe.getEntry());
2546 switch (fe.getUpType()) {
2549 * TODO: Not still sure how to handle the
2552 gotStatus = addEntriesInternal(feiCurrent, true);
2555 gotStatus = modifyEntryInternal(feiCurrent, feiNew, true);
2558 gotStatus = removeEntryInternal(feiCurrent, true);
2562 workOrder.remove(fe);
2564 "The workOrder has been executed and now the status is being returned {}", fe);
2566 workStatus.put(fe, gotStatus);
2568 log.warn("Not expected null WorkOrder", work);
2570 } else if (event instanceof WorkStatusCleanup) {
2572 * Take care of handling the remote Work request
2574 WorkStatusCleanup work = (WorkStatusCleanup) event;
2575 FlowEntryDistributionOrder fe = work.getFe();
2577 logsync.trace("The workStatus {} is being removed", fe);
2578 workStatus.remove(fe);
2580 log.warn("Not expected null WorkStatus", work);
2582 } else if (event instanceof ContainerFlowChangeEvent) {
2584 * Whether it is an addition or removal, we have to
2585 * recompute the merged flows entries taking into
2586 * account all the current container flows because
2587 * flow merging is not an injective function
2589 updateFlowsContainerFlow();
2591 log.warn("Dequeued unknown event {}", event.getClass()
2594 } catch (InterruptedException e) {
2595 // clear pending events
2596 pendingEvents.clear();
2600 }, "FRM EventHandler Collector");
2604 * Function called by the dependency manager when at least one dependency
2605 * become unsatisfied or when the component is shutting down because for
2606 * example bundle is being stopped.
2610 // Interrupt the thread
2611 frmEventHandler.interrupt();
2612 // Clear the pendingEvents queue
2613 pendingEvents.clear();
2615 workMonitor.clear();
2619 * Function called by dependency manager after "init ()" is called and after
2620 * the services provided by the class are registered in the service registry
2624 // Initialize graceful stop flag
2627 // Allocate the executor service
2628 this.executor = Executors.newSingleThreadExecutor();
2630 // Start event handler thread
2631 frmEventHandler.start();
2634 * Read startup and build database if we have not already gotten the
2635 * configurations synced from another node
2637 if (staticFlows.isEmpty()) {
2638 loadFlowConfiguration();
2643 * Function called by the dependency manager before the services exported by
2644 * the component are unregistered, this will be followed by a "destroy ()"
2649 uninstallAllFlowEntries(false);
2650 // Shutdown executor
2651 this.executor.shutdownNow();
2652 // Now walk all the workMonitor and wake up the one sleeping because
2653 // destruction is happening
2654 for (FlowEntryDistributionOrder fe : workMonitor.keySet()) {
2655 FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe);
2660 public void setFlowProgrammerService(IFlowProgrammerService service) {
2661 this.programmer = service;
2664 public void unsetFlowProgrammerService(IFlowProgrammerService service) {
2665 if (this.programmer == service) {
2666 this.programmer = null;
2670 public void setSwitchManager(ISwitchManager switchManager) {
2671 this.switchManager = switchManager;
2674 public void unsetSwitchManager(ISwitchManager switchManager) {
2675 if (this.switchManager == switchManager) {
2676 this.switchManager = null;
2681 public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) {
2682 if (!container.getName().equals(containerName)) {
2688 public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) {
2689 if (!container.getName().equals(containerName)) {
2692 log.trace("Container {}: Updating installed flows because of container flow change: {} {}",
2693 container.getName(), t, current);
2694 ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t);
2695 pendingEvents.offer(ev);
2699 public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) {
2700 if (!container.getName().equals(containerName)) {
2704 boolean updateStaticFlowCluster = false;
2708 log.trace("Port {} was removed from container: uninstalling interested flows", nc);
2709 updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc);
2712 log.trace("Port {} was added to container: reinstall interested flows", nc);
2713 updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc);
2721 if (updateStaticFlowCluster) {
2722 refreshClusterStaticFlowsStatus(nc.getNode());
2727 public void containerModeUpdated(UpdateType update) {
2728 // Only default container instance reacts on this event
2729 if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) {
2735 * Controller is moving to container mode. We are in the default
2736 * container context, we need to remove all our non-internal flows
2737 * to prevent any container isolation breakage. We also need to
2738 * preserve our flow so that they can be re-installed if we move
2739 * back to non container mode (no containers).
2741 this.inContainerMode = true;
2742 this.uninstallAllFlowEntries(true);
2745 this.inContainerMode = false;
2746 this.reinstallAllFlowEntries();
2751 // Update our configuration DB
2752 updateStaticFlowConfigsOnContainerModeChange(update);
2755 protected abstract class FRMEvent {
2759 private class NodeUpdateEvent extends FRMEvent {
2760 private final Node node;
2761 private final UpdateType update;
2763 public NodeUpdateEvent(UpdateType update, Node node) {
2764 this.update = update;
2768 public UpdateType getUpdateType() {
2772 public Node getNode() {
2777 private class ErrorReportedEvent extends FRMEvent {
2778 private final long rid;
2779 private final Node node;
2780 private final Object error;
2782 public ErrorReportedEvent(long rid, Node node, Object error) {
2788 public long getRequestId() {
2792 public Object getError() {
2796 public Node getNode() {
2801 private class WorkOrderEvent extends FRMEvent {
2802 private FlowEntryDistributionOrder fe;
2803 private FlowEntryInstall newEntry;
2809 WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) {
2811 this.newEntry = newEntry;
2817 public FlowEntryDistributionOrder getFe() {
2822 * @return the newEntry
2824 public FlowEntryInstall getNewEntry() {
2828 private class ContainerFlowChangeEvent extends FRMEvent {
2829 private final ContainerFlow previous;
2830 private final ContainerFlow current;
2831 private final UpdateType type;
2833 public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) {
2834 this.previous = previous;
2835 this.current = current;
2839 public ContainerFlow getPrevious() {
2840 return this.previous;
2843 public ContainerFlow getCurrent() {
2844 return this.current;
2847 public UpdateType getType() {
2853 private class WorkStatusCleanup extends FRMEvent {
2854 private FlowEntryDistributionOrder fe;
2859 WorkStatusCleanup(FlowEntryDistributionOrder fe) {
2866 public FlowEntryDistributionOrder getFe() {
2875 public String getHelp() {
2876 StringBuffer help = new StringBuffer();
2877 help.append("---FRM Matrix Application---\n");
2878 help.append("\t printMatrixData - Prints the Matrix Configs\n");
2879 help.append("\t addMatrixConfig <name> <regex>\n");
2880 help.append("\t delMatrixConfig <name>\n");
2881 help.append("\t useMatrixConfig <name>\n");
2882 return help.toString();
2885 public void _printMatrixData(CommandInterpreter ci) {
2886 ci.println("Configs : ");
2887 ci.println("---------");
2888 ci.println(portGroupConfigs);
2890 ci.println("Data : ");
2891 ci.println("------");
2892 ci.println(portGroupData);
2895 public void _addMatrixConfig(CommandInterpreter ci) {
2896 String name = ci.nextArgument();
2897 String regex = ci.nextArgument();
2898 addPortGroupConfig(name, regex, false);
2901 public void _delMatrixConfig(CommandInterpreter ci) {
2902 String name = ci.nextArgument();
2903 delPortGroupConfig(name);
2906 public void _useMatrixConfig(CommandInterpreter ci) {
2907 String name = ci.nextArgument();
2908 usePortGroupConfig(name);
2911 public void _arpPunt(CommandInterpreter ci) {
2912 String switchId = ci.nextArgument();
2913 long swid = HexEncode.stringToLong(switchId);
2914 Node node = NodeCreator.createOFNode(swid);
2915 installImplicitARPReplyPunt(node);
2918 public void _frmaddflow(CommandInterpreter ci) throws UnknownHostException {
2920 String nodeId = ci.nextArgument();
2921 if (nodeId == null) {
2922 ci.print("Node id not specified");
2926 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2927 } catch (NumberFormatException e) {
2928 ci.print("Node id not a number");
2931 ci.println(this.programmer.addFlow(node, getSampleFlow(node)));
2934 public void _frmremoveflow(CommandInterpreter ci) throws UnknownHostException {
2936 String nodeId = ci.nextArgument();
2937 if (nodeId == null) {
2938 ci.print("Node id not specified");
2942 node = NodeCreator.createOFNode(Long.valueOf(nodeId));
2943 } catch (NumberFormatException e) {
2944 ci.print("Node id not a number");
2947 ci.println(this.programmer.removeFlow(node, getSampleFlow(node)));
2950 private Flow getSampleFlow(Node node) throws UnknownHostException {
2951 NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node);
2952 NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node);
2953 byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc };
2954 byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f };
2955 InetAddress srcIP = InetAddress.getByName("172.28.30.50");
2956 InetAddress dstIP = InetAddress.getByName("171.71.9.52");
2957 InetAddress ipMask = InetAddress.getByName("255.255.255.0");
2958 InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
2959 short ethertype = EtherTypes.IPv4.shortValue();
2960 short vlan = (short) 27;
2963 byte proto = IPProtocols.TCP.byteValue();
2964 short src = (short) 55000;
2968 * Create a SAL Flow aFlow
2970 Match match = new Match();
2971 match.setField(MatchType.IN_PORT, port);
2972 match.setField(MatchType.DL_SRC, srcMac);
2973 match.setField(MatchType.DL_DST, dstMac);
2974 match.setField(MatchType.DL_TYPE, ethertype);
2975 match.setField(MatchType.DL_VLAN, vlan);
2976 match.setField(MatchType.DL_VLAN_PR, vlanPr);
2977 match.setField(MatchType.NW_SRC, srcIP, ipMask);
2978 match.setField(MatchType.NW_DST, dstIP, ipMask2);
2979 match.setField(MatchType.NW_TOS, tos);
2980 match.setField(MatchType.NW_PROTO, proto);
2981 match.setField(MatchType.TP_SRC, src);
2982 match.setField(MatchType.TP_DST, dst);
2984 List<Action> actions = new ArrayList<Action>();
2985 actions.add(new Output(oport));
2986 actions.add(new PopVlan());
2987 actions.add(new Flood());
2988 actions.add(new Controller());
2989 return new Flow(match, actions);
2993 public Status saveConfiguration() {
2994 return saveConfig();
2997 public void _frmNodeFlows(CommandInterpreter ci) {
2998 String nodeId = ci.nextArgument();
2999 Node node = Node.fromString(nodeId);
3001 ci.println("frmNodeFlows <node> [verbose]");
3004 boolean verbose = false;
3005 String verboseCheck = ci.nextArgument();
3006 if (verboseCheck != null) {
3007 verbose = verboseCheck.equals("true");
3010 if (!nodeFlows.containsKey(node)) {
3013 // Dump per node database
3014 for (FlowEntryInstall entry : nodeFlows.get(node)) {
3016 ci.println(node + " " + installedSwView.get(entry).getFlowName());
3018 ci.println(node + " " + installedSwView.get(entry).toString());
3023 public void _frmGroupFlows(CommandInterpreter ci) {
3024 String group = ci.nextArgument();
3025 if (group == null) {
3026 ci.println("frmGroupFlows <group> [verbose]");
3029 boolean verbose = false;
3030 String verboseCheck = ci.nextArgument();
3031 if (verboseCheck != null) {
3032 verbose = verboseCheck.equalsIgnoreCase("true");
3035 if (!groupFlows.containsKey(group)) {
3038 // Dump per node database
3039 ci.println("Group " + group + ":\n");
3040 for (FlowEntryInstall flowEntry : groupFlows.get(group)) {
3042 ci.println(flowEntry.getNode() + " " + flowEntry.getFlowName());
3044 ci.println(flowEntry.getNode() + " " + flowEntry.toString());
3050 public void flowRemoved(Node node, Flow flow) {
3051 log.trace("Received flow removed notification on {} for {}", node, flow);
3053 // For flow entry identification, only node, match and priority matter
3054 FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null);
3055 FlowEntryInstall installedEntry = this.installedSwView.get(test);
3056 if (installedEntry == null) {
3057 log.trace("Entry is not known to us");
3061 // Update Static flow status
3063 FlowConfig target = null;
3064 for (Map.Entry<Integer, FlowConfig> entry : staticFlows.entrySet()) {
3065 FlowConfig conf = entry.getValue();
3066 if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) {
3067 key = entry.getKey();
3072 if (target != null) {
3073 // Update Configuration database
3074 target.toggleInstallation();
3075 target.setStatus(SUCCESS);
3076 staticFlows.put(key, target);
3079 // Update software views
3080 this.updateLocalDatabase(installedEntry, false);
3084 public void flowErrorReported(Node node, long rid, Object err) {
3085 log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node });
3086 pendingEvents.offer(new ErrorReportedEvent(rid, node, err));
3089 private void processErrorEvent(ErrorReportedEvent event) {
3090 Node node = event.getNode();
3091 long rid = event.getRequestId();
3092 Object error = event.getError();
3093 String errorString = (error == null) ? "Not provided" : error.toString();
3095 * If this was for a flow install, remove the corresponding entry from
3096 * the software view. If it was a Looking for the rid going through the
3097 * software database. TODO: A more efficient rid <-> FlowEntryInstall
3098 * mapping will have to be added in future
3100 FlowEntryInstall target = null;
3101 List<FlowEntryInstall> flowEntryInstallList = nodeFlows.get(node);
3102 // flowEntryInstallList could be null.
3104 if(flowEntryInstallList != null) {
3105 for (FlowEntryInstall index : flowEntryInstallList) {
3106 FlowEntryInstall entry = installedSwView.get(index);
3108 if (entry.getRequestId() == rid) {
3115 if (target != null) {
3116 // This was a flow install, update database
3117 this.updateLocalDatabase(target, false);
3121 if (frmAware != null) {
3122 synchronized (frmAware) {
3123 for (IForwardingRulesManagerAware frma : frmAware) {
3125 frma.requestFailed(rid, errorString);
3126 } catch (Exception e) {
3127 log.warn("Failed to notify {}", frma);
3135 public Status solicitStatusResponse(Node node, boolean blocking) {
3136 Status rv = new Status(StatusCode.INTERNALERROR);
3138 if (this.programmer != null) {
3140 rv = programmer.syncSendBarrierMessage(node);
3142 rv = programmer.asyncSendBarrierMessage(node);
3149 public void unsetIConnectionManager(IConnectionManager s) {
3150 if (s == this.connectionManager) {
3151 this.connectionManager = null;
3155 public void setIConnectionManager(IConnectionManager s) {
3156 this.connectionManager = s;
3160 public void entryCreated(Object key, String cacheName, boolean originLocal) {
3167 public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) {
3170 * Local updates are of no interest
3174 if (cacheName.equals(WORKORDERCACHE)) {
3175 logsync.trace("Got a WorkOrderCacheUpdate for {}", key);
3177 * This is the case of one workOrder becoming available, so we need
3178 * to dispatch the work to the appropriate handler
3180 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3181 FlowEntryInstall fei = fe.getEntry();
3185 Node n = fei.getNode();
3186 if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) {
3187 logsync.trace("workOrder for fe {} processed locally", fe);
3188 // I'm the controller in charge for the request, queue it for
3190 pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value));
3192 } else if (cacheName.equals(WORKSTATUSCACHE)) {
3193 logsync.trace("Got a WorkStatusCacheUpdate for {}", key);
3195 * This is the case of one workOrder being completed and a status
3198 FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key;
3200 * Check if the order was initiated by this controller in that case
3201 * we need to actually look at the status returned
3203 if (fe.getRequestorController()
3204 .equals(clusterContainerService.getMyAddress())) {
3205 FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe);
3207 logsync.trace("workStatus response is for us {}", fe);
3208 // Signal we got the status
3209 fet.gotStatus(fe, workStatus.get(fe));
3210 pendingEvents.offer(new WorkStatusCleanup(fe));
3217 public void entryDeleted(Object key, String cacheName, boolean originLocal) {