-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathworker.cpp
367 lines (302 loc) · 9.87 KB
/
worker.cpp
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
/**
* @file worker.cpp
* Compile: clang++ -o worker worker.cpp
*
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define __PACKED __attribute__((packed))
/* Private structures used for (un)packing data sent
* through pipes
*/
struct arr_entry {
unsigned int size;
char data[0];
} __PACKED;
struct req_packet {
unsigned int cwdSize;
unsigned int inputSize;
unsigned int cmdLen;
char data[0];
} __PACKED;
struct resp_packet {
unsigned int stdout_size;
unsigned int stderr_size;
int return_code;
unsigned short internal_error;
char data[0];
} __PACKED;
/* Helper exception class to handle both error message and
* errno message in one go
*/
class ExecutionWorkerException : public std::exception {
std::string msg;
public:
ExecutionWorkerException(const char* text, bool storeErrno = false) {
msg = "ExecutionWorker exception: ";
msg += text;
if(storeErrno) {
msg += "(errno: ";
msg += strerror(errno);
msg += ")";
}
}
virtual const char* what(void) const throw() {
return msg.data();
}
};
/* Main executor class responsible for handling pipes
* communication and process creation
*/
class ExecutionWorker {
int readFD, writeFD, retCode;
std::vector<char> cwd, outputOut, outputErr, input;
std::vector<std::vector<char>> cmd;
void full_read(int fd, void* buffer, size_t len);
void full_write(int fd, void* buffer, size_t len);
void recv(void);
void send(bool sentError = false);
void execute(void);
public:
ExecutionWorker(int _readFD, int _writeFD)
: readFD(_readFD), writeFD(_writeFD), retCode(-1) {};
void processSingleRequest(void);
void sendError(const char* errorStr);
};
void ExecutionWorker::full_read(int fd, void* buffer, size_t len) {
size_t offset = 0;
ssize_t ret;
while(offset < len) {
ret = read(fd, (char*)buffer + offset, len - offset);
if(ret <= 0)
throw ExecutionWorkerException("encountered error during read operation", true);
offset += ret;
}
}
void ExecutionWorker::full_write(int fd, void* buffer, size_t len) {
size_t offset = 0;
ssize_t ret;
while(offset < len) {
ret = write(fd, (char*)buffer + offset, len - offset);
if(ret <= 0)
throw ExecutionWorkerException("encountered error during write operation", true);
offset += ret;
}
}
void ExecutionWorker::recv(void) {
struct req_packet packet;
full_read(readFD, &packet, sizeof(packet));
cmd.clear();
cwd.clear();
input.clear();
// Read current working dir (CWD)
cwd.resize(packet.cwdSize + 1);
full_read(readFD, cwd.data(), packet.cwdSize);
cwd[packet.cwdSize] = '\0';
// Read input for process
input.resize(packet.inputSize);
full_read(readFD, input.data(), packet.inputSize);
// Read array of program arguments
for(unsigned int i = 0; i < packet.cmdLen; i++) {
std::vector<char> arg;
struct arr_entry entry;
full_read(readFD, &entry, sizeof(entry));
arg.resize(entry.size + 1);
full_read(readFD, arg.data(), entry.size);
arg[entry.size] = '\0';
cmd.push_back(arg);
}
}
void ExecutionWorker::send(bool sentError) {
struct resp_packet packet;
packet.stdout_size = outputOut.size();
packet.stderr_size = outputErr.size();
packet.internal_error = sentError;
packet.return_code = retCode;
full_write(writeFD, &packet, sizeof(packet));
full_write(writeFD, outputOut.data(), outputOut.size());
full_write(writeFD, outputErr.data(), outputErr.size());
}
void ExecutionWorker::execute(void) {
int fdOut[2], fdErr[2], fdRead[2];
char slice[256];
int status;
int retries = 0;
pid_t writerPid = -1;
outputOut.clear();
outputErr.clear();
int ret = pipe(fdOut);
if(ret < 0)
throw ExecutionWorkerException("cannot create output pipe to subprocess", true);
ret = pipe(fdErr);
if(ret < 0)
throw ExecutionWorkerException("cannot create error pipe to subprocess", true);
ret = pipe(fdRead);
if(ret < 0)
throw ExecutionWorkerException("cannot create input pipe to subprocess", true);
pid_t pid = fork();
if(pid > 0) {
// Parent
close(fdOut[1]);
close(fdErr[1]);
close(fdRead[0]);
// If there's any input to write, spawn new writer process
if(input.size() > 0) {
writerPid = fork();
if(writerPid == 0) {
// Children
ssize_t ret;
size_t writeOffset = 0;
while((ret = write(fdRead[1],
input.data() + writeOffset,
input.size() - writeOffset)) > 0)
writeOffset += ret;
close(fdRead[1]);
exit(0);
} else if(writerPid < 0)
throw ExecutionWorkerException("cannot spawn subprocess for generating input");
}
close(fdRead[1]);
bool isOutDone = false, isErrDone = false;
while(retries < 100) {
/* Things got a bit complicated here - now we've got 2 file descriptors (stdout + stderr)
* and both of them should be read frequently to avoid stalling child process. Let's use
* poll syscall to achieve that
*/
struct pollfd pfds[2];
memset(pfds, 0, sizeof(pfds));
pfds[0].fd = fdOut[0];
pfds[1].fd = fdErr[0];
pfds[0].events = pfds[1].events = POLLIN;
int poll_ret = poll(pfds, 2, -1);
if(poll_ret < 0) {
kill(pid, SIGKILL);
throw ExecutionWorkerException("cannot poll pipe events", true);
}
if(pfds[0].revents) {
ssize_t ret = read(fdOut[0], slice, sizeof(slice));
if(ret < 0) {
kill(pid, SIGKILL);
throw ExecutionWorkerException("cannot read from children stdout pipe", true);
} else if (ret == 0 && waitpid(pid, &status, WNOHANG) == pid) {
isOutDone = true;
if(isErrDone) break;
} else if(ret == 0) {
retries++;
} else {
retries = 0;
size_t oldSize = outputOut.size();
outputOut.resize(oldSize + ret);
memcpy(outputOut.data() + oldSize, slice, ret);
}
}
if(pfds[1].revents) {
ssize_t ret = read(fdErr[0], slice, sizeof(slice));
if(ret < 0) {
kill(pid, SIGKILL);
throw ExecutionWorkerException("cannot read from children stderr pipe", true);
} else if (ret == 0 && waitpid(pid, &status, WNOHANG) == pid) {
isErrDone = true;
if(isOutDone) break;
} else if(ret == 0) {
retries++;
} else {
retries = 0;
size_t oldSize = outputErr.size();
outputErr.resize(oldSize + ret);
memcpy(outputErr.data() + oldSize, slice, ret);
}
}
}
// Make sure our child is cold dead
kill(pid, SIGKILL);
waitpid(pid, &status, WNOHANG);
// Kill writer if it exists
if(writerPid > 0) {
kill(writerPid, SIGKILL);
waitpid(writerPid, nullptr, WNOHANG);
}
// Save return code
if(WIFEXITED(status))
retCode = WEXITSTATUS(status);
else
retCode = -1;
} else if(pid == 0) {
// Child
dup2(fdRead[0], STDIN_FILENO);
dup2(fdOut[1], STDOUT_FILENO);
dup2(fdErr[1], STDERR_FILENO);
close(fdOut[1]);
close(fdOut[0]);
close(fdErr[1]);
close(fdErr[0]);
close(fdRead[0]);
close(fdRead[1]);
if(cwd.size() > 0 && cwd[0] != '\0') {
ret = chdir(cwd.data());
if(ret)
throw ExecutionWorkerException("cannot change children directory", true);
}
std::vector<char*> argv;
for(size_t i = 0; i < cmd.size(); i++)
argv.push_back(cmd[i].data());
argv.push_back(nullptr);
ret = execv(cmd[0].data(), argv.data());
throw ExecutionWorkerException("failed to spawn target subprocess", true);
} else {
// This is an error
throw ExecutionWorkerException("fork failed", true);
}
close(fdOut[0]);
close(fdErr[0]);
}
void ExecutionWorker::processSingleRequest(void) {
recv();
execute();
send();
}
void ExecutionWorker::sendError(const char* errorStr) {
size_t errorLen = strlen(errorStr);
outputErr.clear();
outputErr.resize(errorLen + 1);
memcpy(outputErr.data(), errorStr, errorLen);
outputErr[errorLen] = '\0';
// true - indicate to host that this is an error message
send(true);
}
/*
* Application entry-point
*/
int main(int argc, char** argv) {
// TODO: Switch to getopt
if(argc < 3) {
fprintf(stderr, "Usage: %s <read_fd> <write_fd>\n", argv[0]);
return 1;
}
int read_fd = atoi(argv[1]);
int write_fd = atoi(argv[2]);
ExecutionWorker worker(read_fd, write_fd);
while(1) {
try {
worker.processSingleRequest();
} catch(ExecutionWorkerException& ex) {
// Send error message to host
worker.sendError(ex.what());
// TODO: Maybe we can resume?
exit(1);
}
}
}