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

Add an updateLock step to alter resources in pipelines #305

Open
wants to merge 4 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
31 changes: 28 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ already defined in the Jenkins global configuration, an ephemeral resource is
used: These resources only exist as long as any running build is referencing
them.

Examples:
#### Locking Examples

*Acquire lock*

Expand Down Expand Up @@ -90,8 +90,6 @@ lock(label: 'some_resource', variable: 'LOCKED_RESOURCE', quantity: 2) {
}
```



*Skip executing the block if there is a queue*

```groovy
Expand All @@ -100,6 +98,33 @@ lock(resource: 'some_resource', skipIfLocked: true) {
}
```

#### Update Examples

*Set the note on a lock*

```groovy
updateLock(resource: 'printer', setNote: 'this might take a long time...')
```

*Changing labels of a lock*

```groovy
updateLock(resource: 'printer', addLabel: 'offline')
```
*Adding/Deleting locks dynamically*

```groovy
discoveredPrinters.each { p ->
updateLock(resource: p.name, setLabels:'printer', createResource:true)
}
```

```groovy
brokenPrinters.each { p ->
updateLock(resource: p.name, deleteResource:true)
}
```

Detailed documentation can be found as part of the
[Pipeline Steps](https://jenkins.io/doc/pipeline/steps/lockable-resources/)
documentation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,26 @@ public synchronized void setDeclaredResources(List<LockableResource> declaredRes
this.resources = mergedResources;
}

public void deleteResource(String name) {
LockableResource resource = fromName(name);
if (resource == null) {
return;
}

if (resource.isLocked()) {
// Removed locks became ephemeral.
resource.setDescription("");
resource.setLabels("");
resource.setNote("");
resource.setEphemeral(true);
Copy link
Contributor

Choose a reason for hiding this comment

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

the user shall be inform about that

  • in the job log
  • in the UI like setting some other description. ( in this case I will not change note, labels) Just set ephemeral = true.

One hit more. What happens, when other job is waiting for this resource? This one will be on release deleted. The next one will create it again, or in worst case crashed the job.

}
else {
this.resources.remove(resource);
}

save();
}

public List<LockableResource> getResourcesFromProject(String fullName) {
List<LockableResource> matching = new ArrayList<>();
for (LockableResource r : resources) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package org.jenkins.plugins.lockableresources;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.AutoCompletionCandidates;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import java.io.Serializable;
import java.util.Collections;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.workflow.steps.Step;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepDescriptor;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;

public class UpdateLockStep extends Step implements Serializable {

private static final long serialVersionUID = -7955849755535282258L;

@CheckForNull
public String resource = null;

@CheckForNull
public String addLabels = null;

@CheckForNull
public String setLabels = null;

@CheckForNull
public String removeLabels = null;

@CheckForNull
public String setNote = null;

public boolean createResource = false;
public boolean deleteResource = false;

@DataBoundSetter
public void setResource(String resource) {
this.resource = resource;
}

@DataBoundSetter
public void setAddLabels(String addLabels) {
if (StringUtils.isNotBlank(addLabels)) {
this.addLabels = addLabels;
}
}

@DataBoundSetter
public void setSetLabels(String setLabels) {
if (StringUtils.isNotBlank(setLabels)) {
this.setLabels = setLabels;
}
}

@DataBoundSetter
public void setRemoveLabels(String removeLabels) {
if (StringUtils.isNotBlank(removeLabels)) {
this.removeLabels = removeLabels;
}
}

@DataBoundSetter
public void setCreateResource(boolean createResource) {
this.createResource = createResource;
}

@DataBoundSetter
public void setDeleteResource(boolean deleteResource) {
this.deleteResource = deleteResource;
}

@DataBoundSetter
public void setSetNote(String setNote) {
if (StringUtils.isNotBlank(setNote)) {
this.setNote = setNote;
}
}

@DataBoundConstructor
public UpdateLockStep() {
}


@Extension
public static final class DescriptorImpl extends StepDescriptor {

@Override
public String getFunctionName() {
return "updateLock";
}

@NonNull
@Override
public String getDisplayName() {
return "Update the definition of a lock";
}

@Override
public boolean takesImplicitBlockArgument() {
return false;
}

public AutoCompletionCandidates doAutoCompleteResource(@QueryParameter String value) {
return RequiredResourcesProperty.DescriptorImpl.doAutoCompleteResourceNames(value);
}

public static FormValidation doCheckResource(
@QueryParameter String value) {
return UpdateLockStepResource.DescriptorImpl.doCheckResource(value);
}

public static FormValidation doCheckAddLabels(
@QueryParameter String value, @QueryParameter String setLabels) {
return UpdateLockStepResource.DescriptorImpl.doCheckLabelOperations(value, setLabels);
}

public static FormValidation doCheckRemoveLabels(
@QueryParameter String value, @QueryParameter String setLabels) {
return UpdateLockStepResource.DescriptorImpl.doCheckLabelOperations(value, setLabels);
}

public static FormValidation doCheckDelete(
@QueryParameter boolean value, @QueryParameter String setLabels, @QueryParameter String addLabels, @QueryParameter String removeLabels, @QueryParameter String setNote, @QueryParameter boolean createResource) {
return UpdateLockStepResource.DescriptorImpl.doCheckDelete(value, setLabels,addLabels, removeLabels, setNote, createResource);
}

@Override
public Set<Class<?>> getRequiredContext() {
return Collections.singleton(TaskListener.class);
}
}

@Override
public StepExecution start(StepContext context) {
return new UpdateLockStepExecution(this, context);
}

public void validate() {
if (StringUtils.isBlank(resource)) {
throw new IllegalArgumentException("The resource name must be specified.");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package org.jenkins.plugins.lockableresources;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.jenkinsci.plugins.workflow.steps.AbstractStepExecutionImpl;
import org.jenkinsci.plugins.workflow.steps.StepContext;

public class UpdateLockStepExecution extends AbstractStepExecutionImpl implements Serializable {

private static final long serialVersionUID = 1583205294263267002L;

private static final Logger LOGGER = Logger.getLogger(UpdateLockStepExecution.class.getName());

private final UpdateLockStep step;

public UpdateLockStepExecution(UpdateLockStep step, StepContext context) {
super(context);
this.step = step;
}

@Override
public boolean start() throws Exception {
this.step.validate();

if (this.step.deleteResource) {
LockableResourcesManager.get().deleteResource(this.step.resource);
}
else {
LockableResource resource = LockableResourcesManager.get().fromName(this.step.resource);
LockableResourcesManager lockableResourcesManager = LockableResourcesManager.get();
if (resource == null && this.step.createResource) {
lockableResourcesManager.createResource(this.step.resource);
resource = lockableResourcesManager.fromName(this.step.resource);
resource.setEphemeral(false);
}

if (this.step.setLabels != null) {
List<String> setLabels = Arrays.asList(this.step.setLabels.trim().split("\\s+"));
resource.setLabels(setLabels.stream().collect(Collectors.joining(" ")));
} else if (this.step.addLabels != null || this.step.removeLabels != null) {
List<String> labels = new ArrayList<>(Arrays.asList(resource.getLabels().split("\\s+")));
if (this.step.addLabels != null) {
List<String> addLabels = Arrays.asList(this.step.addLabels.trim().split("\\s+"));
addLabels.stream().filter(l -> labels.contains(l) == false).forEach(labels::add);
}
if (this.step.removeLabels != null) {
List<String> removeLabels = Arrays.asList(this.step.removeLabels.trim().split("\\s+"));
labels.removeAll(removeLabels);
}
resource.setLabels(labels.stream().collect(Collectors.joining(" ")));
}

if (this.step.setNote != null) {
resource.setNote(this.step.setNote);
}

lockableResourcesManager.save();
}

getContext().onSuccess(null);
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package org.jenkins.plugins.lockableresources;

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.AutoCompletionCandidates;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import java.io.Serializable;
import org.kohsuke.stapler.QueryParameter;

public class UpdateLockStepResource extends AbstractDescribableImpl<UpdateLockStepResource> implements Serializable {

private static final long serialVersionUID = -3689811142454137183L;


@Extension
public static class DescriptorImpl extends Descriptor<UpdateLockStepResource> {

@NonNull
@Override
public String getDisplayName() {
return "Resource Update";
}

public AutoCompletionCandidates doAutoCompleteResource(@QueryParameter String value) {
return RequiredResourcesProperty.DescriptorImpl.doAutoCompleteResourceNames(value);
}

public static FormValidation doCheckLabelOperations(String value, String setLabels) {
String updateLabel = Util.fixEmpty(value);
setLabels = Util.fixEmpty(setLabels);

if (setLabels != null && updateLabel != null) {
return FormValidation.error("Cannot set and update labels at the same time.");
}
return FormValidation.ok();
}

public static FormValidation doCheckResource(@QueryParameter String value) {
String resourceName = Util.fixEmpty(value);
if (resourceName == null) {
return FormValidation.error("Resource name cannot be empty.");
}
return FormValidation.ok();
}

public static FormValidation doCheckDelete(boolean value, String setLabels, String addLabels, String removeLabels, String setNote, boolean createResource) {
if (!value) {
return FormValidation.ok();
}

if (createResource) {
return FormValidation.error("Cannot create and delete a resource.");
}

if (Util.fixEmpty(setLabels) != null || Util.fixEmpty(addLabels) != null || Util.fixEmpty(removeLabels) != null || Util.fixEmpty(setNote) != null) {
return FormValidation.error("Cannot update and delete a resource.");
}
return FormValidation.ok();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define"
xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
<f:entry title="${%Resource}" field="resource">
<f:textbox/>
</f:entry>
<f:entry title="${%Set Labels}" field="setLabels">
<f:textbox/>
</f:entry>
<f:entry title="${%Add Labels}" field="addLabels">
<f:textbox/>
</f:entry>
<f:entry title="${%Remove Labels}" field="removeLabels">
<f:textbox/>
</f:entry>
<f:entry title="${%Set Note}" field="setNote">
<f:textbox/>
</f:entry>
<f:entry field="createResource">
<f:checkbox title="${%Create if Missing}"/>
</f:entry>
<f:entry field="deleteResource">
<f:checkbox title="${%Delete Existing}"/>
</f:entry>
</j:jelly>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<div>
<p>
Appends to the current labels with the ones specified as a space-separated list.
</p>
</div>
Loading