diff --git a/README.md b/README.md index 81ae7a7..695df3d 100644 --- a/README.md +++ b/README.md @@ -29,3 +29,7 @@ Sample response: } } ``` + +## Run script on agent + +`curl http://localhost/jenkins/instance/run?agent=&script=println%20"uname%20-a".execute().text -X POST` diff --git a/src/main/java/io/jenkins/plugins/pipeline/restful/api/InstanceAPI.java b/src/main/java/io/jenkins/plugins/pipeline/restful/api/InstanceAPI.java index 82d8f63..bb35c36 100644 --- a/src/main/java/io/jenkins/plugins/pipeline/restful/api/InstanceAPI.java +++ b/src/main/java/io/jenkins/plugins/pipeline/restful/api/InstanceAPI.java @@ -2,9 +2,12 @@ import com.cloudbees.workflow.util.ServeJson; import hudson.Extension; +import hudson.model.Computer; import hudson.model.RootAction; import hudson.model.User; +import hudson.remoting.VirtualChannel; import hudson.util.HttpResponses; +import hudson.util.RemotingDiagnostics; import jenkins.model.Jenkins; import jenkins.model.identity.IdentityRootAction; import jenkins.security.ApiTokenProperty; @@ -167,6 +170,41 @@ public void setWriteListener(WriteListener writeListener) { rsp.setContentLength(result.length()); rsp.getWriter().write(result); } + + @RequirePOST + public HttpResponse doRun(@QueryParameter String script, @QueryParameter String agent, StaplerRequest req) { + if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) { + return HttpResponses.errorJSON("no permission to execute script on '" + agent + "'"); + } + + try { + JSONObject data = req.getSubmittedForm(); + + script = script == null ? data.getString("script") : script; + agent = agent == null ? data.getString("agent") : agent; + } catch (ServletException e) { + e.printStackTrace(); + } + + Computer computer = Jenkins.get().getComputer(agent); + if (computer == null) { + return HttpResponses.errorJSON("cannot find agent: " + agent); + } + + VirtualChannel channel = computer.getChannel(); + if (channel == null) { + return HttpResponses.errorJSON(agent + " is offline"); + } + + JSONObject output = new JSONObject(); + try { + output.put("message", RemotingDiagnostics.executeGroovy(script, channel)); + } catch (IOException | InterruptedException e) { + return HttpResponses.errorJSON(e.getMessage()); + } + + return HttpResponses.okJSON(output); + } } class JenkinsInstance {