blob: f13481ca415799badeafb930bd51ec303d4b9b4a [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 SHIMIZU6c9e33a2016-01-07 18:45:27 -080020import com.google.common.collect.Maps;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070021import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Reference;
24import org.apache.felix.scr.annotations.ReferenceCardinality;
25import org.apache.felix.scr.annotations.Service;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080026import org.onlab.util.GuavaCollectors;
Thomas Vachuska762a2d82016-01-04 10:25:20 -080027import org.onlab.util.Tools;
Sho SHIMIZUf33b8932016-01-25 18:43:32 -080028import org.onosproject.net.newresource.ContinuousResource;
29import org.onosproject.net.newresource.DiscreteResource;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080030import org.onosproject.net.newresource.ResourceAllocation;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070031import org.onosproject.net.newresource.ResourceConsumer;
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080032import org.onosproject.net.newresource.ResourceEvent;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080033import org.onosproject.net.newresource.ResourceId;
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -080034import org.onosproject.net.newresource.Resource;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070035import org.onosproject.net.newresource.ResourceStore;
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080036import org.onosproject.net.newresource.ResourceStoreDelegate;
37import org.onosproject.store.AbstractStore;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070038import org.onosproject.store.serializers.KryoNamespaces;
39import org.onosproject.store.service.ConsistentMap;
Thomas Vachuska762a2d82016-01-04 10:25:20 -080040import org.onosproject.store.service.ConsistentMapException;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070041import org.onosproject.store.service.Serializer;
42import org.onosproject.store.service.StorageService;
43import org.onosproject.store.service.TransactionContext;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070044import org.onosproject.store.service.TransactionalMap;
45import org.onosproject.store.service.Versioned;
46import org.slf4j.Logger;
47import org.slf4j.LoggerFactory;
48
Sho SHIMIZUba41fc12015-08-12 15:43:22 -070049import java.util.Arrays;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070050import java.util.Collection;
51import java.util.Iterator;
Sho SHIMIZUba41fc12015-08-12 15:43:22 -070052import java.util.LinkedHashSet;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070053import java.util.List;
54import java.util.Map;
55import java.util.Optional;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080056import java.util.Set;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070057import java.util.stream.Collectors;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080058import java.util.stream.Stream;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070059
60import static com.google.common.base.Preconditions.checkArgument;
61import static com.google.common.base.Preconditions.checkNotNull;
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080062import static org.onosproject.net.newresource.ResourceEvent.Type.*;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070063
64/**
65 * Implementation of ResourceStore using TransactionalMap.
66 */
Sho SHIMIZU9a2b8292015-10-28 13:00:16 -070067@Component(immediate = true)
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070068@Service
69@Beta
Sho SHIMIZUfa62b472015-11-02 17:35:46 -080070public class ConsistentResourceStore extends AbstractStore<ResourceEvent, ResourceStoreDelegate>
71 implements ResourceStore {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070072 private static final Logger log = LoggerFactory.getLogger(ConsistentResourceStore.class);
73
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080074 private static final String DISCRETE_CONSUMER_MAP = "onos-discrete-consumers";
75 private static final String CONTINUOUS_CONSUMER_MAP = "onos-continuous-consumers";
Sho SHIMIZUba41fc12015-08-12 15:43:22 -070076 private static final String CHILD_MAP = "onos-resource-children";
77 private static final Serializer SERIALIZER = Serializer.using(
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080078 Arrays.asList(KryoNamespaces.BASIC, KryoNamespaces.API),
79 ContinuousResourceAllocation.class);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070080
Thomas Vachuska762a2d82016-01-04 10:25:20 -080081 // TODO: We should provide centralized values for this
82 private static final int MAX_RETRIES = 5;
83 private static final int RETRY_DELAY = 1_000; // millis
84
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070085 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
86 protected StorageService service;
87
Sho SHIMIZUf33b8932016-01-25 18:43:32 -080088 private ConsistentMap<DiscreteResource, ResourceConsumer> discreteConsumers;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080089 private ConsistentMap<ResourceId, ContinuousResourceAllocation> continuousConsumers;
Sho SHIMIZUf33b8932016-01-25 18:43:32 -080090 private ConsistentMap<DiscreteResource, Set<Resource>> childMap;
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -070091
92 @Activate
93 public void activate() {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -080094 discreteConsumers = service.<DiscreteResource, ResourceConsumer>consistentMapBuilder()
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080095 .withName(DISCRETE_CONSUMER_MAP)
Sho SHIMIZUba41fc12015-08-12 15:43:22 -070096 .withSerializer(SERIALIZER)
97 .build();
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -080098 continuousConsumers = service.<ResourceId, ContinuousResourceAllocation>consistentMapBuilder()
99 .withName(CONTINUOUS_CONSUMER_MAP)
100 .withSerializer(SERIALIZER)
101 .build();
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800102 childMap = service.<DiscreteResource, Set<Resource>>consistentMapBuilder()
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700103 .withName(CHILD_MAP)
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700104 .withSerializer(SERIALIZER)
105 .build();
Sho SHIMIZUe7db6142015-11-04 11:24:22 -0800106
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800107 Tools.retryable(() -> childMap.put(Resource.ROOT, new LinkedHashSet<>()),
Thomas Vachuska762a2d82016-01-04 10:25:20 -0800108 ConsistentMapException.class, MAX_RETRIES, RETRY_DELAY);
Madan Jampanic7f49f92015-12-10 11:35:06 -0800109 log.info("Started");
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700110 }
111
112 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800113 public List<ResourceConsumer> getConsumers(Resource resource) {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700114 checkNotNull(resource);
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800115 checkArgument(resource instanceof DiscreteResource || resource instanceof ContinuousResource);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700116
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800117 if (resource instanceof DiscreteResource) {
Sho SHIMIZU4a1e59f2016-01-26 15:27:13 -0800118 return getConsumers((DiscreteResource) resource);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800119 } else {
Sho SHIMIZU4a1e59f2016-01-26 15:27:13 -0800120 return getConsumers((ContinuousResource) resource);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800121 }
122 }
123
Sho SHIMIZU4a1e59f2016-01-26 15:27:13 -0800124 private List<ResourceConsumer> getConsumers(DiscreteResource resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800125 Versioned<ResourceConsumer> consumer = discreteConsumers.get(resource);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700126 if (consumer == null) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800127 return ImmutableList.of();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700128 }
129
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800130 return ImmutableList.of(consumer.value());
131 }
132
Sho SHIMIZU4a1e59f2016-01-26 15:27:13 -0800133 private List<ResourceConsumer> getConsumers(ContinuousResource resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800134 Versioned<ContinuousResourceAllocation> allocations = continuousConsumers.get(resource.id());
135 if (allocations == null) {
136 return ImmutableList.of();
137 }
138
139 return allocations.value().allocations().stream()
140 .filter(x -> x.resource().equals(resource))
141 .map(ResourceAllocation::consumer)
142 .collect(GuavaCollectors.toImmutableList());
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700143 }
144
145 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800146 public boolean register(List<Resource> resources) {
Sho SHIMIZU83e17a02015-08-20 14:07:05 -0700147 checkNotNull(resources);
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800148 if (log.isTraceEnabled()) {
149 resources.forEach(r -> log.trace("registering {}", r));
150 }
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700151
152 TransactionContext tx = service.transactionContextBuilder().build();
153 tx.begin();
154
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800155 TransactionalMap<DiscreteResource, Set<Resource>> childTxMap =
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800156 tx.getTransactionalMap(CHILD_MAP, SERIALIZER);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700157
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800158 Map<DiscreteResource, List<Resource>> resourceMap = resources.stream()
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800159 .filter(x -> x.parent().isPresent())
160 .collect(Collectors.groupingBy(x -> x.parent().get()));
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700161
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800162 for (Map.Entry<DiscreteResource, List<Resource>> entry: resourceMap.entrySet()) {
163 Optional<DiscreteResource> child = lookup(childTxMap, entry.getKey());
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800164 if (!child.isPresent()) {
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800165 return abortTransaction(tx);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700166 }
167
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800168 if (!appendValues(childTxMap, entry.getKey(), entry.getValue())) {
169 return abortTransaction(tx);
170 }
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700171 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800172
Sho SHIMIZUfa62b472015-11-02 17:35:46 -0800173 boolean success = tx.commit();
174 if (success) {
175 List<ResourceEvent> events = resources.stream()
176 .filter(x -> x.parent().isPresent())
177 .map(x -> new ResourceEvent(RESOURCE_ADDED, x))
178 .collect(Collectors.toList());
179 notifyDelegate(events);
180 }
181 return success;
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700182 }
183
184 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800185 public boolean unregister(List<Resource> resources) {
Sho SHIMIZU83e17a02015-08-20 14:07:05 -0700186 checkNotNull(resources);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700187
188 TransactionContext tx = service.transactionContextBuilder().build();
189 tx.begin();
190
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800191 TransactionalMap<DiscreteResource, Set<Resource>> childTxMap =
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800192 tx.getTransactionalMap(CHILD_MAP, SERIALIZER);
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800193 TransactionalMap<DiscreteResource, ResourceConsumer> discreteConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800194 tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER);
195 TransactionalMap<ResourceId, ContinuousResourceAllocation> continuousConsumerTxMap =
196 tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700197
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800198 // Extract Discrete instances from resources
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800199 Map<DiscreteResource, List<Resource>> resourceMap = resources.stream()
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800200 .filter(x -> x.parent().isPresent())
201 .collect(Collectors.groupingBy(x -> x.parent().get()));
Sho SHIMIZU83e17a02015-08-20 14:07:05 -0700202
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800203 // even if one of the resources is allocated to a consumer,
204 // all unregistrations are regarded as failure
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800205 for (Map.Entry<DiscreteResource, List<Resource>> entry: resourceMap.entrySet()) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800206 boolean allocated = entry.getValue().stream().anyMatch(x -> {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800207 if (x instanceof DiscreteResource) {
208 return discreteConsumerTxMap.get((DiscreteResource) x) != null;
209 } else if (x instanceof ContinuousResource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800210 ContinuousResourceAllocation allocations = continuousConsumerTxMap.get(x.id());
211 return allocations != null && !allocations.allocations().isEmpty();
212 } else {
213 return false;
214 }
215 });
216 if (allocated) {
HIGUCHI Yuta5b6dfba2016-01-27 14:43:41 -0800217 log.warn("Failed to unregister {}: allocation exists", entry.getKey());
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800218 return abortTransaction(tx);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700219 }
220
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800221 if (!removeValues(childTxMap, entry.getKey(), entry.getValue())) {
HIGUCHI Yuta5b6dfba2016-01-27 14:43:41 -0800222 log.warn("Failed to unregister {}: Failed to remove values: {}",
223 entry.getKey(), entry.getValue());
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800224 return abortTransaction(tx);
225 }
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700226 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800227
Sho SHIMIZUfa62b472015-11-02 17:35:46 -0800228 boolean success = tx.commit();
229 if (success) {
230 List<ResourceEvent> events = resources.stream()
231 .filter(x -> x.parent().isPresent())
232 .map(x -> new ResourceEvent(RESOURCE_REMOVED, x))
233 .collect(Collectors.toList());
234 notifyDelegate(events);
HIGUCHI Yuta5b6dfba2016-01-27 14:43:41 -0800235 } else {
236 log.warn("Failed to unregister {}: Commit failed.", resources);
Sho SHIMIZUfa62b472015-11-02 17:35:46 -0800237 }
238 return success;
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700239 }
240
241 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800242 public boolean allocate(List<Resource> resources, ResourceConsumer consumer) {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700243 checkNotNull(resources);
244 checkNotNull(consumer);
245
246 TransactionContext tx = service.transactionContextBuilder().build();
247 tx.begin();
248
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800249 TransactionalMap<DiscreteResource, Set<Resource>> childTxMap =
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800250 tx.getTransactionalMap(CHILD_MAP, SERIALIZER);
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800251 TransactionalMap<DiscreteResource, ResourceConsumer> discreteConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800252 tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER);
253 TransactionalMap<ResourceId, ContinuousResourceAllocation> continuousConsumerTxMap =
254 tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700255
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800256 for (Resource resource: resources) {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800257 if (resource instanceof DiscreteResource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800258 if (!lookup(childTxMap, resource).isPresent()) {
259 return abortTransaction(tx);
260 }
Sho SHIMIZUd29847f2015-08-13 09:10:59 -0700261
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800262 ResourceConsumer oldValue = discreteConsumerTxMap.put((DiscreteResource) resource, consumer);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800263 if (oldValue != null) {
264 return abortTransaction(tx);
265 }
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800266 } else if (resource instanceof ContinuousResource) {
267 Optional<ContinuousResource> continuous = lookup(childTxMap, (ContinuousResource) resource);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800268 if (!continuous.isPresent()) {
269 return abortTransaction(tx);
270 }
271
272 ContinuousResourceAllocation allocations = continuousConsumerTxMap.get(continuous.get().id());
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800273 if (!hasEnoughResource(continuous.get(), (ContinuousResource) resource, allocations)) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800274 return abortTransaction(tx);
275 }
276
277 boolean success = appendValue(continuousConsumerTxMap,
278 continuous.get(), new ResourceAllocation(continuous.get(), consumer));
279 if (!success) {
280 return abortTransaction(tx);
281 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800282 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700283 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800284
285 return tx.commit();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700286 }
287
288 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800289 public boolean release(List<Resource> resources, List<ResourceConsumer> consumers) {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700290 checkNotNull(resources);
291 checkNotNull(consumers);
292 checkArgument(resources.size() == consumers.size());
293
294 TransactionContext tx = service.transactionContextBuilder().build();
295 tx.begin();
296
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800297 TransactionalMap<DiscreteResource, ResourceConsumer> discreteConsumerTxMap =
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800298 tx.getTransactionalMap(DISCRETE_CONSUMER_MAP, SERIALIZER);
299 TransactionalMap<ResourceId, ContinuousResourceAllocation> continuousConsumerTxMap =
300 tx.getTransactionalMap(CONTINUOUS_CONSUMER_MAP, SERIALIZER);
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800301 Iterator<Resource> resourceIte = resources.iterator();
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800302 Iterator<ResourceConsumer> consumerIte = consumers.iterator();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700303
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800304 while (resourceIte.hasNext() && consumerIte.hasNext()) {
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800305 Resource resource = resourceIte.next();
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800306 ResourceConsumer consumer = consumerIte.next();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700307
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800308 if (resource instanceof DiscreteResource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800309 // if this single release fails (because the resource is allocated to another consumer,
310 // the whole release fails
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800311 if (!discreteConsumerTxMap.remove((DiscreteResource) resource, consumer)) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800312 return abortTransaction(tx);
313 }
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800314 } else if (resource instanceof ContinuousResource) {
315 ContinuousResource continuous = (ContinuousResource) resource;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800316 ContinuousResourceAllocation allocation = continuousConsumerTxMap.get(continuous.id());
317 ImmutableList<ResourceAllocation> newAllocations = allocation.allocations().stream()
318 .filter(x -> !(x.consumer().equals(consumer) &&
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800319 ((ContinuousResource) x.resource()).value() == continuous.value()))
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800320 .collect(GuavaCollectors.toImmutableList());
321
322 if (!continuousConsumerTxMap.replace(continuous.id(), allocation,
323 new ContinuousResourceAllocation(allocation.original(), newAllocations))) {
324 return abortTransaction(tx);
325 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700326 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700327 }
Sho SHIMIZU1e0a34c2015-11-02 16:52:29 -0800328
329 return tx.commit();
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700330 }
331
332 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800333 public boolean isAvailable(Resource resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800334 checkNotNull(resource);
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800335 checkArgument(resource instanceof DiscreteResource || resource instanceof ContinuousResource);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800336
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800337 // check if it's registered or not.
338 Versioned<Set<Resource>> v = childMap.get(resource.parent().get());
339 if (v == null || !v.value().contains(resource)) {
340 return false;
341 }
342
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800343 if (resource instanceof DiscreteResource) {
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800344 // check if already consumed
Sho SHIMIZU4a1e59f2016-01-26 15:27:13 -0800345 return getConsumers((DiscreteResource) resource).isEmpty();
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800346 } else {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800347 ContinuousResource requested = (ContinuousResource) resource;
348 ContinuousResource registered = v.value().stream()
Sho SHIMIZU2d310222016-01-22 11:45:11 -0800349 .filter(c -> c.id().equals(resource.id()))
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800350 .findFirst()
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800351 .map(c -> (ContinuousResource) c)
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800352 .get();
353 if (registered.value() < requested.value()) {
354 // Capacity < requested, can never satisfy
355 return false;
356 }
357 // check if there's enough left
358 return isAvailable(requested);
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800359 }
360 }
361
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800362 private boolean isAvailable(ContinuousResource resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800363 Versioned<ContinuousResourceAllocation> allocation = continuousConsumers.get(resource.id());
364 if (allocation == null) {
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800365 // no allocation (=no consumer) full registered resources available
366 return true;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800367 }
368
369 return hasEnoughResource(allocation.value().original(), resource, allocation.value());
370 }
371
372 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800373 public Collection<Resource> getResources(ResourceConsumer consumer) {
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700374 checkNotNull(consumer);
375
376 // NOTE: getting all entries may become performance bottleneck
377 // TODO: revisit for better backend data structure
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800378 Stream<DiscreteResource> discreteStream = discreteConsumers.entrySet().stream()
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700379 .filter(x -> x.getValue().value().equals(consumer))
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800380 .map(Map.Entry::getKey);
381
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800382 Stream<ContinuousResource> continuousStream = continuousConsumers.values().stream()
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800383 .flatMap(x -> x.value().allocations().stream()
384 .map(y -> Maps.immutableEntry(x.value().original(), y)))
385 .filter(x -> x.getValue().consumer().equals(consumer))
386 .map(x -> x.getKey());
387
388 return Stream.concat(discreteStream, continuousStream).collect(Collectors.toList());
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700389 }
390
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700391 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800392 public Collection<Resource> getChildResources(Resource parent) {
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700393 checkNotNull(parent);
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800394 if (!(parent instanceof DiscreteResource)) {
HIGUCHI Yuta6f828c32016-01-20 18:11:05 -0800395 // only Discrete resource can have child resource
396 return ImmutableList.of();
397 }
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700398
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800399 Versioned<Set<Resource>> children = childMap.get((DiscreteResource) parent);
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700400 if (children == null) {
Sho SHIMIZU2c0ae122016-01-20 13:14:38 -0800401 return ImmutableList.of();
Sho SHIMIZUe7f4f3f2015-10-13 16:27:25 -0700402 }
403
404 return children.value();
405 }
406
407 @Override
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800408 public <T> Collection<Resource> getAllocatedResources(Resource parent, Class<T> cls) {
Sho SHIMIZU1f5e5912015-08-10 17:00:00 -0700409 checkNotNull(parent);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700410 checkNotNull(cls);
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800411 checkArgument(parent instanceof DiscreteResource);
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700412
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800413 Versioned<Set<Resource>> children = childMap.get((DiscreteResource) parent);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700414 if (children == null) {
Sho SHIMIZU2c0ae122016-01-20 13:14:38 -0800415 return ImmutableList.of();
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700416 }
417
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800418 Stream<DiscreteResource> discrete = children.value().stream()
Sho SHIMIZUc9546a32015-11-10 11:22:28 -0800419 .filter(x -> x.last().getClass().equals(cls))
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800420 .filter(x -> x instanceof DiscreteResource)
421 .map(x -> (DiscreteResource) x)
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800422 .filter(discreteConsumers::containsKey);
423
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800424 Stream<ContinuousResource> continuous = children.value().stream()
Sho SHIMIZU2d310222016-01-22 11:45:11 -0800425 .filter(x -> x.id().equals(parent.id().child(cls)))
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800426 .filter(x -> x instanceof ContinuousResource)
427 .map(x -> (ContinuousResource) x)
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800428 .filter(x -> continuousConsumers.containsKey(x.id()))
429 .filter(x -> continuousConsumers.get(x.id()) != null)
430 .filter(x -> !continuousConsumers.get(x.id()).value().allocations().isEmpty());
431
432 return Stream.concat(discrete, continuous).collect(Collectors.toList());
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700433 }
Sho SHIMIZUd29847f2015-08-13 09:10:59 -0700434
435 /**
436 * Abort the transaction.
437 *
438 * @param tx transaction context
439 * @return always false
440 */
441 private boolean abortTransaction(TransactionContext tx) {
442 tx.abort();
443 return false;
444 }
445
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800446 // Appends the specified ResourceAllocation to the existing values stored in the map
447 private boolean appendValue(TransactionalMap<ResourceId, ContinuousResourceAllocation> map,
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800448 ContinuousResource original, ResourceAllocation value) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800449 ContinuousResourceAllocation oldValue = map.putIfAbsent(original.id(),
450 new ContinuousResourceAllocation(original, ImmutableList.of(value)));
451 if (oldValue == null) {
452 return true;
453 }
454
455 if (oldValue.allocations().contains(value)) {
456 // don't write to map because all values are already stored
457 return true;
458 }
459
460 ContinuousResourceAllocation newValue = new ContinuousResourceAllocation(original,
461 ImmutableList.<ResourceAllocation>builder()
462 .addAll(oldValue.allocations())
463 .add(value)
464 .build());
465 return map.replace(original.id(), oldValue, newValue);
466 }
Sho SHIMIZUd29847f2015-08-13 09:10:59 -0700467 /**
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700468 * Appends the values to the existing values associated with the specified key.
Sho SHIMIZU4568c412015-08-21 16:39:07 -0700469 * If the map already has all the given values, appending will not happen.
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700470 *
471 * @param map map holding multiple values for a key
472 * @param key key specifying values
473 * @param values values to be appended
474 * @param <K> type of the key
475 * @param <V> type of the element of the list
476 * @return true if the operation succeeds, false otherwise.
477 */
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800478 private <K, V> boolean appendValues(TransactionalMap<K, Set<V>> map, K key, List<V> values) {
479 Set<V> oldValues = map.putIfAbsent(key, new LinkedHashSet<>(values));
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700480 if (oldValues == null) {
Sho SHIMIZU93a74b32015-11-09 11:48:23 -0800481 return true;
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700482 }
483
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800484 if (oldValues.containsAll(values)) {
Sho SHIMIZU4568c412015-08-21 16:39:07 -0700485 // don't write to map because all values are already stored
486 return true;
487 }
488
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800489 LinkedHashSet<V> newValues = new LinkedHashSet<>(oldValues);
490 newValues.addAll(values);
491 return map.replace(key, oldValues, newValues);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700492 }
493
494 /**
Sho SHIMIZUba1f83b2015-10-14 08:11:20 -0700495 * Removes the values from the existing values associated with the specified key.
Sho SHIMIZU5618ee52015-08-21 17:19:44 -0700496 * If the map doesn't contain the given values, removal will not happen.
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700497 *
498 * @param map map holding multiple values for a key
499 * @param key key specifying values
500 * @param values values to be removed
501 * @param <K> type of the key
502 * @param <V> type of the element of the list
503 * @return true if the operation succeeds, false otherwise
504 */
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800505 private <K, V> boolean removeValues(TransactionalMap<K, Set<V>> map, K key, List<? extends V> values) {
506 Set<V> oldValues = map.putIfAbsent(key, new LinkedHashSet<>());
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700507 if (oldValues == null) {
HIGUCHI Yutadc4394c2016-01-29 15:35:10 -0800508 log.trace("No-Op removing values. key {} did not exist", key);
Sho SHIMIZU93a74b32015-11-09 11:48:23 -0800509 return true;
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700510 }
511
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800512 if (values.stream().allMatch(x -> !oldValues.contains(x))) {
Sho SHIMIZU5618ee52015-08-21 17:19:44 -0700513 // don't write map because none of the values are stored
HIGUCHI Yutadc4394c2016-01-29 15:35:10 -0800514 log.trace("No-Op removing values. key {} did not contain {}", key, values);
Sho SHIMIZU5618ee52015-08-21 17:19:44 -0700515 return true;
516 }
517
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800518 LinkedHashSet<V> newValues = new LinkedHashSet<>(oldValues);
519 newValues.removeAll(values);
520 return map.replace(key, oldValues, newValues);
Sho SHIMIZU2d8a13a2015-08-18 22:37:41 -0700521 }
522
523 /**
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800524 * Returns the resource which has the same key as the key of the specified resource
525 * in the list as a value of the map.
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700526 *
527 * @param map map storing parent - child relationship of resources
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800528 * @param resource resource to be checked for its key
529 * @return the resource which is regarded as the same as the specified resource
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700530 */
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800531 // Naive implementation, which traverses all elements in the list
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800532 private <T extends Resource> Optional<T> lookup(
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800533 TransactionalMap<DiscreteResource, Set<Resource>> map, T resource) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800534 // if it is root, always returns itself
Sho SHIMIZUc9546a32015-11-10 11:22:28 -0800535 if (!resource.parent().isPresent()) {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800536 return Optional.of(resource);
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700537 }
538
Sho SHIMIZU8fa670a2016-01-14 11:17:18 -0800539 Set<Resource> values = map.get(resource.parent().get());
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800540 if (values == null) {
541 return Optional.empty();
542 }
543
544 @SuppressWarnings("unchecked")
545 Optional<T> result = values.stream()
546 .filter(x -> x.id().equals(resource.id()))
547 .map(x -> (T) x)
548 .findFirst();
549 return result;
550 }
551
552 /**
553 * Checks if there is enough resource volume to allocated the requested resource
554 * against the specified resource.
555 *
556 * @param original original resource
557 * @param request requested resource
558 * @param allocation current allocation of the resource
559 * @return true if there is enough resource volume. Otherwise, false.
560 */
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800561 private boolean hasEnoughResource(ContinuousResource original,
562 ContinuousResource request,
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800563 ContinuousResourceAllocation allocation) {
564 if (allocation == null) {
565 return request.value() <= original.value();
566 }
567
568 double allocated = allocation.allocations().stream()
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800569 .filter(x -> x.resource() instanceof ContinuousResource)
570 .map(x -> (ContinuousResource) x.resource())
571 .mapToDouble(ContinuousResource::value)
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800572 .sum();
573 double left = original.value() - allocated;
574 return request.value() <= left;
575 }
576
577 // internal use only
578 private static final class ContinuousResourceAllocation {
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800579 private final ContinuousResource original;
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800580 private final ImmutableList<ResourceAllocation> allocations;
581
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800582 private ContinuousResourceAllocation(ContinuousResource original,
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800583 ImmutableList<ResourceAllocation> allocations) {
584 this.original = original;
585 this.allocations = allocations;
586 }
587
Sho SHIMIZUf33b8932016-01-25 18:43:32 -0800588 private ContinuousResource original() {
Sho SHIMIZU6c9e33a2016-01-07 18:45:27 -0800589 return original;
590 }
591
592 private ImmutableList<ResourceAllocation> allocations() {
593 return allocations;
594 }
Sho SHIMIZUba41fc12015-08-12 15:43:22 -0700595 }
Sho SHIMIZU78ee25c2015-07-16 15:54:14 -0700596}