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 API to run script on agent #16

Open
wants to merge 2 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down