add user.count_active_users

produces summary of active/pending/ready spawner counts

Avoids brittle bookkeeping of running counts,
computing the value upon request.

For 10k users this is still only a few milliseconds, which seems worth it
This commit is contained in:
Min RK
2017-08-01 17:00:45 +02:00
parent 7520d4b81e
commit f49606dff6
3 changed files with 68 additions and 45 deletions

View File

@@ -1,6 +1,7 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from collections import defaultdict
from datetime import datetime, timedelta
from urllib.parse import quote, urlparse
@@ -73,6 +74,25 @@ class UserDict(dict):
db.commit()
dict.__delitem__(self, user_id)
def count_active_users(self):
"""Count the number of user servers that are active/pending/ready
Returns dict with counts of active/pending/ready servers
"""
counts = defaultdict(lambda : 0)
for user in self.values():
for spawner in user.spawners.values():
pending = spawner.pending
if pending:
counts['pending'] += 1
counts[pending + '_pending'] += 1
if spawner.active:
counts['active'] += 1
if spawner.ready:
counts['ready'] += 1
return counts
class _SpawnerDict(dict):
def __init__(self, spawner_factory):
@@ -294,8 +314,8 @@ class User(HasTraits):
spawner = self.spawners[server_name]
spawner.orm_spawner.server = orm_server
server = spawner.server
spawner.server = Server(orm_server=orm_server)
assert orm_spawner.server is orm_server
# Passing user_options to the spawner
spawner.user_options = options or {}
@@ -434,7 +454,7 @@ class User(HasTraits):
# remove server entry from db
if spawner.server is not None:
self.db.delete(spawner.orm_spawner.server)
spawner.orm_spawner.server = None
spawner.server = None
if not spawner.will_resume:
# find and remove the API token if the spawner isn't
# going to re-use it next time