Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
1005 lines (760 loc) · 32.8 KB
/
Copy pathserver.py
File metadata and controls
1005 lines (760 loc) · 32.8 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from logging import WARNING
from threading import Thread
import os
import shutil
import signal
import tempfile
import time
import json
import logging
import socket
from typing import List
import pathlib
import base64
import getopt
import sys
import coloredlogs
from websocket_server import WebsocketServer, WebSocketHandler
import pexpect
import compiler
import jail
import versions
import weights
from scheduler import Scheduler
from compiler.helper import run_command, prefix, jailed, sandboxed, escape_ansi
import fnmatch
from socketserver import TCPServer
coloredlogs.install()
# Returned images, videos and files are held in memory as base64 (several copies while
# sending), so their size is limited: one file, and all files of one run together.
MAX_FILE_SIZE = 10 * 1024 * 1024
MAX_TOTAL_SIZE = 25 * 1024 * 1024
# An incoming message is read into memory as a whole and unmasked byte by byte in Python:
# 20 MB cost 125 MB of RAM and slowed down all other clients for more than a second.
MAX_MESSAGE_SIZE = 4 * 1024 * 1024
# Output of one run, a program in an endless print loop is stopped at this size.
MAX_OUTPUT_SIZE = 2 * 1024 * 1024
def memory_limit() -> int:
'''Memory of this container or machine in MB.'''
memory = os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
for name in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):
try:
with open(name, encoding="utf8") as file:
memory = min(memory, int(file.read()))
except (OSError, ValueError): # not this cgroup version, or "max"
pass
return memory // 2**20
# Runs (compile and execution) wait in a fair queue for a slot, see scheduler.py.
# A slot is free while the memory suffices: every run has a weight in MB, estimated from
# its command (weights.py) and then measured, and all weights together have to fit into
# MEMORY_SHARE of MEMORY_MB, less what the rest of the system uses. MAX_RUNS limits the
# number of runs as well, per CPU and for one client; a client may have
# MAX_PROJECTS_PER_CLIENT runs, running or waiting. While runs wait, a run without input
# or output for IDLE_LIMIT seconds is stopped.
MEMORY_MB = int(os.environ.get("CODERUNNER_MEMORY_MB") or memory_limit())
MEMORY_SHARE = 0.85
# Where the folders of the runs are created, by default in /tmp. The image sets a folder
# of its own: jail.py can then leave /tmp open to all runs, see there.
RUNS = os.environ.get("CODERUNNER_RUNS") or None
MAX_RUNS = int(os.environ.get("CODERUNNER_MAX_RUNS") or max(2, 2 * (os.cpu_count() or 1)))
MAX_RUNS_PER_CLIENT = 2
MAX_PROJECTS_PER_CLIENT = 20
IDLE_LIMIT = float(os.environ.get("CODERUNNER_IDLE_LIMIT") or 30)
# For this long a starting program counts with its estimated weight, then as measured.
SETTLE = 3
# No estimate is larger than this share of the memory for runs: a run that claims all
# of it could only start while nothing else runs.
LARGEST_ESTIMATE = 0.75
def kill_processes_in(directory: str) -> None:
'''
Kill every process whose working directory is inside of `directory`. This also ends
programs that detached from their terminal (setsid, nohup), which a signal to the
started process does not reach.
'''
# shortcut: a process that changes its working directory escapes, upgrade to a PID
# namespace or cgroup per run once the hosting allows it
directory = os.path.realpath(directory)
for _ in range(3): # a process may start another one while it is killed
found = False
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
cwd = os.readlink("/proc/" + pid + "/cwd")
if cwd == directory or cwd.startswith(directory + os.sep):
os.kill(int(pid), signal.SIGKILL)
found = True
except OSError:
pass
if not found:
break
class NewWebSocketHandler (WebSocketHandler):
def read_bytes(self, num):
# called by the library with the length of a message before it reads it
if num > MAX_MESSAGE_SIZE:
logging.warning("refused a message of %d bytes, closing the connection", num)
self.keep_alive = False
return b""
return self.rfile.read(num)
def read_http_headers(self):
headers = {}
try:
self.connection.settimeout(10) # prevent indefinite blocking on health-check reads
http_get = self.rfile.readline().decode().strip()
if not http_get.upper().startswith('GET'):
logging.debug("Non-GET HTTP request, treating as health check: %r", http_get)
# headers lesen
while True:
header = self.rfile.readline().decode().strip()
if not header:
break
try:
head, value = header.split(':', 1)
headers[head.lower().strip()] = value.strip()
except ValueError:
logging.debug("Malformed header line ignored: %r", header)
except Exception as e:
logging.debug("Error reading HTTP headers: %s", e)
finally:
self.connection.settimeout(None) # restore blocking mode for WebSocket reads
return headers
def handshake(self):
try:
headers = self.read_http_headers()
except Exception as e:
logging.debug("handshake: failed to read headers: %s", e)
headers = {}
if 'upgrade' in headers:
try:
assert headers['upgrade'].lower() == 'websocket'
except AssertionError:
self.keep_alive = False
return
try:
key = headers['sec-websocket-key']
except KeyError:
logging.warning("Client tried to connect but was missing a key")
self.keep_alive = False
return
response = self.make_handshake_response(key)
try:
with self._send_lock:
self.handshake_done = self.request.send(response.encode())
except BrokenPipeError:
logging.debug("Client closed during handshake response.")
self.keep_alive = False
return
self.valid_client = True
self.server._new_client_(self)
else:
# Health-Check: freundlich 200 OK und schließen
body = b"OK\n"
response = (
'HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain; charset=utf-8\r\n'
f'Content-Length: {len(body)}\r\n'
'Connection: close\r\n\r\n'
).encode() + body
try:
with self._send_lock:
self.request.sendall(response)
# Send TCP FIN so the client knows the response is complete
try:
self.request.shutdown(socket.SHUT_WR)
except Exception:
pass
except BrokenPipeError:
logging.debug("Client closed before health-check response.")
except Exception as e:
logging.debug("Failed to send health-check response: %s", e)
finally:
self.keep_alive = False
class Server (WebsocketServer):
def __init__(self, host='127.0.0.1', port=0, loglevel=logging.WARNING, key=None, cert=None):
#logging.setLevel(loglevel)
TCPServer.__init__(self, (host, port), NewWebSocketHandler)
self.host = host
self.port = self.socket.getsockname()[1]
self.key = key
self.cert = cert
self.clients = []
self.id_counter = 0
self.thread = None
self._deny_clients = False
def handle_error(self, request, client_address):
# Unterdrücke laute Tracebacks von erwartbaren Client-Abbrüchen
logging.debug("Suppressed client error from %s", client_address)
class Process:
'''
A process is a running execution within a thread, that sends back received inputs from stdin.
'''
def __init__(self, current_directory: str, cmd: str, filter_files: str | None, callback, stop):
self.stdin: List[str] = []
self.current_directory = current_directory
self.callback = callback
self.stop = stop
self.error = None
self.filter = filter_files
self.budget = MAX_TOTAL_SIZE
self.skipped: List[str] = []
self.output = 0
self.destroyed = False
try:
self.process = pexpect.spawn(cmd, cwd=current_directory, echo=False, encoding="utf-8")
self.process.timeout = None
except Exception as error:
self.error = str(error)
def __del__(self):
self.destroy()
def destroy(self):
'''
Try to terminate the process immediately.
'''
self.destroyed = True
try:
self.process.terminate(force=True)
except Exception as _:
pass
try:
self.process.close(force=True)
except Exception as _:
pass
try:
del self.callback
except Exception as _:
pass
try:
del self.process
except Exception as _:
pass
def is_alive(self) -> bool:
'''
Test if the process is still running.
'''
try:
return self.process.isalive()
except Exception as _:
return False
def input(self, stdin: str) -> None:
'''
Receive strings that should be send to stdin of a running process.
'''
self.stdin.append(stdin)
def spawn(self) -> None:
'''
Spawn a new process and listen to stdout as long as the process is alive.
'''
errors = []
while True:
# First ask whether the program lives, then read. The other way round, output
# is lost that a program writes right before it ends, between the two steps.
alive = self.is_alive()
if not self.read_line() and not alive:
break
if self.output > MAX_OUTPUT_SIZE:
errors.append("Stopped, the program printed more than %d MB." % (MAX_OUTPUT_SIZE // 2**20))
break
try:
if len(self.stdin) > 0:
input_string = self.stdin.pop(0)
if input_string.endswith("\n"):
input_string = input_string[0:-1]
self.process.sendline(input_string)
# self.process.expect(input_string)
except Exception as _:
pass
if self.destroyed:
# by a stop, an eviction or a disconnect, which have already told the client
return
self.process.close()
images, videos, files = self.list_images(), self.list_videos(), self.filter_files()
if self.skipped:
errors.append("Not returned, too large (max. %d MB per file, %d MB per run): %s" % (
MAX_FILE_SIZE // 2**20, MAX_TOTAL_SIZE // 2**20, ", ".join(self.skipped)))
self.stop("\n".join(errors) or None, images, videos, files)
def encode(self, filename: str) -> str | None:
'''
Content of a file as base64, or None if the file exceeds the size limits.
'''
size = os.path.getsize(filename)
if size > MAX_FILE_SIZE or size > self.budget:
self.skipped.append(pathlib.Path(filename).name)
return None
self.budget -= size
with open(filename, "rb") as file:
return base64.b64encode(file.read()).decode("utf8")
def filter_files(self):
'''
Filter all files within the regular expression in self.filter and return them as base46.
'''
if self.filter is None:
return []
files = fnmatch.filter(os.listdir(self.current_directory), self.filter)
files = list(map(lambda filename: self.current_directory + "/" + filename, files))
files = sorted(filter(os.path.isfile, files), key=os.path.getmtime, reverse=True)
blobs = []
for filename in files:
data = self.encode(filename)
if data is not None:
blobs += [{"file": pathlib.Path(filename).name, "data": ";base64," + data}]
return blobs
def list_images(self):
'''
Search the current directory for all generated images and return them as base46.
'''
files = os.listdir(self.current_directory)
files = list(map(lambda filename: self.current_directory + "/" + filename, files))
files = sorted(filter(os.path.isfile, files), key=os.path.getmtime, reverse=True)
images = []
for filename in files:
extension = pathlib.Path(filename).suffix.lower()[1:]
if extension in ["bmp", "gif", "jpg", "jpeg", "png", "svg", "tif"]:
data = self.encode(filename)
if data is not None:
images += [{"file": pathlib.Path(filename).name,
"data": "data:image/" + extension + ";base64," + data}]
return images
def list_videos(self):
'''
Search the current directory for all video files and return them as base64.
'''
files = os.listdir(self.current_directory)
files = list(map(lambda filename: self.current_directory + "/" + filename, files))
files = sorted(filter(os.path.isfile, files), key=os.path.getmtime, reverse=True)
videos = []
for filename in files:
extension = pathlib.Path(filename).suffix.lower()[1:]
if extension in ["mp4", "avi", "mov", "mkv", "flv", "wmv", "webm"]:
data = self.encode(filename)
if data is not None:
videos.append({
"file": pathlib.Path(filename).name,
"data": "data:video/" + extension + ";base64," + data
})
return videos
def read_line(self) -> bool:
'''
Read in a bunch of max 2000 characters from stdin and send them back to
the associated web-socket connection (callback).
'''
stdout = ""
try:
# waits up to 50 ms for output; timeout=0 made the loop in spawn() spin on a full core
stdout = self.process.read_nonblocking(size=2000, timeout=0.05)
except Exception as _:
pass
if stdout:
self.output += len(stdout)
self.callback(stdout)
return True
return False
class Project:
'''
A project is a container for a temporary folder.
All files within this folder will be deleted when a project gets destroyed.
Additionally a process can be associated to project, which spawns an external execution,
that send stdout messages and receives stdin inputs.
'''
def __init__(self, uid: str, client):
self.uid: str = uid
self.dir: str = tempfile.mkdtemp(dir=RUNS)
self.filenames: List[str] = []
self.sources: str = "" # names and contents of all files, for the weight of the run
# for the scheduler
self.client = client
self.client_id = client["id"]
self.pending: list = []
self.busy: bool = False
self.active: float = time.time()
self.queued: float = 0
# memory in MB: the estimate for the command of this phase, set at `weighed`,
# and what counts for the scheduler
self.estimate: float = weights.DEFAULT
self.weighed: float = time.time()
self.weight: float = weights.DEFAULT
self.process: Process | None = None
self.thread: Thread | None = None
def __del__(self):
self.destroy()
def exec(self, cmd: str, filter_files: str | None, stdin, stop):
'''
This will spawn a new and persistent process, that will run in background.
It will send continuos messages back to the web-socket connection and a
finish message, when it is done.
'''
try:
if self.process:
self.process.destroy()
except Exception as _:
pass
# clean up leading spaces
cmd = cmd.lstrip()
if cmd.startswith("dotnet "):
self.process = Process(self.dir, "timeout -k 5 60 nice -19 " + jailed + cmd, filter_files, stdin, stop)
else:
self.process = Process(self.dir, prefix + cmd, filter_files, stdin, stop)
if self.process.error:
stop(self.process.error)
else:
self.thread = Thread(target=self.process.spawn)
self.thread.start()
def input(self, stdin: str):
'''Send inputs to stdin to a running process.'''
if self.process:
self.process.input(stdin)
def run(self, cmd: str):
'''
Directly run a subprocess and wait for the output.
'''
output = run_command(sandboxed(cmd), self.dir)
if len(output.stderr) > 0:
return {"ok": False,
"uid": self.uid,
"response": output.stderr}
return {"ok": True,
"uid": self.uid,
"response": output.stdout}
def compile(self, cmd: str):
'''
Perform a compilation and send back the success or error messages.
'''
rslt = compiler.run(cmd, self.dir, self.filenames)
rslt["uid"] = self.uid
return rslt
def kill(self):
'''
Kill the process if it is running.
'''
if self.process:
self.process.destroy()
kill_processes_in(self.dir)
def destroy(self):
'''
Kill all the process and delete all associated project files.
'''
try:
self.process.destroy()
except Exception as _:
pass
kill_processes_in(self.dir)
try:
shutil.rmtree(self.dir)
except Exception as _:
pass
def add_files(self, files: list[tuple[str, str]]) -> None:
'''Store a list of files, that consist of pairs of [filename, content]
within the predefined temporary folder.'''
self.filenames = []
self.sources = "\n".join(filename + "\n" + content for (filename, content) in files)
for (filename, content) in files:
filepath = os.path.realpath(os.path.join(self.dir, filename))
if not filepath.startswith(os.path.realpath(self.dir) + os.sep):
raise ValueError("file name outside of the project folder: " + filename)
self.filenames.append(filename)
if not os.path.isdir(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
file = open(filepath, "w", encoding='utf8')
file.write(content + "\n")
file.close()
VERSIONS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "versions.json")
VERSIONS = None
def get_versions():
'''
Versions of all compilers and interpreters, collected at image build time
(versions.json) or, if that file is missing, once on the first request.
'''
global VERSIONS
if VERSIONS is None:
try:
with open(VERSIONS_FILE, encoding="utf8") as file:
VERSIONS = json.load(file)
except (OSError, ValueError):
VERSIONS = versions.collect()
return VERSIONS
def new_client(client, x):
'''
Called for every client connecting (after handshake)
'''
logging.info("New client connected and was given id %s", client['id'])
# server.send_message_to_all("Hey all, a new client has joined us")
client["project"] = dict()
def client_left(client, _):
'''
Called for every client disconnecting
'''
if client == None:
return
logging.info("Client disconnected with id %s", client["id"])
# delete all associated files and kill all running processes
try:
for uid in list(client["project"]):
remove_project(client, uid)
scheduler.forget(client["id"])
except Exception as err:
logging.warning("client left with => %s", err)
def remove_project(client, uid) -> None:
'''
A project lives for one run: it is removed with its folder and processes when the
run has finished, failed or was stopped. The client uses a new uid for every run.
'''
project = client["project"].pop(uid, None)
if project:
try:
project.destroy()
finally:
scheduler.release(project)
def evict(project) -> None:
'''
Called by the scheduler: the project held a slot without activity while others wait.
'''
try:
server.send_message(project.client, json.dumps(
{"ok": False, "service": "stop", "uid": project.uid,
"error": "Stopped after %d seconds without input or output, because other runs are waiting." % IDLE_LIMIT}))
finally:
remove_project(project.client, project.uid)
other_memory: float = 0 # MB used by everything that is not a run, set by measure_memory
def capacity() -> float:
'''MB that all runs together may use.'''
return MEMORY_MB * MEMORY_SHARE - other_memory
scheduler = Scheduler(MAX_RUNS, MAX_RUNS_PER_CLIENT, IDLE_LIMIT, evict, capacity)
def measure_memory() -> None:
'''
Replace the estimated weights of the running projects by what their processes really
use, i.e. all processes with a working directory in the project folder. What the
rest uses (the server, compiler servers that stay alive) reduces the capacity.
Memory is counted as PSS, which counts shared pages once.
'''
global other_memory
with scheduler.lock:
running = list(scheduler.running)
folders = [(os.path.realpath(project.dir), project) for project in running]
used = {id(project): 0 for project in running}
total = 0
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/" + pid + "/smaps_rollup", encoding="utf8") as file:
pss = next(int(line.split()[1]) for line in file if line.startswith("Pss:"))
cwd = os.readlink("/proc/" + pid + "/cwd")
except (OSError, StopIteration):
continue # gone, or of another user
total += pss
for folder, project in folders:
if cwd == folder or cwd.startswith(folder + os.sep):
used[id(project)] += pss
break
now = time.time()
for project in running:
# a young program may still grow up to its estimate
floor = project.estimate if now - project.weighed < SETTLE else 1
project.weight = max(used[id(project)] / 1024, floor)
other_memory = (total - sum(used.values())) / 1024
def report(client, uid, error) -> None:
'''Send an error back as a `stop`, which the client shows and which ends the run.'''
logging.warning("message of client %s failed: %s", client["id"], error)
try:
server.send_message(client, json.dumps(
{"ok": False, "service": "stop", "uid": uid, "error": "CodeRunner: " + str(error)}))
finally:
remove_project(client, uid)
def work(client, message) -> None:
'''
The part of a message that needs a slot of the scheduler: compile, run and exec.
It runs in the thread of the connection, or in a thread of its own if it had to wait.
'''
try:
project = client["project"].get(message["uid"])
if project is None:
return # stopped or disconnected while it waited
if "compile" in message:
project.busy = True
try:
response = project.compile(message["compile"])
finally:
project.busy = False
project.active = time.time()
response["service"] = "compile"
server.send_message(client, json.dumps(response))
if not response["ok"]:
# the client ends the run after a failed compilation
remove_project(client, message["uid"])
return
if "run" in message:
project.busy = True
try:
response = project.run(message["run"])
finally:
project.busy = False
project.active = time.time()
response["service"] = "run"
server.send_message(client, json.dumps(response))
if "exec" in message:
def stdout(data):
project.active = time.time()
server.send_message(client, json.dumps(
{"ok": True,
"service": "stdout",
"uid": message["uid"],
"data": escape_ansi(data)}))
def stop(error_message: str | None = None, images=[], videos=[], files=[]):
resp = {"ok": True, "service": "stop", "uid": message["uid"]}
if error_message:
resp["error"] = error_message
if len(images) > 0:
resp["images"] = images
if len(videos) > 0:
resp["videos"] = videos
if len(files) > 0:
resp["files"] = files
try:
server.send_message(client, json.dumps(resp))
finally:
remove_project(client, message["uid"])
project.exec(message["exec"], message.get("filter"), stdout, stop)
except Exception as error:
report(client, message["uid"], error)
# Called when a client sends a message
def message_received(client, _, message) -> None:
'''
# Global message handler
Every message must have an `uid` and messages have to contain one of the
following fields:
* `data`:
This means that a bunch of files arrive, that are stored within the
temporary folder, that is associated with the project. This can be
associated to any message.
* `compile`:
this requires an compilation command, currently supported are:
- gcc
* `run`:
* `exec`:
* `input`:
This message shall contain stdin messages that are send to a
running process.
* `stop`: stop the process
'''
logging.debug("Client with id %s received: %s", client["id"], message)
if message == "ping":
return
message = json.loads(message)
if "uid" not in message:
logging.warning("received message without uid => %s", json.dumps(message, indent=2))
return
# answered directly, without creating a project and its temporary folder
if "versions" in message:
server.send_message(client, json.dumps(
{"ok": True, "service": "versions", "uid": message["uid"], "data": get_versions()}))
return
if not message["uid"] in client["project"]:
# a late stdin or stop of a finished run must not create a new project
if not any(key in message for key in ("data", "compile", "run", "exec")):
if "stop" in message:
server.send_message(client, json.dumps({"ok": True, "service": "stop", "uid": message["uid"]}))
return
if len(client["project"]) >= MAX_PROJECTS_PER_CLIENT:
raise ValueError("too many runs at once, at most %d per connection" % MAX_PROJECTS_PER_CLIENT)
client["project"][message["uid"]] = Project(message["uid"], client)
if "data" in message:
logging.debug("Client(%d) => %s", client['id'], message["data"])
client["project"][message["uid"]].add_files(message["data"])
response = {"ok": True, "uid": message["uid"], "service": "data"}
server.send_message(client, json.dumps(response))
commands = [message[key] for key in ("compile", "run", "exec") if key in message]
commands = [command for command in commands if not command.strip().startswith("none")]
if "compile" in message and not commands:
work(client, message) # nothing to compile: answered at once, the slot is taken for exec
elif commands:
project = client["project"][message["uid"]]
# the weight of this phase: the compiler, then the program
project.estimate = min(max(weights.estimate(command, project.sources) for command in commands),
MEMORY_MB * MEMORY_SHARE * LARGEST_ESTIMATE)
project.weighed = time.time()
project.weight = project.estimate
queue = scheduler.queue_length(project)
if queue:
# sent as output, so that every version of the client shows it
server.send_message(client, json.dumps(
{"ok": True, "service": "stdout", "uid": message["uid"],
"data": "The server is busy: %d run%s waiting. Yours starts as soon as a slot is free ...\n"
% (queue, " is" if queue == 1 else "s are")}))
scheduler.submit(project, lambda: work(client, message))
if "stdin" in message and message["uid"] in client["project"]:
client["project"][message["uid"]].active = time.time()
client["project"][message["uid"]].input(message["stdin"])
if "stop" in message and message["uid"] in client["project"]:
client['project'][message["uid"]].kill()
server.send_message(client, json.dumps({"ok": True, "service": "stop", "uid": message["uid"]}))
remove_project(client, message["uid"])
def safe_message_received(client, server_, message) -> None:
'''
A faulty message must not end the connection. The error is sent back as a
`stop`, which the client shows and which ends the run.
'''
try:
message_received(client, server_, message)
except Exception as error:
try:
uid = json.loads(message)["uid"]
except Exception as _:
logging.warning("message of client %s ignored: %s", client["id"], error)
return
report(client, uid, error)
if __name__ == "__main__":
argv = sys.argv[1:]
PORT = int(os.environ.get('CODERUNNER_PORT') or os.environ.get('PORT') or '8000')
HOST = os.environ.get('CODERUNNER_HOST') or '0.0.0.0'
options, args = getopt.getopt(argv, "p:h", ["port=", "host=", "help"])
for opt, arg in options:
if opt in ('-p', '--port'):
PORT = int(arg)
elif opt == "--host":
HOST = arg
elif opt in ("-h", "--help"):
print("CodeRunner")
print()
print(" This service is meant to be used with LiaScript and its CodeRunner implementation in")
print(" order to run execute small peaces of code as a web-service.")
print()
print("Options:")
print()
print(" -h, --help Print out the help")
print(" -p, --port Set the server port, this will overwrite the env-variable CODERUNNER_PORT or PORT")
print(" ... defaults to 8000")
print(" --host Set the server host, this will overwrite the env-variable CODERUNNER_HOST")
print(" ... defaults to 0.0.0.0")
exit(0)
server = Server(host=HOST, port=PORT)
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(safe_message_received)
logging.basicConfig(level=logging.DEBUG)
def tick():
# measured weights and time alone (idle runs) can make room for waiting runs
while True:
time.sleep(1)
try:
measure_memory()
scheduler.dispatch()
except Exception as error:
logging.warning("tick failed: %s", error)
Thread(target=tick, daemon=True).start()
# The home of all runs, where tools keep their caches. It must not be the folder of the
# server (HOME on Heroku): the runs may write to their home, see jail.py.
os.environ["HOME"] = tempfile.mkdtemp(prefix="home-")
# A helper that outlives its run and serves the next ones has the rights of the run that
# started it, and no access to the files of the others. So dotnet builds without its
# compiler server and without build nodes that wait for the next build.
os.environ.update(UseSharedCompilation="false", MSBUILDDISABLENODEREUSE="1")
landlock = jail.version()
if landlock >= 6:
logging.info("runs are locked into their folders (Landlock %d)", landlock)
elif landlock:
logging.warning("runs are locked into their folders, but can signal the server and other runs "
"(Landlock %d, limiting signals needs Linux 6.12)", landlock)
else:
logging.warning("no Landlock: a run can read and change the folders of other runs and end the server")