hudson.model.Computer Java Examples

The following examples show how to use hudson.model.Computer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DockerNodeStepExecution.java    From docker-plugin with MIT License 6 votes vote down vote up
private void invokeBody(DockerTransientNode node, TaskListener listener) {
    this.nodeName = node.getNodeName();
    FilePath ws = null;
    Computer computer = null;
    EnvVars env = null;
    try {
        // TODO workspace should be a volume
        ws = node.createPath(node.getRemoteFS() + "/workspace");
        FlowNode flowNode = getContext().get(FlowNode.class);
        flowNode.addAction(new WorkspaceActionImpl(ws, flowNode));

        computer = node.toComputer();
        if (computer == null) throw new IllegalStateException("Agent not started");
        env = computer.getEnvironment();
        env.overrideExpandingAll(computer.buildEnvironment(listener));
        env.put("NODE_NAME", computer.getName());
        env.put("EXECUTOR_NUMBER", "0");
        env.put("NODE_LABELS", Util.join(node.getAssignedLabels(), " "));
        env.put("WORKSPACE", ws.getRemote());
    } catch (IOException | InterruptedException e) {
        getContext().onFailure(e);
    }

    getContext().newBodyInvoker().withCallback(new Callback(node)).withContexts(computer, env, ws).start();
}
 
Example #2
Source File: OneShotProvisionQueueListener.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
@Override
public void onLeft(final Queue.LeftItem li) {
    if (li.isCancelled()) {
        final DockerSwarmLabelAssignmentAction labelAssignmentAction = li
                .getAction(DockerSwarmLabelAssignmentAction.class);
        if (labelAssignmentAction != null) {
            final String computerName = labelAssignmentAction.getLabel().getName();

            final Node node = Jenkins.getInstance().getNode(computerName);
            Computer.threadPoolForRemoting.submit(() -> {
                try {
                    ((DockerSwarmAgent) node).terminate();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to terminate agent.", e);
                }
            });
        }
    }
}
 
Example #3
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
/**
 * Waits for a newly created slave to come online.
 * @see #createSlave()
 */
public void waitOnline(Slave s) throws Exception {
    Computer computer = s.toComputer();
    AtomicBoolean run = new AtomicBoolean(true);
    AnnotatedLargeText<?> logText = computer.getLogText();
    Computer.threadPoolForRemoting.submit(() -> {
        long pos = 0;
        while (run.get() && !logText.isComplete()) {
            pos = logText.writeLogTo(pos, System.out);
            Thread.sleep(100);
        }
        return null;
    });
    try {
        if (s.getLauncher().isLaunchSupported()) {
            computer.connect(false).get();
        } else {
            while (!computer.isOnline()) {
                Thread.sleep(100);
            }
        }
    } finally {
        run.set(false);
    }
}
 
Example #4
Source File: DockerSwarmAgentRetentionStrategy.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
private synchronized void done(final DockerSwarmComputer c) {
    c.setAcceptingTasks(false); // just in case
    if (terminating) {
        return;
    }
    terminating = true;
    Computer.threadPoolForRemoting.submit(() -> {
        Queue.withLock(() -> {
            DockerSwarmAgent node = c.getNode();
            if (node != null) {
                try {
                    node.terminate();
                } catch (IOException e) {
                }
            }
        });
    });
}
 
Example #5
Source File: KafkaKubernetesCloud.java    From remoting-kafka-plugin with MIT License 6 votes vote down vote up
@Override
public Collection<PlannedNode> provision(Label label, int excessWorkload) {
    Set<String> allInProvisioning = getNodesInProvisioning(label);
    LOGGER.info("In provisioning : " + allInProvisioning);
    int toBeProvisioned = Math.max(0, excessWorkload - allInProvisioning.size());
    LOGGER.info("Excess workload after pending Kubernetes agents: " + toBeProvisioned);

    List<PlannedNode> provisionNodes = new ArrayList<>();
    for (int i = 0; i < toBeProvisioned; i++) {
        PlannedNode node = new PlannedNode(name,
                Computer.threadPoolForRemoting.submit(() -> new KafkaCloudSlave(this)),
                AGENT_NUM_EXECUTORS);
        provisionNodes.add(node);
    }
    return provisionNodes;
}
 
Example #6
Source File: EC2FleetCloudAwareUtilsTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
    PowerMockito.mockStatic(LabelFinder.class);

    PowerMockito.mockStatic(Jenkins.class);
    PowerMockito.when(Jenkins.getActiveInstance()).thenReturn(jenkins);

    when(oldCloud.getOldId()).thenReturn("cloud");
    when(computer.getCloud()).thenReturn(oldCloud);
    when(node.getCloud()).thenReturn(oldCloud);

    when(cloud.getOldId()).thenReturn("cloud");
    when(otherCloud.getOldId()).thenReturn("other");

    when(jenkins.getNodes()).thenReturn(Collections.<Node>emptyList());
    when(jenkins.getComputers()).thenReturn(new Computer[0]);
}
 
Example #7
Source File: DbBackedBuild.java    From DotCi with MIT License 6 votes vote down vote up
@Override
@Exported
public Executor getExecutor() {
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        return null;
    }
    for (final Computer computer : jenkins.getComputers()) {
        for (final Executor executor : computer.getExecutors()) {
            if (isCurrent(executor)) {
                return executor;
            }
        }
    }
    return null;
}
 
Example #8
Source File: ContainerExecDecoratorTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
@Issue("JENKINS-58975")
public void testContainerExecOnCustomWorkingDirWithComputeEnvVars() throws Exception {
    EnvVars computeEnvVars = new EnvVars();
    computeEnvVars.put("MyDir", "dir");
    computeEnvVars.put("MyCustomDir", "/home/jenkins/agent");
    Computer computer = mock(Computer.class);
    doReturn(computeEnvVars).when(computer).getEnvironment();

    doReturn(computer).when((Node)agent).toComputer();
    ProcReturn r = execCommandInContainer("busybox1", agent, false, "env");
    assertTrue("Environment variable workingDir1 should be changed to /home/jenkins/agent1",
            r.output.contains("workingDir1=/home/jenkins/agent1"));
    assertTrue("Environment variable MyCustomDir should be changed to /home/jenkins/agent1",
            r.output.contains("MyCustomDir=/home/jenkins/agent1"));
    assertEquals(0, r.exitCode);
    assertFalse(r.proc.isAlive());
}
 
Example #9
Source File: ContainerRecordUtils.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
public static void attachFacet(Run<?, ?> run, TaskListener listener) {
    final Executor executor = run.getExecutor();
    if (executor == null) {
        return;
    }

    final Computer owner = executor.getOwner();
    DockerComputer dockerComputer;
    if (owner instanceof DockerComputer) {
        dockerComputer = (DockerComputer) owner;
        try {
            DockerFingerprints.addRunFacet(
                    createRecordFor(dockerComputer),
                    run
            );
        } catch (IOException | ParseException e) {
            listener.error("Can't add Docker fingerprint to run.");
            LOG.error("Can't add fingerprint to run {}", run, e);
        }
    }


}
 
Example #10
Source File: DockerOnceRetentionStrategy.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
protected void done(final AbstractCloudComputer<?> c) {
    c.setAcceptingTasks(false); // just in case
    synchronized (this) {
        if (terminating) {
            return;
        }
        terminating = true;
    }

    Computer.threadPoolForRemoting.submit(() -> {
            try {
                AbstractCloudSlave node = c.getNode();
                if (node != null) {
                    node.terminate();
                }
            } catch (InterruptedException | IOException e) {
                LOG.warn("Failed to terminate " + c.getName(), e);
                synchronized (DockerOnceRetentionStrategy.this) {
                    terminating = false;
                }
            }
        }
    );
}
 
Example #11
Source File: ComputerOnlineEventImpl.java    From jenkins-datadog-plugin with MIT License 6 votes vote down vote up
public ComputerOnlineEventImpl(Computer computer, TaskListener listener, Map<String, Set<String>> tags, boolean isTemporarily) {
    super(tags);

    String nodeName = DatadogUtilities.getNodeName(computer);
    setAggregationKey(nodeName);

    String title = "Jenkins node " + nodeName + " is" + (isTemporarily ? " temporarily " : " ") + "online";
    setTitle(title);

    String text = "%%% \nJenkins node " + nodeName + " is" + (isTemporarily ? " temporarily " : " ") +
            "online \n%%%";
    setText(text);

    setPriority(Priority.LOW);
    setAlertType(AlertType.SUCCESS);
}
 
Example #12
Source File: ComputerOfflineEventImpl.java    From jenkins-datadog-plugin with MIT License 6 votes vote down vote up
public ComputerOfflineEventImpl(Computer computer, OfflineCause cause, Map<String, Set<String>> tags, boolean isTemporarily) {
    super(tags);

    String nodeName = DatadogUtilities.getNodeName(computer);
    setAggregationKey(nodeName);

    String title = "Jenkins node " + nodeName + " is" + (isTemporarily? " temporarily ": " ") + "offline";
    setTitle(title);

    // TODO: Add more info about the case in the event in message.
    String text = "%%% \nJenkins node " + nodeName + " is" + (isTemporarily? " temporarily ": " ") +
            "offline \n%%%";
    setText(text);

    setPriority(Priority.NORMAL);
    setAlertType(AlertType.WARNING);
}
 
Example #13
Source File: ZAProxyBuilder.java    From zaproxy-plugin with MIT License 5 votes vote down vote up
/**
    * Replace macro with environment variable if it exists
    * @param build
    * @param listener
    * @param macro
    * @return
    * @throws InterruptedException
    */
   @SuppressWarnings({ "unchecked", "rawtypes" })
public static String applyMacro(AbstractBuild build, BuildListener listener, String macro)
           throws InterruptedException{
       try {
           EnvVars envVars = new EnvVars(Computer.currentComputer().getEnvironment());
           envVars.putAll(build.getEnvironment(listener));
           envVars.putAll(build.getBuildVariables());
           return Util.replaceMacro(macro, envVars);
       } catch (IOException e) {
       	listener.getLogger().println("Failed to apply macro " + macro);
        listener.error(ExceptionUtils.getStackTrace(e));
       }
       return macro;
   }
 
Example #14
Source File: RestartSurvivabilityTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
private FolderBasedAuthorizationStrategy createNewFolderBasedAuthorizationStrategy() {
    Set<GlobalRole> globalRoles = new HashSet<>();
    globalRoles.add(new GlobalRole("admin", wrapPermissions(Jenkins.ADMINISTER), ImmutableSet.of("admin")));
    globalRoles.add(new GlobalRole("read", wrapPermissions(Jenkins.READ), ImmutableSet.of("authenticated")));

    Set<FolderRole> folderRoles = new HashSet<>();
    folderRoles.add(new FolderRole("read", wrapPermissions(Item.READ), ImmutableSet.of("folder"),
        ImmutableSet.of("user1")));

    Set<AgentRole> agentRoles = new HashSet<>();
    agentRoles.add(new AgentRole("configureMaster", wrapPermissions(Computer.CONFIGURE),
        Collections.singleton("foo"), Collections.singleton("user1")));

    return new FolderBasedAuthorizationStrategy(globalRoles, folderRoles, agentRoles);
}
 
Example #15
Source File: DockerSSHConnector.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    if (context instanceof AccessControlled) {
        if (!((AccessControlled) context).hasPermission(Computer.CONFIGURE)) {
            return new ListBoxModel();
        }
    } else {
        if (!Jenkins.getInstance().hasPermission(Computer.CONFIGURE)) {
            return new ListBoxModel();
        }
    }
    return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class),
            CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context,
                    ACL.SYSTEM, SSH_SCHEME));
}
 
Example #16
Source File: JenkinsRuleHelpers.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
/**
 * Returns true if Hudson is building something or going to build something.
 */
public static boolean isSomethingHappening(Jenkins jenkins) {
    if (!jenkins.getQueue().isEmpty())
        return true;
    for (Computer n : jenkins.getComputers())
        if (!n.isIdle())
            return true;
    return false;
}
 
Example #17
Source File: DockerComputerListener.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
public void onLaunchFailure(Computer comp, TaskListener taskListener) throws IOException, InterruptedException {
    if (comp instanceof DockerComputer) {
        DockerComputer dockerComputer = (DockerComputer) comp;
        if (dockerComputer.getLauncher() instanceof DockerComputerIOLauncher) {
            taskListener.error("Failed to launch");
        }
    }
}
 
Example #18
Source File: ConfigurationAsCodeTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("config3.yml")
public void configurationImportWithHumanReadableTest() {
    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("admin"))) {
        assertTrue(j.jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("user1"))) {
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(j.jenkins.hasPermission(Jenkins.ADMINISTER));

        assertTrue(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.CONFIGURE));
        assertFalse(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.DELETE));
    }
}
 
Example #19
Source File: FolderBasedAuthorizationStrategy.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Nonnull
@Override
public SidACL getACL(@Nonnull Computer computer) {
    String name = computer.getName();
    SidACL acl = agentAcls.get(name);
    if (acl == null) {
        return globalAcl;
    } else {
        // TODO: cache these ACLs
        return globalAcl.newInheritingACL(acl);
    }
}
 
Example #20
Source File: AnsiblePlaybookBuilder.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath ws, @Nonnull Launcher launcher, @Nonnull TaskListener listener)
        throws InterruptedException, IOException
{
    Computer computer = Computer.currentComputer();
    if (computer == null) {
        throw new AbortException("The ansible playbook build step requires to be launched on a node");
    }
    perform(run, computer.getNode(), ws, launcher, listener, run.getEnvironment(listener));
}
 
Example #21
Source File: AnsibleAdHocCommandBuilder.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath ws, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException {
    try {
        CLIRunner runner = new CLIRunner(run, ws, launcher, listener);
        Computer computer = Computer.currentComputer();
        if (computer == null) {
            throw new AbortException("The ansible playbook build step requires to be launched on a node");
        }
        String exe = AnsibleInstallation.getExecutable(ansibleName, AnsibleCommand.ANSIBLE, computer.getNode(), listener, run.getEnvironment(listener));
        AnsibleAdHocCommandInvocation invocation = new AnsibleAdHocCommandInvocation(exe, run, ws, listener);
        invocation.setHostPattern(hostPattern);
        invocation.setInventory(inventory);
        invocation.setModule(module);
        invocation.setModuleCommand(command);
        invocation.setSudo(sudo, sudoUser);
        invocation.setForks(forks);
        invocation.setCredentials(StringUtils.isNotBlank(credentialsId) ?
                CredentialsProvider.findCredentialById(credentialsId, StandardUsernameCredentials.class, run) :
                null);
        invocation.setAdditionalParameters(additionalParameters);
        invocation.setHostKeyCheck(hostKeyChecking);
        invocation.setUnbufferedOutput(unbufferedOutput);
        invocation.setColorizedOutput(colorizedOutput);
        if (!invocation.execute(runner)) {
            throw new AbortException("Ansible Ad-Hoc command execution failed");
        }
    } catch (IOException ioe) {
        Util.displayIOException(ioe, listener);
        ioe.printStackTrace(listener.fatalError(hudson.tasks.Messages.CommandInterpreter_CommandFailed()));
        throw ioe;
    } catch (AnsibleInvocationException aie) {
        listener.fatalError(aie.getMessage());
        throw new AbortException(aie.getMessage());
    }
}
 
Example #22
Source File: ComputerLaunchFailedEventImpl.java    From jenkins-datadog-plugin with MIT License 5 votes vote down vote up
public ComputerLaunchFailedEventImpl(Computer computer, TaskListener listener, Map<String, Set<String>> tags) {
    super(tags);

    String nodeName = DatadogUtilities.getNodeName(computer);
    setAggregationKey(nodeName);

    String title = "Jenkins node " + nodeName + " failed to launch";
    setTitle(title);

    String text = "%%% \nJenkins node " + nodeName + " failed to launch \n%%%";
    setText(text);

    setPriority(Priority.NORMAL);
    setAlertType(AlertType.ERROR);
}
 
Example #23
Source File: RegistryEndpointStepTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test
public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception {
    assumeNotWindows();

    r.getInstance().setSecurityRealm(r.createDummySecurityRealm());
    MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
            .grant(Jenkins.READ).everywhere().to("alice", "bob")
            .grant(Computer.BUILD).everywhere().to("alice", "bob")
            // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById
            // uses when determining whether to include item-scope credentials in the search.
            .grant(Item.CONFIGURE).everywhere().to("alice");
    r.getInstance().setAuthorizationStrategy(auth);

    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials);

    String script = "node {\n" +
            "  mockDockerLoginWithEcho {\n" +
            "    withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" +
            "    }\n" +
            "  }\n" +
            "}";
    WorkflowJob p1 = r.createProject(WorkflowJob.class, "prj1");
    p1.setDefinition(new CpsFlowDefinition(script, true));
    WorkflowJob p2 = r.createProject(WorkflowJob.class, "prj2");
    p2.setDefinition(new CpsFlowDefinition(script, true));

    Map<String, Authentication> jobsToAuths = new HashMap<>();
    jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate());
    jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate());
    QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths));

    // Alice has Credentials.USE_ITEM permission and should be able to use the credential.
    WorkflowRun b1 = r.buildAndAssertSuccess(p1);
    r.assertLogContains("docker login -u me -p pass https://my-reg:1234", b1);

    // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential.
    r.assertBuildStatus(Result.FAILURE, p2.scheduleBuild2(0));
}
 
Example #24
Source File: ParallelsDesktopCloud.java    From jenkins-parallels with MIT License 5 votes vote down vote up
@Override
public Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload)
{
	LOGGER.log(Level.SEVERE, "Going to provision " + excessWorkload + " executors");
	Collection<NodeProvisioner.PlannedNode> result = new ArrayList<NodeProvisioner.PlannedNode>();
	final ParallelsDesktopConnectorSlaveComputer connector = getConnector();
	for (int i = 0; (i < vms.size()) && (excessWorkload > 0); i++)
	{
		final ParallelsDesktopVM vm = vms.get(i);
		if (vm.isProvisioned())
			continue;
		if (!label.matches(Label.parse(vm.getLabels())))
			continue;
		final String vmId = vm.getVmid();
		final String slaveName = name + " " + vmId;
		vm.setSlaveName(slaveName);
		vm.setProvisioned(true);
		--excessWorkload;
		result.add(new NodeProvisioner.PlannedNode(slaveName,
			Computer.threadPoolForRemoting.submit(new Callable<Node>()
			{
				@Override
				public Node call() throws Exception
				{
					connector.checkVmExists(vmId);
					return connector.createSlaveOnVM(vm);
				}
			}), 1));
	}
	return result;
}
 
Example #25
Source File: ChannelShutdownListener.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override
public synchronized void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
    VirtualChannel ch = c.getChannel();
    if (ch instanceof Channel) {
        channels.add((Channel)ch);
    }
}
 
Example #26
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Returns true if Hudson is building something or going to build something.
 */
public boolean isSomethingHappening() {
    if (!jenkins.getQueue().isEmpty())
        return true;
    for (Computer n : jenkins.getComputers())
        if (!n.isIdle())
            return true;
    return false;
}
 
Example #27
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public Set<Permission> getFolderPermissions() {
    HashSet<PermissionGroup> groups = new HashSet<>(PermissionGroup.getAll());
    groups.remove(PermissionGroup.get(Hudson.class));
    groups.remove(PermissionGroup.get(Computer.class));
    groups.remove(PermissionGroup.get(Permission.class));
    return getSafePermissions(groups);
}
 
Example #28
Source File: DummyCloudImpl.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public Collection<PlannedNode> provision(Label label, int excessWorkload) {
    List<PlannedNode> r = new ArrayList<PlannedNode>();
    if(label!=this.label)   return r;   // provisioning impossible

    while(excessWorkload>0) {
        System.out.println("Provisioning");
        numProvisioned++;
        Future<Node> f = Computer.threadPoolForRemoting.submit(new Launcher(delay));
        r.add(new PlannedNode(name+" #"+numProvisioned,f,1));
        excessWorkload-=1;
    }
    return r;
}
 
Example #29
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the computer for the current launcher.
 *
 * @return the computer
 * @throws AbortException in case of error.
 */
@Nonnull
private Computer getComputer() throws AbortException {
    if (computer != null) {
        return computer;
    }

    String node = null;
    Jenkins j = Jenkins.getInstance();

    for (Computer c : j.getComputers()) {
        if (c.getChannel() == launcher.getChannel()) {
            node = c.getName();
            break;
        }
    }

    if (node == null) {
        throw new AbortException("Could not find computer for the job");
    }

    computer = j.getComputer(node);
    if (computer == null) {
        throw new AbortException("No such computer " + node);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Computer: {0}", computer.getName());
        try {
            LOGGER.log(Level.FINE, "Env: {0}", computer.getEnvironment());
        } catch (IOException | InterruptedException e) {// ignored
        }
    }
    return computer;
}
 
Example #30
Source File: ConfigurationAsCodeTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("config.yml")
public void configurationImportTest() {
    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("admin"))) {
        assertTrue(j.jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("user1"))) {
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(j.jenkins.hasPermission(Jenkins.ADMINISTER));

        assertTrue(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.CONFIGURE));
        assertFalse(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.DELETE));
    }
}