aboutsummaryrefslogtreecommitdiffstats
path: root/snekbox.py
blob: 4dfcc4814c95982b9181fb83f44a13c9ca156264 (plain) (blame)
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
import traceback
import sys
import time
import pika
import io
import json

from rmq.consumer import consume
from rmq.publisher import publish

from config import USERNAME
from config import PASSWORD
from config import HOST
from config import PORT
from config import EXCHANGE
from config import EXCHANGE_TYPE
from config import QUEUE
from config import RETURN_QUEUE
from config import RETURN_EXCHANGE
from config import RETURN_ROUTING_KEY

def execute(snippet):
    old_stdout = sys.stdout
    redirected_output = sys.stdout = io.StringIO()
    failed = False
    try:
        exec(snippet)
    except Exception as e:
        failed = str(e)
    finally:
        sys.stdout = old_stdout

    if failed:
        return failed.strip()
    return redirected_output.getvalue().strip()


def message_handler(ch, method, properties, body):
    msg = body.decode('utf-8')

    # Execute code snippets here
    print(f"incoming: {msg}", flush=True)
    snek_msg = json.loads(msg)
    for snekid, snekcode in snek_msg.items():
        result = execute(snekcode)
        print(f"outgoing: {result}", flush=True)
        publish(result, host=HOST, queue=snekid, routingkey=snekid, exchange=snekid, exchange_type=EXCHANGE_TYPE)

    ch.basic_ack(delivery_tag = method.delivery_tag)

if __name__ == '__main__':
    consume(host=HOST, queue=QUEUE, callback=message_handler)