diff --git a/ocflib/lab/stats.py b/ocflib/lab/stats.py index 6315c738..f6cc78b8 100644 --- a/ocflib/lab/stats.py +++ b/ocflib/lab/stats.py @@ -140,6 +140,34 @@ def list_desktops(public_only=False): return [entry['attributes']['cn'][0] for entry in c.response] +def add_ocf(hostname): + if not hostname.endswith('.ocf.berkeley.edu'): + return hostname + '.ocf.berkeley.edu' + return hostname + + +def last_used(host): + with open('/etc/ocfstats-ro.passwd', 'r') as fin: + password = fin.read().strip() + with mysql.get_connection(user='ocfstats-ro', password=password, db='ocfstats') as c: + # The reason for not using the partial `get_connection` is because of this: + # https://github.com/PyCQA/pylint/issues/2271 + + query = 'SELECT * FROM `session`' + query_args = [] + + query_conditions = [] + query_conditions.append('`host` = %s') + query_args.append(add_ocf(host)) + + query += ' WHERE ' + ' AND '.join(query_conditions) + query += ' ORDER BY `start` DESC LIMIT 1' + # we can't have another user start before current user ends so here we order by start + + c.execute(query, query_args) + return Session.from_row(c.fetchone()) + + class UtilizationProfile(namedtuple('UtilizationProfile', [ 'hostname', 'start', 'end', 'sessions' ])): @@ -172,10 +200,6 @@ def from_hostname(cls, hostname, start, end): @classmethod def from_hostnames(cls, hostnames, start, end): - def add_ocf(hostname): - if not hostname.endswith('.ocf.berkeley.edu'): - return hostname + '.ocf.berkeley.edu' - return hostname hostnames = tuple(map(add_ocf, hostnames))