blob: e11ead5833e170973149bb3d1e7c3f8579d5e0c3 [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 SHIMIZUa890e7c2015-10-02 14:48:13 -0700169 BandwidthResource bandwidth = DEFAULT_BANDWIDTH;
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) {
Sho SHIMIZUa890e7c2015-10-02 14:48:13 -0700175 // do nothings, use default bandwidth
176 bandwidth = DEFAULT_BANDWIDTH;
Ayaka Koshibee114f042015-05-01 11:43:00 -0700177 }
178 }
179
Ayaka Koshibee114f042015-05-01 11:43:00 -0700180 return new BandwidthResourceAllocation(bandwidth);
181 }
182
183 private Set<MplsLabelResourceAllocation> getMplsResourceCapacity() {
184 Set<MplsLabelResourceAllocation> 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
188 .valueOf(i)));
189
190 }
191 return allocations;
192 }
193
194 private Map<ResourceType, Set<? extends ResourceAllocation>> getResourceCapacity(Link link) {
195 Map<ResourceType, Set<? extends ResourceAllocation>> caps = new HashMap<>();
196 for (ResourceType type : ResourceType.values()) {
197 Set<? extends ResourceAllocation> cap = getResourceCapacity(type, link);
Sho SHIMIZUf618cb02015-10-02 14:43:50 -0700198 caps.put(type, cap);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700199 }
200 return caps;
201 }
202
203 @Override
204 public Set<ResourceAllocation> getFreeResources(Link link) {
205 TransactionContext tx = getTxContext();
206
207 tx.begin();
208 try {
209 Map<ResourceType, Set<? extends ResourceAllocation>> freeResources = getFreeResourcesEx(tx, link);
210 Set<ResourceAllocation> allFree = new HashSet<>();
211 freeResources.values().forEach(allFree::addAll);
212 return allFree;
213 } finally {
214 tx.abort();
215 }
216 }
217
218 private Map<ResourceType, Set<? extends ResourceAllocation>> getFreeResourcesEx(TransactionContext tx, Link link) {
219 checkNotNull(tx);
220 checkNotNull(link);
221
222 Map<ResourceType, Set<? extends ResourceAllocation>> free = new HashMap<>();
223 final Map<ResourceType, Set<? extends ResourceAllocation>> caps = getResourceCapacity(link);
224 final Iterable<LinkResourceAllocations> allocations = getAllocations(tx, link);
225
226 for (ResourceType type : ResourceType.values()) {
227 // there should be class/category of resources
228
229 switch (type) {
230 case BANDWIDTH:
231 Set<? extends ResourceAllocation> bw = caps.get(type);
232 if (bw == null || bw.isEmpty()) {
233 bw = Sets.newHashSet(new BandwidthResourceAllocation(EMPTY_BW));
234 }
235
236 BandwidthResourceAllocation cap = (BandwidthResourceAllocation) bw.iterator().next();
237 double freeBw = cap.bandwidth().toDouble();
238
239 // enumerate current allocations, subtracting resources
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700240 double allocatedBw = ImmutableList.copyOf(allocations).stream()
241 .flatMap(x -> x.getResourceAllocation(link).stream())
242 .filter(x -> x instanceof BandwidthResourceAllocation)
243 .map(x -> (BandwidthResourceAllocation) x)
244 .mapToDouble(x -> x.bandwidth().toDouble())
245 .sum();
246 freeBw -= allocatedBw;
Ayaka Koshibee114f042015-05-01 11:43:00 -0700247
Sho SHIMIZU6d01d3d2015-05-08 14:08:36 -0700248 free.put(type, Sets.newHashSet(
249 new BandwidthResourceAllocation(new BandwidthResource(Bandwidth.bps(freeBw)))));
Ayaka Koshibee114f042015-05-01 11:43:00 -0700250 break;
251 case LAMBDA:
252 Set<? extends ResourceAllocation> lmd = caps.get(type);
253 if (lmd == null || lmd.isEmpty()) {
254 // nothing left
255 break;
256 }
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700257 Set<LambdaResourceAllocation> freeL = lmd.stream()
258 .filter(x -> x instanceof LambdaResourceAllocation)
259 .map(x -> (LambdaResourceAllocation) x)
260 .collect(Collectors.toSet());
Ayaka Koshibee114f042015-05-01 11:43:00 -0700261
262 // enumerate current allocations, removing resources
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700263 List<LambdaResourceAllocation> allocatedLambda = ImmutableList.copyOf(allocations).stream()
264 .flatMap(x -> x.getResourceAllocation(link).stream())
265 .filter(x -> x instanceof LambdaResourceAllocation)
266 .map(x -> (LambdaResourceAllocation) x)
267 .collect(Collectors.toList());
268 freeL.removeAll(allocatedLambda);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700269
270 free.put(type, freeL);
271 break;
272 case MPLS_LABEL:
273 Set<? extends ResourceAllocation> mpls = caps.get(type);
274 if (mpls == null || mpls.isEmpty()) {
275 // nothing left
276 break;
277 }
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700278 Set<MplsLabelResourceAllocation> freeLabel = mpls.stream()
279 .filter(x -> x instanceof MplsLabelResourceAllocation)
280 .map(x -> (MplsLabelResourceAllocation) x)
281 .collect(Collectors.toSet());
Ayaka Koshibee114f042015-05-01 11:43:00 -0700282
283 // enumerate current allocations, removing resources
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700284 List<MplsLabelResourceAllocation> allocatedLabel = ImmutableList.copyOf(allocations).stream()
285 .flatMap(x -> x.getResourceAllocation(link).stream())
286 .filter(x -> x instanceof MplsLabelResourceAllocation)
287 .map(x -> (MplsLabelResourceAllocation) x)
288 .collect(Collectors.toList());
289 freeLabel.removeAll(allocatedLabel);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700290
291 free.put(type, freeLabel);
292 break;
293 default:
294 log.debug("unsupported ResourceType {}", type);
295 break;
296 }
297 }
298 return free;
299 }
300
301 @Override
302 public void allocateResources(LinkResourceAllocations allocations) {
303 checkNotNull(allocations);
304 TransactionContext tx = getTxContext();
305
306 tx.begin();
307 try {
308 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
309 intentAllocs.put(allocations.intentId(), allocations);
310 allocations.links().forEach(link -> allocateLinkResource(tx, link, allocations));
311 tx.commit();
312 } catch (Exception e) {
313 log.error("Exception thrown, rolling back", e);
314 tx.abort();
315 throw e;
316 }
317 }
318
319 private void allocateLinkResource(TransactionContext tx, Link link,
320 LinkResourceAllocations allocations) {
321 // requested resources
322 Set<ResourceAllocation> reqs = allocations.getResourceAllocation(link);
323 Map<ResourceType, Set<? extends ResourceAllocation>> available = getFreeResourcesEx(tx, link);
324 for (ResourceAllocation req : reqs) {
325 Set<? extends ResourceAllocation> avail = available.get(req.type());
326 if (req instanceof BandwidthResourceAllocation) {
327 // check if allocation should be accepted
328 if (avail.isEmpty()) {
329 checkState(!avail.isEmpty(),
330 "There's no Bandwidth resource on %s?",
331 link);
332 }
333 BandwidthResourceAllocation bw = (BandwidthResourceAllocation) avail.iterator().next();
334 double bwLeft = bw.bandwidth().toDouble();
335 BandwidthResourceAllocation bwReq = ((BandwidthResourceAllocation) req);
336 bwLeft -= bwReq.bandwidth().toDouble();
337 if (bwLeft < 0) {
338 throw new ResourceAllocationException(
339 PositionalParameterStringFormatter.format(
340 "Unable to allocate bandwidth for link {} "
341 + " requested amount is {} current allocation is {}",
342 link,
343 bwReq.bandwidth().toDouble(),
344 bw));
345 }
346 } else if (req instanceof LambdaResourceAllocation) {
347 LambdaResourceAllocation lambdaAllocation = (LambdaResourceAllocation) req;
348 // check if allocation should be accepted
349 if (!avail.contains(req)) {
350 // requested lambda was not available
351 throw new ResourceAllocationException(
352 PositionalParameterStringFormatter.format(
353 "Unable to allocate lambda for link {} lambda is {}",
354 link,
355 lambdaAllocation.lambda().toInt()));
356 }
357 } else if (req instanceof MplsLabelResourceAllocation) {
358 MplsLabelResourceAllocation mplsAllocation = (MplsLabelResourceAllocation) req;
359 if (!avail.contains(req)) {
360 throw new ResourceAllocationException(
361 PositionalParameterStringFormatter
362 .format("Unable to allocate MPLS label for link "
363 + "{} MPLS label is {}",
364 link,
365 mplsAllocation
366 .mplsLabel()
367 .toString()));
368 }
369 }
370 }
371 // all requests allocatable => add allocation
372 final LinkKey linkKey = LinkKey.linkKey(link);
373 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
374 List<LinkResourceAllocations> before = linkAllocs.get(linkKey);
375 if (before == null) {
376 List<LinkResourceAllocations> after = new ArrayList<>();
377 after.add(allocations);
378 before = linkAllocs.putIfAbsent(linkKey, after);
379 if (before != null) {
380 // concurrent allocation detected, retry transaction : is this needed?
381 log.warn("Concurrent Allocation, retrying");
382 throw new TransactionException();
383 }
384 } else {
385 List<LinkResourceAllocations> after = new ArrayList<>(before.size() + 1);
386 after.addAll(before);
387 after.add(allocations);
388 linkAllocs.replace(linkKey, before, after);
389 }
390 }
391
392 @Override
393 public LinkResourceEvent releaseResources(LinkResourceAllocations allocations) {
394 checkNotNull(allocations);
395
396 final IntentId intentId = allocations.intentId();
397 final Collection<Link> links = allocations.links();
398 boolean success = false;
399 do {
400 TransactionContext tx = getTxContext();
401 tx.begin();
402 try {
403 TransactionalMap<IntentId, LinkResourceAllocations> intentAllocs = getIntentAllocs(tx);
404 intentAllocs.remove(intentId);
405
406 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
407 links.forEach(link -> {
408 final LinkKey linkId = LinkKey.linkKey(link);
409
410 List<LinkResourceAllocations> before = linkAllocs.get(linkId);
411 if (before == null || before.isEmpty()) {
412 // something is wrong, but it is already freed
413 log.warn("There was no resource left to release on {}", linkId);
414 return;
415 }
416 List<LinkResourceAllocations> after = new ArrayList<>(before);
417 after.remove(allocations);
418 linkAllocs.replace(linkId, before, after);
419 });
420 tx.commit();
421 success = true;
422 } catch (TransactionException e) {
423 log.debug("Transaction failed, retrying", e);
424 tx.abort();
425 } catch (Exception e) {
426 log.error("Exception thrown during releaseResource {}", allocations, e);
427 tx.abort();
428 throw e;
429 }
430 } while (!success);
431
432 // Issue events to force recompilation of intents.
433 final List<LinkResourceAllocations> releasedResources = ImmutableList.of(allocations);
434 return new LinkResourceEvent(
435 LinkResourceEvent.Type.ADDITIONAL_RESOURCES_AVAILABLE,
436 releasedResources);
437
438 }
439
440 @Override
441 public LinkResourceAllocations getAllocations(IntentId intentId) {
442 checkNotNull(intentId);
443 Versioned<LinkResourceAllocations> alloc = null;
444 try {
445 alloc = intentAllocMap.get(intentId);
446 } catch (Exception e) {
447 log.warn("Could not read resource allocation information", e);
448 }
449 return alloc == null ? null : alloc.value();
450 }
451
452 @Override
453 public Iterable<LinkResourceAllocations> getAllocations(Link link) {
454 checkNotNull(link);
455 TransactionContext tx = getTxContext();
456 Iterable<LinkResourceAllocations> res = null;
457 tx.begin();
458 try {
459 res = getAllocations(tx, link);
460 } finally {
461 tx.abort();
462 }
463 return res == null ? Collections.emptyList() : res;
464 }
465
466 @Override
467 public Iterable<LinkResourceAllocations> getAllocations() {
468 try {
469 Set<LinkResourceAllocations> allocs =
470 intentAllocMap.values().stream().map(Versioned::value).collect(Collectors.toSet());
471 return ImmutableSet.copyOf(allocs);
472 } catch (Exception e) {
473 log.warn("Could not read resource allocation information", e);
474 }
475 return ImmutableSet.of();
476 }
477
478 private Iterable<LinkResourceAllocations> getAllocations(TransactionContext tx, Link link) {
479 checkNotNull(tx);
480 checkNotNull(link);
481 final LinkKey key = LinkKey.linkKey(link);
482 TransactionalMap<LinkKey, List<LinkResourceAllocations>> linkAllocs = getLinkAllocs(tx);
Ayaka Koshibee114f042015-05-01 11:43:00 -0700483
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700484 List<LinkResourceAllocations> res = linkAllocs.get(key);
485 if (res != null) {
486 return res;
Ayaka Koshibee114f042015-05-01 11:43:00 -0700487 }
Sho SHIMIZU88d36e22015-10-02 14:23:46 -0700488
489 res = linkAllocs.putIfAbsent(key, new ArrayList<>());
490 if (res == null) {
491 return Collections.emptyList();
492 } else {
493 return res;
494 }
Ayaka Koshibee114f042015-05-01 11:43:00 -0700495 }
496
497}