| OLD | NEW |
| (Empty) |
| 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 import os | |
| 5 import socket | |
| 6 import subprocess | |
| 7 import sys | |
| 8 import urlparse | |
| 9 | |
| 10 from telemetry.core import util | |
| 11 | |
| 12 class TemporaryHTTPServer(object): | |
| 13 def __init__(self, browser_backend, path): | |
| 14 self._server = None | |
| 15 self._devnull = None | |
| 16 self._path = path | |
| 17 self._forwarder = None | |
| 18 | |
| 19 self._host_port = util.GetAvailableLocalPort() | |
| 20 | |
| 21 assert os.path.exists(path), path | |
| 22 assert os.path.isdir(path), path | |
| 23 | |
| 24 self._devnull = open(os.devnull, 'w') | |
| 25 self._server = subprocess.Popen( | |
| 26 [sys.executable, '-m', 'SimpleHTTPServer', str(self._host_port)], | |
| 27 cwd=self._path, | |
| 28 stdout=self._devnull, stderr=self._devnull) | |
| 29 | |
| 30 self._forwarder = browser_backend.CreateForwarder( | |
| 31 util.PortPair(self._host_port, | |
| 32 browser_backend.GetRemotePort(self._host_port))) | |
| 33 | |
| 34 def IsServerUp(): | |
| 35 return not socket.socket().connect_ex(('localhost', self._host_port)) | |
| 36 util.WaitFor(IsServerUp, 5) | |
| 37 | |
| 38 @property | |
| 39 def path(self): | |
| 40 return self._path | |
| 41 | |
| 42 def __enter__(self): | |
| 43 return self | |
| 44 | |
| 45 def __exit__(self, *args): | |
| 46 self.Close() | |
| 47 | |
| 48 def __del__(self): | |
| 49 self.Close() | |
| 50 | |
| 51 def Close(self): | |
| 52 if self._forwarder: | |
| 53 self._forwarder.Close() | |
| 54 self._forwarder = None | |
| 55 if self._server: | |
| 56 self._server.kill() | |
| 57 self._server = None | |
| 58 if self._devnull: | |
| 59 self._devnull.close() | |
| 60 self._devnull = None | |
| 61 | |
| 62 @property | |
| 63 def url(self): | |
| 64 return self._forwarder.url | |
| 65 | |
| 66 def UrlOf(self, path): | |
| 67 return urlparse.urljoin(self.url, path) | |
| OLD | NEW |