blob: c455929bf519c694629777c3c4e111219842fc76 (
plain) (
blame)
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
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.system;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import com.yahoo.collections.Pair;
/**
* Executes a system command synchronously.
*
* @author bratseth
*/
public class ProcessExecuter {
private final boolean override_log_control;
public ProcessExecuter(boolean override_log_control) {
this.override_log_control = override_log_control;
}
public ProcessExecuter() {
this(false);
}
/**
* Executes the given command synchronously without timeout.
*
* @return Retcode and stdout/stderr merged
*/
public Pair<Integer, String> exec(String command) throws IOException {
StringTokenizer tok = new StringTokenizer(command);
List<String> tokens = new ArrayList<>();
while (tok.hasMoreElements())
tokens.add(tok.nextToken());
return exec(tokens.toArray(new String[0]));
}
/**
* Executes the given command synchronously without timeout.
*
* @param command tokens
* @return Retcode and stdout/stderr merged
*/
public Pair<Integer, String> exec(String[] command) throws IOException {
ProcessBuilder pb = new ProcessBuilder(command);
StringBuilder ret = new StringBuilder();
pb.environment().remove("VESPA_LOG_TARGET");
if (override_log_control) {
pb.environment().remove("VESPA_LOG_CONTROL_FILE");
pb.environment().put("VESPA_SERVICE_NAME", "exec-" + command[0]);
}
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
while (true) {
int b = is.read();
if (b == -1) break;
ret.append((char)b);
}
int rc = 0;
try {
rc = p.waitFor();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return new Pair<>(rc, ret.toString());
}
}
|