/usr/share/pyshared/celery/datastructures.py is in python-celery 2.4.6-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | # -*- coding: utf-8 -*-
"""
celery.datastructures
~~~~~~~~~~~~~~~~~~~~~
Custom types and data structures.
:copyright: (c) 2009 - 2011 by Ask Solem.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from __future__ import with_statement
import sys
import time
import traceback
from itertools import chain
from threading import RLock
from .utils.compat import UserDict, OrderedDict
class AttributeDictMixin(object):
"""Adds attribute access to mappings.
`d.key -> d[key]`
"""
def __getattr__(self, key):
"""`d.key -> d[key]`"""
try:
return self[key]
except KeyError:
raise AttributeError("'%s' object has no attribute '%s'" % (
self.__class__.__name__, key))
def __setattr__(self, key, value):
"""`d[key] = value -> d.key = value`"""
self[key] = value
class AttributeDict(dict, AttributeDictMixin):
"""Dict subclass with attribute access."""
pass
class DictAttribute(object):
"""Dict interface to attributes.
`obj[k] -> obj.k`
"""
def __init__(self, obj):
self.obj = obj
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default):
try:
return self[key]
except KeyError:
self[key] = default
return default
def __getitem__(self, key):
try:
return getattr(self.obj, key)
except AttributeError:
raise KeyError(key)
def __setitem__(self, key, value):
setattr(self.obj, key, value)
def __contains__(self, key):
return hasattr(self.obj, key)
def _iterate_items(self):
return vars(self.obj).iteritems()
iteritems = _iterate_items
if sys.version_info >= (3, 0):
items = _iterate_items
else:
def items(self):
return list(self._iterate_items())
class ConfigurationView(AttributeDictMixin):
"""A view over an applications configuration dicts.
If the key does not exist in ``changes``, the ``defaults`` dict
is consulted.
:param changes: Dict containing changes to the configuration.
:param defaults: Dict containing the default configuration.
"""
changes = None
defaults = None
_order = None
def __init__(self, changes, defaults):
self.__dict__.update(changes=changes, defaults=defaults,
_order=[changes] + defaults)
def __getitem__(self, key):
for d in self._order:
try:
return d[key]
except KeyError:
pass
raise KeyError(key)
def __setitem__(self, key, value):
self.changes[key] = value
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default):
try:
return self[key]
except KeyError:
self[key] = default
return default
def update(self, *args, **kwargs):
return self.changes.update(*args, **kwargs)
def __contains__(self, key):
for d in self._order:
if key in d:
return True
return False
def __repr__(self):
return repr(dict(self.iteritems()))
def __iter__(self):
return self.iterkeys()
def _iter(self, op):
# defaults must be first in the stream, so values in
# changes takes precedence.
return chain(*[op(d) for d in reversed(self._order)])
def _iterate_keys(self):
return self._iter(lambda d: d.iterkeys())
iterkeys = _iterate_keys
def _iterate_items(self):
return self._iter(lambda d: d.iteritems())
iteritems = _iterate_items
def _iterate_values(self):
return self._iter(lambda d: d.itervalues())
itervalues = _iterate_values
def keys(self):
return list(self._iterate_keys())
def items(self):
return list(self._iterate_items())
def values(self):
return list(self._iterate_values())
class _Code(object):
def __init__(self, code):
self.co_filename = code.co_filename
self.co_name = code.co_name
class _Frame(object):
Code = _Code
def __init__(self, frame):
self.f_globals = {
"__file__": frame.f_globals.get("__file__", "__main__"),
}
self.f_code = self.Code(frame.f_code)
class Traceback(object):
Frame = _Frame
def __init__(self, tb):
self.tb_frame = self.Frame(tb.tb_frame)
self.tb_lineno = tb.tb_lineno
if tb.tb_next is None:
self.tb_next = None
else:
self.tb_next = Traceback(tb.tb_next)
class ExceptionInfo(object):
"""Exception wrapping an exception and its traceback.
:param exc_info: The exception info tuple as returned by
:func:`sys.exc_info`.
"""
#: Exception type.
type = None
#: Exception instance.
exception = None
#: Pickleable traceback instance for use with :mod:`traceback`
tb = None
#: String representation of the traceback.
traceback = None
def __init__(self, exc_info):
self.type, self.exception, tb = exc_info
self.tb = Traceback(tb)
self.traceback = ''.join(traceback.format_exception(*exc_info))
def __str__(self):
return self.traceback
def __repr__(self):
return "<ExceptionInfo: %r>" % (self.exception, )
@property
def exc_info(self):
return self.type, self.exception, self.tb
class LimitedSet(object):
"""Kind-of Set with limitations.
Good for when you need to test for membership (`a in set`),
but the list might become to big, so you want to limit it so it doesn't
consume too much resources.
:keyword maxlen: Maximum number of members before we start
evicting expired members.
:keyword expires: Time in seconds, before a membership expires.
"""
__slots__ = ("maxlen", "expires", "_data")
def __init__(self, maxlen=None, expires=None):
self.maxlen = maxlen
self.expires = expires
self._data = {}
def add(self, value):
"""Add a new member."""
self._expire_item()
self._data[value] = time.time()
def clear(self):
"""Remove all members"""
self._data.clear()
def pop_value(self, value):
"""Remove membership by finding value."""
self._data.pop(value, None)
def _expire_item(self):
"""Hunt down and remove an expired item."""
while 1:
if self.maxlen and len(self) >= self.maxlen:
value, when = self.first
if not self.expires or time.time() > when + self.expires:
try:
self.pop_value(value)
except TypeError: # pragma: no cover
continue
break
def __contains__(self, value):
return value in self._data
def update(self, other):
if isinstance(other, self.__class__):
self._data.update(other._data)
else:
self._data.update(other)
def as_dict(self):
return self._data
def __iter__(self):
return iter(self._data.keys())
def __len__(self):
return len(self._data.keys())
def __repr__(self):
return "LimitedSet([%s])" % (repr(self._data.keys()))
@property
def chronologically(self):
return sorted(self._data.items(), key=lambda (value, when): when)
@property
def first(self):
"""Get the oldest member."""
return self.chronologically[0]
class LRUCache(UserDict):
"""LRU Cache implementation using a doubly linked list to track access.
:keyword limit: The maximum number of keys to keep in the cache.
When a new key is inserted and the limit has been exceeded,
the *Least Recently Used* key will be discarded from the
cache.
"""
def __init__(self, limit=None):
self.limit = limit
self.mutex = RLock()
self.data = OrderedDict()
def __getitem__(self, key):
with self.mutex:
value = self[key] = self.data.pop(key)
return value
def keys(self):
# userdict.keys in py3k calls __getitem__
return self.data.keys()
def values(self):
return list(self._iterate_values())
def items(self):
return list(self._iterate_items())
def __setitem__(self, key, value):
# remove least recently used key.
with self.mutex:
if self.limit and len(self.data) >= self.limit:
self.data.pop(iter(self.data).next())
self.data[key] = value
def __iter__(self):
return self.data.iterkeys()
def _iterate_items(self):
for k in self.data:
try:
yield (k, self.data[k])
except KeyError:
pass
iteritems = _iterate_items
def _iterate_values(self):
for k in self.data:
try:
yield self.data[k]
except KeyError:
pass
itervalues = _iterate_values
class TokenBucket(object):
"""Token Bucket Algorithm.
See http://en.wikipedia.org/wiki/Token_Bucket
Most of this code was stolen from an entry in the ASPN Python Cookbook:
http://code.activestate.com/recipes/511490/
.. admonition:: Thread safety
This implementation may not be thread safe.
"""
#: The rate in tokens/second that the bucket will be refilled
fill_rate = None
#: Maximum number of tokensin the bucket.
capacity = 1
#: Timestamp of the last time a token was taken out of the bucket.
timestamp = None
def __init__(self, fill_rate, capacity=1):
self.capacity = float(capacity)
self._tokens = capacity
self.fill_rate = float(fill_rate)
self.timestamp = time.time()
def can_consume(self, tokens=1):
"""Returns :const:`True` if `tokens` number of tokens can be consumed
from the bucket."""
if tokens <= self._get_tokens():
self._tokens -= tokens
return True
return False
def expected_time(self, tokens=1):
"""Returns the expected time in seconds when a new token should be
available.
.. admonition:: Warning
This consumes a token from the bucket.
"""
_tokens = self._get_tokens()
tokens = max(tokens, _tokens)
return (tokens - _tokens) / self.fill_rate
def _get_tokens(self):
if self._tokens < self.capacity:
now = time.time()
delta = self.fill_rate * (now - self.timestamp)
self._tokens = min(self.capacity, self._tokens + delta)
self.timestamp = now
return self._tokens
|