blob: 223cfec08ab37dd5b89f7fdf24c8acfac1182bc6 [file] [log] [blame]
Jordan Halterman948d6592017-04-20 17:18:24 -07001/*
2 * Copyright 2017-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 */
16package org.onosproject.store.primitives.impl;
17
18import java.util.Collection;
19import java.util.Collections;
20import java.util.HashMap;
21import java.util.List;
22import java.util.Map;
23import java.util.concurrent.CompletableFuture;
24import java.util.concurrent.ExecutionException;
25
26import com.google.common.cache.Cache;
27import com.google.common.cache.CacheBuilder;
28import com.google.common.collect.Lists;
29import com.google.common.collect.Maps;
30import com.google.common.hash.Hashing;
31import com.google.common.util.concurrent.Futures;
32import org.onosproject.cluster.PartitionId;
33import org.onosproject.store.primitives.MapUpdate;
34import org.onosproject.store.primitives.PartitionService;
35import org.onosproject.store.primitives.TransactionId;
36import org.onosproject.store.serializers.KryoNamespaces;
37import org.onosproject.store.service.AsyncConsistentMap;
38import org.onosproject.store.service.Serializer;
39import org.onosproject.store.service.StorageService;
40import org.onosproject.store.service.TransactionException;
41
42/**
43 * Transaction manager for managing state shared across multiple transactions.
44 */
45public class TransactionManager {
46 private static final int DEFAULT_CACHE_SIZE = 100;
47
48 private final PartitionService partitionService;
49 private final List<PartitionId> sortedPartitions;
50 private final AsyncConsistentMap<TransactionId, Transaction.State> transactions;
51 private final int cacheSize;
Jordan Halterman9fa43032017-07-28 11:00:26 -070052 private final Map<PartitionId, Cache<String, CachedMap>> partitionCache = Maps.newConcurrentMap();
Jordan Halterman948d6592017-04-20 17:18:24 -070053
54 public TransactionManager(StorageService storageService, PartitionService partitionService) {
55 this(storageService, partitionService, DEFAULT_CACHE_SIZE);
56 }
57
58 public TransactionManager(StorageService storageService, PartitionService partitionService, int cacheSize) {
59 this.partitionService = partitionService;
60 this.cacheSize = cacheSize;
61 this.transactions = storageService.<TransactionId, Transaction.State>consistentMapBuilder()
62 .withName("onos-transactions")
63 .withSerializer(Serializer.using(KryoNamespaces.API,
64 Transaction.class,
65 Transaction.State.class))
66 .buildAsyncMap();
67 this.sortedPartitions = Lists.newArrayList(partitionService.getAllPartitionIds());
68 Collections.sort(sortedPartitions);
69 }
70
71 /**
72 * Returns the collection of currently pending transactions.
73 *
74 * @return a collection of currently pending transactions
75 */
76 public Collection<TransactionId> getPendingTransactions() {
77 return Futures.getUnchecked(transactions.keySet());
78 }
79
80 /**
81 * Returns a partitioned transactional map for use within a transaction context.
82 * <p>
83 * The transaction coordinator will return a map that takes advantage of caching that's shared across transaction
84 * contexts.
85 *
86 * @param name the map name
87 * @param serializer the map serializer
88 * @param transactionCoordinator the transaction coordinator for which the map is being created
89 * @param <K> key type
90 * @param <V> value type
91 * @return a partitioned transactional map
92 */
93 <K, V> PartitionedTransactionalMap<K, V> getTransactionalMap(
94 String name,
95 Serializer serializer,
96 TransactionCoordinator transactionCoordinator) {
97 Map<PartitionId, TransactionalMapParticipant<K, V>> partitions = new HashMap<>();
98 for (PartitionId partitionId : partitionService.getAllPartitionIds()) {
99 partitions.put(partitionId, getTransactionalMapPartition(
100 name, partitionId, serializer, transactionCoordinator));
101 }
102
103 Hasher<K> hasher = key -> {
104 int hashCode = Hashing.sha256().hashBytes(serializer.encode(key)).asInt();
105 return sortedPartitions.get(Math.abs(hashCode) % sortedPartitions.size());
106 };
107 return new PartitionedTransactionalMap<>(partitions, hasher);
108 }
109
110 @SuppressWarnings("unchecked")
111 private <K, V> TransactionalMapParticipant<K, V> getTransactionalMapPartition(
112 String mapName,
113 PartitionId partitionId,
114 Serializer serializer,
115 TransactionCoordinator transactionCoordinator) {
Jordan Halterman9fa43032017-07-28 11:00:26 -0700116 Cache<String, CachedMap> mapCache = partitionCache.computeIfAbsent(partitionId, p ->
Jordan Halterman948d6592017-04-20 17:18:24 -0700117 CacheBuilder.newBuilder().maximumSize(cacheSize / partitionService.getNumberOfPartitions()).build());
118 try {
Jordan Halterman9fa43032017-07-28 11:00:26 -0700119 CachedMap<K, V> cachedMap = mapCache.get(mapName,
120 () -> new CachedMap<>(partitionService.getDistributedPrimitiveCreator(partitionId)
121 .newAsyncConsistentMap(mapName, serializer)));
Jordan Halterman948d6592017-04-20 17:18:24 -0700122
123 Transaction<MapUpdate<K, V>> transaction = new Transaction<>(
124 transactionCoordinator.transactionId,
Jordan Halterman9fa43032017-07-28 11:00:26 -0700125 cachedMap.baseMap);
126 return new DefaultTransactionalMapParticipant<>(cachedMap.cachedMap.asConsistentMap(), transaction);
Jordan Halterman948d6592017-04-20 17:18:24 -0700127 } catch (ExecutionException e) {
128 throw new TransactionException(e);
129 }
130 }
131
132 /**
133 * Updates the state of a transaction in the transaction registry.
134 *
135 * @param transactionId the transaction identifier
136 * @param state the state of the transaction
137 * @return a completable future to be completed once the transaction state has been updated in the registry
138 */
139 CompletableFuture<Void> updateState(TransactionId transactionId, Transaction.State state) {
140 return transactions.put(transactionId, state).thenApply(v -> null);
141 }
142
143 /**
144 * Removes the given transaction from the transaction registry.
145 *
146 * @param transactionId the transaction identifier
147 * @return a completable future to be completed once the transaction state has been removed from the registry
148 */
149 CompletableFuture<Void> remove(TransactionId transactionId) {
150 return transactions.remove(transactionId).thenApply(v -> null);
151 }
Jordan Halterman9fa43032017-07-28 11:00:26 -0700152
153 private static class CachedMap<K, V> {
154 private final AsyncConsistentMap<K, V> baseMap;
155 private final AsyncConsistentMap<K, V> cachedMap;
156
157 public CachedMap(AsyncConsistentMap<K, V> baseMap) {
158 this.baseMap = baseMap;
159 this.cachedMap = DistributedPrimitives.newCachingMap(baseMap);
160 }
161 }
Jordan Halterman948d6592017-04-20 17:18:24 -0700162}