Merge "Bug 6380 lldp-speaker - DTCL instead of DTL"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / registry / flow / DeviceFlowRegistryImpl.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.openflowplugin.impl.registry.flow;
9
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;
27 import java.util.Map;
28 import java.util.Objects;
29 import java.util.concurrent.ConcurrentMap;
30 import java.util.concurrent.atomic.AtomicInteger;
31 import java.util.function.Consumer;
32 import javax.annotation.concurrent.GuardedBy;
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
35 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
36 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
37 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
38 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
39 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Created by Martin Bobak <mbobak@cisco.com> on 8.4.2015.
52  */
53 public class DeviceFlowRegistryImpl implements DeviceFlowRegistry {
54     private static final Logger LOG = LoggerFactory.getLogger(DeviceFlowRegistryImpl.class);
55     private static final String ALIEN_SYSTEM_FLOW_ID = "#UF$TABLE*";
56     private static final AtomicInteger UNACCOUNTED_FLOWS_COUNTER = new AtomicInteger(0);
57
58
59     private final BiMap<FlowRegistryKey, FlowDescriptor> flowRegistry = HashBiMap.create();
60     @GuardedBy("marks")
61     private final Collection<FlowRegistryKey> marks = new HashSet<>();
62     private final DataBroker dataBroker;
63     private final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier;
64     private final List<ListenableFuture<List<Optional<FlowCapableNode>>>> lastFillFutures = new ArrayList<>();
65
66     // Specifies what to do with flow read from datastore
67     private final Consumer<Flow> flowConsumer = flow -> {
68         // Create flow registry key from flow
69         final FlowRegistryKey key = FlowRegistryKeyFactory.create(flow);
70
71         // Now, we will update the registry, but we will also try to prevent duplicate entries
72         if (!flowRegistry.containsKey(key)) {
73             LOG.trace("Found flow with table ID : {} and flow ID : {}", flow.getTableId(), flow.getId().getValue());
74             final FlowDescriptor descriptor = FlowDescriptorFactory.create(flow.getTableId(), flow.getId());
75             store(key, descriptor);
76         }
77     };
78
79
80     public DeviceFlowRegistryImpl(final DataBroker dataBroker, final KeyedInstanceIdentifier<Node, NodeKey> instanceIdentifier) {
81         this.dataBroker = dataBroker;
82         this.instanceIdentifier = instanceIdentifier;
83     }
84
85     @Override
86     public ListenableFuture<List<Optional<FlowCapableNode>>> fill() {
87         LOG.debug("Filling flow registry with flows for node: {}", instanceIdentifier.getKey().getId().getValue());
88
89         // Prepare path for read transaction
90         // TODO: Read only Tables, and not entire FlowCapableNode (fix Yang model)
91         final InstanceIdentifier<FlowCapableNode> path = instanceIdentifier.augmentation(FlowCapableNode.class);
92
93         // First, try to fill registry with flows from DS/Configuration
94         CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> configFuture = fillFromDatastore(LogicalDatastoreType.CONFIGURATION, path);
95
96         // Now, try to fill registry with flows from DS/Operational
97         // in case of cluster fail over, when clients are not using DS/Configuration
98         // for adding flows, but only RPCs
99         CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> operationalFuture = fillFromDatastore(LogicalDatastoreType.OPERATIONAL, path);
100
101         // And at last, chain and return futures created above.
102         // Also, cache this future, so call to DeviceFlowRegistry.close() will be able
103         // to cancel this future immediately if it will be still in progress
104         final ListenableFuture<List<Optional<FlowCapableNode>>> lastFillFuture = Futures.allAsList(Arrays.asList(configFuture, operationalFuture));
105         lastFillFutures.add(lastFillFuture);
106         return lastFillFuture;
107     }
108
109     private CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> fillFromDatastore(final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<FlowCapableNode> path) {
110         // Create new read-only transaction
111         final ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();
112
113         // Bail out early if transaction is null
114         if (transaction == null) {
115             return Futures.immediateFailedCheckedFuture(
116                     new ReadFailedException("Read transaction is null"));
117         }
118
119         // Prepare read operation from datastore for path
120         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> future =
121                 transaction.read(logicalDatastoreType, path);
122
123         // Bail out early if future is null
124         if (future == null) {
125             return Futures.immediateFailedCheckedFuture(
126                     new ReadFailedException("Future from read transaction is null"));
127         }
128
129         Futures.addCallback(future, new FutureCallback<Optional<FlowCapableNode>>() {
130             @Override
131             public void onSuccess(Optional<FlowCapableNode> result) {
132                 result.asSet().stream()
133                         .filter(Objects::nonNull)
134                         .filter(flowCapableNode -> Objects.nonNull(flowCapableNode.getTable()))
135                         .flatMap(flowCapableNode -> flowCapableNode.getTable().stream())
136                         .filter(Objects::nonNull)
137                         .filter(table -> Objects.nonNull(table.getFlow()))
138                         .flatMap(table -> table.getFlow().stream())
139                         .filter(Objects::nonNull)
140                         .filter(flow -> Objects.nonNull(flow.getId()))
141                         .forEach(flowConsumer);
142
143                 // After we are done with reading from datastore, close the transaction
144                 transaction.close();
145             }
146
147             @Override
148             public void onFailure(Throwable t) {
149                 // Even when read operation failed, close the transaction
150                 transaction.close();
151             }
152         });
153
154         return future;
155     }
156
157     @Override
158     public FlowDescriptor retrieveIdForFlow(final FlowRegistryKey flowRegistryKey) {
159         LOG.trace("Retrieving flow descriptor for flow hash : {}", flowRegistryKey.hashCode());
160         FlowDescriptor flowDescriptor = flowRegistry.get(flowRegistryKey);
161         // Get FlowDescriptor from flow registry
162         if(flowDescriptor == null){
163             if (LOG.isTraceEnabled()) {
164                 LOG.trace("Failed to retrieve flow descriptor for flow hash : {}, trying with custom equals method", flowRegistryKey.hashCode());
165             }
166             for(Map.Entry<FlowRegistryKey, FlowDescriptor> fd : flowRegistry.entrySet()) {
167                 if (fd.getKey().equals(flowRegistryKey)) {
168                     flowDescriptor = fd.getValue();
169                     break;
170                 }
171             }
172         }
173         return flowDescriptor;
174     }
175
176
177     @Override
178     public void store(final FlowRegistryKey flowRegistryKey, final FlowDescriptor flowDescriptor) {
179         LOG.trace("Storing flowDescriptor with table ID : {} and flow ID : {} for flow hash : {}",
180                 flowDescriptor.getTableKey().getId(), flowDescriptor.getFlowId().getValue(), flowRegistryKey.hashCode());
181         try {
182             flowRegistry.put(flowRegistryKey, flowDescriptor);
183         } catch (IllegalArgumentException ex) {
184             LOG.error("Flow with flowId {} already exists in table {}", flowDescriptor.getFlowId().getValue(),
185                     flowDescriptor.getTableKey().getId());
186             final FlowId newFlowId = createAlienFlowId(flowDescriptor.getTableKey().getId());
187             final FlowDescriptor newFlowDescriptor = FlowDescriptorFactory.
188                     create(flowDescriptor.getTableKey().getId(), newFlowId);
189             flowRegistry.put(flowRegistryKey, newFlowDescriptor);
190         }
191     }
192
193     @Override
194     public FlowId storeIfNecessary(final FlowRegistryKey flowRegistryKey) {
195         LOG.trace("Trying to retrieve flow ID for flow hash : {}", flowRegistryKey.hashCode());
196
197         // First, try to get FlowDescriptor from flow registry
198         FlowDescriptor flowDescriptor = retrieveIdForFlow(flowRegistryKey);
199
200         // We was not able to retrieve FlowDescriptor, so we will at least try to generate it
201         if (flowDescriptor == null) {
202             LOG.trace("Flow descriptor for flow hash : {} not found, generating alien flow ID", flowRegistryKey.hashCode());
203             final short tableId = flowRegistryKey.getTableId();
204             final FlowId alienFlowId = createAlienFlowId(tableId);
205             flowDescriptor = FlowDescriptorFactory.create(tableId, alienFlowId);
206
207             // Finally we got flowDescriptor, so now we will store it to registry,
208             // so next time we won't need to generate it again
209             store(flowRegistryKey, flowDescriptor);
210         }
211
212         return flowDescriptor.getFlowId();
213     }
214
215     @Override
216     public void markToBeremoved(final FlowRegistryKey flowRegistryKey) {
217         synchronized (marks) {
218             marks.add(flowRegistryKey);
219         }
220
221         LOG.trace("Flow hash {} was marked for removal.", flowRegistryKey.hashCode());
222     }
223
224     @Override
225     public void removeMarked() {
226         synchronized (marks) {
227             for (FlowRegistryKey flowRegistryKey : marks) {
228                 LOG.trace("Removing flow descriptor for flow hash : {}", flowRegistryKey.hashCode());
229                 flowRegistry.remove(flowRegistryKey);
230             }
231
232             marks.clear();
233         }
234     }
235
236     @Override
237     public Map<FlowRegistryKey, FlowDescriptor> getAllFlowDescriptors() {
238         return Collections.unmodifiableMap(flowRegistry);
239     }
240
241     @Override
242     public void close() {
243         final Iterator<ListenableFuture<List<Optional<FlowCapableNode>>>> iterator = lastFillFutures.iterator();
244
245         while(iterator.hasNext()) {
246             final ListenableFuture<List<Optional<FlowCapableNode>>> next = iterator.next();
247             boolean success = next.cancel(true);
248             LOG.trace("Cancelling filling flow registry with flows job {} with result: {}", next, success);
249             iterator.remove();
250         }
251
252         flowRegistry.clear();
253         marks.clear();
254     }
255
256     @VisibleForTesting
257     static FlowId createAlienFlowId(final short tableId) {
258         final String alienId = ALIEN_SYSTEM_FLOW_ID + tableId + '-' + UNACCOUNTED_FLOWS_COUNTER.incrementAndGet();
259         return new FlowId(alienId);
260     }
261 }