-
Notifications
You must be signed in to change notification settings - Fork 967
/
modules.py
1449 lines (1221 loc) · 58 KB
/
modules.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
"""
Modules used in building workflows
"""
import logging
import re
from xml.etree.ElementTree import Element
import galaxy.tools
from galaxy import exceptions
from galaxy import model
from galaxy import web
from galaxy.dataset_collections import matching
from galaxy.web.framework import formbuilder
from galaxy.jobs.actions.post import ActionBox
from galaxy.model import PostJobAction
from galaxy.tools.parameters import check_param, visit_input_values
from galaxy.tools.parameters.basic import (
parameter_types,
DataCollectionToolParameter,
DataToolParameter,
DummyDataset,
RuntimeValue,
)
from galaxy.tools.parameters.wrapped import make_dict_copy
from galaxy.tools.execute import execute
from galaxy.util.bunch import Bunch
from galaxy.util import odict
from galaxy.util.json import loads
from galaxy.util.json import dumps
from tool_shed.util import common_util
log = logging.getLogger( __name__ )
# Key into Tool state to describe invocation-specific runtime properties.
RUNTIME_STEP_META_STATE_KEY = "__STEP_META_STATE__"
# Key into step runtime state dict describing invocation-specific post job
# actions (i.e. PJA specified at runtime on top of the workflow-wide defined
# ones.
RUNTIME_POST_JOB_ACTIONS_KEY = "__POST_JOB_ACTIONS__"
NO_REPLACEMENT = object()
class WorkflowModule( object ):
def __init__( self, trans ):
self.trans = trans
# ---- Creating modules from various representations ---------------------
@classmethod
def new( Class, trans, content_id=None ):
"""
Create a new instance of the module with default state
"""
return Class( trans )
@classmethod
def from_dict( Class, trans, d ):
"""
Create a new instance of the module initialized from values in the
dictionary `d`.
"""
return Class( trans )
@classmethod
def from_workflow_step( Class, trans, step ):
return Class( trans )
# ---- Saving in various forms ------------------------------------------
def save_to_step( self, step ):
step.type = self.type
# ---- General attributes -----------------------------------------------
def get_type( self ):
return self.type
def get_name( self ):
return self.name
def get_content_id( self ):
""" If this component has an identifier external to the step (such
as a tool or another workflow) return the identifier for that content.
"""
return None
def get_tooltip( self, static_path='' ):
return None
# ---- Configuration time -----------------------------------------------
def get_state( self, secure=True ):
""" Return a serializable representation of the persistable state of
the step - for tools it DefaultToolState.encode returns a string and
for simpler module types a json description is dumped out.
"""
return None
def update_state( self, incoming ):
""" Update the current state of the module against the user supplied
parameters in the dict-like object `incoming`.
"""
pass
def get_errors( self ):
""" It seems like this is effectively just used as boolean - some places
in the tool shed self.errors is set to boolean, other places 'unavailable',
likewise in Galaxy it stores a list containing a string with an unrecognized
tool id error message.
"""
return None
def get_data_inputs( self ):
""" Get configure time data input descriptions. """
return []
def get_data_outputs( self ):
return []
def get_runtime_input_dicts( self, step_annotation ):
""" Get runtime inputs (inputs and parameters) as simple dictionary. """
return []
def get_config_form( self ):
""" Render form that is embedded in workflow editor for modifying the
step state of a node.
"""
raise TypeError( "Abstract method" )
def check_and_update_state( self ):
"""
If the state is not in sync with the current implementation of the
module, try to update. Returns a list of messages to be displayed
"""
pass
def add_dummy_datasets( self, connections=None):
# Replaced connected inputs with DummyDataset values.
pass
# ---- Run time ---------------------------------------------------------
def get_runtime_inputs( self, **kwds ):
""" Used internally by modules and when displaying inputs in workflow
editor and run workflow templates.
Note: The ToolModule doesn't implement this and these templates contain
specialized logic for dealing with the tool and state directly in the
case of ToolModules.
"""
raise TypeError( "Abstract method" )
def encode_runtime_state( self, trans, state ):
""" Encode the default runtime state at return as a simple `str` for
use in a hidden parameter on the workflow run submission form.
This default runtime state will be combined with user supplied
parameters in `compute_runtime_state` below at workflow invocation time to
actually describe how each step will be executed.
"""
raise TypeError( "Abstract method" )
def compute_runtime_state( self, trans, step_updates=None, source="html" ):
""" Determine the runtime state (potentially different from self.state
which describes configuration state). This (again unlike self.state) is
currently always a `DefaultToolState` object.
If `step_updates` is `None`, this is likely for rendering the run form
for instance and no runtime properties are available and state must be
solely determined by the default runtime state described by the step.
If `step_updates` are available they describe the runtime properties
supplied by the workflow runner (potentially including a `tool_state`
parameter which is the serialized default encoding state created with
encode_runtime_state above).
"""
raise TypeError( "Abstract method" )
def execute( self, trans, progress, invocation, step ):
""" Execute the given workflow step in the given workflow invocation.
Use the supplied workflow progress object to track outputs, find
inputs, etc...
"""
raise TypeError( "Abstract method" )
def do_invocation_step_action( self, step, action ):
""" Update or set the workflow invocation state action - generic
extension point meant to allows users to interact with interactive
workflow modules. The action object returned from this method will
be attached to the WorkflowInvocationStep and be available the next
time the workflow scheduler visits the workflow.
"""
raise exceptions.RequestParameterInvalidException( "Attempting to perform invocation step action on module that does not support actions." )
def recover_mapping( self, step, step_invocations, progress ):
""" Re-populate progress object with information about connections
from previously executed steps recorded via step_invocations.
"""
raise TypeError( "Abstract method" )
class SimpleWorkflowModule( WorkflowModule ):
@classmethod
def new( Class, trans, content_id=None ):
module = Class( trans )
module.state = Class.default_state()
module.label = None
return module
@classmethod
def from_dict( Class, trans, d, secure=True ):
module = Class( trans )
state = loads( d["tool_state"] )
module.recover_state( state )
module.label = d.get("label", None) or None
return module
@classmethod
def from_workflow_step( Class, trans, step ):
module = Class( trans )
module.recover_state( step.tool_inputs )
module.label = step.label
return module
@classmethod
def default_state( Class ):
""" This method should return a dictionary describing each
configuration property and its default value.
"""
raise TypeError( "Abstract method" )
def save_to_step( self, step ):
step.type = self.type
step.tool_id = None
step.tool_version = None
step.tool_inputs = self.state
def get_state( self, secure=True ):
return dumps( self.state )
def update_state( self, incoming ):
self.recover_state( incoming )
def recover_runtime_state( self, runtime_state ):
""" Take secure runtime state from persisted invocation and convert it
into a DefaultToolState object for use during workflow invocation.
"""
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
state = galaxy.tools.DefaultToolState()
state.decode( runtime_state, fake_tool, self.trans.app, secure=False )
return state
def normalize_runtime_state( self, runtime_state ):
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
return runtime_state.encode( fake_tool, self.trans.app, secure=False )
def encode_runtime_state( self, trans, state ):
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
return state.encode( fake_tool, trans.app )
def decode_runtime_state( self, trans, string ):
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
state = galaxy.tools.DefaultToolState()
if string:
state.decode( string, fake_tool, trans.app )
return state
def update_runtime_state( self, trans, state, values ):
errors = {}
for name, param in self.get_runtime_inputs().iteritems():
value, error = check_param( trans, param, values.get( name, None ), values )
state.inputs[ name ] = value
if error:
errors[ name ] = error
return errors
def compute_runtime_state( self, trans, step_updates=None, source="html" ):
if step_updates and "tool_state" in step_updates:
# Fix this for multiple inputs
state = self.decode_runtime_state( trans, step_updates.pop( "tool_state" ) )
step_errors = self.update_runtime_state( trans, state, step_updates )
else:
state = self.get_runtime_state()
step_errors = {}
return state, step_errors
def recover_state( self, state, **kwds ):
""" Recover state `dict` from simple dictionary describing configuration
state (potentially from persisted step state).
Sub-classes should supply `default_state` method and `state_fields`
attribute which are used to build up the state `dict`.
"""
self.state = self.default_state()
for key in self.state_fields:
if state and key in state:
self.state[ key ] = state[ key ]
def get_config_form( self ):
form = self._abstract_config_form( )
return self.trans.fill_template( "workflow/editor_generic_form.mako",
module=self, form=form )
class SubWorkflowModule( WorkflowModule ):
state_fields = [ ]
type = "subworkflow"
name = "Subworkflow"
default_name = "Subworkflow"
@classmethod
def new( Class, trans, content_id=None ):
module = Class( trans )
module.subworkflow = SubWorkflowModule.subworkflow_from_content_id( trans, content_id )
module.label = None
return module
@classmethod
def from_dict( Class, trans, d, secure=True ):
module = Class( trans )
if "subworkflow" in d:
module.subworkflow = d["subworkflow"]
elif "content_id" in d:
content_id = d["content_id"]
module.subworkflow = SubWorkflowModule.subworkflow_from_content_id( trans, content_id )
module.label = d.get("label", None) or None
return module
@classmethod
def from_workflow_step( Class, trans, step ):
module = Class( trans )
module.subworkflow = step.subworkflow
module.label = step.label
return module
def save_to_step( self, step ):
step.type = self.type
step.subworkflow = self.subworkflow
@classmethod
def default_state( Class ):
return dict( )
def get_name( self ):
if hasattr( self, 'subworkflow' ) and hasattr( self.subworkflow, 'name' ):
return self.subworkflow.name
return self.name
def get_errors( self ):
return None
def get_data_inputs( self ):
""" Get configure time data input descriptions. """
# Filter subworkflow steps and get inputs
step_to_input_type = {
"data_input": "dataset",
"data_collection_input": "dataset_collection",
}
inputs = []
for step in self.subworkflow.input_steps:
name = step.label
if name is None:
# trans shouldn't really be needed for data inputs...
step_module = module_factory.from_workflow_step(self.trans, step)
name = step_module.get_runtime_input_dicts(None)[0]["name"]
if not name:
raise Exception("Failed to find name for workflow module.")
step_type = step.type
assert step_type in step_to_input_type
input = dict(
input_subworkflow_step_id=step.order_index,
name=name,
label=name,
multiple=False,
extensions="input",
input_type=step_to_input_type[step_type],
)
inputs.append(input)
return inputs
def get_data_outputs( self ):
outputs = []
for workflow_output in self.subworkflow.workflow_outputs:
output_step = workflow_output.workflow_step
label = name = workflow_output.label
if name is None:
name = "%s:%s" % (output_step.order_index, workflow_output.output_name)
label = name
output = dict(
name=name,
label=label,
extensions=['input'], # TODO
)
outputs.append(output)
return outputs
def get_runtime_input_dicts( self, step_annotation ):
""" Get runtime inputs (inputs and parameters) as simple dictionary. """
return []
def get_content_id( self ):
return self.trans.security.encode_id(self.subworkflow.id)
def recover_runtime_state( self, runtime_state ):
""" Take secure runtime state from persisted invocation and convert it
into a DefaultToolState object for use during workflow invocation.
"""
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
state = galaxy.tools.DefaultToolState()
state.decode( runtime_state, fake_tool, self.trans.app, secure=False )
return state
def normalize_runtime_state( self, runtime_state ):
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
return runtime_state.encode( fake_tool, self.trans.app, secure=False )
def encode_runtime_state( self, trans, state ):
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
return state.encode( fake_tool, trans.app )
def decode_runtime_state( self, trans, string ):
fake_tool = Bunch( inputs=self.get_runtime_inputs() )
state = galaxy.tools.DefaultToolState()
if string:
state.decode( string, fake_tool, trans.app )
return state
def update_runtime_state( self, trans, state, values ):
errors = {}
for name, param in self.get_runtime_inputs().iteritems():
value, error = check_param( trans, param, values.get( name, None ), values )
state.inputs[ name ] = value
if error:
errors[ name ] = error
return errors
def compute_runtime_state( self, trans, step_updates=None, source="html" ):
state = self.get_runtime_state()
step_errors = {}
return state, step_errors
def recover_state( self, state, **kwds ):
""" Recover state `dict` from simple dictionary describing configuration
state (potentially from persisted step state).
Sub-classes should supply `default_state` method and `state_fields`
attribute which are used to build up the state `dict`.
"""
self.state = self.default_state()
for key in self.state_fields:
if state and key in state:
self.state[ key ] = state[ key ]
def get_config_form( self ):
form = self._abstract_config_form( )
return self.trans.fill_template( "workflow/editor_generic_form.mako",
module=self, form=form )
def _abstract_config_form( self ):
form = formbuilder.FormBuilder( title=self.get_name() )
return form
def check_and_update_state( self ):
"""
If the state is not in sync with the current implementation of the
module, try to update. Returns a list of messages to be displayed
"""
return None
def add_dummy_datasets( self, connections=None):
# Replaced connected inputs with DummyDataset values.
return None
def get_runtime_inputs( self, **kwds ):
# Two step improvements to this...
# - First pass verify nested workflow doesn't have an RuntimeInputs
# - Second pass actually turn RuntimeInputs into inputs here if possible.
return {}
def execute( self, trans, progress, invocation, step ):
""" Execute the given workflow step in the given workflow invocation.
Use the supplied workflow progress object to track outputs, find
inputs, etc...
"""
subworkflow_invoker = progress.subworkflow_invoker( trans, step )
subworkflow_invoker.invoke()
subworkflow = subworkflow_invoker.workflow
subworkflow_progress = subworkflow_invoker.progress
outputs = {}
for workflow_output in subworkflow.workflow_outputs:
workflow_output_label = workflow_output.label
replacement = subworkflow_progress.get_replacement_workflow_output( workflow_output )
outputs[ workflow_output_label ] = replacement
progress.set_step_outputs( step, outputs )
return None
def recover_mapping( self, step, step_invocations, progress ):
""" Re-populate progress object with information about connections
from previously executed steps recorded via step_invocations.
"""
raise TypeError( "Abstract method" )
def get_runtime_state( self ):
state = galaxy.tools.DefaultToolState()
state.inputs = dict( )
return state
@classmethod
def subworkflow_from_content_id(clazz, trans, content_id):
from galaxy.managers.workflows import WorkflowsManager
workflow_manager = WorkflowsManager(trans.app)
subworkflow = workflow_manager.get_owned_workflow( trans, content_id )
return subworkflow
class InputModule( SimpleWorkflowModule ):
def get_runtime_state( self ):
state = galaxy.tools.DefaultToolState()
state.inputs = dict( input=None )
return state
def get_runtime_input_dicts( self, step_annotation ):
name = self.state.get( "name", self.default_name )
return [ dict( name=name, description=step_annotation ) ]
def get_data_inputs( self ):
return []
def execute( self, trans, progress, invocation, step ):
job, step_outputs = None, dict( output=step.state.inputs['input'])
# Web controller may set copy_inputs_to_history, API controller always sets
# inputs.
if invocation.copy_inputs_to_history:
for input_dataset_hda in step_outputs.values():
content_type = input_dataset_hda.history_content_type
if content_type == "dataset":
new_hda = input_dataset_hda.copy( copy_children=True )
invocation.history.add_dataset( new_hda )
step_outputs[ 'input_ds_copy' ] = new_hda
elif content_type == "dataset_collection":
new_hdca = input_dataset_hda.copy()
invocation.history.add_dataset_collection( new_hdca )
step_outputs[ 'input_ds_copy' ] = new_hdca
else:
raise Exception("Unknown history content encountered")
# If coming from UI - we haven't registered invocation inputs yet,
# so do that now so dependent steps can be recalculated. In the future
# everything should come in from the API and this can be eliminated.
if not invocation.has_input_for_step( step.id ):
content = step_outputs.values()[ 0 ]
if content:
invocation.add_input( content, step.id )
progress.set_outputs_for_input( step, step_outputs )
return job
def recover_mapping( self, step, step_invocations, progress ):
progress.set_outputs_for_input( step )
class InputDataModule( InputModule ):
type = "data_input"
name = "Input dataset"
default_name = "Input Dataset"
state_fields = [ "name" ]
@classmethod
def default_state( Class ):
return dict( name=Class.default_name )
def _abstract_config_form( self ):
form = formbuilder.FormBuilder( title=self.name ) \
.add_text( "name", "Name", value=self.state['name'] )
return form
def get_data_outputs( self ):
return [ dict( name='output', extensions=['input'] ) ]
def get_runtime_inputs( self, filter_set=['data'] ):
label = self.state.get( "name", "Input Dataset" )
return dict( input=DataToolParameter( None, Element( "param", name="input", label=label, multiple=True, type="data", format=', '.join(filter_set) ), self.trans ) )
class InputDataCollectionModule( InputModule ):
default_name = "Input Dataset Collection"
default_collection_type = "list"
type = "data_collection_input"
name = "Input dataset collection"
collection_type = default_collection_type
state_fields = [ "name", "collection_type" ]
@classmethod
def default_state( Class ):
return dict( name=Class.default_name, collection_type=Class.default_collection_type )
def get_runtime_inputs( self, filter_set=['data'] ):
label = self.state.get( "name", self.default_name )
collection_type = self.state.get( "collection_type", self.default_collection_type )
input_element = Element( "param", name="input", label=label, type="data_collection", collection_type=collection_type )
return dict( input=DataCollectionToolParameter( None, input_element, self.trans ) )
def _abstract_config_form( self ):
type_hints = odict.odict()
type_hints[ "list" ] = "List of Datasets"
type_hints[ "paired" ] = "Dataset Pair"
type_hints[ "list:paired" ] = "List of Dataset Pairs"
type_input = formbuilder.DatalistInput(
name="collection_type",
label="Collection Type",
value=self.state[ "collection_type" ],
extra_attributes=dict(refresh_on_change='true'),
options=type_hints
)
form = formbuilder.FormBuilder(
title=self.name
).add_text(
"name", "Name", value=self.state['name']
)
form.inputs.append( type_input )
return form
def get_data_outputs( self ):
return [
dict(
name='output',
extensions=['input_collection'],
collection=True,
collection_type=self.state[ 'collection_type' ]
)
]
class InputParameterModule( SimpleWorkflowModule ):
default_name = "input_parameter"
default_parameter_type = "text"
default_optional = False
type = "parameter_input"
name = default_name
parameter_type = default_parameter_type
optional = default_optional
state_fields = [
"name",
"parameter_type",
"optional",
]
@classmethod
def default_state( Class ):
return dict(
name=Class.default_name,
parameter_type=Class.default_parameter_type,
optional=Class.default_optional,
)
def _abstract_config_form( self ):
form = formbuilder.FormBuilder(
title=self.name
).add_text(
"name", "Name", value=self.state['name']
).add_select(
"parameter_type", "Parameter Type", value=self.state['parameter_type'],
options=[
('text', "Text"),
('integer', "Integer"),
('float', "Float"),
('boolean', "Boolean (True or False)"),
('color', "Color"),
]
).add_checkbox(
"optional", "Optional", value=self.state['optional']
)
return form
def get_runtime_inputs( self, **kwds ):
label = self.state.get( "name", self.default_name )
parameter_type = self.state.get("parameter_type", self.default_parameter_type)
optional = self.state.get("optional", self.default_optional)
if parameter_type not in ["text", "boolean", "integer", "float", "color"]:
raise ValueError("Invalid parameter type for workflow parameters encountered.")
parameter_class = parameter_types[parameter_type]
parameter_kwds = {}
if parameter_type in ["integer", "float"]:
parameter_kwds["value"] = str(0)
# TODO: Use a dict-based description from YAML tool source
element = Element("param", name="input", label=label, type=parameter_type, optional=str(optional), **parameter_kwds )
input = parameter_class( None, element )
return dict( input=input )
def get_runtime_state( self ):
state = galaxy.tools.DefaultToolState()
state.inputs = dict( input=None )
return state
def get_runtime_input_dicts( self, step_annotation ):
name = self.state.get( "name", self.default_name )
return [ dict( name=name, description=step_annotation ) ]
def get_data_inputs( self ):
return []
def execute( self, trans, progress, invocation, step ):
job, step_outputs = None, dict( output=step.state.inputs['input'])
progress.set_outputs_for_input( step, step_outputs )
return job
class PauseModule( SimpleWorkflowModule ):
""" Initially this module will unconditionally pause a workflow - will aim
to allow conditional pausing later on.
"""
type = "pause"
name = "Pause for dataset review"
default_name = "Pause for Dataset Review"
state_fields = [ "name" ]
@classmethod
def default_state( Class ):
return dict( name=Class.default_name )
def get_data_inputs( self ):
input = dict(
name="input",
label="Dataset for Review",
multiple=False,
extensions='input',
input_type="dataset",
)
return [ input ]
def get_data_outputs( self ):
return [ dict( name="output", label="Reviewed Dataset", extensions=['input'] ) ]
def _abstract_config_form( self ):
form = formbuilder.FormBuilder(
title=self.name
).add_text( "name", "Name", value=self.state['name'] )
return form
def get_runtime_inputs( self, **kwds ):
return dict( )
def get_runtime_input_dicts( self, step_annotation ):
return []
def get_runtime_state( self ):
state = galaxy.tools.DefaultToolState()
state.inputs = dict( )
return state
def execute( self, trans, progress, invocation, step ):
progress.mark_step_outputs_delayed( step )
return None
def recover_mapping( self, step, step_invocations, progress ):
if step_invocations:
step_invocation = step_invocations[0]
action = step_invocation.action
if action:
connection = step.input_connections_by_name[ "input" ][ 0 ]
replacement = progress.replacement_for_connection( connection )
progress.set_step_outputs( step, { 'output': replacement } )
return
elif action is False:
raise CancelWorkflowEvaluation()
raise DelayedWorkflowEvaluation()
def do_invocation_step_action( self, step, action ):
""" Update or set the workflow invocation state action - generic
extension point meant to allows users to interact with interactive
workflow modules. The action object returned from this method will
be attached to the WorkflowInvocationStep and be available the next
time the workflow scheduler visits the workflow.
"""
return bool( action )
class ToolModule( WorkflowModule ):
type = "tool"
def __init__( self, trans, tool_id, tool_version=None ):
self.trans = trans
self.tool_id = tool_id
self.tool = trans.app.toolbox.get_tool( tool_id, tool_version=tool_version )
self.post_job_actions = {}
self.runtime_post_job_actions = {}
self.workflow_outputs = []
self.state = None
self.version_changes = []
if self.tool:
self.errors = None
else:
self.errors = {}
self.errors[ tool_id ] = 'Tool unavailable'
@classmethod
def new( Class, trans, content_id=None ):
module = Class( trans, content_id )
if module.tool is None:
error_message = "Attempted to create new workflow module for invalid tool_id, no tool with id - %s." % content_id
raise Exception( error_message )
module.state = module.tool.new_state( trans )
module.label = None
return module
@classmethod
def from_dict( Class, trans, d, secure=True ):
tool_id = d.get( 'content_id', None )
if tool_id is None:
tool_id = d.get( 'tool_id', None ) # Older workflows will have exported this as tool_id.
tool_version = str( d.get( 'tool_version', None ) )
module = Class( trans, tool_id, tool_version=tool_version )
module.state = galaxy.tools.DefaultToolState()
module.label = d.get("label", None) or None
if module.tool is not None:
message = ""
if tool_id != module.tool_id:
message += "The tool (id '%s') specified in this step is not available. Using the tool with id %s instead." % (tool_id, module.tool_id)
if d.get('tool_version', 'Unspecified') != module.get_tool_version():
message += "%s: using version '%s' instead of version '%s' specified in this workflow." % ( tool_id, d.get( 'tool_version', 'Unspecified' ), module.get_tool_version() )
if message:
log.debug(message)
module.version_changes.append(message)
if d[ "tool_state" ]:
module.state.decode( d[ "tool_state" ], module.tool, module.trans.app, secure=secure )
module.errors = d.get( "tool_errors", None )
module.post_job_actions = d.get( "post_job_actions", {} )
module.workflow_outputs = d.get( "workflow_outputs", [] )
return module
@classmethod
def from_workflow_step( Class, trans, step ):
toolbox = trans.app.toolbox
tool_id = step.tool_id
if toolbox:
# See if we have access to a different version of the tool.
# TODO: If workflows are ever enhanced to use tool version
# in addition to tool id, enhance the selection process here
# to retrieve the correct version of the tool.
tool_id = toolbox.get_tool_id( tool_id )
if ( toolbox and tool_id ):
if step.config:
# This step has its state saved in the config field due to the
# tool being previously unavailable.
return module_factory.from_dict(trans, loads(step.config), secure=False)
tool_version = step.tool_version
module = Class( trans, tool_id, tool_version=tool_version )
message = ""
if step.tool_id != module.tool_id: # This means the exact version of the tool is not installed. We inform the user.
old_tool_shed = step.tool_id.split( "/repos/" )[0]
if old_tool_shed not in tool_id: # Only display the following warning if the tool comes from a different tool shed
old_tool_shed_url = common_util.get_tool_shed_url_from_tool_shed_registry( trans.app, old_tool_shed )
old_url = old_tool_shed_url + "/view/%s/%s/" % (module.tool.repository_owner, module.tool.repository_name)
new_url = module.tool.tool_shed_repository.get_sharable_url( module.tool.app ) + '/%s/' % module.tool.tool_shed_repository.changeset_revision
new_tool_shed_url = new_url.split( "/view" )[0]
message += "The tool \'%s\', version %s by the owner %s installed from <a href=\"%s\" target=\"_blank\">%s</a> is not available. " % (module.tool.name, tool_version, module.tool.repository_owner, old_url, old_tool_shed_url)
message += "A derivation of this tool installed from <a href=\"%s\" target=\"_blank\">%s</a> will be used instead. " % (new_url, new_tool_shed_url)
if step.tool_version and (step.tool_version != module.tool.version):
message += "<span title=\"tool id '%s'\">Using version '%s' instead of version '%s' specified in this workflow. " % (tool_id, module.tool.version, step.tool_version)
if message:
log.debug(message)
module.version_changes.append(message)
module.recover_state( step.tool_inputs )
module.errors = step.tool_errors
module.workflow_outputs = step.workflow_outputs
module.label = step.label or None
pjadict = {}
for pja in step.post_job_actions:
pjadict[pja.action_type] = pja
module.post_job_actions = pjadict
return module
return None
def recover_state( self, state, **kwds ):
""" Recover module configuration state property (a `DefaultToolState`
object) using the tool's `params_from_strings` method.
"""
app = self.trans.app
self.state = galaxy.tools.DefaultToolState()
params_from_kwds = dict(
ignore_errors=kwds.get( "ignore_errors", True )
)
self.state.inputs = self.tool.params_from_strings( state, app, **params_from_kwds )
def recover_runtime_state( self, runtime_state ):
""" Take secure runtime state from persisted invocation and convert it
into a DefaultToolState object for use during workflow invocation.
"""
state = galaxy.tools.DefaultToolState()
app = self.trans.app
state.decode( runtime_state, self.tool, app, secure=False )
state_dict = loads( runtime_state )
if RUNTIME_STEP_META_STATE_KEY in state_dict:
self.__restore_step_meta_runtime_state( loads( state_dict[ RUNTIME_STEP_META_STATE_KEY ] ) )
return state
def normalize_runtime_state( self, runtime_state ):
return runtime_state.encode( self.tool, self.trans.app, secure=False )
def save_to_step( self, step ):
step.type = self.type
step.tool_id = self.tool_id
if self.tool:
step.tool_version = self.get_tool_version()
step.tool_inputs = self.tool.params_to_strings( self.state.inputs, self.trans.app )
else:
step.tool_version = None
step.tool_inputs = None
step.tool_errors = self.errors
for k, v in self.post_job_actions.iteritems():
pja = self.__to_pja( k, v, step )
self.trans.sa_session.add( pja )
def __to_pja( self, key, value, step ):
if 'output_name' in value:
output_name = value['output_name']
else:
output_name = None
if 'action_arguments' in value:
action_arguments = value['action_arguments']
else:
action_arguments = None
return PostJobAction(value['action_type'], step, output_name, action_arguments)
def get_name( self ):
if self.tool:
return self.tool.name
return 'unavailable'
def get_content_id( self ):
return self.tool_id
def get_tool_version( self ):
return self.tool.version
def get_state( self, secure=True ):
return self.state.encode( self.tool, self.trans.app, secure=secure )
def get_errors( self ):
return self.errors
def get_tooltip( self, static_path='' ):
if self.tool.help:
return self.tool.help.render( host_url=web.url_for('/'), static_path=static_path )
else:
return None
def get_data_inputs( self ):
data_inputs = []
def callback( input, value, prefixed_name, prefixed_label ):
if isinstance( input, DataToolParameter ):
data_inputs.append( dict(
name=prefixed_name,
label=prefixed_label,
multiple=input.multiple,
extensions=input.extensions,
input_type="dataset", ) )
if isinstance( input, DataCollectionToolParameter ):
data_inputs.append( dict(
name=prefixed_name,
label=prefixed_label,
multiple=input.multiple,
input_type="dataset_collection",
collection_types=input.collection_types,
extensions=input.extensions,
) )
visit_input_values( self.tool.inputs, self.state.inputs, callback )
return data_inputs
def get_data_outputs( self ):
data_outputs = []
data_inputs = None
for name, tool_output in self.tool.outputs.iteritems():
extra_kwds = {}
if tool_output.collection:
extra_kwds["collection"] = True
extra_kwds["collection_type"] = tool_output.structure.collection_type
formats = [ 'input' ] # TODO: fix
elif tool_output.format_source is not None:
formats = [ 'input' ] # default to special name "input" which remove restrictions on connections
if data_inputs is None:
data_inputs = self.get_data_inputs()
# find the input parameter referenced by format_source
for di in data_inputs:
# input names come prefixed with conditional and repeat names separated by '|'
# remove prefixes when comparing with format_source