-
Notifications
You must be signed in to change notification settings - Fork 138
/
devtools.py
2457 lines (2363 loc) · 125 KB
/
devtools.py
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2019 WebPageTest LLC.
# Copyright 2017 Google Inc.
# Copyright 2020 Catchpoint Systems Inc.
# Use of this source code is governed by the Polyform Shield 1.0.0 license that can be
# found in the LICENSE.md file.
"""Main entry point for interfacing with Chrome's remote debugging protocol"""
import base64
import gzip
import io
import logging
import multiprocessing
import os
import re
import socket
import struct
import subprocess
import sys
import threading
import time
import uuid
import zipfile
if (sys.version_info >= (3, 0)):
from time import monotonic
from urllib.parse import urlsplit # pylint: disable=import-error
unicode = str
GZIP_TEXT = 'wt'
else:
from monotonic import monotonic
from urlparse import urlsplit # pylint: disable=import-error
GZIP_TEXT = 'w'
try:
import ujson as json
except BaseException:
import json
from ws4py.client.threadedclient import WebSocketClient
class DevTools(object):
"""Interface into Chrome's remote dev tools protocol"""
def __init__(self, options, job, task, use_devtools_video, is_webkit, is_ios):
self.url = "http://localhost:{0:d}/json".format(task['port'])
self.must_exit = False
self.websocket = None
self.options = options
self.job = job
self.task = task
self.is_webkit = is_webkit
self.is_ios = is_ios
self.command_id = 0
self.command_responses = {}
self.pending_body_requests = {}
self.pending_commands = []
self.console_log = []
self.audit_issues = []
self.performance_timing = []
self.workers = []
self.page_loaded = None
self.main_frame = None
self.response_started = False
self.is_navigating = False
self.last_activity = monotonic()
self.dev_tools_file = None
self.trace_file = None
self.trace_enabled = False
self.requests = {}
self.netlog_requests = {}
self.netlog_urls = {}
self.netlog_lock = threading.Lock()
self.request_count = 0
self.response_bodies = {}
self.body_fail_count = 0
self.body_index = 0
self.bodies_zip_file = None
self.nav_error = None
self.nav_error_code = None
self.main_request = None
self.main_request_headers = None
self.start_timestamp = None
self.path_base = None
self.support_path = None
self.video_path = None
self.video_prefix = None
self.recording = False
self.mobile_viewport = None
self.tab_id = None
self.use_devtools_video = use_devtools_video
self.recording_video = False
self.main_thread_blocked = False
self.stylesheets = {}
self.headers = {}
self.execution_contexts = {}
self.execution_context = None
self.trace_parser = None
self.prepare()
self.html_body = False
self.all_bodies = False
self.request_sequence = 0
self.default_target = None
self.dom_tree = None
self.key_definitions = {}
self.wait_interval = 5.0
self.wait_for_script = None
keyfile = os.path.join(os.path.dirname(__file__), 'support', 'keys.json')
try:
with open(keyfile, 'rt') as f_in:
self.key_definitions = json.load(f_in)
except Exception:
logging.exception('Error loading keyboard definitions')
def shutdown(self):
"""The agent is dying NOW"""
self.must_exit = True
def prepare(self):
"""Set up the various paths and states"""
self.requests = {}
self.request_count = 0
self.response_bodies = {}
self.console_log = []
self.audit_issues = []
self.performance_timing = []
self.nav_error = None
self.nav_error_code = None
self.start_timestamp = None
self.path_base = os.path.join(self.task['dir'], self.task['prefix'])
self.support_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "support")
self.video_path = os.path.join(self.task['dir'], self.task['video_subdirectory'])
self.video_prefix = os.path.join(self.video_path, 'ms_')
if not os.path.isdir(self.video_path):
os.makedirs(self.video_path)
self.body_fail_count = 0
self.body_index = 0
if self.bodies_zip_file is not None:
self.bodies_zip_file.close()
self.bodies_zip_file = None
self.dom_tree = None
self.html_body = False
self.all_bodies = False
if 'bodies' in self.job and self.job['bodies']:
self.all_bodies = True
if 'htmlbody' in self.job and self.job['htmlbody']:
self.html_body = True
def start_navigating(self):
"""Indicate that we are about to start a known-navigation"""
self.main_frame = None
self.is_navigating = True
self.response_started = False
def wait_for_available(self, timeout):
"""Wait for the dev tools interface to become available (but don't connect)"""
import requests
self.profile_start('devtools_start')
proxies = {"http": None, "https": None}
ret = False
end_time = monotonic() + timeout
while not ret and monotonic() < end_time and not self.must_exit:
try:
response = requests.get(self.url, timeout=timeout, proxies=proxies)
if len(response.text):
tabs = response.json()
logging.debug("Dev Tools tabs: %s", json.dumps(tabs))
if len(tabs):
for index in range(len(tabs)):
if 'type' in tabs[index] and \
(tabs[index]['type'] == 'page' or tabs[index]['type'] == 'webview') and \
'webSocketDebuggerUrl' in tabs[index] and \
'id' in tabs[index]:
ret = True
logging.debug('Dev tools interface is available')
except Exception as err:
logging.exception("Connect to dev tools Error: %s", err.__str__())
time.sleep(0.5)
self.profile_end('devtools_start')
return ret
def connect(self, timeout):
"""Connect to the browser"""
self.profile_start('connect')
if self.is_webkit and not self.is_ios:
ret = False
end_time = monotonic() + timeout
while not ret and monotonic() < end_time and not self.must_exit:
try:
self.websocket = WebKitGTKInspector()
self.websocket.connect(self.task['port'], timeout)
# Wait to get the targetCreated message
while self.default_target is None and monotonic() < end_time:
self.pump_message()
if self.default_target is not None:
ret = True
except Exception:
logging.exception("Error connecting to webkit inspector")
time.sleep(0.5)
else:
import requests
session = requests.session()
proxies = {"http": None, "https": None}
ret = False
end_time = monotonic() + timeout
while not ret and monotonic() < end_time and not self.must_exit:
try:
response = session.get(self.url, timeout=timeout, proxies=proxies)
if len(response.text):
tabs = response.json()
logging.debug("Dev Tools tabs: %s", json.dumps(tabs))
if len(tabs):
websocket_url = None
for index in range(len(tabs)):
if 'type' in tabs[index]:
if (tabs[index]['type'] == 'page' or tabs[index]['type'] == 'webview') and \
'webSocketDebuggerUrl' in tabs[index] and \
'id' in tabs[index]:
if websocket_url is None:
websocket_url = tabs[index]['webSocketDebuggerUrl']
self.tab_id = tabs[index]['id']
else:
# Close extra tabs
try:
session.get(self.url + '/close/' + tabs[index]['id'], proxies=proxies)
except Exception:
logging.exception('Error closing tabs')
elif 'title' in tabs[index] and 'webSocketDebuggerUrl' in tabs[index]:
if websocket_url is None and tabs[index]['title'] == 'Orange':
websocket_url = tabs[index]['webSocketDebuggerUrl']
if websocket_url is not None:
try:
self.websocket = DevToolsClient(websocket_url)
self.websocket.connect()
self.job['shaper'].set_devtools(self)
ret = True
except Exception as err:
logging.exception("Connect to dev tools websocket Error: %s", err.__str__())
if not ret:
# try connecting to 127.0.0.1 instead of localhost
try:
websocket_url = websocket_url.replace('localhost', '127.0.0.1')
self.websocket = DevToolsClient(websocket_url)
self.websocket.connect()
ret = True
except Exception as err:
logging.exception("Connect to dev tools websocket Error: %s", err.__str__())
else:
time.sleep(0.5)
else:
time.sleep(0.5)
except Exception as err:
logging.debug("Connect to dev tools Error: %s", err.__str__())
time.sleep(0.5)
# Wait for the default target to be created for iOS
if ret and self.is_ios:
while self.default_target is None and monotonic() < end_time and not self.must_exit:
self.pump_message()
self.profile_end('connect')
return ret
def _to_int(self, s):
return int(re.search(r'\d+', str(s)).group())
def enable_shaper(self, target_id=None):
"""Enable the Chromium dev tools traffic shaping"""
if self.job['dtShaper']:
in_Bps = -1
if 'bwIn' in self.job:
in_Bps = (self._to_int(self.job['bwIn']) * 1000) / 8
out_Bps = -1
if 'bwOut' in self.job:
out_Bps = (self._to_int(self.job['bwOut']) * 1000) / 8
rtt = 0
if 'latency' in self.job:
rtt = self._to_int(self.job['latency'])
self.send_command('Network.emulateNetworkConditions', {
'offline': False,
'latency': rtt,
'downloadThroughput': in_Bps,
'uploadThroughput': out_Bps
}, wait=True, target_id=target_id)
def enable_webkit_events(self):
if self.is_webkit:
self.send_command('Inspector.enable', {})
self.send_command('Network.enable', {})
self.send_command('Runtime.enable', {})
self.job['shaper'].apply()
self.enable_shaper()
if self.headers:
self.send_command('Network.setExtraHTTPHeaders', {'headers': self.headers})
if len(self.workers):
for target in self.workers:
self.enable_target(target['targetId'])
if 'user_agent_string' in self.job:
self.send_command('Page.overrideUserAgent', {'value': self.job['user_agent_string']})
if self.task['log_data']:
self.send_command('Console.enable', {})
self.send_command('Timeline.start', {}, wait=True)
self.send_command('Page.enable', {}, wait=True)
def prepare_browser(self):
"""Run any one-time startup preparation before testing starts"""
if self.is_webkit:
self.send_command('Target.setPauseOnStart', {'pauseOnStart': True}, wait=True)
else:
self.send_command('Target.setAutoAttach',
{'autoAttach': True, 'waitForDebuggerOnStart': True})
response = self.send_command('Target.getTargets', {}, wait=True)
if response is not None and 'result' in response and 'targetInfos' in response['result']:
for target in response['result']['targetInfos']:
logging.debug(target)
if 'type' in target and 'targetId' in target:
if target['type'] == 'service_worker':
self.send_command('Target.attachToTarget', {'targetId': target['targetId']},
wait=True)
def close(self, close_tab=True):
"""Close the dev tools connection"""
self.job['shaper'].set_devtools(None)
if self.websocket:
try:
self.websocket.close()
except Exception:
logging.exception('Error closing websocket')
self.websocket = None
if close_tab and self.tab_id is not None:
import requests
proxies = {"http": None, "https": None}
try:
requests.get(self.url + '/close/' + self.tab_id, proxies=proxies)
except Exception:
logging.exception('Error closing tab')
self.tab_id = None
def start_recording(self):
"""Start capturing dev tools, timeline and trace data"""
self.profile_start('prepare_chrome')
self.prepare()
if (self.bodies_zip_file is None and (self.html_body or self.all_bodies)):
self.bodies_zip_file = zipfile.ZipFile(self.path_base + '_bodies.zip', 'w',
zipfile.ZIP_DEFLATED)
self.recording = True
if self.use_devtools_video and self.job['video'] and self.task['log_data']:
self.grab_screenshot(self.video_prefix + '000000.jpg', png=False)
self.flush_pending_messages()
self.send_command('Page.enable', {})
self.send_command('Inspector.enable', {})
self.send_command('Debugger.enable', {})
self.send_command('Debugger.setSkipAllPauses', {'skip': True})
self.send_command('ServiceWorker.enable', {})
self.send_command('DOMSnapshot.enable', {})
inject_file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'support', 'chrome', 'inject.js')
if os.path.isfile(inject_file_path):
with io.open(inject_file_path, 'r', encoding='utf-8') as inject_file:
inject_script = inject_file.read()
self.send_command('Page.addScriptToEvaluateOnNewDocument', {'source': inject_script})
self.enable_webkit_events()
self.enable_target()
if len(self.workers):
for target in self.workers:
self.enable_target(target['targetId'])
if self.task['log_data']:
self.send_command('Security.enable', {})
if 'coverage' in self.job and self.job['coverage']:
self.send_command('DOM.enable', {})
self.send_command('CSS.enable', {})
self.send_command('CSS.startRuleUsageTracking', {})
self.send_command('Profiler.enable', {})
self.send_command('Profiler.setSamplingInterval', {'interval': 100})
self.send_command('Profiler.start', {})
trace_config = {"recordMode": "recordAsMuchAsPossible",
"includedCategories": []}
if 'trace' in self.job and self.job['trace']:
self.job['keep_netlog'] = True
if 'traceCategories' in self.job:
categories = self.job['traceCategories'].split(',')
for category in categories:
if category.find("*") < 0 and category not in trace_config["includedCategories"]:
trace_config["includedCategories"].append(category)
else:
trace_config["includedCategories"] = [
"toplevel",
"blink",
"v8",
"cc",
"gpu",
"blink.net",
"blink.resource",
"disabled-by-default-v8.runtime_stats"
]
else:
self.job['keep_netlog'] = False
if 'netlog' in self.job and self.job['netlog']:
self.job['keep_netlog'] = True
if 'timeline' in self.job and self.job['timeline']:
if self.is_webkit:
from internal.support.trace_parser import Trace
self.trace_parser = Trace()
self.trace_parser.cpu['main_thread'] = '0'
self.trace_parser.threads['0'] = {}
if "blink.console" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("blink.console")
if "devtools.timeline" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("devtools.timeline")
if 'timeline_fps' in self.job and self.job['timeline_fps']:
if "disabled-by-default-devtools.timeline" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-devtools.timeline")
if "disabled-by-default-devtools.timeline.frame" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-devtools.timeline.frame")
if 'profiler' in self.job and self.job['profiler']:
trace_config["enableSampling"] = True
if "disabled-by-default-v8.cpu_profiler" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-v8.cpu_profiler")
if "disabled-by-default-devtools.timeline" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-devtools.timeline")
if "disabled-by-default-devtools.timeline.frame" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-devtools.timeline.frame")
if 'v8rcs' in self.job and self.job['v8rcs']:
if "v8" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("v8")
if "disabled-by-default-v8.runtime_stats" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-v8.runtime_stats")
if self.use_devtools_video and self.job['video']:
if "disabled-by-default-devtools.screenshot" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-devtools.screenshot")
self.recording_video = True
# Add the required trace events
if "rail" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("rail")
if "content" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("content")
self.job['discard_trace_content'] = True
if "loading" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("loading")
if "blink.user_timing" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("blink.user_timing")
if "netlog" not in trace_config["includedCategories"] and not self.job.get('streaming_netlog'):
trace_config["includedCategories"].append("netlog")
if "disabled-by-default-netlog" not in trace_config["includedCategories"] and not self.job.get('streaming_netlog'):
trace_config["includedCategories"].append("disabled-by-default-netlog")
if "blink.resource" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("blink.resource")
if "disabled-by-default-blink.feature_usage" not in trace_config["includedCategories"]:
trace_config["includedCategories"].append("disabled-by-default-blink.feature_usage")
if not self.is_webkit:
self.trace_enabled = True
self.send_command('Tracing.start', {'traceConfig': trace_config}, wait=True)
now = monotonic()
if not self.task['stop_at_onload']:
self.last_activity = now
if self.page_loaded is not None:
self.page_loaded = now
self.profile_end('prepare_chrome')
def stop_capture(self):
"""Do any quick work to stop things that are capturing data"""
if self.must_exit:
return
self.start_collecting_trace()
# Process messages for up to 10 seconds in case we still have some pending async commands
self.wait_for_pending_commands(10)
def stop_recording(self):
"""Stop capturing dev tools, timeline and trace data"""
if self.must_exit:
return
self.profile_start('stop_recording')
if self.task['log_data']:
if 'coverage' in self.job and self.job['coverage']:
try:
coverage = {}
# process the JS coverage
self.send_command('Profiler.stop', {})
response = self.send_command('Profiler.getBestEffortCoverage', {}, wait=True, timeout=30)
if 'result' in response and 'result' in response['result']:
for script in response['result']['result']:
if 'url' in script and script['url'] and 'functions' in script:
if script['url'] not in coverage:
coverage[script['url']] = {}
if 'JS' not in coverage[script['url']]:
coverage[script['url']]['JS'] = []
for function in script['functions']:
if 'ranges' in function:
for chunk in function['ranges']:
coverage[script['url']]['JS'].append({
'startOffset': chunk['startOffset'],
'endOffset': chunk['endOffset'],
'count': chunk['count'],
'used': True if chunk['count'] else False
})
self.send_command('Profiler.disable', {})
# Process the css coverage
response = self.send_command('CSS.stopRuleUsageTracking', {}, wait=True, timeout=30)
if 'result' in response and 'ruleUsage' in response['result']:
rule_usage = response['result']['ruleUsage']
for rule in rule_usage:
if 'styleSheetId' in rule and rule['styleSheetId'] in self.stylesheets:
sheet_id = rule['styleSheetId']
url = self.stylesheets[sheet_id]
if url not in coverage:
coverage[url] = {}
if 'CSS' not in coverage[url]:
coverage[url]['CSS'] = []
coverage[url]['CSS'].append({
'startOffset': rule['startOffset'],
'endOffset': rule['endOffset'],
'used': rule['used']
})
if coverage:
summary = {}
categories = ['JS', 'CSS']
for url in coverage:
for category in categories:
if category in coverage[url]:
total_bytes = 0
used_bytes = 0
for chunk in coverage[url][category]:
range_bytes = chunk['endOffset'] - chunk['startOffset']
if range_bytes > 0:
total_bytes += range_bytes
if chunk['used']:
used_bytes += range_bytes
used_pct = 100.0
if total_bytes > 0:
used_pct = float((used_bytes * 10000) / total_bytes) / 100.0
if url not in summary:
summary[url] = {}
summary[url]['{0}_bytes'.format(category)] = total_bytes
summary[url]['{0}_bytes_used'.format(category)] = used_bytes
summary[url]['{0}_percent_used'.format(category)] = used_pct
path = self.path_base + '_coverage.json.gz'
with gzip.open(path, GZIP_TEXT, 7) as f_out:
json.dump(summary, f_out)
self.send_command('CSS.disable', {})
self.send_command('DOM.disable', {})
except Exception:
logging.exception('Error stopping devtools')
self.recording = False
# Process messages for up to 10 seconds in case we still have some pending async commands
self.wait_for_pending_commands(10)
self.flush_pending_messages()
if self.task['log_data']:
self.send_command('Security.disable', {})
self.send_command('Audits.disable', {})
self.send_command('Log.disable', {})
self.send_command('Log.stopViolationsReport', {})
self.send_command('Console.disable', {})
self.send_command('Timeline.stop', {})
self.get_response_bodies()
if self.bodies_zip_file is not None:
self.bodies_zip_file.close()
self.bodies_zip_file = None
self.send_command('Network.disable', {})
if len(self.workers):
for target in self.workers:
self.send_command('Network.disable', {}, target_id=target['targetId'])
self.send_command('ServiceWorker.disable', {})
if self.dev_tools_file is not None:
self.dev_tools_file.write("\n]")
self.dev_tools_file.close()
self.dev_tools_file = None
# Save the console logs
log_file = self.path_base + '_console_log.json.gz'
with gzip.open(log_file, GZIP_TEXT, 7) as f_out:
json.dump(self.console_log, f_out)
self.send_command('Inspector.disable', {})
self.send_command('Page.disable', {})
self.send_command('Debugger.disable', {})
# Add the audit issues to the page data
if len(self.audit_issues):
self.task['page_data']['audit_issues'] = self.audit_issues
# Add the list of execution contexts
contexts = []
for id in self.execution_contexts:
contexts.append(self.execution_contexts[id])
if len(contexts):
self.task['page_data']['execution_contexts'] = contexts
# Process the timeline data
if self.trace_parser is not None:
start = monotonic()
logging.debug("Processing the trace timeline events")
self.trace_parser.ProcessTimelineEvents()
self.trace_parser.WriteCPUSlices(self.path_base + '_timeline_cpu.json.gz')
self.trace_parser.WriteScriptTimings(self.path_base + '_script_timing.json.gz')
self.trace_parser.WriteInteractive(self.path_base + '_interactive.json.gz')
self.trace_parser.WriteLongTasks(self.path_base + '_long_tasks.json.gz')
elapsed = monotonic() - start
logging.debug("Done processing the trace events: %0.3fs", elapsed)
self.trace_parser = None
self.profile_end('stop_recording')
def wait_for_pending_commands(self, timeout):
"""Wait for any queued commands"""
end_time = monotonic() + timeout
while monotonic() < end_time and (len(self.pending_body_requests) or len(self.pending_commands))and not self.must_exit:
try:
self.pump_message()
except Exception:
pass
def pump_message(self):
""" Run the message pump """
try:
raw = self.websocket.get_message(1)
try:
if raw is not None and len(raw):
if raw.find("Timeline.eventRecorded") == -1 and raw.find("Target.dispatchMessageFromTarget") == -1 and raw.find("Target.receivedMessageFromTarget") == -1:
logging.debug('<- %s', raw[:200])
msg = json.loads(raw)
self.process_message(msg)
except Exception:
logging.exception('Error processing websocket message')
except Exception:
pass
def start_collecting_trace(self):
"""Kick off the trace processing asynchronously"""
if self.trace_enabled and not self.must_exit:
keep_timeline = True
if 'discard_timeline' in self.job and self.job['discard_timeline']:
keep_timeline = False
video_prefix = self.video_prefix if self.recording_video else None
self.snapshot_dom()
self.websocket.start_processing_trace(self.path_base, video_prefix,
self.options, self.job, self.task,
self.start_timestamp, keep_timeline, self.dom_tree, self.performance_timing)
self.send_command('Tracing.end', {})
def snapshot_dom(self):
"""Grab a snapshot of the DOM to use for processing element locations"""
if self.dom_tree is not None:
return self.dom_tree
if self.must_exit:
return
try:
self.profile_start('snapshot_dom')
styles = ['background-image']
response = self.send_command('DOMSnapshot.captureSnapshot', {'computedStyles': styles, 'includePaintOrder': False, 'includeDOMRects': True}, wait=True)
if response and 'result' in response:
self.dom_tree = response['result']
self.dom_tree['style_names'] = styles
self.profile_end('snapshot_dom')
except Exception:
logging.exception("Error capturing DOM snapshot")
return self.dom_tree
def collect_trace(self):
"""Stop tracing and collect the results"""
if self.must_exit:
return
if self.trace_enabled:
self.trace_enabled = False
self.profile_start('collect_trace')
start = monotonic()
try:
# Keep pumping messages until we get tracingComplete or
# we get a gap of 30 seconds between messages
if self.websocket:
logging.info('Collecting trace events')
no_message_count = 0
while not self.websocket.trace_done and no_message_count < 30 and monotonic() - start < 600:
try:
raw = self.websocket.get_message(1)
try:
if raw is not None and len(raw):
no_message_count = 0
else:
no_message_count += 1
except Exception:
no_message_count += 1
logging.exception('Error processing devtools message')
except Exception:
no_message_count += 1
time.sleep(1)
self.websocket.stop_processing_trace(self.job)
except Exception:
logging.exception('Error processing trace events')
elapsed = monotonic() - start
self.profile_end('collect_trace')
logging.debug("Time to collect trace: %0.3f sec", elapsed)
self.recording_video = False
def get_response_body(self, request_id, wait):
"""Retrieve and store the given response body (if necessary)"""
if request_id not in self.response_bodies and self.body_fail_count < 3 and not self.is_ios and not self.must_exit:
request = self.get_request(request_id, True)
# See if we have a netlog-based response body
found = False
if request is not None and 'url' in request:
try:
path = os.path.join(self.task['dir'], 'netlog_bodies')
with self.netlog_lock:
if request['url'] in self.netlog_urls:
for netlog_id in self.netlog_urls[request['url']]:
if netlog_id in self.netlog_requests and 'body_claimed' not in self.netlog_requests[netlog_id]:
body_file_path = os.path.join(path, netlog_id)
if os.path.exists(body_file_path):
self.netlog_requests[netlog_id]['body_claimed'] = True
found = True
logging.debug('Matched netlog response body %s to %s for %s', netlog_id, request_id, request['url'])
# For text-based responses, ignore any utf-8 decode errors so we can err on the side of getting more text bodies
errors=None
try:
if 'response_headers' in self.netlog_requests[netlog_id]:
headers = self.extract_headers(self.netlog_requests[netlog_id]['response_headers'])
content_type = self.get_header_value(headers, 'Content-Type')
if content_type is not None:
content_type = content_type.lower()
text_types = ['application/json',
'application/xhtml+xml',
'application/xml',
'application/ld+json',
'application/javascript']
if content_type.startswith('text/') or content_type in text_types:
errors = 'ignore'
except Exception:
logging.exception('Error processing content type for response body')
self.process_response_body(request_id, None, body_file_path, errors)
if not found and len(self.netlog_requests):
logging.debug('Unable to match netlog response body for %s', request['url'])
except Exception:
logging.exception('Error matching netlog response body')
if not found and request is not None and 'status' in request and request['status'] == 200 and \
'response_headers' in request and 'url' in request and request['url'].startswith('http'):
content_length = self.get_header_value(request['response_headers'], 'Content-Length')
if content_length is not None:
content_length = int(re.search(r'\d+', str(content_length)).group())
elif 'transfer_size' in request:
content_length = request['transfer_size']
else:
content_length = 0
logging.debug('Getting body for %s (%d) - %s', request_id,
content_length, request['url'])
path = os.path.join(self.task['dir'], 'bodies')
if not os.path.isdir(path):
os.makedirs(path)
body_file_path = os.path.join(path, request_id)
if not os.path.exists(body_file_path):
# Only grab bodies needed for optimization checks
# or if we are saving full bodies
need_body = True
content_type = self.get_header_value(request['response_headers'], 'Content-Type')
if content_type is not None:
content_type = content_type.lower()
# Ignore video files over 10MB
if content_type[:6] == 'video/' and content_length > 10000000:
need_body = False
optimization_checks_disabled = bool('noopt' in self.job and self.job['noopt'])
if optimization_checks_disabled and self.bodies_zip_file is None:
need_body = False
if need_body:
target_id = None
if request_id in self.requests and 'targetId' in self.requests[request_id]:
target_id = self.requests[request_id]['targetId']
response = self.send_command("Network.getResponseBody", {'requestId': request_id}, wait=wait, target_id=target_id)
if wait:
self.process_response_body(request_id, response)
def process_response_body(self, request_id, response, netlog_body_file=None, errors=None):
try:
request = self.get_request(request_id, True)
path = os.path.join(self.task['dir'], 'bodies')
if not os.path.isdir(path):
os.makedirs(path)
body_file_path = os.path.join(path, request_id)
is_text = False
body = None
if netlog_body_file is not None:
try:
with open(netlog_body_file, 'r', encoding='utf-8', errors=errors) as f:
body = f.read()
body = body.encode('utf-8')
is_text = True
except Exception:
pass
if body is None:
with open(netlog_body_file, 'rb') as f:
body = f.read()
elif not os.path.exists(body_file_path):
is_text = False
if request is not None and 'status' in request and request['status'] == 200 and 'response_headers' in request:
content_type = self.get_header_value(request['response_headers'], 'Content-Type')
if content_type is not None:
content_type = content_type.lower()
if content_type.startswith('text/') or \
content_type.find('javascript') >= 0 or \
content_type.find('json') >= 0 or \
content_type.find('/svg+xml'):
is_text = True
if response is None:
self.body_fail_count += 1
logging.warning('No response to body request for request %s',
request_id)
elif 'result' not in response or \
'body' not in response['result']:
self.body_fail_count = 0
logging.warning('Missing response body for request %s',
request_id)
elif len(response['result']['body']):
try:
self.body_fail_count = 0
# Write the raw body to a file (all bodies)
if 'base64Encoded' in response['result'] and \
response['result']['base64Encoded']:
body = base64.b64decode(response['result']['body'])
is_text = False
else:
body = response['result']['body'].encode('utf-8')
is_text = True
except Exception:
logging.exception('Exception retrieving body')
else:
self.body_fail_count = 0
self.response_bodies[request_id] = response['result']['body']
# Store the actual body for processing
if body is not None and not os.path.exists(body_file_path):
if 'request_headers' in request:
fetch_dest = self.get_header_value(request['request_headers'], 'Sec-Fetch-Dest')
if fetch_dest is not None and fetch_dest in ['audio', 'audioworklet', 'font', 'image', 'object', 'track', 'video']:
is_text = False
# Add text bodies to the zip archive
store_body = self.all_bodies
if self.html_body and request_id == self.main_request:
store_body = True
if store_body and self.bodies_zip_file is not None and is_text:
self.body_index += 1
name = '{0:03d}-{1}-body.txt'.format(self.body_index, request_id)
self.bodies_zip_file.writestr(name, body)
logging.debug('%s: Stored body in zip', request_id)
logging.debug('%s: Body length: %d', request_id, len(body))
self.response_bodies[request_id] = body
with open(body_file_path, 'wb') as body_file:
body_file.write(body)
except Exception:
logging.exception('Error processing response body')
def get_response_bodies(self):
"""Retrieve all of the response bodies for the requests that we know about"""
if self.must_exit:
return
self.profile_start('get_response_bodies')
requests = self.get_requests(True)
if (self.task['error'] is None or self.task['soft_error']) and requests:
for request_id in requests:
self.get_response_body(request_id, True)
self.profile_end('get_response_bodies')
def get_request(self, request_id, include_bodies):
"""Get the given request details if it is a real request"""
request = None
if request_id in self.requests and 'fromNet' in self.requests[request_id] and self.requests[request_id]['fromNet']:
events = self.requests[request_id]
request = {'id': request_id}
if 'sequence' not in events:
self.request_sequence += 1
events['sequence'] = self.request_sequence
request['sequence'] = events['sequence']
# See if we have a body
if include_bodies:
body_path = os.path.join(self.task['dir'], 'bodies')
body_file_path = os.path.join(body_path, request_id)
if os.path.isfile(body_file_path):
request['body'] = body_file_path
if request_id in self.response_bodies:
request['response_body'] = self.response_bodies[request_id]
# Get the headers from responseReceived
if 'response' in events:
response = events['response'][-1]
if 'response' in response:
fields = ['url', 'status', 'connectionId', 'protocol', 'connectionReused',
'fromServiceWorker', 'timing', 'fromDiskCache', 'remoteIPAddress',
'remotePort', 'securityState', 'securityDetails', 'fromPrefetchCache']
for field in fields:
if field in response['response']:
request[field] = response['response'][field]
if 'headers' in response['response']:
request['response_headers'] = response['response']['headers']
if 'requestHeaders' in response['response']:
request['request_headers'] = response['response']['requestHeaders']
if 'requestExtra' in events:
extra = events['requestExtra']
if 'headers' in extra:
request['request_headers'] = extra['headers']
if 'responseExtra' in events:
extra = events['responseExtra']
if 'headers' in extra:
request['response_headers'] = extra['headers']
# Fill in any missing details from the requestWillBeSent event
if 'request' in events:
req = events['request'][-1]
fields = ['initiator', 'documentURL', 'timestamp', 'frameId', 'hasUserGesture',
'type', 'wallTime']
for field in fields:
if field in req and field not in request:
request[field] = req[field]
if 'request' in req:
if 'url' not in request and 'url' in req['request']:
request['url'] = req['request']['url']
if 'request_headers' not in request and 'headers' in req['request']:
request['request_headers'] = req['request']['headers']
if 'initialPriority' in req['request']:
request['initialPriority'] = req['request']['initialPriority']
# See if we have final priority information
if 'priority' in events:
priority_data = events['priority'][-1]
if 'newPriority' in priority_data:
request['priority'] = priority_data['newPriority']
if 'priority' not in request and 'initialPriority' in request:
request['priority'] = request['initialPriority']
# Get the response length from the data events
if 'finished' in events and 'encodedDataLength' in events['finished']:
request['transfer_size'] = events['finished']['encodedDataLength']
elif 'data' in events:
transfer_size = 0
for data in events['data']:
if 'encodedDataLength' in data:
transfer_size += data['encodedDataLength']
elif 'dataLength' in data:
transfer_size += data['dataLength']
request['transfer_size'] = transfer_size
return request
def extract_headers(self, raw_headers):
"""Convert flat headers into a keyed dictionary"""
headers = {}
for header in raw_headers:
key_len = header.find(':', 1)
if key_len >= 0:
key = header[:key_len].strip(' :')
value = header[key_len + 1:].strip()
if key in headers:
headers[key] += ',' + value
else:
headers[key] = value
return headers
def get_requests(self, include_bodies):
"""Get a dictionary of all of the requests and the details (headers, body file)"""
requests = None
if self.requests:
for request_id in self.requests:
request = self.get_request(request_id, include_bodies)
if request is not None:
if requests is None:
requests = {}
requests[request_id] = request
# Patch-in any netlog requests that were not seen through dev tools
# This is only used for optimization checks and custom metrics, not the
# actual waterfall.
with self.netlog_lock:
try:
path = os.path.join(self.task['dir'], 'netlog_bodies')
for netlog_id in self.netlog_requests:
netlog_request = self.netlog_requests[netlog_id]
if 'url' in netlog_request:
url = netlog_request['url']
found = False
for request_id in requests:
request = requests[request_id]
if 'url' in request and request['url'] == url:
found = True
if not found:
self.request_sequence += 1
request = {'id': netlog_id, 'sequence': self.request_sequence, 'url': url}
if 'request_headers' in netlog_request:
request['request_headers'] = self.extract_headers(netlog_request['request_headers'])
if 'response_headers' in netlog_request:
request['response_headers'] = self.extract_headers(netlog_request['response_headers'])
if 'initial_priority' in netlog_request:
request['initialPriority'] = netlog_request['initial_priority']
request['priority'] = netlog_request['initial_priority']
if 'priority' in netlog_request:
request['priority'] = netlog_request['priority']
body_file_path = os.path.join(path, netlog_id)
if os.path.exists(body_file_path):
request['body'] = body_file_path
body = None
with open(body_file_path, 'rb') as f:
body = f.read()
if body is not None and len(body):
request['response_body'] = body
requests[netlog_id] = request
except Exception:
logging.exception('Error adding netlog requests')
return requests
def flush_pending_messages(self):
"""Clear out any pending websocket messages"""
if self.websocket:
try:
while True:
raw = self.websocket.get_message(0)
try:
if raw is not None and len(raw):
if self.recording:
if raw.find("Timeline.eventRecorded") == -1 and raw.find("Target.dispatchMessageFromTarget") == -1 and raw.find("Target.receivedMessageFromTarget") == -1:
logging.debug('<- %s', raw[:200])
msg = json.loads(raw)
self.process_message(msg)
if not raw:
break
except Exception:
logging.exception('Error flushing websocket messages')