forked from pzread/judge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PyExt.py
284 lines (209 loc) · 6.54 KB
/
PyExt.py
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
'''C extension interface.
Attributes:
FFI (ffi): cffi interface.
FFILIB (object): cffi library.
'''
from collections import deque
import cffi
from tornado.ioloop import IOLoop
import Config
RESTRICT_LEVEL_LOW = 0
RESTRICT_LEVEL_HIGH = 1
DETECT_NONE = 0
DETECT_OOM = 1
DETECT_TIMEOUT = 2
DETECT_FORCETIMEOUT = 3
DETECT_EXITERR = 4
DETECT_INTERNALERR = 5
FFI = None
FFILIB = None
TASK_MAP = None
TASK_QUEUE = None
TASK_RUNNING_COUNT = 0
TASK_STOP_CB = None
class EvPoll:
'''Evpoll interface.
Attributes:
ffi (ffi): cffi interface.
ffilib (object): cffi library.
pollpairs (object): cffi polling pair buffer.
'''
def __init__(self):
'''Initialize.'''
self.ffi = FFI
self.ffilib = FFILIB
self.pollpairs = self.ffi.new('pollpair[]', 65536)
def close(self):
'''Handle close.'''
self.ffilib.destroy()
def register(self, evfd, events):
'''Register event.
Args:
evfd (int): File descriptor.
events (int): Event flag.
Returns:
None
'''
self.ffilib.ext_register(evfd, events)
def unregister(self, evfd):
'''Unregister event.
Args:
evfd (int): File descriptor.
Returns:
None
'''
self.ffilib.ext_unregister(evfd)
def modify(self, evfd, events):
'''Modify event flag.
Args:
evfd (int): File descriptor.
events (int): Event flag.
Returns:
None
'''
self.ffilib.ext_modify(evfd, events)
def poll(self, timeout, maxevts=65536):
'''Poll events.
Args:
timeout (int): Timeout.
maxevts (int): Maximum number of events which are polled.
Returns:
[(int, int)]: Event pairs (fd, events).
'''
assert maxevts <= 65536
num = self.ffilib.ext_poll(self.pollpairs, int(timeout * 1000))
pairs = list()
for idx in range(num):
pairs.append((
int(self.pollpairs[idx].fd),
int(self.pollpairs[idx].events)
))
return pairs
def init():
'''Initialize the module.'''
global FFI
global FFILIB
global TASK_MAP
global TASK_QUEUE
global TASK_STOP_CB
TASK_MAP = {}
TASK_QUEUE = deque()
FFI = cffi.FFI()
FFI.cdef('''
typedef struct {
int fd;
uint32_t events;
} pollpair;
''')
FFI.cdef('''
struct taskstat {
uint64_t utime;
uint64_t stime;
uint64_t peakmem;
int detect_error;
};
''')
FFI.cdef('''int init();''')
FFI.cdef('''void destroy();''')
FFI.cdef('''int ext_register(int fd, int events);''')
FFI.cdef('''int ext_unregister(int fd);''')
FFI.cdef('''int ext_modify(int fd, int events);''')
FFI.cdef('''int ext_poll(pollpair[], int timeout);''')
FFI.cdef('''uint64_t create_task(
char exe_path[], char *argv[], char *envp[],
int stdin_fd, int stdout_fd, int stderr_fd,
char work_path[], char root_path[],
unsigned int uid, unsigned int gid,
uint64_t timelimit, uint64_t memlimit,
int restrict_level);''')
FFI.cdef('''int start_task(uint64_t id,
void (*callback)(uint64_t id, struct taskstat stat));''')
FFILIB = FFI.dlopen('lib/libpyext.so')
FFILIB.init()
@FFI.callback('void(uint64_t, struct taskstat)')
def task_stop_cb(task_id, stat):
'''Task stop callback of cffi.
Args:
task_id (int): Task ID.
stat (object): Task result.
Returns:
None
'''
global TASK_RUNNING_COUNT
callback, _ = TASK_MAP[task_id]
del TASK_MAP[task_id]
IOLoop.instance().add_callback(
callback,
task_id,
{
'utime': int(stat.utime),
'stime': int(stat.stime),
'peakmem': int(stat.peakmem),
'detect_error': int(stat.detect_error),
}
)
TASK_RUNNING_COUNT -= 1
IOLoop.instance().add_callback(emit_task)
TASK_STOP_CB = task_stop_cb
def create_task(exe_path, argv, envp, stdin_fd, stdout_fd, stderr_fd, \
work_path, root_path, uid, gid, timelimit, memlimit, restrict_level):
'''Create a task.
Args:
exe_path (string): Executable file path.
argv ([string]): List of arguments.
envp ([string]): List of environment variables.
stdin_fd (int): Standard input file descriptor.
stdout_fd (int): Standard output file descriptor.
stderr_fd (int): Standard error file descriptor.
work_path (string): Working directory.
root_path (string): Root directory.
uid (int): UID of sandbox.
gid (int): GID of sandbox.
timelimit (int): Timelimit of sandbox.
memlimit (int): Memlimit of sandbox.
restrict_level (int): Restriction level of sandbox.
Returns:
int: Task ID, or None if failed to create the task.
'''
ffi_argv = []
for arg in argv:
ffi_argv.append(FFI.new('char[]', arg.encode('utf-8')))
ffi_argv.append(FFI.NULL)
ffi_envp = []
for env in envp:
ffi_envp.append(FFI.new('char[]', env.encode('utf-8')))
ffi_envp.append(FFI.NULL)
task_id = FFILIB.create_task(
FFI.new('char[]', exe_path.encode('utf-8')),
ffi_argv, ffi_envp,
stdin_fd, stdout_fd, stderr_fd,
FFI.new('char[]', work_path.encode('utf-8')),
FFI.new('char[]', root_path.encode('utf-8')),
uid, gid, timelimit, memlimit, restrict_level)
if task_id == 0:
return None
return task_id
def start_task(task_id, callback, started_callback=None):
'''Start a task.
The task may be pended if the running queue is full.
Args:
task_id (int): Task ID.
callback (function): Done callback.
started_callback (function, optinal): Started callback.
Returns:
None
'''
TASK_MAP[task_id] = (callback, started_callback)
TASK_QUEUE.append(task_id)
emit_task()
def emit_task():
'''Emit tasks.'''
global TASK_RUNNING_COUNT
while len(TASK_QUEUE) > 0 \
and TASK_RUNNING_COUNT < Config.TASK_MAXCONCURRENT:
task_id = TASK_QUEUE.popleft()
TASK_RUNNING_COUNT += 1
_, started_callback = TASK_MAP[task_id]
FFILIB.start_task(task_id, TASK_STOP_CB)
if started_callback is not None:
started_callback(task_id)