From f0d09640109a77933381b933745f53aa0b6eca2e Mon Sep 17 00:00:00 2001 From: Francois Dang Ngoc Date: Thu, 13 Aug 2015 15:58:06 -0400 Subject: [PATCH] improved detection of postgres already running on a port --- pyembedpg.py | 19 ++++++++++--------- setup.py | 2 +- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/pyembedpg.py b/pyembedpg.py index bcaa4c4..94963cd 100644 --- a/pyembedpg.py +++ b/pyembedpg.py @@ -20,6 +20,7 @@ import os from os.path import expanduser import re +import socket import tempfile from psycopg2._psycopg import OperationalError from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT @@ -172,15 +173,17 @@ def __init__(self, bin_dir, ports): 'host all all ::1/128 md5\n'.format(admin=DatabaseRunner.ADMIN_USER) ) - for port in ports: - self.proc = Popen([self._postgres_cmd, '-D', self._temp_dir, '-p', str(port)]) - # if the process is still running, then there was problem, most likely the port is taken so try the next one - if not self.proc.poll(): - self.running_port = port - break - else: + def can_connect(port): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + return sock.connect_ex(('127.0.0.1', port)) != 0 + + self.running_port = next((port for port in ports if can_connect(port)), None) + if self.running_port is None: raise PyEmbedPgException('Cannot run postgres on any of these ports [{ports}]'.format(ports=', '.join((str(p) for p in ports)))) + self.proc = Popen([self._postgres_cmd, '-D', self._temp_dir, '-p', str(self.running_port)]) + logger.debug('Postgres started on port {port}...'.format(port=self.running_port)) + # Loop until the server is started logger.debug('Waiting for Postgres to start...') start = time.time() @@ -194,8 +197,6 @@ def __init__(self, bin_dir, ports): else: raise PyEmbedPgException('Cannot start postgres after {timeout} seconds'.format(timeout=DatabaseRunner.TIMEOUT)) - logger.debug('Postgres started on port {port}...'.format(port=self.running_port)) - def __enter__(self): return self diff --git a/setup.py b/setup.py index 07d4514..b665f78 100755 --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ def run_tests(self): setup( name='pyembedpg', - version='0.0.2', + version='0.0.3', description='Run embedded version of Postgres', long_description='Run embedded version of Postgres', keywords='postgres, python, tests',