blob: 65179aed05eb1b2a9549fde13cf733ab7ddb5ec3 [file] [log] [blame]
Thomas Vachuska58de4162015-09-10 16:15:33 -07001/*
2 * Copyright 2015 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 */
Ayaka Koshibee114f042015-05-01 11:43:00 -070016package org.onosproject.store.resource.impl;
17
18import java.util.ArrayList;
19import java.util.Collection;
20import java.util.Collections;
21import java.util.HashMap;
22import java.util.HashSet;
23import java.util.List;
24import java.util.Map;
25import java.util.Set;
26import java.util.stream.Collectors;
27
28import org.apache.felix.scr.annotations.Component;
29import org.apache.felix.scr.annotations.Reference;
30import org.apache.felix.scr.annotations.ReferenceCardinality;
31import org.apache.felix.scr.annotations.Service;
32import org.apache.felix.scr.annotations.Activate;
33import org.apache.felix.scr.annotations.Deactivate;
Sho SHIMIZU6d01d3d2015-05-08 14:08:36 -070034import org.onlab.util.Bandwidth;
Marc De Leenheer1afa2a02015-05-13 09:18:07 -070035import org.onosproject.net.OmsPort;
36import org.onosproject.net.device.DeviceService;
Ayaka Koshibee114f042015-05-01 11:43:00 -070037import org.slf4j.Logger;
Ayaka Koshibee114f042015-05-01 11:43:00 -070038import org.onlab.util.PositionalParameterStringFormatter;
39import org.onosproject.net.Link;
40import org.onosproject.net.LinkKey;
Ayaka Koshibe8117f362015-06-02 13:44:01 -070041import org.onosproject.net.Port;
Ayaka Koshibee114f042015-05-01 11:43:00 -070042import org.onosproject.net.intent.IntentId;
Brian O'Connor6de2e202015-05-21 14:30:41 -070043import org.onosproject.net.resource.link.BandwidthResource;
44import org.onosproject.net.resource.link.BandwidthResourceAllocation;
45import org.onosproject.net.resource.link.LambdaResource;
46import org.onosproject.net.resource.link.LambdaResourceAllocation;
47import org.onosproject.net.resource.link.LinkResourceAllocations;
48import org.onosproject.net.resource.link.LinkResourceEvent;
49import org.onosproject.net.resource.link.LinkResourceStore;
50import org.onosproject.net.resource.link.LinkResourceStoreDelegate;
51import org.onosproject.net.resource.link.MplsLabel;
52import org.onosproject.net.resource.link.MplsLabelResourceAllocation;
Ayaka Koshibee114f042015-05-01 11:43:00 -070053import org.onosproject.net.resource.ResourceAllocation;
54import org.onosproject.net.resource.ResourceAllocationException;
55import org.onosproject.net.resource.ResourceType;
56import org.onosproject.store.AbstractStore;
57import org.onosproject.store.serializers.KryoNamespaces;
58import org.onosproject.store.service.ConsistentMap;
59import org.onosproject.store.service.Serializer;
60import org.onosproject.store.service.StorageService;
61import org.onosproject.store.service.TransactionContext;
62import org.onosproject.store.service.TransactionException;
63import org.onosproject.store.service.TransactionalMap;
64import org.onosproject.store.service.Versioned;
65
66import com.google.common.collect.ImmutableList;
67import com.google.common.collect.ImmutableSet;
68import com.google.common.collect.Sets;
69
70import static com.google.common.base.Preconditions.checkNotNull;
71import static com.google.common.base.Preconditions.checkState;
72import static org.slf4j.LoggerFactory.getLogger;
73import static org.onosproject.net.AnnotationKeys.BANDWIDTH;
Ayaka Koshibee114f042015-05-01 11:43:00 -070074
75/**
76 * Store that manages link resources using Copycat-backed TransactionalMaps.
77 */
Ayaka Koshibe474ef5f2015-05-01 15:24:51 -070078@Component(immediate = true, enabled = true)
Ayaka Koshibee114f042015-05-01 11:43:00 -070079@Service
80public class ConsistentLinkResourceStore extends
81 AbstractStore<LinkResourceEvent, LinkResourceStoreDelegate> implements
82 LinkResourceStore {
83
84 private final Logger log = getLogger(getClass());
85
Sho SHIMIZU6d01d3d2015-05-08 14:08:36 -070086 private static final BandwidthResource DEFAULT_BANDWIDTH = new BandwidthResource(Bandwidth.mbps(1_000));
87 private static final BandwidthResource EMPTY_BW = new BandwidthResource(Bandwidth.bps(0));
Ayaka Koshibee114f042015-05-01 11:43:00 -070088
89 // Smallest non-reserved MPLS label
90 private static final int MIN_UNRESERVED_LABEL = 0x10;
91 // Max non-reserved MPLS label = 239
92 private static final int MAX_UNRESERVED_LABEL = 0xEF;
93
94 // table to store current allocations
95 /** LinkKey -> List<LinkResourceAllocations>. */
Ayaka Koshibebcb02372015-06-01 10:56:42 -070096 private static final String LINK_RESOURCE_ALLOCATIONS = "LinkAllocations";
Ayaka Koshibee114f042015-05-01 11:43:00 -070097
98 /** IntentId -> LinkResourceAllocations. */
Ayaka Koshibebcb02372015-06-01 10:56:42 -070099 private static final String INTENT_ALLOCATIONS = "LinkIntentAllocations";
Ayaka Koshibee114f042015-05-01 11:43:00 -0700100
Sho SHIMIZU200a7392015-07-23 16:28:35 -0700101 private static final Serializer SERIALIZER = Serializer.using(KryoNamespaces.API);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700102
103 // for reading committed values.
104 private ConsistentMap<IntentId, LinkResourceAllocations> intentAllocMap;
105
106 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
107 protected StorageService storageService;
108
109 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Marc De Leenheer1afa2a02015-05-13 09:18:07 -0700110 protected DeviceService deviceService;
111
Ayaka Koshibee114f042015-05-01 11:43:00 -0700112 @Activate
113 public void activate() {
114 intentAllocMap = storageService.<IntentId, LinkResourceAllocations>consistentMapBuilder()
115 .withName(INTENT_ALLOCATIONS)
116 .withSerializer(SERIALIZER)
117 .build();
118 log.info("Started");
119 }
120
121 @Deactivate
122 public void deactivate() {
123 log.info("Stopped");
124 }
125
126 private TransactionalMap<IntentId, LinkResourceAllocations> getIntentAllocs(TransactionContext tx) {
127 return tx.getTransactionalMap(INTENT_ALLOCATIONS, SERIALIZER);
128 }
129
130 private TransactionalMap<LinkKey, List<LinkResourceAllocations>> getLinkAllocs(TransactionContext tx) {
131 return tx.getTransactionalMap(LINK_RESOURCE_ALLOCATIONS, SERIALIZER);
132 }
133
134 private TransactionContext getTxContext() {
135 return storageService.transactionContextBuilder().build();
136 }
137
138 private Set<? extends ResourceAllocation> getResourceCapacity(ResourceType type, Link link) {
139 if (type == ResourceType.BANDWIDTH) {
140 return ImmutableSet.of(getBandwidthResourceCapacity(link));
141 }
142 if (type == ResourceType.LAMBDA) {
143 return getLambdaResourceCapacity(link);
144 }
145 if (type == ResourceType.MPLS_LABEL) {
146 return getMplsResourceCapacity();
147 }
148 return ImmutableSet.of();
149 }
150
151 private Set<LambdaResourceAllocation> getLambdaResourceCapacity(Link link) {
Ayaka Koshibe8117f362015-06-02 13:44:01 -0700152 Port port = deviceService.getPort(link.src().deviceId(), link.src().port());
Sho SHIMIZUa005a6e52015-10-02 15:13:27 -0700153 if (!(port instanceof OmsPort)) {
154 return Collections.emptySet();
155 }
Marc De Leenheer1afa2a02015-05-13 09:18:07 -0700156
Sho SHIMIZUa005a6e52015-10-02 15:13:27 -0700157 OmsPort omsPort = (OmsPort) port;
158 Set<LambdaResourceAllocation> allocations = new HashSet<>();
159 // Assume fixed grid for now
160 for (int i = 0; i < omsPort.totalChannels(); i++) {
161 allocations.add(new LambdaResourceAllocation(LambdaResource.valueOf(i)));
Ayaka Koshibee114f042015-05-01 11:43:00 -0700162 }
163 return allocations;
164 }
165
166 private BandwidthResourceAllocation getBandwidthResourceCapacity(Link link) {
167
168 // if Link annotation exist, use them
169 // if all fails, use DEFAULT_BANDWIDTH
Sho SHIMIZUa890e7c2015-10-02 14:48:13 -0700170 BandwidthResource bandwidth = DEFAULT_BANDWIDTH;
Ayaka Koshibee114f042015-05-01 11:43:00 -0700171 String strBw = link.annotations().value(BANDWIDTH);
Sho SHIMIZUa005a6e52015-10-02 15:13:27 -0700172 if (strBw == null) {
173 return new BandwidthResourceAllocation(bandwidth);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700174 }
175
Sho SHIMIZUa005a6e52015-10-02 15:13:27 -0700176 try {
177 bandwidth = new BandwidthResource(Bandwidth.mbps(Double.parseDouble(strBw)));
178 } catch (NumberFormatException e) {
179 // do nothings, use default bandwidth
180 bandwidth = DEFAULT_BANDWIDTH;
181 }
Ayaka Koshibee114f042015-05-01 11:43:00 -0700182 return new BandwidthResourceAllocation(bandwidth);
183 }
184
185 private Set<MplsLabelResourceAllocation> getMplsResourceCapacity() {
186 Set<MplsLabelResourceAllocation> allocations = new HashSet<>();
187 //Ignoring reserved labels of 0 through 15
188 for (int i = MIN_UNRESERVED_LABEL; i <= MAX_UNRESERVED_LABEL; i++) {
189 allocations.add(new MplsLabelResourceAllocation(MplsLabel
190 .valueOf(i)));
191
192 }
193 return allocations;
194 }
195
196 private Map<ResourceType, Set<? extends ResourceAllocation>> getResourceCapacity(Link link) {
197 Map<ResourceType, Set<? extends ResourceAllocation>> caps = new HashMap<>();
198 for (ResourceType type : ResourceType.values()) {
199 Set<? extends ResourceAllocation> cap = getResourceCapacity(type, link);
Sho SHIMIZUf618cb02015-10-02 14:43:50 -0700200 caps.put(type, cap);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700201 }
202 return caps;
203 }
204
205 @Override
206 public Set<ResourceAllocation> getFreeResources(Link link) {
207 TransactionContext tx = getTxContext();
208
209 tx.begin();
210 try {
211 Map<ResourceType, Set<? extends ResourceAllocation>> freeResources = getFreeResourcesEx(tx, link);
212 Set<ResourceAllocation> allFree = new HashSet<>();
213 freeResources.values().forEach(allFree::addAll);
214 return allFree;
215 } finally {
216 tx.abort();
217 }
218 }
219
220 private Map<ResourceType, Set<? extends ResourceAllocation>> getFreeResourcesEx(TransactionContext tx, Link link) {
221 checkNotNull(tx);
222 checkNotNull(link);
223
224 Map<ResourceType, Set<? extends ResourceAllocation>> free = new HashMap<>();
225 final Map<ResourceType, Set<? extends ResourceAllocation>> caps = getResourceCapacity(link);
226 final Iterable<LinkResourceAllocations> allocations = getAllocations(tx, link);
227
228 for (ResourceType type : ResourceType.values()) {
229 // there should be class/category of resources
230
231 switch (type) {
232 case BANDWIDTH:
233 Set<? extends ResourceAllocation> bw = caps.get(type);
234 if (bw == null || bw.isEmpty()) {
235 bw = Sets.newHashSet(new BandwidthResourceAllocation(EMPTY_BW));
236 }
237
238 BandwidthResourceAllocation cap = (BandwidthResourceAllocation) bw.iterator().next();
239 double freeBw = cap.bandwidth().toDouble();
240
241 // enumerate current allocations, subtracting resources
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700242 double allocatedBw = ImmutableList.copyOf(allocations).stream()
243 .flatMap(x -> x.getResourceAllocation(link).stream())
244 .filter(x -> x instanceof BandwidthResourceAllocation)
245 .map(x -> (BandwidthResourceAllocation) x)
246 .mapToDouble(x -> x.bandwidth().toDouble())
247 .sum();
248 freeBw -= allocatedBw;
Ayaka Koshibee114f042015-05-01 11:43:00 -0700249
Sho SHIMIZU6d01d3d2015-05-08 14:08:36 -0700250 free.put(type, Sets.newHashSet(
251 new BandwidthResourceAllocation(new BandwidthResource(Bandwidth.bps(freeBw)))));
Ayaka Koshibee114f042015-05-01 11:43:00 -0700252 break;
253 case LAMBDA:
254 Set<? extends ResourceAllocation> lmd = caps.get(type);
255 if (lmd == null || lmd.isEmpty()) {
256 // nothing left
257 break;
258 }
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700259 Set<LambdaResourceAllocation> freeL = lmd.stream()
260 .filter(x -> x instanceof LambdaResourceAllocation)
261 .map(x -> (LambdaResourceAllocation) x)
262 .collect(Collectors.toSet());
Ayaka Koshibee114f042015-05-01 11:43:00 -0700263
264 // enumerate current allocations, removing resources
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700265 List<LambdaResourceAllocation> allocatedLambda = ImmutableList.copyOf(allocations).stream()
266 .flatMap(x -> x.getResourceAllocation(link).stream())
267 .filter(x -> x instanceof LambdaResourceAllocation)
268 .map(x -> (LambdaResourceAllocation) x)
269 .collect(Collectors.toList());
270 freeL.removeAll(allocatedLambda);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700271
272 free.put(type, freeL);
273 break;
274 case MPLS_LABEL:
275 Set<? extends ResourceAllocation> mpls = caps.get(type);
276 if (mpls == null || mpls.isEmpty()) {
277 // nothing left
278 break;
279 }
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700280 Set<MplsLabelResourceAllocation> freeLabel = mpls.stream()
281 .filter(x -> x instanceof MplsLabelResourceAllocation)
282 .map(x -> (MplsLabelResourceAllocation) x)
283 .collect(Collectors.toSet());
Ayaka Koshibee114f042015-05-01 11:43:00 -0700284
285 // enumerate current allocations, removing resources
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700286 List<MplsLabelResourceAllocation> allocatedLabel = ImmutableList.copyOf(allocations).stream()
287 .flatMap(x -> x.getResourceAllocation(link).stream())
288 .filter(x -> x instanceof MplsLabelResourceAllocation)
289 .map(x -> (MplsLabelResourceAllocation) x)
290 .collect(Collectors.toList());
291 freeLabel.removeAll(allocatedLabel);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700292
293 free.put(type, freeLabel);
294 break;
295 default:
296 log.debug("unsupported ResourceType {}", type);
297 break;
298 }
299 }
300 return free;
301 }
302
303 @Override
304 public void allocateResources(LinkResourceAllocations allocations) {
305 checkNotNull(allocations);
306 TransactionContext tx = getTxContext();
307
308 tx.begin();
309 try {
310 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
311 intentAllocs.put(allocations.intentId(), allocations);
312 allocations.links().forEach(link -> allocateLinkResource(tx, link, allocations));
313 tx.commit();
314 } catch (Exception e) {
315 log.error("Exception thrown, rolling back", e);
316 tx.abort();
317 throw e;
318 }
319 }
320
321 private void allocateLinkResource(TransactionContext tx, Link link,
322 LinkResourceAllocations allocations) {
323 // requested resources
324 Set<ResourceAllocation> reqs = allocations.getResourceAllocation(link);
325 Map<ResourceType, Set<? extends ResourceAllocation>> available = getFreeResourcesEx(tx, link);
326 for (ResourceAllocation req : reqs) {
327 Set<? extends ResourceAllocation> avail = available.get(req.type());
328 if (req instanceof BandwidthResourceAllocation) {
329 // check if allocation should be accepted
330 if (avail.isEmpty()) {
331 checkState(!avail.isEmpty(),
332 "There's no Bandwidth resource on %s?",
333 link);
334 }
335 BandwidthResourceAllocation bw = (BandwidthResourceAllocation) avail.iterator().next();
336 double bwLeft = bw.bandwidth().toDouble();
337 BandwidthResourceAllocation bwReq = ((BandwidthResourceAllocation) req);
338 bwLeft -= bwReq.bandwidth().toDouble();
339 if (bwLeft < 0) {
340 throw new ResourceAllocationException(
341 PositionalParameterStringFormatter.format(
342 "Unable to allocate bandwidth for link {} "
343 + " requested amount is {} current allocation is {}",
344 link,
345 bwReq.bandwidth().toDouble(),
346 bw));
347 }
348 } else if (req instanceof LambdaResourceAllocation) {
349 LambdaResourceAllocation lambdaAllocation = (LambdaResourceAllocation) req;
350 // check if allocation should be accepted
351 if (!avail.contains(req)) {
352 // requested lambda was not available
353 throw new ResourceAllocationException(
354 PositionalParameterStringFormatter.format(
355 "Unable to allocate lambda for link {} lambda is {}",
356 link,
357 lambdaAllocation.lambda().toInt()));
358 }
359 } else if (req instanceof MplsLabelResourceAllocation) {
360 MplsLabelResourceAllocation mplsAllocation = (MplsLabelResourceAllocation) req;
361 if (!avail.contains(req)) {
362 throw new ResourceAllocationException(
363 PositionalParameterStringFormatter
364 .format("Unable to allocate MPLS label for link "
365 + "{} MPLS label is {}",
366 link,
367 mplsAllocation
368 .mplsLabel()
369 .toString()));
370 }
371 }
372 }
373 // all requests allocatable => add allocation
374 final LinkKey linkKey = LinkKey.linkKey(link);
375 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
376 List<LinkResourceAllocations> before = linkAllocs.get(linkKey);
377 if (before == null) {
378 List<LinkResourceAllocations> after = new ArrayList<>();
379 after.add(allocations);
380 before = linkAllocs.putIfAbsent(linkKey, after);
381 if (before != null) {
382 // concurrent allocation detected, retry transaction : is this needed?
383 log.warn("Concurrent Allocation, retrying");
384 throw new TransactionException();
385 }
386 } else {
387 List<LinkResourceAllocations> after = new ArrayList<>(before.size() + 1);
388 after.addAll(before);
389 after.add(allocations);
390 linkAllocs.replace(linkKey, before, after);
391 }
392 }
393
394 @Override
395 public LinkResourceEvent releaseResources(LinkResourceAllocations allocations) {
396 checkNotNull(allocations);
397
398 final IntentId intentId = allocations.intentId();
399 final Collection<Link> links = allocations.links();
400 boolean success = false;
401 do {
402 TransactionContext tx = getTxContext();
403 tx.begin();
404 try {
405 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
406 intentAllocs.remove(intentId);
407
408 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
409 links.forEach(link -> {
410 final LinkKey linkId = LinkKey.linkKey(link);
411
412 List<LinkResourceAllocations> before = linkAllocs.get(linkId);
413 if (before == null || before.isEmpty()) {
414 // something is wrong, but it is already freed
415 log.warn("There was no resource left to release on {}", linkId);
416 return;
417 }
418 List<LinkResourceAllocations> after = new ArrayList<>(before);
419 after.remove(allocations);
420 linkAllocs.replace(linkId, before, after);
421 });
422 tx.commit();
423 success = true;
424 } catch (TransactionException e) {
425 log.debug("Transaction failed, retrying", e);
426 tx.abort();
427 } catch (Exception e) {
428 log.error("Exception thrown during releaseResource {}", allocations, e);
429 tx.abort();
430 throw e;
431 }
432 } while (!success);
433
434 // Issue events to force recompilation of intents.
435 final List<LinkResourceAllocations> releasedResources = ImmutableList.of(allocations);
436 return new LinkResourceEvent(
437 LinkResourceEvent.Type.ADDITIONAL_RESOURCES_AVAILABLE,
438 releasedResources);
439
440 }
441
442 @Override
443 public LinkResourceAllocations getAllocations(IntentId intentId) {
444 checkNotNull(intentId);
445 Versioned<LinkResourceAllocations> alloc = null;
446 try {
447 alloc = intentAllocMap.get(intentId);
448 } catch (Exception e) {
449 log.warn("Could not read resource allocation information", e);
450 }
451 return alloc == null ? null : alloc.value();
452 }
453
454 @Override
455 public Iterable<LinkResourceAllocations> getAllocations(Link link) {
456 checkNotNull(link);
457 TransactionContext tx = getTxContext();
458 Iterable<LinkResourceAllocations> res = null;
459 tx.begin();
460 try {
461 res = getAllocations(tx, link);
462 } finally {
463 tx.abort();
464 }
465 return res == null ? Collections.emptyList() : res;
466 }
467
468 @Override
469 public Iterable<LinkResourceAllocations> getAllocations() {
470 try {
471 Set<LinkResourceAllocations> allocs =
472 intentAllocMap.values().stream().map(Versioned::value).collect(Collectors.toSet());
473 return ImmutableSet.copyOf(allocs);
474 } catch (Exception e) {
475 log.warn("Could not read resource allocation information", e);
476 }
477 return ImmutableSet.of();
478 }
479
480 private Iterable<LinkResourceAllocations> getAllocations(TransactionContext tx, Link link) {
481 checkNotNull(tx);
482 checkNotNull(link);
483 final LinkKey key = LinkKey.linkKey(link);
484 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700485
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700486 List<LinkResourceAllocations> res = linkAllocs.get(key);
487 if (res != null) {
488 return res;
Ayaka Koshibee114f042015-05-01 11:43:00 -0700489 }
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700490
491 res = linkAllocs.putIfAbsent(key, new ArrayList<>());
492 if (res == null) {
493 return Collections.emptyList();
494 } else {
495 return res;
496 }
Ayaka Koshibee114f042015-05-01 11:43:00 -0700497 }
498
499}