/
ScriptlerManagment.java
595 lines (526 loc) · 21.8 KB
/
ScriptlerManagment.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*
* The MIT License
*
* Copyright (c) 2010, Dominik Bartholdi
*
* 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 org.jenkinsci.plugins.scriptler;
import hudson.Extension;
import hudson.Util;
import hudson.PluginWrapper;
import hudson.model.ManagementLink;
import hudson.model.RootAction;
import hudson.model.ComputerSet;
import hudson.model.Hudson;
import hudson.security.Permission;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.scriptler.config.Parameter;
import org.jenkinsci.plugins.scriptler.config.Script;
import org.jenkinsci.plugins.scriptler.config.ScriptlerConfiguration;
import org.jenkinsci.plugins.scriptler.share.CatalogInfo;
import org.jenkinsci.plugins.scriptler.share.ScriptInfo;
import org.jenkinsci.plugins.scriptler.share.ScriptInfoCatalog;
import org.jenkinsci.plugins.scriptler.util.ScriptHelper;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* Creates the link on the "manage Jenkins" page and handles all the web requests.
*
* @author Dominik Bartholdi (imod)
*/
@Extension
public class ScriptlerManagment extends ManagementLink implements RootAction {
private final static Logger LOGGER = Logger.getLogger(ScriptlerManagment.class.getName());
private final static String MASTER = "(master)";
private final static String ALL = "(all)";
private final static String ALL_SLAVES = "(all slaves)";
private boolean isRunScriptPermissionEnabled() {
return getConfiguration().isAllowRunScriptPermission();
}
private Permission getRequiredPermissionForRunScript() {
return isRunScriptPermissionEnabled() ? Jenkins.RUN_SCRIPTS : Jenkins.ADMINISTER;
}
/*
* (non-Javadoc)
*
* @see hudson.model.ManagementLink#getIconFileName()
*/
@Override
public String getIconFileName() {
return Jenkins.getInstance().hasPermission(getRequiredPermissionForRunScript()) ? "notepad.gif" : null;
}
/*
* (non-Javadoc)
*
* @see hudson.model.ManagementLink#getUrlName()
*/
@Override
public String getUrlName() {
return "scriptler";
}
public boolean disableRemoteCatalog() {
return getConfiguration().isDisbableRemoteCatalog();
}
public boolean allowRunScriptEdit() {
return getConfiguration().isAllowRunScriptEdit();
}
public boolean allowRunScriptPermission() {
return getConfiguration().isAllowRunScriptPermission();
}
/*
* (non-Javadoc)
*
* @see hudson.model.Action#getDisplayName()
*/
public String getDisplayName() {
return Messages.display_name();
}
@Override
public String getDescription() {
return Messages.description();
}
public ScriptlerManagment getScriptler() {
return this;
}
public ScriptlerConfiguration getConfiguration() {
return ScriptlerConfiguration.getConfiguration();
}
public String getPluginResourcePath() {
PluginWrapper wrapper = Hudson.getInstance().getPluginManager().getPlugin(ScritplerPluginImpl.class);
return Hudson.getInstance().getRootUrl() + "plugin/" + wrapper.getShortName() + "/";
}
/**
* save the scriptler 'global' settings (on settings screen, not global Jenkins config)
*
* @param res
* @param rsp
* @param disableRemoteCatalog
* @param allowRunScriptPermission
* @param allowRunScriptEdit
* @return
* @throws IOException
*/
public HttpResponse doScriptlerSettings(StaplerRequest res, StaplerResponse rsp, @QueryParameter("disableRemoteCatalog") boolean disableRemoteCatalog,
@QueryParameter("allowRunScriptPermission") boolean allowRunScriptPermission, @QueryParameter("allowRunScriptEdit") boolean allowRunScriptEdit)
throws IOException {
checkPermission(Hudson.ADMINISTER);
ScriptlerConfiguration cfg = getConfiguration();
cfg.setDisbableRemoteCatalog(disableRemoteCatalog);
cfg.setAllowRunScriptEdit(allowRunScriptEdit);
cfg.setAllowRunScriptPermission(allowRunScriptPermission);
cfg.save();
return new HttpRedirect("settings");
}
/**
* Downloads a script from a catalog and imports it to the local system.
*
* @param res
* request
* @param rsp
* response
* @param id
* the id of the file to be downloaded
* @param catalogName
* the catalog to download the file from
* @return same forward as from <code>doScriptAdd</code>
* @throws IOException
* @throws ServletException
*/
public HttpResponse doDownloadScript(StaplerRequest req, StaplerResponse rsp, @QueryParameter("id") String id, @QueryParameter("catalog") String catalogName)
throws IOException, ServletException {
checkPermission(Hudson.ADMINISTER);
ScriptlerConfiguration c = getConfiguration();
if (c.isDisbableRemoteCatalog()) {
return new HttpRedirect("index");
}
for (ScriptInfoCatalog scriptInfoCatalog : ScriptInfoCatalog.all()) {
if (catalogName.equals(scriptInfoCatalog.getInfo().name)) {
final ScriptInfo info = scriptInfoCatalog.getEntryById(id);
final String source = scriptInfoCatalog.getScriptSource(info);
final List<Parameter> paramList = new ArrayList<Parameter>();
for (String paramName : info.getParameters()) {
paramList.add(new Parameter(paramName, null));
}
Parameter[] parameters = paramList.toArray(new Parameter[paramList.size()]);
final String finalName = saveScriptAndForward(id, info.getName(), info.getComment(), source, false, catalogName, id, parameters);
return new HttpRedirect("editScript?id=" + finalName);
}
}
final ForwardToView view = new ForwardToView(this, "catalog.jelly");
view.with("message", Messages.download_failed(id, catalogName));
view.with("catName", catalogName);
return view;
}
/**
* Saves a script snipplet as file to the system.
*
* @param req
* response
* @param rsp
* request
* @param id
* the script id (fileName)
* @param name
* the name of the script
* @param comment
* a comment
* @param script
* script code
* @param catalogName
* (optional) the name of the catalog the script is loaded/added from
* @param originId
* (optional) the original id the script had at the catalog
* @return forward to 'index'
* @throws IOException
* @throws ServletException
*/
public HttpResponse doScriptAdd(StaplerRequest req, StaplerResponse rsp, @QueryParameter("id") String id, @QueryParameter("name") String name,
@QueryParameter("comment") String comment, @QueryParameter("script") String script,
@QueryParameter("nonAdministerUsing") boolean nonAdministerUsing, String originCatalogName, String originId) throws IOException, ServletException {
checkPermission(Hudson.ADMINISTER);
Parameter[] parameters = extractParameters(req);
saveScriptAndForward(id, name, comment, script, nonAdministerUsing, originCatalogName, originId, parameters);
return new HttpRedirect("index");
}
/**
* Extracts the parameters from the given request
*
* @param req
* the request potentially containing parameters
* @return parameters - might be an empty array, but never <code>null</code>.
* @throws ServletException
*/
private Parameter[] extractParameters(StaplerRequest req) throws ServletException {
Parameter[] parameters = new Parameter[0];
final JSONObject json = req.getSubmittedForm();
final JSONObject defineParams = json.getJSONObject("defineParams");
if (!defineParams.isNullObject()) {
JSONObject argsObj = defineParams.optJSONObject("parameters");
if (argsObj == null) {
JSONArray argsArrayObj = defineParams.optJSONArray("parameters");
if (argsArrayObj != null) {
parameters = (Parameter[]) JSONArray.toArray(argsArrayObj, Parameter.class);
}
} else {
Parameter param = (Parameter) JSONObject.toBean(argsObj, Parameter.class);
parameters = new Parameter[] { param };
}
}
return parameters;
}
/**
* Save the script details and return the forward to index
*
* @return the final name of the saved script - which is also the id of the script!
* @throws IOException
*/
private String saveScriptAndForward(String id, String name, String comment, String script, boolean nonAdministerUsing, String originCatalogName,
String originId, Parameter[] parameters) throws IOException {
script = script == null ? "TODO" : script;
if (StringUtils.isEmpty(id)) {
throw new IllegalArgumentException("'id' must not be empty!");
}
final String displayName = name == null ? id : name;
final String finalFileName = fixFileName(originCatalogName, id);
// save (overwrite) the file/script
File newScriptFile = new File(getScriptDirectory(), finalFileName);
Writer writer = new FileWriter(newScriptFile);
writer.write(script);
writer.close();
Script newScript = null;
if (!StringUtils.isEmpty(originId)) {
newScript = new Script(finalFileName, displayName, comment, true, originCatalogName, originId,
new SimpleDateFormat("dd MMM yyyy HH:mm:ss a").format(new Date()), parameters);
} else {
// save (overwrite) the meta information
newScript = new Script(finalFileName, displayName, comment, nonAdministerUsing, parameters);
}
ScriptlerConfiguration cfg = getConfiguration();
cfg.addOrReplace(newScript);
cfg.save();
return finalFileName;
}
/**
* Removes a script from the config and filesystem.
*
* @param res
* response
* @param rsp
* request
* @param name
* the name of the file to be removed
* @return forward to 'index'
* @throws IOException
*/
public HttpResponse doRemoveScript(StaplerRequest res, StaplerResponse rsp, @QueryParameter("id") String id) throws IOException {
checkPermission(Hudson.ADMINISTER);
// remove the file
File oldScript = new File(getScriptDirectory(), id);
oldScript.delete();
// remove the meta information
ScriptlerConfiguration cfg = getConfiguration();
cfg.removeScript(id);
cfg.save();
return new HttpRedirect("index");
}
/**
* Uploads a script and stores it with the given filename to the configuration. It will be stored on the filessytem.
*
* @param req
* request
* @return forward to index page.
* @throws IOException
* @throws ServletException
*/
public HttpResponse doUploadScript(StaplerRequest req) throws IOException, ServletException {
checkPermission(Hudson.ADMINISTER);
try {
File rootDir = getScriptDirectory();
FileItem fileItem = req.getFileItem("file");
boolean nonAdministerUsing = req.getSubmittedForm().getBoolean("nonAdministerUsing");
String fileName = Util.getFileName(fileItem.getName());
if (StringUtils.isEmpty(fileName)) {
return new HttpRedirect(".");
}
// upload can only be to/from local catalog
fileName = fixFileName(null, fileName);
fileItem.write(new File(rootDir, fileName));
Script script = ScriptHelper.getScript(fileName, false);
if (script == null) {
script = new Script(fileName, "uploaded");
}
script.setNonAdministerUsing(nonAdministerUsing);
ScriptlerConfiguration config = getConfiguration();
config.addOrReplace(script);
return new HttpRedirect("index");
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new ServletException(e);
}
}
/**
* Display the screen to trigger a script. The source of the script get loaded from the filesystem and placed in the request to display it on the page before execution.
*
* @param req
* request
* @param rsp
* response
* @param scriptName
* the name of the script to be executed
* @throws IOException
* @throws ServletException
*/
public void doRunScript(StaplerRequest req, StaplerResponse rsp, @QueryParameter("id") String id) throws IOException, ServletException {
Script script = ScriptHelper.getScript(id, true);
checkPermission(getRequiredPermissionForRunScript());
final boolean isAdmin = Jenkins.getInstance().getACL().hasPermission(Jenkins.ADMINISTER);
final boolean isChangeScriptAllowed = isAdmin || allowRunScriptEdit();
req.setAttribute("script", script);
req.setAttribute("readOnly", !isChangeScriptAllowed);
// set default selection
req.setAttribute("currentNode", MASTER);
req.getView(this, "runscript.jelly").forward(req, rsp);
}
/**
* Trigger/run/execute the script on a slave and show the result/output. The request then gets forward to <code>runscript.jelly</code> (This is usually also where the request came from). The
* script passed to this method gets restored in the request again (and not loaded from the system). This way one is able to modify the script before execution and reuse the modified version for
* further executions.
*
* @param req
* request
* @param rsp
* response
* @param scriptName
* the name of the script
* @param scriptSrc
* the script code (groovy)
* @param node
* the node, to execute the code on.
* @throws IOException
* @throws ServletException
*/
public void doTriggerScript(StaplerRequest req, StaplerResponse rsp, @QueryParameter("id") String id, @QueryParameter("script") String scriptSrc,
@QueryParameter("node") String node) throws IOException, ServletException {
checkPermission(getRequiredPermissionForRunScript());
final Parameter[] parameters = extractParameters(req);
Script tempScript = null;
final boolean isAdmin = Jenkins.getInstance().getACL().hasPermission(Jenkins.ADMINISTER);
final boolean isChangeScriptAllowed = isAdmin || allowRunScriptEdit();
if (!isChangeScriptAllowed) {
tempScript = ScriptHelper.getScript(id, true);
// use original script, user has no permission to change it!s
scriptSrc = tempScript.script;
} else {
// set the script info back to the request, to display it together with
// the output.
tempScript = ScriptHelper.getScript(id, false);
tempScript.setScript(scriptSrc);
}
final String[] slaves = resolveSlaveNames(node);
String output = ScriptHelper.runScript(slaves, scriptSrc, parameters);
tempScript.setParameters(parameters);// show the same parameters to the user
req.setAttribute("script", tempScript);
req.setAttribute("currentNode", node);
req.setAttribute("output", output);
req.setAttribute("readOnly", !isChangeScriptAllowed);
req.getView(this, "runscript.jelly").forward(req, rsp);
}
private String[] resolveSlaveNames(String nameAlias) {
List<String> slaves = null;
if (nameAlias.equalsIgnoreCase(ALL) || nameAlias.equalsIgnoreCase(ALL_SLAVES)) {
slaves = this.getSlaveNames();
if (nameAlias.equalsIgnoreCase(ALL)) {
if (!slaves.contains(MASTER)) {
slaves.add(MASTER);
}
}
if (nameAlias.equalsIgnoreCase(ALL_SLAVES)) {
// take the master node out of the loop if we said all slaves
slaves.remove(MASTER);
}
} else {
slaves = Arrays.asList(nameAlias);
}
return slaves.toArray(new String[slaves.size()]);
}
/**
* Loads the script by its name and forwards the request to "edit.jelly".
*
* @param req
* request
* @param rsp
* response
* @param scriptName
* the name of the script to be loaded in to the edit view.
* @throws IOException
* @throws ServletException
*/
public void doEditScript(StaplerRequest req, StaplerResponse rsp, @QueryParameter("id") String id) throws IOException, ServletException {
checkPermission(Hudson.ADMINISTER);
Script script = ScriptHelper.getScript(id, true);
req.setAttribute("script", script);
req.getView(this, "edit.jelly").forward(req, rsp);
}
/**
* Gets the names of all configured slaves, regardless whether they are online, including alias of ALL and ALL_SLAVES
*
* @return list with all slave names
*/
public List<String> getSlaveAlias() {
final List<String> slaveNames = getSlaveNames();
// add 'magic' name for master, so all nodes can be handled the same way
if (!slaveNames.contains(MASTER)) {
slaveNames.add(0, MASTER);
}
if (slaveNames.size() > 0) {
if (!slaveNames.contains(ALL)) {
slaveNames.add(1, ALL);
}
if (!slaveNames.contains(ALL_SLAVES)) {
slaveNames.add(2, ALL_SLAVES);
}
}
return slaveNames;
}
private List<String> getSlaveNames() {
ComputerSet computers = Jenkins.getInstance().getComputer();
List<String> slaveNames = computers.get_slaveNames();
// slaveNames is unmodifiable, therefore create a new list
List<String> slaves = new ArrayList<String>();
slaves.addAll(slaveNames);
return slaves;
}
/**
* Gets the remote catalogs containing the available scripts for download.
*
* @return the catalog
*/
public List<ScriptInfoCatalog> getCatalogs() {
return ScriptInfoCatalog.all();
}
public ScriptInfoCatalog<? extends ScriptInfo> getCatalogByName(String catalogName) {
if (StringUtils.isNotBlank(catalogName)) {
for (ScriptInfoCatalog<? extends ScriptInfo> sic : getCatalogs()) {
final CatalogInfo info = sic.getInfo();
if (catalogName.equals(info.name)) {
return sic;
}
}
}
return null;
}
public CatalogInfo getCatalogInfoByName(String catalogName) {
if (StringUtils.isNotBlank(catalogName)) {
for (ScriptInfoCatalog<? extends ScriptInfo> sic : getCatalogs()) {
final CatalogInfo info = sic.getInfo();
if (catalogName.equals(info.name)) {
return info;
}
}
}
return null;
}
/**
* returns the directory where the script files get stored
*
* @return the script directory
*/
public static File getScriptDirectory() {
return new File(getScriptlerHomeDirectory(), "scripts");
}
public static File getScriptlerHomeDirectory() {
return new File(Hudson.getInstance().getRootDir(), "scriptler");
}
private void checkPermission(Permission permission) {
Hudson.getInstance().checkPermission(permission);
}
private String fixFileName(String catalogName, String name) {
if (!name.endsWith(".groovy")) {
if (!StringUtils.isEmpty(catalogName)) {
name += "." + catalogName;
}
name += ".groovy";
}
// make sure we don't have spaces in the filename
name = name.replace(" ", "_").trim();
LOGGER.fine("set file name to: " + name);
return name;
}
}