Skip to content

Commit

Permalink
Merge pull request #14 from oleg-nenashev/feature/JENKINS-38644-class…
Browse files Browse the repository at this point in the history
…-restriction

[JENKINS-38644] - Support job class restrictions
  • Loading branch information
oleg-nenashev committed Oct 1, 2016
2 parents efec8e7 + 2f21464 commit 2cd4fc7
Show file tree
Hide file tree
Showing 9 changed files with 366 additions and 1 deletion.
17 changes: 16 additions & 1 deletion pom.xml
Expand Up @@ -59,5 +59,20 @@
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
</licenses>

<dependencies>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>matrix-project</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>matrix-auth</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,96 @@
/*
* The MIT License
*
* Copyright 2016 Oleg Nenashev
*
* 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 io.jenkins.plugins.jobrestrictions.restrictions.job;

import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.Messages;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestriction;
import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.restrictions.JobRestrictionDescriptor;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.model.Queue;
import hudson.model.Run;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.DataBoundConstructor;

/**
* Handles job class restrictions.
* @author Oleg Nenashev
* @see ClassSelector
* @since TODO
*/
// TODO: it's a real issue, needs some love
@SuppressFBWarnings(value = "SE_NO_SERIALVERSIONID",
justification = "XStream does actually need serialization, the code needs refactoring in 1.0")
public class JobClassNameRestriction extends JobRestriction {

private final List<ClassSelector> jobClasses;

private transient Set<String> acceptedClassesHash = null;

@DataBoundConstructor
public JobClassNameRestriction(List<ClassSelector> jobClasses) {
this.jobClasses = jobClasses;
}

@Nonnull
public List<ClassSelector> getJobClasses() {
return jobClasses;
}

@Nonnull
private synchronized Set<String> getAcceptedJobClasses() {
if (acceptedClassesHash == null) {
final List<ClassSelector> selectors = getJobClasses();
acceptedClassesHash = new HashSet<String>(selectors.size());
for (ClassSelector selector : selectors) {
acceptedClassesHash.add(selector.getSelectedClass()); // merge equal entries
}
}
return acceptedClassesHash;
}

@Override
public boolean canTake(Queue.BuildableItem item) {
return getAcceptedJobClasses().contains(item.task.getClass().getName());
}

@Override
public boolean canTake(Run run) {
return getAcceptedJobClasses().contains(run.getParent().getClass().getName());
}

@Extension
public static class DescriptorImpl extends JobRestrictionDescriptor {

@Override
public String getDisplayName() {
return Messages.restrictions_Job_JobClassNameRestriction_displayName();
}
}
}
@@ -0,0 +1,101 @@
/*
* The MIT License
*
* Copyright 2016 Oleg Nenashev
*
* 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 io.jenkins.plugins.jobrestrictions.util;

import hudson.Extension;
import hudson.Util;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import java.io.Serializable;
import javax.annotation.CheckForNull;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;

/**
* Describable Item, which allows to select class.
* Class existence is being verified.
* @since TODO
*/
public class ClassSelector implements Describable<ClassSelector>, Serializable {

/**ID of the user*/
final @CheckForNull String selectedClass;

@DataBoundConstructor
public ClassSelector(@CheckForNull String selectedClass) {
this.selectedClass = hudson.Util.fixEmptyAndTrim(selectedClass);
}

@CheckForNull
public String getSelectedClass() {
return selectedClass;
}

@Override
public Descriptor<ClassSelector> getDescriptor() {
return DESCRIPTOR;
}

@Override
public boolean equals(Object obj) {
if (obj instanceof ClassSelector) {
ClassSelector cmp = (ClassSelector)obj;
return selectedClass != null ? selectedClass.equals(cmp.selectedClass) : cmp.selectedClass == null;
}
return false;
}

@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (selectedClass != null ? selectedClass.hashCode() : 0);
return hash;
}

@Extension
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static class DescriptorImpl extends Descriptor<ClassSelector> {

@Override
public String getDisplayName() {
return "N/A";
}

public FormValidation doCheckSelectedClass(final @QueryParameter String selectedClass) {
String _selectedClass = Util.fixEmptyAndTrim(selectedClass);
if (_selectedClass == null) {
return FormValidation.error("Field is empty");
}

try {
Class.forName(selectedClass);
} catch (Exception ex) {
return FormValidation.warning("Class " + _selectedClass + " cannot be resolved: " + ex.toString());
}

return FormValidation.ok();
}
}
}
Expand Up @@ -13,5 +13,6 @@ restrictions.Job.RegexName.OkMessage=Pattern is valid
restrictions.Job.RegexName.FailMessage=Pattern is invalid and will be ignored.
restrictions.Job.StartedByUserRestriction.displayName=Started By User
restrictions.Job.StartedByMemberOfGroupRestriction.displayName=Started By member of group
restrictions.Job.JobClassNameRestriction.displayName=Job class
restirctions.Stuff.MultipleSuffix=(multiple entries)

@@ -0,0 +1,32 @@
<!--
* The MIT License
*
* Copyright 2016 Oleg Nenashev
*
* 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.
-->
<?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"
xmlns:i="jelly:fmt" xmlns:p="/lib/hudson/project">

<f:entry title="${%Job Classes}">
<f:repeatableProperty field="jobClasses" add="${%Add job class}"/>
</f:entry>
</j:jelly>
@@ -0,0 +1,3 @@
usersList=Users list
checkUpstreamProjects=Accept upstream runs started by users above
acceptAnonymousUsers=Accept runs started by anonymous users
@@ -0,0 +1,36 @@
<!--
* The MIT License
*
* Copyright 2016 Oleg Nenashev
*
* 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.
-->
<?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"
xmlns:i="jelly:fmt" xmlns:p="/lib/hudson/project">
<f:entry title="${%Class name}" field="selectedClass">
<f:textbox/>
</f:entry>
<f:entry title="">
<div align="right">
<f:repeatableDeleteButton />
</div>
</f:entry>
</j:jelly>
@@ -0,0 +1,3 @@
<div>
Class name to be checked.
</div>
@@ -0,0 +1,78 @@
/*
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* 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 io.jenkins.plugins.jobrestrictions.restrictions.job;

import com.synopsys.arc.jenkinsci.plugins.jobrestrictions.nodes.JobRestrictionProperty;
import io.jenkins.plugins.jobrestrictions.util.ClassSelector;
import hudson.matrix.MatrixProject;
import hudson.model.Action;
import hudson.model.Queue;
import hudson.model.FreeStyleProject;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;

/**
* Tests of {@link JobClassNameRestriction}.
* @author Oleg Nenashev
*/
@Issue("JENKINS-38644")
public class JobClassNameRestrictionTest {

@Rule
public JenkinsRule j = new JenkinsRule();

@Test
public void shouldRestrictJobClass() throws Exception {
JobClassNameRestriction jobClassNameRestriction = new JobClassNameRestriction(
Arrays.asList(new ClassSelector(FreeStyleProject.class.getName())));
JobRestrictionProperty prop = new JobRestrictionProperty(jobClassNameRestriction);

FreeStyleProject freestylePrj = j.createFreeStyleProject();
MatrixProject matrixProject = j.createProject(MatrixProject.class);

assertCanTake(prop, freestylePrj);
assertCannotTake(prop, matrixProject);
}

private void assertCanTake(JobRestrictionProperty prop, Queue.Task task) {
Queue.BuildableItem item = new Queue.BuildableItem(new Queue.WaitingItem(Calendar.getInstance(),
task, Collections.<Action>emptyList()));
assertThat("Job Restriction Property should accept " + task.getClass(),
prop.canTake(item), nullValue());
}

private void assertCannotTake(JobRestrictionProperty prop, Queue.Task task) {
Queue.BuildableItem item = new Queue.BuildableItem(new Queue.WaitingItem(Calendar.getInstance(),
task, Collections.<Action>emptyList()));
assertThat("Job Restriction Property should not accept " + task.getClass(),
prop.canTake(item), notNullValue());
}
}

0 comments on commit 2cd4fc7

Please sign in to comment.