From 2bdad0ae7a3a6e4ec5116becd39910388b679ed2 Mon Sep 17 00:00:00 2001 From: Leif Johansson Date: Thu, 4 Oct 2012 15:39:08 +0200 Subject: restructure --- meetingtools/ac/__init__.py | 57 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 meetingtools/ac/__init__.py (limited to 'meetingtools/ac/__init__.py') diff --git a/meetingtools/ac/__init__.py b/meetingtools/ac/__init__.py new file mode 100644 index 0000000..2bbd25f --- /dev/null +++ b/meetingtools/ac/__init__.py @@ -0,0 +1,57 @@ +from meetingtools.ac.api import ACPClient +import time +from meetingtools.apps.cluster.models import acc_for_user +from django.core.cache import cache +from Queue import Queue +import logging +from django.contrib.auth.models import User + +_pools = {} + +MAXCALLS = 10 +MAXIDLE = 10 + +class ClientPool(object): + + def __init__(self,acc,maxsize=0,increment=2): + self._q = Queue(maxsize) + self._acc = acc + self._increment = increment + + def allocate(self): + now = time.time() + api = None + while not api: + if self._q.empty(): + for i in range(1,self._increment): + logging.debug("adding instance %d" % i) + api = ACPClient(self._acc.api_url,self._acc.user,self._acc.password,cpool=self) + self._q.put_nowait(api) + + api = self._q.get() + if api and (api.age > MAXCALLS or now - api.lastused > MAXIDLE): + api = None + return api + +# with ac_api_client(acc) as api +# ... + +def ac_api_client(o): + acc = o + logging.debug("ac_api_client(%s)" % repr(o)) + if hasattr(o,'user') and isinstance(getattr(o,'user'),User): + acc = acc_for_user(getattr(o,'user')) + elif hasattr(o,'acc'): + acc = getattr(o,'acc') + + tag = 'ac_api_client_%d' % acc.id + pool = _pools.get(tag) + if pool is None: + pool = ClientPool(acc,maxsize=30) + _pools[tag] = pool + + return pool.allocate() + + + + \ No newline at end of file -- cgit v1.1