forked from INCF/xnnppx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xnnppx.py
289 lines (262 loc) · 11 KB
/
xnnppx.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
import sys
import os
import datetime
import urllib2
import smtplib
from copy import deepcopy
import email.mime.text
import xml.dom.minidom
import suds.client
import suds.xsd.doctor
import suds.transport.http
import nipype.pipeline.engine
import nipype.pipeline.plugins.linear
from nipype.pipeline.plugins.base import report_nodes_not_run
from nipype.pipeline.plugins.base import str2bool
from nipype.pipeline.plugins.base import report_crash
from nipype.pipeline.utils import nx
from nipype.pipeline.utils import dfs_preorder
from nipype.pipeline.engine import MapNode
from nipype.utils.logger import config
from nipype.utils.logger import logger
from nipype.pipeline.utils import merge_dict
from nipype.pipeline.utils import generate_expanded_graph
class WorkflowNotFoundError(Exception):
"""workflow not found"""
class WorkflowInfo:
"""class for mirroring workflow information (XML) in XNAT"""
def _call(self,
jws,
operation,
inputs,
authenticated=False,
fix_import=False):
"""perform a SOAP call"""
url = '%s/axis/%s' % (self._base_url, jws)
if authenticated:
t = suds.transport.http.HttpAuthenticated(username=self._username,
password=self._password)
else:
t = suds.transport.http.HttpTransport()
if self._cookiejar is not None:
t.cookiejar = self._cookiejar
if fix_import:
xsd_url = 'http://schemas.xmlsoap.org/soap/encoding/'
imp = suds.xsd.doctor.Import(xsd_url)
doctor = suds.xsd.doctor.ImportDoctor(imp)
client = suds.client.Client('%s?wsdl' % url,
transport=t,
doctor=doctor)
else:
client = suds.client.Client('%s?wsdl' % url, transport=t)
typed_inputs = []
for (dtype, val) in inputs:
ti = client.factory.create(dtype)
ti.value = val
typed_inputs.append(ti)
# the WSDL returns the local IP address in the URLs; these need
# to be corrected if XNAT is behind a proxy
client.set_options(location=url)
f = getattr(client.service, operation)
result = f(*typed_inputs)
if self._cookiejar is None:
self._cookiejar = t.cookiejar
return result
def __init__(self, base_url, username, password, workflow_id):
self._base_url = base_url
self._username = username
self._password = password
self._cookiejar = None
res = self._call('CreateServiceSession.jws',
'execute',
(),
authenticated=True)
self._session = str(res)
args = (('ns1:string', self._session),
('ns1:string', 'wrk:workflowData.ID'),
('ns1:string', '='),
('ns1:string', workflow_id),
('ns1:string', 'wrk:workflowData'))
workflow_ids = self._call('GetIdentifiers.jws', 'search', args)
self._doc = None
for w_id in workflow_ids:
url = '%s/app/template/XMLSearch.vm/id/%s/data_type/wrk:workflowData' % (self._base_url, str(w_id))
r = urllib2.Request(url)
self._cookiejar.add_cookie_header(r)
data = urllib2.urlopen(r).read()
doc = xml.dom.minidom.parseString(data)
workflow_node = doc.getElementsByTagName('wrk:Workflow')[0]
status = workflow_node.getAttribute('status').lower()
if status in ('queued', 'awaiting action', 'hold'):
self._doc = doc
break
if self._doc is None:
raise WorkflowNotFoundError
return
def _close(self):
"""close the XNAT session (log out)"""
self._call('CloseServiceSession.jws', 'execute', ())
return
def _update_xnat(self):
"""update XNAT with the current state of this (WorkflowInfo) object"""
inputs = (('ns0:string', self._session),
('ns0:string', self._doc.toxml()),
('ns0:boolean', False),
('ns0:boolean', True))
self._call('StoreXML.jws',
'store',
inputs,
authenticated=True,
fix_import=True)
return
def _append_node(self, root, name, value):
"""add a simple text node with tag "name" and data "value" under
the node "root"
"""
node = self._doc.createElement(name)
node.appendChild(self._doc.createTextNode(value))
root.appendChild(node)
return
def set_environment(self, arguments, parameters):
"""set the execution environment
should be run only once before update() is called
"""
# order is important
workflow_node = self._doc.getElementsByTagName('wrk:Workflow')[0]
ee_node = self._doc.createElement('wrk:executionEnvironment')
ee_node.setAttribute('xsi:type', 'wrk:xnatExecutionEnvironment')
workflow_node.appendChild(ee_node)
self._append_node(ee_node, 'wrk:pipeline', arguments['pipeline'])
self._append_node(ee_node, 'wrk:xnatuser', arguments['u'])
self._append_node(ee_node, 'wrk:host', arguments['host'])
params_node = self._doc.createElement('wrk:parameters')
ee_node.appendChild(params_node)
for key in parameters:
param_node = self._doc.createElement('wrk:parameter')
param_node.setAttribute('name', key)
for val in parameters[key]:
param_node.appendChild(self._doc.createTextNode(val))
params_node.appendChild(param_node)
for email in arguments['notify_emails']:
self._append_node(ee_node, 'wrk:notify', email)
self._append_node(ee_node, 'wrk:dataType', arguments['dataType'])
self._append_node(ee_node, 'wrk:id', arguments['id'])
if arguments['notify_flag']:
self._append_node(ee_node, 'wrk:supressNotification', '0')
else:
self._append_node(ee_node, 'wrk:supressNotification', '1')
return
def update(self, step_id, step_description, percent_complete):
"""update the workflow in XNAT"""
workflow_node = self._doc.getElementsByTagName('wrk:Workflow')[0]
workflow_node.setAttribute('status', 'Running')
t = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
workflow_node.setAttribute('current_step_launch_time', t)
workflow_node.setAttribute('current_step_id', step_id)
workflow_node.setAttribute('step_description', step_description)
workflow_node.setAttribute('percentageComplete', percent_complete)
self._update_xnat()
return
def complete(self):
"""mark the workflow comleted in XNAT and close the session"""
workflow_node = self._doc.getElementsByTagName('wrk:Workflow')[0]
workflow_node.setAttribute('status', 'Complete')
t = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
workflow_node.setAttribute('current_step_launch_time', t)
workflow_node.setAttribute('percentageComplete', '100.0')
try:
workflow_node.removeAttribute('current_step_id')
except xml.dom.NotFoundErr:
pass
try:
workflow_node.removeAttribute('step_description')
except xml.dom.NotFoundErr:
pass
self._update_xnat()
self._close()
return
def fail(self, description=None):
"""mark the workflow failed in XNAT and close the session"""
workflow_node = self._doc.getElementsByTagName('wrk:Workflow')[0]
workflow_node.setAttribute('status', 'Failed')
if description is not None:
workflow_node.setAttribute('step_description', description)
self._update_xnat()
self._close()
return
class Workflow(nipype.pipeline.engine.Workflow):
def run(self, plugin_args=None, updatehash=False):
""" Execute the workflow
XNAT-modified Linear runner only
plugin_args : dictionary containing arguments to be sent to plugin
constructor. see individual plugin doc strings for details.
"""
runner = LinearPlugin(plugin_args=plugin_args)
flatgraph = self._create_flat_graph()
self.config = merge_dict(deepcopy(config._sections), self.config)
logger.info(str(sorted(self.config)))
self._set_needed_outputs(flatgraph)
execgraph = generate_expanded_graph(deepcopy(flatgraph))
for index, node in enumerate(execgraph.nodes()):
node.config = self.config
node.base_dir = self.base_dir
node.index = index
if isinstance(node, MapNode):
node.use_plugin = (plugin, plugin_args)
self._configure_exec_nodes(execgraph)
self._write_report_info(self.base_dir, self.name, execgraph)
runner.run(execgraph, updatehash=updatehash, config=self.config)
return execgraph
class LinearPlugin(nipype.pipeline.plugins.linear.LinearPlugin):
"""Execute workflow in series
"""
def run(self, graph, config, updatehash=False):
"""Executes a pre-defined pipeline in a serial order.
modifed for XNAT workflow XML updates
Parameters
----------
graph : networkx digraph
defines order of execution
"""
if not isinstance(graph, nx.DiGraph):
raise ValueError('Input must be a networkx digraph object')
logger.info("Running serially.")
old_wd = os.getcwd()
notrun = []
donotrun = []
nodes = nx.topological_sort(graph)
for (i, node) in enumerate(nodes):
try:
pct = 100.0*i/len(nodes)
workflow_info.update(str(i+1), str(node), '%.1f' % pct)
if node in donotrun:
continue
node.run(updatehash=updatehash)
except:
os.chdir(old_wd)
if str2bool(config['execution']['stop_on_first_crash']):
raise
# bare except, but i really don't know where a
# node might fail
crashfile = report_crash(node)
# remove dependencies from queue
subnodes = [s for s in dfs_preorder(graph, node)]
notrun.append(dict(node = node,
dependents = subnodes,
crashfile = crashfile))
donotrun.extend(subnodes)
report_nodes_not_run(notrun)
def send_mail(to_addrs, subject, body):
if not to_addrs:
return
message = email.message.Message()
message['From'] = from_email
for addr in to_addrs:
message['To'] = addr
message['Subject'] = subject
message.set_payload(body)
s = smtplib.SMTP(mail_host)
s.sendmail(from_email, to_addrs, message.as_string())
s.quit()
return
# eof