-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
384 lines (332 loc) · 15.3 KB
/
Copy pathcache.py
File metadata and controls
384 lines (332 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# decorator makes wrappers that have the same API as their wrapped function
from __future__ import annotations
from collections import defaultdict
from collections.abc import Mapping, Collection
from inspect import signature, Parameter
import functools
import logging
import signal
import sys
import threading
import time
import typing
import warnings
if typing.TYPE_CHECKING:
from .lru import LRU
from collections.abc import Callable, Iterable
from odoo.models import BaseModel
C = typing.TypeVar('C', bound=Callable)
unsafe_eval = eval
_logger = logging.getLogger(__name__)
_logger_lock = threading.RLock()
_logger_state: typing.Literal['wait', 'abort', 'run'] = 'wait'
class ormcache_counter:
""" Statistic counters for cache entries. """
__slots__ = ['cache_name', 'err', 'gen_time', 'hit', 'miss', 'tx_err', 'tx_hit', 'tx_miss']
def __init__(self):
self.hit: int = 0
self.miss: int = 0
self.err: int = 0
self.gen_time: float = 0.0
self.cache_name: str = ''
self.tx_hit: int = 0
self.tx_miss: int = 0
self.tx_err: int = 0
@property
def ratio(self) -> float:
return 100.0 * self.hit / (self.hit + self.miss or 1)
@property
def tx_ratio(self) -> float:
return 100.0 * self.tx_hit / (self.tx_hit + self.tx_miss or 1)
@property
def tx_calls(self) -> int:
return self.tx_hit + self.tx_miss
_COUNTERS: defaultdict[tuple[str, Callable], ormcache_counter] = defaultdict(ormcache_counter)
"""statistic counters dictionary, maps (dbname, method) to counter"""
class ormcache:
""" LRU cache decorator for model methods.
The parameters are strings that represent expressions referring to the
signature of the decorated method, and are used to compute a cache key::
@ormcache('model_name', 'mode')
def _compute_domain(self, model_name, mode="read"):
...
For the sake of backward compatibility, the decorator supports the named
parameter `skiparg`::
@ormcache(skiparg=1)
def _compute_domain(self, model_name, mode="read"):
...
Methods implementing this decorator should never return a Recordset,
because the underlying cursor will eventually be closed and raise a
`psycopg2.InterfaceError`.
"""
key: Callable[..., tuple]
def __init__(self, *args: str, cache: str = 'default', skiparg: int | None = None, **kwargs):
self.args = args
self.skiparg = skiparg
self.cache_name = cache
if skiparg is not None:
warnings.warn("Deprecated since 19.0, ormcache(skiparg) will be removed", DeprecationWarning)
def __call__(self, method: C) -> C:
assert not hasattr(self, 'method'), "ormcache is already bound to a method"
self.method = method
self.determine_key()
assert self.key is not None, "ormcache.key not initialized"
@functools.wraps(method)
def lookup(*args, **kwargs):
return self.lookup(*args, **kwargs)
lookup.__cache__ = self # type: ignore
return lookup
def add_value(self, *args, cache_value=None, **kwargs) -> None:
model: BaseModel = args[0]
d: LRU = model.pool._Registry__caches[self.cache_name] # type: ignore
key = self.key(*args, **kwargs)
d[key] = cache_value
def determine_key(self) -> None:
""" Determine the function that computes a cache key from arguments. """
assert self.method is not None
if self.skiparg is not None:
# backward-compatible function that uses self.skiparg
self.key = lambda *args, **kwargs: (args[0]._name, self.method, *args[self.skiparg:])
return
# build a string that represents function code and evaluate it
args = ', '.join(
# remove annotations because lambdas can't be type-annotated,
str(params.replace(annotation=Parameter.empty))
for params in signature(self.method).parameters.values()
)
values = ['self._name', 'method', *self.args]
code = f"lambda {args}: ({''.join(a for arg in values for a in (arg, ','))})"
self.key = unsafe_eval(code, {'method': self.method})
def lookup(self, *args, **kwargs):
model: BaseModel = args[0]
d: LRU = model.pool._Registry__caches[self.cache_name] # type: ignore
key = self.key(*args, **kwargs)
counter = _COUNTERS[model.pool.db_name, self.method]
tx_lookups = model.env.cr.cache.setdefault('_ormcache_lookups', set())
# tx: is it the first call in the transation for that key
tx_first_lookup = key not in tx_lookups
if tx_first_lookup:
counter.cache_name = self.cache_name
tx_lookups.add(key)
try:
r = d[key]
counter.hit += 1
counter.tx_hit += tx_first_lookup
return r
except KeyError:
counter.miss += 1
counter.tx_miss += tx_first_lookup
miss = True
except TypeError:
_logger.warning("cache lookup error on %r", key, exc_info=True)
counter.err += 1
counter.tx_err += tx_first_lookup
miss = False
if miss:
start = time.monotonic()
value = self.method(*args, **kwargs)
counter.gen_time += time.monotonic() - start
d[key] = value
return value
else:
return self.method(*args, **kwargs)
class ormcache_context(ormcache):
""" This LRU cache decorator is a variant of :class:`ormcache`, with an
extra parameter ``keys`` that defines a sequence of dictionary keys. Those
keys are looked up in the ``context`` parameter and combined to the cache
key made by :class:`ormcache`.
"""
def __init__(self, *args: str, keys, skiparg=None, **kwargs):
assert skiparg is None, "ormcache_context() no longer supports skiparg"
warnings.warn("Since 19.0, use ormcache directly, context values are available as `self.env.context.get`", DeprecationWarning)
super().__init__(*args, **kwargs)
def determine_key(self) -> None:
assert self.method is not None
sign = signature(self.method)
cont_expr = "(context or {})" if 'context' in sign.parameters else "self.env.context"
keys_expr = "tuple(%s.get(k) for k in %r)" % (cont_expr, self.keys)
self.args += (keys_expr,)
super().determine_key()
def log_ormcache_stats(sig=None, frame=None): # noqa: ARG001 (arguments are there for signals)
# collect and log data in a separate thread to avoid blocking the main thread
# and avoid using logging module directly in the signal handler
# https://docs.python.org/3/library/logging.html#thread-safety
global _logger_state # noqa: PLW0603
with _logger_lock:
if _logger_state != 'wait':
# send the signal again to stop the logging thread
_logger_state = 'abort'
return
_logger_state = 'run'
def check_continue_logging():
if _logger_state == 'run':
return True
_logger.info('Stopping logging ORM cache stats')
return False
class StatsLine:
def __init__(self, method, counter: ormcache_counter):
self.sz_entries_sum: int = 0
self.sz_entries_max: int = 0
self.nb_entries: int = 0
self.counter = counter
self.method = method
def _log_ormcache_stats():
""" Log statistics of ormcache usage by database, model, and method. """
from odoo.modules.registry import Registry # noqa: PLC0415
try:
# {dbname: {method: StatsLine}}
cache_stats: defaultdict[str, dict[Callable, StatsLine]] = defaultdict(dict)
# {dbname: (cache_name, entries, count, total_size)}
cache_usage: defaultdict[str, list[tuple[str, int, int, int]]] = defaultdict(list)
# browse the values in cache
registries = Registry.registries.snapshot
class_slots = {}
for i, (dbname, registry) in enumerate(registries.items(), start=1):
if not check_continue_logging():
return
_logger.info("Processing database %s (%d/%d)", dbname, i, len(registries))
db_cache_stats = cache_stats[dbname]
db_cache_usage = cache_usage[dbname]
for cache_name, cache in registry._Registry__caches.items():
cache_total_size = 0
for cache_key, cache_value in cache.snapshot.items():
method = cache_key[1]
stats = db_cache_stats.get(method)
if stats is None:
stats = db_cache_stats[method] = StatsLine(method, _COUNTERS[dbname, method])
stats.nb_entries += 1
if not show_size:
continue
size = get_cache_size((cache_key, cache_value), cache_info=method.__qualname__, class_slots=class_slots)
cache_total_size += size
stats.sz_entries_sum += size
stats.sz_entries_max = max(stats.sz_entries_max, size)
db_cache_usage.append((cache_name, len(cache), cache.count, cache_total_size))
# add counters that have no values in cache
for (dbname, method), counter in _COUNTERS.copy().items(): # copy to avoid concurrent modification
if not check_continue_logging():
return
db_cache_stats = cache_stats[dbname]
stats = db_cache_stats.get(method)
if stats is None:
db_cache_stats[method] = StatsLine(method, counter)
# Output the stats
log_msgs = ['Caches stats:']
size_column_info = (
f"{'Memory %':>10},"
f"{'Memory SUM':>12},"
f"{'Memory MAX':>12},"
) if show_size else ''
column_info = (
f"{'Cache Name':>25},"
f"{'Entry':>7},"
f"{size_column_info}"
f"{'Hit':>6},"
f"{'Miss':>6},"
f"{'Err':>6},"
f"{'Gen Time [s]':>13},"
f"{'Hit Ratio':>10},"
f"{'TX Hit Ratio':>13},"
f"{'TX Call':>8},"
" Method"
)
for dbname, db_cache_stats in sorted(cache_stats.items(), key=lambda k: k[0] or '~'):
if not check_continue_logging():
return
log_msgs.append(f'Database {dbname or "<no_db>"}:')
log_msgs.extend(
f" * {cache_name}: {entries}/{count}{' (' if cache_total_size else ''}{cache_total_size}{' bytes)' if cache_total_size else ''}"
for cache_name, entries, count, cache_total_size in db_cache_usage
)
log_msgs.append('Details:')
# sort by -sz_entries_sum and method_name
db_cache_stat = sorted(db_cache_stats.items(), key=lambda k: (-k[1].sz_entries_sum, k[0].__name__))
sz_entries_all = sum(stat.sz_entries_sum for _, stat in db_cache_stat)
log_msgs.append(column_info)
for method, stat in db_cache_stat:
size_data = (
f'{stat.sz_entries_sum / (sz_entries_all or 1) * 100:9.1f}%,'
f'{stat.sz_entries_sum:12d},'
f'{stat.sz_entries_max:12d},'
) if show_size else ''
log_msgs.append(
f'{stat.counter.cache_name:>25},'
f'{stat.nb_entries:7d},'
f'{size_data}'
f'{stat.counter.hit:6d},'
f'{stat.counter.miss:6d},'
f'{stat.counter.err:6d},'
f'{stat.counter.gen_time:13.3f},'
f'{stat.counter.ratio:9.1f}%,'
f'{stat.counter.tx_ratio:12.1f}%,'
f'{stat.counter.tx_calls:8d},'
f' {method.__qualname__}'
)
_logger.info('\n'.join(log_msgs))
except Exception: # noqa: BLE001
_logger.exception()
finally:
global _logger_state # noqa: PLW0603
with _logger_lock:
_logger_state = 'wait'
show_size = False
if sig == signal.SIGUSR1:
threading.Thread(target=_log_ormcache_stats,
name="odoo.signal.log_ormcache_stats").start()
elif sig == signal.SIGUSR2:
show_size = True
threading.Thread(target=_log_ormcache_stats,
name="odoo.signal.log_ormcache_stats_with_size").start()
def get_cache_key_counter(bound_method: Callable, *args, **kwargs) -> tuple[LRU, tuple, ormcache_counter]:
""" Return the cache, key and stat counter for the given call. """
model: BaseModel = bound_method.__self__ # type: ignore
ormcache_instance: ormcache = bound_method.__cache__ # type: ignore
cache: LRU = model.pool._Registry__caches[ormcache_instance.cache_name] # type: ignore
key = ormcache_instance.key(model, *args, **kwargs)
counter = _COUNTERS[model.pool.db_name, ormcache_instance.method]
return cache, key, counter
def get_cache_size(
obj,
*,
cache_info: str = '',
seen_ids: set[int] | None = None,
class_slots: dict[type, Iterable[str]] | None = None
) -> int:
""" A non-thread-safe recursive object size estimator """
from odoo.models import BaseModel # noqa: PLC0415
from odoo.api import Environment # noqa: PLC0415
if seen_ids is None:
# count internal constants as 0 bytes
seen_ids = set(map(id, (None, False, True)))
if class_slots is None:
class_slots = {} # {class_id: combined_slots}
total_size = 0
objects = [obj]
while objects:
cur_obj = objects.pop()
if id(cur_obj) in seen_ids:
continue
if cache_info and isinstance(cur_obj, (BaseModel, Environment)):
_logger.error('%s is cached by %s', cur_obj, cache_info)
continue
seen_ids.add(id(cur_obj))
total_size += sys.getsizeof(cur_obj)
if hasattr(cur_obj, '__slots__'):
cur_obj_cls = type(cur_obj)
attributes = class_slots.get(id(cur_obj_cls))
if attributes is None:
class_slots[id(cur_obj_cls)] = attributes = tuple({
f'_{cls.__name__}{attr}' if attr.startswith('__') else attr
for cls in cur_obj_cls.mro()
for attr in getattr(cls, '__slots__', ())
})
objects.extend(getattr(cur_obj, attr, None) for attr in attributes)
if hasattr(cur_obj, '__dict__'):
objects.append(object.__dict__)
if isinstance(cur_obj, Mapping):
objects.extend(cur_obj.values())
objects.extend(cur_obj.keys())
elif isinstance(cur_obj, Collection) and not isinstance(cur_obj, (str, bytes, bytearray)):
objects.extend(cur_obj)
return total_size