blob: 5f71b571182dd45eebbc038aff3567f684c6e6f1 [file] [log] [blame]
yoonseonbd8a93d2016-12-07 15:51:21 -08001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.incubator.store.virtual.impl;
18
19import com.google.common.cache.Cache;
20import com.google.common.cache.CacheBuilder;
21import com.google.common.cache.RemovalListener;
22import com.google.common.cache.RemovalNotification;
23import com.google.common.collect.FluentIterable;
24import com.google.common.collect.Sets;
25import com.google.common.util.concurrent.SettableFuture;
26import org.apache.felix.scr.annotations.Activate;
27import org.apache.felix.scr.annotations.Component;
28import org.apache.felix.scr.annotations.Deactivate;
29import org.apache.felix.scr.annotations.Modified;
30import org.apache.felix.scr.annotations.Property;
31import org.apache.felix.scr.annotations.Reference;
32import org.apache.felix.scr.annotations.ReferenceCardinality;
33import org.apache.felix.scr.annotations.Service;
34import org.onlab.util.Tools;
35import org.onosproject.incubator.net.virtual.NetworkId;
36import org.onosproject.incubator.net.virtual.VirtualNetworkFlowRuleStore;
37import org.onosproject.net.DeviceId;
38import org.onosproject.net.flow.CompletedBatchOperation;
39import org.onosproject.net.flow.DefaultFlowEntry;
40import org.onosproject.net.flow.FlowEntry;
41import org.onosproject.net.flow.FlowId;
42import org.onosproject.net.flow.FlowRule;
43import org.onosproject.net.flow.FlowRuleBatchEntry;
44import org.onosproject.net.flow.FlowRuleBatchEvent;
45import org.onosproject.net.flow.FlowRuleBatchOperation;
46import org.onosproject.net.flow.FlowRuleBatchRequest;
47import org.onosproject.net.flow.FlowRuleEvent;
48import org.onosproject.net.flow.FlowRuleStoreDelegate;
49import org.onosproject.net.flow.StoredFlowEntry;
50import org.onosproject.net.flow.TableStatisticsEntry;
51import org.onosproject.store.service.StorageService;
52import org.osgi.service.component.ComponentContext;
53import org.slf4j.Logger;
54
55import java.util.ArrayList;
56import java.util.Collections;
57import java.util.Dictionary;
58import java.util.List;
59import java.util.concurrent.ConcurrentHashMap;
60import java.util.concurrent.ConcurrentMap;
61import java.util.concurrent.CopyOnWriteArrayList;
62import java.util.concurrent.ExecutionException;
63import java.util.concurrent.TimeUnit;
64import java.util.concurrent.TimeoutException;
65import java.util.concurrent.atomic.AtomicInteger;
66
67import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
68import static org.slf4j.LoggerFactory.getLogger;
69
yoonseondc3210d2017-01-25 16:03:10 -080070/**
yoonseon97b9b592017-01-31 14:35:06 -080071 * Implementation of the virtual network flow rule store to manage inventory of
72 * virtual flow rules using trivial in-memory implementation.
yoonseondc3210d2017-01-25 16:03:10 -080073 */
yoonseondc3210d2017-01-25 16:03:10 -080074//TODO: support distributed flowrule store for virtual networks
yoonseon97b9b592017-01-31 14:35:06 -080075
yoonseonbd8a93d2016-12-07 15:51:21 -080076@Component(immediate = true)
77@Service
78public class SimpleVirtualFlowRuleStore
79 extends AbstractVirtualStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
80 implements VirtualNetworkFlowRuleStore {
81
82 private final Logger log = getLogger(getClass());
83
84 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
85 protected StorageService storageService;
86
87 private final ConcurrentMap<NetworkId,
88 ConcurrentMap<DeviceId, ConcurrentMap<FlowId, List<StoredFlowEntry>>>>
89 flowEntries = new ConcurrentHashMap<>();
90
91
92 private final AtomicInteger localBatchIdGen = new AtomicInteger();
93
94 private static final int DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES = 5;
95 @Property(name = "pendingFutureTimeoutMinutes", intValue = DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES,
96 label = "Expiration time after an entry is created that it should be automatically removed")
97 private int pendingFutureTimeoutMinutes = DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES;
98
99 private Cache<Integer, SettableFuture<CompletedBatchOperation>> pendingFutures =
100 CacheBuilder.newBuilder()
101 .expireAfterWrite(pendingFutureTimeoutMinutes, TimeUnit.MINUTES)
102 .removalListener(new TimeoutFuture())
103 .build();
104
105 @Activate
106 public void activate() {
107 log.info("Started");
108 }
109
110 @Deactivate
111 public void deactivate() {
112 flowEntries.clear();
113 log.info("Stopped");
114 }
115
116 @Modified
117 public void modified(ComponentContext context) {
118
119 readComponentConfiguration(context);
120
121 // Reset Cache and copy all.
122 Cache<Integer, SettableFuture<CompletedBatchOperation>> prevFutures = pendingFutures;
123 pendingFutures = CacheBuilder.newBuilder()
124 .expireAfterWrite(pendingFutureTimeoutMinutes, TimeUnit.MINUTES)
125 .removalListener(new TimeoutFuture())
126 .build();
127
128 pendingFutures.putAll(prevFutures.asMap());
129 }
130
131 /**
132 * Extracts properties from the component configuration context.
133 *
134 * @param context the component context
135 */
136 private void readComponentConfiguration(ComponentContext context) {
137 Dictionary<?, ?> properties = context.getProperties();
138
139 Integer newPendingFutureTimeoutMinutes =
140 Tools.getIntegerProperty(properties, "pendingFutureTimeoutMinutes");
141 if (newPendingFutureTimeoutMinutes == null) {
142 pendingFutureTimeoutMinutes = DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES;
143 log.info("Pending future timeout is not configured, " +
144 "using current value of {}", pendingFutureTimeoutMinutes);
145 } else {
146 pendingFutureTimeoutMinutes = newPendingFutureTimeoutMinutes;
147 log.info("Configured. Pending future timeout is configured to {}",
148 pendingFutureTimeoutMinutes);
149 }
150 }
151
152 @Override
153 public int getFlowRuleCount(NetworkId networkId) {
154
155 int sum = 0;
156 for (ConcurrentMap<FlowId, List<StoredFlowEntry>> ft :
157 flowEntries.get(networkId).values()) {
158 for (List<StoredFlowEntry> fes : ft.values()) {
159 sum += fes.size();
160 }
161 }
162 return sum;
163 }
164
165 @Override
166 public FlowEntry getFlowEntry(NetworkId networkId, FlowRule rule) {
167 return getFlowEntryInternal(networkId, rule.deviceId(), rule);
168 }
169
170 @Override
171 public Iterable<FlowEntry> getFlowEntries(NetworkId networkId, DeviceId deviceId) {
172 return FluentIterable.from(getFlowTable(networkId, deviceId).values())
173 .transformAndConcat(Collections::unmodifiableList);
174 }
175
176 @Override
177 public void storeFlowRule(NetworkId networkId, FlowRule rule) {
178 storeFlowRuleInternal(networkId, rule);
179 }
180
181 @Override
182 public void storeBatch(NetworkId networkId, FlowRuleBatchOperation batchOperation) {
183 List<FlowRuleBatchEntry> toAdd = new ArrayList<>();
184 List<FlowRuleBatchEntry> toRemove = new ArrayList<>();
185
186 for (FlowRuleBatchEntry entry : batchOperation.getOperations()) {
187 final FlowRule flowRule = entry.target();
188 if (entry.operator().equals(FlowRuleBatchEntry.FlowRuleOperation.ADD)) {
189 if (!getFlowEntries(networkId, flowRule.deviceId(),
190 flowRule.id()).contains(flowRule)) {
191 storeFlowRule(networkId, flowRule);
192 toAdd.add(entry);
193 }
194 } else if (entry.operator().equals(FlowRuleBatchEntry.FlowRuleOperation.REMOVE)) {
195 if (getFlowEntries(networkId, flowRule.deviceId(), flowRule.id()).contains(flowRule)) {
196 deleteFlowRule(networkId, flowRule);
197 toRemove.add(entry);
198 }
199 } else {
200 throw new UnsupportedOperationException("Unsupported operation type");
201 }
202 }
203
204 if (toAdd.isEmpty() && toRemove.isEmpty()) {
205 notifyDelegate(networkId, FlowRuleBatchEvent.completed(
206 new FlowRuleBatchRequest(batchOperation.id(), Collections.emptySet()),
207 new CompletedBatchOperation(true, Collections.emptySet(),
208 batchOperation.deviceId())));
209 return;
210 }
211
212 SettableFuture<CompletedBatchOperation> r = SettableFuture.create();
213 final int batchId = localBatchIdGen.incrementAndGet();
214
215 pendingFutures.put(batchId, r);
216
217 toAdd.addAll(toRemove);
218 notifyDelegate(networkId, FlowRuleBatchEvent.requested(
219 new FlowRuleBatchRequest(batchId, Sets.newHashSet(toAdd)), batchOperation.deviceId()));
220
221 }
222
223 @Override
224 public void batchOperationComplete(NetworkId networkId, FlowRuleBatchEvent event) {
225 final Long batchId = event.subject().batchId();
226 SettableFuture<CompletedBatchOperation> future
227 = pendingFutures.getIfPresent(batchId);
228 if (future != null) {
229 future.set(event.result());
230 pendingFutures.invalidate(batchId);
231 }
232 notifyDelegate(networkId, event);
233 }
234
235 @Override
236 public void deleteFlowRule(NetworkId networkId, FlowRule rule) {
237 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
238
239 synchronized (entries) {
240 for (StoredFlowEntry entry : entries) {
241 if (entry.equals(rule)) {
242 synchronized (entry) {
243 entry.setState(FlowEntry.FlowEntryState.PENDING_REMOVE);
244 }
245 }
246 }
247 }
248 }
249
250 @Override
251 public FlowRuleEvent addOrUpdateFlowRule(NetworkId networkId, FlowEntry rule) {
252 // check if this new rule is an update to an existing entry
253 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
254 synchronized (entries) {
255 for (StoredFlowEntry stored : entries) {
256 if (stored.equals(rule)) {
257 synchronized (stored) {
258 //FIXME modification of "stored" flow entry outside of flow table
259 stored.setBytes(rule.bytes());
260 stored.setLife(rule.life());
261 stored.setPackets(rule.packets());
262 if (stored.state() == FlowEntry.FlowEntryState.PENDING_ADD) {
263 stored.setState(FlowEntry.FlowEntryState.ADDED);
264 // TODO: Do we need to change `rule` state?
265 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADDED, rule);
266 }
267 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
268 }
269 }
270 }
271 }
272
273 // should not reach here
274 // storeFlowRule was expected to be called
275 log.error("FlowRule was not found in store {} to update", rule);
276
277 return null;
278 }
279
280 @Override
281 public FlowRuleEvent removeFlowRule(NetworkId networkId, FlowEntry rule) {
282 // This is where one could mark a rule as removed and still keep it in the store.
283 final DeviceId did = rule.deviceId();
284
285 List<StoredFlowEntry> entries = getFlowEntries(networkId, did, rule.id());
286 synchronized (entries) {
287 if (entries.remove(rule)) {
288 return new FlowRuleEvent(RULE_REMOVED, rule);
289 }
290 }
291 return null;
292 }
293
294 @Override
295 public FlowRuleEvent pendingFlowRule(NetworkId networkId, FlowEntry rule) {
296 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
297 synchronized (entries) {
298 for (StoredFlowEntry entry : entries) {
299 if (entry.equals(rule) &&
300 entry.state() != FlowEntry.FlowEntryState.PENDING_ADD) {
301 synchronized (entry) {
302 entry.setState(FlowEntry.FlowEntryState.PENDING_ADD);
303 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
304 }
305 }
306 }
307 }
308 return null;
309 }
310
311 @Override
312 public void purgeFlowRule(NetworkId networkId, DeviceId deviceId) {
313 flowEntries.get(networkId).remove(deviceId);
314 }
315
316 @Override
317 public void purgeFlowRules(NetworkId networkId) {
318 flowEntries.get(networkId).clear();
319 }
320
321 @Override
322 public FlowRuleEvent
323 updateTableStatistics(NetworkId networkId, DeviceId deviceId, List<TableStatisticsEntry> tableStats) {
324 //TODO: Table operations are not supported yet
325 return null;
326 }
327
328 @Override
329 public Iterable<TableStatisticsEntry>
330 getTableStatistics(NetworkId networkId, DeviceId deviceId) {
331 //TODO: Table operations are not supported yet
332 return null;
333 }
334
335 /**
336 * Returns the flow table for specified device.
337 *
338 * @param networkId identifier of the virtual network
339 * @param deviceId identifier of the virtual device
340 * @return Map representing Flow Table of given device.
341 */
342 private ConcurrentMap<FlowId, List<StoredFlowEntry>>
343 getFlowTable(NetworkId networkId, DeviceId deviceId) {
344 return flowEntries
345 .computeIfAbsent(networkId, n -> new ConcurrentHashMap<>())
346 .computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
347 }
348
349 private List<StoredFlowEntry>
350 getFlowEntries(NetworkId networkId, DeviceId deviceId, FlowId flowId) {
351 final ConcurrentMap<FlowId, List<StoredFlowEntry>> flowTable
352 = getFlowTable(networkId, deviceId);
353
354 List<StoredFlowEntry> r = flowTable.get(flowId);
355 if (r == null) {
356 final List<StoredFlowEntry> concurrentlyAdded;
357 r = new CopyOnWriteArrayList<>();
358 concurrentlyAdded = flowTable.putIfAbsent(flowId, r);
359 if (concurrentlyAdded != null) {
360 return concurrentlyAdded;
361 }
362 }
363 return r;
364 }
365
366 private FlowEntry
367 getFlowEntryInternal(NetworkId networkId, DeviceId deviceId, FlowRule rule) {
368 List<StoredFlowEntry> fes = getFlowEntries(networkId, deviceId, rule.id());
369 for (StoredFlowEntry fe : fes) {
370 if (fe.equals(rule)) {
371 return fe;
372 }
373 }
374 return null;
375 }
376
377 private void storeFlowRuleInternal(NetworkId networkId, FlowRule rule) {
378 StoredFlowEntry f = new DefaultFlowEntry(rule);
379 final DeviceId did = f.deviceId();
380 final FlowId fid = f.id();
381 List<StoredFlowEntry> existing = getFlowEntries(networkId, did, fid);
382 synchronized (existing) {
383 for (StoredFlowEntry fe : existing) {
384 if (fe.equals(rule)) {
385 // was already there? ignore
386 return;
387 }
388 }
389 // new flow rule added
390 existing.add(f);
391 }
392 }
393
394 private static final class TimeoutFuture
395 implements RemovalListener<Integer, SettableFuture<CompletedBatchOperation>> {
396 @Override
397 public void onRemoval(RemovalNotification<Integer,
398 SettableFuture<CompletedBatchOperation>> notification) {
399 // wrapping in ExecutionException to support Future.get
400 if (notification.wasEvicted()) {
401 notification.getValue()
402 .setException(new ExecutionException("Timed out",
403 new TimeoutException()));
404 }
405 }
406 }
407}