use of org.onosproject.net.resource.Resources in project onos by opennetworkinglab.
the class OpticalConnectivityIntentCompiler method findFirstAvailableLambda.
/**
* Find the first available lambda on the given path by checking all the port resources.
*
* @param path the path
* @return list of consecutive and available OChSignals
*/
private List<OchSignal> findFirstAvailableLambda(OpticalConnectivityIntent intent, Path path) {
if (intent.ochSignal().isPresent()) {
// create lambdas w.r.t. slotGanularity/slotWidth
OchSignal ochSignal = intent.ochSignal().get();
if (ochSignal.gridType() == GridType.FLEX) {
// multiplier sits in the middle of slots
int startMultiplier = ochSignal.spacingMultiplier() - (ochSignal.slotGranularity() / 2);
return IntStream.range(0, ochSignal.slotGranularity()).mapToObj(x -> OchSignal.newFlexGridSlot(startMultiplier + (2 * x))).collect(Collectors.toList());
} else if (ochSignal.gridType() == GridType.DWDM) {
int startMultiplier = (int) (1 - ochSignal.slotGranularity() + ochSignal.spacingMultiplier() * ochSignal.channelSpacing().frequency().asHz() / ChannelSpacing.CHL_6P25GHZ.frequency().asHz());
return IntStream.range(0, ochSignal.slotGranularity()).mapToObj(x -> OchSignal.newFlexGridSlot(startMultiplier + (2 * x))).collect(Collectors.toList());
}
// TODO: add support for other gridTypes
log.error("Grid type: {} not supported for user defined signal intents", ochSignal.gridType());
return Collections.emptyList();
}
Set<OchSignal> lambdas = findCommonLambdas(path);
if (lambdas.isEmpty()) {
return Collections.emptyList();
}
return findFirstLambda(lambdas, slotCount());
}
use of org.onosproject.net.resource.Resources in project onos by opennetworkinglab.
the class ResourcesCommand method printResource.
private void printResource(Resource resource, int level) {
// workaround to preserve the original behavior of ResourceService#getRegisteredResources
Set<Resource> children;
if (resource instanceof DiscreteResource) {
children = resourceService.getRegisteredResources(((DiscreteResource) resource).id());
} else {
children = Collections.emptySet();
}
if (resource.equals(Resource.ROOT)) {
print("ROOT");
} else {
String resourceName = resource.simpleTypeName();
if (resource instanceof ContinuousResource) {
if (availablesOnly) {
// Get the total resource
double total = ((ContinuousResource) resource).value();
// Get allocated resource
double allocated = resourceService.getResourceAllocations(resource.id()).stream().mapToDouble(rA -> ((ContinuousResource) rA.resource()).value()).sum();
// Difference
double difference = total - allocated;
print("%s%s: %f", Strings.repeat(" ", level), resourceName, difference);
} else {
print("%s%s: %f", Strings.repeat(" ", level), resourceName, ((ContinuousResource) resource).value());
}
// Continuous resource is terminal node, stop here
return;
} else {
String availability = "";
if (availablesOnly && !children.isEmpty()) {
// intermediate nodes cannot be omitted, print availability
if (resourceService.isAvailable(resource)) {
availability = " ✔";
} else {
availability = " ✘";
}
}
String toString = String.valueOf(resource.valueAs(Object.class).orElse(""));
if (toString.startsWith(resourceName)) {
print("%s%s%s", Strings.repeat(" ", level), toString, availability);
} else {
print("%s%s: %s%s", Strings.repeat(" ", level), resourceName, toString, availability);
}
}
}
// Classify children into aggregatable terminal resources and everything else
Set<Class<?>> aggregatableTypes = ImmutableSet.<Class<?>>builder().add(VlanId.class).add(MplsLabel.class).build();
// (last() resource name) -> { Resource }
Multimap<String, Resource> aggregatables = ArrayListMultimap.create();
List<Resource> nonAggregatable = new ArrayList<>();
for (Resource r : children) {
if (!isPrintTarget(r)) {
// A
continue;
}
if (r instanceof DiscreteResource) {
if (resourceService.getRegisteredResources(((DiscreteResource) r).id()).isEmpty()) {
// resource which has children should be printed
continue;
}
}
if (r instanceof ContinuousResource) {
// non-aggregatable terminal node
nonAggregatable.add(r);
} else if (Iterables.any(aggregatableTypes, r::isTypeOf)) {
// aggregatable & terminal node
String simpleName = r.simpleTypeName();
aggregatables.put(simpleName, r);
} else {
nonAggregatable.add(r);
}
}
// print aggregated (terminal)
aggregatables.asMap().entrySet().forEach(e -> {
// for each type...
String resourceName = e.getKey();
RangeSet<Long> rangeSet = TreeRangeSet.create();
// aggregate into RangeSet
e.getValue().stream().map(res -> {
if (res.isTypeOf(VlanId.class)) {
return (long) res.valueAs(VlanId.class).get().toShort();
} else if (res.isTypeOf(MplsLabel.class)) {
return (long) res.valueAs(MplsLabel.class).get().toInt();
} else if (res.isTypeOf(TributarySlot.class)) {
return res.valueAs(TributarySlot.class).get().index();
}
// TODO support Lambda (OchSignal types)
return 0L;
}).map(Range::singleton).map(range -> range.canonical(DiscreteDomain.longs())).forEach(rangeSet::add);
print("%s%s: %s", Strings.repeat(" ", level + 1), resourceName, rangeSet);
});
// print non-aggregatables (recurse)
if (sort) {
nonAggregatable.stream().sorted((o1, o2) -> String.valueOf(o1.id()).compareTo(String.valueOf(o2.id()))).forEach(r -> printResource(r, level + 1));
} else {
nonAggregatable.forEach(r -> printResource(r, level + 1));
}
}
use of org.onosproject.net.resource.Resources in project onos by opennetworkinglab.
the class ConnectivityIntentCompiler method allocateBandwidth.
/**
* Allocates the bandwidth specified as intent constraint on each link
* composing the intent, if a bandwidth constraint is specified.
*
* @param intent the intent requesting bandwidth allocation
* @param connectPoints the connect points composing the intent path computed
*/
protected void allocateBandwidth(ConnectivityIntent intent, List<ConnectPoint> connectPoints) {
// Retrieve bandwidth constraint if exists
List<Constraint> constraints = intent.constraints();
if (constraints == null) {
return;
}
Optional<Constraint> constraint = constraints.stream().filter(c -> c instanceof BandwidthConstraint).findAny();
// If there is no bandwidth constraint continue
if (!constraint.isPresent()) {
return;
}
BandwidthConstraint bwConstraint = (BandwidthConstraint) constraint.get();
double bw = bwConstraint.bandwidth().bps();
// If a resource group is set on the intent, the resource consumer is
// set equal to it. Otherwise it's set to the intent key
ResourceConsumer newResourceConsumer = intent.resourceGroup() != null ? intent.resourceGroup() : intent.key();
// Get the list of current resource allocations
Collection<ResourceAllocation> resourceAllocations = resourceService.getResourceAllocations(newResourceConsumer);
// Get the list of resources already allocated from resource allocations
List<Resource> resourcesAllocated = resourcesFromAllocations(resourceAllocations);
// Get the list of resource ids for resources already allocated
List<ResourceId> idsResourcesAllocated = resourceIds(resourcesAllocated);
// Create the list of incoming resources requested. Exclude resources
// already allocated.
List<Resource> incomingResources = resources(connectPoints, bw).stream().filter(r -> !resourcesAllocated.contains(r)).collect(Collectors.toList());
if (incomingResources.isEmpty()) {
return;
}
// Create the list of resources to be added, meaning their key is not
// present in the resources already allocated
List<Resource> resourcesToAdd = incomingResources.stream().filter(r -> !idsResourcesAllocated.contains(r.id())).collect(Collectors.toList());
// Resources to updated are all the new valid resources except the
// resources to be added
List<Resource> resourcesToUpdate = Lists.newArrayList(incomingResources);
resourcesToUpdate.removeAll(resourcesToAdd);
// If there are no resources to update skip update procedures
if (!resourcesToUpdate.isEmpty()) {
// Remove old resources that need to be updated
// TODO: use transaction updates when available in the resource service
List<ResourceAllocation> resourceAllocationsToUpdate = resourceAllocations.stream().filter(rA -> resourceIds(resourcesToUpdate).contains(rA.resource().id())).collect(Collectors.toList());
log.debug("Releasing bandwidth for intent {}: {} bps", newResourceConsumer, resourcesToUpdate);
resourceService.release(resourceAllocationsToUpdate);
// Update resourcesToAdd with the list of both the new resources and
// the resources to update
resourcesToAdd.addAll(resourcesToUpdate);
}
// remove them
if (intent.resourceGroup() != null) {
// Get the list of current resource allocations made by intent key
Collection<ResourceAllocation> resourceAllocationsByKey = resourceService.getResourceAllocations(intent.key());
resourceService.release(Lists.newArrayList(resourceAllocationsByKey));
}
// Allocate resources
log.debug("Allocating bandwidth for intent {}: {} bps", newResourceConsumer, resourcesToAdd);
List<ResourceAllocation> allocations = resourceService.allocate(newResourceConsumer, resourcesToAdd);
if (allocations.isEmpty()) {
log.debug("No resources allocated for intent {}", newResourceConsumer);
}
log.debug("Done allocating bandwidth for intent {}", newResourceConsumer);
}
use of org.onosproject.net.resource.Resources in project onos by opennetworkinglab.
the class ConsistentResourceStore method unregister.
@Override
public boolean unregister(List<? extends ResourceId> ids) {
checkNotNull(ids);
// Retry the transaction until successful.
while (true) {
TransactionContext tx = service.transactionContextBuilder().build();
tx.begin();
TransactionalDiscreteResourceSubStore discreteTxStore = discreteStore.transactional(tx);
TransactionalContinuousResourceSubStore continuousTxStore = continuousStore.transactional(tx);
// Look up resources by resource IDs
List<Resource> resources = ids.stream().filter(x -> x.parent().isPresent()).map(x -> {
// avoid access to consistent map in the case of discrete resource
if (x instanceof DiscreteResourceId) {
return Optional.of(Resources.discrete((DiscreteResourceId) x).resource());
} else {
return continuousTxStore.lookup((ContinuousResourceId) x);
}
}).flatMap(Tools::stream).collect(Collectors.toList());
// the order is preserved by LinkedHashMap
Map<DiscreteResourceId, List<Resource>> resourceMap = resources.stream().collect(Collectors.groupingBy(x -> x.parent().get().id(), LinkedHashMap::new, Collectors.toList()));
for (Map.Entry<DiscreteResourceId, List<Resource>> entry : resourceMap.entrySet()) {
if (!unregister(discreteTxStore, continuousTxStore, entry.getKey(), entry.getValue())) {
log.warn("Failed to unregister {}: Failed to remove {} values.", entry.getKey(), entry.getValue().size());
return abortTransaction(tx);
}
}
try {
CommitStatus status = commitTransaction(tx);
if (status == CommitStatus.SUCCESS) {
List<ResourceEvent> events = resources.stream().filter(x -> x.parent().isPresent()).map(x -> new ResourceEvent(RESOURCE_REMOVED, x)).collect(Collectors.toList());
notifyDelegate(events);
return true;
}
} catch (InterruptedException | ExecutionException | TimeoutException e) {
String message = resources.stream().map(Resource::simpleTypeName).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream().map(entry -> String.format("%d %s type resources", entry.getValue(), entry.getKey())).collect(Collectors.joining(", "));
log.warn("Failed to unregister {}: {}", message, e);
return false;
}
}
}
use of org.onosproject.net.resource.Resources in project onos by opennetworkinglab.
the class OpticalPathProvisioner method updateBandwidthUsage.
/**
* Updates usage information of bandwidth based on connectivity which is established.
* @param connectivity Optical connectivity
*/
private void updateBandwidthUsage(OpticalConnectivity connectivity) {
if (NO_BW_REQUIREMENT.equals(connectivity.bandwidth())) {
// no bandwidth requirement, nothing to allocate.
return;
}
OpticalConnectivityId connectivityId = connectivity.id();
List<Link> links = connectivity.links();
List<Resource> resources = links.stream().flatMap(l -> Stream.of(l.src(), l.dst())).filter(cp -> !isTransportLayer(deviceService.getDevice(cp.deviceId()).type())).map(cp -> Resources.continuous(cp.deviceId(), cp.port(), Bandwidth.class).resource(connectivity.bandwidth().bps())).collect(Collectors.toList());
log.debug("allocating bandwidth for {} : {}", connectivityId, resources);
List<ResourceAllocation> allocations = resourceService.allocate(connectivityId, resources);
if (allocations.isEmpty()) {
log.warn("Failed to allocate bandwidth {} to {}", connectivity.bandwidth().bps(), resources);
// TODO any recovery?
}
log.debug("Done allocating bandwidth for {}", connectivityId);
}
Aggregations