-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathwebpagetest.py
More file actions
1964 lines (1922 loc) · 99.2 KB
/
webpagetest.py
File metadata and controls
1964 lines (1922 loc) · 99.2 KB
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 WebPageTest server"""
import base64
from datetime import datetime
import glob
import gzip
import hashlib
import logging
import multiprocessing
import os
import platform
import random
import re
import shutil
import socket
import string
import subprocess
import sys
import threading
import time
import zipfile
import psutil
from internal import os_util
if (sys.version_info >= (3, 0)):
from time import monotonic
from urllib.parse import quote_plus # pylint: disable=import-error
from urllib.parse import urlsplit # pylint: disable=import-error
GZIP_READ_TEXT = 'rt'
GZIP_TEXT = 'wt'
else:
from monotonic import monotonic
from urllib import quote_plus # pylint: disable=import-error,no-name-in-module
from urlparse import urlsplit # pylint: disable=import-error
GZIP_READ_TEXT = 'r'
GZIP_TEXT = 'w'
try:
import ujson as json
except BaseException:
import json
"""
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
"""
DEFAULT_JPEG_QUALITY = 30
class WebPageTest(object):
"""Controller for interfacing with the WebPageTest server"""
# pylint: disable=E0611
def __init__(self, options, workdir):
import requests
self.fetch_queue = multiprocessing.JoinableQueue()
self.fetch_result_queue = multiprocessing.JoinableQueue()
self.job = None
self.raw_job = None
self.first_failure = None
self.is_rebooting = False
self.is_dead = False
self.health_check_server = None
self.metadata_blocked = False
self.session = requests.Session()
self.session.headers.update({'User-Agent': 'wptagent'})
self.extension_session = requests.Session()
self.extension_session.headers.update({'User-Agent': 'wptagent'})
self.options = options
self.last_test_id = None
self.fps = options.fps
self.test_run_count = 0
self.log_formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d - %(message)s",
datefmt="%H:%M:%S")
self.log_handler = None
# Configurable options
self.work_servers = []
self.needs_zip = []
self.url = ''
if options.server is not None:
self.work_servers_str = options.server
if self.work_servers_str == 'www.webpagetest.org':
self.work_servers_str = 'http://www.webpagetest.org/'
self.work_servers = self.work_servers_str.split(',')
self.url = str(self.work_servers[0])
self.location = ''
self.test_locations = []
if options.location is not None:
self.test_locations = options.location.split(',')
self.location = str(self.test_locations[0])
self.wpthost = None
self.license_pinged = False
self.key = options.key
self.scheduler = options.scheduler
self.scheduler_salt = options.schedulersalt
self.scheduler_nodes = []
if options.schedulernode is not None:
self.scheduler_nodes = options.schedulernode.split(',')
self.scheduler_node = None
self.last_diagnostics = None
self.time_limit = 120
self.cpu_scale_multiplier = None
self.pc_name = os_util.pc_name() if options.name is None else options.name
self.auth_name = options.username
self.auth_password = options.password if options.password is not None else ''
self.validate_server_certificate = options.validcertificate
self.instance_id = None
self.zone = None
self.cpu_pct = None
# Get the screen resolution if we're in desktop mode
self.screen_width = None
self.screen_height = None
if not self.options.android and not self.options.iOS:
if self.options.xvfb:
self.screen_width = 1920
self.screen_height = 1200
elif platform.system() == 'Windows':
try:
from win32api import GetSystemMetrics # pylint: disable=import-error
self.screen_width = GetSystemMetrics(0)
self.screen_height = GetSystemMetrics(1)
except Exception:
logging.exception('Error getting screen resolution')
elif platform.system() == 'Darwin':
try:
from AppKit import NSScreen # pylint: disable=import-error
self.screen_width = int(NSScreen.screens()[0].frame().size.width)
self.screen_height = int(NSScreen.screens()[0].frame().size.height)
except Exception:
logging.exception('Error getting screen resolution')
elif platform.system() == 'Linux':
out = subprocess.check_output(['xprop','-notype','-len','16','-root','_NET_DESKTOP_GEOMETRY'], universal_newlines=True)
if out is not None:
logging.debug(out)
parts = out.split('=', 1)
if len(parts) == 2:
dimensions = parts[1].split(',', 1)
if len(dimensions) == 2:
self.screen_width = int(dimensions[0].strip())
self.screen_height = int(dimensions[1].strip())
# Grab the list of configured DNS servers
self.dns_servers = None
try:
from dns import resolver
dns_resolver = resolver.Resolver()
self.dns_servers = '-'.join(dns_resolver.nameservers)
except Exception:
pass
# See if we have to load dynamic config options
if self.options.ec2:
self.load_from_ec2()
elif self.options.gce:
self.load_from_gce()
self.block_metadata()
# Set the session authentication options
if self.auth_name is not None:
self.session.auth = (self.auth_name, self.auth_password)
self.session.verify = self.validate_server_certificate
if options.cert is not None:
if options.certkey is not None:
self.session.cert = (options.cert, options.certkey)
else:
self.session.cert = options.cert
# Set up the temporary directories
self.workdir = os.path.join(workdir, self.pc_name)
self.persistent_dir = self.workdir + '.data'
self.profile_dir = os.path.join(self.workdir, 'browser')
if os.path.isdir(self.workdir):
try:
shutil.rmtree(self.workdir)
except Exception:
pass
# If we are running in a git clone, grab the date of the last
# commit as the version
self.version = '23.07'
try:
directory = os.path.abspath(os.path.dirname(__file__))
if (sys.version_info >= (3, 0)):
out = subprocess.check_output('git log -1 --format=%cd --date=raw', shell=True, cwd=directory, encoding='UTF-8')
else:
out = subprocess.check_output('git log -1 --format=%cd --date=raw', shell=True, cwd=directory)
if out is not None:
matches = re.search(r'^(\d+)', out)
if matches:
timestamp = int(matches.group(1))
git_date = datetime.utcfromtimestamp(timestamp)
self.version = git_date.strftime('%y%m%d.%H%M%S')
except Exception:
pass
# Load the discovered browser margins
self.margins = {}
margins_file = os.path.join(self.persistent_dir, 'margins.json')
if os.path.isfile(margins_file):
with open(margins_file, 'r') as f_in:
self.margins = json.load(f_in)
# Load any locally-defined custom metrics from {agent root}/custom/metrics/*.js
self.custom_metrics = {}
self.load_local_custom_metrics()
# Warn if no server is configured
if len(self.work_servers) == 0 and len(self.scheduler_nodes) == 0 and not self.options.pubsub:
logging.warning("No WebPageTest server configured. Please specify --server option (e.g., --server http://your-server.com/work/) or --scheduler option.")
# pylint: enable=E0611
def load_local_custom_metrics(self):
metrics_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'custom', 'metrics')
if (os.path.isdir(metrics_dir)):
files = glob.glob(metrics_dir + '/*.js')
for file in files:
try:
with open(file, 'rt') as f:
metric_value = f.read()
if metric_value:
metric_name = os.path.basename(file)[:-3]
self.custom_metrics[metric_name] = metric_value
logging.debug('Loaded custom metric %s from %s', metric_name, file)
except Exception:
pass
def benchmark_cpu(self):
"""Benchmark the CPU for mobile emulation"""
self.cpu_scale_multiplier = 1.0
if not self.options.android and not self.options.iOS:
import hashlib
logging.debug('Starting CPU benchmark')
hash_val = hashlib.sha256()
with open(__file__, 'rb') as f_in:
hash_data = f_in.read(4096)
start = monotonic()
# 106k iterations takes ~1 second on the reference machine
iteration = 0
while iteration < 106000:
hash_val.update(hash_data)
iteration += 1
elapsed = monotonic() - start
self.cpu_scale_multiplier = min(1.0 / elapsed, float(self.options.maxcpuscale))
logging.debug('CPU Benchmark elapsed time: %0.3f, multiplier: %0.3f',
elapsed, self.cpu_scale_multiplier)
# Get the median scale value from the last 9 benchmarks on this machine
try:
cpu_scale = []
scale_file = os.path.join(self.persistent_dir, 'cpu_scale.json')
if os.path.isfile(scale_file):
with open(scale_file, 'r') as f_in:
cpu_scale = json.load(f_in)
if type(cpu_scale) is list:
if len(cpu_scale) >= 9:
cpu_scale.pop(0)
cpu_scale.append(self.cpu_scale_multiplier)
if not os.path.isdir(self.persistent_dir):
os.makedirs(self.persistent_dir)
with open(scale_file, 'w') as f_out:
json.dump(cpu_scale, f_out)
cpu_scale.sort()
median_index = int((len(cpu_scale) - 1) / 2)
self.cpu_scale_multiplier = cpu_scale[median_index]
logging.debug('CPU Benchmark selected multiplier: %0.3f at index %d of %d values', self.cpu_scale_multiplier, median_index, len(cpu_scale))
except Exception:
logging.exception('Error processing benchmark history')
def get_persistent_dir(self):
"""Return the path to the persistent cache directory"""
return self.persistent_dir
def load_from_ec2(self):
"""Load config settings from EC2 user data"""
import requests
session = requests.Session()
proxies = {"http": None, "https": None}
# The Windows AMI's use static routes which are not copied across regions.
# This sets them up before we attempt to access the metadata
if platform.system() == "Windows":
from .os_util import run_elevated
directory = os.path.abspath(os.path.dirname(__file__))
ec2_script = os.path.join(directory, 'support', 'ec2', 'win_routes.ps1')
run_elevated('powershell.exe', ec2_script)
# Make sure the route blocking isn't configured on Linux
if platform.system() == "Linux":
subprocess.call(['sudo', 'route', 'delete', '169.254.169.254'])
ok = False
while not ok:
try:
response = session.get('http://169.254.169.254/latest/user-data', timeout=30, proxies=proxies)
if len(response.text):
self.parse_user_data(response.text)
ok = True
except Exception:
pass
if not ok:
time.sleep(10)
ok = False
while not ok:
try:
response = session.get('http://169.254.169.254/latest/meta-data/instance-id', timeout=30, proxies=proxies)
if len(response.text):
self.instance_id = response.text.strip()
ok = True
except Exception:
pass
if not ok:
time.sleep(10)
ok = False
while not ok:
try:
response = session.get('http://169.254.169.254/latest/meta-data/placement/availability-zone', timeout=30, proxies=proxies)
if len(response.text):
self.zone = response.text.strip()
if not len(self.test_locations):
self.location = self.zone[:-1]
if platform.system() == "Linux":
self.location += '-linux'
self.test_locations = [self.location]
ok = True
except Exception:
pass
if not ok:
time.sleep(10)
# Block access to the metadata server
if platform.system() == "Linux":
subprocess.call(['sudo', 'route', 'add', '169.254.169.254', 'gw', '127.0.0.1', 'lo'])
self.metadata_blocked = True
def load_from_gce(self):
"""Load config settings from GCE user data"""
import requests
session = requests.Session()
proxies = {"http": None, "https": None}
ok = False
while not ok:
try:
response = session.get(
'http://metadata.google.internal/computeMetadata/v1/instance/attributes/wpt_data',
headers={'Metadata-Flavor': 'Google'},
timeout=30, proxies=proxies)
if len(response.text):
self.parse_user_data(response.text)
ok = True
except Exception:
pass
if not ok:
time.sleep(10)
ok = False
while not ok:
try:
response = session.get('http://metadata.google.internal/computeMetadata/v1/instance/id',
headers={'Metadata-Flavor': 'Google'},
timeout=30, proxies=proxies)
if len(response.text):
self.instance_id = response.text.strip()
ok = True
except Exception:
pass
if not ok:
time.sleep(10)
if not len(self.test_locations):
ok = False
while not ok:
try:
response = session.get('http://metadata.google.internal/computeMetadata/v1/instance/zone',
headers={'Metadata-Flavor': 'Google'},
timeout=30, proxies=proxies)
if len(response.text):
zone = response.text.strip()
position = zone.rfind('/')
if position > -1:
zone = zone[position + 1:]
self.zone = zone
self.location = 'gce-' + self.zone[:-2]
if platform.system() == "Linux":
self.location += '-linux'
self.test_locations = [self.location]
ok = True
except Exception:
pass
if not ok:
time.sleep(10)
def block_metadata(self):
"""Block access to the metadata service if we are on EC2 or Azure"""
if not self.metadata_blocked:
import requests
needs_block = False
session = requests.Session()
proxies = {"http": None, "https": None}
try:
response = session.get('http://169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance', timeout=10, proxies=proxies)
if response.status_code == 200:
needs_block = True
else:
response = session.get('http://169.254.169.254/metadata/instance?api-version=2017-04-02', timeout=10, proxies=proxies)
if response.status_code == 200:
needs_block = True
except Exception:
pass
if needs_block:
subprocess.call(['sudo', 'route', 'add', '169.254.169.254', 'gw', '127.0.0.1', 'lo'])
self.metadata_blocked = True
def parse_user_data(self, user_data):
"""Parse the provided user data and extract the config info"""
logging.debug("User Data: %s", user_data)
options = user_data.split()
for option in options:
try:
parts = option.split('=', 1)
if len(parts) == 2:
key = parts[0].strip()
value = parts[1].strip()
logging.debug('Setting config option "%s" to "%s"', key, value)
if key == 'wpt_server':
server = ''
if re.search(r'^https?://', value):
server = value
if value.endswith('/'):
server += 'work/'
else:
server += '/work/'
else:
server = 'http://{0}/work/'.format(value)
self.work_servers_str = str(server)
self.work_servers = self.work_servers_str.split(',')
self.url = str(self.work_servers[0])
if key == 'wpt_url':
self.work_servers_str = str(value)
self.work_servers = self.work_servers_str.split(',')
self.url = str(self.work_servers[0])
elif key == 'wpt_loc' or key == 'wpt_location':
if value is not None:
self.test_locations = value.split(',')
self.location = str(self.test_locations[0])
if key == 'wpt_location':
append = []
for loc in self.test_locations:
append.append('{0}_wptdriver'.format(loc))
if len(append):
self.test_locations.extend(append)
elif key == 'wpt_key':
self.key = value
elif key == 'wpt_timeout':
self.time_limit = int(re.search(r'\d+', str(value)).group())
elif key == 'wpt_username':
self.auth_name = value
elif key == 'wpt_password':
self.auth_password = value
elif key == 'wpt_validcertificate' and value == '1':
self.validate_server_certificate = True
elif key == 'validcertificate' and value == '1':
self.validate_server_certificate = True
elif key == 'wpt_scheduler':
self.scheduler = value
elif key == 'wpt_scheduler_salt':
self.scheduler_salt = value
elif key == 'wpt_scheduler_node':
self.scheduler_nodes = value.split(',')
elif key == 'wpt_fps':
self.fps = int(re.search(r'\d+', str(value)).group())
elif key == 'fps':
self.fps = int(re.search(r'\d+', str(value)).group())
except Exception:
logging.exception('Error parsing metadata')
# pylint: disable=E1101
def get_uptime_minutes(self):
"""Get the system uptime in seconds"""
boot_time = None
try:
boot_time = psutil.boot_time()
except Exception:
pass
if boot_time is None:
try:
boot_time = psutil.get_boot_time()
except Exception:
pass
if boot_time is None:
try:
boot_time = psutil.BOOT_TIME
except Exception:
pass
uptime = None
if boot_time is not None and boot_time > 0:
uptime = int((time.time() - boot_time) / 60)
if uptime is not None and uptime < 0:
uptime = 0
return uptime
# pylint: enable=E1101
def reboot(self):
self.is_rebooting = True
if platform.system() == 'Windows':
subprocess.call(['shutdown', '/r', '/f'])
else:
subprocess.call(['sudo', 'reboot'])
def get_cpid(self, node = None):
"""Get a salt-signed header for the scheduler"""
entity = node if node else self.scheduler_node
hash_src = entity.upper() + ';' + datetime.now().strftime('%Y%m') + self.scheduler_salt
hash_string = base64.b64encode(hashlib.sha1(hash_src.encode('ascii')).digest()).decode('ascii')
cpid_header = 'm;' + entity + ';' + hash_string
return cpid_header
def process_job_json(self, test_json):
"""Process the JSON of a test into a job file"""
if self.cpu_scale_multiplier is None:
self.benchmark_cpu()
job = test_json
self.raw_job = dict(test_json)
if job is not None:
try:
logging.debug("Job: %s", json.dumps(job))
# set some default options
job['agent_version'] = self.version
if 'imageQuality' not in job:
job['imageQuality'] = DEFAULT_JPEG_QUALITY
if 'pngScreenShot' not in job:
job['pngScreenShot'] = 0
if 'fvonly' not in job:
job['fvonly'] = not self.options.testrv
if 'width' not in job:
job['width'] = 1366
if 'height' not in job:
job['height'] = 768
if 'browser_width' in job:
job['width'] = job['browser_width']
if 'browser_height' in job:
job['height'] = job['browser_height']
if 'timeout' not in job:
job['timeout'] = self.time_limit
if 'noscript' not in job:
job['noscript'] = 0
if 'type' not in job:
job['type'] = ''
if job['type'] == 'traceroute':
job['fvonly'] = 1
if 'fps' not in job:
job['fps'] = self.fps
if 'warmup' not in job:
job['warmup'] = 0
if 'wappalyzer' not in job:
job['wappalyzer'] = 1
if 'axe' not in job:
job['axe'] = 1
if 'axe_categories' not in job:
job['axe_categories'] = 'wcag2a,wcag2aa'
if job['type'] == 'lighthouse':
job['fvonly'] = 1
job['lighthouse'] = 1
job['keep_lighthouse_trace'] = bool('lighthouseTrace' in job and job['lighthouseTrace'])
job['keep_lighthouse_screenshots'] = bool(job['lighthouseScreenshots']) if 'lighthouseScreenshots' in job else False
job['lighthouse_throttle'] = bool('lighthouseThrottle' in job and job['lighthouseThrottle'])
job['lighthouse_config'] = str(job['lighthouseConfig']) if 'lighthouseConfig' in job else False
if 'video' not in job:
job['video'] = bool('Capture Video' not in job or job['Capture Video'])
job['keepvideo'] = bool('keepvideo' in job and job['keepvideo'])
job['dtShaper'] = bool('dtShaper' in job and job['dtShaper'])
job['disable_video'] = bool(not job['video'] and 'disable_video' in job and job['disable_video'])
job['atomic'] = bool('atomic' in job and job['atomic'])
job['interface'] = None
job['persistent_dir'] = self.persistent_dir
if 'throttle_cpu' in job:
throttle = float(re.search(r'\d+\.?\d*', str(job['throttle_cpu'])).group())
if 'bypass_cpu_normalization' not in job or not job['bypass_cpu_normalization']:
throttle *= self.cpu_scale_multiplier
job['throttle_cpu_requested'] = job['throttle_cpu']
job['throttle_cpu'] = throttle
if 'work_servers' in job and job['work_servers'] != self.work_servers_str:
self.work_servers_str = job['work_servers']
self.work_servers = self.work_servers_str.split(',')
logging.debug("Servers changed to: %s", self.work_servers_str)
if 'wpthost' in job:
self.wpthost = job['wpthost']
job['started'] = time.time()
if 'testinfo' in job:
job['testinfo']['started'] = job['started']
# Add the security insights custom metrics locally if requested
if 'securityInsights' in job:
js_directory = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'js')
if 'customMetrics' not in job:
job['customMetrics'] = {}
if 'jsLibsVulns' not in job['customMetrics']:
with open(os.path.join(js_directory, 'jsLibsVulns.js'), 'rt') as f_in:
job['customMetrics']['jsLibsVulns'] = f_in.read()
if 'securityHeaders' not in job['customMetrics']:
with open(os.path.join(js_directory, 'securityHeaders.js'), 'rt') as f_in:
job['customMetrics']['securityHeaders'] = f_in.read()
if 'browser' not in job:
job['browser'] = 'Chrome'
if 'runs' not in job:
job['runs'] = 1
if 'timeline' not in job:
job['timeline'] = 1
if self.options.location is not None:
job['location'] = self.options.location
if self.scheduler_node is not None and 'saas_test_id' in job:
job['saas_node_id'] = self.scheduler_node
# For CLI tests, write out the raw job file
if self.options.testurl or self.options.testspec or 'saas_test_id' in job:
if not os.path.isdir(self.workdir):
os.makedirs(self.workdir)
job_path = os.path.join(self.workdir, 'job.json')
logging.debug('Job Path: {}'.format(job_path))
with open(job_path, 'wt') as f_out:
json.dump(job, f_out)
self.needs_zip.append({'path': job_path, 'name': 'job.json'})
if 'testinfo' in job:
job['testinfo']['started'] = job['started']
# Add the non-serializable members
if self.health_check_server is not None:
job['health_check_server'] = self.health_check_server
# add any locally-defined custom metrics (server versions override locals with the same name)
if self.custom_metrics:
if 'customMetrics' not in job:
job['customMetrics'] = {}
for name in self.custom_metrics:
if name not in job['customMetrics']:
job['customMetrics'][name] = self.custom_metrics[name]
except Exception:
logging.exception("Error processing job json")
self.job = job
return job
def get_test(self, browsers):
"""Get a job from the server"""
if self.is_rebooting or self.is_dead or self.options.pubsub:
return
import requests
proxies = {"http": None, "https": None}
from .os_util import get_free_disk_space
if len(self.work_servers) == 0 and len(self.scheduler_nodes) == 0:
logging.critical("No work servers or scheduler nodes configured. Please specify --server or --scheduler options.")
return None
job = None
self.raw_job = None
scheduler_nodes = list(self.scheduler_nodes)
if len(scheduler_nodes) > 0:
random.shuffle(scheduler_nodes)
self.scheduler_node = str(scheduler_nodes.pop(0)).strip(', ')
servers = list(self.work_servers)
if len(servers) >0 :
random.shuffle(servers)
self.url = str(servers.pop(0))
locations = list(self.test_locations) if len(self.test_locations) > 1 else [self.location]
if len(locations) > 0:
random.shuffle(locations)
location = str(locations.pop(0))
# Shuffle the list order
if len(self.test_locations) > 1:
self.test_locations.append(str(self.test_locations.pop(0)))
count = 0
retry = True
while count < 3 and retry:
retry = False
count += 1
url = self.url + "getwork.php?f=json&shards=1&reboot=1&servers=1&testinfo=1"
url += "&location=" + quote_plus(location)
url += "&pc=" + quote_plus(self.pc_name)
if self.key is not None:
url += "&key=" + quote_plus(self.key)
if self.instance_id is not None:
url += "&ec2=" + quote_plus(self.instance_id)
if self.zone is not None:
url += "&ec2zone=" + quote_plus(self.zone)
if self.options.android:
url += '&apk=1'
url += '&version={0}'.format(self.version)
if self.screen_width is not None:
url += '&screenwidth={0:d}'.format(self.screen_width)
if self.screen_height is not None:
url += '&screenheight={0:d}'.format(self.screen_height)
if self.dns_servers is not None:
url += '&dns=' + quote_plus(self.dns_servers)
free_disk = get_free_disk_space()
url += '&freedisk={0:0.3f}'.format(free_disk)
uptime = self.get_uptime_minutes()
if uptime is not None:
url += '&upminutes={0:d}'.format(uptime)
if 'collectversion' in self.options and \
self.options.collectversion:
versions = []
for name in browsers.keys():
if 'version' in browsers[name]:
versions.append('{0}:{1}'.format(name, \
browsers[name]['version']))
browser_versions = ','.join(versions)
url += '&browsers=' + quote_plus(browser_versions)
try:
if self.scheduler and self.scheduler_salt and self.scheduler_node:
url = self.scheduler + 'hawkscheduleserver/wpt-dequeue.ashx?machine={}'.format(quote_plus(self.pc_name))
logging.info("Checking for work for node %s: %s", self.scheduler_node, url)
response = self.session.get(url, timeout=10, proxies=proxies, headers={'CPID': self.get_cpid(self.scheduler_node)})
response_text = response.text if len(response.text) else None
else:
logging.info("Checking for work: %s", url)
response = self.session.get(url, timeout=10, proxies=proxies)
response_text = response.text if len(response.text) else None
if self.options.alive:
with open(self.options.alive, 'a'):
os.utime(self.options.alive, None)
if self.health_check_server is not None:
self.health_check_server.healthy()
self.first_failure = None
if response_text is not None:
if response_text == 'Reboot':
self.reboot()
return None
elif response_text.startswith('Servers:') or response_text.startswith('Scheduler:'):
for line in response_text.splitlines():
line = line.strip()
if line.startswith('Servers:'):
servers_str = line[8:]
if servers_str and servers_str != self.work_servers_str:
self.work_servers_str = servers_str
self.work_servers = self.work_servers_str.split(',')
logging.debug("Servers changed to: %s", self.work_servers_str)
elif line.startswith('Scheduler:'):
scheduler_parts = line[10:].split(' ')
if scheduler_parts and len(scheduler_parts) == 3:
self.scheduler = scheduler_parts[0].strip()
self.scheduler_salt = scheduler_parts[1].strip()
self.scheduler_node = scheduler_parts[2].strip()
self.scheduler_nodes = [self.scheduler_node]
retry = True
logging.debug("Scheduler configured: '%s' Salt: '%s' Node: %s", self.scheduler, self.scheduler_salt, self.scheduler_node)
job = self.process_job_json(json.loads(response_text))
# Store the raw job info in case we need to re-queue it
if job is not None and 'Test ID' in job and 'signature' in job and 'work_server' in job:
self.raw_job = {
'id': job['Test ID'],
'signature': job['signature'],
'work_server': job['work_server'],
'location': location,
'payload': str(response.text)
}
if 'jobID' in job:
self.raw_job['jobID'] = job['jobID']
# Rotate through the list of locations
if job is None and len(locations) > 0 and not self.scheduler:
location = str(locations.pop(0))
count -= 1
retry = True
if job is None and len(scheduler_nodes) > 0 and self.scheduler:
self.scheduler_node = str(scheduler_nodes.pop(0)).strip(', ')
count -= 1
retry = True
except requests.exceptions.RequestException as err:
error_msg = str(err)
if hasattr(err, 'response') and err.response is not None:
error_msg = "{} (Status: {})".format(error_msg, err.response.status_code)
logging.critical("Get Work Error connecting to %s: %s", url, error_msg)
now = monotonic()
if self.first_failure is None:
self.first_failure = now
# Reboot if we haven't been able to reach the server for 30 minutes
elapsed = now - self.first_failure
if elapsed > 1800:
self.reboot()
time.sleep(0.1)
except Exception as e:
logging.exception("Unexpected error in get_test: %s", str(e))
# Rotate through the list of servers
if not retry and job is None and len(servers) > 0 and not self.scheduler:
self.url = str(servers.pop(0))
locations = list(self.test_locations) if len(self.test_locations) > 1 else [self.location]
random.shuffle(locations)
location = str(locations.pop(0))
count -= 1
retry = True
return job
def notify_test_started(self, job):
"""
Tell the server that we have started the test.
Used when the queueing isn't handled directly by the server.
"""
if 'work_server' in job and 'Test ID' in job:
try:
url = job['work_server'] + 'started.php?id=' + quote_plus(job['Test ID'])
proxies = {"http": None, "https": None}
self.session.get(url, timeout=30, proxies=proxies)
except Exception:
logging.exception("Unexpected error in notify_test_started")
def get_task(self, job):
"""Create a task object for the next test run or return None if the job is done"""
if self.is_dead:
return None
# Do the one-time setup at the beginning of a job
if 'current_state' not in job:
if not self.needs_zip:
self.needs_zip = []
if 'work_server' in job and 'jobID' in job:
self.notify_test_started(job)
self.install_extensions()
self.report_diagnostics()
task = None
if self.log_handler is not None:
try:
self.log_handler.close()
logging.getLogger().removeHandler(self.log_handler)
self.log_handler = None
except Exception:
pass
if 'current_state' not in job or not job['current_state']['done']:
if 'run' in job:
# Sharded test, running one run only
if 'current_state' not in job:
job['current_state'] = {"run": int(re.search(r'\d+', str(job['run'])).group()),
"repeat_view": False,
"done": False}
elif not job['current_state']['repeat_view'] and \
('fvonly' not in job or not job['fvonly']):
job['current_state']['repeat_view'] = True
else:
return task
elif 'current_state' not in job:
job['current_state'] = {"run": 1, "repeat_view": False, "done": False}
elif not job['current_state']['repeat_view'] and \
('fvonly' not in job or not job['fvonly']):
job['current_state']['repeat_view'] = True
else:
if job['warmup'] > 0:
job['warmup'] -= 1
else:
job['current_state']['run'] += 1
job['current_state']['repeat_view'] = False
if job['current_state']['run'] <= job['runs']:
if 'Test ID' in job:
test_id = job['Test ID']
else:
test_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))
run = job['current_state']['run']
profile_dir = '{0}.{1}.{2:d}'.format(self.profile_dir, test_id, run)
task = {'id': test_id,
'run': run,
'cached': 1 if job['current_state']['repeat_view'] else 0,
'done': False,
'profile': profile_dir,
'error': None,
'soft_error': False,
'log_data': True,
'activity_time': 3,
'combine_steps': False,
'video_directories': [],
'page_data': {'tester': self.pc_name, 'start_epoch': time.time()},
'navigated': False,
'page_result': None,
'script_step_count': 1}
# Increase the activity timeout for high-latency tests
if 'latency' in job:
try:
factor = int(min(job['latency'] / 100, 4))
if factor > 1:
task['activity_time'] *= factor
except Exception:
pass
# Set up the task configuration options
task['port'] = 9222 + (self.test_run_count % 500)
task['task_prefix'] = "{0:d}".format(run)
if task['cached']:
task['task_prefix'] += "_Cached"
task['prefix'] = task['task_prefix']
short_id = "{0}.{1}.{2}".format(task['id'], run, task['cached'])
task['dir'] = os.path.join(self.workdir, short_id)
if 'test_shared_dir' not in job:
job['test_shared_dir'] = os.path.join(self.workdir, task['id'])
task['task_video_prefix'] = 'video_{0:d}'.format(run)
if task['cached']:
task['task_video_prefix'] += "_cached"
task['video_subdirectory'] = task['task_video_prefix']
if os.path.isdir(task['dir']):
shutil.rmtree(task['dir'])
os.makedirs(task['dir'])
if not os.path.isdir(job['test_shared_dir']):
os.makedirs(job['test_shared_dir'])
if not os.path.isdir(profile_dir):
os.makedirs(profile_dir)
if job['current_state']['run'] == job['runs'] or 'run' in job:
if job['current_state']['repeat_view']:
job['current_state']['done'] = True
task['done'] = True
elif 'fvonly' in job and job['fvonly']:
job['current_state']['done'] = True
task['done'] = True
if 'debug' in job and job['debug']:
task['debug_log'] = os.path.join(task['dir'], task['prefix'] + '_debug.log')
try:
self.log_handler = logging.FileHandler(task['debug_log'])
self.log_handler.setFormatter(self.log_formatter)
logging.getLogger().addHandler(self.log_handler)
except Exception:
pass
if 'keepua' not in job or not job['keepua']:
task['AppendUA'] = 'PTST'
if 'UAModifier' in job:
task['AppendUA'] = job['UAModifier']
task['AppendUA'] += '/{0}'.format(self.version)
if 'AppendUA' in job:
if 'AppendUA' in task:
task['AppendUA'] += ' ' + job['AppendUA']
else:
task['AppendUA'] = job['AppendUA']
if 'AppendUA' in task:
task['AppendUA'] = task['AppendUA'].replace('%TESTID%', test_id)\
.replace('%RUN%', str(run))\
.replace('%CACHED%', str(task['cached']))\
.replace('%VERSION%', self.version)
task['block'] = []
if 'block' in job:
block_list = job['block'].split()
for block in block_list:
block = block.strip()
if len(block):
task['block'].append(block)
if 'blockDomains' in job:
if 'host_rules' not in task:
task['host_rules'] = []
if 'block_domains' not in task:
task['block_domains'] = []
if 'dns_override' not in task:
task['dns_override'] = []
domains = re.split('[, ]', job['blockDomains'])
for domain in domains:
domain = domain.strip()
if len(domain) and domain.find('"') == -1:
task['block_domains'].append(domain)
task['host_rules'].append('"MAP {0} 127.0.0.1"'.format(domain))
if re.match(r'^[a-zA-Z0-9\-\.]+$', domain):
task['dns_override'].append([domain, "0.0.0.0"])
# Load the crypto mining block list
crypto_list = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'support', 'adblock', 'nocoin', 'hosts.txt')
if os.path.exists(crypto_list):
with open(crypto_list, 'rt') as f_in:
if 'dns_override' not in task:
task['dns_override'] = []
for line in f_in:
if line.startswith('0.0.0.0'):
domain = line[8:].strip()
task['dns_override'].append([domain, "0.0.0.0"])
self.build_script(job, task)
task['width'] = job['width']
task['height'] = job['height']
if 'mobile' in job and job['mobile']:
if 'browser' in job and job['browser'] in self.margins:
task['width'] = \
job['width'] + max(self.margins[job['browser']]['width'], 0)
task['height'] = \
job['height'] + max(self.margins[job['browser']]['height'], 0)
else:
task['width'] = job['width'] + 20
task['height'] = job['height'] + 120
if 'time' in job:
task['minimumTestSeconds'] = job['time']
task['time_limit'] = job['timeout']
task['test_time_limit'] = task['time_limit'] * task['script_step_count']
task['stop_at_onload'] = bool('web10' in job and job['web10'])
task['run_start_time'] = monotonic()
if 'profile_data' in job:
task['profile_data'] = {
'lock': threading.Lock(),
'start': monotonic(),
'test':{
'id': task['id'],
'run': task['run'],
'cached': task['cached'],
's': 0}}
# Keep the full resolution video frames if the browser window is smaller than 600px
if 'thumbsize' not in job and (task['width'] < 600 or task['height'] < 600):
job['fullSizeVideo'] = 1
# Pass-through the SaaS fields
if 'saas_test_id' in job:
task['page_data']['saas_test_id'] = job['saas_test_id']
if 'saas_node_id' in job:
task['page_data']['saas_node_id'] = job['saas_node_id']
if 'saas_report_window_start' in job:
task['page_data']['saas_report_window_start'] = job['saas_report_window_start']
if 'saas_report_window_end' in job:
task['page_data']['saas_report_window_end'] = job['saas_report_window_end']
if 'saas_device_type_id' in job:
task['page_data']['saas_device_type_id'] = job['saas_device_type_id']
else:
task['page_data']['saas_device_type_id'] = 0
self.test_run_count += 1
if task is None and self.job is not None:
self.upload_test_result()
if 'reboot' in job and job['reboot']:
self.reboot()
return task
def running_another_test(self, task):
"""Increment the port for Chrome and the run count"""
task['port'] = 9222 + (self.test_run_count % 500)
self.test_run_count += 1