blob: 173851d9fdf1462c88a93db4283a31db1c45b17f [file] [log] [blame]
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -07001/*
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -08002 * Copyright 2015-2016 Open Networking Laboratory
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -07003 *
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.newresource.impl;
17
18import com.google.common.annotations.Beta;
Sho SHIMIZUe7db6142015-11-04 11:24:22 -080019import com.google.common.collect.ImmutableList;
Sho SHIMIZU83258ae2016-01-29 17:39:07 -080020import com.google.common.collect.ImmutableSet;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080021import com.google.common.collect.Maps;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Reference;
25import org.apache.felix.scr.annotations.ReferenceCardinality;
26import org.apache.felix.scr.annotations.Service;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080027import org.onlab.util.GuavaCollectors;
Thomas Vachuska762a2d82016-01-04 10:25:20 -080028import org.onlab.util.Tools;
Sho SHIMIZUf33b8932016-01-25 18:43:32 -080029import org.onosproject.net.newresource.ContinuousResource;
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -080030import org.onosproject.net.newresource.ContinuousResourceId;
Sho SHIMIZUf33b8932016-01-25 18:43:32 -080031import org.onosproject.net.newresource.DiscreteResource;
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -080032import org.onosproject.net.newresource.DiscreteResourceId;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080033import org.onosproject.net.newresource.ResourceAllocation;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070034import org.onosproject.net.newresource.ResourceConsumer;
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080035import org.onosproject.net.newresource.ResourceEvent;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080036import org.onosproject.net.newresource.ResourceId;
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -080037import org.onosproject.net.newresource.Resource;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070038import org.onosproject.net.newresource.ResourceStore;
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080039import org.onosproject.net.newresource.ResourceStoreDelegate;
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -080040import org.onosproject.net.newresource.Resources;
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080041import org.onosproject.store.AbstractStore;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070042import org.onosproject.store.serializers.KryoNamespaces;
43import org.onosproject.store.service.ConsistentMap;
Thomas Vachuska762a2d82016-01-04 10:25:20 -080044import org.onosproject.store.service.ConsistentMapException;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070045import org.onosproject.store.service.Serializer;
46import org.onosproject.store.service.StorageService;
47import org.onosproject.store.service.TransactionContext;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070048import org.onosproject.store.service.TransactionalMap;
49import org.onosproject.store.service.Versioned;
50import org.slf4j.Logger;
51import org.slf4j.LoggerFactory;
52
Sho SHIMIZUba41fc12015-08-12 15:43:22 -070053import java.util.Arrays;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070054import java.util.Collection;
55import java.util.Iterator;
Sho SHIMIZUba41fc12015-08-12 15:43:22 -070056import java.util.LinkedHashSet;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070057import java.util.List;
58import java.util.Map;
59import java.util.Optional;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080060import java.util.Set;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070061import java.util.stream.Collectors;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080062import java.util.stream.Stream;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070063
64import static com.google.common.base.Preconditions.checkArgument;
65import static com.google.common.base.Preconditions.checkNotNull;
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080066import static org.onosproject.net.newresource.ResourceEvent.Type.*;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070067
68/**
69 * Implementation of ResourceStore using TransactionalMap.
70 */
Sho SHIMIZU9a2b8292015-10-28 13:00:16 -070071@Component(immediate = true)
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070072@Service
73@Beta
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080074public class ConsistentResourceStore extends AbstractStore<ResourceEvent, ResourceStoreDelegate>
75 implements ResourceStore {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070076 private static final Logger log = LoggerFactory.getLogger(ConsistentResourceStore.class);
77
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080078 private static final String DISCRETE_CONSUMER_MAP = "onos-discrete-consumers";
79 private static final String CONTINUOUS_CONSUMER_MAP = "onos-continuous-consumers";
Sho SHIMIZUba41fc12015-08-12 15:43:22 -070080 private static final String CHILD_MAP = "onos-resource-children";
81 private static final Serializer SERIALIZER = Serializer.using(
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080082 Arrays.asList(KryoNamespaces.BASIC, KryoNamespaces.API),
83 ContinuousResourceAllocation.class);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070084
Thomas Vachuska762a2d82016-01-04 10:25:20 -080085 // TODO: We should provide centralized values for this
86 private static final int MAX_RETRIES = 5;
87 private static final int RETRY_DELAY = 1_000; // millis
88
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070089 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
90 protected StorageService service;
91
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -080092 private ConsistentMap<DiscreteResourceId, ResourceConsumer> discreteConsumers;
93 private ConsistentMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumers;
94 private ConsistentMap<DiscreteResourceId, Set<Resource>> childMap;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070095
96 @Activate
97 public void activate() {
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -080098 discreteConsumers = service.<DiscreteResourceId, ResourceConsumer>consistentMapBuilder()
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080099 .withName(DISCRETE_CONSUMER_MAP)
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700100 .withSerializer(SERIALIZER)
101 .build();
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800102 continuousConsumers = service.<ContinuousResourceId, ContinuousResourceAllocation>consistentMapBuilder()
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800103 .withName(CONTINUOUS_CONSUMER_MAP)
104 .withSerializer(SERIALIZER)
105 .build();
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800106 childMap = service.<DiscreteResourceId, Set<Resource>>consistentMapBuilder()
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700107 .withName(CHILD_MAP)
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700108 .withSerializer(SERIALIZER)
109 .build();
Sho SHIMIZUe7db6142015-11-04 11:24:22 -0800110
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800111 Tools.retryable(() -> childMap.put(Resource.ROOT.id(), new LinkedHashSet<>()),
Thomas Vachuska762a2d82016-01-04 10:25:20 -0800112 ConsistentMapException.class, MAX_RETRIES, RETRY_DELAY);
Madan Jampanic7f49f92015-12-10 11:35:06 -0800113 log.info("Started");
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700114 }
115
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800116 // Computational complexity: O(1) if the resource is discrete type.
117 // O(n) if the resource is continuous type where n is the number of the existing allocations for the resource
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700118 @Override
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800119 public List<ResourceAllocation> getResourceAllocations(ResourceId id) {
120 checkNotNull(id);
121 checkArgument(id instanceof DiscreteResourceId || id instanceof ContinuousResourceId);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700122
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800123 if (id instanceof DiscreteResourceId) {
124 return getResourceAllocations((DiscreteResourceId) id);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800125 } else {
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800126 return getResourceAllocations((ContinuousResourceId) id);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800127 }
128 }
129
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800130 // computational complexity: O(1)
131 private List<ResourceAllocation> getResourceAllocations(DiscreteResourceId resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800132 Versioned<ResourceConsumer> consumer = discreteConsumers.get(resource);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700133 if (consumer == null) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800134 return ImmutableList.of();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700135 }
136
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800137 return ImmutableList.of(new ResourceAllocation(Resources.discrete(resource).resource(), consumer.value()));
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800138 }
139
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800140 // computational complexity: O(n) where n is the number of the existing allocations for the resource
141 private List<ResourceAllocation> getResourceAllocations(ContinuousResourceId resource) {
142 Versioned<ContinuousResourceAllocation> allocations = continuousConsumers.get(resource);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800143 if (allocations == null) {
144 return ImmutableList.of();
145 }
146
147 return allocations.value().allocations().stream()
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800148 .filter(x -> x.resource().id().equals(resource))
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800149 .collect(GuavaCollectors.toImmutableList());
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700150 }
151
152 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800153 public boolean register(List<Resource> resources) {
Sho SHIMIZU83e17a02015-08-20 14:07:05 -0700154 checkNotNull(resources);
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800155 if (log.isTraceEnabled()) {
156 resources.forEach(r -> log.trace("registering {}", r));
157 }
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700158
159 TransactionContext tx = service.transactionContextBuilder().build();
160 tx.begin();
161
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800162 TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap =
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800163 tx.getTransactionalMap(CHILD_MAP, SERIALIZER);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700164
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800165 Map<DiscreteResource, List<Resource>> resourceMap = resources.stream()
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800166 .filter(x -> x.parent().isPresent())
167 .collect(Collectors.groupingBy(x -> x.parent().get()));
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700168
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800169 for (Map.Entry<DiscreteResource, List<Resource>> entry: resourceMap.entrySet()) {
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800170 if (!lookup(childTxMap, entry.getKey().id()).isPresent()) {
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800171 return abortTransaction(tx);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700172 }
173
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800174 if (!appendValues(childTxMap, entry.getKey().id(), entry.getValue())) {
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800175 return abortTransaction(tx);
176 }
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700177 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800178
Sho SHIMIZUfa62b472015-11-02 17:35:46 -0800179 boolean success = tx.commit();
180 if (success) {
181 List<ResourceEvent> events = resources.stream()
182 .filter(x -> x.parent().isPresent())
183 .map(x -> new ResourceEvent(RESOURCE_ADDED, x))
184 .collect(Collectors.toList());
185 notifyDelegate(events);
186 }
187 return success;
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700188 }
189
190 @Override
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800191 public boolean unregister(List<ResourceId> ids) {
192 checkNotNull(ids);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700193
194 TransactionContext tx = service.transactionContextBuilder().build();
195 tx.begin();
196
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800197 TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap =
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800198 tx.getTransactionalMap(CHILD_MAP, SERIALIZER);
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800199 TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800200 tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800201 TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800202 tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700203
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800204 // Extract Discrete instances from resources
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800205 List<Resource> resources = ids.stream()
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800206 .filter(x -> x.parent().isPresent())
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800207 .map(x -> lookup(childTxMap, x))
208 .filter(Optional::isPresent)
209 .map(Optional::get)
210 .collect(Collectors.toList());
211 Map<DiscreteResourceId, List<Resource>> resourceMap = resources.stream()
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800212 .collect(Collectors.groupingBy(x -> x.parent().get().id()));
Sho SHIMIZU83e17a02015-08-20 14:07:05 -0700213
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800214 // even if one of the resources is allocated to a consumer,
215 // all unregistrations are regarded as failure
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800216 for (Map.Entry<DiscreteResourceId, List<Resource>> entry: resourceMap.entrySet()) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800217 boolean allocated = entry.getValue().stream().anyMatch(x -> {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800218 if (x instanceof DiscreteResource) {
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800219 return discreteConsumerTxMap.get(((DiscreteResource) x).id()) != null;
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800220 } else if (x instanceof ContinuousResource) {
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800221 ContinuousResourceAllocation allocations =
222 continuousConsumerTxMap.get(((ContinuousResource) x).id());
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800223 return allocations != null && !allocations.allocations().isEmpty();
224 } else {
225 return false;
226 }
227 });
228 if (allocated) {
HIGUCHI Yuta5b6dfba2016-01-27 14:43:41 -0800229 log.warn("Failed to unregister {}: allocation exists", entry.getKey());
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800230 return abortTransaction(tx);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700231 }
232
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800233 if (!removeValues(childTxMap, entry.getKey(), entry.getValue())) {
HIGUCHI Yuta5b6dfba2016-01-27 14:43:41 -0800234 log.warn("Failed to unregister {}: Failed to remove values: {}",
235 entry.getKey(), entry.getValue());
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800236 return abortTransaction(tx);
237 }
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700238 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800239
Sho SHIMIZUfa62b472015-11-02 17:35:46 -0800240 boolean success = tx.commit();
241 if (success) {
242 List<ResourceEvent> events = resources.stream()
243 .filter(x -> x.parent().isPresent())
244 .map(x -> new ResourceEvent(RESOURCE_REMOVED, x))
245 .collect(Collectors.toList());
246 notifyDelegate(events);
HIGUCHI Yuta5b6dfba2016-01-27 14:43:41 -0800247 } else {
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800248 log.warn("Failed to unregister {}: Commit failed.", ids);
Sho SHIMIZUfa62b472015-11-02 17:35:46 -0800249 }
250 return success;
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700251 }
252
253 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800254 public boolean allocate(List<Resource> resources, ResourceConsumer consumer) {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700255 checkNotNull(resources);
256 checkNotNull(consumer);
257
258 TransactionContext tx = service.transactionContextBuilder().build();
259 tx.begin();
260
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800261 TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap =
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800262 tx.getTransactionalMap(CHILD_MAP, SERIALIZER);
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800263 TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800264 tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800265 TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800266 tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700267
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800268 for (Resource resource: resources) {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800269 if (resource instanceof DiscreteResource) {
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800270 if (!lookup(childTxMap, resource.id()).isPresent()) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800271 return abortTransaction(tx);
272 }
Sho SHIMIZUd29847f2015-08-13 09:10:59 -0700273
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800274 ResourceConsumer oldValue = discreteConsumerTxMap.put(((DiscreteResource) resource).id(), consumer);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800275 if (oldValue != null) {
276 return abortTransaction(tx);
277 }
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800278 } else if (resource instanceof ContinuousResource) {
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800279 Optional<Resource> lookedUp = lookup(childTxMap, resource.id());
280 if (!lookedUp.isPresent()) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800281 return abortTransaction(tx);
282 }
283
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800284 // Down cast: this must be safe as ContinuousResource is associated with ContinuousResourceId
285 ContinuousResource continuous = (ContinuousResource) lookedUp.get();
286 ContinuousResourceAllocation allocations = continuousConsumerTxMap.get(continuous.id());
287 if (!hasEnoughResource(continuous, (ContinuousResource) resource, allocations)) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800288 return abortTransaction(tx);
289 }
290
291 boolean success = appendValue(continuousConsumerTxMap,
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800292 continuous, new ResourceAllocation(continuous, consumer));
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800293 if (!success) {
294 return abortTransaction(tx);
295 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800296 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700297 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800298
299 return tx.commit();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700300 }
301
302 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800303 public boolean release(List<Resource> resources, List<ResourceConsumer> consumers) {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700304 checkNotNull(resources);
305 checkNotNull(consumers);
306 checkArgument(resources.size() == consumers.size());
307
308 TransactionContext tx = service.transactionContextBuilder().build();
309 tx.begin();
310
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800311 TransactionalMap<DiscreteResourceId, ResourceConsumer> discreteConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800312 tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800313 TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> continuousConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800314 tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800315 Iterator<Resource> resourceIte = resources.iterator();
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800316 Iterator<ResourceConsumer> consumerIte = consumers.iterator();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700317
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800318 while (resourceIte.hasNext() && consumerIte.hasNext()) {
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800319 Resource resource = resourceIte.next();
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800320 ResourceConsumer consumer = consumerIte.next();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700321
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800322 if (resource instanceof DiscreteResource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800323 // if this single release fails (because the resource is allocated to another consumer,
324 // the whole release fails
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800325 if (!discreteConsumerTxMap.remove(((DiscreteResource) resource).id(), consumer)) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800326 return abortTransaction(tx);
327 }
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800328 } else if (resource instanceof ContinuousResource) {
329 ContinuousResource continuous = (ContinuousResource) resource;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800330 ContinuousResourceAllocation allocation = continuousConsumerTxMap.get(continuous.id());
331 ImmutableList<ResourceAllocation> newAllocations = allocation.allocations().stream()
332 .filter(x -> !(x.consumer().equals(consumer) &&
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800333 ((ContinuousResource) x.resource()).value() == continuous.value()))
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800334 .collect(GuavaCollectors.toImmutableList());
335
336 if (!continuousConsumerTxMap.replace(continuous.id(), allocation,
337 new ContinuousResourceAllocation(allocation.original(), newAllocations))) {
338 return abortTransaction(tx);
339 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700340 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700341 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800342
343 return tx.commit();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700344 }
345
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800346 // computational complexity: O(1) if the resource is discrete type.
347 // O(n) if the resource is continuous type where n is the number of the children of
348 // the specified resource's parent
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700349 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800350 public boolean isAvailable(Resource resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800351 checkNotNull(resource);
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800352 checkArgument(resource instanceof DiscreteResource || resource instanceof ContinuousResource);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800353
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800354 // check if it's registered or not.
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800355 Versioned<Set<Resource>> v = childMap.get(resource.parent().get().id());
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800356 if (v == null || !v.value().contains(resource)) {
357 return false;
358 }
359
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800360 if (resource instanceof DiscreteResource) {
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800361 // check if already consumed
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800362 return getResourceAllocations(resource.id()).isEmpty();
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800363 } else {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800364 ContinuousResource requested = (ContinuousResource) resource;
365 ContinuousResource registered = v.value().stream()
Sho SHIMIZU2d310222016-01-22 11:45:11 -0800366 .filter(c -> c.id().equals(resource.id()))
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800367 .findFirst()
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800368 .map(c -> (ContinuousResource) c)
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800369 .get();
370 if (registered.value() < requested.value()) {
371 // Capacity < requested, can never satisfy
372 return false;
373 }
374 // check if there's enough left
375 return isAvailable(requested);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800376 }
377 }
378
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800379 // computational complexity: O(n) where n is the number of existing allocations for the resource
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800380 private boolean isAvailable(ContinuousResource resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800381 Versioned<ContinuousResourceAllocation> allocation = continuousConsumers.get(resource.id());
382 if (allocation == null) {
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800383 // no allocation (=no consumer) full registered resources available
384 return true;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800385 }
386
387 return hasEnoughResource(allocation.value().original(), resource, allocation.value());
388 }
389
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800390 // computational complexity: O(n + m) where n is the number of entries in discreteConsumers
391 // and m is the number of allocations for all continuous resources
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800392 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800393 public Collection<Resource> getResources(ResourceConsumer consumer) {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700394 checkNotNull(consumer);
395
396 // NOTE: getting all entries may become performance bottleneck
397 // TODO: revisit for better backend data structure
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800398 Stream<DiscreteResource> discreteStream = discreteConsumers.entrySet().stream()
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700399 .filter(x -> x.getValue().value().equals(consumer))
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800400 .map(Map.Entry::getKey)
401 .map(x -> Resources.discrete(x).resource());
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800402
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800403 Stream<ContinuousResource> continuousStream = continuousConsumers.values().stream()
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800404 .flatMap(x -> x.value().allocations().stream()
405 .map(y -> Maps.immutableEntry(x.value().original(), y)))
406 .filter(x -> x.getValue().consumer().equals(consumer))
407 .map(x -> x.getKey());
408
409 return Stream.concat(discreteStream, continuousStream).collect(Collectors.toList());
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700410 }
411
Sho SHIMIZU82bfe992016-02-10 09:55:32 -0800412 // computational complexity: O(1)
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700413 @Override
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800414 public Set<Resource> getChildResources(DiscreteResourceId parent) {
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700415 checkNotNull(parent);
416
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800417 Versioned<Set<Resource>> children = childMap.get(parent);
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700418 if (children == null) {
Sho SHIMIZU83258ae2016-01-29 17:39:07 -0800419 return ImmutableSet.of();
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700420 }
421
422 return children.value();
423 }
424
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800425 // computational complexity: O(n) where n is the number of the children of the parent
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700426 @Override
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800427 public <T> Collection<Resource> getAllocatedResources(DiscreteResourceId parent, Class<T> cls) {
Sho SHIMIZU1f5e5912015-08-10 17:00:00 -0700428 checkNotNull(parent);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700429 checkNotNull(cls);
430
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800431 Versioned<Set<Resource>> children = childMap.get(parent);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700432 if (children == null) {
Sho SHIMIZU2c0ae122016-01-20 13:14:38 -0800433 return ImmutableList.of();
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700434 }
435
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800436 Stream<DiscreteResource> discrete = children.value().stream()
Sho SHIMIZUc9546a32015-11-10 11:22:28 -0800437 .filter(x -> x.last().getClass().equals(cls))
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800438 .filter(x -> x instanceof DiscreteResource)
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800439 .map(x -> ((DiscreteResource) x))
440 .filter(x -> discreteConsumers.containsKey(x.id()));
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800441
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800442 Stream<ContinuousResource> continuous = children.value().stream()
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800443 .filter(x -> x.id().equals(parent.child(cls)))
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800444 .filter(x -> x instanceof ContinuousResource)
445 .map(x -> (ContinuousResource) x)
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800446 .filter(x -> continuousConsumers.containsKey(x.id()))
447 .filter(x -> continuousConsumers.get(x.id()) != null)
448 .filter(x -> !continuousConsumers.get(x.id()).value().allocations().isEmpty());
449
450 return Stream.concat(discrete, continuous).collect(Collectors.toList());
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700451 }
Sho SHIMIZUd29847f2015-08-13 09:10:59 -0700452
453 /**
454 * Abort the transaction.
455 *
456 * @param tx transaction context
457 * @return always false
458 */
459 private boolean abortTransaction(TransactionContext tx) {
460 tx.abort();
461 return false;
462 }
463
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800464 // Appends the specified ResourceAllocation to the existing values stored in the map
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800465 // computational complexity: O(n) where n is the number of the elements in the associated allocation
466 private boolean appendValue(TransactionalMap<ContinuousResourceId, ContinuousResourceAllocation> map,
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800467 ContinuousResource original, ResourceAllocation value) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800468 ContinuousResourceAllocation oldValue = map.putIfAbsent(original.id(),
469 new ContinuousResourceAllocation(original, ImmutableList.of(value)));
470 if (oldValue == null) {
471 return true;
472 }
473
474 if (oldValue.allocations().contains(value)) {
475 // don't write to map because all values are already stored
476 return true;
477 }
478
479 ContinuousResourceAllocation newValue = new ContinuousResourceAllocation(original,
480 ImmutableList.<ResourceAllocation>builder()
481 .addAll(oldValue.allocations())
482 .add(value)
483 .build());
484 return map.replace(original.id(), oldValue, newValue);
485 }
Sho SHIMIZUd29847f2015-08-13 09:10:59 -0700486 /**
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700487 * Appends the values to the existing values associated with the specified key.
Sho SHIMIZU4568c412015-08-21 16:39:07 -0700488 * If the map already has all the given values, appending will not happen.
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700489 *
490 * @param map map holding multiple values for a key
491 * @param key key specifying values
492 * @param values values to be appended
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700493 * @return true if the operation succeeds, false otherwise.
494 */
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800495 // computational complexity: O(n) where n is the number of the specified value
496 private boolean appendValues(TransactionalMap<DiscreteResourceId, Set<Resource>> map,
497 DiscreteResourceId key, List<Resource> values) {
Sho SHIMIZU07b7bc92016-01-29 18:27:58 -0800498 Set<Resource> oldValues = map.putIfAbsent(key, new LinkedHashSet<>(values));
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700499 if (oldValues == null) {
Sho SHIMIZU93a74b32015-11-09 11:48:23 -0800500 return true;
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700501 }
502
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800503 if (oldValues.containsAll(values)) {
Sho SHIMIZU4568c412015-08-21 16:39:07 -0700504 // don't write to map because all values are already stored
505 return true;
506 }
507
Sho SHIMIZU07b7bc92016-01-29 18:27:58 -0800508 LinkedHashSet<Resource> newValues = new LinkedHashSet<>(oldValues);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800509 newValues.addAll(values);
510 return map.replace(key, oldValues, newValues);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700511 }
512
513 /**
Sho SHIMIZUba1f83b2015-10-14 08:11:20 -0700514 * Removes the values from the existing values associated with the specified key.
Sho SHIMIZU5618ee52015-08-21 17:19:44 -0700515 * If the map doesn't contain the given values, removal will not happen.
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700516 *
517 * @param map map holding multiple values for a key
518 * @param key key specifying values
519 * @param values values to be removed
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700520 * @return true if the operation succeeds, false otherwise
521 */
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800522 // computational complexity: O(n) where n is the number of the specified values
523 private boolean removeValues(TransactionalMap<DiscreteResourceId, Set<Resource>> map,
524 DiscreteResourceId key, List<Resource> values) {
Sho SHIMIZU07b7bc92016-01-29 18:27:58 -0800525 Set<Resource> oldValues = map.putIfAbsent(key, new LinkedHashSet<>());
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700526 if (oldValues == null) {
HIGUCHI Yutadc4394c2016-01-29 15:35:10 -0800527 log.trace("No-Op removing values. key {} did not exist", key);
Sho SHIMIZU93a74b32015-11-09 11:48:23 -0800528 return true;
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700529 }
530
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800531 if (values.stream().allMatch(x -> !oldValues.contains(x))) {
Sho SHIMIZU5618ee52015-08-21 17:19:44 -0700532 // don't write map because none of the values are stored
HIGUCHI Yutadc4394c2016-01-29 15:35:10 -0800533 log.trace("No-Op removing values. key {} did not contain {}", key, values);
Sho SHIMIZU5618ee52015-08-21 17:19:44 -0700534 return true;
535 }
536
Sho SHIMIZU07b7bc92016-01-29 18:27:58 -0800537 LinkedHashSet<Resource> newValues = new LinkedHashSet<>(oldValues);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800538 newValues.removeAll(values);
539 return map.replace(key, oldValues, newValues);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700540 }
541
542 /**
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800543 * Returns the resource which has the same key as the specified resource ID
544 * in the set as a value of the map.
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700545 *
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800546 * @param childTxMap map storing parent - child relationship of resources
547 * @param id ID of resource to be checked
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800548 * @return the resource which is regarded as the same as the specified resource
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700549 */
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800550 // Naive implementation, which traverses all elements in the set
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800551 // computational complexity: O(n) where n is the number of elements
552 // in the associated set
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800553 private Optional<Resource> lookup(TransactionalMap<DiscreteResourceId, Set<Resource>> childTxMap, ResourceId id) {
554 if (!id.parent().isPresent()) {
555 return Optional.of(Resource.ROOT);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700556 }
557
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800558 Set<Resource> values = childTxMap.get(id.parent().get());
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800559 if (values == null) {
560 return Optional.empty();
561 }
562
Sho SHIMIZU72f81b12016-02-09 09:26:17 -0800563 return values.stream()
564 .filter(x -> x.id().equals(id))
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800565 .findFirst();
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800566 }
567
568 /**
569 * Checks if there is enough resource volume to allocated the requested resource
570 * against the specified resource.
571 *
572 * @param original original resource
573 * @param request requested resource
574 * @param allocation current allocation of the resource
575 * @return true if there is enough resource volume. Otherwise, false.
576 */
Sho SHIMIZUdd3750c2016-02-01 11:37:04 -0800577 // computational complexity: O(n) where n is the number of allocations
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800578 private boolean hasEnoughResource(ContinuousResource original,
579 ContinuousResource request,
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800580 ContinuousResourceAllocation allocation) {
581 if (allocation == null) {
582 return request.value() <= original.value();
583 }
584
585 double allocated = allocation.allocations().stream()
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800586 .filter(x -> x.resource() instanceof ContinuousResource)
587 .map(x -> (ContinuousResource) x.resource())
588 .mapToDouble(ContinuousResource::value)
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800589 .sum();
590 double left = original.value() - allocated;
591 return request.value() <= left;
592 }
593
594 // internal use only
595 private static final class ContinuousResourceAllocation {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800596 private final ContinuousResource original;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800597 private final ImmutableList<ResourceAllocation> allocations;
598
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800599 private ContinuousResourceAllocation(ContinuousResource original,
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800600 ImmutableList<ResourceAllocation> allocations) {
601 this.original = original;
602 this.allocations = allocations;
603 }
604
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800605 private ContinuousResource original() {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800606 return original;
607 }
608
609 private ImmutableList<ResourceAllocation> allocations() {
610 return allocations;
611 }
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700612 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700613}