forked from BimberLab/DiscvrLabKeyModules
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAbstractCommandWrapper.java
More file actions
363 lines (314 loc) · 10.1 KB
/
AbstractCommandWrapper.java
File metadata and controls
363 lines (314 loc) · 10.1 KB
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
/*
* Copyright (c) 2012-2015 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.api.sequenceanalysis.run;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.jetbrains.annotations.Nullable;
import org.labkey.api.pipeline.PipelineJobException;
import org.labkey.api.pipeline.PipelineJobService;
import org.labkey.api.sequenceanalysis.pipeline.SequencePipelineService;
import org.labkey.api.util.StringUtilsLabKey;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is the basic wrapper around command line tools. It should manage the available arguments and
* handle constructing and executing the command
*/
abstract public class AbstractCommandWrapper implements CommandWrapper
{
private File _outputDir = null;
private File _workingDir = null;
private Logger _log;
private boolean _logPath = false;
private Level _logLevel = Level.DEBUG;
private boolean _warnNonZeroExits = true;
private boolean _throwNonZeroExits = true;
private Integer _lastReturnCode = null;
private final Map<String, String> _environment = new HashMap<>();
private final List<String> _commandsExecuted = new ArrayList<>();
public AbstractCommandWrapper(@Nullable Logger logger)
{
_log = logger;
//Apply some default environment vars:
for (String varName : Arrays.asList("HOME", "UID", "JAVA_HOME"))
{
String val = StringUtils.trimToNull(System.getenv(varName));
if (val != null)
{
_environment.put(varName, val);
}
}
}
@Override
public void execute(List<String> params) throws PipelineJobException
{
execute(params, null, null);
}
@Override
public String executeWithOutput(List<String> params) throws PipelineJobException
{
StringBuffer ret = new StringBuffer();
execute(params, null, ret);
return ret.toString();
}
public void addToEnvironment(String key, String value)
{
_environment.put(key, value);
}
@Override
public List<String> getCommandsExecuted()
{
return _commandsExecuted;
}
@Override
public void execute(List<String> params, File stdout) throws PipelineJobException
{
execute(params, ProcessBuilder.Redirect.to(stdout));
}
@Override
public void execute(List<String> params, ProcessBuilder.Redirect redirect) throws PipelineJobException
{
execute(params, redirect, null);
}
public ProcessBuilder getProcessBuilder(List<String> params)
{
ProcessBuilder pb = new ProcessBuilder(params);
setPath(pb);
if (!_environment.isEmpty())
{
pb.environment().putAll(_environment);
}
if (getWorkingDir() != null)
{
getLogger().log(_logLevel, "using working directory: " + getWorkingDir().getPath());
pb.directory(getWorkingDir());
}
return pb;
}
public void executeWithOutput(List<String> params, StringBuffer output) throws PipelineJobException
{
execute(params, null, output);
}
private void execute(List<String> params, ProcessBuilder.Redirect redirect, @Nullable StringBuffer output) throws PipelineJobException
{
getLogger().info("\t" + StringUtils.join(params, " "));
_commandsExecuted.add(StringUtils.join(params, " "));
ProcessBuilder pb = getProcessBuilder(params);
pb.redirectErrorStream(false);
if (redirect != null)
{
if (redirect.file() != null)
{
getLogger().info("\tredirecting STDOUT to: " + redirect.file().getPath());
}
pb.redirectOutput(redirect);
}
else
{
pb.redirectErrorStream(true);
}
Process p = null;
try
{
p = pb.start();
try (BufferedReader procReader = new BufferedReader(new InputStreamReader(redirect == null ? p.getInputStream() : p.getErrorStream(), StringUtilsLabKey.DEFAULT_CHARSET)))
{
String line;
while ((line = procReader.readLine()) != null)
{
if (output != null)
{
output.append(line);
output.append(System.getProperty("line.separator"));
}
getLogger().log(_logLevel, "\t" + line);
}
}
_lastReturnCode = p.waitFor();
if (_lastReturnCode != 0 && _warnNonZeroExits)
{
getLogger().warn("\tprocess exited with non-zero value: " + _lastReturnCode);
}
if (_lastReturnCode != 0 && _throwNonZeroExits)
{
throw new PipelineJobException("process exited with non-zero value: " + _lastReturnCode);
}
}
catch (IOException | InterruptedException e)
{
throw new PipelineJobException(e);
}
finally
{
if (p != null)
{
p.destroy();
}
}
}
public Integer getLastReturnCode()
{
return _lastReturnCode;
}
private void setPath(ProcessBuilder pb)
{
// Update PATH environment variable to make sure all files in the tools
// directory and the directory of the executable or on the path.
String toolDir = PipelineJobService.get().getAppProperties().getToolsDirectory();
if (!StringUtils.isEmpty(toolDir))
{
String path = System.getenv("PATH");
if (_logPath)
{
getLogger().log(_logLevel, "Existing PATH: " + path);
getLogger().log(_logLevel, "toolDir: " + toolDir);
}
if (path == null)
{
path = toolDir;
}
else
{
path = toolDir + File.pathSeparatorChar + path;
}
// If the command has a path, then prepend its parent directory to the PATH
// environment variable as well.
String exePath = pb.command().get(0);
if (exePath != null && !exePath.isEmpty() && exePath.indexOf(File.separatorChar) != -1)
{
File fileExe = new File(exePath);
String exeDir = fileExe.getParent();
if (!exeDir.equals(toolDir) && fileExe.exists())
path = fileExe.getParent() + File.pathSeparatorChar + path;
}
if (_logPath)
{
getLogger().log(_logLevel, "using path: " + path);
}
pb.environment().put("PATH", path);
}
}
public void setLogPath(boolean logPath)
{
_logPath = logPath;
}
public void setOutputDir(File outputDir)
{
_outputDir = outputDir;
}
public File getOutputDir(File file)
{
return _outputDir == null ? file.getParentFile() : _outputDir;
}
public void setWorkingDir(File workingDir)
{
_workingDir = workingDir;
}
private File getWorkingDir()
{
return _workingDir;
}
public Logger getLogger()
{
if (_log == null)
{
return LogManager.getLogger("NoOpLogger");
}
return _log;
}
public void setLogLevel(Level logLevel)
{
_logLevel = logLevel;
}
public Level getLogLevel()
{
return _logLevel;
}
public void setWarnNonZeroExits(boolean warnNonZeroExits)
{
_warnNonZeroExits = warnNonZeroExits;
}
public void setThrowNonZeroExits(boolean throwNonZeroExits)
{
_throwNonZeroExits = throwNonZeroExits;
}
protected boolean isWarnNonZeroExits()
{
return _warnNonZeroExits;
}
protected boolean isThrowNonZeroExits()
{
return _throwNonZeroExits;
}
public static File resolveFileInPath(String exe, @Nullable String packageName, boolean throwIfNotFound)
{
File fn;
String path;
if (packageName != null)
{
path = PipelineJobService.get().getConfigProperties().getSoftwarePackagePath(packageName);
if (path != null)
{
fn = new File(path, exe);
if (fn.exists())
{
return fn;
}
}
}
path = PipelineJobService.get().getConfigProperties().getSoftwarePackagePath(SequencePipelineService.SEQUENCE_TOOLS_PARAM);
if (path != null)
{
fn = new File(path, exe);
if (fn.exists())
{
return fn;
}
}
path = PipelineJobService.get().getAppProperties().getToolsDirectory();
if (path != null)
{
fn = new File(path, exe);
if (fn.exists())
{
return fn;
}
}
String[] paths = System.getenv("PATH").split(File.pathSeparator);
for (String pathDir : paths)
{
fn = new File(pathDir, exe);
if (fn.exists())
{
return fn;
}
}
if (throwIfNotFound)
{
throw new IllegalArgumentException("Unable to find file: "+ exe);
}
return null;
}
}