-
Notifications
You must be signed in to change notification settings - Fork 5
/
module_manager.py
1694 lines (1336 loc) · 66.8 KB
/
module_manager.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
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import ConfigParser
import sys, os, fnmatch
import re
import copy
import gen_utils
import glob
from meta_module import MetaModule
import modules
import mutex
from random import choice
from module_base import DefaultConfigClass
import time
import types
import traceback
# some notes with regards to extra module state/logic required for scheduling
# * in general, execute_module()/transfer_output()/etc calls do exactly that
# when called, i.e. they don't automatically cache. The scheduler should
# take care of caching by making the necessary isModified() or
# shouldTransfer() calls. The reason for this is so that the module
# actions can be forced
#
# notes with regards to execute on change:
# * devide.py should register a "change" handler with the ModuleManager.
# I've indicated places with "execute on change" where I think this
# handler should be invoked. devide.py can then invoke the scheduler.
#########################################################################
class ModuleManagerException(Exception):
pass
#########################################################################
class ModuleSearch:
"""Class for doing relative fast searches through module metadata.
@author Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self):
# dict of dicts of tuple, e.g.:
# {'isosurface' : {('contour', 'keywords') : 1,
# ('marching', 'help') : 1} ...
self.search_dict = {}
self.previous_partial_text = ''
self.previous_results = None
def build_search_index(self, available_modules, available_segments):
"""Build search index given a list of available modules and segments.
@param available_modules: available modules dictionary from module
manager with module metadata classes as values.
@param available_segments: simple list of segments.
"""
self.search_dict.clear()
def index_field(index_name, mi_class, field_name, split=False):
try:
field = getattr(mi_class, field_name)
except AttributeError:
pass
else:
if split:
iter_list = field.split()
else:
iter_list = field
for w in iter_list:
wl = w.lower()
if wl not in self.search_dict:
self.search_dict[wl] = {(index_name,
field_name) : 1}
else:
self.search_dict[wl][(index_name,
field_name)] = 1
for module_name in available_modules:
mc = available_modules[module_name]
index_name = 'module:%s' % (module_name,)
short_module_name = mc.__name__.lower()
if short_module_name not in self.search_dict:
self.search_dict[short_module_name] = {(index_name, 'name') :
1}
else:
# we don't have to increment, there can be only one unique
# complete module_name
self.search_dict[short_module_name][(index_name, 'name')] = 1
index_field(index_name, mc, 'keywords')
index_field(index_name, mc, 'help', True)
for segment_name in available_segments:
index_name = 'segment:%s' % (segment_name,)
# segment name's are unique by definition (complete file names)
self.search_dict[segment_name] = {(index_name, 'name') : 1}
def find_matches(self, partial_text):
"""Do partial text (containment) search through all module names,
help and keywords.
Simple caching is currently done. Each space-separated word in
partial_text is searched for and results are 'AND'ed.
@returns: a list of unique tuples consisting of (modulename,
where_found) where where_found is 'name', 'keywords' or 'help'
"""
# cache results in case the user asks for exactly the same
if partial_text == self.previous_partial_text:
return self.previous_results
partial_words = partial_text.lower().split()
# dict mapping from full.module.name -> {'where_found' : 1, 'wf2' : 1}
# think about optimising this with a bit mask rather; less flexible
# but saves space and is at least as fast.
def find_one_word(search_word):
"""Searches for all partial / containment matches with
search_word.
@returns: search_results dict mapping from module name to
dictionary with where froms as keys and 1s as values.
"""
search_results = {}
for w in self.search_dict:
if w.find(search_word) >= 0:
# we can have partial matches with more than one key
# returning the same location, so we stuff results in a
# dict too to consolidate results
for k in self.search_dict[w].keys():
# k[1] is where_found, k[0] is module_name
if k[0] not in search_results:
search_results[k[0]] = {k[1] : 1}
else:
search_results[k[0]][k[1]] = 1
return search_results
# search using each of the words in the given list
search_results_list = []
for search_word in partial_words:
search_results_list.append(find_one_word(search_word))
# if more than one word, combine the results;
# a module + where_from result is only shown if ALL words occur in
# that specific module + where_from.
sr0 = search_results_list[0]
srl_len = len(search_results_list)
if srl_len > 1:
# will create brand-new combined search_results dict
search_results = {}
# iterate through all module names in the first word's results
for module_name in sr0:
# we will only process a module_name if it occurs in the
# search results of ALL search words
all_found = True
for sr in search_results_list[1:]:
if module_name not in sr:
all_found = False
break
# now only take results where ALL search words occur
# in the same where_from of a specific module
if all_found:
temp_finds = {}
for sr in search_results_list:
# sr[module_name] is a dict with where_founds as keys
# by definition (dictionary) all where_founds are
# unique per sr[module_name]
for i in sr[module_name].keys():
if i in temp_finds:
temp_finds[i] += 1
else:
temp_finds[i] = 1
# extract where_froms for which the number of hits is
# equal to the number of words.
temp_finds2 = [wf for wf in temp_finds.keys() if
temp_finds[wf] == srl_len]
# make new dictionary from temp_finds2 list as keys,
# 1 as value
search_results[module_name] = dict.fromkeys(temp_finds2,1)
else:
# only a single word was searched for.
search_results = sr0
self.previous_partial_text = partial_text
rl = search_results
self.previous_results = rl
return rl
#########################################################################
class PickledModuleState:
def __init__(self):
self.module_config = DefaultConfigClass()
# e.g. modules.Viewers.histogramSegment
self.module_name = None
# this is the unique name of the module, e.g. dvm15
self.instance_name = None
#########################################################################
class PickledConnection:
def __init__(self, source_instance_name=None, output_idx=None,
target_instance_name=None, input_idx=None, connection_type=None):
self.source_instance_name = source_instance_name
self.output_idx = output_idx
self.target_instance_name = target_instance_name
self.input_idx = input_idx
self.connection_type = connection_type
#########################################################################
class ModuleManager:
"""This class in responsible for picking up new modules in the modules
directory and making them available to the rest of the program.
@todo: we should split this functionality into a ModuleManager and
networkManager class. One ModuleManager per processing node,
global networkManager to coordinate everything.
@todo: ideally, ALL module actions should go via the MetaModule.
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, devide_app):
"""Initialise module manager by fishing .py devide modules from
all pertinent directories.
"""
self._devide_app = devide_app
# module dictionary, keyed on instance... cool.
# values are MetaModules
self._module_dict = {}
appdir = self._devide_app.get_appdir()
self._modules_dir = os.path.join(appdir, 'modules')
#sys.path.insert(0,self._modules_dir)
self._userModules_dir = os.path.join(appdir, 'userModules')
############################################################
# initialise module Kits - Kits are collections of libraries
# that modules can depend on. The Kits also make it possible
# for us to write hooks for when these libraries are imported
import module_kits
module_kits.load(self)
# binding to module that can be used without having to do
# import module_kits
self.module_kits = module_kits
##############################################################
self.module_search = ModuleSearch()
# make first scan of available modules
self.scan_modules()
# auto_execute mode, still need to link this up with the GUI
self.auto_execute = True
# this is a list of modules that have the ability to start a network
# executing all by themselves and usually do... when we break down
# a network, we should take these out first. when we build a network
# we should put them down last
# slice3dVWRs must be connected LAST, histogramSegment second to last
# and all the rest before them
self.consumerTypeTable = {'slice3dVWR' : 5,
'histogramSegment' : 4}
# we'll use this to perform mutex-based locking on the progress
# callback... (there SHOULD only be ONE ModuleManager instance)
self._inProgressCallback = mutex.mutex()
def refresh_module_kits(self):
"""Go through list of imported module kits, reload each one, and
also call its refresh() method if available.
This means a kit author can work on a module_kit and just refresh
when she wants her changes to be available. However, the kit must
have loaded successfully at startup, else no-go.
"""
for module_kit in self.module_kits.module_kit_list:
kit = getattr(self.module_kits, module_kit)
try:
refresh_method = getattr(kit, "refresh")
except AttributeError:
pass
else:
try:
reload(kit)
refresh_method()
except Exception, e:
self._devide_app.log_error_with_exception(
'Unable to refresh module_kit %s: '
'%s. Continuing...' %
(module_kit, str(e)))
else:
self.set_progress(100, 'Refreshed %s.' % (module_kit,))
def close(self):
"""Iterates through each module and closes it.
This is only called during devide application shutdown.
"""
self.delete_all_modules()
def delete_all_modules(self):
"""Deletes all modules.
This is usually only called during the offline mode of operation. In
view mode, the GraphEditor takes care of the deletion of all networks.
"""
# this is fine because .items() makes a copy of the dict
for mModule in self._module_dict.values():
print "Deleting %s (%s) >>>>>" % \
(mModule.instance_name,
mModule.instance.__class__.__name__)
try:
self.delete_module(mModule.instance)
except Exception, e:
# we can't allow a module to stop us
print "Error deleting %s (%s): %s" % \
(mModule.instance_name,
mModule.instance.__class__.__name__,
str(e))
print "FULL TRACE:"
traceback.print_exc()
def apply_module_view_to_logic(self, instance):
"""Interface method that can be used by clients to transfer module
view to underlying logic.
This is called by module_utils (the ECASH button handlers) and thunks
through to the relevant MetaModule call.
"""
mModule = self._module_dict[instance]
try:
# these two MetaModule wrapper calls will take care of setting
# the modified flag / time correctly
if self._devide_app.view_mode:
# only in view mode do we call this transfer
mModule.view_to_config()
mModule.config_to_logic()
# we round-trip so that view variables that are dependent on
# the effective changes to logic and/or config can update
instance.logic_to_config()
if self._devide_app.view_mode:
instance.config_to_view()
except Exception, e:
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
def sync_module_logic_with_config(self, instance):
"""Method that should be called during __init__ for all (view and
non-view) modules, after the config structure has been set.
In the view() method, or after having setup the view in view-modules,
also call syncModuleViewWithLogic()
"""
instance.config_to_logic()
instance.logic_to_config()
def sync_module_view_with_config(self, instance):
"""If DeVIDE is in view model, transfor config information to view
and back again. This is called AFTER sync_module_logic_with_config(),
usually in the module view() method after createViewFrame().
"""
if self._devide_app.view_mode:
# in this case we don't round trip, view shouldn't change
# things that affect the config.
instance.config_to_view()
def sync_module_view_with_logic(self, instance):
"""Interface method that can be used by clients to transfer config
information from the underlying module logic (model) to the view.
At the moment used by standard ECASH handlers.
"""
try:
instance.logic_to_config()
# we only do the view transfer if DeVIDE is in the correct mode
if self._devide_app.view_mode:
instance.config_to_view()
except Exception, e:
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
syncModuleViewWithLogic = sync_module_view_with_logic
def blockmodule(self, meta_module):
meta_module.blocked = True
def unblockmodule(self, meta_module):
meta_module.blocked = False
def log_error(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_error(message)
def log_error_list(self, message_list):
self._devide_app.log_error_list(message_list)
def log_error_with_exception(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_error_with_exception(message)
def log_info(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_info(message)
def log_message(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_message(message)
def log_warning(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_warning(message)
def scan_modules(self):
"""(Re)Check the modules directory for *.py files and put them in
the list self.module_files.
"""
# this is a dict mapping from full module name to the classes as
# found in the module_index.py files
self._available_modules = {}
appDir = self._devide_app.get_appdir()
# module path without trailing slash
modulePath = self.get_modules_dir()
# search through modules hierarchy and pick up all module_index files
####################################################################
module_indices = []
def miwFunc(arg, dirname, fnames):
"""arg is top-level module path.
"""
module_path = arg
for fname in fnames:
mi_full_name = os.path.join(dirname, fname)
if not fnmatch.fnmatch(fname, 'module_index.py'):
continue
# e.g. /viewers/module_index
mi2 = os.path.splitext(
mi_full_name.replace(module_path, ''))[0]
# e.g. .viewers.module_index
mim = mi2.replace(os.path.sep, '.')
# remove . before
if mim.startswith('.'):
mim = mim[1:]
# special case: modules in the central devide
# module dir should be modules.viewers.module_index
# this is mostly for backward compatibility
if module_path == modulePath:
mim = 'modules.%s' % (mim)
module_indices.append(mim)
os.path.walk(modulePath, miwFunc, arg=modulePath)
for emp in self.get_app_main_config().extra_module_paths:
# make sure there are no extra spaces at the ends, as well
# as normalize and absolutize path (haha) for this
# platform
emp = os.path.abspath(emp.strip())
if emp and os.path.exists(emp):
# make doubly sure we only process an EMP if it's
# really there
if emp not in sys.path:
sys.path.insert(0,emp)
os.path.walk(emp, miwFunc, arg=emp)
# iterate through the moduleIndices, building up the available
# modules list.
import module_kits # we'll need this to check available kits
failed_mis = {}
for mim in module_indices:
# mim is importable module_index spec, e.g.
# modules.viewers.module_index
# if this thing was imported before, we have to remove it, else
# classes that have been removed from the module_index file
# will still appear after the reload.
if mim in sys.modules:
del sys.modules[mim]
try:
# now we can import
__import__(mim, globals(), locals())
except Exception, e:
# make a list of all failed moduleIndices
failed_mis[mim] = sys.exc_info()
msgs = gen_utils.exceptionToMsgs()
# and log them as mesages
self._devide_app.log_info(
'Error loading %s: %s.' % (mim, str(e)))
for m in msgs:
self._devide_app.log_info(m.strip(), timeStamp=False)
# we don't want to throw an exception here, as that would
# mean that a singe misconfigured module_index file can
# prevent the whole scan_modules process from completing
# so we'll report on errors here and at the end
else:
# reload, as this could be a run-time rescan
m = sys.modules[mim]
reload(m)
# find all classes in the imported module
cs = [a for a in dir(m)
if type(getattr(m,a)) == types.ClassType]
# stuff these classes, keyed on the module name that they
# represent, into the modules list.
for a in cs:
# a is the name of the class
c = getattr(m,a)
module_deps = True
for kit in c.kits:
if kit not in module_kits.module_kit_list:
module_deps = False
break
if module_deps:
module_name = mim.replace('module_index', a)
self._available_modules[module_name] = c
# we should move this functionality to the graphEditor. "segments"
# are _probably_ only valid there... alternatively, we should move
# the concept here
segmentList = []
def swFunc(arg, dirname, fnames):
segmentList.extend([os.path.join(dirname, fname)
for fname in fnames
if fnmatch.fnmatch(fname, '*.dvn')])
os.path.walk(os.path.join(appDir, 'segments'), swFunc, arg=None)
# this is purely a list of segment filenames
self.availableSegmentsList = segmentList
# self._available_modules is a dict keyed on module_name with
# module description class as value
self.module_search.build_search_index(self._available_modules,
self.availableSegmentsList)
# report on accumulated errors - this is still a non-critical error
# so we don't throw an exception.
if len(failed_mis) > 0:
failed_indices = '\n'.join(failed_mis.keys())
self._devide_app.log_error(
'The following module indices failed to load '
'(see message log for details): \n%s' \
% (failed_indices,))
self._devide_app.log_info(
'%d modules and %d segments scanned.' %
(len(self._available_modules), len(self.availableSegmentsList)))
########################################################################
def get_appdir(self):
return self._devide_app.get_appdir()
def get_app_main_config(self):
return self._devide_app.main_config
def get_available_modules(self):
"""Return the available_modules, a dictionary keyed on fully qualified
module name (e.g. modules.Readers.vtiRDR) with values the classes
defined in module_index files.
"""
return self._available_modules
def get_instance(self, instance_name):
"""Given the unique instance name, return the instance itself.
If the module doesn't exist, return None.
"""
found = False
for instance, mModule in self._module_dict.items():
if mModule.instance_name == instance_name:
found = True
break
if found:
return mModule.instance
else:
return None
def get_instance_name(self, instance):
"""Given the actual instance, return its unique instance. If the
instance doesn't exist in self._module_dict, return the currently
halfborn instance.
"""
try:
return self._module_dict[instance].instance_name
except Exception:
return self._halfBornInstanceName
def get_meta_module(self, instance):
"""Given an instance, return the corresponding meta_module.
@param instance: the instance whose meta_module should be returned.
@return: meta_module corresponding to instance.
@raise KeyError: this instance doesn't exist in the module_dict.
"""
return self._module_dict[instance]
def get_modules_dir(self):
return self._modules_dir
def get_module_view_parent_window(self):
# this could change
return self.get_module_view_parent_window()
def get_module_spec(self, module_instance):
"""Given a module instance, return the full module spec.
"""
return 'module:%s' % (module_instance.__class__.__module__,)
def get_module_view_parent_window(self):
"""Get parent window for module windows.
THIS METHOD WILL BE DEPRECATED. The ModuleManager and view-less
(back-end) modules shouldn't know ANYTHING about windows or UI
aspects.
"""
try:
return self._devide_app.get_interface().get_main_window()
except AttributeError:
# the interface has no main_window
return None
def create_module(self, fullName, instance_name=None):
"""Try and create module fullName.
@param fullName: The complete module spec below application directory,
e.g. modules.Readers.hdfRDR.
@return: module_instance if successful.
@raises ModuleManagerException: if there is a problem creating the
module.
"""
if fullName not in self._available_modules:
raise ModuleManagerException(
'%s is not available in the current Module Manager / '
'Kit configuration.' % (fullName,))
try:
# think up name for this module (we have to think this up now
# as the module might want to know about it whilst it's being
# constructed
instance_name = self._make_unique_instance_name(instance_name)
self._halfBornInstanceName = instance_name
# perform the conditional import/reload
self.import_reload(fullName)
# import_reload requires this afterwards for safety reasons
exec('import %s' % fullName)
# in THIS case, there is a McMillan hook which'll tell the
# installer about all the devide modules. :)
ae = self.auto_execute
self.auto_execute = False
try:
# then instantiate the requested class
module_instance = None
exec(
'module_instance = %s.%s(self)' % (fullName,
fullName.split('.')[-1]))
finally:
# do the following in all cases:
self.auto_execute = ae
# if there was an exception, it will now be re-raised
if hasattr(module_instance, 'PARTS_TO_INPUTS'):
pti = module_instance.PARTS_TO_INPUTS
else:
pti = None
if hasattr(module_instance, 'PARTS_TO_OUTPUTS'):
pto = module_instance.PARTS_TO_OUTPUTS
else:
pto = None
# and store it in our internal structures
self._module_dict[module_instance] = MetaModule(
module_instance, instance_name, fullName, pti, pto)
# it's now fully born ;)
self._halfBornInstanceName = None
except ImportError, e:
# we re-raise with the three argument form to retain full
# trace information.
es = "Unable to import module %s: %s" % (fullName, str(e))
raise ModuleManagerException, es, sys.exc_info()[2]
except Exception, e:
es = "Unable to instantiate module %s: %s" % (fullName, str(e))
raise ModuleManagerException, es, sys.exc_info()[2]
# return the instance
return module_instance
def import_reload(self, fullName):
"""This will import and reload a module if necessary. Use this only
for things in modules or userModules.
If we're NOT running installed, this will run import on the module.
If it's not the first time this module is imported, a reload will
be run straight after.
If we're running installed, reloading only makes sense for things in
userModules, so it's only done for these modules. At the moment,
the stock Installer reload() is broken. Even with my fixes, it doesn't
recover memory used by old modules, see:
http://trixie.triqs.com/pipermail/installer/2003-May/000303.html
This is one of the reasons we try to avoid unnecessary reloads.
You should use this as follows:
ModuleManager.import_reloadModule('full.path.to.my.module')
import full.path.to.my.module
so that the module is actually brought into the calling namespace.
import_reload used to return the modulePrefix object, but this has
been changed to force module writers to use a conventional import
afterwards so that the McMillan installer will know about dependencies.
"""
# this should yield modules or userModules
modulePrefix = fullName.split('.')[0]
# determine whether this is a new import
if not sys.modules.has_key(fullName):
newModule = True
else:
newModule = False
# import the correct module - we have to do this in anycase to
# get the thing into our local namespace
exec('import ' + fullName)
# there can only be a reload if this is not a newModule
if not newModule:
exec('reload(' + fullName + ')')
# we need to inject the import into the calling dictionary...
# importing my.module results in "my" in the dictionary, so we
# split at '.' and return the object bound to that name
# return locals()[modulePrefix]
# we DON'T do this anymore, so that module writers are forced to
# use an import statement straight after calling import_reload (or
# somewhere else in the module)
def isInstalled(self):
"""Returns True if devide is running from an Installed state.
Installed of course refers to being installed with Gordon McMillan's
Installer. This can be used by devide modules to determine whether
they should use reload or not.
"""
return hasattr(modules, '__importsub__')
def execute_module(self, meta_module, part=0, streaming=False):
"""Execute module instance.
Important: this method does not result in data being transferred
after the execution, it JUST performs the module execution. This
method is called by the scheduler during network execution. No
other call should be used to execute a single module!
@param instance: module instance to be executed.
@raise ModuleManagerException: this exception is raised with an
informative error string if a module fails to execute.
@return: Nothing.
"""
try:
# this goes via the MetaModule so that time stamps and the
# like are correctly reported
meta_module.execute_module(part, streaming)
except Exception, e:
# get details about the errored module
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# and raise the relevant exception
es = 'Unable to execute part %d of module %s (%s): %s' \
% (part, instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
def execute_network(self, startingModule=None):
"""Execute local network in order, starting from startingModule.
This is a utility method used by module_utils to bind to the Execute
control found on must module UIs. We are still in the process
of formalising the concepts of networks vs. groups of modules.
Eventually, networks will be grouped by process node and whatnot.
@todo: integrate concept of startingModule.
"""
try:
self._devide_app.network_manager.execute_network(
self._module_dict.values())
except Exception, e:
# if an error occurred, but progress is not at 100% yet,
# we have to put it there, else app remains in visually
# busy state.
if self._devide_app.get_progress() < 100.0:
self._devide_app.set_progress(
100.0, 'Error during network execution.')
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
def view_module(self, instance):
instance.view()
def delete_module(self, instance):
"""Destroy module.
This will disconnect all module inputs and outputs and call the
close() method. This method is used by the graphEditor and by
the close() method of the ModuleManager.
@raise ModuleManagerException: if an error occurs during module
deletion.
"""
# get details about the module (we might need this later)
meta_module = self._module_dict[instance]
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# first disconnect all outgoing connections
inputs = self._module_dict[instance].inputs
outputs = self._module_dict[instance].outputs
# outputs is a list of lists of tuples, each tuple containing
# module_instance and input_idx of the consumer module
for output in outputs:
if output:
# we just want to walk through the dictionary tuples
for consumer in output:
# disconnect all consumers
self.disconnect_modules(consumer[0], consumer[1])
# inputs is a list of tuples, each tuple containing module_instance
# and output_idx of the producer/supplier module
for input_idx in range(len(inputs)):
try:
# also make sure we fully disconnect ourselves from
# our producers
self.disconnect_modules(instance, input_idx)
except Exception, e:
# we can't allow this to prevent a destruction, just log
self.log_error_with_exception(
'Module %s (%s) errored during disconnect of input %d. '
'Continuing with deletion.' % \
(instance_name, module_name, input_idx))
# set supplier to None - so we know it's nuked
inputs[input_idx] = None
# we've disconnected completely - let's reset all lists
self._module_dict[instance].reset_inputsOutputs()
# store autoexecute, then disable
ae = self.auto_execute
self.auto_execute = False
try:
try:
# now we can finally call close on the instance
instance.close()
finally:
# do the following in all cases:
# 1. remove module from our dict
del self._module_dict[instance]
# 2. reset auto_execute mode
self.auto_execute = ae
# the exception will now be re-raised if there was one
# to begin with.
except Exception, e:
# we're going to re-raise the exception: this method could be
# called by other parties that need to do alternative error
# handling
# create new exception message
es = 'Error calling close() on module %s (%s): %s' \
% (instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
def connect_modules(self, output_module, output_idx,
input_module, input_idx):
"""Connect output_idx'th output of provider output_module to
input_idx'th input of consumer input_module. If an error occurs
during connection, an exception will be raised.
@param output_module: This is a module instance.
"""
# record connection (this will raise an exception if the input
# is already occupied)
self._module_dict[input_module].connectInput(
input_idx, output_module, output_idx)
# record connection on the output of the producer module
# this will also initialise the transfer times
self._module_dict[output_module].connectOutput(
output_idx, input_module, input_idx)
def disconnect_modules(self, input_module, input_idx):
"""Disconnect a consumer module from its provider.