|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * |
| 4 | + * The OpenSearch Contributors require contributions made to |
| 5 | + * this file be licensed under the Apache-2.0 license or a |
| 6 | + * compatible open source license. |
| 7 | + */ |
| 8 | + |
| 9 | +package org.opensearch.search; |
| 10 | + |
| 11 | +import org.opensearch.common.annotation.PublicApi; |
| 12 | +import org.opensearch.core.common.io.stream.StreamOutput; |
| 13 | +import org.opensearch.core.tasks.resourcetracker.ResourceStats; |
| 14 | +import org.opensearch.tasks.Task; |
| 15 | + |
| 16 | +import java.io.IOException; |
| 17 | +import java.util.function.Function; |
| 18 | + |
| 19 | +/** |
| 20 | + * Enum to hold the resource type |
| 21 | + */ |
| 22 | +@PublicApi(since = "2.x") |
| 23 | +public enum ResourceType { |
| 24 | + CPU("cpu", task -> task.getTotalResourceUtilization(ResourceStats.CPU)), |
| 25 | + MEMORY("memory", task -> task.getTotalResourceUtilization(ResourceStats.MEMORY)); |
| 26 | + |
| 27 | + private final String name; |
| 28 | + private final Function<Task, Long> getResourceUsage; |
| 29 | + |
| 30 | + ResourceType(String name, Function<Task, Long> getResourceUsage) { |
| 31 | + this.name = name; |
| 32 | + this.getResourceUsage = getResourceUsage; |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * The string match here is case-sensitive |
| 37 | + * @param s name matching the resource type name |
| 38 | + * @return a {@link ResourceType} |
| 39 | + */ |
| 40 | + public static ResourceType fromName(String s) { |
| 41 | + for (ResourceType resourceType : values()) { |
| 42 | + if (resourceType.getName().equals(s)) { |
| 43 | + return resourceType; |
| 44 | + } |
| 45 | + } |
| 46 | + throw new IllegalArgumentException("Unknown resource type: [" + s + "]"); |
| 47 | + } |
| 48 | + |
| 49 | + public static void writeTo(StreamOutput out, ResourceType resourceType) throws IOException { |
| 50 | + out.writeString(resourceType.getName()); |
| 51 | + } |
| 52 | + |
| 53 | + public String getName() { |
| 54 | + return name; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Gets the resource usage for a given resource type and task. |
| 59 | + * |
| 60 | + * @param task the task for which to calculate resource usage |
| 61 | + * @return the resource usage |
| 62 | + */ |
| 63 | + public long getResourceUsage(Task task) { |
| 64 | + return getResourceUsage.apply(task); |
| 65 | + } |
| 66 | +} |
0 commit comments