From 24fb30bf557f24f33b69544824949419e7e6784e Mon Sep 17 00:00:00 2001 From: speedplane Date: Thu, 24 Nov 2016 13:01:14 -0500 Subject: [PATCH 1/2] If the JSON doesn't load, it's likely because the user has another server running on the same port. Improve the error message here so can figure out what's going on more easily. --- browsermobproxy/client.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/browsermobproxy/client.py b/browsermobproxy/client.py index 174baa0..00d7c9c 100644 --- a/browsermobproxy/client.py +++ b/browsermobproxy/client.py @@ -29,7 +29,12 @@ def __init__(self, url, params=None, options=None): self.port = options['existing_proxy_port_to_use'] else: resp = requests.post('%s/proxy' % self.host + urlparams) - jcontent = json.loads(resp.content.decode('utf-8')) + content = resp.content.decode('utf-8') + try: + jcontent = json.loads(content) + except Exception as e: + raise Exception("Could not read Browsermob-Proxy json\n" + "Another server running on this port?\n%s..."%content[:512]) self.port = jcontent['port'] url_parts = self.host.split(":") self.proxy = url_parts[1][2:] + ":" + str(self.port) From 998691511992aab8c3bb1d2646fbb0b9385d6a49 Mon Sep 17 00:00:00 2001 From: speedplane Date: Sat, 26 Nov 2016 16:06:01 -0500 Subject: [PATCH 2/2] Before starting a new Browserproy server, check to see if the server is running. If it is, then just use the existing server rather than starting a new one. This can be helpful if you're running in a multiprocess or threaded environment and many different clients want to use the server simultaneously. --- browsermobproxy/server.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/browsermobproxy/server.py b/browsermobproxy/server.py index 04bfcc4..c94ccd0 100644 --- a/browsermobproxy/server.py +++ b/browsermobproxy/server.py @@ -3,6 +3,7 @@ import socket import subprocess import time +import logging from .client import Client from .exceptions import ProxyServerError @@ -40,10 +41,10 @@ def create_proxy(self, params=None): client = Client(self.url[7:], params) return client - def _is_listening(self): + def _is_listening(self, timeout = 1): try: socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - socket_.settimeout(1) + socket_.settimeout(timeout) socket_.connect((self.host, self.port)) socket_.close() return True @@ -108,6 +109,10 @@ def start(self, options=None): log_path_name = os.path.join(log_path, log_file) self.log_file = open(log_path_name, 'w') + if self._is_listening(.1): + logging.info("BrowserMob proxy already running. Won't start again.") + return + self.process = subprocess.Popen(self.command, stdout=self.log_file, stderr=subprocess.STDOUT)