/
cmodule.py
1845 lines (1591 loc) · 75.8 KB
/
cmodule.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
"""Generate and compile C modules for Python,
"""
import atexit
import cPickle
import logging
import operator
import os
import re
import shutil
import stat
import StringIO
import subprocess
import sys
import tempfile
import time
import distutils.sysconfig
import numpy.distutils # TODO: TensorType should handle this
import theano
from theano.compat import PY3, b, next
from theano.gof.utils import flatten
from theano.configparser import config
from theano.gof.cc import hash_from_code
from theano.misc.windows import call_subprocess_Popen
# we will abuse the lockfile mechanism when reading and writing the registry
from theano.gof import compilelock
from theano.gof.compiledir import gcc_version_str, local_bitwidth
from theano.configparser import AddConfigVar, BoolParam
AddConfigVar('cmodule.mac_framework_link',
"If set to True, breaks certain MacOS installations with the infamous "
"Bus Error",
BoolParam(False))
AddConfigVar('cmodule.warn_no_version',
"If True, will print a warning when compiling one or more Op "
"with C code that can't be cached because there is no "
"c_code_cache_version() function associated to at least one of "
"those Ops.",
BoolParam(False),
in_c_key=False)
AddConfigVar('cmodule.remove_gxx_opt',
"If True, will remove the -O* parameter passed to g++."
"This is useful to debug in gdb modules compiled by Theano."
"The parameter -g is passed by default to g++",
BoolParam(False))
AddConfigVar('cmodule.compilation_warning',
"If True, will print compilation warnings.",
BoolParam(False))
_logger = logging.getLogger("theano.gof.cmodule")
_logger.setLevel(logging.WARNING)
METH_VARARGS = "METH_VARARGS"
METH_NOARGS = "METH_NOARGS"
class MissingGXX(Exception):
"""
This error is raised when we try to generate c code,
but g++ is not available
"""
pass
def debug_counter(name, every=1):
"""Debug counter to know how often we go through some piece of code.
This is a utility function one may use when debugging. Usage example:
debug_counter('I want to know how often I run this line')
"""
setattr(debug_counter, name, getattr(debug_counter, name, 0) + 1)
n = getattr(debug_counter, name)
if n % every == 0:
print >>sys.stderr, "debug_counter [%s]: %s" % (name, n)
class ExtFunction(object):
"""A C function to put into a DynamicModule """
name = ""
"""string - function's name"""
code_block = ""
"""string - the entire code for the function.
Has the form ``static PyObject* <name>([...]){ ... }
See Python's C API Reference for how to write c functions for python
modules.
"""
method = ""
"""
str - calling method for this function (i.e. 'METH_VARARGS', 'METH_NOARGS')
"""
doc = ""
"""str - documentation string for this function"""
def __init__(self, name, code_block, method, doc="undocumented"):
self.name = name
self.code_block = code_block
self.method = method
self.doc = doc
def method_decl(self):
"""
Returns the signature for this function.
It goes into the DynamicModule's method table.
"""
return '\t{"%s", %s, %s, "%s"}' % (
self.name, self.name, self.method, self.doc)
class DynamicModule(object):
def __init__(self, name=None):
assert name is None, ("The 'name' parameter of DynamicModule"
" cannot be specified anymore. Instead, 'code_hash'"
" will be automatically computed and can be used as"
" the module's name.")
# While the module is not finalized, we can call add_...
# when it is finalized, a hash is computed and used instead of
# the placeholder, and as module name.
self.finalized = False
self.code_hash = None
self.hash_placeholder = '<<<<HASH_PLACEHOLDER>>>>'
self.support_code = []
self.functions = []
self.includes = ["<Python.h>", "<iostream>"]
#TODO: this should come from TensorType
self.includes.append('<numpy/arrayobject.h>')
#TODO: from TensorType
self.init_blocks = ['import_array();']
def print_methoddef(self, stream):
print >> stream, "static PyMethodDef MyMethods[] = {"
for f in self.functions:
print >> stream, f.method_decl(), ','
print >> stream, "\t{NULL, NULL, 0, NULL}"
print >> stream, "};"
def print_init(self, stream):
if PY3:
print >> stream, """\
static struct PyModuleDef moduledef = {{
PyModuleDef_HEAD_INIT,
"{name}",
NULL,
-1,
MyMethods,
}};
""".format(name=self.hash_placeholder)
print >> stream, ("PyMODINIT_FUNC PyInit_%s(void) {" %
self.hash_placeholder)
for block in self.init_blocks:
print >> stream, ' ', block
print >> stream, " PyObject *m = PyModule_Create(&moduledef);"
print >> stream, " return m;"
else:
print >> stream, ("PyMODINIT_FUNC init%s(void){" %
self.hash_placeholder)
for block in self.init_blocks:
print >> stream, ' ', block
print >> stream, ' ', ('(void) Py_InitModule("%s", MyMethods);'
% self.hash_placeholder)
print >> stream, "}"
def add_include(self, str):
assert not self.finalized
self.includes.append(str)
def add_init_code(self, code):
assert not self.finalized
self.init_blocks.append(code)
def add_support_code(self, code):
assert not self.finalized
if code not in self.support_code: # TODO: KLUDGE
self.support_code.append(code)
def add_function(self, fn):
assert not self.finalized
self.functions.append(fn)
def code(self):
sio = StringIO.StringIO()
for inc in self.includes:
if not inc:
continue
if inc[0] == '<' or inc[0] == '"':
print >> sio, "#include", inc
else:
print >> sio, '#include "%s"' % inc
print >> sio, "//////////////////////"
print >> sio, "//// Support Code"
print >> sio, "//////////////////////"
for sc in self.support_code:
print >> sio, sc
print >> sio, "//////////////////////"
print >> sio, "//// Functions"
print >> sio, "//////////////////////"
for f in self.functions:
print >> sio, f.code_block
print >> sio, "//////////////////////"
print >> sio, "//// Module init"
print >> sio, "//////////////////////"
self.print_methoddef(sio)
self.print_init(sio)
rval = sio.getvalue()
self.code_hash = hash_from_code(rval)
rval = re.sub(self.hash_placeholder, self.code_hash, rval)
# Finalize the Module, so no support code or function
# can be added
self.finalized = True
return rval
def list_code(self, ofile=sys.stdout):
"""Print out the code with line numbers to `ofile` """
for i, line in enumerate(self.code().split('\n')):
print >> ofile, ('%4i' % (i + 1)), line
ofile.flush()
#TODO: add_type
def dlimport(fullpath, suffix=None):
"""Dynamically load a .so, .pyd, .dll, or .py file
:type fullpath: string
:param fullpath: a fully-qualified path do a compiled python module
:param suffix: a suffix to strip from the end of fullpath to get the
import name
:type suffix: string
:returns: the dynamically loaded module (from __import__)
"""
if not os.path.isabs(fullpath):
raise ValueError('`fullpath` must be an absolute path', fullpath)
if suffix is None:
if fullpath.endswith('.so'):
suffix = '.so'
elif fullpath.endswith('.pyd'):
suffix = '.pyd'
elif fullpath.endswith('.dll'):
suffix = '.dll'
elif fullpath.endswith('.py'):
suffix = '.py'
else:
suffix = ''
rval = None
if fullpath.endswith(suffix):
module_name = '.'.join(fullpath.split(os.path.sep)[-2:])[:-len(suffix)]
else:
raise ValueError('path has wrong suffix', (fullpath, suffix))
workdir = fullpath[:-len(module_name) - 1 - len(suffix)]
_logger.debug("WORKDIR %s", workdir)
_logger.debug("module_name %s", module_name)
sys.path[0:0] = [workdir] # insert workdir at beginning (temporarily)
try:
rval = __import__(module_name, {}, {}, [module_name])
if not rval:
raise Exception('__import__ failed', fullpath)
finally:
del sys.path[0]
assert fullpath.startswith(rval.__file__)
return rval
def dlimport_workdir(basedir):
"""
Return a directory where you should put your .so file for dlimport
to be able to load it, given a basedir which should normally be
config.compiledir
"""
return tempfile.mkdtemp(dir=basedir)
def last_access_time(path):
"""
Return the number of seconds since the epoch of the last access of a
given file.
"""
return os.stat(path)[stat.ST_ATIME]
def module_name_from_dir(dirname, err=True):
"""
Scan the contents of a cache directory and return full path of the
dynamic lib in it.
"""
files = os.listdir(dirname)
names = [file for file in files
if file.endswith('.so') or file.endswith('.pyd')]
if len(names) == 0 and not err:
return None
elif len(names) == 1:
return os.path.join(dirname, names[0])
else:
raise ValueError("More than 1 compiled module in this directory:" +
dirname)
def is_same_entry(entry_1, entry_2):
"""
Return True iff both paths can be considered to point to the same module.
This is the case if and only if at least one of these conditions holds:
- They are equal.
- Their real paths are equal.
- They share the same temporary work directory and module file name.
"""
if entry_1 == entry_2:
return True
if os.path.realpath(entry_1) == os.path.realpath(entry_2):
return True
if (os.path.basename(entry_1) == os.path.basename(entry_2) and
(os.path.basename(os.path.dirname(entry_1)) ==
os.path.basename(os.path.dirname(entry_2))) and
os.path.basename(os.path.dirname(entry_1)).startswith('tmp')):
return True
return False
def get_module_hash(src_code, key):
"""
Return an MD5 hash that uniquely identifies a module.
This hash takes into account:
1. The C source code of the module (`src_code`).
2. The version part of the key.
3. The compiler options defined in `key` (command line parameters and
libraries to link against).
4. The NumPy ABI version.
"""
# `to_hash` will contain any element such that we know for sure that if
# it changes, then the module hash should be different.
# We start with the source code itself (stripping blanks might avoid
# recompiling after a basic indentation fix for instance).
to_hash = map(str.strip, src_code.split('\n'))
# Get the version part of the key (ignore if unversioned).
if key[0]:
to_hash += map(str, key[0])
c_link_key = key[1]
# Currently, in order to catch potential bugs early, we are very
# convervative about the structure of the key and raise an exception
# if it does not match exactly what we expect. In the future we may
# modify this behavior to be less strict and be able to accomodate
# changes to the key in an automatic way.
# Note that if the key structure changes, the `get_safe_part` fucntion
# below may also need to be modified.
error_msg = ("This should not happen unless someone modified the code "
"that defines the CLinker key, in which case you should "
"ensure this piece of code is still valid (and this "
"AssertionError may be removed or modified to accomodate "
"this change)")
assert c_link_key[0] == 'CLinker.cmodule_key', error_msg
for key_element in c_link_key[1:]:
if isinstance(key_element, tuple):
# This should be the C++ compilation command line parameters or the
# libraries to link against.
to_hash += list(key_element)
elif isinstance(key_element, basestring):
if key_element.startswith('md5:'):
# This is the md5 hash of the config options. We can stop
# here.
break
elif (key_element.startswith('NPY_ABI_VERSION=0x') or
key_element.startswith('c_compiler_str=')):
to_hash.append(key_element)
else:
raise AssertionError(error_msg)
else:
raise AssertionError(error_msg)
return hash_from_code('\n'.join(to_hash))
def get_safe_part(key):
"""
Return a tuple containing a subset of `key`, to be used to find equal keys.
This tuple should only contain objects whose __eq__ and __hash__ methods
can be trusted (currently: the version part of the key, as well as the
md5 hash of the config options).
It is used to reduce the amount of key comparisons one has to go through
in order to find broken keys (i.e. keys with bad implementations of __eq__
or __hash__).
"""
version = key[0]
# This function should only be called on versioned keys.
assert version
# Find the md5 hash part.
c_link_key = key[1]
for key_element in c_link_key[1:]:
if (isinstance(key_element, basestring)
and key_element.startswith('md5:')):
md5 = key_element[4:]
break
return key[0] + (md5, )
class KeyData(object):
"""Used to store the key information in the cache."""
def __init__(self, keys, module_hash, key_pkl, entry):
"""
Constructor.
:param keys: Set of keys that are associated to the exact same module.
:param module_hash: Hash identifying the module (it should hash both
the code and the compilation options).
:param key_pkl: Path to the file in which this KeyData object should be
pickled.
"""
self.keys = keys
self.module_hash = module_hash
self.key_pkl = key_pkl
self.entry = entry
def add_key(self, key, save_pkl=True):
"""Add a key to self.keys, and update pickled file if asked to."""
assert key not in self.keys
self.keys.add(key)
if save_pkl:
self.save_pkl()
def remove_key(self, key, save_pkl=True):
"""Remove a key from self.keys, and update pickled file if asked to."""
self.keys.remove(key)
if save_pkl:
self.save_pkl()
def save_pkl(self):
"""
Dump this object into its `key_pkl` file.
May raise a cPickle.PicklingError if such an exception is raised at
pickle time (in which case a warning is also displayed).
"""
# Note that writing in binary mode is important under Windows.
try:
cPickle.dump(self, open(self.key_pkl, 'wb'),
protocol=cPickle.HIGHEST_PROTOCOL)
except cPickle.PicklingError:
_logger.warning("Cache leak due to unpickle-able key data %s",
self.keys)
os.remove(self.key_pkl)
raise
def get_entry(self):
"""Return path to the module file."""
# TODO This method may be removed in the future (e.g. in 0.5) since
# its only purpose is to make sure that old KeyData objects created
# before the 'entry' field was added are properly handled.
if not hasattr(self, 'entry'):
self.entry = module_name_from_dir(os.path.dirname(self.key_pkl))
return self.entry
def delete_keys_from(self, entry_from_key, do_manual_check=True):
"""
Delete from entry_from_key all keys associated to this KeyData object.
Note that broken keys will not appear in the keys field, so we also
manually look for keys associated to the same entry, unless
do_manual_check is False.
"""
entry = self.get_entry()
for key in self.keys:
del entry_from_key[key]
if do_manual_check:
to_del = []
for key, key_entry in entry_from_key.iteritems():
if key_entry == entry:
to_del.append(key)
for key in to_del:
del entry_from_key[key]
class ModuleCache(object):
"""Interface to the cache of dynamically compiled modules on disk
Note that this interface does not assume exclusive use of the cache
directory. It is built to handle the case where multiple programs are also
using instances of this class to manage the same directory.
The cache works on the basis of keys. Each key is mapped to only one
dynamic module, but multiple keys may be mapped to the same module (see
below for details). Each module is a dynamic library file, that Python
can import.
The cache contains one directory for each module, containing:
- the dynamic library file itself (.so/.pyd),
- an empty __init__.py file, so Python can import it,
- a file containing the source code for the module (mod.cpp/mod.cu),
- a key.pkl file, containing a KeyData object with all the keys
associated with that module,
- possibly a delete.me file, meaning this directory has been marked
for deletion.
Keys should be tuples of length 2: (version, rest). The
``rest`` can be anything hashable and picklable, that uniquely
identifies the computation in the module. The key is returned by
``CLinker.cmodule_key_``.
The ``version`` should be a hierarchy of tuples of integers.
If the ``version`` is either 0 or (), then the key is unversioned, and its
corresponding module will be marked for deletion in an atexit() handler.
If the ``version`` is neither 0 nor (), then the module will be kept in the
cache between processes.
An unversioned module is not always deleted by the process that
creates it. Deleting such modules may not work on NFS filesystems
because the tmpdir in which the library resides is in use until the
end of the process' lifetime. In this case, unversioned modules
are left in their tmpdirs without corresponding .pkl files. These
modules and their directories are erased by subsequent processes'
refresh() functions.
Two different keys are mapped to the same module when all conditions below
are met:
- They have the same version.
- They share the same compilation options in their ``rest`` part (see
``CLinker.cmodule_key_`` for how this part is built).
- They share the same C code.
These three elements uniquely identify a module, and are summarized
in a single "module hash".
"""
dirname = ""
"""The working directory that is managed by this interface"""
module_from_name = {}
"""maps a module filename to the loaded module object"""
entry_from_key = {}
"""Maps keys to the filename of a .so/.pyd.
"""
similar_keys = {}
"""Maps a part-of-key to all keys that share this same part."""
module_hash_to_key_data = {}
"""Maps a module hash to its corresponding KeyData object."""
stats = []
"""
A list with counters for the number of hits, loads, compiles issued by
module_from_key()
"""
loaded_key_pkl = set()
"""set of all key.pkl files that have been loaded.
"""
def __init__(self, dirname, check_for_broken_eq=True, do_refresh=True):
"""
:param check_for_broken_eq: A bad __eq__ implementation can break this
cache mechanism. This option turns on a not-too-expensive sanity check
every time a new key is added to the cache.
:param do_refresh: If True, then the ``refresh`` method will be called
in the constructor.
"""
self.dirname = dirname
self.module_from_name = dict(self.module_from_name)
self.entry_from_key = dict(self.entry_from_key)
self.module_hash_to_key_data = dict(self.module_hash_to_key_data)
self.similar_keys = dict(self.similar_keys)
self.stats = [0, 0, 0]
self.check_for_broken_eq = check_for_broken_eq
self.loaded_key_pkl = set()
self.time_spent_in_check_key = 0
if do_refresh:
self.refresh()
age_thresh_use = 60 * 60 * 24 * 24 # 24 days
"""
The default age threshold (in seconds) for cache files we want to use.
Older modules will be deleted in ``clear_old``.
"""
def refresh(self, age_thresh_use=None, delete_if_problem=False):
"""Update cache data by walking the cache directory structure.
Load key.pkl files that have not been loaded yet.
Remove entries which have been removed from the filesystem.
Also, remove malformed cache directories.
:param age_thresh_use: Do not use modules olther than this.
Defaults to self.age_thresh_use.
:param delete_if_problem: If True, cache entries that meet one of those
two conditions are deleted:
- Those for which unpickling the KeyData file fails with an
unknown exception.
- Duplicated modules, regardless of their age.
:returns: a list of modules of age higher than age_thresh_use.
"""
if age_thresh_use is None:
age_thresh_use = self.age_thresh_use
start_time = time.time()
too_old_to_use = []
compilelock.get_lock()
try:
# add entries that are not in the entry_from_key dictionary
time_now = time.time()
# Go through directories in alphabetical order to ensure consistent
# behavior.
root_dirs_files = sorted(os.walk(self.dirname),
key=operator.itemgetter(0))
for root, dirs, files in root_dirs_files:
key_pkl = os.path.join(root, 'key.pkl')
if key_pkl in self.loaded_key_pkl:
continue
elif 'delete.me' in files or not files:
_rmtree(root, ignore_nocleanup=True,
msg="delete.me found in dir")
elif 'key.pkl' in files:
try:
entry = module_name_from_dir(root)
except ValueError: # there is a key but no dll!
if not root.startswith("/tmp"):
# Under /tmp, file are removed periodically by the
# os. So it is normal that this happens from time
# to time.
_logger.warning("ModuleCache.refresh() Found key "
"without dll in cache, deleting it. %s",
key_pkl)
_rmtree(root, ignore_nocleanup=True,
msg="missing module file", level=logging.INFO)
continue
if (time_now - last_access_time(entry)) < age_thresh_use:
_logger.debug('refresh adding %s', key_pkl)
def unpickle_failure():
_logger.info("ModuleCache.refresh() Failed to "
"unpickle cache file %s", key_pkl)
try:
key_data = cPickle.load(open(key_pkl, 'rb'))
except EOFError:
# Happened once... not sure why (would be worth
# investigating if it ever happens again).
unpickle_failure()
_rmtree(root, ignore_nocleanup=True,
msg='broken cache directory [EOF]',
level=logging.WARNING)
continue
except ValueError:
# This can happen when we have bad config value
# in the cuda.nvcc_compiler.py file.
# We should not hide it here, as this will cause
# an unrelated error to appear.
raise
except Exception:
unpickle_failure()
if delete_if_problem:
_rmtree(root, ignore_nocleanup=True,
msg='broken cache directory',
level=logging.INFO)
else:
# This exception is often triggered by keys
# that contain references to classes that have
# not yet been imported (e.g. when running two
# different Theano-based scripts). They are not
# necessarily broken, but we cannot load them
# here.
pass
continue
if not isinstance(key_data, KeyData):
# This is some old cache data, that does not fit
# the new cache format. It would be possible to
# update it, but it is not entirely safe since we
# do not know the config options that were used.
# As a result, we delete it instead (which is also
# simpler to implement).
_rmtree(root, ignore_nocleanup=True,
msg=(
'invalid cache entry format -- this '
'should not happen unless your cache '
'was really old'),
level=logging.WARN)
continue
# Check the path to the module stored in the KeyData
# object matches the path to `entry`. There may be
# a mismatch e.g. due to symlinks, or some directory
# being renamed since last time cache was created.
kd_entry = key_data.get_entry()
if kd_entry != entry:
if is_same_entry(entry, kd_entry):
# Update KeyData object. Note that we also need
# to update the key_pkl field, because it is
# likely to be incorrect if the entry itself
# was wrong.
key_data.entry = entry
key_data.key_pkl = key_pkl
else:
# This is suspicious. Better get rid of it.
_rmtree(root, ignore_nocleanup=True,
msg='module file path mismatch',
level=logging.INFO)
continue
# Find unversioned keys from other processes.
# TODO: check if this can happen at all
to_del = [key for key in key_data.keys if not key[0]]
if to_del:
_logger.warning(
"ModuleCache.refresh() Found unversioned "
"key in cache, removing it. %s", key_pkl)
# Since the version is in the module hash, all
# keys should be unversioned.
if len(to_del) != len(key_data.keys):
_logger.warning(
'Found a mix of unversioned and '
'versioned keys for the same '
'module %s', key_pkl)
_rmtree(root, ignore_nocleanup=True,
msg="unversioned key(s) in cache",
level=logging.INFO)
continue
mod_hash = key_data.module_hash
if mod_hash in self.module_hash_to_key_data:
# This may happen when two processes running
# simultaneously compiled the same module, one
# after the other. We delete one once it is old
# enough (to be confident there is no other process
# using it), or if `delete_if_problem` is True.
# Note that it is important to walk through
# directories in alphabetical order so as to make
# sure all new processes only use the first one.
age = time.time() - last_access_time(entry)
if delete_if_problem or age > self.age_thresh_del:
_rmtree(root, ignore_nocleanup=True,
msg='duplicated module',
level=logging.DEBUG)
else:
_logger.debug('Found duplicated module not '
'old enough yet to be deleted '
'(age: %s): %s',
age, entry)
continue
# Remember the map from a module's hash to the KeyData
# object associated with it.
self.module_hash_to_key_data[mod_hash] = key_data
for key in key_data.keys:
if key not in self.entry_from_key:
self.entry_from_key[key] = entry
# Assert that we have not already got this
# entry somehow.
assert entry not in self.module_from_name
# Store safe part of versioned keys.
if key[0]:
self.similar_keys.setdefault(
get_safe_part(key),
[]).append(key)
else:
_logger.warning(
"The same cache key is associated to "
"different modules (%s and %s). This "
"is not supposed to happen! You may "
"need to manually delete your cache "
"directory to fix this.",
self.entry_from_key[key],
entry)
# Clean up the name space to prevent bug.
if key_data.keys:
del key
self.loaded_key_pkl.add(key_pkl)
else:
too_old_to_use.append(entry)
# If the compilation failed, no key.pkl is in that
# directory, but a mod.* should be there.
# We do nothing here.
# Clean up the name space to prevent bug.
if root_dirs_files:
del root, dirs, files
# Remove entries that are not in the filesystem.
items_copy = list(self.module_hash_to_key_data.iteritems())
for module_hash, key_data in items_copy:
entry = key_data.get_entry()
try:
# Test to see that the file is [present and] readable.
open(entry).close()
gone = False
except IOError:
gone = True
if gone:
# Assert that we did not have one of the deleted files
# loaded up and in use.
# If so, it should not have been deleted. This should be
# considered a failure of the OTHER process, that deleted
# it.
if entry in self.module_from_name:
_logger.warning("A module that was loaded by this "
"ModuleCache can no longer be read from file "
"%s... this could lead to problems.",
entry)
del self.module_from_name[entry]
_logger.info("deleting ModuleCache entry %s", entry)
key_data.delete_keys_from(self.entry_from_key)
del self.module_hash_to_key_data[module_hash]
if key_data.keys and list(key_data.keys)[0][0]:
# this is a versioned entry, so should have been on
# disk. Something weird happened to cause this, so we
# are responding by printing a warning, removing
# evidence that we ever saw this mystery key.
pkl_file_to_remove = key_data.key_pkl
if not key_data.key_pkl.startswith("/tmp"):
# Under /tmp, file are removed periodically by the
# os. So it is normal that this happen from time to
# time.
_logger.warning("Removing key file %s because the "
"corresponding module is gone from the "
"file system.",
pkl_file_to_remove)
self.loaded_key_pkl.remove(pkl_file_to_remove)
finally:
compilelock.release_lock()
_logger.debug('Time needed to refresh cache: %s',
(time.time() - start_time))
return too_old_to_use
def module_from_key(self, key, fn=None, keep_lock=False, key_data=None):
"""
:param fn: A callable object that will return an iterable object when
called, such that the first element in this iterable object is the
source code of the module, and the last element is the module itself.
`fn` is called only if the key is not already in the cache, with
a single keyword argument `location` that is the path to the directory
where the module should be compiled.
:param key_data: If not None, it should be a KeyData object and the
key parameter should be None. In this case, we use the info from the
KeyData object to recover the module, rather than the key itself. Note
that this implies the module already exists (and may or may not have
already been loaded).
"""
# We should only use one of the two ways to get a module.
assert key_data is None or key is None
rval = None
if key is not None:
try:
_version, _rest = key
except (TypeError, ValueError):
raise ValueError(
"Invalid key. key must have form (version, rest)", key)
name = None
if key is not None and key in self.entry_from_key:
# We have seen this key either in this process or previously.
name = self.entry_from_key[key]
elif key_data is not None:
name = key_data.get_entry()
if name is not None:
# This is an existing module we can recover.
if name not in self.module_from_name:
_logger.debug('loading name %s', name)
self.module_from_name[name] = dlimport(name)
self.stats[1] += 1
else:
self.stats[0] += 1
_logger.debug('returning compiled module from cache %s', name)
rval = self.module_from_name[name]
else:
hash_key = hash(key)
key_data = None
# We have never seen this key before.
# We acquire the lock later only if we were able to
# generate C code. Otherwise, we would take the lock for ops
# that have only a perform().
lock_taken = False
# This try/finally block ensures that the lock is released once we
# are done writing in the cache file or after raising an exception.
try:
# Embedding two try statements for Python 2.4 compatibility
# (cannot do try / except / finally).
try:
location = dlimport_workdir(self.dirname)
except OSError, e:
_logger.error(e)
if e.errno == 31:
_logger.error('There are %i files in %s',
len(os.listdir(config.compiledir)),
config.compiledir)
raise
try:
compile_steps = fn(location=location).__iter__()
# Check if we already know a module with the same hash.
# If we do, then there is no need to even compile it.
duplicated_module = False
# The first compilation step is to yield the source code.
src_code = next(compile_steps)
module_hash = get_module_hash(src_code, key)
# The op has c_code, so take the lock.
compilelock.get_lock()
lock_taken = True
if not os.path.exists(location):
# Temporary fix, we should make sure it don't
# get deleted by the clear*() fct.
os.makedirs(location)
if module_hash in self.module_hash_to_key_data:
_logger.debug("Duplicated module! Will re-use the "
"previous one")
duplicated_module = True
# Load the already existing module.
key_data = self.module_hash_to_key_data[module_hash]
# Note that we do not pass the `fn` argument, since it
# should not be used considering that the module should
# already be compiled.
module = self.module_from_key(key=None,
key_data=key_data)
name = module.__file__
# Add current key to the set of keys associated to the
# same module. We only save the KeyData object of
# versioned modules.
try:
key_data.add_key(key, save_pkl=bool(_version))
key_broken = False
except cPickle.PicklingError:
# This should only happen if we tried to save the
# pickled file.
assert _version
# The key we are trying to add is broken: we will
# not add it after all.
key_data.remove_key(key)
key_broken = True
if (_version and not key_broken and
self.check_for_broken_eq):
self.check_key(key, key_data.key_pkl)
# We can delete the work directory.
_rmtree(location, ignore_nocleanup=True,
msg='temporary workdir of duplicated module')
else:
# Will fail if there is an error compiling the C code.
# The exception will be caught and the work dir will be
# deleted.
while True:
try:
# The module should be returned by the last
# step of the compilation.
module = next(compile_steps)
except StopIteration:
break
# Obtain path to the '.so' module file.
name = module.__file__
_logger.debug("Adding module to cache %s %s",
key, name)