blob: 798bb75b941e74caa4b469755d6261cbb555bcb4 [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) {
152 Set<LambdaResourceAllocation> allocations = new HashSet<>();
Ayaka Koshibe8117f362015-06-02 13:44:01 -0700153 Port port = deviceService.getPort(link.src().deviceId(), link.src().port());
154 if (port instanceof OmsPort) {
155 OmsPort omsPort = (OmsPort) port;
Marc De Leenheer1afa2a02015-05-13 09:18:07 -0700156
Ayaka Koshibe8117f362015-06-02 13:44:01 -0700157 // Assume fixed grid for now
158 for (int i = 0; i < omsPort.totalChannels(); i++) {
159 allocations.add(new LambdaResourceAllocation(LambdaResource.valueOf(i)));
160 }
Ayaka Koshibee114f042015-05-01 11:43:00 -0700161 }
162 return allocations;
163 }
164
165 private BandwidthResourceAllocation getBandwidthResourceCapacity(Link link) {
166
167 // if Link annotation exist, use them
168 // if all fails, use DEFAULT_BANDWIDTH
Sho SHIMIZU63feca72015-05-07 10:44:25 -0700169 BandwidthResource bandwidth = null;
Ayaka Koshibee114f042015-05-01 11:43:00 -0700170 String strBw = link.annotations().value(BANDWIDTH);
171 if (strBw != null) {
172 try {
Sho SHIMIZU6d01d3d2015-05-08 14:08:36 -0700173 bandwidth = new BandwidthResource(Bandwidth.mbps(Double.parseDouble(strBw)));
Ayaka Koshibee114f042015-05-01 11:43:00 -0700174 } catch (NumberFormatException e) {
175 // do nothings
176 bandwidth = null;
177 }
178 }
179
180 if (bandwidth == null) {
181 // fall back, use fixed default
182 bandwidth = DEFAULT_BANDWIDTH;
183 }
184 return new BandwidthResourceAllocation(bandwidth);
185 }
186
187 private Set<MplsLabelResourceAllocation> getMplsResourceCapacity() {
188 Set<MplsLabelResourceAllocation> allocations = new HashSet<>();
189 //Ignoring reserved labels of 0 through 15
190 for (int i = MIN_UNRESERVED_LABEL; i <= MAX_UNRESERVED_LABEL; i++) {
191 allocations.add(new MplsLabelResourceAllocation(MplsLabel
192 .valueOf(i)));
193
194 }
195 return allocations;
196 }
197
198 private Map<ResourceType, Set<? extends ResourceAllocation>> getResourceCapacity(Link link) {
199 Map<ResourceType, Set<? extends ResourceAllocation>> caps = new HashMap<>();
200 for (ResourceType type : ResourceType.values()) {
201 Set<? extends ResourceAllocation> cap = getResourceCapacity(type, link);
202 if (cap != null) {
203 caps.put(type, cap);
204 }
205 }
206 return caps;
207 }
208
209 @Override
210 public Set<ResourceAllocation> getFreeResources(Link link) {
211 TransactionContext tx = getTxContext();
212
213 tx.begin();
214 try {
215 Map<ResourceType, Set<? extends ResourceAllocation>> freeResources = getFreeResourcesEx(tx, link);
216 Set<ResourceAllocation> allFree = new HashSet<>();
217 freeResources.values().forEach(allFree::addAll);
218 return allFree;
219 } finally {
220 tx.abort();
221 }
222 }
223
224 private Map<ResourceType, Set<? extends ResourceAllocation>> getFreeResourcesEx(TransactionContext tx, Link link) {
225 checkNotNull(tx);
226 checkNotNull(link);
227
228 Map<ResourceType, Set<? extends ResourceAllocation>> free = new HashMap<>();
229 final Map<ResourceType, Set<? extends ResourceAllocation>> caps = getResourceCapacity(link);
230 final Iterable<LinkResourceAllocations> allocations = getAllocations(tx, link);
231
232 for (ResourceType type : ResourceType.values()) {
233 // there should be class/category of resources
234
235 switch (type) {
236 case BANDWIDTH:
237 Set<? extends ResourceAllocation> bw = caps.get(type);
238 if (bw == null || bw.isEmpty()) {
239 bw = Sets.newHashSet(new BandwidthResourceAllocation(EMPTY_BW));
240 }
241
242 BandwidthResourceAllocation cap = (BandwidthResourceAllocation) bw.iterator().next();
243 double freeBw = cap.bandwidth().toDouble();
244
245 // enumerate current allocations, subtracting resources
246 for (LinkResourceAllocations alloc : allocations) {
247 Set<ResourceAllocation> types = alloc.getResourceAllocation(link);
248 for (ResourceAllocation a : types) {
249 if (a instanceof BandwidthResourceAllocation) {
250 BandwidthResourceAllocation bwA = (BandwidthResourceAllocation) a;
251 freeBw -= bwA.bandwidth().toDouble();
252 }
253 }
254 }
255
Sho SHIMIZU6d01d3d2015-05-08 14:08:36 -0700256 free.put(type, Sets.newHashSet(
257 new BandwidthResourceAllocation(new BandwidthResource(Bandwidth.bps(freeBw)))));
Ayaka Koshibee114f042015-05-01 11:43:00 -0700258 break;
259 case LAMBDA:
260 Set<? extends ResourceAllocation> lmd = caps.get(type);
261 if (lmd == null || lmd.isEmpty()) {
262 // nothing left
263 break;
264 }
265 Set<LambdaResourceAllocation> freeL = new HashSet<>();
266 for (ResourceAllocation r : lmd) {
267 if (r instanceof LambdaResourceAllocation) {
268 freeL.add((LambdaResourceAllocation) r);
269 }
270 }
271
272 // enumerate current allocations, removing resources
273 for (LinkResourceAllocations alloc : allocations) {
274 Set<ResourceAllocation> types = alloc.getResourceAllocation(link);
275 for (ResourceAllocation a : types) {
276 if (a instanceof LambdaResourceAllocation) {
277 freeL.remove(a);
278 }
279 }
280 }
281
282 free.put(type, freeL);
283 break;
284 case MPLS_LABEL:
285 Set<? extends ResourceAllocation> mpls = caps.get(type);
286 if (mpls == null || mpls.isEmpty()) {
287 // nothing left
288 break;
289 }
290 Set<MplsLabelResourceAllocation> freeLabel = new HashSet<>();
291 for (ResourceAllocation r : mpls) {
292 if (r instanceof MplsLabelResourceAllocation) {
293 freeLabel.add((MplsLabelResourceAllocation) r);
294 }
295 }
296
297 // enumerate current allocations, removing resources
298 for (LinkResourceAllocations alloc : allocations) {
299 Set<ResourceAllocation> types = alloc.getResourceAllocation(link);
300 for (ResourceAllocation a : types) {
301 if (a instanceof MplsLabelResourceAllocation) {
302 freeLabel.remove(a);
303 }
304 }
305 }
306
307 free.put(type, freeLabel);
308 break;
309 default:
310 log.debug("unsupported ResourceType {}", type);
311 break;
312 }
313 }
314 return free;
315 }
316
317 @Override
318 public void allocateResources(LinkResourceAllocations allocations) {
319 checkNotNull(allocations);
320 TransactionContext tx = getTxContext();
321
322 tx.begin();
323 try {
324 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
325 intentAllocs.put(allocations.intentId(), allocations);
326 allocations.links().forEach(link -> allocateLinkResource(tx, link, allocations));
327 tx.commit();
328 } catch (Exception e) {
329 log.error("Exception thrown, rolling back", e);
330 tx.abort();
331 throw e;
332 }
333 }
334
335 private void allocateLinkResource(TransactionContext tx, Link link,
336 LinkResourceAllocations allocations) {
337 // requested resources
338 Set<ResourceAllocation> reqs = allocations.getResourceAllocation(link);
339 Map<ResourceType, Set<? extends ResourceAllocation>> available = getFreeResourcesEx(tx, link);
340 for (ResourceAllocation req : reqs) {
341 Set<? extends ResourceAllocation> avail = available.get(req.type());
342 if (req instanceof BandwidthResourceAllocation) {
343 // check if allocation should be accepted
344 if (avail.isEmpty()) {
345 checkState(!avail.isEmpty(),
346 "There's no Bandwidth resource on %s?",
347 link);
348 }
349 BandwidthResourceAllocation bw = (BandwidthResourceAllocation) avail.iterator().next();
350 double bwLeft = bw.bandwidth().toDouble();
351 BandwidthResourceAllocation bwReq = ((BandwidthResourceAllocation) req);
352 bwLeft -= bwReq.bandwidth().toDouble();
353 if (bwLeft < 0) {
354 throw new ResourceAllocationException(
355 PositionalParameterStringFormatter.format(
356 "Unable to allocate bandwidth for link {} "
357 + " requested amount is {} current allocation is {}",
358 link,
359 bwReq.bandwidth().toDouble(),
360 bw));
361 }
362 } else if (req instanceof LambdaResourceAllocation) {
363 LambdaResourceAllocation lambdaAllocation = (LambdaResourceAllocation) req;
364 // check if allocation should be accepted
365 if (!avail.contains(req)) {
366 // requested lambda was not available
367 throw new ResourceAllocationException(
368 PositionalParameterStringFormatter.format(
369 "Unable to allocate lambda for link {} lambda is {}",
370 link,
371 lambdaAllocation.lambda().toInt()));
372 }
373 } else if (req instanceof MplsLabelResourceAllocation) {
374 MplsLabelResourceAllocation mplsAllocation = (MplsLabelResourceAllocation) req;
375 if (!avail.contains(req)) {
376 throw new ResourceAllocationException(
377 PositionalParameterStringFormatter
378 .format("Unable to allocate MPLS label for link "
379 + "{} MPLS label is {}",
380 link,
381 mplsAllocation
382 .mplsLabel()
383 .toString()));
384 }
385 }
386 }
387 // all requests allocatable => add allocation
388 final LinkKey linkKey = LinkKey.linkKey(link);
389 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
390 List<LinkResourceAllocations> before = linkAllocs.get(linkKey);
391 if (before == null) {
392 List<LinkResourceAllocations> after = new ArrayList<>();
393 after.add(allocations);
394 before = linkAllocs.putIfAbsent(linkKey, after);
395 if (before != null) {
396 // concurrent allocation detected, retry transaction : is this needed?
397 log.warn("Concurrent Allocation, retrying");
398 throw new TransactionException();
399 }
400 } else {
401 List<LinkResourceAllocations> after = new ArrayList<>(before.size() + 1);
402 after.addAll(before);
403 after.add(allocations);
404 linkAllocs.replace(linkKey, before, after);
405 }
406 }
407
408 @Override
409 public LinkResourceEvent releaseResources(LinkResourceAllocations allocations) {
410 checkNotNull(allocations);
411
412 final IntentId intentId = allocations.intentId();
413 final Collection<Link> links = allocations.links();
414 boolean success = false;
415 do {
416 TransactionContext tx = getTxContext();
417 tx.begin();
418 try {
419 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
420 intentAllocs.remove(intentId);
421
422 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
423 links.forEach(link -> {
424 final LinkKey linkId = LinkKey.linkKey(link);
425
426 List<LinkResourceAllocations> before = linkAllocs.get(linkId);
427 if (before == null || before.isEmpty()) {
428 // something is wrong, but it is already freed
429 log.warn("There was no resource left to release on {}", linkId);
430 return;
431 }
432 List<LinkResourceAllocations> after = new ArrayList<>(before);
433 after.remove(allocations);
434 linkAllocs.replace(linkId, before, after);
435 });
436 tx.commit();
437 success = true;
438 } catch (TransactionException e) {
439 log.debug("Transaction failed, retrying", e);
440 tx.abort();
441 } catch (Exception e) {
442 log.error("Exception thrown during releaseResource {}", allocations, e);
443 tx.abort();
444 throw e;
445 }
446 } while (!success);
447
448 // Issue events to force recompilation of intents.
449 final List<LinkResourceAllocations> releasedResources = ImmutableList.of(allocations);
450 return new LinkResourceEvent(
451 LinkResourceEvent.Type.ADDITIONAL_RESOURCES_AVAILABLE,
452 releasedResources);
453
454 }
455
456 @Override
457 public LinkResourceAllocations getAllocations(IntentId intentId) {
458 checkNotNull(intentId);
459 Versioned<LinkResourceAllocations> alloc = null;
460 try {
461 alloc = intentAllocMap.get(intentId);
462 } catch (Exception e) {
463 log.warn("Could not read resource allocation information", e);
464 }
465 return alloc == null ? null : alloc.value();
466 }
467
468 @Override
469 public Iterable<LinkResourceAllocations> getAllocations(Link link) {
470 checkNotNull(link);
471 TransactionContext tx = getTxContext();
472 Iterable<LinkResourceAllocations> res = null;
473 tx.begin();
474 try {
475 res = getAllocations(tx, link);
476 } finally {
477 tx.abort();
478 }
479 return res == null ? Collections.emptyList() : res;
480 }
481
482 @Override
483 public Iterable<LinkResourceAllocations> getAllocations() {
484 try {
485 Set<LinkResourceAllocations> allocs =
486 intentAllocMap.values().stream().map(Versioned::value).collect(Collectors.toSet());
487 return ImmutableSet.copyOf(allocs);
488 } catch (Exception e) {
489 log.warn("Could not read resource allocation information", e);
490 }
491 return ImmutableSet.of();
492 }
493
494 private Iterable<LinkResourceAllocations> getAllocations(TransactionContext tx, Link link) {
495 checkNotNull(tx);
496 checkNotNull(link);
497 final LinkKey key = LinkKey.linkKey(link);
498 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
499 List<LinkResourceAllocations> res = null;
500
501 res = linkAllocs.get(key);
502 if (res == null) {
503 res = linkAllocs.putIfAbsent(key, new ArrayList<>());
504
505 if (res == null) {
506 return Collections.emptyList();
507 } else {
508 return res;
509 }
510 }
511 return res;
512 }
513
514}