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.
11 from telemetry
.core
import exceptions
14 class DevToolsClientConnectionError(exceptions
.Error
):
18 class DevToolsClientUrlError(DevToolsClientConnectionError
):
22 class DevToolsHttp(object):
23 """A helper class to send and parse DevTools HTTP requests.
25 This class maintains a persistent http connection to Chrome devtools.
26 Ideally, owners of instances of this class should call Disconnect() before
27 disposing of the instance. Otherwise, the connection will not be closed until
28 the instance is garbage collected.
31 def __init__(self
, devtools_port
):
32 self
._devtools
_port
= devtools_port
38 def _Connect(self
, timeout
):
39 """Attempts to establish a connection to Chrome devtools."""
42 host_port
= '127.0.0.1:%i' % self
._devtools
_port
43 self
._conn
= httplib
.HTTPConnection(host_port
, timeout
=timeout
)
44 except (socket
.error
, httplib
.HTTPException
) as e
:
45 raise DevToolsClientConnectionError
, (e
,), sys
.exc_info()[2]
48 """Closes the HTTP connection."""
54 except (socket
.error
, httplib
.HTTPException
) as e
:
55 raise DevToolsClientConnectionError
, (e
,), sys
.exc_info()[2]
59 def Request(self
, path
, timeout
=30):
60 """Sends a request to Chrome devtools.
62 This method lazily creates an HTTP connection, if one does not already
66 path: The DevTools URL path, without the /json/ prefix.
67 timeout: Timeout defaults to 30 seconds.
70 DevToolsClientConnectionError: If the connection fails.
75 self
._Connect
(timeout
)
79 endpoint
+= '/' + path
81 self
._conn
.sock
.settimeout(timeout
)
83 self
._conn
.timeout
= timeout
86 # By default, httplib avoids going through the default system proxy.
87 self
._conn
.request('GET', endpoint
)
88 response
= self
._conn
.getresponse()
89 return response
.read()
90 except (socket
.error
, httplib
.HTTPException
) as e
:
92 if isinstance(e
, socket
.error
) and e
.errno
== errno
.ECONNREFUSED
:
93 raise DevToolsClientUrlError
, (e
,), sys
.exc_info()[2]
94 raise DevToolsClientConnectionError
, (e
,), sys
.exc_info()[2]
96 def RequestJson(self
, path
, timeout
=30):
97 """Sends a request and parse the response as JSON.
100 path: The DevTools URL path, without the /json/ prefix.
101 timeout: Timeout defaults to 30 seconds.
104 DevToolsClientConnectionError: If the connection fails.
105 ValueError: If the response is not a valid JSON.
107 return json
.loads(self
.Request(path
, timeout
))