-
Notifications
You must be signed in to change notification settings - Fork 0
/
chal.py
360 lines (308 loc) · 11.4 KB
/
chal.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
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
import os
import json
from tornado.gen import coroutine
from tornado.websocket import websocket_connect
import msgpack
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
import config
from user import UserConst
from req import Service
from log import LogService
class ChalConst:
STATE_AC = 1
STATE_WA = 2
STATE_RE = 3
STATE_TLE = 4
STATE_MLE = 5
STATE_CE = 6
STATE_ERR = 7
STATE_JUDGE = 100
STATE_STR = {
STATE_AC:'AC',
STATE_WA:'WA',
STATE_RE:'RE',
STATE_TLE:'TLE',
STATE_MLE:'MLE',
STATE_CE:'CE',
STATE_ERR:'IE',
STATE_JUDGE:'JDG',
}
class ChalService:
STATE_AC = 1
STATE_WA = 2
STATE_RE = 3
STATE_TLE = 4
STATE_MLE = 5
STATE_CE = 6
STATE_ERR = 7
STATE_JUDGE = 100
STATE_NOTSTARTED = 101
STATE_STR = {
STATE_AC:'Accepted',
STATE_WA:'Wrong Answer',
STATE_RE:'Runtime Error',
STATE_TLE:'Time Limit Exceed',
STATE_MLE:'Memory Limit Exceed',
STATE_CE:'Compile Error',
STATE_ERR:'Internal Error',
STATE_JUDGE:'Challenging',
STATE_NOTSTARTED:'Not Started',
}
def __init__(self,db,rs):
self.db = db
self.rs = rs
self.ws = None
self._collect_judge()
ChalService.inst = self
def add_chal(self,pro_id,acct_id,code):
if Service.Contest.running()[1] == False:
return ('Eacces',None)
os.mkdir('code/tmp')
os.rmdir('code/tmp')
cur = yield self.db.cursor()
yield cur.execute(('INSERT INTO "challenge" '
'("pro_id","acct_id") '
'VALUES (%s,%s) RETURNING "chal_id";'),
(pro_id,acct_id))
if cur.rowcount != 1:
return ('Eunk',None)
chal_id = cur.fetchone()[0]
os.mkdir('code/%d'%chal_id)
code_f = open('code/%d/main.cpp'%chal_id,'wb')
code_f.write(code.encode('utf-8'))
code_f.close()
return (None,chal_id)
def reset_chal(self,chal_id):
cur = yield self.db.cursor()
yield cur.execute('DELETE FROM "test" WHERE "chal_id" = %s;',
(chal_id,))
self.rs.publish('materialized_view_req', self.rs.get('materialized_view_counter'))
self.rs.delete('rate@kernel_True')
self.rs.delete('rate@kernel_False')
return (None,None)
def get_chal(self,chal_id,acct):
cur = yield self.db.cursor()
yield cur.execute(('SELECT '
'"challenge"."pro_id",'
'"challenge"."acct_id",'
'"challenge"."timestamp",'
'"account"."name" AS "acct_name" '
'FROM "challenge" '
'INNER JOIN "account" '
'ON "challenge"."acct_id" = "account"."acct_id" '
'WHERE "chal_id" = %s;'),
(chal_id,))
if cur.rowcount != 1:
return ('Enoext',None)
#LogService.inst.add_log('get chal')
pro_id,acct_id,timestamp,acct_name = cur.fetchone()
yield cur.execute(('SELECT "test_idx","state","runtime","memory" '
'FROM "test" '
'WHERE "chal_id" = %s ORDER BY "test_idx" ASC;'),
(chal_id,))
testl = list()
for test_idx,state,runtime,memory in cur:
testl.append({
'test_idx':test_idx,
'state':state,
'runtime':int(runtime),
'memory':int(memory),
})
owner = self.rs.get(str(pro_id)+'_owner')
unlock = [1]
if (acct['acct_id'] == acct_id or
(acct['acct_type'] == UserConst.ACCTTYPE_KERNEL and
(owner == None or acct['acct_id'] in config.lock_user_list) and (acct['acct_id'] in config.can_see_code_user))):
if (acct['acct_type'] == UserConst.ACCTTYPE_KERNEL) and (acct['acct_id'] != acct_id):
yield from LogService.inst.add_log((acct['name'] + " view the challenge " + str(chal_id)))
try:
code_f = open('code/%d/main.cpp'%chal_id,'rb')
code = code_f.read().decode('utf-8')
code_f.close()
except FileNotFoundError:
code = 'ERROR: The code is lost on server.'
else:
code = None
return (None,{
'chal_id':chal_id,
'pro_id':pro_id,
'acct_id':acct_id,
'acct_name':acct_name,
'timestamp':timestamp,
'testl':testl,
'code':code
})
def emit_chal(self,chal_id,pro_id,testm_conf,code_path,res_path):
cur = yield self.db.cursor()
yield cur.execute(('SELECT "acct_id","timestamp" FROM "challenge" '
'WHERE "chal_id" = %s;'),
(chal_id,))
if cur.rowcount != 1:
return ('Enoext',None)
acct_id,timestamp = cur.fetchone()
testl = list()
for test_idx,test_conf in testm_conf.items():
testl.append({
'test_idx':test_idx,
'timelimit':test_conf['timelimit'],
'memlimit':test_conf['memlimit'],
'metadata':test_conf['metadata']
})
yield cur.execute(('INSERT INTO "test" '
'("chal_id","acct_id","pro_id","test_idx","state","timestamp") '
'VALUES (%s,%s,%s,%s,%s,%s);'),
(chal_id,acct_id,pro_id,test_idx,
ChalService.STATE_JUDGE,timestamp))
self.rs.publish('materialized_view_req', self.rs.get('materialized_view_counter'))
# tmp_ws = yield websocket_connect(config.PATH_JUDGE)
if self.ws == None:
self.ws = yield websocket_connect(config.PATH_JUDGE)
try:
code_f = open('code/%d/main.cpp'%chal_id,'rb')
code = code_f.read().decode('utf-8')
code_f.close()
except FileNotFoundError:
for test in testl:
err, ret = yield from self.update_test(
chal_id,
test['test_idx'],
ChalService.STATE_ERR,
0,
0,
''
)
return (None, None)
chalmeta = test_conf['chalmeta']
self.ws.write_message(json.dumps({
'chal_id':chal_id,
'test':testl,
'code_path':code_path,
'res_path':res_path,
'code':code,
'metadata':chalmeta,
'comp_type':test_conf['comp_type'],
'check_type':test_conf['check_type'],
}))
'''tmp_ws.write_message(json.dumps({
'chal_id':chal_id,
'testl':testl,
'code_path':code_path,
'res_path':res_path
}))'''
return (None,None)
def list_chal(self,off,num,min_accttype = UserConst.ACCTTYPE_USER,
flt = {'pro_id':None,'acct_id':None,'state':0}):
fltquery,fltarg = self._get_fltquery(flt)
cur = yield self.db.cursor()
yield cur.execute(('SELECT '
'"challenge"."chal_id",'
'"challenge"."pro_id",'
'"challenge"."acct_id",'
'"challenge"."timestamp",'
'"account"."name" AS "acct_name",'
'"challenge_state"."state",'
'"challenge_state"."runtime",'
'"challenge_state"."memory" '
'FROM "challenge" '
'INNER JOIN "account" '
'ON "challenge"."acct_id" = "account"."acct_id" '
'LEFT JOIN "challenge_state" '
'ON "challenge"."chal_id" = "challenge_state"."chal_id" '
'WHERE "account"."acct_type" >= %s' + fltquery +
'ORDER BY "challenge"."timestamp" DESC OFFSET %s LIMIT %s;'),
[min_accttype] + fltarg + [off,num])
challist = list()
for (chal_id,pro_id,acct_id,timestamp,acct_name,
state,runtime,memory) in cur:
if state == None:
state = ChalService.STATE_NOTSTARTED
if runtime == None:
runtime = 0
else:
runtime = int(runtime)
if memory == None:
memory = 0
else:
memory = int(memory)
challist.append({
'chal_id':chal_id,
'pro_id':pro_id,
'acct_id':acct_id,
'timestamp':timestamp,
'acct_name':acct_name,
'state':state,
'runtime':runtime,
'memory':memory
})
return (None,challist)
def get_stat(self,min_accttype = UserConst.ACCTTYPE_USER,flt = None):
fltquery,fltarg = self._get_fltquery(flt)
cur = yield self.db.cursor()
yield cur.execute(('SELECT COUNT(1) FROM "challenge" '
'INNER JOIN "account" '
'ON "challenge"."acct_id" = "account"."acct_id" '
'LEFT JOIN "challenge_state" '
'ON "challenge"."chal_id"="challenge_state"."chal_id" '
'WHERE "account"."acct_type" >= %s' + fltquery + ';'),
[min_accttype] + fltarg)
if cur.rowcount != 1:
return ('Eunk',None)
total_chal = cur.fetchone()[0]
return (None,{
'total_chal':total_chal
})
def update_test(self,chal_id,test_idx,state,runtime,memory,response):
cur = yield self.db.cursor()
yield cur.execute(('UPDATE "test" '
'SET "state" = %s,"runtime" = %s,"memory" = %s,"response" = %s '
'WHERE "chal_id" = %s AND "test_idx" = %s;'),
(state,runtime,memory,response,chal_id,test_idx))
if cur.rowcount != 1:
return ('Enoext',None)
self.rs.publish('materialized_view_req', self.rs.get('materialized_view_counter'))
self.rs.delete('prolist')
self.rs.delete('rate@kernel_True')
self.rs.delete('rate@kernel_False')
return (None,None)
def _get_fltquery(self,flt):
query = ' '
arg = []
if flt['pro_id'] != None:
query += 'AND ( "challenge"."pro_id" = 0 '
for pro_id in flt['pro_id']:
query += ' OR "challenge"."pro_id" = %s '
arg.append(pro_id)
query += ')'
if flt['acct_id'] != None:
query += 'AND ( "challenge"."acct_id" = 0 '
for acct_id in flt['acct_id']:
query += ' OR "challenge"."acct_id" = %s '
arg.append(acct_id)
query += ')'
if flt['state'] != 0:
if flt['state'] == ChalService.STATE_NOTSTARTED:
query += ' AND "challenge_state"."state" IS NULL '
else:
query += ' AND "challenge_state"."state"=%s'
arg.append(flt['state'])
return (query,arg)
@coroutine
def _collect_judge(self):
if self.ws == None:
self.ws = yield websocket_connect(config.PATH_JUDGE)
while True:
ret = yield self.ws.read_message()
if ret == None:
break
res = json.loads(ret,'utf-8')
if res['result'] is not None:
for result in res['result']:
err,ret = yield from self.update_test(
res['chal_id'],
result['test_idx'],
result['state'],
result['runtime'],
result['peakmem'],
ret)