2015-04-13 17:31:07 +00:00
|
|
|
import logging
|
|
|
|
|
2015-04-13 18:25:09 +00:00
|
|
|
from app import app
|
2015-12-04 20:51:53 +00:00
|
|
|
from data.database import Repository, LogEntry, RepositoryActionCount, db_random_func
|
|
|
|
from datetime import date, timedelta
|
2015-07-28 21:25:12 +00:00
|
|
|
from workers.worker import Worker
|
2015-04-13 17:31:07 +00:00
|
|
|
|
2015-07-28 21:25:12 +00:00
|
|
|
POLL_PERIOD_SECONDS = 10
|
2015-04-13 17:31:07 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2015-04-22 21:11:08 +00:00
|
|
|
|
2015-07-29 18:21:29 +00:00
|
|
|
def count_repository_actions():
|
2016-06-17 17:52:27 +00:00
|
|
|
""" Aggregates repository actions from the LogEntry table and writes them to
|
|
|
|
the RepositoryActionCount table. Returns the number of repositories for
|
|
|
|
which actions were logged. Returns 0 when there is no more work.
|
|
|
|
"""
|
2015-12-04 20:51:53 +00:00
|
|
|
try:
|
|
|
|
# Get a random repository to count.
|
|
|
|
today = date.today()
|
|
|
|
yesterday = today - timedelta(days=1)
|
|
|
|
has_yesterday_actions = (RepositoryActionCount.select(RepositoryActionCount.repository)
|
|
|
|
.where(RepositoryActionCount.date == yesterday))
|
|
|
|
|
|
|
|
to_count = (Repository.select()
|
|
|
|
.where(~(Repository.id << (has_yesterday_actions)))
|
|
|
|
.order_by(db_random_func()).get())
|
|
|
|
|
|
|
|
logger.debug('Counting: %s', to_count.id)
|
|
|
|
|
|
|
|
actions = (LogEntry.select()
|
|
|
|
.where(LogEntry.repository == to_count,
|
|
|
|
LogEntry.datetime >= yesterday,
|
|
|
|
LogEntry.datetime < today)
|
|
|
|
.count())
|
|
|
|
|
|
|
|
# Create the row.
|
2015-07-29 18:21:29 +00:00
|
|
|
try:
|
2015-12-04 20:51:53 +00:00
|
|
|
RepositoryActionCount.create(repository=to_count, date=yesterday, count=actions)
|
2016-06-17 17:52:27 +00:00
|
|
|
return 1
|
2015-12-04 20:51:53 +00:00
|
|
|
except:
|
|
|
|
logger.exception('Exception when writing count')
|
|
|
|
except Repository.DoesNotExist:
|
|
|
|
logger.debug('No further repositories to count')
|
2015-07-29 18:21:29 +00:00
|
|
|
|
2016-06-17 17:52:27 +00:00
|
|
|
return 0
|
|
|
|
|
2015-07-29 18:21:29 +00:00
|
|
|
|
2015-07-28 21:25:12 +00:00
|
|
|
class RepositoryActionCountWorker(Worker):
|
|
|
|
def __init__(self):
|
|
|
|
super(RepositoryActionCountWorker, self).__init__()
|
|
|
|
self.add_operation(self._count_repository_actions, POLL_PERIOD_SECONDS)
|
2015-04-22 21:11:08 +00:00
|
|
|
|
2015-07-28 21:25:12 +00:00
|
|
|
def _count_repository_actions(self):
|
|
|
|
""" Counts actions for a random repository for the previous day. """
|
2015-07-29 18:21:29 +00:00
|
|
|
count_repository_actions()
|
2015-04-13 17:31:07 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2015-07-28 21:25:12 +00:00
|
|
|
worker = RepositoryActionCountWorker()
|
|
|
|
worker.start()
|