-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
CLIAction.java
337 lines (302 loc) · 11.4 KB
/
CLIAction.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
* The MIT License
*
* Copyright (c) 2013 Red Hat, Inc.
*
* 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 hudson.cli;
import hudson.Extension;
import hudson.model.UnprotectedRootAction;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import jenkins.model.Jenkins;
import jenkins.util.FullDuplexHttpService;
import jenkins.websocket.WebSocketSession;
import jenkins.websocket.WebSockets;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.springframework.security.core.Authentication;
/**
* Shows usage of CLI and commands.
*
* @author ogondza
*/
@Extension @Symbol("cli")
@Restricted(NoExternalUse.class)
public class CLIAction implements UnprotectedRootAction, StaplerProxy {
private static final Logger LOGGER = Logger.getLogger(CLIAction.class.getName());
private final transient Map<UUID, FullDuplexHttpService> duplexServices = new HashMap<>();
@Override
public String getIconFileName() {
return null;
}
@Override
public String getDisplayName() {
return "Jenkins CLI";
}
@Override
public String getUrlName() {
return "cli";
}
public void doCommand(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
final Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(Jenkins.READ);
// Strip trailing slash
final String commandName = req.getRestOfPath().substring(1);
CLICommand command = CLICommand.clone(commandName);
if (command == null) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND, "No such command");
return;
}
req.setAttribute("command", command);
req.getView(this, "command.jelly").forward(req, rsp);
}
/** for Jelly */
public boolean isWebSocketSupported() {
return WebSockets.isSupported();
}
/**
* WebSocket endpoint.
*/
public HttpResponse doWs() {
if (!WebSockets.isSupported()) {
return HttpResponses.notFound();
}
Authentication authentication = Jenkins.getAuthentication2();
return WebSockets.upgrade(new WebSocketSession() {
ServerSideImpl connection;
long sentBytes, sentCount, receivedBytes, receivedCount;
class OutputImpl implements PlainCLIProtocol.Output {
@Override
public void send(byte[] data) throws IOException {
sendBinary(ByteBuffer.wrap(data));
sentBytes += data.length;
sentCount++;
}
@Override
public void close() throws IOException {
doClose();
}
}
private void doClose() throws IOException {
close();
}
@Override
protected void opened() {
try {
connection = new ServerSideImpl(new OutputImpl(), authentication);
} catch (IOException x) {
error(x);
return;
}
new Thread(() -> {
try {
try {
connection.run();
} finally {
connection.close();
}
} catch (Exception x) {
error(x);
}
}, "CLI handler for " + authentication.getName()).start();
}
@Override
protected void binary(byte[] payload, int offset, int len) {
try {
connection.handle(new DataInputStream(new ByteArrayInputStream(payload, offset, len)));
receivedBytes += len;
receivedCount++;
} catch (IOException x) {
error(x);
}
}
@Override
protected void error(Throwable cause) {
LOGGER.log(Level.WARNING, null, cause);
}
@Override
protected void closed(int statusCode, String reason) {
LOGGER.fine(() -> "closed: " + statusCode + ": " + reason);
LOGGER.fine(() -> "received " + receivedCount + " packets of " + receivedBytes + " bytes; sent " + sentCount + " packets of " + sentBytes + " bytes");
connection.handleClose();
}
});
}
@Override
public Object getTarget() {
StaplerRequest req = Stapler.getCurrentRequest();
if (req.getRestOfPath().length() == 0 && "POST".equals(req.getMethod())) {
// CLI connection request
if ("false".equals(req.getParameter("remoting"))) {
throw new PlainCliEndpointResponse();
} else {
// remoting=true (the historical default) no longer supported.
throw HttpResponses.forbidden();
}
} else {
return this;
}
}
static class ServerSideImpl extends PlainCLIProtocol.ServerSide {
private Thread runningThread;
private boolean ready;
private final List<String> args = new ArrayList<>();
private Locale locale = Locale.getDefault();
private Charset encoding = Charset.defaultCharset();
private final PipedInputStream stdin = new PipedInputStream();
private final PipedOutputStream stdinMatch = new PipedOutputStream();
private final Authentication authentication;
ServerSideImpl(PlainCLIProtocol.Output out, Authentication authentication) throws IOException {
super(out);
stdinMatch.connect(stdin);
this.authentication = authentication;
}
@Override
protected void onArg(String text) {
args.add(text);
}
@Override
protected void onLocale(String text) {
for (Locale _locale : Locale.getAvailableLocales()) {
if (_locale.toString().equals(text)) {
locale = _locale;
return;
}
}
LOGGER.log(Level.WARNING, "unknown client locale {0}", text);
}
@Override
protected void onEncoding(String text) {
try {
encoding = Charset.forName(text);
} catch (UnsupportedCharsetException x) {
LOGGER.log(Level.WARNING, "unknown client charset {0}", text);
}
}
@Override
protected void onStart() {
ready();
}
@Override
protected void onStdin(byte[] chunk) throws IOException {
stdinMatch.write(chunk);
}
@Override
protected void onEndStdin() throws IOException {
stdinMatch.close();
}
@Override
protected void handleClose() {
ready();
if (runningThread != null) {
runningThread.interrupt();
}
}
private synchronized void ready() {
ready = true;
notifyAll();
}
void run() throws IOException, InterruptedException {
synchronized (this) {
while (!ready) {
wait();
}
}
PrintStream stdout = new PrintStream(streamStdout(), false, encoding);
PrintStream stderr = new PrintStream(streamStderr(), true, encoding);
if (args.isEmpty()) {
stderr.println("Connection closed before arguments received");
sendExit(2);
return;
}
String commandName = args.get(0);
CLICommand command = CLICommand.clone(commandName);
if (command == null) {
stderr.println("No such command " + commandName);
sendExit(2);
return;
}
command.setTransportAuth2(authentication);
command.setClientCharset(encoding);
CLICommand orig = CLICommand.setCurrent(command);
try {
runningThread = Thread.currentThread();
int exit = command.main(args.subList(1, args.size()), locale, stdin, stdout, stderr);
stdout.flush();
sendExit(exit);
try { // seems to avoid ReadPendingException from Jetty
Thread.sleep(1000);
} catch (InterruptedException x) {
// expected; ignore
}
} finally {
CLICommand.setCurrent(orig);
runningThread = null;
}
}
}
/**
* Serves {@link PlainCLIProtocol} response.
*/
private class PlainCliEndpointResponse extends FullDuplexHttpService.Response {
PlainCliEndpointResponse() {
super(duplexServices);
}
@Override
protected FullDuplexHttpService createService(StaplerRequest req, UUID uuid) throws IOException {
return new FullDuplexHttpService(uuid) {
@Override
protected void run(InputStream upload, OutputStream download) throws IOException, InterruptedException {
try (ServerSideImpl connection = new ServerSideImpl(new PlainCLIProtocol.FramedOutput(download), Jenkins.getAuthentication2())) {
new PlainCLIProtocol.FramedReader(connection, upload).start();
connection.run();
}
}
};
}
}
}