| 1 |
from collections import defaultdict |
| 2 |
from datetime import datetime |
| 3 |
|
| 4 |
from debug_toolbar.panels import Panel |
| 5 |
from django.apps import apps |
| 6 |
from django.conf import settings |
| 7 |
from django.utils.translation import gettext_lazy as _ |
| 8 |
from django.utils.timesince import timesince |
| 9 |
|
| 10 |
from .cache import cachalot_caches |
| 11 |
from .settings import cachalot_settings |
| 12 |
|
| 13 |
|
| 14 |
class CachalotPanel(Panel): |
| 15 |
title = 'Cachalot' |
| 16 |
template = 'cachalot/panel.html' |
| 17 |
|
| 18 |
def __init__(self, *args, **kwargs): |
| 19 |
self.last_invalidation = None |
| 20 |
super(CachalotPanel, self).__init__(*args, **kwargs) |
| 21 |
|
| 22 |
@property |
| 23 |
def enabled(self): |
| 24 |
enabled = super(CachalotPanel, self).enabled |
| 25 |
if enabled: |
| 26 |
self.enable_instrumentation() |
| 27 |
else: |
| 28 |
self.disable_instrumentation() |
| 29 |
return enabled |
| 30 |
|
| 31 |
def enable_instrumentation(self): |
| 32 |
settings.CACHALOT_ENABLED = True |
| 33 |
cachalot_settings.reload() |
| 34 |
|
| 35 |
def disable_instrumentation(self): |
| 36 |
settings.CACHALOT_ENABLED = False |
| 37 |
cachalot_settings.reload() |
| 38 |
|
| 39 |
def process_request(self, request): |
| 40 |
self.collect_invalidations() |
| 41 |
return super(CachalotPanel, self).process_request(request) |
| 42 |
|
| 43 |
def collect_invalidations(self): |
| 44 |
models = apps.get_models() |
| 45 |
data = defaultdict(list) |
| 46 |
cache = cachalot_caches.get_cache() |
| 47 |
for db_alias in settings.DATABASES: |
| 48 |
get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN |
| 49 |
model_cache_keys = { |
| 50 |
get_table_cache_key(db_alias, model._meta.db_table): model |
| 51 |
for model in models} |
| 52 |
for cache_key, timestamp in cache.get_many( |
| 53 |
model_cache_keys.keys()).items(): |
| 54 |
invalidation = datetime.fromtimestamp(timestamp) |
| 55 |
model = model_cache_keys[cache_key] |
| 56 |
data[db_alias].append( |
| 57 |
(model._meta.app_label, model.__name__, timesince(invalidation))) |
| 58 |
if self.last_invalidation is None \ |
| 59 |
or invalidation > self.last_invalidation: |
| 60 |
self.last_invalidation = invalidation |
| 61 |
data[db_alias].sort(key=lambda row: row[2], reverse=True) |
| 62 |
self.record_stats({'invalidations_per_db': list(data.items())}) |
| 63 |
|
| 64 |
@property |
| 65 |
def nav_subtitle(self): |
| 66 |
if self.enabled and self.last_invalidation is not None: |
| 67 |
return (_('Last invalidation: %s') |
| 68 |
% timesince(self.last_invalidation)) |
| 69 |
return '' |