2 * Copyright (c) 2015 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
8 package org.opendaylight.openflowplugin.impl.registry.flow;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import com.google.common.collect.BiMap;
13 import com.google.common.collect.HashBiMap;
14 import com.google.common.collect.Maps;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.romix.scala.collection.concurrent.TrieMap;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
28 import java.util.concurrent.ConcurrentMap;
29 import java.util.concurrent.atomic.AtomicInteger;
30 import java.util.function.Consumer;
31 import javax.annotation.concurrent.GuardedBy;
32 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
35 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
36 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
37 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
38 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * Created by Martin Bobak <mbobak@cisco.com> on 8.4.2015.
52 public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
53 private static final Logger LOG = LoggerFactory.getLogger(DeviceFlowRegistryImpl.class);
54 private static final String ALIEN_SYSTEM_FLOW_ID = "#UF$TABLE*";
55 private static final AtomicInteger UNACCOUNTED_FLOWS_COUNTER = new AtomicInteger(0);
58 private final BiMap<FlowRegistryKey, FlowDescriptor> flowRegistry = HashBiMap.create();
60 private final Collection<FlowRegistryKey> marks = new HashSet<>();
61 private final DataBroker dataBroker;
62 private final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier;
63 private final List<ListenableFuture<List<Optional<FlowCapableNode>>>> lastFillFutures = new ArrayList<>();
65 // Specifies what to do with flow read from datastore
66 private final Consumer<Flow> flowConsumer = flow -> {
67 // Create flow registry key from flow
68 final FlowRegistryKey key = FlowRegistryKeyFactory.create(flow);
70 // Now, we will update the registry, but we will also try to prevent duplicate entries
71 if (!flowRegistry.containsKey(key)) {
72 LOG.trace("Found flow with table ID : {} and flow ID : {}", flow.getTableId(), flow.getId().getValue());
73 final FlowDescriptor descriptor = FlowDescriptorFactory.create(flow.getTableId(), flow.getId());
74 store(key, descriptor);
79 public DeviceFlowRegistryImpl(final DataBroker dataBroker, final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier) {
80 this.dataBroker = dataBroker;
81 this.instanceIdentifier = instanceIdentifier;
85 public ListenableFuture<List<Optional<FlowCapableNode>>> fill() {
86 LOG.debug("Filling flow registry with flows for node: {}", instanceIdentifier);
88 // Prepare path for read transaction
89 // TODO: Read only Tables, and not entire FlowCapableNode (fix Yang model)
90 final InstanceIdentifier<FlowCapableNode> path = instanceIdentifier.augmentation(FlowCapableNode.class);
92 // First, try to fill registry with flows from DS/Configuration
93 CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> configFuture = fillFromDatastore(LogicalDatastoreType.CONFIGURATION, path);
95 // Now, try to fill registry with flows from DS/Operational
96 // in case of cluster fail over, when clients are not using DS/Configuration
97 // for adding flows, but only RPCs
98 CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> operationalFuture = fillFromDatastore(LogicalDatastoreType.OPERATIONAL, path);
100 // And at last, chain and return futures created above.
101 // Also, cache this future, so call to DeviceFlowRegistry.close() will be able
102 // to cancel this future immediately if it will be still in progress
103 final ListenableFuture<List<Optional<FlowCapableNode>>> lastFillFuture = Futures.allAsList(Arrays.asList(configFuture, operationalFuture));
104 lastFillFutures.add(lastFillFuture);
105 return lastFillFuture;
108 private CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> fillFromDatastore(final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<FlowCapableNode> path) {
109 // Create new read-only transaction
110 final ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();
112 // Bail out early if transaction is null
113 if (transaction == null) {
114 return Futures.immediateFailedCheckedFuture(
115 new ReadFailedException("Read transaction is null"));
118 // Prepare read operation from datastore for path
119 final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> future =
120 transaction.read(logicalDatastoreType, path);
122 // Bail out early if future is null
123 if (future == null) {
124 return Futures.immediateFailedCheckedFuture(
125 new ReadFailedException("Future from read transaction is null"));
128 Futures.addCallback(future, new FutureCallback<Optional<FlowCapableNode>>() {
130 public void onSuccess(Optional<FlowCapableNode> result) {
131 result.asSet().stream()
132 .flatMap(flowCapableNode -> flowCapableNode.getTable().stream())
133 .flatMap(table -> table.getFlow().stream())
134 .forEach(flowConsumer);
136 // After we are done with reading from datastore, close the transaction
141 public void onFailure(Throwable t) {
142 // Even when read operation failed, close the transaction
151 public FlowDescriptor retrieveIdForFlow(final FlowRegistryKey flowRegistryKey) {
152 LOG.trace("Retrieving flowDescriptor for flow hash: {}", flowRegistryKey.hashCode());
153 FlowDescriptor flowDescriptor = flowRegistry.get(flowRegistryKey);
154 // Get FlowDescriptor from flow registry
155 if(flowDescriptor == null){
156 for(Map.Entry<FlowRegistryKey, FlowDescriptor> fd : flowRegistry.entrySet()) {
157 if (fd.getKey().equals(flowRegistryKey)) {
158 flowDescriptor = fd.getValue();
163 return flowDescriptor;
168 public void store(final FlowRegistryKey flowRegistryKey, final FlowDescriptor flowDescriptor) {
169 LOG.trace("Storing flowDescriptor with table ID : {} and flow ID : {} for flow hash : {}",
170 flowDescriptor.getTableKey().getId(), flowDescriptor.getFlowId().getValue(), flowRegistryKey.hashCode());
172 flowRegistry.put(flowRegistryKey, flowDescriptor);
173 } catch (IllegalArgumentException ex) {
174 LOG.error("Flow with flowId {} already exists in table {}", flowDescriptor.getFlowId().getValue(),
175 flowDescriptor.getTableKey().getId());
176 final FlowId newFlowId = createAlienFlowId(flowDescriptor.getTableKey().getId());
177 final FlowDescriptor newFlowDescriptor = FlowDescriptorFactory.
178 create(flowDescriptor.getTableKey().getId(), newFlowId);
179 flowRegistry.put(flowRegistryKey, newFlowDescriptor);
184 public FlowId storeIfNecessary(final FlowRegistryKey flowRegistryKey) {
185 LOG.trace("Trying to retrieve flowDescriptor for flow hash: {}", flowRegistryKey.hashCode());
187 // First, try to get FlowDescriptor from flow registry
188 FlowDescriptor flowDescriptor = retrieveIdForFlow(flowRegistryKey);
190 // We was not able to retrieve FlowDescriptor, so we will at least try to generate it
191 if (flowDescriptor == null) {
192 final short tableId = flowRegistryKey.getTableId();
193 final FlowId alienFlowId = createAlienFlowId(tableId);
194 flowDescriptor = FlowDescriptorFactory.create(tableId, alienFlowId);
196 // Finally we got flowDescriptor, so now we will store it to registry,
197 // so next time we won't need to generate it again
198 store(flowRegistryKey, flowDescriptor);
201 return flowDescriptor.getFlowId();
205 public void markToBeremoved(final FlowRegistryKey flowRegistryKey) {
206 synchronized (marks) {
207 marks.add(flowRegistryKey);
210 LOG.trace("Flow hash {} was marked for removal.", flowRegistryKey.hashCode());
214 public void removeMarked() {
215 synchronized (marks) {
216 for (FlowRegistryKey flowRegistryKey : marks) {
217 LOG.trace("Removing flowDescriptor for flow hash : {}", flowRegistryKey.hashCode());
218 flowRegistry.remove(flowRegistryKey);
226 public Map<FlowRegistryKey, FlowDescriptor> getAllFlowDescriptors() {
227 return Collections.unmodifiableMap(flowRegistry);
231 public void close() {
232 final Iterator<ListenableFuture<List<Optional<FlowCapableNode>>>> iterator = lastFillFutures.iterator();
234 while(iterator.hasNext()) {
235 final ListenableFuture<List<Optional<FlowCapableNode>>> next = iterator.next();
236 boolean success = next.cancel(true);
237 LOG.trace("Cancelling filling flow registry with flows job {} with result: {}", next, success);
241 flowRegistry.clear();
246 static FlowId createAlienFlowId(final short tableId) {
247 final String alienId = ALIEN_SYSTEM_FLOW_ID + tableId + '-' + UNACCOUNTED_FLOWS_COUNTER.incrementAndGet();
248 return new FlowId(alienId);