diff --git a/rattail_tempmon/commands.py b/rattail_tempmon/commands.py index 941cc72..5504630 100644 --- a/rattail_tempmon/commands.py +++ b/rattail_tempmon/commands.py @@ -26,7 +26,16 @@ Tempmon commands from __future__ import unicode_literals, absolute_import +import datetime +import logging + from rattail import commands +from rattail.time import localtime, make_utc + +from rattail_tempmon.db import Session as TempmonSession, model as tempmon + + +log = logging.getLogger(__name__) class ExportHotCooler(commands.ImportSubcommand): @@ -38,6 +47,46 @@ class ExportHotCooler(commands.ImportSubcommand): handler_spec = 'rattail_tempmon.hotcooler.importing.tempmon:FromTempmonToHotCooler' +class PurgeTempmon(commands.Subcommand): + """ + Purge stale data from Tempmon database + """ + name = 'purge-tempmon' + description = __doc__.strip() + + def add_parser_args(self, parser): + parser.add_argument('--keep', metavar='DAYS', required=True, type=int, + help="Number of days for which data should be kept.") + parser.add_argument('--dry-run', action='store_true', + help="Go through the full motions and allow logging etc. to " + "occur, but rollback (abort) the transaction at the end.") + + def run(self, args): + cutoff = localtime(self.config).date() - datetime.timedelta(days=args.keep) + cutoff = localtime(self.config, datetime.datetime.combine(cutoff, datetime.time(0))) + session = TempmonSession() + + readings = session.query(tempmon.Reading)\ + .filter(tempmon.Reading.taken < make_utc(cutoff)) + count = readings.count() + + def purge(reading, i): + session.delete(reading) + if i % 200 == 0: + session.flush() + + self.progress_loop(purge, readings, count=count, message="Purging stale readings") + log.info("deleted {} stale readings".format(count)) + + if args.dry_run: + session.rollback() + log.info("dry run, so transaction was rolled back") + else: + session.commit() + log.info("transaction was committed") + session.close() + + class TempmonClient(commands.Subcommand): """ Manage the tempmon-client daemon diff --git a/setup.py b/setup.py index d554cc7..6b3cafe 100644 --- a/setup.py +++ b/setup.py @@ -99,6 +99,7 @@ setup( entry_points = { 'rattail.commands': [ 'export-hotcooler = rattail_tempmon.commands:ExportHotCooler', + 'purge-tempmon = rattail_tempmon.commands:PurgeTempmon', 'tempmon-client = rattail_tempmon.commands:TempmonClient', 'tempmon-server = rattail_tempmon.commands:TempmonServer', ],