Package ZenUtils :: Module Map
[hide private]
[frames] | no frames]

Source Code for Module ZenUtils.Map

  1  ########################################################################### 
  2  # 
  3  # This program is part of Zenoss Core, an open source monitoring platform. 
  4  # Copyright (C) 2007, Zenoss Inc. 
  5  # 
  6  # This program is free software; you can redistribute it and/or modify it 
  7  # under the terms of the GNU General Public License version 2 as published by 
  8  # the Free Software Foundation. 
  9  # 
 10  # For complete information please visit: http://www.zenoss.com/oss/ 
 11  # 
 12  ########################################################################### 
 13   
 14  import threading 
 15  import time 
 16   
17 -class Timed:
18 "Store elements in a map for the given time" 19
20 - def __init__(self, map, timeout):
21 self.map = map 22 self.timeout = timeout 23 self.lastClean = 0
24 25
26 - def clean(self, now = None):
27 "remove old values" 28 # FIXME O(N) search 29 if now is None: 30 now = time.time() 31 if self.lastClean + self.timeout > now: 32 return 33 for k, (v, t) in self.map.items(): 34 if t + self.timeout < now: 35 del self.map[k] 36 self.lastClean = now
37 38
39 - def get(self, key, default):
40 now = time.time() 41 self.clean(now) 42 v, t = self.map.get(key, (default, None) ) 43 if t is None or t + self.timeout < now: 44 return default 45 return v
46 47
48 - def __getitem__(self, key):
49 now = time.time() 50 v, t = self.map[key] 51 if t + self.timeout < now: 52 del self.map[key] 53 raise KeyError 54 return v
55 56
57 - def __setitem__(self, key, value):
58 now = time.time() 59 self.clean(now) 60 self.map[key] = (value, now)
61 62
63 - def update(self, d):
64 now = time.time() 65 self.clean(now) 66 for k, v in d.items(): 67 self.map[k] = (v, now)
68 69
70 -class Locked:
71 "Use a simple lock for all read/write access to a map" 72
73 - def __init__(self, map):
74 self.map = map 75 self.lock = threading.Lock()
76 77
78 - def impl(self, m, *args, **kw):
79 "call a method on the map, with the lock held" 80 self.lock.acquire() 81 try: 82 return m(*args, **kw) 83 finally: 84 self.lock.release()
85 86
87 - def has_key(self, *args, **kw):
88 return self.impl(self.map.has_key, *args, **kw)
89 90
91 - def get(self, *args, **kw):
92 return self.impl(self.map.get, *args, **kw)
93 94
95 - def __setitem__(self, *args, **kw):
96 return self.impl(self.map.__setitem__, *args, **kw)
97 98
99 - def __getitem__(self, *args, **kw):
100 return self.impl(self.map.__getitem__, *args, **kw)
101 102
103 - def update(self, *args, **kw):
104 return self.impl(self.map.update, *args, **kw)
105