-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
63 lines (56 loc) · 2.09 KB
/
routes.js
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
const express = require('express');
const Docker = require('dockerode');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const fs = require('fs');
const config = require('./config.js');
const docker = new Docker({ socketPath: '/var/run/docker.sock' });
const router = express.Router();
router.route('/run').post(async (req, res) => {
try {
let language = config.languages[req.body.language];
if (typeof language === 'undefined') {
res.status(400).send('Language not supported');
return;
}
let randomName = Math.random().toString(36).substring(7);
await fs.writeFileSync(`./temp/${randomName}`, req.body.code);
let container = await docker.createContainer({ Image: language.docker, Cmd: ['./run.sh'], name: randomName });
await exec(`docker cp ./temp/${randomName} ${container.id}:${language.file} && docker cp ./languages/${language.script} ${container.id}:run.sh`);
container.start();
res.status(200);
res.setHeader('content-type', 'text/html');
const stream = await container.attach({ stream: true, stdin: true, stdout: true, stderr: true });
stream.setEncoding('utf8');
stream.on('data', (chunk) => {
res.write((chunk.toString() + "").replace(0, "").substring(8), 'utf8');
});
stream.on('end', () => { res.end() });
await sleep(5000);
container = docker.getContainer(container.id);
if (container.status == 'running') {
await container.kill();
}
await container.remove();
await fs.unlinkSync(`./temp/${randomName}`);
} catch (err) {
try{
await container.remove();
} catch (err) {
}
console.log(err);
}
});
router.route('/languages').get((req, res) => {
let l = [];
for (const property in config.languages) {
l.push(config.languages[property].name);
}
res.send(l);
});
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
module.exports = router;