diff --git a/src/c3nav/mapdata/management/commands/statssnapshot.py b/src/c3nav/mapdata/management/commands/statssnapshot.py new file mode 100644 index 00000000..37e59a35 --- /dev/null +++ b/src/c3nav/mapdata/management/commands/statssnapshot.py @@ -0,0 +1,27 @@ +import json +import os +from django.conf import settings +from django.core.management.base import BaseCommand +from django.utils.translation import ugettext_lazy as _ + +from c3nav.mapdata.utils.cache.stats import stats_snapshot + + +class Command(BaseCommand): + help = 'get stats snapshot' + + def add_arguments(self, parser): + parser.add_argument('--reset', action='store_const', const=True, default=False, + help=_('reset the values')) + parser.add_argument('--save', action='store_const', const=True, default=False, + help=_('save result to the stats directory')) + + def handle(self, *args, **options): + result = stats_snapshot(reset=options['reset']) + if options['save']: + filename = os.path.join(settings.STATS_ROOT, + 'stats_%s_%s.json' % (result['start_date'], result['end_date'])) + json.dump(result, open(filename, 'w'), indent=4) + print('saved to %s' % filename) + else: + print(json.dumps(result, indent=4)) diff --git a/src/c3nav/mapdata/utils/cache/stats.py b/src/c3nav/mapdata/utils/cache/stats.py index 38818240..be2678f3 100644 --- a/src/c3nav/mapdata/utils/cache/stats.py +++ b/src/c3nav/mapdata/utils/cache/stats.py @@ -1,4 +1,5 @@ from django.core.cache import cache +from django.utils import timezone def increment_cache_key(cache_key): @@ -6,3 +7,21 @@ def increment_cache_key(cache_key): cache.incr(cache_key) except ValueError: cache.set(cache_key, 0, None) + + +def stats_snapshot(reset=True): + last_now = cache.get('apistats_last_reset', '', None) + now = timezone.now() + results = {} + for key in cache.keys('apistats__*'): + results[key] = cache.get(key) + if reset: + cache.delete(key) + if reset: + cache.set('apistats_last_reset', now, None) + results = dict(sorted(results.items())) + return { + 'start_time': str(last_now), + 'end_time': str(now), + 'data': results + } diff --git a/src/c3nav/settings.py b/src/c3nav/settings.py index decd1d8d..5fa096fb 100644 --- a/src/c3nav/settings.py +++ b/src/c3nav/settings.py @@ -41,6 +41,7 @@ MAP_ROOT = os.path.join(DATA_DIR, 'map') RENDER_ROOT = os.path.join(DATA_DIR, 'render') TILES_ROOT = os.path.join(DATA_DIR, 'tiles') CACHE_ROOT = os.path.join(DATA_DIR, 'cache') +STATS_ROOT = os.path.join(DATA_DIR, 'stats') if not os.path.exists(DATA_DIR): os.mkdir(DATA_DIR) @@ -58,6 +59,8 @@ if not os.path.exists(TILES_ROOT): os.mkdir(TILES_ROOT) if not os.path.exists(CACHE_ROOT): os.mkdir(CACHE_ROOT) +if not os.path.exists(STATS_ROOT): + os.mkdir(STATS_ROOT) PUBLIC_EDITOR = config.getboolean('c3nav', 'editor', fallback=True) PUBLIC_BASE_MAPDATA = config.getboolean('c3nav', 'public_base_mapdata', fallback=False)