Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JENKINS-27650] TCB plugin performance (extra caching) #28

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ THE SOFTWARE.
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>1.424</version>
<version>1.532.2</version>
</parent>

<artifactId>throttle-concurrents</artifactId>
Expand Down Expand Up @@ -113,6 +113,12 @@ THE SOFTWARE.
<version>2.0.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>matrix-project</artifactId>
<version>1.0</version>
<type>jar</type>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type can be omitted BTW

</dependency>
</dependencies>
</project>

Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
/*
* The MIT License
*
* Copyright 2015 CloudBees Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.plugins.throttleconcurrents;

import hudson.model.AbstractBuild;
import hudson.model.JobProperty;
import hudson.model.queue.CauseOfBlockage;
import hudson.plugins.throttleconcurrents.util.ThrottleHelper;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;

/**
* Stores additional cache for {@link ThrottleQueueTaskDispatcher}.
* The cache is supposed to be used from {@link RunListener}.
* @author Oleg Nenashev
* @since TODO
*/
public class ThrottleCategoriesCountersCache {

private static final ThrottleCategoriesCountersCache INSTANCE = new ThrottleCategoriesCountersCache();

public static ThrottleCategoriesCountersCache getInstance() {
return INSTANCE;
}

private final Map<String, CategoryEntry> categoriesMap = new HashMap<String, CategoryEntry>();

private @CheckForNull Map<String, ThrottleJobProperty.ThrottleCategory> categoriesHash = null;

private CategoryEntry getCategoryEntry(String categoryName) {
CategoryEntry res = categoriesMap.get(categoryName);
if (res == null) {
res = new CategoryEntry(categoryName);
categoriesMap.put(categoryName, res);
}
return res;
}

private Map<String, ThrottleJobProperty.ThrottleCategory> getCategoriesHash() {
if (categoriesHash == null) {
categoriesHash = new HashMap<String, ThrottleJobProperty.ThrottleCategory>();
refreshCategoriesCache();
}
return categoriesHash;
}

public synchronized @CheckForNull CauseOfBlockage canTake(Collection<String> categoryNames, String nodeName) {
// Global check
for (String categoryName : categoryNames) {
int maxValue = getCategoriesHash().get(categoryName).getMaxConcurrentTotal();
int totalBuildsCount = getTotalBuildsNumber(categoryName);
if (totalBuildsCount >= maxValue) {
return CauseOfBlockage.fromMessage(Messages._ThrottleQueueTaskDispatcher_MaxCapacityTotal(totalBuildsCount));
}
}

// Per-node check
for (String categoryName : categoryNames) {
int maxValue = getCategoriesHash().get(categoryName).getMaxConcurrentPerNode();
int totalBuildsCountOnNode = getNodeBuildsNumber(categoryName, nodeName);
if (totalBuildsCountOnNode >= maxValue) {
return CauseOfBlockage.fromMessage(Messages._ThrottleQueueTaskDispatcher_MaxCapacityTotal(totalBuildsCountOnNode));
}
}
return null;
}

public synchronized @CheckForNull CauseOfBlockage canRun(Collection<String> categoryNames) {
for (String categoryName : categoryNames) {
int maxValue = getCategoriesHash().get(categoryName).getMaxConcurrentTotal();
int totalBuildsCount = getTotalBuildsNumber(categoryName);
if (totalBuildsCount >= maxValue) {
return CauseOfBlockage.fromMessage(Messages._ThrottleQueueTaskDispatcher_MaxCapacityTotal(totalBuildsCount));
}
}
return null;
}

/**
* Updates global cache of category properties
*/
public synchronized void refreshCategoriesCache() {
Jenkins j = Jenkins.getInstance();
if (j == null) {
throw new IllegalStateException("Jenkins must be started");
}

ThrottleJobProperty.DescriptorImpl d = j.getDescriptorByType(ThrottleJobProperty.DescriptorImpl.class);
if (d == null) {
throw new IllegalStateException("Cannot get the Throttle Property descriptor");
}

List<ThrottleJobProperty.ThrottleCategory> categories = d.getCategories();
getCategoriesHash().clear();
for (ThrottleJobProperty.ThrottleCategory category : categories) {
categoriesHash.put(category.getCategoryName(), category);
}
}

private int getTotalBuildsNumber(String categoryName) {
return getCategoryEntry(categoryName).globalCount.count;
}

private int getNodeBuildsNumber(String categoryName, String nodeName) {
return getCategoryEntry(categoryName).getEntry(nodeName).count;
}

//TODO: recalculate cache on jobs update

public synchronized void fireStarted(AbstractBuild build) {
JobProperty jp = ThrottleHelper.getThrottleJobProperty(build.getProject());
if (jp == null) {
return;
}
final ThrottleJobProperty tjp = (ThrottleJobProperty)jp;
if ( !ThrottleHelper.shouldBeThrottled(build.getParent(), tjp) ) {
return;
}

// Update the categories cache
if (tjp.getThrottleOption().equals("category")) {
final List<String> categories = tjp.getCategories();
if (categories != null && !categories.isEmpty()) {
for (String categoryName : categories) {
getCategoryEntry(categoryName).fireStarted(build);
}
}
}

}

public synchronized void fireCompleted(AbstractBuild build) {
//TODO: remove code dup
JobProperty jp = ThrottleHelper.getThrottleJobProperty(build.getProject());
if (jp == null) {
return;
}
final ThrottleJobProperty tjp = (ThrottleJobProperty)jp;
if ( !ThrottleHelper.shouldBeThrottled(build.getParent(), tjp) ) {
return;
}

// Update the categories cache
if (tjp.getThrottleOption().equals("category")) {
final List<String> categories = tjp.getCategories();
if (categories != null && !categories.isEmpty()) {
for (String categoryName : categories) {
getCategoryEntry(categoryName).fireCompleted(build);
}
}
}
}

private static class CategoryEntry {
private final String categoryName;
private final CounterEntry globalCount = new CounterEntry();
private final Map<String, CounterEntry> nodeCounts = new HashMap<String, CounterEntry>();

public CategoryEntry(String categoryName) {
this.categoryName = null;
}

public String getCategoryName() {
return categoryName;
}

void fireStarted(AbstractBuild build) {
globalCount.inc();
getEntry(build.getBuiltOnStr()).inc();
}

void fireCompleted(AbstractBuild build) {
globalCount.dec();
getEntry(build.getBuiltOnStr()).dec();
}

private @Nonnull CounterEntry getEntry(String nodeName) {
String key = StringUtils.isEmpty(nodeName) ? "(master)" : nodeName;
CounterEntry res = nodeCounts.get(key);
if (res == null) {
res = new CounterEntry();
nodeCounts.put(key, res);
}
return res;
}
}

private static class CounterEntry {
int count=0;

public int getCount() {
return count;
}

public void inc() {
count++;
}

public void dec() {
count--;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ public boolean isMatrixProject(Job job) {
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
ThrottleCategoriesCountersCache.getInstance().refreshCategoriesCache();
save();
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,61 @@
@Extension
public class ThrottleQueueTaskDispatcher extends QueueTaskDispatcher {

/**
* Fast and unreliable implementation of can take.
* It's designed to be a first-stage check in
* {@link ThrottleQueueTaskDispatcher#canTake(hudson.model.Node, hudson.model.Queue.Task)}.
* @param node
* @param task
* @param tjp Non-null job property of the task
* @return {@link CauseOfBlockage} if Jenkins cannot take the fob.
* null means that Jenkins <b>may</b> be able to take the job, but
* a full check is required.
*/
private @CheckForNull CauseOfBlockage fastCanTake(Node node, AbstractProject prj, ThrottleJobProperty tjp) {
// We presume that the throttling eligibility has been checked before
// The only supported type is AbstractProject

if (tjp.getThrottleOption().equals("category")) {
final CauseOfBlockage categoriesCheckResult =
ThrottleCategoriesCountersCache.getInstance().canTake(
tjp.getCategories(), node.getNodeName());
if (categoriesCheckResult != null) {
return categoriesCheckResult;
}
}

return null;
}

/**
* Fast and unreliable implementation of canRun.
* It's designed to be a first-stage check in
* {@link ThrottleQueueTaskDispatcher#canTake(hudson.model.Node, hudson.model.Queue.Task)}.
* @param node
* @param task
* @param tjp Non-null job property of the task
* @return {@link CauseOfBlockage} if Jenkins cannot take the fob.
* null means that Jenkins <b>may</b> be able to take the job, but
* a full check is required.
*/
private @CheckForNull CauseOfBlockage fastCanRun(AbstractProject prj, ThrottleJobProperty tjp) {
// We presume that the throttling eligibility has been checked before
// The only supported type is AbstractProject
if (tjp.getThrottleOption().equals("category")) {
final CauseOfBlockage categoriesCheckResult =
ThrottleCategoriesCountersCache.getInstance().canRun(tjp.getCategories());
if (categoriesCheckResult != null) {
return categoriesCheckResult;
}
}

return null;
}

@Override
public CauseOfBlockage canTake(Node node, Task task) {
public CauseOfBlockage canTake(Node node, Queue.BuildableItem item) {
Task task =item.task;

ThrottleJobProperty tjp = getThrottleJobProperty(task);

Expand All @@ -34,8 +87,14 @@ public CauseOfBlockage canTake(Node node, Task task) {
return null;
}

// Perform fast inaccurate check and exit if it vetoes the task
final CauseOfBlockage fastCheckResult = fastCanTake(node, (AbstractProject) task, tjp);
if (fastCheckResult != null) {
return fastCheckResult;
}

if (tjp!=null && tjp.getThrottleEnabled()) {
CauseOfBlockage cause = canRun(task, tjp);
CauseOfBlockage cause = canRun(task, tjp); // TODO: ? isPending() is not required for canTake()
if (cause != null) return cause;

if (tjp.getThrottleOption().equals("project")) {
Expand Down Expand Up @@ -91,9 +150,23 @@ else if (tjp.getThrottleOption().equals("category")) {
// @Override on jenkins 4.127+ , but still compatible with 1.399
public CauseOfBlockage canRun(Queue.Item item) {
ThrottleJobProperty tjp = getThrottleJobProperty(item.task);
if (tjp!=null && tjp.getThrottleEnabled()) {
return canRun(item.task, tjp);
if (!shouldBeThrottled(item.task, tjp)) {
return null;
}

// Perform fast inaccurate check and exit if it vetoes the task
final CauseOfBlockage fastCheckResult = fastCanRun((AbstractProject)item.task, tjp);
if (fastCheckResult != null) {
return fastCheckResult;
}

// TODO: fast check of nodes

// We do not check everything else and rely on CanTake
// It has been done to make canRun as a spot-check only
if (tjp!=null && tjp.getThrottleEnabled()) {
return canRun(item, tjp);
}
return null;
}

Expand Down Expand Up @@ -123,17 +196,25 @@ private boolean shouldBeThrottled(@Nonnull Task task, @CheckForNull ThrottleJobP
return true;
}

@Deprecated
public CauseOfBlockage canRun(Task task, ThrottleJobProperty tjp) {
if (!shouldBeThrottled(task, tjp)) {
return null;
}
if (Hudson.getInstance().getQueue().isPending(task)) {
return canRun(Hudson.getInstance().getQueue().getItem(task), tjp);
}

private boolean isPending(Queue.Item item) {
return (item instanceof Queue.BuildableItem)
? ((Queue.BuildableItem)item).isPending() : false;
}

public CauseOfBlockage canRun(Queue.Item item, ThrottleJobProperty tjp) {

if (isPending(item)) {
return CauseOfBlockage.fromMessage(Messages._ThrottleQueueTaskDispatcher_BuildPending());
}
if (tjp.getThrottleOption().equals("project")) {
if (tjp.getMaxConcurrentTotal().intValue() > 0) {
int maxConcurrentTotal = tjp.getMaxConcurrentTotal().intValue();
int totalRunCount = buildsOfProjectOnAllNodes(task);
int totalRunCount = buildsOfProjectOnAllNodes(item.task);

if (totalRunCount >= maxConcurrentTotal) {
return CauseOfBlockage.fromMessage(Messages._ThrottleQueueTaskDispatcher_MaxCapacityTotal(totalRunCount));
Expand Down
Loading