1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
|
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import contextlib
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import time
_SRC_DIR = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(os.path.join(_SRC_DIR, 'third_party', 'catapult', 'devil'))
from devil.android import device_utils
from devil.android import flag_changer
from devil.android import forwarder
from devil.android.sdk import intent
sys.path.append(os.path.join(_SRC_DIR, 'build', 'android'))
from pylib import constants
sys.path.append(os.path.join(_SRC_DIR, 'tools', 'perf'))
from chrome_telemetry_build import chromium_config
sys.path.append(chromium_config.GetTelemetryDir())
from telemetry.internal.util import webpagereplay
sys.path.append(os.path.join(_SRC_DIR, 'third_party', 'webpagereplay'))
import adb_install_cert
import certutils
import chrome_setup
import devtools_monitor
import options
OPTIONS = options.OPTIONS
class DeviceSetupException(Exception):
def __init__(self, msg):
super(DeviceSetupException, self).__init__(msg)
logging.error(msg)
def GetFirstDevice():
"""Returns the first connected device.
Raises:
DeviceSetupException if there is no such device.
"""
devices = device_utils.DeviceUtils.HealthyDevices()
if not devices:
raise DeviceSetupException('No devices found')
return devices[0]
@contextlib.contextmanager
def FlagReplacer(device, command_line_path, new_flags):
"""Replaces chrome flags in a context, restores them afterwards.
Args:
device: Device to target, from DeviceUtils. Can be None, in which case this
context manager is a no-op.
command_line_path: Full path to the command-line file.
new_flags: Flags to replace.
"""
# If we're logging requests from a local desktop chrome instance there is no
# device.
if not device:
yield
return
changer = flag_changer.FlagChanger(device, command_line_path)
changer.ReplaceFlags(new_flags)
try:
yield
finally:
changer.Restore()
@contextlib.contextmanager
def ForwardPort(device, local, remote):
"""Forwards a local port to a remote one on a device in a context."""
# If we're logging requests from a local desktop chrome instance there is no
# device.
if not device:
yield
return
device.adb.Forward(local, remote)
try:
yield
finally:
device.adb.ForwardRemove(local)
# Deprecated
def _SetUpDevice(device, package_info):
"""Enables root and closes Chrome on a device."""
device.EnableRoot()
device.KillAll(package_info.package, quiet=True)
@contextlib.contextmanager
def WprHost(device, wpr_archive_path, record=False,
network_condition_name=None,
disable_script_injection=False):
"""Launches web page replay host.
Args:
device: Android device.
wpr_archive_path: host sided WPR archive's path.
network_condition_name: Network condition name available in
chrome_setup.NETWORK_CONDITIONS.
record: Enables or disables WPR archive recording.
Returns:
Additional flags list that may be used for chromium to load web page through
the running web page replay host.
"""
assert device
if wpr_archive_path == None:
assert not record, 'WPR cannot record without a specified archive.'
assert not network_condition_name, ('WPR cannot emulate network condition' +
' without a specified archive.')
yield []
return
wpr_server_args = ['--use_closest_match']
if record:
wpr_server_args.append('--record')
if os.path.exists(wpr_archive_path):
os.remove(wpr_archive_path)
else:
assert os.path.exists(wpr_archive_path)
if network_condition_name:
condition = chrome_setup.NETWORK_CONDITIONS[network_condition_name]
if record:
logging.warning('WPR network condition is ignored when recording.')
else:
wpr_server_args.extend([
'--down', chrome_setup.BandwidthToString(condition['download']),
'--up', chrome_setup.BandwidthToString(condition['upload']),
'--delay_ms', str(condition['latency']),
'--shaping_type', 'proxy'])
if disable_script_injection:
# Remove default WPR injected scripts like deterministic.js which
# overrides Math.random.
wpr_server_args.extend(['--inject_scripts', ''])
# Deploy certification authority to the device.
temp_certificate_dir = tempfile.mkdtemp()
wpr_ca_cert_path = os.path.join(temp_certificate_dir, 'testca.pem')
certutils.write_dummy_ca_cert(*certutils.generate_dummy_ca_cert(),
cert_path=wpr_ca_cert_path)
device_cert_util = adb_install_cert.AndroidCertInstaller(
device.adb.GetDeviceSerial(), None, wpr_ca_cert_path)
device_cert_util.install_cert(overwrite_cert=True)
wpr_server_args.extend(['--should_generate_certs',
'--https_root_ca_cert_path=' + wpr_ca_cert_path])
# Set up WPR server and device forwarder.
wpr_server = webpagereplay.ReplayServer(wpr_archive_path,
'127.0.0.1', 0, 0, None, wpr_server_args)
ports = wpr_server.StartServer()[:-1]
host_http_port = ports[0]
host_https_port = ports[1]
forwarder.Forwarder.Map([(0, host_http_port), (0, host_https_port)], device)
device_http_port = forwarder.Forwarder.DevicePortForHostPort(host_http_port)
device_https_port = forwarder.Forwarder.DevicePortForHostPort(host_https_port)
try:
yield [
'--host-resolver-rules="MAP * 127.0.0.1,EXCLUDE localhost"',
'--testing-fixed-http-port={}'.format(device_http_port),
'--testing-fixed-https-port={}'.format(device_https_port)]
finally:
forwarder.Forwarder.UnmapDevicePort(device_http_port, device)
forwarder.Forwarder.UnmapDevicePort(device_https_port, device)
wpr_server.StopServer()
# Remove certification authority from the device.
device_cert_util.remove_cert()
shutil.rmtree(temp_certificate_dir)
# Deprecated
@contextlib.contextmanager
def _DevToolsConnectionOnDevice(device, flags):
"""Returns a DevToolsConnection context manager for a given device.
Args:
device: Device to connect to.
flags: ([str]) List of flags.
Returns:
A DevToolsConnection context manager.
"""
package_info = OPTIONS.ChromePackage()
command_line_path = '/data/local/chrome-command-line'
_SetUpDevice(device, package_info)
with FlagReplacer(device, command_line_path, flags):
start_intent = intent.Intent(
package=package_info.package, activity=package_info.activity,
data='about:blank')
device.StartActivity(start_intent, blocking=True)
time.sleep(2)
with ForwardPort(device, 'tcp:%d' % OPTIONS.devtools_port,
'localabstract:chrome_devtools_remote'):
yield devtools_monitor.DevToolsConnection(
OPTIONS.devtools_hostname, OPTIONS.devtools_port)
# Deprecated, use *Controller.
def DeviceConnection(device, additional_flags=None):
"""Context for starting recording on a device.
Sets up and restores any device and tracing appropriately
Args:
device: Android device, or None for a local run (in which case chrome needs
to have been started with --remote-debugging-port=XXX).
additional_flags: Additional chromium arguments.
Returns:
A context manager type which evaluates to a DevToolsConnection.
"""
new_flags = ['--disable-fre',
'--enable-test-events',
'--remote-debugging-port=%d' % OPTIONS.devtools_port]
if OPTIONS.no_sandbox:
new_flags.append('--no-sandbox')
if additional_flags != None:
new_flags.extend(additional_flags)
if device:
return _DevToolsConnectionOnDevice(device, new_flags)
else:
return chrome_setup.DevToolsConnectionForLocalBinary(new_flags)
|