blob: 1c9e44d46819d84d35e8aad418353b0c1399c019 [file] [log] [blame]
Madan Jampani04aeb452015-05-02 16:12:24 -07001package org.onosproject.store.core.impl;
2
3import static org.slf4j.LoggerFactory.getLogger;
4
5import java.util.Map;
6
7import org.apache.felix.scr.annotations.Activate;
8import org.apache.felix.scr.annotations.Component;
9import org.apache.felix.scr.annotations.Deactivate;
10import org.apache.felix.scr.annotations.Reference;
11import org.apache.felix.scr.annotations.ReferenceCardinality;
12import org.apache.felix.scr.annotations.Service;
13import org.onosproject.core.IdBlock;
14import org.onosproject.core.IdBlockStore;
15import org.onosproject.store.service.AtomicCounter;
Thomas Vachuskaf64c0772015-06-01 10:32:14 -070016import org.onosproject.store.service.StorageException;
Madan Jampani04aeb452015-05-02 16:12:24 -070017import org.onosproject.store.service.StorageService;
18import org.slf4j.Logger;
19
20import com.google.common.collect.Maps;
21
22/**
23 * Implementation of {@code IdBlockStore} using {@code AtomicCounter}.
24 */
25@Component(immediate = true, enabled = true)
26@Service
27public class ConsistentIdBlockStore implements IdBlockStore {
28
Thomas Vachuskaf64c0772015-06-01 10:32:14 -070029 private static final int MAX_TRIES = 3;
30
Madan Jampani04aeb452015-05-02 16:12:24 -070031 private final Logger log = getLogger(getClass());
32 private final Map<String, AtomicCounter> topicCounters = Maps.newConcurrentMap();
33
34 private static final long DEFAULT_BLOCK_SIZE = 0x100000L;
35
36 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
37 protected StorageService storageService;
38
39 @Activate
40 public void activate() {
41 log.info("Started");
42 }
43
44 @Deactivate
45 public void deactivate() {
46 log.info("Stopped");
47 }
48
49 @Override
50 public IdBlock getIdBlock(String topic) {
Thomas Vachuskaf64c0772015-06-01 10:32:14 -070051 AtomicCounter counter = topicCounters
52 .computeIfAbsent(topic,
53 name -> storageService.atomicCounterBuilder()
54 .withName(name)
55 .build());
56 Throwable exc = null;
57 for (int i = 0; i < MAX_TRIES; i++) {
58 try {
59 Long blockBase = counter.getAndAdd(DEFAULT_BLOCK_SIZE);
60 return new IdBlock(blockBase, DEFAULT_BLOCK_SIZE);
61 } catch (StorageException e) {
62 log.warn("Unable to allocate ID block due to {}; retrying...",
63 e.getMessage());
64 exc = e;
65 }
66 }
67 throw new IllegalStateException("Unable to allocate ID block", exc);
Madan Jampani04aeb452015-05-02 16:12:24 -070068 }
Thomas Vachuskaf64c0772015-06-01 10:32:14 -070069
Madan Jampani04aeb452015-05-02 16:12:24 -070070}