2 * Copyright 2015 Open Networking Laboratory
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onosproject.store.resource.impl;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
26 import java.util.stream.Collectors;
28 import org.apache.felix.scr.annotations.Component;
29 import org.apache.felix.scr.annotations.Reference;
30 import org.apache.felix.scr.annotations.ReferenceCardinality;
31 import org.apache.felix.scr.annotations.Service;
32 import org.apache.felix.scr.annotations.Activate;
33 import org.apache.felix.scr.annotations.Deactivate;
34 import org.onlab.util.Bandwidth;
35 import org.onosproject.net.OmsPort;
36 import org.onosproject.net.device.DeviceService;
37 import org.slf4j.Logger;
38 import org.onlab.util.PositionalParameterStringFormatter;
39 import org.onosproject.net.Link;
40 import org.onosproject.net.LinkKey;
41 import org.onosproject.net.Port;
42 import org.onosproject.net.intent.IntentId;
43 import org.onosproject.net.resource.link.BandwidthResource;
44 import org.onosproject.net.resource.link.BandwidthResourceAllocation;
45 import org.onosproject.net.resource.link.LambdaResource;
46 import org.onosproject.net.resource.link.LambdaResourceAllocation;
47 import org.onosproject.net.resource.link.LinkResourceAllocations;
48 import org.onosproject.net.resource.link.LinkResourceEvent;
49 import org.onosproject.net.resource.link.LinkResourceStore;
50 import org.onosproject.net.resource.link.LinkResourceStoreDelegate;
51 import org.onosproject.net.resource.link.MplsLabel;
52 import org.onosproject.net.resource.link.MplsLabelResourceAllocation;
53 import org.onosproject.net.resource.ResourceAllocation;
54 import org.onosproject.net.resource.ResourceAllocationException;
55 import org.onosproject.net.resource.ResourceType;
56 import org.onosproject.store.AbstractStore;
57 import org.onosproject.store.serializers.KryoNamespaces;
58 import org.onosproject.store.service.ConsistentMap;
59 import org.onosproject.store.service.Serializer;
60 import org.onosproject.store.service.StorageService;
61 import org.onosproject.store.service.TransactionContext;
62 import org.onosproject.store.service.TransactionalMap;
63 import org.onosproject.store.service.Versioned;
65 import com.google.common.collect.ImmutableList;
66 import com.google.common.collect.ImmutableSet;
67 import com.google.common.collect.Sets;
69 import static com.google.common.base.Preconditions.checkNotNull;
70 import static org.slf4j.LoggerFactory.getLogger;
71 import static org.onosproject.net.AnnotationKeys.BANDWIDTH;
74 * Store that manages link resources using Copycat-backed TransactionalMaps.
76 @Component(immediate = true, enabled = true)
78 public class ConsistentLinkResourceStore extends
79 AbstractStore<LinkResourceEvent, LinkResourceStoreDelegate> implements
82 private final Logger log = getLogger(getClass());
84 private static final BandwidthResource DEFAULT_BANDWIDTH = new BandwidthResource(Bandwidth.mbps(1_000));
85 private static final BandwidthResource EMPTY_BW = new BandwidthResource(Bandwidth.bps(0));
87 // Smallest non-reserved MPLS label
88 private static final int MIN_UNRESERVED_LABEL = 0x10;
89 // Max non-reserved MPLS label = 239
90 private static final int MAX_UNRESERVED_LABEL = 0xEF;
92 // table to store current allocations
93 /** LinkKey -> List<LinkResourceAllocations>. */
94 private static final String LINK_RESOURCE_ALLOCATIONS = "LinkAllocations";
96 /** IntentId -> LinkResourceAllocations. */
97 private static final String INTENT_ALLOCATIONS = "LinkIntentAllocations";
99 private static final Serializer SERIALIZER = Serializer.using(KryoNamespaces.API);
101 // for reading committed values.
102 private ConsistentMap<IntentId, LinkResourceAllocations> intentAllocMap;
104 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
105 protected StorageService storageService;
107 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
108 protected DeviceService deviceService;
111 public void activate() {
112 intentAllocMap = storageService.<IntentId, LinkResourceAllocations>consistentMapBuilder()
113 .withName(INTENT_ALLOCATIONS)
114 .withSerializer(SERIALIZER)
120 public void deactivate() {
124 private TransactionalMap<IntentId, LinkResourceAllocations> getIntentAllocs(TransactionContext tx) {
125 return tx.getTransactionalMap(INTENT_ALLOCATIONS, SERIALIZER);
128 private TransactionalMap<LinkKey, List<LinkResourceAllocations>> getLinkAllocs(TransactionContext tx) {
129 return tx.getTransactionalMap(LINK_RESOURCE_ALLOCATIONS, SERIALIZER);
132 private TransactionContext getTxContext() {
133 return storageService.transactionContextBuilder().build();
136 private Set<ResourceAllocation> getResourceCapacity(ResourceType type, Link link) {
139 return ImmutableSet.of(getBandwidthResourceCapacity(link));
141 return getLambdaResourceCapacity(link);
143 return getMplsResourceCapacity();
145 return ImmutableSet.of();
149 private Set<ResourceAllocation> getLambdaResourceCapacity(Link link) {
150 Port port = deviceService.getPort(link.src().deviceId(), link.src().port());
151 if (!(port instanceof OmsPort)) {
152 return Collections.emptySet();
155 OmsPort omsPort = (OmsPort) port;
156 Set<ResourceAllocation> allocations = new HashSet<>();
157 // Assume fixed grid for now
158 for (int i = 0; i < omsPort.totalChannels(); i++) {
159 allocations.add(new LambdaResourceAllocation(LambdaResource.valueOf(i)));
164 private BandwidthResourceAllocation getBandwidthResourceCapacity(Link link) {
166 // if Link annotation exist, use them
167 // if all fails, use DEFAULT_BANDWIDTH
168 BandwidthResource bandwidth = DEFAULT_BANDWIDTH;
169 String strBw = link.annotations().value(BANDWIDTH);
171 return new BandwidthResourceAllocation(bandwidth);
175 bandwidth = new BandwidthResource(Bandwidth.mbps(Double.parseDouble(strBw)));
176 } catch (NumberFormatException e) {
177 // do nothings, use default bandwidth
178 bandwidth = DEFAULT_BANDWIDTH;
180 return new BandwidthResourceAllocation(bandwidth);
183 private Set<ResourceAllocation> getMplsResourceCapacity() {
184 Set<ResourceAllocation> allocations = new HashSet<>();
185 //Ignoring reserved labels of 0 through 15
186 for (int i = MIN_UNRESERVED_LABEL; i <= MAX_UNRESERVED_LABEL; i++) {
187 allocations.add(new MplsLabelResourceAllocation(MplsLabel
194 private Map<ResourceType, Set<ResourceAllocation>> getResourceCapacity(Link link) {
195 Map<ResourceType, Set<ResourceAllocation>> caps = new HashMap<>();
196 for (ResourceType type : ResourceType.values()) {
197 Set<ResourceAllocation> cap = getResourceCapacity(type, link);
204 public Set<ResourceAllocation> getFreeResources(Link link) {
205 TransactionContext tx = getTxContext();
209 Map<ResourceType, Set<ResourceAllocation>> freeResources = getFreeResourcesEx(tx, link);
210 return freeResources.values().stream()
211 .flatMap(Collection::stream)
212 .collect(Collectors.toSet());
218 private Map<ResourceType, Set<ResourceAllocation>> getFreeResourcesEx(TransactionContext tx, Link link) {
222 Map<ResourceType, Set<ResourceAllocation>> free = new HashMap<>();
223 final Map<ResourceType, Set<ResourceAllocation>> caps = getResourceCapacity(link);
224 final List<LinkResourceAllocations> allocations = ImmutableList.copyOf(getAllocations(tx, link));
226 Set<ResourceAllocation> bw = caps.get(ResourceType.BANDWIDTH);
227 Set<ResourceAllocation> value = getFreeBandwidthResources(link, bw, allocations);
228 free.put(ResourceType.BANDWIDTH, value);
230 Set<ResourceAllocation> lmd = caps.get(ResourceType.LAMBDA);
231 Set<ResourceAllocation> freeL = getFreeResources(link, lmd, allocations,
232 LambdaResourceAllocation.class);
233 free.put(ResourceType.LAMBDA, freeL);
235 Set<ResourceAllocation> mpls = caps.get(ResourceType.MPLS_LABEL);
236 Set<ResourceAllocation> freeLabel = getFreeResources(link, mpls, allocations,
237 MplsLabelResourceAllocation.class);
238 free.put(ResourceType.MPLS_LABEL, freeLabel);
243 private Set<ResourceAllocation> getFreeBandwidthResources(Link link, Set<ResourceAllocation> bw,
244 List<LinkResourceAllocations> allocations) {
245 if (bw == null || bw.isEmpty()) {
246 bw = Sets.newHashSet(new BandwidthResourceAllocation(EMPTY_BW));
249 BandwidthResourceAllocation cap = (BandwidthResourceAllocation) bw.iterator().next();
250 double freeBw = cap.bandwidth().toDouble();
252 // enumerate current allocations, subtracting resources
253 double allocatedBw = allocations.stream()
254 .flatMap(x -> x.getResourceAllocation(link).stream())
255 .filter(x -> x instanceof BandwidthResourceAllocation)
256 .map(x -> (BandwidthResourceAllocation) x)
257 .mapToDouble(x -> x.bandwidth().toDouble())
259 freeBw -= allocatedBw;
260 return Sets.newHashSet(
261 new BandwidthResourceAllocation(new BandwidthResource(Bandwidth.bps(freeBw))));
264 private Set<ResourceAllocation> getFreeResources(Link link,
265 Set<ResourceAllocation> resources,
266 List<LinkResourceAllocations> allocations,
267 Class<? extends ResourceAllocation> cls) {
268 if (resources == null || resources.isEmpty()) {
270 return Collections.emptySet();
272 Set<ResourceAllocation> freeL = resources.stream()
273 .filter(cls::isInstance)
274 .collect(Collectors.toSet());
276 // enumerate current allocations, removing resources
277 List<ResourceAllocation> allocated = allocations.stream()
278 .flatMap(x -> x.getResourceAllocation(link).stream())
279 .filter(cls::isInstance)
280 .collect(Collectors.toList());
281 freeL.removeAll(allocated);
286 public void allocateResources(LinkResourceAllocations allocations) {
287 checkNotNull(allocations);
288 TransactionContext tx = getTxContext();
292 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
293 intentAllocs.put(allocations.intentId(), allocations);
294 allocations.links().forEach(link -> allocateLinkResource(tx, link, allocations));
296 } catch (ResourceAllocationException e) {
297 log.error("Exception thrown, rolling back", e);
299 } catch (Exception e) {
300 log.error("Exception thrown, rolling back", e);
306 private void allocateLinkResource(TransactionContext tx, Link link,
307 LinkResourceAllocations allocations) {
308 // requested resources
309 Set<ResourceAllocation> reqs = allocations.getResourceAllocation(link);
310 Map<ResourceType, Set<ResourceAllocation>> available = getFreeResourcesEx(tx, link);
311 for (ResourceAllocation req : reqs) {
312 Set<ResourceAllocation> avail = available.get(req.type());
313 if (req instanceof BandwidthResourceAllocation) {
314 // check if allocation should be accepted
315 if (avail.isEmpty()) {
316 throw new ResourceAllocationException(String.format("There's no Bandwidth resource on %s?", link));
318 BandwidthResourceAllocation bw = (BandwidthResourceAllocation) avail.iterator().next();
319 double bwLeft = bw.bandwidth().toDouble();
320 BandwidthResourceAllocation bwReq = ((BandwidthResourceAllocation) req);
321 bwLeft -= bwReq.bandwidth().toDouble();
323 throw new ResourceAllocationException(
324 PositionalParameterStringFormatter.format(
325 "Unable to allocate bandwidth for link {} "
326 + " requested amount is {} current allocation is {}",
328 bwReq.bandwidth().toDouble(),
331 } else if (req instanceof LambdaResourceAllocation) {
332 LambdaResourceAllocation lambdaAllocation = (LambdaResourceAllocation) req;
333 // check if allocation should be accepted
334 if (!avail.contains(req)) {
335 // requested lambda was not available
336 throw new ResourceAllocationException(
337 PositionalParameterStringFormatter.format(
338 "Unable to allocate lambda for link {} lambda is {}",
340 lambdaAllocation.lambda().toInt()));
342 } else if (req instanceof MplsLabelResourceAllocation) {
343 MplsLabelResourceAllocation mplsAllocation = (MplsLabelResourceAllocation) req;
344 if (!avail.contains(req)) {
345 throw new ResourceAllocationException(
346 PositionalParameterStringFormatter
347 .format("Unable to allocate MPLS label for link "
348 + "{} MPLS label is {}",
356 // all requests allocatable => add allocation
357 final LinkKey linkKey = LinkKey.linkKey(link);
358 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
359 List<LinkResourceAllocations> before = linkAllocs.get(linkKey);
360 if (before == null) {
361 List<LinkResourceAllocations> after = new ArrayList<>();
362 after.add(allocations);
363 linkAllocs.putIfAbsent(linkKey, after);
365 boolean overlapped = before.stream()
366 .flatMap(x -> x.getResourceAllocation(link).stream())
367 .anyMatch(x -> allocations.getResourceAllocation(link).contains(x));
369 throw new ResourceAllocationException(
370 String.format("Resource allocations are overlapped between %s and %s",
374 List<LinkResourceAllocations> after = new ArrayList<>(before.size() + 1);
375 after.addAll(before);
376 after.add(allocations);
377 linkAllocs.replace(linkKey, before, after);
382 public LinkResourceEvent releaseResources(LinkResourceAllocations allocations) {
383 checkNotNull(allocations);
385 final IntentId intentId = allocations.intentId();
386 final Collection<Link> links = allocations.links();
387 boolean success = false;
389 TransactionContext tx = getTxContext();
392 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
393 intentAllocs.remove(intentId);
395 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
396 links.forEach(link -> {
397 final LinkKey linkId = LinkKey.linkKey(link);
399 List<LinkResourceAllocations> before = linkAllocs.get(linkId);
400 if (before == null || before.isEmpty()) {
401 // something is wrong, but it is already freed
402 log.warn("There was no resource left to release on {}", linkId);
405 List<LinkResourceAllocations> after = new ArrayList<>(before);
406 after.remove(allocations);
407 linkAllocs.replace(linkId, before, after);
409 success = tx.commit();
410 } catch (Exception e) {
411 log.error("Exception thrown during releaseResource {}", allocations, e);
417 // Issue events to force recompilation of intents.
418 final List<LinkResourceAllocations> releasedResources = ImmutableList.of(allocations);
419 return new LinkResourceEvent(
420 LinkResourceEvent.Type.ADDITIONAL_RESOURCES_AVAILABLE,
426 public LinkResourceAllocations getAllocations(IntentId intentId) {
427 checkNotNull(intentId);
428 Versioned<LinkResourceAllocations> alloc = null;
430 alloc = intentAllocMap.get(intentId);
431 } catch (Exception e) {
432 log.warn("Could not read resource allocation information", e);
434 return alloc == null ? null : alloc.value();
438 public Iterable<LinkResourceAllocations> getAllocations(Link link) {
440 TransactionContext tx = getTxContext();
441 Iterable<LinkResourceAllocations> res = null;
444 res = getAllocations(tx, link);
448 return res == null ? Collections.emptyList() : res;
452 public Iterable<LinkResourceAllocations> getAllocations() {
454 Set<LinkResourceAllocations> allocs =
455 intentAllocMap.values().stream().map(Versioned::value).collect(Collectors.toSet());
456 return ImmutableSet.copyOf(allocs);
457 } catch (Exception e) {
458 log.warn("Could not read resource allocation information", e);
460 return ImmutableSet.of();
463 private Iterable<LinkResourceAllocations> getAllocations(TransactionContext tx, Link link) {
466 final LinkKey key = LinkKey.linkKey(link);
467 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
469 List<LinkResourceAllocations> res = linkAllocs.get(key);
474 res = linkAllocs.putIfAbsent(key, new ArrayList<>());
476 return Collections.emptyList();