blob: 4b22d9ed83aea618701d595f19c5f26232d58833 [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) {
yoonseonbd8a93d2016-12-07 15:51:21 -0800154 int sum = 0;
yoonseon86bebed2017-02-03 15:23:57 -0800155
156 if (flowEntries.get(networkId) == null) {
157 return 0;
158 }
159
yoonseonbd8a93d2016-12-07 15:51:21 -0800160 for (ConcurrentMap<FlowId, List<StoredFlowEntry>> ft :
161 flowEntries.get(networkId).values()) {
162 for (List<StoredFlowEntry> fes : ft.values()) {
163 sum += fes.size();
164 }
165 }
166 return sum;
167 }
168
169 @Override
170 public FlowEntry getFlowEntry(NetworkId networkId, FlowRule rule) {
171 return getFlowEntryInternal(networkId, rule.deviceId(), rule);
172 }
173
174 @Override
175 public Iterable<FlowEntry> getFlowEntries(NetworkId networkId, DeviceId deviceId) {
176 return FluentIterable.from(getFlowTable(networkId, deviceId).values())
177 .transformAndConcat(Collections::unmodifiableList);
178 }
179
180 @Override
181 public void storeFlowRule(NetworkId networkId, FlowRule rule) {
182 storeFlowRuleInternal(networkId, rule);
183 }
184
185 @Override
186 public void storeBatch(NetworkId networkId, FlowRuleBatchOperation batchOperation) {
187 List<FlowRuleBatchEntry> toAdd = new ArrayList<>();
188 List<FlowRuleBatchEntry> toRemove = new ArrayList<>();
189
190 for (FlowRuleBatchEntry entry : batchOperation.getOperations()) {
191 final FlowRule flowRule = entry.target();
192 if (entry.operator().equals(FlowRuleBatchEntry.FlowRuleOperation.ADD)) {
193 if (!getFlowEntries(networkId, flowRule.deviceId(),
194 flowRule.id()).contains(flowRule)) {
195 storeFlowRule(networkId, flowRule);
196 toAdd.add(entry);
197 }
198 } else if (entry.operator().equals(FlowRuleBatchEntry.FlowRuleOperation.REMOVE)) {
199 if (getFlowEntries(networkId, flowRule.deviceId(), flowRule.id()).contains(flowRule)) {
200 deleteFlowRule(networkId, flowRule);
201 toRemove.add(entry);
202 }
203 } else {
204 throw new UnsupportedOperationException("Unsupported operation type");
205 }
206 }
207
208 if (toAdd.isEmpty() && toRemove.isEmpty()) {
209 notifyDelegate(networkId, FlowRuleBatchEvent.completed(
210 new FlowRuleBatchRequest(batchOperation.id(), Collections.emptySet()),
211 new CompletedBatchOperation(true, Collections.emptySet(),
212 batchOperation.deviceId())));
213 return;
214 }
215
216 SettableFuture<CompletedBatchOperation> r = SettableFuture.create();
Yoonseon Han997c8422017-04-24 16:20:03 -0700217 final int futureId = localBatchIdGen.incrementAndGet();
yoonseonbd8a93d2016-12-07 15:51:21 -0800218
Yoonseon Han997c8422017-04-24 16:20:03 -0700219 pendingFutures.put(futureId, r);
yoonseonbd8a93d2016-12-07 15:51:21 -0800220
221 toAdd.addAll(toRemove);
222 notifyDelegate(networkId, FlowRuleBatchEvent.requested(
Yoonseon Han997c8422017-04-24 16:20:03 -0700223 new FlowRuleBatchRequest(batchOperation.id(),
224 Sets.newHashSet(toAdd)), batchOperation.deviceId()));
yoonseonbd8a93d2016-12-07 15:51:21 -0800225
226 }
227
228 @Override
229 public void batchOperationComplete(NetworkId networkId, FlowRuleBatchEvent event) {
230 final Long batchId = event.subject().batchId();
231 SettableFuture<CompletedBatchOperation> future
232 = pendingFutures.getIfPresent(batchId);
233 if (future != null) {
234 future.set(event.result());
235 pendingFutures.invalidate(batchId);
236 }
237 notifyDelegate(networkId, event);
238 }
239
240 @Override
241 public void deleteFlowRule(NetworkId networkId, FlowRule rule) {
242 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
243
244 synchronized (entries) {
245 for (StoredFlowEntry entry : entries) {
246 if (entry.equals(rule)) {
247 synchronized (entry) {
248 entry.setState(FlowEntry.FlowEntryState.PENDING_REMOVE);
249 }
250 }
251 }
252 }
253 }
254
255 @Override
256 public FlowRuleEvent addOrUpdateFlowRule(NetworkId networkId, FlowEntry rule) {
257 // check if this new rule is an update to an existing entry
258 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
259 synchronized (entries) {
260 for (StoredFlowEntry stored : entries) {
261 if (stored.equals(rule)) {
262 synchronized (stored) {
263 //FIXME modification of "stored" flow entry outside of flow table
264 stored.setBytes(rule.bytes());
265 stored.setLife(rule.life());
266 stored.setPackets(rule.packets());
267 if (stored.state() == FlowEntry.FlowEntryState.PENDING_ADD) {
268 stored.setState(FlowEntry.FlowEntryState.ADDED);
269 // TODO: Do we need to change `rule` state?
270 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADDED, rule);
271 }
272 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
273 }
274 }
275 }
276 }
277
278 // should not reach here
279 // storeFlowRule was expected to be called
280 log.error("FlowRule was not found in store {} to update", rule);
281
282 return null;
283 }
284
285 @Override
286 public FlowRuleEvent removeFlowRule(NetworkId networkId, FlowEntry rule) {
287 // This is where one could mark a rule as removed and still keep it in the store.
288 final DeviceId did = rule.deviceId();
289
290 List<StoredFlowEntry> entries = getFlowEntries(networkId, did, rule.id());
291 synchronized (entries) {
292 if (entries.remove(rule)) {
293 return new FlowRuleEvent(RULE_REMOVED, rule);
294 }
295 }
296 return null;
297 }
298
299 @Override
300 public FlowRuleEvent pendingFlowRule(NetworkId networkId, FlowEntry rule) {
301 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
302 synchronized (entries) {
303 for (StoredFlowEntry entry : entries) {
304 if (entry.equals(rule) &&
305 entry.state() != FlowEntry.FlowEntryState.PENDING_ADD) {
306 synchronized (entry) {
307 entry.setState(FlowEntry.FlowEntryState.PENDING_ADD);
308 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
309 }
310 }
311 }
312 }
313 return null;
314 }
315
316 @Override
317 public void purgeFlowRule(NetworkId networkId, DeviceId deviceId) {
318 flowEntries.get(networkId).remove(deviceId);
319 }
320
321 @Override
322 public void purgeFlowRules(NetworkId networkId) {
323 flowEntries.get(networkId).clear();
324 }
325
326 @Override
327 public FlowRuleEvent
328 updateTableStatistics(NetworkId networkId, DeviceId deviceId, List<TableStatisticsEntry> tableStats) {
329 //TODO: Table operations are not supported yet
330 return null;
331 }
332
333 @Override
334 public Iterable<TableStatisticsEntry>
335 getTableStatistics(NetworkId networkId, DeviceId deviceId) {
336 //TODO: Table operations are not supported yet
337 return null;
338 }
339
340 /**
341 * Returns the flow table for specified device.
342 *
343 * @param networkId identifier of the virtual network
344 * @param deviceId identifier of the virtual device
345 * @return Map representing Flow Table of given device.
346 */
347 private ConcurrentMap<FlowId, List<StoredFlowEntry>>
348 getFlowTable(NetworkId networkId, DeviceId deviceId) {
349 return flowEntries
350 .computeIfAbsent(networkId, n -> new ConcurrentHashMap<>())
351 .computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
352 }
353
354 private List<StoredFlowEntry>
355 getFlowEntries(NetworkId networkId, DeviceId deviceId, FlowId flowId) {
356 final ConcurrentMap<FlowId, List<StoredFlowEntry>> flowTable
357 = getFlowTable(networkId, deviceId);
358
359 List<StoredFlowEntry> r = flowTable.get(flowId);
360 if (r == null) {
361 final List<StoredFlowEntry> concurrentlyAdded;
362 r = new CopyOnWriteArrayList<>();
363 concurrentlyAdded = flowTable.putIfAbsent(flowId, r);
364 if (concurrentlyAdded != null) {
365 return concurrentlyAdded;
366 }
367 }
368 return r;
369 }
370
371 private FlowEntry
372 getFlowEntryInternal(NetworkId networkId, DeviceId deviceId, FlowRule rule) {
373 List<StoredFlowEntry> fes = getFlowEntries(networkId, deviceId, rule.id());
374 for (StoredFlowEntry fe : fes) {
375 if (fe.equals(rule)) {
376 return fe;
377 }
378 }
379 return null;
380 }
381
382 private void storeFlowRuleInternal(NetworkId networkId, FlowRule rule) {
383 StoredFlowEntry f = new DefaultFlowEntry(rule);
384 final DeviceId did = f.deviceId();
385 final FlowId fid = f.id();
386 List<StoredFlowEntry> existing = getFlowEntries(networkId, did, fid);
387 synchronized (existing) {
388 for (StoredFlowEntry fe : existing) {
389 if (fe.equals(rule)) {
390 // was already there? ignore
391 return;
392 }
393 }
394 // new flow rule added
395 existing.add(f);
396 }
397 }
398
399 private static final class TimeoutFuture
400 implements RemovalListener<Integer, SettableFuture<CompletedBatchOperation>> {
401 @Override
402 public void onRemoval(RemovalNotification<Integer,
403 SettableFuture<CompletedBatchOperation>> notification) {
404 // wrapping in ExecutionException to support Future.get
405 if (notification.wasEvicted()) {
406 notification.getValue()
407 .setException(new ExecutionException("Timed out",
408 new TimeoutException()));
409 }
410 }
411 }
412}