| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# |
| 3 |
# testcontrol-web-service.py |
| 4 |
# |
| 5 |
# Author: Toke Høiland-Jørgensen ([email protected]) |
| 6 |
# Date: 25 October 2014 |
| 7 |
# Copyright (c) 2014-2016, Toke Høiland-Jørgensen |
| 8 |
# |
| 9 |
# This program is free software: you can redistribute it and/or modify |
| 10 |
# it under the terms of the GNU General Public License as published by |
| 11 |
# the Free Software Foundation, either version 3 of the License, or |
| 12 |
# (at your option) any later version. |
| 13 |
# |
| 14 |
# This program is distributed in the hope that it will be useful, |
| 15 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 |
# GNU General Public License for more details. |
| 18 |
# |
| 19 |
# You should have received a copy of the GNU General Public License |
| 20 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 21 |
|
| 22 |
from __future__ import absolute_import, division, print_function, unicode_literals |
| 23 |
|
| 24 |
import json |
| 25 |
import os |
| 26 |
import re |
| 27 |
import select |
| 28 |
import shlex |
| 29 |
import subprocess |
| 30 |
import sys |
| 31 |
|
| 32 |
try: |
| 33 |
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler |
| 34 |
from SocketServer import ForkingMixIn |
| 35 |
except ImportError: |
| 36 |
from http.server import HTTPServer, BaseHTTPRequestHandler |
| 37 |
from socketserver import ForkingMixIn |
| 38 |
|
| 39 |
tests = [{'name': 'test', |
| 40 |
'args': {'ipver': 'IP version (4 or 6)'}, |
| 41 |
'exec': './test-exec.sh ${ipver}'}] |
| 42 |
|
| 43 |
|
| 44 |
class TestWebServer(ForkingMixIn, HTTPServer): |
| 45 |
pass |
| 46 |
|
| 47 |
|
| 48 |
class TestWebService(BaseHTTPRequestHandler): |
| 49 |
_INTERP_REGEX = re.compile(r"(^|[^$])(\$\{([^}]+)\})") |
| 50 |
_MAX_INTERP = 1000 |
| 51 |
|
| 52 |
def respond(self, obj): |
| 53 |
self.send_response(200) |
| 54 |
self.send_header("Content-type", "application/json; charset=utf8") |
| 55 |
self.end_headers() |
| 56 |
self.wfile.write(json.dumps(obj).encode("utf-8")) |
| 57 |
self.wfile.write("\n".encode("utf-8")) |
| 58 |
|
| 59 |
def find_test(self, name): |
| 60 |
for t in tests: |
| 61 |
if t['name'] == name: |
| 62 |
return t |
| 63 |
self.send_error(404, "Test not found: %s" % name) |
| 64 |
return None |
| 65 |
|
| 66 |
def do_GET(self): |
| 67 |
print(self.headers) |
| 68 |
parts = os.path.split(self.path) |
| 69 |
if len(parts) < 3 and not parts[1]: |
| 70 |
self.respond(list([i['name'] for i in tests])) |
| 71 |
else: |
| 72 |
test = self.find_test(parts[1]) |
| 73 |
if test: |
| 74 |
self.respond(test['args']) |
| 75 |
|
| 76 |
def parse_input(self): |
| 77 |
length = self.headers.get('content-length') |
| 78 |
input_type = self.headers.get('Content-Type') |
| 79 |
parts = input_type.split(";", 1) |
| 80 |
if parts[0].strip().lower() != 'application/json': |
| 81 |
self.send_error(415, 'Invalid format. Needs application/json') |
| 82 |
return None |
| 83 |
if len(parts) > 1 and parts[1].startswith('charset='): |
| 84 |
charset = parts[1].split("=", 1)[1].strip() |
| 85 |
else: |
| 86 |
charset = 'utf-8' |
| 87 |
|
| 88 |
try: |
| 89 |
nbytes = int(length) |
| 90 |
except (TypeError, ValueError): |
| 91 |
self.send_error(411) |
| 92 |
return None |
| 93 |
|
| 94 |
if nbytes > 0: |
| 95 |
data = self.rfile.read(nbytes) |
| 96 |
|
| 97 |
while select.select([self.rfile], [], [], 0)[0]: |
| 98 |
if not self.rfile.read(1): |
| 99 |
break |
| 100 |
|
| 101 |
try: |
| 102 |
return json.loads(data.decode(charset)) |
| 103 |
except Exception as e: |
| 104 |
self.send_error(400, "Unable to decode: %s" % e) |
| 105 |
|
| 106 |
def interpolate(self, string, req): |
| 107 |
m = self._INTERP_REGEX.search(string) |
| 108 |
i = 0 |
| 109 |
while m is not None: |
| 110 |
k = m.group(3) |
| 111 |
if k in req: |
| 112 |
string = string.replace(m.group(2), str(req[k])) |
| 113 |
else: |
| 114 |
string = string.replace(m.group(2), "$${%s}" % k) |
| 115 |
m = self._INTERP_REGEX.search(string) |
| 116 |
i += 1 |
| 117 |
if i > self._MAX_INTERP: |
| 118 |
self.send_error( |
| 119 |
500, "Too many interpolations performed for exec string.") |
| 120 |
return None |
| 121 |
return string.replace("$$", "$") |
| 122 |
|
| 123 |
def handle_test(self, test, req): |
| 124 |
cmdline = self.interpolate(test['exec'], req) |
| 125 |
if cmdline: |
| 126 |
args = shlex.split(cmdline) |
| 127 |
proc = subprocess.Popen(args, stdout=subprocess.PIPE) |
| 128 |
resp = json.loads(proc.stdout.readline().decode('utf-8')) |
| 129 |
self.respond(resp) |
| 130 |
|
| 131 |
def do_POST(self): |
| 132 |
parts = os.path.split(self.path) |
| 133 |
if not parts[1]: |
| 134 |
self.send_error(405) |
| 135 |
return |
| 136 |
test = self.find_test(parts[1]) |
| 137 |
if test: |
| 138 |
req = self.parse_input() |
| 139 |
if req: |
| 140 |
self.handle_test(test, req) |
| 141 |
|
| 142 |
|
| 143 |
if __name__ == "__main__": |
| 144 |
server_addr = ('localhost', 8000) |
| 145 |
server = TestWebServer(server_addr, TestWebService) |
| 146 |
try: |
| 147 |
server.serve_forever() |
| 148 |
except KeyboardInterrupt: |
| 149 |
sys.exit(0) |