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