/
__init__.py
executable file
·2637 lines (2329 loc) · 117 KB
/
__init__.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
"""
Classes encapsulating galaxy tools and tool configuration.
"""
import json
import logging
import os
import re
import tarfile
import tempfile
import threading
from cgi import FieldStorage
from datetime import datetime
from distutils.version import LooseVersion
from xml.etree import ElementTree
from mako.template import Template
from paste import httpexceptions
from six import string_types
from six.moves.urllib.parse import unquote_plus
import tool_shed.util.repository_util as repository_util
import tool_shed.util.shed_util_common
from galaxy import (
exceptions,
model
)
from galaxy.datatypes.metadata import JobExternalOutputMetadataWrapper
from galaxy.managers import histories
from galaxy.queue_worker import send_control_task
from galaxy.tools.actions import DefaultToolAction
from galaxy.tools.actions.data_manager import DataManagerToolAction
from galaxy.tools.actions.data_source import DataSourceToolAction
from galaxy.tools.actions.model_operations import ModelOperationToolAction
from galaxy.tools.deps import (
CachedDependencyManager,
views
)
from galaxy.tools.fetcher import ToolLocationFetcher
from galaxy.tools.parameters import (
check_param,
params_from_strings,
params_to_incoming,
params_to_strings,
populate_state,
visit_input_values
)
from galaxy.tools.parameters import output_collect
from galaxy.tools.parameters.basic import (
BaseURLToolParameter,
DataCollectionToolParameter,
DataToolParameter,
HiddenToolParameter,
SelectToolParameter,
ToolParameter,
workflow_building_modes,
)
from galaxy.tools.parameters.grouping import Conditional, ConditionalWhen, Repeat, Section, UploadDataset
from galaxy.tools.parameters.input_translation import ToolInputTranslator
from galaxy.tools.parameters.meta import expand_meta_parameters
from galaxy.tools.parser import (
get_tool_source,
ToolOutputCollectionPart
)
from galaxy.tools.parser.xml import XmlPageSource
from galaxy.tools.test import parse_tests
from galaxy.tools.toolbox import BaseGalaxyToolBox
from galaxy.util import (
ExecutionTimer,
listify,
Params,
rst_to_html,
string_as_bool,
unicodify
)
from galaxy.util.bunch import Bunch
from galaxy.util.dictifiable import Dictifiable
from galaxy.util.expressions import ExpressionContext
from galaxy.util.json import json_fix
from galaxy.util.json import safe_loads
from galaxy.util.odict import odict
from galaxy.util.template import fill_template
from galaxy.version import VERSION_MAJOR
from galaxy.web import url_for
from galaxy.web.form_builder import SelectField
from galaxy.work.context import WorkRequestContext
from tool_shed.util import common_util
from .execute import (
execute as execute_job,
MappingParameters,
)
from .loader import (
imported_macro_paths,
raw_tool_xml_tree,
template_macro_params
)
log = logging.getLogger(__name__)
HELP_UNINITIALIZED = threading.Lock()
MODEL_TOOLS_PATH = os.path.abspath(os.path.dirname(__file__))
# Tools that require Galaxy's Python environment to be preserved.
GALAXY_LIB_TOOLS_UNVERSIONED = [
"upload1",
# Legacy tools bundled with Galaxy.
"vcf_to_maf_customtrack1",
"laj_1",
"meme_fimo",
"secure_hash_message_digest",
"join1",
"gff2bed1",
"gff_filter_by_feature_count",
"Extract genomic DNA 1",
"aggregate_scores_in_intervals2",
"Interval_Maf_Merged_Fasta2",
"GeneBed_Maf_Fasta2",
"maf_stats1",
"Interval2Maf1",
"Interval2Maf_pairwise1",
"MAF_To_Interval1",
"MAF_filter",
"MAF_To_Fasta1",
"MAF_Reverse_Complement_1",
"MAF_split_blocks_by_species1",
"MAF_Limit_To_Species1",
"maf_by_block_number1",
"wiggle2simple1",
# Converters
"CONVERTER_bed_to_fli_0",
"CONVERTER_fastq_to_fqtoc0",
"CONVERTER_gff_to_fli_0",
"CONVERTER_gff_to_interval_index_0",
"CONVERTER_maf_to_fasta_0",
"CONVERTER_maf_to_interval_0",
"CONVERTER_wiggle_to_interval_0",
# Tools improperly migrated to the tool shed (devteam)
"lastz_wrapper_2",
"qualityFilter",
"winSplitter",
"pileup_interval",
"count_gff_features",
"Convert characters1",
"lastz_paired_reads_wrapper",
"subRate1",
"substitutions1",
"sam_pileup",
"find_diag_hits",
"cufflinks",
# Tools improperly migrated to the tool shed (iuc)
"tabular_to_dbnsfp",
# Tools improperly migrated using Galaxy (from shed other)
"column_join",
"gd_coverage_distributions", # Genome Diversity tools from miller-lab
"gd_dpmix",
"gd_pca",
"gd_phylogenetic_tree",
"gd_population_structure",
"gd_prepare_population_structure",
# Datasources
"genomespace_importer"
]
# Tools that needed galaxy on the PATH in the past but no longer do along
# with the version at which they were fixed.
GALAXY_LIB_TOOLS_VERSIONED = {
"sam_to_bam": LooseVersion("1.1.3"),
"PEsortedSAM2readprofile": LooseVersion("1.1.1"),
"fetchflank": LooseVersion("1.0.1"),
}
class ToolErrorLog:
def __init__(self):
self.error_stack = []
self.max_errors = 100
def add_error(self, file, phase, exception):
self.error_stack.insert(0, {
"file": file,
"time": str(datetime.now()),
"phase": phase,
"error": str(exception)
})
if len(self.error_stack) > self.max_errors:
self.error_stack.pop()
global_tool_errors = ToolErrorLog()
class ToolInputsNotReadyException(Exception):
pass
class ToolNotFoundException(Exception):
pass
def create_tool_from_source(app, tool_source, config_file=None, **kwds):
# Allow specifying a different tool subclass to instantiate
tool_module = tool_source.parse_tool_module()
if tool_module is not None:
module, cls = tool_module
mod = __import__(module, globals(), locals(), [cls])
ToolClass = getattr(mod, cls)
elif tool_source.parse_tool_type():
tool_type = tool_source.parse_tool_type()
ToolClass = tool_types.get(tool_type)
else:
# Normal tool
root = getattr(tool_source, 'root', None)
ToolClass = Tool
tool = ToolClass(config_file, tool_source, app, **kwds)
return tool
class ToolBox(BaseGalaxyToolBox):
""" A derivative of AbstractToolBox with knowledge about Tool internals -
how to construct them, action types, dependency management, etc....
"""
def __init__(self, config_filenames, tool_root_dir, app):
self._reload_count = 0
self.tool_location_fetcher = ToolLocationFetcher()
super(ToolBox, self).__init__(
config_filenames=config_filenames,
tool_root_dir=tool_root_dir,
app=app,
)
def handle_panel_update(self, section_dict):
"""
Sends a panel update to all threads/processes.
"""
send_control_task(self.app, 'create_panel_section', kwargs=section_dict)
# The following local call to self.create_section should be unnecessary
# but occasionally the local ToolPanelElements instance appears to not
# get updated.
self.create_section(section_dict)
def has_reloaded(self, other_toolbox):
return self._reload_count != other_toolbox._reload_count
@property
def all_requirements(self):
reqs = set([req for _, tool in self.tools() for req in tool.tool_requirements])
return [r.to_dict() for r in reqs]
@property
def tools_by_id(self):
# Deprecated method, TODO - eliminate calls to this in test/.
return self._tools_by_id
def create_tool(self, config_file, **kwds):
try:
tool_source = get_tool_source(
config_file,
enable_beta_formats=getattr(self.app.config, "enable_beta_tool_formats", False),
tool_location_fetcher=self.tool_location_fetcher,
)
except Exception as e:
# capture and log parsing errors
global_tool_errors.add_error(config_file, "Tool XML parsing", e)
raise e
return self._create_tool_from_source(tool_source, config_file=config_file, **kwds)
def _create_tool_from_source(self, tool_source, **kwds):
return create_tool_from_source(self.app, tool_source, **kwds)
def get_tool_components(self, tool_id, tool_version=None, get_loaded_tools_by_lineage=False, set_selected=False):
"""
Retrieve all loaded versions of a tool from the toolbox and return a select list enabling
selection of a different version, the list of the tool's loaded versions, and the specified tool.
"""
toolbox = self
tool_version_select_field = None
tools = []
tool = None
# Backwards compatibility for datasource tools that have default tool_id configured, but which
# are now using only GALAXY_URL.
tool_ids = listify(tool_id)
for tool_id in tool_ids:
if get_loaded_tools_by_lineage:
tools = toolbox.get_loaded_tools_by_lineage(tool_id)
else:
tools = toolbox.get_tool(tool_id, tool_version=tool_version, get_all_versions=True)
if tools:
tool = toolbox.get_tool(tool_id, tool_version=tool_version, get_all_versions=False)
if len(tools) > 1:
tool_version_select_field = self.__build_tool_version_select_field(tools, tool.id, set_selected)
break
return tool_version_select_field, tools, tool
def _path_template_kwds(self):
return {
"model_tools_path": MODEL_TOOLS_PATH,
}
def _get_tool_shed_repository(self, tool_shed, name, owner, installed_changeset_revision):
# Abstract toolbox doesn't have a dependency on the the database, so
# override _get_tool_shed_repository here to provide this information.
return repository_util.get_installed_repository(
self.app,
tool_shed=tool_shed,
name=name,
owner=owner,
installed_changeset_revision=installed_changeset_revision
)
def __build_tool_version_select_field(self, tools, tool_id, set_selected):
"""Build a SelectField whose options are the ids for the received list of tools."""
options = []
refresh_on_change_values = []
for tool in tools:
options.insert(0, (tool.version, tool.id))
refresh_on_change_values.append(tool.id)
select_field = SelectField(name='tool_id', refresh_on_change=True, refresh_on_change_values=refresh_on_change_values)
for option_tup in options:
selected = set_selected and option_tup[1] == tool_id
if selected:
select_field.add_option('version %s' % option_tup[0], option_tup[1], selected=True)
else:
select_field.add_option('version %s' % option_tup[0], option_tup[1])
return select_field
class DefaultToolState(object):
"""
Keeps track of the state of a users interaction with a tool between
requests.
"""
def __init__(self):
self.page = 0
self.rerun_remap_job_id = None
self.inputs = {}
def initialize(self, trans, tool):
"""
Create a new `DefaultToolState` for this tool. It will be initialized
with default values for inputs. Grouping elements are filled in recursively.
"""
self.inputs = {}
context = ExpressionContext(self.inputs)
for input in tool.inputs.itervalues():
self.inputs[input.name] = input.get_initial_value(trans, context)
def encode(self, tool, app, nested=False):
"""
Convert the data to a string
"""
value = params_to_strings(tool.inputs, self.inputs, app, nested=nested)
value["__page__"] = self.page
value["__rerun_remap_job_id__"] = self.rerun_remap_job_id
return value
def decode(self, values, tool, app):
"""
Restore the state from a string
"""
values = json_fix(safe_loads(values)) or {}
self.page = values.pop("__page__") if "__page__" in values else None
self.rerun_remap_job_id = values.pop("__rerun_remap_job_id__") if "__rerun_remap_job_id__" in values else None
self.inputs = params_from_strings(tool.inputs, values, app, ignore_errors=True)
def copy(self):
"""
Shallow copy of the state
"""
new_state = DefaultToolState()
new_state.page = self.page
new_state.rerun_remap_job_id = self.rerun_remap_job_id
new_state.inputs = self.inputs
return new_state
class Tool(object, Dictifiable):
"""
Represents a computational tool that can be executed through Galaxy.
"""
tool_type = 'default'
requires_setting_metadata = True
default_tool_action = DefaultToolAction
dict_collection_visible_keys = ['id', 'name', 'version', 'description', 'labels']
def __init__(self, config_file, tool_source, app, guid=None, repository_id=None, allow_code_files=True):
"""Load a tool from the config named by `config_file`"""
# Determine the full path of the directory where the tool config is
self.config_file = config_file
self.tool_dir = os.path.dirname(config_file)
self.app = app
self.repository_id = repository_id
self._allow_code_files = allow_code_files
# setup initial attribute values
self.inputs = odict()
self.stdio_exit_codes = list()
self.stdio_regexes = list()
self.inputs_by_page = list()
self.display_by_page = list()
self.action = '/tool_runner/index'
self.target = 'galaxy_main'
self.method = 'post'
self.labels = []
self.check_values = True
self.nginx_upload = False
self.input_required = False
self.display_interface = True
self.require_login = False
self.rerun = False
# Define a place to keep track of all input These
# differ from the inputs dictionary in that inputs can be page
# elements like conditionals, but input_params are basic form
# parameters like SelectField objects. This enables us to more
# easily ensure that parameter dependencies like index files or
# tool_data_table_conf.xml entries exist.
self.input_params = []
# Attributes of tools installed from Galaxy tool sheds.
self.tool_shed = None
self.repository_name = None
self.repository_owner = None
self.changeset_revision = None
self.installed_changeset_revision = None
self.sharable_url = None
# The tool.id value will be the value of guid, but we'll keep the
# guid attribute since it is useful to have.
self.guid = guid
self.old_id = None
self.version = None
self._lineage = None
self.dependencies = []
# populate toolshed repository info, if available
self.populate_tool_shed_info()
# add tool resource parameters
self.populate_resource_parameters(tool_source)
# Parse XML element containing configuration
try:
self.parse(tool_source, guid=guid)
except Exception as e:
global_tool_errors.add_error(config_file, "Tool Loading", e)
raise e
self.history_manager = histories.HistoryManager(app)
self._view = views.DependencyResolversView(app)
@property
def version_object(self):
return LooseVersion(self.version)
@property
def sa_session(self):
"""Returns a SQLAlchemy session"""
return self.app.model.context
@property
def lineage(self):
"""Return ToolLineage for this tool."""
return self._lineage
@property
def tool_versions(self):
# If we have versions, return them.
if self.lineage:
return self.lineage.get_versions()
else:
return []
@property
def tool_shed_repository(self):
# If this tool is included in an installed tool shed repository, return it.
if self.tool_shed:
return repository_util.get_installed_repository(self.app,
tool_shed=self.tool_shed,
name=self.repository_name,
owner=self.repository_owner,
installed_changeset_revision=self.installed_changeset_revision)
return None
@property
def produces_collections_with_unknown_structure(self):
def output_is_dynamic(output):
if not output.collection:
return False
return output.dynamic_structure
return any(map(output_is_dynamic, self.outputs.values()))
@property
def valid_input_states(self):
return model.Dataset.valid_input_states
@property
def requires_galaxy_python_environment(self):
"""Indicates this tool's runtime requires Galaxy's Python environment."""
# All special tool types (data source, history import/export, etc...)
# seem to require Galaxy's Python.
if self.tool_type != "default":
return True
config = self.app.config
preserve_python_environment = config.preserve_python_environment
if preserve_python_environment == "always":
return True
elif preserve_python_environment == "legacy_and_local" and self.repository_id is None:
return True
else:
unversioned_legacy_tool = self.old_id in GALAXY_LIB_TOOLS_UNVERSIONED
versioned_legacy_tool = self.old_id in GALAXY_LIB_TOOLS_VERSIONED
legacy_tool = unversioned_legacy_tool or \
(versioned_legacy_tool and self.version_object < GALAXY_LIB_TOOLS_VERSIONED[self.old_id])
return legacy_tool
def __get_job_tool_configuration(self, job_params=None):
"""Generalized method for getting this tool's job configuration.
:type job_params: dict or None
:returns: `galaxy.jobs.JobToolConfiguration` -- JobToolConfiguration that matches this `Tool` and the given `job_params`
"""
rval = None
if len(self.job_tool_configurations) == 1:
# If there's only one config, use it rather than wasting time on comparisons
rval = self.job_tool_configurations[0]
elif job_params is None:
for job_tool_config in self.job_tool_configurations:
if not job_tool_config.params:
rval = job_tool_config
break
else:
for job_tool_config in self.job_tool_configurations:
if job_tool_config.params:
# There are job params and this config has params defined
for param, value in job_params.items():
if param not in job_tool_config.params or job_tool_config.params[param] != value:
break
else:
# All params match, use this config
rval = job_tool_config
break
else:
rval = job_tool_config
assert rval is not None, 'Could not get a job tool configuration for Tool %s with job_params %s, this is a bug' % (self.id, job_params)
return rval
def get_job_handler(self, job_params=None):
"""Get a suitable job handler for this `Tool` given the provided `job_params`. If multiple handlers are valid for combination of `Tool` and `job_params` (e.g. the defined handler is a handler tag), one will be selected at random.
:param job_params: Any params specific to this job (e.g. the job source)
:type job_params: dict or None
:returns: str -- The id of a job handler for a job run of this `Tool`
"""
# convert tag to ID if necessary
return self.app.job_config.get_handler(self.__get_job_tool_configuration(job_params=job_params).handler)
def get_job_destination(self, job_params=None):
"""
:returns: galaxy.jobs.JobDestination -- The destination definition and runner parameters.
"""
return self.app.job_config.get_destination(self.__get_job_tool_configuration(job_params=job_params).destination)
def get_panel_section(self):
return self.app.toolbox.get_integrated_section_for_tool(self)
def allow_user_access(self, user, attempting_access=True):
"""
:returns: bool -- Whether the user is allowed to access the tool.
"""
if self.require_login and user is None:
return False
return True
def parse(self, tool_source, guid=None):
"""
Read tool configuration from the element `root` and fill in `self`.
"""
self.profile = float(tool_source.parse_profile())
# Get the UNIQUE id for the tool
self.old_id = tool_source.parse_id()
if guid is None:
self.id = self.old_id
else:
self.id = guid
if not self.id:
raise Exception("Missing tool 'id' for tool at '%s'" % tool_source)
profile = LooseVersion(str(self.profile))
if profile >= LooseVersion("16.04") and LooseVersion(VERSION_MAJOR) < profile:
template = "The tool %s targets version %s of Galaxy, you should upgrade Galaxy to ensure proper functioning of this tool."
message = template % (self.id, self.profile)
raise Exception(message)
# Get the (user visible) name of the tool
self.name = tool_source.parse_name()
if not self.name:
raise Exception("Missing tool 'name' for tool with id '%s' at '%s'" % (self.id, tool_source))
self.version = tool_source.parse_version()
if not self.version:
if self.profile < 16.04:
# For backward compatibility, some tools may not have versions yet.
self.version = "1.0.0"
else:
raise Exception("Missing tool 'version' for tool with id '%s' at '%s'" % (self.id, tool_source))
self.edam_operations = tool_source.parse_edam_operations()
self.edam_topics = tool_source.parse_edam_topics()
# Support multi-byte tools
self.is_multi_byte = tool_source.parse_is_multi_byte()
# Legacy feature, ignored by UI.
self.force_history_refresh = False
self.display_interface = tool_source.parse_display_interface(default=self.display_interface)
self.require_login = tool_source.parse_require_login(self.require_login)
request_param_translation_elem = tool_source.parse_request_param_translation_elem()
if request_param_translation_elem is not None:
# Load input translator, used by datasource tools to change names/values of incoming parameters
self.input_translator = ToolInputTranslator.from_element(request_param_translation_elem)
else:
self.input_translator = None
self.parse_command(tool_source)
self.environment_variables = self.parse_environment_variables(tool_source)
# Parameters used to build URL for redirection to external app
redirect_url_params = tool_source.parse_redirect_url_params_elem()
if redirect_url_params is not None and redirect_url_params.text is not None:
# get rid of leading / trailing white space
redirect_url_params = redirect_url_params.text.strip()
# Replace remaining white space with something we can safely split on later
# when we are building the params
self.redirect_url_params = redirect_url_params.replace(' ', '**^**')
else:
self.redirect_url_params = ''
# Short description of the tool
self.description = tool_source.parse_description()
# Versioning for tools
self.version_string_cmd = None
version_command = tool_source.parse_version_command()
if version_command is not None:
self.version_string_cmd = version_command.strip()
version_cmd_interpreter = tool_source.parse_version_command_interpreter()
if version_cmd_interpreter:
executable = self.version_string_cmd.split()[0]
abs_executable = os.path.abspath(os.path.join(self.tool_dir, executable))
command_line = self.version_string_cmd.replace(executable, abs_executable, 1)
self.version_string_cmd = version_cmd_interpreter + " " + command_line
# Parallelism for tasks, read from tool config.
self.parallelism = tool_source.parse_parallelism()
# Get JobToolConfiguration(s) valid for this particular Tool. At least
# a 'default' will be provided that uses the 'default' handler and
# 'default' destination. I thought about moving this to the
# job_config, but it makes more sense to store here. -nate
self_ids = [self.id.lower()]
if self.old_id != self.id:
# Handle toolshed guids
self_ids = [self.id.lower(), self.id.lower().rsplit('/', 1)[0], self.old_id.lower()]
self.all_ids = self_ids
# In the toolshed context, there is no job config.
if hasattr(self.app, 'job_config'):
self.job_tool_configurations = self.app.job_config.get_job_tool_configurations(self_ids)
# Is this a 'hidden' tool (hidden in tool menu)
self.hidden = tool_source.parse_hidden()
self.__parse_legacy_features(tool_source)
# Load any tool specific options (optional)
self.options = dict(
sanitize=tool_source.parse_sanitize(),
refresh=tool_source.parse_refresh(),
)
self.options = Bunch(** self.options)
# Read in name of galaxy.json metadata file and how to parse it.
self.provided_metadata_file = tool_source.parse_provided_metadata_file()
self.provided_metadata_style = tool_source.parse_provided_metadata_style()
# Parse tool inputs (if there are any required)
self.parse_inputs(tool_source)
# Parse tool help
self.parse_help(tool_source)
# Description of outputs produced by an invocation of the tool
self.parse_outputs(tool_source)
# Parse result handling for tool exit codes and stdout/stderr messages:
self.parse_stdio(tool_source)
self.strict_shell = tool_source.parse_strict_shell()
# Any extra generated config files for the tool
self.__parse_config_files(tool_source)
# Action
action = tool_source.parse_action_module()
if action is None:
self.tool_action = self.default_tool_action()
else:
module, cls = action
mod = __import__(module, globals(), locals(), [cls])
self.tool_action = getattr(mod, cls)()
# Tests
self.__parse_tests(tool_source)
# Requirements (dependencies)
requirements, containers = tool_source.parse_requirements_and_containers()
self.requirements = requirements
self.containers = containers
self.citations = self._parse_citations(tool_source)
# Determine if this tool can be used in workflows
self.is_workflow_compatible = self.check_workflow_compatible(tool_source)
self.__parse_trackster_conf(tool_source)
# Record macro paths so we can reload a tool if any of its macro has changes
self._macro_paths = tool_source._macro_paths
def __parse_legacy_features(self, tool_source):
self.code_namespace = dict()
self.hook_map = {}
self.uihints = {}
if not hasattr(tool_source, 'root'):
return
# TODO: Move following logic into XmlToolSource.
root = tool_source.root
# Load any tool specific code (optional) Edit: INS 5/29/2007,
# allow code files to have access to the individual tool's
# "module" if it has one. Allows us to reuse code files, etc.
if self._allow_code_files:
for code_elem in root.findall("code"):
for hook_elem in code_elem.findall("hook"):
for key, value in hook_elem.items():
# map hook to function
self.hook_map[key] = value
file_name = code_elem.get("file")
code_path = os.path.join(self.tool_dir, file_name)
with open(code_path) as f:
exec(compile(f.read(), code_path, 'exec'), self.code_namespace)
# User interface hints
uihints_elem = root.find("uihints")
if uihints_elem is not None:
for key, value in uihints_elem.attrib.items():
self.uihints[key] = value
def __parse_tests(self, tool_source):
self.__tests_source = tool_source
self.__tests_populated = False
def __parse_config_files(self, tool_source):
self.config_files = []
if not hasattr(tool_source, 'root'):
return
root = tool_source.root
conf_parent_elem = root.find("configfiles")
if conf_parent_elem is not None:
inputs_elem = conf_parent_elem.find("inputs")
if inputs_elem is not None:
name = inputs_elem.get("name")
filename = inputs_elem.get("filename", None)
format = inputs_elem.get("format", "json")
content = dict(format=format)
self.config_files.append((name, filename, content))
for conf_elem in conf_parent_elem.findall("configfile"):
name = conf_elem.get("name")
filename = conf_elem.get("filename", None)
content = conf_elem.text
self.config_files.append((name, filename, content))
def __parse_trackster_conf(self, tool_source):
self.trackster_conf = None
if not hasattr(tool_source, 'root'):
return
# Trackster configuration.
trackster_conf = tool_source.root.find("trackster_conf")
if trackster_conf is not None:
self.trackster_conf = TracksterConfig.parse(trackster_conf)
@property
def tests(self):
if not self.__tests_populated:
tests_source = self.__tests_source
if tests_source:
try:
self.__tests = parse_tests(self, tests_source)
except Exception:
self.__tests = None
log.exception("Failed to parse tool tests")
else:
self.__tests = None
self.__tests_populated = True
return self.__tests
def tool_provided_metadata(self, job_wrapper):
meta_file = os.path.join(job_wrapper.tool_working_directory, self.provided_metadata_file)
# LEGACY: Remove in 17.XX
if not os.path.exists(meta_file):
# Maybe this is a legacy job, use the job working directory instead
meta_file = os.path.join(job_wrapper.working_directory, self.provided_metadata_file)
if not os.path.exists(meta_file):
return output_collect.NullToolProvidedMetadata()
if self.provided_metadata_style == "legacy":
return output_collect.LegacyToolProvidedMetadata(job_wrapper, meta_file)
else:
return output_collect.ToolProvidedMetadata(job_wrapper, meta_file)
def parse_command(self, tool_source):
"""
"""
# Command line (template). Optional for tools that do not invoke a local program
command = tool_source.parse_command()
if command is not None:
self.command = command.lstrip() # get rid of leading whitespace
# Must pre-pend this AFTER processing the cheetah command template
self.interpreter = tool_source.parse_interpreter()
else:
self.command = ''
self.interpreter = None
def parse_environment_variables(self, tool_source):
return tool_source.parse_environment_variables()
def parse_inputs(self, tool_source):
"""
Parse the "<inputs>" element and create appropriate `ToolParameter`s.
This implementation supports multiple pages and grouping constructs.
"""
# Load parameters (optional)
pages = tool_source.parse_input_pages()
enctypes = set()
if pages.inputs_defined:
if hasattr(pages, "input_elem"):
input_elem = pages.input_elem
# Handle properties of the input form
self.check_values = string_as_bool(input_elem.get("check_values", self.check_values))
self.nginx_upload = string_as_bool(input_elem.get("nginx_upload", self.nginx_upload))
self.action = input_elem.get('action', self.action)
# If we have an nginx upload, save the action as a tuple instead of
# a string. The actual action needs to get url_for run to add any
# prefixes, and we want to avoid adding the prefix to the
# nginx_upload_path. This logic is handled in the tool_form.mako
# template.
if self.nginx_upload and self.app.config.nginx_upload_path:
if '?' in unquote_plus(self.action):
raise Exception('URL parameters in a non-default tool action can not be used '
'in conjunction with nginx upload. Please convert them to '
'hidden POST parameters')
self.action = (self.app.config.nginx_upload_path + '?nginx_redir=',
unquote_plus(self.action))
self.target = input_elem.get("target", self.target)
self.method = input_elem.get("method", self.method)
# Parse the actual parameters
# Handle multiple page case
for page_source in pages.page_sources:
inputs = self.parse_input_elem(page_source, enctypes)
display = page_source.parse_display()
self.inputs_by_page.append(inputs)
self.inputs.update(inputs)
self.display_by_page.append(display)
else:
self.inputs_by_page.append(self.inputs)
self.display_by_page.append(None)
self.display = self.display_by_page[0]
self.npages = len(self.inputs_by_page)
self.last_page = len(self.inputs_by_page) - 1
self.has_multiple_pages = bool(self.last_page)
# Determine the needed enctype for the form
if len(enctypes) == 0:
self.enctype = "application/x-www-form-urlencoded"
elif len(enctypes) == 1:
self.enctype = enctypes.pop()
else:
raise Exception("Conflicting required enctypes: %s" % str(enctypes))
# Check if the tool either has no parameters or only hidden (and
# thus hardcoded) FIXME: hidden parameters aren't
# parameters at all really, and should be passed in a different
# way, making this check easier.
template_macros = {}
if hasattr(tool_source, 'root'):
template_macros = template_macro_params(tool_source.root)
self.template_macro_params = template_macros
for param in self.inputs.values():
if not isinstance(param, (HiddenToolParameter, BaseURLToolParameter)):
self.input_required = True
break
def parse_help(self, tool_source):
"""
Parse the help text for the tool. Formatted in reStructuredText, but
stored as Mako to allow for dynamic image paths.
This implementation supports multiple pages.
"""
# TODO: Allow raw HTML or an external link.
self.__help = HELP_UNINITIALIZED
self.__help_by_page = HELP_UNINITIALIZED
self.__help_source = tool_source
def parse_outputs(self, tool_source):
"""
Parse <outputs> elements and fill in self.outputs (keyed by name)
"""
self.outputs, self.output_collections = tool_source.parse_outputs(self)
# TODO: Include the tool's name in any parsing warnings.
def parse_stdio(self, tool_source):
"""
Parse <stdio> element(s) and fill in self.return_codes,
self.stderr_rules, and self.stdout_rules. Return codes have a range
and an error type (fault or warning). Stderr and stdout rules have
a regular expression and an error level (fault or warning).
"""
exit_codes, regexes = tool_source.parse_stdio()
self.stdio_exit_codes = exit_codes
self.stdio_regexes = regexes
def _parse_citations(self, tool_source):
# TODO: Move following logic into ToolSource abstraction.
if not hasattr(tool_source, 'root'):
return []
root = tool_source.root
citations = []
citations_elem = root.find("citations")
if citations_elem is None:
return citations
for citation_elem in citations_elem:
if citation_elem.tag != "citation":
pass
if hasattr(self.app, 'citations_manager'):
citation = self.app.citations_manager.parse_citation(citation_elem, self.tool_dir)
if citation:
citations.append(citation)
return citations
def parse_input_elem(self, page_source, enctypes, context=None):
"""
Parse a parent element whose children are inputs -- these could be
groups (repeat, conditional) or param elements. Groups will be parsed
recursively.
"""
rval = odict()
context = ExpressionContext(rval, context)
for input_source in page_source.parse_input_sources():
# Repeat group
input_type = input_source.parse_input_type()
if input_type == "repeat":
group = Repeat()
group.name = input_source.get("name")
group.title = input_source.get("title")
group.help = input_source.get("help", None)
page_source = input_source.parse_nested_inputs_source()
group.inputs = self.parse_input_elem(page_source, enctypes, context)
group.default = int(input_source.get("default", 0))
group.min = int(input_source.get("min", 0))
# Use float instead of int so that 'inf' can be used for no max
group.max = float(input_source.get("max", "inf"))
assert group.min <= group.max, \
ValueError("Min repeat count must be less-than-or-equal to the max.")
# Force default to be within min-max range
group.default = min(max(group.default, group.min), group.max)
rval[group.name] = group
elif input_type == "conditional":
group = Conditional()
group.name = input_source.get("name")
group.value_ref = input_source.get('value_ref', None)
group.value_ref_in_group = input_source.get_bool('value_ref_in_group', True)
value_from = input_source.get("value_from", None)
if value_from:
value_from = value_from.split(':')
group.value_from = locals().get(value_from[0])
group.test_param = rval[group.value_ref]
group.test_param.refresh_on_change = True
for attr in value_from[1].split('.'):
group.value_from = getattr(group.value_from, attr)
for case_value, case_inputs in group.value_from(context, group, self).items():
case = ConditionalWhen()
case.value = case_value
if case_inputs:
page_source = XmlPageSource(ElementTree.XML("<when>%s</when>" % case_inputs))
case.inputs = self.parse_input_elem(page_source, enctypes, context)
else:
case.inputs = odict()
group.cases.append(case)
else:
# Should have one child "input" which determines the case
test_param_input_source = input_source.parse_test_input_source()