OLD | NEW |
(Empty) | |
| 1 # Copyright 2014 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 |
| 5 import socket |
| 6 import subprocess |
| 7 import logging |
| 8 import os.path |
| 9 |
| 10 class SkyServer(object): |
| 11 def __init__(self, paths, port, configuration, root): |
| 12 self.paths = paths |
| 13 self.port = port |
| 14 self.configuration = configuration |
| 15 self.root = root |
| 16 self.server = None |
| 17 |
| 18 @staticmethod |
| 19 def _port_in_use(port): |
| 20 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 21 return sock.connect_ex(('localhost', port)) == 0 |
| 22 |
| 23 @staticmethod |
| 24 def _download_server_if_necessary(paths): |
| 25 subprocess.call(os.path.join(paths.sky_tools_directory, |
| 26 'download_sky_server')) |
| 27 return os.path.join(paths.src_root, 'out', 'downloads', 'sky_server') |
| 28 |
| 29 def __enter__(self): |
| 30 if self._port_in_use(self.port): |
| 31 logging.warn( |
| 32 'Port %s already in use, assuming custom sky_server started.' % |
| 33 self.port) |
| 34 return |
| 35 |
| 36 server_path = self._download_server_if_necessary(self.paths) |
| 37 server_command = [ |
| 38 server_path, |
| 39 '-t', self.configuration, |
| 40 self.root, |
| 41 str(self.port), |
| 42 ] |
| 43 self.server = subprocess.Popen(server_command) |
| 44 |
| 45 def __exit__(self, exc_type, exc_value, traceback): |
| 46 if self.server: |
| 47 self.server.terminate() |
| 48 |
| 49 def path_as_url(self, path): |
| 50 return self.url_for_path(self.port, self.root, path) |
| 51 |
| 52 @staticmethod |
| 53 def url_for_path(port, root, path): |
| 54 relative_path = os.path.relpath(path, root) |
| 55 return 'http://localhost:%s/%s' % (port, relative_path) |
OLD | NEW |