Repository: michaelliao/remote-code-runner Branch: master Commit: 9aa5d154f366 Files: 8 Total size: 29.4 KB Directory structure: gitextract_20f7fthz/ ├── .gitignore ├── LICENSE ├── README.md ├── generate.py └── src/ ├── config.json ├── nginx-proxy-sample.conf ├── runner.py └── start-runner.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # skip bin and ssl: bin/ ssl/*.crt ssl/*.key # Docker.gitignore # docker/app/log docker/elasticsearch/data docker/mysql/data docker/nginx/cache docker/nginx/log docker/nginx/root docker/.env # Java.gitignore ############################################################## *.class backup/ # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.ear # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* # Maven.gitignore ############################################################# target/ pom.xml.tag pom.xml.releaseBackup pom.xml.versionsBackup pom.xml.next release.properties dependency-reduced-pom.xml buildNumber.properties .mvn/timing.properties # Eclipse.gitignore ########################################################### *.pydevproject .metadata .gradle tmp/ *.tmp *.bak *.swp *~.nib local.properties .settings/ .loadpath # Eclipse Core .project # External tool builders .externalToolBuilders/ .recommenders/ # Locally stored "Eclipse launch configurations" *.launch # CDT-specific .cproject # JDT-specific (Eclipse Java Development Tools) .classpath # Java annotation processor (APT) .factorypath # PDT-specific .buildpath # sbteclipse plugin .target # TeXlipse plugin .texlipse # NetBeans.gitignore ########################################################## nbproject/private/ build/ nbbuild/ dist/ nbdist/ nbactions.xml nb-configuration.xml .nb-gradle/ # JetBrains.gitignore ######################################################### # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio *.iml ## Directory-based project format: .idea/ # if you remove the above rule, at least ignore the following: # User-specific stuff: # .idea/workspace.xml # .idea/tasks.xml # .idea/dictionaries # Sensitive or high-churn files: # .idea/dataSources.ids # .idea/dataSources.xml # .idea/sqlDataSources.xml # .idea/dynamic.xml # .idea/uiDesigner.xml # Gradle: # .idea/gradle.xml # .idea/libraries # Mongo Explorer plugin: # .idea/mongoSettings.xml ## File-based project format: *.ipr *.iws ## Plugin-specific files: # IntelliJ /out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties # SublimeText.gitignore ####################################################### # cache files for sublime text *.tmlanguage.cache *.tmPreferences.cache *.stTheme.cache # workspace files are user-specific *.sublime-workspace # project files should be checked into the repository, unless a significant # proportion of contributors will probably not be using SublimeText # *.sublime-project # sftp configuration file sftp-config.json # Vim.gitignore ############################################################### [._]*.s[a-w][a-z] [._]s[a-w][a-z] *.un~ Session.vim .netrwhist *~ # Emacs.gitignore ############################################################# # -*- mode: gitignore; -*- *~ \#*\# /.emacs.desktop /.emacs.desktop.lock *.elc auto-save-list tramp .\#* # Org-mode .org-id-locations *_archive # flymake-mode *_flymake.* # eshell files /eshell/history /eshell/lastdir # elpa packages /elpa/ # reftex files *.rel # AUCTeX auto folder /auto/ # cask packages .cask/ # Python ignore ############################################################### *.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 __pycache__ # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # OSX.gitignore ############################################################### .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk # Windows.gitignore ########################################################### # Windows image file caches Thumbs.db ehthumbs.db # Folder config file Desktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msm *.msp # Windows shortcuts *.lnk # Linux.gitignore ############################################################# *~ # KDE directory preferences .directory # Linux trash folder which might appear on any partition or disk .Trash-* ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Remote Code Runner Remote Code Runner is a simple code service for running code on remote server side. Docker is used to execute untrusted code in a sandbox environment. # Install Environment: - Ubuntu Linux 18.04 - Docker 19.x - Python 3.8 MAKE SURE the login user has `sudo` privileges and does not require entering a password. Install all required software: ``` $ sudo apt install git docker.io python3.8 ``` Get source: ``` $ cd /srv $ sudo git clone https://github.com/michaelliao/remote-code-runner.git ``` Generate all from source: ``` $ cd /srv/remote-code-runner $ sudo python3.8 generate.py ``` Download required docker images by warm up script (this may take a long time): ``` $ cd /srv/remote-code-runner/bin $ sudo sh warm-up-docker.sh ``` Start server: ``` $ cd /srv/remote-code-runner/bin $ sudo start-runner.sh ``` # Usage Using simple HTTP JSON API: ``` $ curl http://server-ip:8080/run -H 'Content-Type: application/json' -d '{"language":"python","code":"import math\nprint(math.pi)"}' {"error": false, "timeout": false, "truncated": false, "output": "3.141592653589793\n"} ``` API input: - language: language name, lowercase: `java`, `python`, `ruby`. - code: language code as JSON string: `import math\nprint(math.pi)` API output: - timeout: boolean, is execution timeout. - error: boolean, is error output. e.g. compile failed or syntax error. - truncated: boolean, is output was truncated for too many characters. - output: string, the output of execution. # Execution How code are executed on the remote server side: 1. Http server `runner.py` got language name and code from API; 2. Write code into a temperary directory like `/tmp/remote-code-runner/1`; 3. Execute command like `sudo docker run -t --rm -w /app -v /tmp/dir:/app python3 main.py`; 4. Write output into API response; 5. Clean up temperary directory. # Limitation - Multiple files are not supported. - There is no way to read input from console. Any user input code will cause timeout. # Security Remote code runner should only be served in private network. User identity check, rate limit must be done in application server or reverse proxy like Nginx. # Extension How to add a new language: 1. Add configuration in `config.json`: ``` { ... "languages": { ... "node": { "file": "main.js", "image": "node:14.17-slim", "command": "node main.js" } } } ``` The key `node` is the language name. 2. Make sure image is downloaded on local: ``` $ sudo docker run -t --rm node:13.12-slim ls ``` 3. Restart `start-runner.sh`. ================================================ FILE: generate.py ================================================ #!/usr/bin/env python3 # -*- coding: utf-8 -*- 'a remote code running service tool' import os, sys, json, subprocess def main(): cwd = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) print('Set remote code runner path = %s' % cwd) print('Check system requirement:') run('sudo docker -v', 'Try install docker by command: sudo apt install docker.io') run('sudo python3.8 --version', 'Try install python 3.8 by command: sudo apt install python3.8') settings = {} settings['$RCR_PATH'] = cwd settings['$RCR_IP'] = getInput('Remote code runner listening IP', '127.0.0.1') settings['$RCR_PORT'] = getInput('Remote code runner listening port', '8080') settings['$RCR_TIMEOUT'] = getInput('Remote code runner execution timeout in seconds', '5') settings['$RCR_TEMP'] = getInput('Remote code runner temporary directory', '/tmp/remote-code-runner') yn = input('Generate release? [yN] ') if yn.lower() != 'y': exit(1) print('generate config.json...') generateFile(cwd, 'src/config.json', 'bin/config.json', settings) print('copy runner.py...') generateFile(cwd, 'src/runner.py', 'bin/runner.py', settings) print('generate start-runner.sh...') generateFile(cwd, 'src/start-runner.sh', 'bin/start-runner.sh', settings) print('generate warm-up-docker.sh...') warmUps = [] configJson = json.loads(readFile(cwd, 'src/config.json')) for lang, conf in configJson['languages'].items(): warmUps.append('echo ">>> sudo docker run -t --rm %s ls"' % conf['image']) warmUps.append('sudo docker run -t --rm %s ls' % conf['image']) writeFile(cwd, 'bin/warm-up-docker.sh', '\n'.join(warmUps)) def run(cmd, msgOnError=''): print('[execute] %s' % cmd) code = subprocess.call(cmd, shell=True) if code != 0: print(msgOnError) exit(1) def getInput(prompt, default=None): if default: s = input('%s [%s]: ' % (prompt, default)).strip() if s == '': s = default return s else: s = input('%s: ' % prompt).strip() return s def generateFile(cwd, source, dest, settings): content = readFile(cwd, source) content = replaceAll(content, settings) writeFile(cwd, dest, content) def readFile(cwd, fname): with open(os.path.join(cwd, fname), 'r', encoding='utf-8') as f: return f.read() def writeFile(cwd, fname, content): with open(os.path.join(cwd, fname), 'w', encoding='utf-8') as f: f.write(content) def replaceAll(s, settings): for k, v in settings.items(): s = s.replace(k, v) return s if __name__ == '__main__': main() ================================================ FILE: src/config.json ================================================ { "ip": "$RCR_IP", "port": "$RCR_PORT", "tempdir": "$RCR_TEMP", "docker": "docker run -t --rm --cpus=1 --network none -w /app -v %s:/app %s %s", "timeout": "$RCR_TIMEOUT", "languages": { "java": { "file": "Main.java", "image": "openjdk:16-slim", "command": "java -Xmx48m --source 16 --enable-preview -XX:+ShowCodeDetailsInExceptionMessages Main.java" }, "python": { "file": "main.py", "image": "python:3.9-slim", "command": "python3 -B main.py" }, "ruby": { "file": "main.rb", "image": "ruby:2.7-slim", "command": "ruby main.rb" }, "node": { "file": "main.js", "image": "node:14.17-slim", "command": "node main.js" }, "c": { "file": "main.c", "image": "gcc:9.3", "command": "gcc -Wall -o main main.c && ./main" } } } ================================================ FILE: src/nginx-proxy-sample.conf ================================================ # # NGINX CONFIGURATION # upstream rcr_upstream { server 127.0.0.1:80 fail_timeout=10s; } server { listen 80; server_name _; root /var/www/html; access_log /var/log/nginx/remote_code_runner_access.log; error_log /var/log/nginx/remote_code_runner_error.log; client_max_body_size 2m; gzip on; gzip_min_length 1024; gzip_buffers 4 8k; gzip_types text/css application/x-javascript application/json; location / { proxy_pass http://rcr_upstream; proxy_set_header Host $host; proxy_read_timeout 10s; } } ================================================ FILE: src/runner.py ================================================ #!/usr/bin/env python3 # -*- coding: utf-8 -*- 'a remote code running service' import os, sys, time, json, shutil, subprocess, threading from urllib import parse from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler class Dict(dict): def __init__(self, **kw): super().__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"'Dict' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value def configHook(d): kw = dict() for k, v in d.items(): if isinstance(v, str): kw[k] = os.path.expandvars(v) else: kw[k] = v return Dict(**kw) APP_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) with open(os.path.join(APP_DIR, 'config.json'), 'r', encoding='utf-8') as f: CONFIG = json.load(f, object_hook=configHook) print('load config:\n%s' % json.dumps(CONFIG, indent=4)) HTML_INDEX = ''' Remote Code Runner

Timeout:

Response:

''' globalIdCounter = 0 globalIdCounterLock = threading.Lock() def nextId(): global globalIdCounter with globalIdCounterLock: globalIdCounter += 1 return globalIdCounter def run(cmd, cwd, timeout): result = dict(error=False, timeout=False, truncated=False, output='') try: output = subprocess.check_output(cmd.split(' '), cwd=cwd, stderr=subprocess.STDOUT, timeout=timeout) output = decode(output) if len(output) > 4000: result['output'] = output[:4000] result['truncated'] = True else: result['output'] = output except subprocess.TimeoutExpired: result['timeout'] = True except subprocess.CalledProcessError as e: result['error'] = True result['output'] = decode(e.output) return result def decode(s): try: return s.decode('utf-8') except UnicodeDecodeError: return s.decode('gbk') class RunnerHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.sendResponse(HTML_INDEX, 'text/html') elif self.path == '/health': self.sendResponse(b'{"status":"UP"}') else: self.responseError(404) def do_POST(self): if self.path != '/run': return self.responseError(404) body = json.loads(self.rfile.read(int(self.headers['Content-Length'])).decode('utf-8')) lang = body['language'] code = body['code'] if not lang in CONFIG.languages: raise KeyError('language not found: ' + lang) start = time.time() print('[%s] prepare...' % lang) tempDir = self.createTempDir() print('[%s] create temp dir: %s' % (lang, tempDir)) try: cfg = CONFIG.languages[lang] tempFile = os.path.join(tempDir, cfg.file) with open(tempFile, 'w', encoding='utf-8') as f: f.write(code) print('[%s] write file: %s' % (lang, tempFile)) # execute: cmd = 'timeout %s %s' % (CONFIG.timeout, cfg.command) if 'docker' in CONFIG: img = cfg.image cmd = CONFIG.docker % (tempDir, img, cmd) print('[%s] command: %s' % (lang, cmd)) result = run(cmd, tempDir, int(CONFIG.timeout)) finally: shutil.rmtree(tempDir) print('[%s] remove temp dir: %s' % (lang, tempDir)) print('[%s] executed in %s.' % (lang, time.time() - start)) self.sendResponse(result) def responseError(self, errorCode, body=None): self.close_connection = True self.send_response(errorCode) if body: data = self.toJsonBytes(body) self.send_header('Content-Type') self.send_header('Content-Length', str(len(data))) self.end_headers() self.wfile.write(data) def sendResponse(self, body, contentType='application/json'): data = self.toJsonBytes(body) self.close_connection = True self.send_response(200) self.send_header('Content-Type', contentType) self.send_header('Content-Length', str(len(data))) self.end_headers() self.wfile.write(data) def toJsonBytes(self, data): if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('utf-8') else: return json.dumps(data).encode('utf-8') def createTempDir(self): dirName = str(nextId()) fp = os.path.join(CONFIG.tempdir, dirName) os.mkdir(fp) return fp def writeTempFile(self, path, content): with open(os.path.join(path, filename), 'w', encoding='utf-8') as f: f.write(content) def main(): print('Prepare temporary dir %s for code runner...' % CONFIG.tempdir) if not os.path.isdir(CONFIG.tempdir): os.makedirs(CONFIG.tempdir) httpd = ThreadingHTTPServer((CONFIG.ip, int(CONFIG.port)), RunnerHTTPRequestHandler) print('Ready for code runner on %s:%s...' % (CONFIG.ip, CONFIG.port)) print('Press Ctrl + C to exit...') httpd.serve_forever() if __name__ == '__main__': main() ================================================ FILE: src/start-runner.sh ================================================ #!/bin/bash cd "$(dirname "$0")" sudo nohup python3.8 runner.py > ./output.log 2>&1