-
Notifications
You must be signed in to change notification settings - Fork 188
/
SingularityExecutorShellCommandRunner.java
204 lines (161 loc) · 8.59 KB
/
SingularityExecutorShellCommandRunner.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
package com.hubspot.singularity.executor.shells;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.hubspot.singularity.SingularityTaskShellCommandRequest;
import com.hubspot.singularity.SingularityTaskShellCommandUpdate.UpdateType;
import com.hubspot.singularity.executor.config.SingularityExecutorConfiguration;
import com.hubspot.singularity.executor.task.SingularityExecutorTask;
import com.hubspot.singularity.executor.task.SingularityExecutorTaskProcessCallable;
import com.hubspot.singularity.executor.utils.MesosUtils;
public class SingularityExecutorShellCommandRunner {
private final SingularityTaskShellCommandRequest shellRequest;
private final SingularityExecutorTask task;
private final SingularityExecutorTaskProcessCallable taskProcess;
private final ListeningExecutorService shellCommandExecutorService;
private final SingularityExecutorShellCommandUpdater shellCommandUpdater;
private final SingularityExecutorConfiguration executorConfiguration;
@SuppressWarnings("serial")
private static class InvalidShellCommandException extends RuntimeException {
public InvalidShellCommandException(String message) {
super(message);
}
}
public static String convertCommandNameToLogfileName(String str) {
return CharMatcher.WHITESPACE.or(CharMatcher.is('/')).replaceFrom(str, '-').toLowerCase();
}
public SingularityExecutorShellCommandRunner(SingularityTaskShellCommandRequest shellRequest, SingularityExecutorConfiguration executorConfiguration, SingularityExecutorTask task,
SingularityExecutorTaskProcessCallable taskProcess, ListeningExecutorService shellCommandExecutorService, SingularityExecutorShellCommandUpdater shellCommandUpdater) {
this.shellRequest = shellRequest;
this.executorConfiguration = executorConfiguration;
this.task = task;
this.taskProcess = taskProcess;
this.shellCommandUpdater = shellCommandUpdater;
this.shellCommandExecutorService = shellCommandExecutorService;
}
public SingularityTaskShellCommandRequest getShellRequest() {
return shellRequest;
}
public SingularityExecutorTask getTask() {
return task;
}
public ProcessBuilder buildProcessBuilder(List<String> command, File outputFile, Map<String, String> additionalEnv) {
ProcessBuilder builder = new ProcessBuilder(command);
builder.environment().putAll(additionalEnv);
builder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile));
builder.redirectError(ProcessBuilder.Redirect.appendTo(outputFile));
return builder;
}
public void start() {
List<String> command = null;
try {
command = buildCommand();
} catch (InvalidShellCommandException isce) {
shellCommandUpdater.sendUpdate(UpdateType.INVALID, Optional.of(isce.getMessage()), Optional.<String>absent());
return;
}
final String outputFilename = executorConfiguration.getShellCommandOutFile()
.replace("{NAME}", shellRequest.getShellCommand().getLogfileName().or(convertCommandNameToLogfileName(shellRequest.getShellCommand().getName())))
.replace("{TIMESTAMP}", Long.toString(shellRequest.getTimestamp()));
shellCommandUpdater.sendUpdate(UpdateType.ACKED, Optional.of(Joiner.on(" ").join(command)), Optional.of(outputFilename));
final File outputFile = MesosUtils.getTaskDirectoryPath(getTask().getTaskId()).resolve(outputFilename).toFile();
Map<String, String> additionalEnv = new HashMap<>();
additionalEnv.put("TASK_SANDBOX_DIR", MesosUtils.getTaskDirectoryPath(getTask().getTaskId()).toString());
SingularityExecutorShellCommandRunnerCallable callable = new SingularityExecutorShellCommandRunnerCallable(task.getLog(), shellCommandUpdater, buildProcessBuilder(command, outputFile, additionalEnv), outputFile);
ListenableFuture<Integer> shellFuture = shellCommandExecutorService.submit(callable);
Futures.addCallback(shellFuture, new FutureCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
task.getLog().info("ShellRequest {} finished with {}", shellRequest, result);
shellCommandUpdater.sendUpdate(UpdateType.FINISHED, Optional.of(String.format("Finished with code %s", result)), Optional.<String>absent());
}
@Override
public void onFailure(Throwable t) {
task.getLog().warn("ShellRequest {} failed", shellRequest, t);
shellCommandUpdater.sendUpdate(UpdateType.FAILED, Optional.of(String.format("Failed - %s (%s)", t.getClass().getSimpleName(), t.getMessage())), Optional.<String>absent());
}
});
}
private List<String> buildCommand() {
Optional<SingularityExecutorShellCommandDescriptor> matchingShellCommandDescriptor = Iterables.tryFind(executorConfiguration.getShellCommands(), new Predicate<SingularityExecutorShellCommandDescriptor>() {
@Override
public boolean apply(SingularityExecutorShellCommandDescriptor input) {
return input.getName().equals(shellRequest.getShellCommand().getName());
}
});
if (!matchingShellCommandDescriptor.isPresent()) {
throw new InvalidShellCommandException(String.format(
"\"%s\" command not found. If this command was added or modified after the task launched, then the task must be restarted to find it. Currently available commands are: %s",
shellRequest.getShellCommand().getName(),
executorConfiguration.getShellCommands().stream().map(SingularityExecutorShellCommandDescriptor::getName).collect(Collectors.toList())));
}
final SingularityExecutorShellCommandDescriptor shellCommandDescriptor = matchingShellCommandDescriptor.get();
List<String> command = new ArrayList<>();
boolean isDocker = task.getTaskInfo().hasContainer() && task.getTaskInfo().getContainer().hasDocker();
if (isDocker) {
if (!shellCommandDescriptor.isSkipCommandPrefix() && !shellCommandDescriptor.isSkipCommandPrefixDockerOnly()) {
command.addAll(executorConfiguration.getShellCommandPrefix());
}
command.addAll(Arrays.asList("docker", "exec", String.format("%s%s", executorConfiguration.getDockerPrefix(), task.getTaskId())));
} else if (!shellCommandDescriptor.isSkipCommandPrefix()) {
command.addAll(executorConfiguration.getShellCommandPrefix());
}
command.addAll(shellCommandDescriptor.getCommand());
for (int i = 0; i < command.size(); i++) {
if (command.get(i).equals(executorConfiguration.getShellCommandPidPlaceholder())) {
int pid;
Path pidFilePath = MesosUtils.getTaskDirectoryPath(getTask().getTaskId()).resolve(executorConfiguration.getShellCommandPidFile());
if (Files.exists(pidFilePath)) {
Scanner scanner = null;
try {
scanner = new Scanner(pidFilePath);
scanner.useDelimiter("\\Z");
pid = Integer.parseInt(scanner.next());
} catch (Exception e) {
throw new InvalidShellCommandException(String.format("No PID found due to exception reading pid file: %s", e.getMessage()));
} finally {
if (scanner != null) {
try {
scanner.close();
} catch (Throwable t) {}
}
}
} else if (isDocker) {
pid = 1;
} else {
if (!taskProcess.getCurrentPid().isPresent()) {
throw new InvalidShellCommandException("No PID found");
}
pid = taskProcess.getCurrentPid().get();
}
command.set(i, Integer.toString(pid));
} else if (command.get(i).equals(executorConfiguration.getShellCommandUserPlaceholder())) {
command.set(i, taskProcess.getTask().getExecutorData().getUser().or(executorConfiguration.getDefaultRunAsUser()));
}
}
if (shellRequest.getShellCommand().getOptions().isPresent()) {
for (SingularityExecutorShellCommandOptionDescriptor option : shellCommandDescriptor.getOptions()) {
if (shellRequest.getShellCommand().getOptions().get().contains(option.getName())) {
command.add(option.getFlag());
}
}
}
return command;
}
}