|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright 2016 The Chromium Authors. All rights reserved. |
| 3 | +# Use of this source code is governed by a BSD-style license that can be |
| 4 | +# found in the LICENSE file. |
| 5 | + |
| 6 | +"""Exceptions used by the Kasko integration test module.""" |
| 7 | + |
| 8 | +import BaseHTTPServer |
| 9 | +import cgi |
| 10 | +import logging |
| 11 | +import os |
| 12 | +import socket |
| 13 | +import threading |
| 14 | +import time |
| 15 | +import uuid |
| 16 | +import json |
| 17 | +import gzip |
| 18 | +from StringIO import StringIO |
| 19 | + |
| 20 | +_LOGGER = logging.getLogger(os.path.basename(__file__)) |
| 21 | + |
| 22 | + |
| 23 | +class _StoppableHTTPServer(BaseHTTPServer.HTTPServer): |
| 24 | + """An extension of BaseHTTPServer that uses timeouts and is interruptable.""" |
| 25 | + |
| 26 | + def server_bind(self): |
| 27 | + BaseHTTPServer.HTTPServer.server_bind(self) |
| 28 | + self.socket.settimeout(1) |
| 29 | + self.run_ = True |
| 30 | + |
| 31 | + def get_request(self): |
| 32 | + while self.run_: |
| 33 | + try: |
| 34 | + sock, addr = self.socket.accept() |
| 35 | + sock.settimeout(None) |
| 36 | + return (sock, addr) |
| 37 | + except socket.timeout: |
| 38 | + pass |
| 39 | + |
| 40 | + def stop(self): |
| 41 | + self.run_ = False |
| 42 | + |
| 43 | + def serve(self): |
| 44 | + while self.run_: |
| 45 | + self.handle_request() |
| 46 | + |
| 47 | + |
| 48 | +class CrashServer(object): |
| 49 | + """A simple crash server for testing.""" |
| 50 | + |
| 51 | + def __init__(self): |
| 52 | + self.server_ = None |
| 53 | + self.lock_ = threading.Lock() |
| 54 | + self.crashes_ = [] # Under lock_. |
| 55 | + |
| 56 | + def crash(self, index): |
| 57 | + """Accessor for the list of crashes.""" |
| 58 | + with self.lock_: |
| 59 | + if index >= len(self.crashes_): |
| 60 | + return None |
| 61 | + return self.crashes_[index] |
| 62 | + |
| 63 | + @property |
| 64 | + def port(self): |
| 65 | + """Returns the port associated with the server.""" |
| 66 | + if not self.server_: |
| 67 | + return 0 |
| 68 | + return self.server_.server_port |
| 69 | + |
| 70 | + def start(self): |
| 71 | + """Starts the server on another thread. Call from main thread only.""" |
| 72 | + page_handler = self.multipart_form_handler() |
| 73 | + self.server_ = _StoppableHTTPServer(('127.0.0.1', 0), page_handler) |
| 74 | + self.thread_ = self.server_thread() |
| 75 | + self.thread_.start() |
| 76 | + |
| 77 | + def stop(self): |
| 78 | + """Stops the running server. Call from main thread only.""" |
| 79 | + self.server_.stop() |
| 80 | + self.thread_.join() |
| 81 | + self.server_ = None |
| 82 | + self.thread_ = None |
| 83 | + |
| 84 | + def wait_for_report(self, timeout): |
| 85 | + """Waits until the server has received a crash report. |
| 86 | +
|
| 87 | + Returns True if the a report has been received in the given time, or False |
| 88 | + if a timeout occurred. Since Python condition variables have no notion of |
| 89 | + timeout this is, sadly, a busy loop on the calling thread. |
| 90 | + """ |
| 91 | + started = time.time() |
| 92 | + elapsed = 0 |
| 93 | + while elapsed < timeout: |
| 94 | + with self.lock_: |
| 95 | + if len(self.crashes_): |
| 96 | + return True |
| 97 | + time.sleep(0.1) |
| 98 | + elapsed = time.time() - started |
| 99 | + |
| 100 | + return False |
| 101 | + |
| 102 | + |
| 103 | + def multipart_form_handler(crash_server): |
| 104 | + """Returns a multi-part form handler class for use with a BaseHTTPServer.""" |
| 105 | + |
| 106 | + class MultipartFormHandler(BaseHTTPServer.BaseHTTPRequestHandler): |
| 107 | + """A multi-part form handler that processes crash reports. |
| 108 | +
|
| 109 | + This class only handles multipart form POST messages, with all other |
| 110 | + requests by default returning a '501 not implemented' error. |
| 111 | + """ |
| 112 | + |
| 113 | + def __init__(self, request, client_address, socket_server): |
| 114 | + BaseHTTPServer.BaseHTTPRequestHandler.__init__( |
| 115 | + self, request, client_address, socket_server) |
| 116 | + |
| 117 | + def log_message(self, format, *args): |
| 118 | + _LOGGER.debug(format, *args) |
| 119 | + |
| 120 | + def do_POST(self): |
| 121 | + """Handles POST messages contained multipart form data.""" |
| 122 | + content_type, parameters = cgi.parse_header( |
| 123 | + self.headers.getheader('content-type')) |
| 124 | + if content_type != 'multipart/form-data': |
| 125 | + raise Exception('Unsupported Content-Type: ' + content_type) |
| 126 | + if self.headers.getheader('content-encoding') == 'gzip': |
| 127 | + self.log_message('GZIP'); |
| 128 | + readsize = self.headers.getheader('content-length') |
| 129 | + buffer = StringIO(self.rfile.read(int(readsize))) |
| 130 | + with gzip.GzipFile(fileobj=buffer, mode="r") as f: |
| 131 | + post_multipart = cgi.parse_multipart(f, parameters) |
| 132 | + else: |
| 133 | + post_multipart = cgi.parse_multipart(self.rfile, parameters) |
| 134 | + self.log_message("got part") |
| 135 | + |
| 136 | + # Save the crash report. |
| 137 | + report = dict(post_multipart.items()) |
| 138 | + report_id = str(uuid.uuid4()) |
| 139 | + report['report-id'] = [report_id] |
| 140 | + self.log_message("got report %s", report_id) |
| 141 | + self.log_message("%s", json.dumps(report.keys())) |
| 142 | + with crash_server.lock_: |
| 143 | + crash_server.crashes_.append(report) |
| 144 | + |
| 145 | + # Send the response. |
| 146 | + self.send_response(200) |
| 147 | + self.send_header("Content-Type", "text/plain") |
| 148 | + self.end_headers() |
| 149 | + self.wfile.write(report_id) |
| 150 | + |
| 151 | + return MultipartFormHandler |
| 152 | + |
| 153 | + def server_thread(crash_server): |
| 154 | + """Returns a thread that hosts the webserver.""" |
| 155 | + |
| 156 | + class ServerThread(threading.Thread): |
| 157 | + def run(self): |
| 158 | + crash_server.server_.serve() |
| 159 | + |
| 160 | + return ServerThread() |
| 161 | + |
| 162 | +def main(): |
| 163 | + server = CrashServer() |
| 164 | + server.start() |
| 165 | + |
| 166 | +if __name__ == "__main__": |
| 167 | + main() |
0 commit comments