Skip to content

Instantly share code, notes, and snippets.

@ecarreras
Created September 7, 2012 05:54
Show Gist options
  • Save ecarreras/3663597 to your computer and use it in GitHub Desktop.
Save ecarreras/3663597 to your computer and use it in GitHub Desktop.
Spawn oop running instances
diff --git a/spawn_oop/__init__.py b/spawn_oop/__init__.py
index cbae3cc..23da04f 100644
--- a/spawn_oop/__init__.py
+++ b/spawn_oop/__init__.py
@@ -7,6 +7,7 @@ import sys
import time
import tempfile
from datetime import datetime
+from hashlib import sha1
import psutil
from ooop import OOOP, Manager
@@ -17,6 +18,14 @@ from tools import config
__version__ = '0.3.2'
+RUNNING_INSTANCES = {}
+
+def compute_hash_instance(dbname, osv_object, method, *args):
+ if args:
+ args = '-'.join([str(x) for x in args])
+ return sha1('%s-%s-%s-%s' % (dbname, osv_object, method, args)).hexdigest()
+
+
def spawn(port=8069):
"""Spawn decorator.
"""
@@ -25,14 +34,23 @@ def spawn(port=8069):
if not os.getenv('SPAWNED', False):
logger = netsvc.Logger()
# self, cursor, uid, *args
+ osv_object = args[0]
+ cursor = args[1]
+ uid = args[2]
+ hash_instance = compute_hash_instance(
+ cursor.dbname, osv_object, f.__name__, args[:3]
+ )
+ pid = RUNNING_INSTANCES.get(hash_instance, -1)
+ try:
+ psutil.Process(pid)
+ raise Exception("Already running pid: %s" % pid)
+ except psutil.error.NoSuchProcess:
+ pass
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 0))
child_port = sock.getsockname()[1]
sock.listen(1)
sock.shutdown(socket.SHUT_RDWR)
- osv_object = args[0]
- cursor = args[1]
- uid = args[2]
user_obj = osv_object.pool.get('res.users')
# Aquí hem de fer l'spawn
env = os.environ.copy()
@@ -63,18 +81,24 @@ def spawn(port=8069):
time.sleep(0.1)
is_listen = False
startup = datetime.now() - start
- logger.notifyChannel('spawn_oop', netsvc.LOG_INFO, 'Server '
- 'started in %s. PID: %s. Listening on %s.'
- % (startup, p.pid, child_port))
+ RUNNING_INSTANCES[hash_instance] = p.pid
+ logger.notifyChannel('spawn_oop', netsvc.LOG_INFO,
+ 'Server started in %s. PID: %s. Listening on %s. '
+ 'Hash instance: %s ' % (startup, p.pid, child_port,
+ hash_instance)
+ )
start = datetime.now()
O = OOOP(dbname=cursor.dbname, port=child_port, user=user,
pwd=pwd, uri=uri)
obj = Manager(osv_object._name, O)
method = f.__name__
newargs = args[3:]
- logger.notifyChannel('spawn_oop', netsvc.LOG_INFO, 'Calling '
- '%s.%s(%s)' % (osv_object._name, method,
- ', '.join(map(str, newargs))))
+ logger.notifyChannel('spawn_oop', netsvc.LOG_INFO,
+ 'Calling %s.%s(%s)' % (
+ osv_object._name, method,
+ ', '.join([str(x) for x in newargs])
+ )
+ )
res = getattr(obj, method)(*newargs)
duration = datetime.now() - start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment