blob: ff13ac228152736484514f3876d1764342effee4 [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
70//TODO: support distributed flowrule store for virtual networks
71
72@Component(immediate = true)
73@Service
74public class SimpleVirtualFlowRuleStore
75 extends AbstractVirtualStore<FlowRuleBatchEvent, FlowRuleStoreDelegate>
76 implements VirtualNetworkFlowRuleStore {
77
78 private final Logger log = getLogger(getClass());
79
80 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
81 protected StorageService storageService;
82
83 private final ConcurrentMap<NetworkId,
84 ConcurrentMap<DeviceId, ConcurrentMap<FlowId, List<StoredFlowEntry>>>>
85 flowEntries = new ConcurrentHashMap<>();
86
87
88 private final AtomicInteger localBatchIdGen = new AtomicInteger();
89
90 private static final int DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES = 5;
91 @Property(name = "pendingFutureTimeoutMinutes", intValue = DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES,
92 label = "Expiration time after an entry is created that it should be automatically removed")
93 private int pendingFutureTimeoutMinutes = DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES;
94
95 private Cache<Integer, SettableFuture<CompletedBatchOperation>> pendingFutures =
96 CacheBuilder.newBuilder()
97 .expireAfterWrite(pendingFutureTimeoutMinutes, TimeUnit.MINUTES)
98 .removalListener(new TimeoutFuture())
99 .build();
100
101 @Activate
102 public void activate() {
103 log.info("Started");
104 }
105
106 @Deactivate
107 public void deactivate() {
108 flowEntries.clear();
109 log.info("Stopped");
110 }
111
112 @Modified
113 public void modified(ComponentContext context) {
114
115 readComponentConfiguration(context);
116
117 // Reset Cache and copy all.
118 Cache<Integer, SettableFuture<CompletedBatchOperation>> prevFutures = pendingFutures;
119 pendingFutures = CacheBuilder.newBuilder()
120 .expireAfterWrite(pendingFutureTimeoutMinutes, TimeUnit.MINUTES)
121 .removalListener(new TimeoutFuture())
122 .build();
123
124 pendingFutures.putAll(prevFutures.asMap());
125 }
126
127 /**
128 * Extracts properties from the component configuration context.
129 *
130 * @param context the component context
131 */
132 private void readComponentConfiguration(ComponentContext context) {
133 Dictionary<?, ?> properties = context.getProperties();
134
135 Integer newPendingFutureTimeoutMinutes =
136 Tools.getIntegerProperty(properties, "pendingFutureTimeoutMinutes");
137 if (newPendingFutureTimeoutMinutes == null) {
138 pendingFutureTimeoutMinutes = DEFAULT_PENDING_FUTURE_TIMEOUT_MINUTES;
139 log.info("Pending future timeout is not configured, " +
140 "using current value of {}", pendingFutureTimeoutMinutes);
141 } else {
142 pendingFutureTimeoutMinutes = newPendingFutureTimeoutMinutes;
143 log.info("Configured. Pending future timeout is configured to {}",
144 pendingFutureTimeoutMinutes);
145 }
146 }
147
148 @Override
149 public int getFlowRuleCount(NetworkId networkId) {
150
151 int sum = 0;
152 for (ConcurrentMap<FlowId, List<StoredFlowEntry>> ft :
153 flowEntries.get(networkId).values()) {
154 for (List<StoredFlowEntry> fes : ft.values()) {
155 sum += fes.size();
156 }
157 }
158 return sum;
159 }
160
161 @Override
162 public FlowEntry getFlowEntry(NetworkId networkId, FlowRule rule) {
163 return getFlowEntryInternal(networkId, rule.deviceId(), rule);
164 }
165
166 @Override
167 public Iterable<FlowEntry> getFlowEntries(NetworkId networkId, DeviceId deviceId) {
168 return FluentIterable.from(getFlowTable(networkId, deviceId).values())
169 .transformAndConcat(Collections::unmodifiableList);
170 }
171
172 @Override
173 public void storeFlowRule(NetworkId networkId, FlowRule rule) {
174 storeFlowRuleInternal(networkId, rule);
175 }
176
177 @Override
178 public void storeBatch(NetworkId networkId, FlowRuleBatchOperation batchOperation) {
179 List<FlowRuleBatchEntry> toAdd = new ArrayList<>();
180 List<FlowRuleBatchEntry> toRemove = new ArrayList<>();
181
182 for (FlowRuleBatchEntry entry : batchOperation.getOperations()) {
183 final FlowRule flowRule = entry.target();
184 if (entry.operator().equals(FlowRuleBatchEntry.FlowRuleOperation.ADD)) {
185 if (!getFlowEntries(networkId, flowRule.deviceId(),
186 flowRule.id()).contains(flowRule)) {
187 storeFlowRule(networkId, flowRule);
188 toAdd.add(entry);
189 }
190 } else if (entry.operator().equals(FlowRuleBatchEntry.FlowRuleOperation.REMOVE)) {
191 if (getFlowEntries(networkId, flowRule.deviceId(), flowRule.id()).contains(flowRule)) {
192 deleteFlowRule(networkId, flowRule);
193 toRemove.add(entry);
194 }
195 } else {
196 throw new UnsupportedOperationException("Unsupported operation type");
197 }
198 }
199
200 if (toAdd.isEmpty() && toRemove.isEmpty()) {
201 notifyDelegate(networkId, FlowRuleBatchEvent.completed(
202 new FlowRuleBatchRequest(batchOperation.id(), Collections.emptySet()),
203 new CompletedBatchOperation(true, Collections.emptySet(),
204 batchOperation.deviceId())));
205 return;
206 }
207
208 SettableFuture<CompletedBatchOperation> r = SettableFuture.create();
209 final int batchId = localBatchIdGen.incrementAndGet();
210
211 pendingFutures.put(batchId, r);
212
213 toAdd.addAll(toRemove);
214 notifyDelegate(networkId, FlowRuleBatchEvent.requested(
215 new FlowRuleBatchRequest(batchId, Sets.newHashSet(toAdd)), batchOperation.deviceId()));
216
217 }
218
219 @Override
220 public void batchOperationComplete(NetworkId networkId, FlowRuleBatchEvent event) {
221 final Long batchId = event.subject().batchId();
222 SettableFuture<CompletedBatchOperation> future
223 = pendingFutures.getIfPresent(batchId);
224 if (future != null) {
225 future.set(event.result());
226 pendingFutures.invalidate(batchId);
227 }
228 notifyDelegate(networkId, event);
229 }
230
231 @Override
232 public void deleteFlowRule(NetworkId networkId, FlowRule rule) {
233 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
234
235 synchronized (entries) {
236 for (StoredFlowEntry entry : entries) {
237 if (entry.equals(rule)) {
238 synchronized (entry) {
239 entry.setState(FlowEntry.FlowEntryState.PENDING_REMOVE);
240 }
241 }
242 }
243 }
244 }
245
246 @Override
247 public FlowRuleEvent addOrUpdateFlowRule(NetworkId networkId, FlowEntry rule) {
248 // check if this new rule is an update to an existing entry
249 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
250 synchronized (entries) {
251 for (StoredFlowEntry stored : entries) {
252 if (stored.equals(rule)) {
253 synchronized (stored) {
254 //FIXME modification of "stored" flow entry outside of flow table
255 stored.setBytes(rule.bytes());
256 stored.setLife(rule.life());
257 stored.setPackets(rule.packets());
258 if (stored.state() == FlowEntry.FlowEntryState.PENDING_ADD) {
259 stored.setState(FlowEntry.FlowEntryState.ADDED);
260 // TODO: Do we need to change `rule` state?
261 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADDED, rule);
262 }
263 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
264 }
265 }
266 }
267 }
268
269 // should not reach here
270 // storeFlowRule was expected to be called
271 log.error("FlowRule was not found in store {} to update", rule);
272
273 return null;
274 }
275
276 @Override
277 public FlowRuleEvent removeFlowRule(NetworkId networkId, FlowEntry rule) {
278 // This is where one could mark a rule as removed and still keep it in the store.
279 final DeviceId did = rule.deviceId();
280
281 List<StoredFlowEntry> entries = getFlowEntries(networkId, did, rule.id());
282 synchronized (entries) {
283 if (entries.remove(rule)) {
284 return new FlowRuleEvent(RULE_REMOVED, rule);
285 }
286 }
287 return null;
288 }
289
290 @Override
291 public FlowRuleEvent pendingFlowRule(NetworkId networkId, FlowEntry rule) {
292 List<StoredFlowEntry> entries = getFlowEntries(networkId, rule.deviceId(), rule.id());
293 synchronized (entries) {
294 for (StoredFlowEntry entry : entries) {
295 if (entry.equals(rule) &&
296 entry.state() != FlowEntry.FlowEntryState.PENDING_ADD) {
297 synchronized (entry) {
298 entry.setState(FlowEntry.FlowEntryState.PENDING_ADD);
299 return new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, rule);
300 }
301 }
302 }
303 }
304 return null;
305 }
306
307 @Override
308 public void purgeFlowRule(NetworkId networkId, DeviceId deviceId) {
309 flowEntries.get(networkId).remove(deviceId);
310 }
311
312 @Override
313 public void purgeFlowRules(NetworkId networkId) {
314 flowEntries.get(networkId).clear();
315 }
316
317 @Override
318 public FlowRuleEvent
319 updateTableStatistics(NetworkId networkId, DeviceId deviceId, List<TableStatisticsEntry> tableStats) {
320 //TODO: Table operations are not supported yet
321 return null;
322 }
323
324 @Override
325 public Iterable<TableStatisticsEntry>
326 getTableStatistics(NetworkId networkId, DeviceId deviceId) {
327 //TODO: Table operations are not supported yet
328 return null;
329 }
330
331 /**
332 * Returns the flow table for specified device.
333 *
334 * @param networkId identifier of the virtual network
335 * @param deviceId identifier of the virtual device
336 * @return Map representing Flow Table of given device.
337 */
338 private ConcurrentMap<FlowId, List<StoredFlowEntry>>
339 getFlowTable(NetworkId networkId, DeviceId deviceId) {
340 return flowEntries
341 .computeIfAbsent(networkId, n -> new ConcurrentHashMap<>())
342 .computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
343 }
344
345 private List<StoredFlowEntry>
346 getFlowEntries(NetworkId networkId, DeviceId deviceId, FlowId flowId) {
347 final ConcurrentMap<FlowId, List<StoredFlowEntry>> flowTable
348 = getFlowTable(networkId, deviceId);
349
350 List<StoredFlowEntry> r = flowTable.get(flowId);
351 if (r == null) {
352 final List<StoredFlowEntry> concurrentlyAdded;
353 r = new CopyOnWriteArrayList<>();
354 concurrentlyAdded = flowTable.putIfAbsent(flowId, r);
355 if (concurrentlyAdded != null) {
356 return concurrentlyAdded;
357 }
358 }
359 return r;
360 }
361
362 private FlowEntry
363 getFlowEntryInternal(NetworkId networkId, DeviceId deviceId, FlowRule rule) {
364 List<StoredFlowEntry> fes = getFlowEntries(networkId, deviceId, rule.id());
365 for (StoredFlowEntry fe : fes) {
366 if (fe.equals(rule)) {
367 return fe;
368 }
369 }
370 return null;
371 }
372
373 private void storeFlowRuleInternal(NetworkId networkId, FlowRule rule) {
374 StoredFlowEntry f = new DefaultFlowEntry(rule);
375 final DeviceId did = f.deviceId();
376 final FlowId fid = f.id();
377 List<StoredFlowEntry> existing = getFlowEntries(networkId, did, fid);
378 synchronized (existing) {
379 for (StoredFlowEntry fe : existing) {
380 if (fe.equals(rule)) {
381 // was already there? ignore
382 return;
383 }
384 }
385 // new flow rule added
386 existing.add(f);
387 }
388 }
389
390 private static final class TimeoutFuture
391 implements RemovalListener<Integer, SettableFuture<CompletedBatchOperation>> {
392 @Override
393 public void onRemoval(RemovalNotification<Integer,
394 SettableFuture<CompletedBatchOperation>> notification) {
395 // wrapping in ExecutionException to support Future.get
396 if (notification.wasEvicted()) {
397 notification.getValue()
398 .setException(new ExecutionException("Timed out",
399 new TimeoutException()));
400 }
401 }
402 }
403}