diff options
author | Anton Khirnov <anton@khirnov.net> | 2020-04-06 16:59:14 +0200 |
---|---|---|
committer | Anton Khirnov <anton@khirnov.net> | 2020-04-06 16:59:14 +0200 |
commit | 287d50705266a05214f14fb276c3496a4c42e87f (patch) | |
tree | 04f434b995e15f60c33bc6c8690b27c9570225fa /sshban.py | |
parent | 1e7883269f6f5ba61c9fc618d418b484916aba7f (diff) |
sshban: periodically remove expired items from ExpiringCounter
Diffstat (limited to 'sshban.py')
-rwxr-xr-x | sshban.py | 18 |
1 files changed, 18 insertions, 0 deletions
@@ -55,12 +55,16 @@ class ExpiringCounter: default_timeout = None _data = None + _gc_counter = None def __init__(self, default_timeout): self._data = {} self.default_timeout = default_timeout + self._gc_counter = 0 def __str__(self): + self._gc() + now = self._now() ret = '' for key, (ts, count) in self._data.items(): @@ -86,6 +90,16 @@ class ExpiringCounter: def _now(self): return time.clock_gettime(time.CLOCK_BOOTTIME) + def _gc(self): + to_remove = [] + now = self._now() + for key, (ts, count) in self._data.items(): + if now - ts > self.default_timeout: + to_remove.append(key) + + for key in to_remove: + del self._data[key] + def inc(self, key, count = 1): now = self._now() @@ -97,6 +111,10 @@ class ExpiringCounter: elif key in self: del self[key] + self._gc_counter += 1 + if (self._gc_counter & ((1 << 10) - 1)) == 0: + self._gc() + return newval def dec(self, key, count = 1): |