https://bugs.webkit.org/show_bug.cgi?id=144038
[WebKit-https.git] / Tools / Scripts / webkitpy / benchmark_runner / http_server_driver / simple_http_server_driver.py
1 #!/usr/bin/env python
2
3 import logging
4 import os
5 import re
6 import socket
7 import subprocess
8 import time
9
10 from http_server_driver import HTTPServerDriver
11
12
13 _log = logging.getLogger(__name__)
14
15
16 class SimpleHTTPServerDriver(HTTPServerDriver):
17
18     """This class depends on unix environment, need to be modified to achieve crossplatform compability
19     """
20
21     def __init__(self):
22         self.serverProcess = None
23         self.serverPort = 0
24         # FIXME: This may not be reliable.
25         _log.info('Finding the IP address of current machine')
26         try:
27             self.ip = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][0]
28             _log.info('IP of current machine is: %s' % self.ip)
29         except:
30             _log.error('Cannot get the ip address of current machine')
31             raise
32
33     def serve(self, webroot):
34         oldWorkingDirectory = os.getcwd()
35         os.chdir(os.path.dirname(os.path.abspath(__file__)))
36         _log.info('Lauchning an http server')
37         self.serverProcess = subprocess.Popen(['/usr/bin/python', 'http_server/twisted_http_server.py', webroot], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
38         os.chdir(oldWorkingDirectory)
39         maxAttempt = 5
40         interval = 0.5
41         _log.info('Start to fetching the port number of the http server')
42         try:
43             import psutil
44             for attempt in xrange(maxAttempt):
45                 try:
46                     self.serverPort = psutil.Process(self.serverProcess.pid).connections()[0][3][1]
47                     if self.serverPort:
48                         _log.info('HTTP Server is serving at port: %d', self.serverPort)
49                         break
50                 except IndexError:
51                     pass
52                 _log.info('Server port is not found this time, retry after %f seconds' % interval)
53                 time.sleep(interval)
54                 interval *= 2
55         except ImportError:
56             try:
57                 for attempt in xrange(maxAttempt):
58                     try:
59                         p = subprocess.Popen(' '.join(['/usr/sbin/lsof', '-a', '-iTCP', '-sTCP:LISTEN', '-p', str(self.serverProcess.pid)]), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
60                         self.serverPort = int(re.findall('TCP \*:(\d+) \(LISTEN\)', p.communicate()[0])[0])
61                         if self.serverPort:
62                             _log.info('HTTP Server is serving at port: %d', self.serverPort)
63                             break
64                     # Raising exception means the server is not ready to server, try later
65                     except ValueError:
66                         pass
67                     except IndexError:
68                         pass
69                     _log.info('Server port is not found this time, retry after %f seconds' % interval)
70                     time.sleep(interval)
71                     interval *= 2
72             except:
73                 raise Exception("Server may not be serving")
74
75     def baseUrl(self):
76         return "http://%s:%d" % (self.ip, self.serverPort)
77
78     def fetchResult(self):
79         return self.serverProcess.communicate()[0]