Skip to content

Commit a6a7b82

Browse files
authored
Merge pull request #667 from catchpoint/firefox_parser_fix
Fix Firefox log parser
2 parents 3e9509c + 9172c6b commit a6a7b82

File tree

3 files changed

+73
-36
lines changed

3 files changed

+73
-36
lines changed

internal/firefox.py

Lines changed: 51 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
import json
3232
from .desktop_browser import DesktopBrowser
3333

34+
def _get_location_uri(accuracy, lat, lng) -> str:
35+
return f'data:application/json, {{ "status":"OK", "accuracy":{accuracy}, "location":{{ "lat":{lat}, "lng":{lng} }} }}'
3436

3537
class Firefox(DesktopBrowser):
3638
"""Firefox"""
@@ -140,26 +142,47 @@ def start_firefox(self, job, task):
140142
return
141143
from selenium import webdriver # pylint: disable=import-error
142144

143-
capabilities = webdriver.DesiredCapabilities.FIREFOX.copy()
144-
if 'ignoreSSL' in job and job['ignoreSSL']:
145-
capabilities['acceptInsecureCerts'] = True
146-
else:
147-
capabilities['acceptInsecureCerts'] = False
145+
if webdriver.__version__ >= "4.12":
146+
service_args = ["--marionette-port", "2828"]
147+
service = webdriver.FirefoxService(service_args=service_args, log_output=os.environ["MOZ_LOG_FILE"])
148148

149-
capabilities['moz:firefoxOptions'] = {
150-
'binary': self.path,
151-
'args': ['-profile', task['profile']],
152-
'prefs': self.prepare_prefs(),
153-
"log": {"level": "error"},
154-
'env': {
155-
"MOZ_LOG_FILE": os.environ["MOZ_LOG_FILE"],
156-
"MOZ_LOG": os.environ["MOZ_LOG"]
157-
}
158-
}
159-
service_args = ["--marionette-port", "2828"]
149+
options = webdriver.FirefoxOptions()
150+
options.binary_location = self.path
151+
options.add_argument('--profile')
152+
options.add_argument(f'{task["profile"]}')
153+
options.log.level = 'error'
154+
options.prefs = self.prepare_prefs()
155+
156+
capabilities = webdriver.DesiredCapabilities.FIREFOX.copy()
157+
if 'ignoreSSL' in job and job['ignoreSSL']:
158+
capabilities['acceptInsecureCerts'] = True
159+
else:
160+
capabilities['acceptInsecureCerts'] = False
161+
162+
for key, value in capabilities.items():
163+
options.set_capability(key, value)
164+
self.driver = webdriver.Firefox(options=options, service=service)
165+
elif webdriver.__version__ <= "4.9":
166+
capabilities = webdriver.DesiredCapabilities.FIREFOX.copy()
167+
if 'ignoreSSL' in job and job['ignoreSSL']:
168+
capabilities['acceptInsecureCerts'] = True
169+
else:
170+
capabilities['acceptInsecureCerts'] = False
160171

161-
self.driver = webdriver.Firefox(desired_capabilities=capabilities, service_args=service_args)
162-
logging.debug(self.driver.capabilities)
172+
capabilities['moz:firefoxOptions'] = {
173+
'binary': self.path,
174+
'args': ['-profile', task['profile']],
175+
'prefs': self.prepare_prefs(),
176+
"log": {"level": "error"},
177+
'env': {
178+
"MOZ_LOG_FILE": os.environ["MOZ_LOG_FILE"],
179+
"MOZ_LOG": os.environ["MOZ_LOG"]
180+
}
181+
}
182+
service_args = ["--marionette-port", "2828"]
183+
self.driver = webdriver.Firefox(desired_capabilities=capabilities, service_args=service_args)
184+
else:
185+
raise Exception("Unsupported selenium version %s", webdriver.__version__)
163186

164187
self.driver.set_page_load_timeout(task['time_limit'])
165188
if 'browserVersion' in self.driver.capabilities:
@@ -208,17 +231,13 @@ def launch(self, job, task):
208231
ua_string += ' ' + task['AppendUA']
209232
modified = True
210233
if modified:
211-
logging.debug(ua_string)
212234
self.driver_set_pref('general.useragent.override', ua_string)
213235
# Location
214236
if 'lat' in self.job and 'lng' in self.job:
215237
try:
216238
lat = float(str(self.job['lat']))
217239
lng = float(str(self.job['lng']))
218-
location_uri = 'data:application/json,{{'\
219-
'"status":"OK","accuracy":10.0,'\
220-
'"location":{{"lat":{0:f},"lng":{1:f}}}'\
221-
'}}'.format(lat, lng)
240+
location_uri = _get_location_uri(10, lat, lng)
222241
logging.debug('Setting location: %s', location_uri)
223242
self.driver_set_pref('geo.wifi.uri', location_uri)
224243
except Exception:
@@ -292,6 +311,8 @@ def close_browser(self, job, task):
292311
if platform.system() == "Linux":
293312
subprocess.call(['killall', '-9', 'firefox'])
294313
subprocess.call(['killall', '-9', 'firefox-trunk'])
314+
subprocess.call(['killall', '-9', 'firefox-nightly'])
315+
subprocess.call(['killall', '-9', 'firefox-esr'])
295316
os.environ["MOZ_LOG_FILE"] = ''
296317
os.environ["MOZ_LOG"] = ''
297318

@@ -326,7 +347,7 @@ def run_axe(self, task):
326347
script += "'" + "', '".join(axe_cats) + "'"
327348
script += ']}).then(results=>{return results;});'
328349
except Exception as err:
329-
logging.exception("Exception running Axe: %s", err.__str__())
350+
logging.exception("Exception running Axe: %s", err)
330351
if self.must_exit_now:
331352
return
332353
completed = False
@@ -349,7 +370,7 @@ def run_axe(self, task):
349370
axe_info['incomplete'] = axe_results['incomplete']
350371
task['page_data']['axe'] = axe_info
351372
except Exception as err:
352-
logging.exception("Exception running Axe: %s", err.__str__())
373+
logging.exception("Exception running Axe: %s", err)
353374
if not completed:
354375
task['page_data']['axe_failed'] = 1
355376
self.axe_time = monotonic() - start
@@ -376,7 +397,7 @@ def run_task(self, task):
376397
logging.exception("Exception running task")
377398
if command['record']:
378399
self.wait_for_page_load()
379-
if not task['combine_steps'] or not len(task['script']):
400+
if not task['combine_steps'] or not task['script']:
380401
self.on_stop_capture(task)
381402
self.on_stop_recording(task)
382403
recording = False
@@ -397,10 +418,9 @@ def run_task(self, task):
397418
self.task = None
398419

399420
def alert_size(self, _alert_config, _task_dir, _prefix):
400-
'''Checks the agents file size and alert on certain percentage over avg byte size'''
421+
'''Checks the agents file size and alert on certain percentage over avg byte size'''
401422
self.alert_desktop_results(_alert_config, 'Firefox', _task_dir, _prefix)
402423

403-
404424
def wait_for_extension(self):
405425
"""Wait for the extension to send the started message"""
406426
if self.job['message_server'] is not None:
@@ -506,7 +526,7 @@ def run_js_file(self, file_name):
506526
script = None
507527
script_file_path = os.path.join(self.script_dir, file_name)
508528
if os.path.isfile(script_file_path):
509-
with open(script_file_path, 'r') as script_file:
529+
with open(script_file_path, 'r', encoding='utf-8') as script_file:
510530
script = script_file.read()
511531
if self.driver is not None and script is not None:
512532
try:
@@ -518,7 +538,7 @@ def run_js_file(self, file_name):
518538
logging.debug(ret)
519539
return ret
520540

521-
def get_sorted_requests_json(self, include_bodies):
541+
def get_sorted_requests_json(self, _include_bodies):
522542
return 'null'
523543

524544
def collect_browser_metrics(self, task):
@@ -962,10 +982,7 @@ def process_command(self, command):
962982
parts = command['target'].split(',')
963983
lat = float(parts[0])
964984
lng = float(parts[1])
965-
location_uri = 'data:application/json,{{'\
966-
'"status":"OK","accuracy":{2:d},'\
967-
'"location":{{"lat":{0:f},"lng":{1:f}}}'\
968-
'}}'.format(lat, lng, accuracy)
985+
location_uri = _get_location_uri(accuracy, lat, lng)
969986
logging.debug('Setting location: %s', location_uri)
970987
self.set_pref('geo.wifi.uri', location_uri)
971988
except Exception:

internal/support/firefox_log_parser.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,14 @@ def socket_thread_http_entry(self, msg):
296296
socket = self.http['current_socket']
297297
self.http['connections'][connection] = {'socket': socket}
298298
del self.http['current_socket']
299+
elif msg['message'].startswith('TlsHandshaker::SetupSSL '):
300+
match = re.search(r'^TlsHandshaker::SetupSSL (?P<connection>[\w\d]+)',
301+
msg['message'])
302+
if match:
303+
connection = match.groupdict().get('connection')
304+
if connection in self.http['connections']:
305+
if 'ssl_start' not in self.http['connections'][connection]:
306+
self.http['connections'][connection]['ssl_start'] = msg['timestamp']
299307
elif msg['message'].startswith('nsHttpConnection::SetupSSL '):
300308
match = re.search(r'^nsHttpConnection::SetupSSL (?P<connection>[\w\d]+)',
301309
msg['message'])
@@ -332,6 +340,17 @@ def socket_thread_http_entry(self, msg):
332340
if byte_count > 0 and trans_id in self.http['requests'] and \
333341
'start' not in self.http['requests'][trans_id]:
334342
self.http['requests'][trans_id]['start'] = msg['timestamp']
343+
elif msg['message'].startswith('nsHttpTransaction::OnSocketStatus ') and \
344+
msg['message'].find(' status=4b0005 progress=') > -1:
345+
match = re.search(r'^nsHttpTransaction::OnSocketStatus '
346+
r'\[this=(?P<id>[\w\d]+) status=4b0005 progress=(?P<bytes>[\d+]+)',
347+
msg['message'])
348+
if match:
349+
trans_id = match.groupdict().get('id')
350+
byte_count = int(match.groupdict().get('bytes'))
351+
if byte_count > 0 and trans_id in self.http['requests'] and \
352+
'start' not in self.http['requests'][trans_id]:
353+
self.http['requests'][trans_id]['start'] = msg['timestamp']
335354
elif msg['message'].startswith('nsHttpTransaction::ProcessData '):
336355
match = re.search(r'^nsHttpTransaction::ProcessData \[this=(?P<id>[\w\d]+)',
337356
msg['message'])
@@ -446,14 +465,15 @@ def socket_transport_entry(self, msg):
446465
port = match.groupdict().get('port')
447466
self.http['sockets'][socket] = {'host': host, 'port': port}
448467
# nsSocketTransport::SendStatus [this=143f4000 status=804b0007]
468+
# nsSocketTransport::SendStatus [this=7fe074bd2a00 status=4B0007]
449469
elif msg['message'].startswith('nsSocketTransport::SendStatus '):
450470
match = re.search(r'^nsSocketTransport::SendStatus \['
451471
r'this=(?P<socket>[\w\d]+) '
452472
r'status=(?P<status>[\w\d]+)', msg['message'])
453473
if match:
454474
socket = match.groupdict().get('socket')
455475
status = match.groupdict().get('status')
456-
if status == '804b0007':
476+
if status in ['804b0007', '4b0007']:
457477
if socket not in self.http['sockets']:
458478
self.http['sockets'][socket] = {}
459479
if 'start' not in self.http['sockets'][socket]:

wptagent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1084,7 +1084,7 @@ def fix_selenium_version():
10841084
newer versions are going to use 4.8.3
10851085
"""
10861086
from internal.os_util import run_elevated
1087-
version = '4.8.3'
1087+
version = '4.18.1'
10881088
if sys.version_info[1] == 6:
10891089
version = '3.141.0'
10901090

0 commit comments

Comments
 (0)