forked from SETI/rms-webtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdscache.py
executable file
·1046 lines (786 loc) · 34.1 KB
/
pdscache.py
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import time
import random
try:
import pylibmc
MEMCACHED_LOADED = True
except ImportError:
MEMCACHED_LOADED = False
################################################################################
################################################################################
################################################################################
class PdsCache(object):
pass
################################################################################
################################################################################
################################################################################
class DictionaryCache(PdsCache):
def __init__(self, lifetime=86400, limit=1000, logger=None):
"""Constructor.
Input:
lifetime default lifetime in seconds; 0 for no expiration.
Can be a constant or a function; if the latter, then
the default lifetime must be returned by this call:
lifetime(value)
limit limit on the number of items in the cache. Permanent
objects do not count against this limit.
logger PdsLogger to use, optional.
"""
self.dict = {} # returns (value, expiration) by key
self.keys = set() # set of non-permanent keys
if type(lifetime).__name__ == 'function':
self.lifetime_func = lifetime
self.lifetime = None
else:
self.lifetime = lifetime
self.lifetime_func = None
self.limit = limit
self.slop = max(20, self.limit/10)
self.logger = logger
self.pauses = 0
self.preload_eligible = True
def _trim(self):
"""Trim the dictionary if it is too big."""
if len(self.keys) > self.limit + self.slop:
expirations = [(self.dict[k][1], k) for k in self.keys if
self.dict[k][1] is not None]
expirations.sort()
pairs = expirations[:-self.limit]
for (_, key) in pairs:
del self.dict[key]
self.keys.remove(key)
if self.logger:
self.logger.debug('%d items trimmed from DictionaryCache' %
len(pairs))
def _trim_if_necessary(self):
if self.pauses == 0:
self._trim()
def flush(self):
"""Flush any buffered items. Not used for DictionaryCache."""
return
def wait_for_unblock(self, funcname=''):
"""Pause until another process stops blocking, or until timeout."""
return
def wait_and_block(self, funcname=''):
"""Pause until another process stops blocking, or until timeout, and
then obtain the block."""
return
def unblock(self, flush=True):
"""Un-block processes from touching the cache. Not used by
DictionaryCache."""
return
def is_blocked(self):
"""Status of blocking. Not used by DictionaryCache."""
return False
def pause(self):
"""Increment the pause count. Trimming will resume when the count
returns to zero."""
self.pauses += 1
if self.pauses == 1 and self.logger:
self.logger.debug('DictionaryCache trimming paused')
@property
def is_paused(self):
"""Report on status of automatic trimming."""
return self.pauses > 0
def resume(self):
"""Decrement the pause count. Trimming will resume when the count
returns to zero."""
if self.pauses > 0:
self.pauses -= 1
if self.pauses == 0:
self._trim()
if self.logger:
self.logger.debug('DictionaryCache trimming resumed')
def __contains__(self, key):
"""Enable the "in" operator."""
return (key in self.dict)
def __len__(self):
"""Enable len() operator."""
return len(self.dict)
######## Get methods
def get(self, key):
"""Return the value associated with a key. Return None if the key is
missing."""
if key not in self.dict:
return None
(value, expiration) = self.dict[key]
if expiration is None:
return value
if expiration < time.time():
del self[key]
return None
return value
def __getitem__(self, key):
"""Enable dictionary syntax. Raise KeyError if the key is missing."""
value = self.get(key)
if value is None:
raise KeyError(key)
return value
def get_multi(self, keys):
"""Return a dictionary of multiple values based on a list of keys.
Missing keys do not appear in the returned dictionary."""
mydict = {}
for key in keys:
value = self[key]
if value is not None:
mydict[key] = value
return mydict
def get_local(self, key):
"""Return the value associated with a key, only using the local dict."""
return self.get(key)
def get_now(self, key):
"""Return the non-local value associated with a key."""
return self.get(key)
######## Set methods
def set(self, key, value, lifetime=None):
"""Set the value associated with a key.
lifetime the lifetime of this item in seconds; 0 for no expiration;
None to use the default lifetime.
"""
# Determine the expiration time
if lifetime is None:
if self.lifetime:
lifetime = self.lifetime
else:
lifetime = self.lifetime_func(value)
if lifetime == 0:
expiration = None
else:
expiration = time.time() + lifetime
# Save in the dictionary
self.dict[key] = (value, expiration)
if expiration:
self.keys.add(key)
# Trim if necessary
if not self.is_paused:
self._trim_if_necessary()
def __setitem__(self, key, value):
"""Enable dictionary syntax."""
self.set(key, value)
def set_multi(self, mydict, lifetime=0, pause=False):
"""Set multiple values at one time based on a dictionary."""
for (key, value) in mydict.items():
self.set(key, value, lifetime, pause=True)
if not pause:
self._trim_if_necessary()
return []
def set_local(self, key, value, lifetime=None):
"""Just like set() but always goes to the local dictionary without
touching the cache."""
return self.set(key, value, lifetime=lifetime)
######## Delete methods
def delete(self, key):
"""Delete one key. Return true if it was deleted, false otherwise."""
if key in self.dict:
del self.dict[key]
return True
return False
def __delitem__(self, key):
"""Enable the "del" operator. Raise KeyError if the key is absent."""
if key in self.dict:
del self.dict[key]
return
raise KeyError(key)
def delete_multi(self, keys):
"""Delete multiple items based on a list of keys. Keys not found in
the cache are ignored. Returns True if all keys were deleted."""
status = True
for key in keys:
if key in self.dict:
del self.dict[key]
else:
status = False
return status
def clear(self, block=False):
"""Clear all contents of the cache."""
self.dict.clear()
self.keys = set()
def replicate_clear(self, clear_count):
"""Clear the local cache if clear_count was incremented.
Return True if cache was cleared; False otherwise.
"""
return False
def replicate_clear_if_necessary(self):
"""Clear the local cache only if MemCache was cleared."""
return False
def was_cleared(self):
"""Returns True if the cache has been cleared."""
return False
################################################################################
################################################################################
################################################################################
MAX_BLOCK_SECONDS = 120.
class MemcachedCache(PdsCache):
def __init__(self, port=11211, lifetime=86400, logger=None):
"""Constructor.
Input:
port port number for the memcache, which must already
have been established. Alternatively, the absolute
path to a Unix socket.
lifetime default lifetime in seconds; 0 for no expiration.
Can be a constant or a function; if the latter, then
the default lifetime must be returned by
lifetime(self)
logger PdsLogger to use, optional.
"""
self.port = port
if type(port) == str:
self.mc = pylibmc.Client([port], binary=True)
else:
self.mc = pylibmc.Client(['127.0.0.1:%d' % port], binary=True)
if type(lifetime).__name__ == 'function':
self.lifetime_func = lifetime
self.lifetime = None
else:
self.lifetime = int(lifetime + 0.999)
self.lifetime_func = None
self.local_value_by_key = {}
self.local_lifetime_by_key = {}
self.local_keys_by_lifetime = {}
# local_values_by_key is an internal dictionary of values that have not
# yet been flushed to memcache.
# local_lifetime_by_key is an internal dictionary of their lifetimes in
# seconds, using the same key.
# local_keys_by_lifetime is the inverse dictionary, which returns a list
# of keys given a lifetime value.
self.pauses = 0
# This counter is incremented for every call to pause() and decremented
# by every call to resume(). Flushing will not occur unless this value
# is zero. Note that pauses can be nested, which is why it is a counter
# and not a flag.
self.permanent_values = {}
# This is an internal copy of all values that this thread has
# encountered lifetime == 0. It is used for extra protection in case
# memcache allows a permanent value to expire.
self.toobig_dict = {}
# Any object that triggers a "TooBig" error is stored inside this
# internal dictionary. It is not removed from memcached (if there)
# because other threads might still use it, but this thread will never
# again try to retrieve it from memcached. As a result, this dictionary
# has to be the first place to look for any key.
self.logger = logger
# Test the cache with a random key so as not to clobber existing keys
while True:
key = str(random.randint(0,10**40))
if key in self.mc:
continue
self.mc[key] = 1
del self.mc[key]
break
# Save the ID of this process
self.pid = os.getpid()
# Initialize cache as unblocked
ok_pid = self.mc.get('$OK_PID')
if ok_pid is None:
self.mc.set('$OK_PID', 0, time=0)
# When the cached value of '$OK_PID' is nonzero, it means that the
# thread with this process ID is currently blocking it.
# Get the current count of clear() events and save it internally
self.clear_count = self.mc.get('$CLEAR_COUNT')
if self.clear_count is None:
self.clear_count = 0
self.mc.set('$CLEAR_COUNT', 0, time=0)
# This is the internal copy of the cached value of '$CLEAR_COUNT'. When
# a thread clears the cache, this value is incremented. If this thread
# finds a cached value that differs from its internal value, it knows
# to clear its own contents.
def _wait_for_ok(self, funcname='', try_to_block=False):
"""Pause until another process stops blocking, or until timeout."""
was_blocked = False
broken_block = False
while True:
blocking_pid = self.mc.get('$OK_PID')
if blocking_pid in (0, self.pid):
break
was_blocked = True
unblock_time = time.time() + MAX_BLOCK_SECONDS
if self.logger:
if funcname:
self.logger.info(f'Process {self.pid} is blocked by ' +
f'{blocking_pid} at {funcname}() on ' +
f'MemcacheCache [{self.port}]')
else:
self.logger.info(f'Process {self.pid} is blocked by ' +
f'{blocking_pid} on ' +
f'MemcacheCache [{self.port}]')
while True:
time.sleep(0.5 * (1. + random.random())) # A random short delay
test_pid = self.mc.get('$OK_PID')
if test_pid != blocking_pid:
break
if time.time() > unblock_time:
new_pid = self.pid if try_to_block else 0
self.mc.set('$OK_PID', new_pid, time=0)
self.logger.warn(f'Process {self.pid} broke a block by ' +
f'{blocking_pid} on ' +
f'MemcacheCache [{self.port}]')
return True
if try_to_block and blocking_pid != self.pid:
self.mc.set('$OK_PID', self.pid, time=0)
return was_blocked
def wait_for_unblock(self, funcname=''):
"""Pause until another process stops blocking, or until timeout. True if
any wait was required."""
was_blocked = self._wait_for_ok(funcname=funcname, try_to_block=False)
if was_blocked and self.logger:
self.logger.info(f'Process {self.pid} is unblocked on ' +
f'MemcacheCache [{self.port}]')
return was_blocked
def wait_and_block(self, funcname=''):
"""Pause until another process stops blocking, or until timeout, and
then obtain the block. True if any wait was required."""
was_blocked = False
while True:
was_blocked |= self._wait_for_ok(funcname=funcname,
try_to_block=True)
test_pid = self.mc.get('$OK_PID')
if test_pid == self.pid:
if self.logger:
self.logger.info(f'Process {self.pid} is now blocking '
f'MemcachedCache [{self.port}]')
return was_blocked
self.logger.warn(f'Process {self.pid} was outraced by {test_pid} ' +
f'while waiting to block')
def unblock(self, flush=True):
"""Remove block preventing processes from touching the cache."""
test_pid = self.mc.get('$OK_PID')
if not test_pid:
if self.logger:
self.logger.error(f'Process {self.pid} is unable to unblock ' +
f'MemcachedCache [{self.port}]; ' +
f'Cache is already unblocked')
return
if test_pid != self.pid:
if self.logger:
self.logger.error(f'Process {self.pid} is unable to unblock ' +
f'MemcachedCache [{self.port}]; ' +
f'Cache is blocked by process {test_pid}')
return
self.mc.set('$OK_PID', 0, time=0)
if self.logger:
self.logger.info(f'Process {self.pid} removed block of ' +
f'MemcachedCache [{self.port}]')
if flush:
self.flush()
def is_blocked(self):
"""Status of blocking. 0 if unblocked; otherwise ID of process that is
now blocking."""
test_pid = self.mc.get('$OK_PID')
if test_pid is None: # repair a missing $OK_PID
self.mc.set('$OK_PID', 0, time=0)
test_pid = 0
if test_pid in (0, self.pid):
return 0
else:
return test_pid
def pause(self):
"""Increment the pause count. Flushing will resume when this count
returns to zero."""
self.pauses += 1
if self.pauses == 1 and self.logger:
self.logger.debug(f'Process {self.pid} has paused flushing on ' +
f'MemcachedCache [{self.port}]')
@property
def is_paused(self):
"""Report on status of automatic flushing for this thread."""
return self.pauses > 0
def resume(self):
"""Decrement the pause count. Flushing of this thread will resume when
the count returns to zero."""
if self.pauses > 0:
self.pauses -= 1
if self.pauses == 0:
if self.logger:
self.logger.debug(f'Process {self.pid} has resumed flushing ' +
f'on MemcachedCache [{self.port}]')
self.flush()
def __contains__(self, key):
"""Enable the "in" operator."""
if key in self.toobig_dict: return True
if key in self.local_value_by_key: return True
if key in self.permanent_values: return True
return key in self.mc
def __len__(self):
"""Enable len() operator."""
items = self.len_mc()
for key in self.toobig_dict:
if key not in self.mc:
items += 1
for key in self.local_value_by_key:
if key not in self.mc:
items += 1
return items
def len_mc(self):
return int(self.mc.get_stats()[0][1]['curr_items'])
######## Flush methods
def flush(self):
"""Flush any buffered items into the cache."""
# Nothing to do if local cache is empty
if len(self.local_value_by_key) == 0:
return
if self.replicate_clear_if_necessary():
return
# Save non-expiring values to the permanent dictionary
if 0 in self.local_keys_by_lifetime:
for k in self.local_keys_by_lifetime[0]:
self.permanent_values[k] = self.local_value_by_key[k]
self.wait_for_unblock('flush')
# Cache items grouped by lifetime
failures = []
toobigs = []
for lifetime in self.local_keys_by_lifetime:
# Save tuples (value, lifetime)
mydict = {k:(self.local_value_by_key[k], lifetime) for
k in self.local_keys_by_lifetime[lifetime]}
# Update to memcache
try:
self.mc.set_multi(mydict, time=lifetime)
except pylibmc.TooBig:
for (k,v) in mydict.items():
try:
self.mc.set(k, v, time=lifetime)
except pylibmc.TooBig:
toobigs.append(k)
failures.append(k)
self.toobig_dict[k] = v[0]
if self.logger:
self.logger.warn(f'TooBig error in process ' +
f'{self.pid}; ' +
f'saved to internal cache', k)
except pylibmc.Error as e:
if self.logger:
self.logger.exception(e)
keys = mydict.keys()
if self.logger:
keys.sort()
for key in keys:
self.logger.error(f'Process {self.pid} has failed ' +
f'to flush; deleted', key)
failures += keys
if self.logger:
count = len(self.local_keys_by_lifetime) - len(failures)
if count == 1:
desc = '1 item,'
else:
desc = str(count) + ' items, including'
self.logger.debug(f'Process {self.pid} has flushed {desc} ' +
list(mydict.keys())[0] +
f', to MemcachedCache [{self.port}]; ' +
f'current size is {self.len_mc()}')
if toobigs:
count = len(self.toobig_dict)
noun = 'item' if count == 1 else 'items'
self.logger.debug(f'Process {self.pid} now has {count} ' +
f'toobig {noun} cached locally')
# Clear internal dictionaries
self.local_lifetime_by_key.clear()
self.local_value_by_key.clear()
self.local_keys_by_lifetime.clear()
######## Get methods
def get(self, key):
"""Return the value associated with a key. Return None if the key is
missing."""
self.replicate_clear_if_necessary()
# Return from local caches if found
if key in self.toobig_dict:
return self.toobig_dict[key]
if key in self.local_value_by_key:
return self.local_value_by_key[key]
# Otherwise, go to memcache
self.wait_for_unblock('get')
pair = self.mc.get(key)
# Value not found...
if pair is None:
# Check the permanent dictionary in case it was wrongly deleted
if key in self.permanent_values:
self._restore_permanent_to_cache()
return self.permanent_values[key]
# Otherwise, return None
return None
(value, lifetime) = pair
# If this is a permanent value, update the local copy
if lifetime == 0:
self.permanent_values[key] = value
return value
def __getitem__(self, key):
"""Enable dictionary syntax. Raise KeyError if the key is missing."""
value = self.get(key)
if value is None:
raise KeyError(key)
return value
def get_multi(self, keys):
"""Return a dictionary of multiple values based on a list or set of
keys. Missing keys do not appear in the returned dictionary."""
self.replicate_clear_if_necessary()
# Separate keys into local, toobig, and non-local (in memcache)
nonlocal_keys = set(keys)
toobig_keys = set(self.toobig_dict.keys()) & nonlocal_keys
nonlocal_keys -= toobig_keys
local_keys = set(self.local_value_by_key.keys()) & nonlocal_keys
nonlocal_keys -= local_keys
# Retrieve non-local keys if any
if nonlocal_keys:
self.wait_for_unblock('get_multi')
# Memcached->get_multi hangs on long lists; individual requests work fine
# mydict = self.mc.get_multi(nonlocal_keys)
mydict = {}
for key in nonlocal_keys:
pair = self.mc.get(key)
if pair:
mydict[key] = pair
for (key, tuple) in mydict.items():
(value, lifetime) = tuple
mydict[key] = value
# Update the local copy of any permanent values
if lifetime == 0:
self.permanent_values[key] = value
# Check the permanent dictionary in case it was wrongly deleted
for key in nonlocal_keys:
if key in self.permanent_values and key not in mydict:
self._restore_permanent_to_cache()
break
else:
mydict = {}
# Augment the dictionary with the locally-cached values
for key in toobig_keys:
mydict[key] = self.toobig_dict[key]
for key in local_keys:
mydict[key] = self.local_value_by_key[key]
return mydict
def get_local(self, key):
"""Return the value associated with a key, only using the local dict."""
# Return from local cache if found
if key in self.toobig_dict:
return self.toobig_dict[key]
if key in self.local_value_by_key:
return self.local_value_by_key[key]
return None
def get_now(self, key):
"""Return the non-local value associated with a key, even if blocked."""
result = self.mc.get(key)
if result is None:
return None
(value, lifetime) = result
return value
######## Set methods
def set(self, key, value, lifetime=None):
"""Set a single value. Preserve a previously-defined lifetime if
lifetime is None."""
if key in self.toobig_dict:
self.toobig_dict[key] = value
return
if (lifetime is None) and (key not in self.local_lifetime_by_key):
try:
(_, lifetime) = self.mc[key]
except KeyError:
pass
self.set_local(key, value, lifetime)
if not self.is_paused:
self.flush()
return True
def __setitem__(self, key, value):
"""Enable dictionary syntax."""
_ = self.set(key, value, lifetime=None)
def set_multi(self, mydict, lifetime=None):
"""Set multiple values at one time based on a dictionary. Preserve a
previously-defined lifetime (and reset the clock) if lifetime is None.
"""
# Separate keys into local, toobig, and non-local (in memcache)
nonlocal_keys = set(mydict.keys())
toobig_keys = set(self.toobig_dict.keys()) & nonlocal_keys
nonlocal_keys -= toobig_keys
local_keys = set(self.local_value_by_key.keys()) & nonlocal_keys
nonlocal_keys -= local_keys
# Retrieve lifetimes from cache if necessary
if lifetime is None and nonlocal_keys:
nonlocal_dict = self.mc.get_multi(nonlocal_keys)
for (key, tuple) in nonlocal_dict:
lifetime = tuple[1]
self.local_lifetime_by_key[key] = lifetime
# Save or update values in local cache
for (key, value) in mydict.items():
if key in toobig_keys:
self.toobig_dict[key] = value
else:
self.set_local(key, value, lifetime)
if not self.is_paused:
self.flush()
return []
def set_local(self, key, value, lifetime=None):
"""Set or update a single value in the local cache. If lifetime is None,
it preserves the lifetime of any value already in the local cache. The
nonlocal cache is not checked."""
if key in self.toobig_dict:
self.toobig_dict[key] = value
return
# Save the value
self.local_value_by_key[key] = value
# Determine the lifetime
if lifetime is None:
try:
lifetime = self.local_lifetime_by_key[key]
except KeyError:
if self.lifetime:
lifetime = self.lifetime
else:
lifetime = int(self.lifetime_func(value) + 0.999)
# Remove an outdated key from the lifetime-to-keys dictionary
try:
prev_lifetime = self.local_lifetime_by_key[key]
if prev_lifetime != lifetime:
self.local_keys_by_lifetime[prev_lifetime].remove(key)
if len(self.local_keys_by_lifetime[prev_lifetime]) == 0:
del self.local_keys_by_lifetime[prev_lifetime]
except (KeyError, ValueError):
pass
# Insert the key into the lifetime-to-keys dictionary
if lifetime not in self.local_keys_by_lifetime:
self.local_keys_by_lifetime[lifetime] = [key]
elif key not in self.local_keys_by_lifetime[lifetime]:
self.local_keys_by_lifetime[lifetime].append(key)
# Insert the key into the key-to-lifetime dictionary
self.local_lifetime_by_key[key] = lifetime
######## Delete methods
def delete(self, key):
"""Delete one key. Return True if it was deleted, False otherwise."""
self.wait_for_unblock('delete')
status1 = self.mc.delete(key)
status2 = self._delete_local(key)
if key in self.permanent_values:
del self.permanent_values[key]
if key in self.toobig_dict:
del self.toobig_dict[key]
return status1 or status2
def __delitem__(self, key):
"""Enable the "del" operator. Raise KeyError if the key is absent."""
status = self.delete(key)
if status:
return
raise KeyError(key)
def delete_multi(self, keys):
"""Delete multiple items based on a list of keys. Keys not found in
the cache are ignored. Returns True if all keys were deleted."""
self.wait_for_unblock('delete_multi')
_ = self.mc.del_multi(keys)
# Save the current length
prev_len = len(self)
# Delete whatever we can from the local cache and permanent dictionary
for key in keys:
_ = self._del_local(key)
if key in self.permanent_values:
del self.permanent_values[key]
if key in self.toobig_dict:
del self.toobig_dict[key]
count = len(self) - prev_len
return (count == len(keys))
def _delete_local(self, key):
"""Delete a single key from the local cache, if present. The nonlocal
cache is not checked. Return True if deleted, False otherwise."""
deleted = False
if key in self.toobig_dict:
del self.toobig_dict[key]
deleted = True
if key in self.local_lifetime_by_key:
del self.local_value_by_key[key]
deleted = True
lifetime = self.local_lifetime_by_key[key]
self.local_keys_by_lifetime[lifetime].remove(key)
if len(self.local_keys_by_lifetime[lifetime]) == 0:
del self.local_keys_by_lifetime[lifetime]
del self.local_lifetime_by_key[key]
return deleted
def clear(self, block=False):
"""Clear all contents of the cache."""
if block:
self.wait_and_block('clear')
else:
self.wait_for_unblock('clear')
clear_count = max(self.mc.get('$CLEAR_COUNT'), self.clear_count) + 1
self.mc.flush_all()
self.mc.set_multi({'$OK_PID': self.pid, # retain block!
'$CLEAR_COUNT': clear_count}, time=0)
self.local_value_by_key.clear()
self.local_keys_by_lifetime.clear()
self.local_lifetime_by_key.clear()
self.permanent_values.clear()
self.toobig_dict.clear()
self.clear_count = clear_count
if self.logger:
self.logger.info(f'Process {self.pid} has set clear count to ' +
f'{self.clear_count} on ' +
f'MemcacheCache [{self.port}]')
if block:
if self.logger:
self.logger.info(f'Process {self.pid} has completed clear() ' +
f'of MemcacheCache [{self.port}] ' +
f'but continues to block')
else:
self.unblock()
def replicate_clear(self, clear_count):
"""Clear the local cache if clear_count was incremented.
Return True if cache was cleared; False otherwise.
"""
if clear_count == self.clear_count:
return False
if clear_count is None: # lost from memcache!
self.mc.set('$CLEAR_COUNT', clear_count, time=0)
return False
self.local_value_by_key.clear()
self.local_keys_by_lifetime.clear()
self.local_lifetime_by_key.clear()
self.permanent_values.clear()
self.toobig_dict.clear()
self.clear_count = clear_count
if self.logger:
self.logger.info(f'Process {self.pid} has replicated clear of ' +
f'MemcacheCache [{self.port}]')
return True
def replicate_clear_if_necessary(self):
"""Clear the local cache if MemCache was cleared by another process."""
clear_count = self.mc.get('$CLEAR_COUNT')
return self.replicate_clear(clear_count)
def was_cleared(self):
"""Returns True if the cache has been cleared."""
clear_count = self.mc.get('$CLEAR_COUNT')
return clear_count > self.clear_count
def _restore_permanent_to_cache(self):
"""Write every permanent value to the cache. This is triggered if any
permanent value disappears from memcache. It ensures that permanent
values are always in memcache."""