forked from b3c/wfmng-vph-share
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wfmng.py
1532 lines (1311 loc) · 59.9 KB
/
wfmng.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) 2012 SCS srl <[email protected]>
"""
The **Workflow Manager** is a core *Hypermodel* Application.
It maps workflows and users, manages sessions, serializes workflows and
logs. Is the frontend for all other hypermodel application.
"""
import sys
import os
import smtplib
from datetime import datetime, timedelta
import argparse
from email.mime.text import MIMEText
from raven.contrib.flask import Sentry
from flask import Flask, render_template
try:
from flaskext.xmlrpc import XMLRPCHandler
except ImportError, e:
from flask.ext.xmlrpc import XMLRPCHandler
try:
from flaskext.sqlalchemy import SQLAlchemy
except ImportError, e:
from flask.ext.sqlalchemy import SQLAlchemy
try:
from flaskext.login import *
except ImportError, e:
from flask.ext.login import *
from flask.ext.login import UserMixin, login_required
from auth import extractUserFromTicket
import requests
# requirements for createOutputFolders
import xmltodict
import string
import base64
from cyfronet import easywebdav
from cfinterface import CloudFacadeInterface
import time
############################################################################
# create and configure main application
app = Flask(__name__)
# read configuration file
if os.path.exists("local.wfmng.cfg"):
app.config.from_pyfile("local.wfmng.cfg")
else:
app.config.from_pyfile("wfmng.cfg")
############################################################################
# connect xmlrpc handler to app
xmlrpc = XMLRPCHandler("xmlrpc")
xmlrpc.connect(app, '/api')
############################################################################
# create the Cloud server connector
serverManager = CloudFacadeInterface(app.config["CLOUDFACACE_URL"])
############################################################################
# configure database
# app.config['SQLALCHEMY_DATABASE_URI'] =
# 'postgresql://tiger:scot@localhost/wfmng'
# SQLAlchemy Database Connector
db = SQLAlchemy(app)
sentry = Sentry(app, dsn=app.config["SENTRY_DNS"])
class Workflow(db.Model):
"""
This class represents a Workfow into the database
Fields:
**workflowId** (string): the workflow unique identifier (primary key)
username (string): the workflow owner
title (string): the workflow title
status (string): the workflow status
createTime (string): the creation time iso-format string
startTime (string): the start time iso-format string
finishTime (string): the finish time iso-format string
expiry (string): the expiration time iso-format string
exitcode (string): the taverna command line exit code
stdout (string): the taverna command line standard out stream
stderr (string): the taverna command line standard error stream
output (string): xml document specifying the workflow outputs
"""
workflowRunId = db.Column(db.String(80), primary_key=True)
username = db.Column(db.String(80), primary_key=False)
title = db.Column(db.String(120), primary_key=False)
status = db.Column(db.String(20), primary_key=False)
createTime = db.Column(db.String(30), primary_key=False)
startTime = db.Column(db.String(30), primary_key=False)
finishTime = db.Column(db.String(30), primary_key=False)
expiry = db.Column(db.String(30), primary_key=False)
exitcode = db.Column(db.String(5), primary_key=False)
stdout = db.Column(db.String(2048), primary_key=False)
stderr = db.Column(db.String(2048), primary_key=False)
outputfolder = db.Column(db.String(2048), primary_key=False)
output = db.Column(db.String(2048), primary_key=False)
def __init__(self,
username,
workflowId,
title,
outputfolder,
status="Initialized",
createTime="",
startTime="",
finishTime="",
expiry="",
exitcode="",
stdout="",
stderr="",
output=""):
self.username = username
self.workflowRunId = workflowId
self.title = title
self.status = status
self.createTime = createTime
self.startTime = startTime
self.finishTime = finishTime
self.expiry = expiry
self.exitcode = exitcode
self.stdout = stdout
self.stderr = stderr
self.outputfolder = outputfolder
self.output = output
def __repr__(self):
return '<Workflow %r-%r>' % (self.username, self.workflowId)
def toDictionary(self):
""" return a dictionary with the given workflow """
ret = {'workflowId': self.workflowId,
'status': self.status,
'title': self.title,
'createTime': self.createTime,
'startTime': self.startTime,
'finishTime': self.finishTime,
'expiry': self.expiry,
'exitcode': self.exitcode,
'stdout': self.stdout,
'stderr': self.stderr,
'owner': self.username,
'outputfolder': self.outputfolder,
'output': self.output}
return ret
def update(self, d):
""" update the worfklow according to the given dictionary """
for key in dir(self):
if key in d:
setattr(self, key, d[key])
class SessionCache(db.Model):
""" This class caches a session item into the database.
It is not used for authentication purpose, it only caches useful information.
Fields:
**username** (string): the user identifier (primary key)
email (string): the user email address
tkt (string): the authentication ticket
"""
username = db.Column(db.String(80), primary_key=True)
email = db.Column(db.String(80), primary_key=False)
tkt = db.Column(db.String(), primary_key=False)
def __init__(self, username, email, tkt):
self.username = username
self.email = email
self.tkt = tkt
def __repr__(self):
return '<UserCache %r-%r>' % (self.username, self.tkt)
class Execution(db.Model):
username = db.Column(db.String(80), primary_key=False)
eid = db.Column(db.Integer(), primary_key=True)
status = db.Column(db.Integer(), primary_key=False)
tavernaId = db.Column(db.String(80), primary_key=False)
workflowRunId = db.Column(db.String(80), primary_key=False)
error = db.Column(db.Boolean(), primary_key=False)
error_msg = db.Column(db.String(80), primary_key=False)
def __init__(self,
username,
eid,
status=0,
tavernaId='',
workflowRunId=''):
self.username = username
self.eid = eid
self.status = status
self.tavernaId = tavernaId
self.workflowRunId = workflowRunId
self.error = False
self.error_msg = ''
class TavernaServer(db.Model):
""" This class represents a Taverna Server workflow (i.e. a workflow containing an AS running a Taverna Server) in the database
Fields:
**username** (string): the user identifier (primary key)
**url** (string): url for the web endpoint of the server
**workflowId** (string): id of the workflow containing the Taverna Server
**asConfigId** (string): configuration id of the atomic service running the server
**count** (integer): number of workflows running in the server at a given time
"""
username = db.Column(db.String(80), primary_key=True)
url = db.Column(db.String(80), primary_key=True)
workflowId = db.Column(db.String(80), primary_key=True)
asConfigId = db.Column(db.String(80), primary_key=True)
userAndPass = db.Column(db.String(80), primary_key=True)
tavernaServerCloudId = db.Column(db.String(80), primary_key=True)
valid = db.Column(db.Boolean())
def __init__(self,
username,
endpoint,
workflowId,
asConfigId,
tavernaServerCloudId,
tavernaUser='taverna',
tavernaPass='taverna'):
self.username = username
self.url = endpoint
self.workflowId = workflowId
self.asConfigId = asConfigId
self.userAndPass = base64.b64encode(tavernaUser + ":" + tavernaPass)
self.tavernaServerCloudId = tavernaServerCloudId
self.valid = False
def isAlive(self):
response = requests.get(
self.url,
headers={
'Authorization': 'Basic %s' % self.userAndPass,
'Accept': 'application/json'
},
verify=False)
if response.status_code == 200:
return True
return False
def isWorkflowAlive(self, wfRunId):
response = requests.get(
"%s/%s" % (self.url, wfRunId),
headers={
'Authorization': 'Basic %s' % self.userAndPass,
'Accept': 'application/json'
},
verify=False)
if response.status_code == 200:
return True
return False
def getWorkflowRunNumber(self):
response = requests.get(
"%s" % (self.url),
headers={
'Authorization': 'Basic %s' % self.userAndPass,
'Accept': 'application/json'
},
verify=False)
if response.status_code == 200:
ret = response.json()
if ret['runList'] == "":
return 0
listWf = ret['runList'].get('run', False)
if listWf:
if type(listWf) is list:
return len(listWf)
else:
return 1
return 0
def createWorkflow(self, workflowDefinition):
""" Create a new workflow according to the given definition string.
Arguments:
workflowDefinition (string): the workflow definition file string buffer
Returns:
dictionary::
Success -- 'workflow run id'
Failure -- raise Exception with possible error message
"""
wf = workflowDefinition
response = requests.post(
self.url,
data=wf,
headers={
'Content-type': 'application/vnd.taverna.t2flow+xml',
'Authorization': 'Basic %s' % self.userAndPass,
#'Accept': 'application/json'
},
allow_redirects=False,
verify=False)
if response.status_code in [201, 200]:
# workflow has been correctly created
wfRunId = response.headers['location'].split("/")[-1]
#wfRunId = response.url.split("/")[-1]
return wfRunId
raise Exception("Submitting workflow failed " + response.text)
def setPlugins(self, wfRunId, pluginDefinition):
""" Takes the contents of a plugin.xml file, and then creates this file in the server
Arguments:
workflowId (string): the workflow unique identifier
pluginDefinition (string): the plugin definition file string buffer
Returns:
dictionary::
Success -- True
Failure -- raise errors with message
"""
plugins = """<t2sr:upload t2sr:name="plugins.xml" xmlns:t2sr="http://ns.taverna.org.uk/2010/xml/server/rest/">%s</t2sr:upload>""" % base64.b64encode(
pluginDefinition)
response = requests.post(
"%s/%s/wd/plugins" % (self.url, wfRunId),
data=plugins,
headers={
"Content-type": "application/xml",
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 201:
return True
raise Exception("Plugin setting failed " + response.text)
def setPluginProperties(self, wfRunId, propertiesFileName,
propertiesDefinition):
""" Creates a properties file with the specified filename and content, and uploads the file to the server
Arguments:
workflowId (string): the workflow unique identifier
propertiesFileName (string): the name of the properties file to be created
propertiesDefinition (string): the content of the properties file
Returns:
dictionary::
Success -- True
Failure -- Raise exception with message
"""
properties = """<t2sr:upload t2sr:name="%s" xmlns:t2sr="http://ns.taverna.org.uk/2010/xml/server/rest/">%s</t2sr:upload>""" % (
propertiesFileName, base64.b64encode(propertiesDefinition))
response = requests.post(
"%s/%s/wd/conf" % (self.url, wfRunId),
data=properties,
headers={
"Content-type": "application/xml",
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 201:
return True
raise Exception("Plugin properties setting failed " + response.text)
def setTicket(self, wfRunId, ticket):
""" Stores the specified ticket in the working directory of the workflow with the specified id
Arguments:
workflowId (string): the workflow unique identifier
ticket (string): a valid authentication ticket
Returns:
dictionary::
Success -- True
Failure -- raise Exception with message
"""
credential = """<t2sr:upload t2sr:name="ticket" xmlns:t2sr="http://ns.taverna.org.uk/2010/xml/server/rest/">%s</t2sr:upload>""" % base64.b64encode(
ticket)
response = requests.post(
"%s/%s/wd/conf" % (self.url, wfRunId),
data=credential,
headers={
"Content-type": "application/xml",
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 201:
return True
raise Exception("Ticket setting failed " + response.text)
def setTrustedIdentity(self, wfRunId, identityFileName,
identityDefinition):
""" Takes the name of the certificate file, reads the contents of the file and submits the file contents to the server
Arguments:
workflowId (string): the workflow unique identifier
identityFileName (string): name of the certificate file
identityDefinition (string): contents of the certificate file
Returns:
dictionary::
Success -- True
Failure -- raise Exception with message
"""
identity = """<t2sr:trustedIdentity xmlns:t2sr="http://ns.taverna.org.uk/2010/xml/server/" xmlns:t2s="http://ns.taverna.org.uk/2010/xml/server/"><t2s:certificateFile>%s</t2s:certificateFile><t2s:certificateBytes>%s</t2s:certificateBytes></t2sr:trustedIdentity>""" % (
base64.b64encode(identityFileName),
base64.b64encode(identityDefinition))
response = requests.post(
"%s/%s/security/trusts" % (self.url, wfRunId),
data=identity,
headers={
"Content-type": "application/xml",
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 201:
return True
raise Exception("Trusted Identity setting failed " + response.text)
def setWorkflowInputs(self, wfRunId, inputDefinition):
""" Take the inputs definition string and create a baclava.xml file for the workflow with the given id.
Arguments:
workflowId (string): the workflowd unique identifier
workflowDefinition (string): the workflow definition file string buffer
inputDefinition (string): the input definition file string buffer:param workflowId: the id unique identifier
defaultInputMap (map): a map with the default inputs to be added to all (i.e. defaultInputMap = {'sessionTicket': <sessionTicket<, 'workflowId': >workflowId>, ...}
Returns:
dictionary::
Success -- True
Failure -- Raise Exception with message
"""
try:
baclava = """<t2sr:upload xmlns:t2sr="http://ns.taverna.org.uk/2010/xml/server/rest/" t2sr:name="baclava.xml">%s</t2sr:upload>""" % base64.b64encode(
inputDefinition)
response = requests.post(
"%s/%s/wd" % (self.url, wfRunId),
data=baclava,
headers={
"Content-type": "application/xml",
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 201:
# PUT baclava
response2 = requests.put(
"%s/%s/input/baclava" % (self.url, wfRunId),
headers={
"Content-type": "text/plain",
'Authorization': 'Basic %s' % self.userAndPass
},
data="baclava.xml", )
if response2.status_code == 200:
return True
raise Exception("Workflow input setting failed " + response.text)
except Exception, e:
print e
raise Exception("Workflow input setting failed " + response.text)
def getWorkflowInputs(self, wfRunId):
"""
Retrieve the workflow inputs file from taverna server
:param workflowId:
:return:
"""
response = requests.get(
"%s/%s/wd/baclava.xml" % (self.url, wfRunId),
headers={
'Accept':
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 200:
return response.text
return ""
def getWorkflowOutput(self, wfRunId, port):
"""
Retrieves the value of a workflow port from taverna server
:param workflowId:
:param port:
:return:
"""
response = requests.get(
"%s/%s/wd/out/%s" % (self.url, wfRunId, port),
headers={
'Accept':
'text/plain,text/html,application/xml;q=0.9,*/*;q=0.8',
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 200:
return response.text
return ""
def enhanceWorkflowOutputs(self, wfRunId, outputXML):
"""
Return an improved and simpler version of the specified output XML
:param workflowId:
:param outputXML:
:return:
"""
out = ""
try:
outputXMLContent = xmltodict.parse(outputXML)
if u'port:absent' in outputXMLContent[u'port:workflowOutputs'][
u'port:output']:
return outputXMLContent[u'port:workflowOutputs'][
u'port:output'][u'@port:name'] + "="
if outputXMLContent[u'port:workflowOutputs'][u'port:output'][
u'@port:depth'] == u'0':
port = outputXMLContent[u'port:workflowOutputs'][
u'port:output']
out = port[u'@port:name'] + "="
value = self.getWorkflowOutput(wfRunId, port[u'@port:name'])
out = out + value
if outputXMLContent[u'port:workflowOutputs'][u'port:output'][
u'@port:depth'] == u'1':
port = outputXMLContent[u'port:workflowOutputs'][
u'port:output']
count = int(port['port:list']['@port:length'])
value = ""
for i in range(count):
if out != "":
out = out + ", "
out = out + port[u'@port:name'] + "="
value = self.getWorkflowOutput(
wfRunId, port[u'@port:name'] + "/" + str(i + 1))
out = out + value
except Exception, e:
pass
out = "Could not parse: " + outputXML
return out
def getWorkflowDefinition(self, wfRunId):
"""
Retrieve the workflow file from taverna server
:param workflowId:
:return:
"""
response = requests.get(
"%s/%s/workflow" % (self.url, wfRunId),
headers={
"Content-type": "text/plain",
'Authorization': 'Basic %s' % self.userAndPass
},
allow_redirects=True,
verify=False)
if response.status_code == 200:
return response.text
return ""
def getRunInformations(self, wfRunId=''):
""" return the basic information associated to the given workflow id
Arguments:
workflowId (string): the workflow unique identifier
Returns:
dictionary::
Success -- {'workflowId':'a string value', 'info01':'a string value', 'info02':'a string value',..}
Failure -- {'workflowId':'', 'error.description':'', error.code:''}
"""
ret = {
'status': '',
'createTime': '',
'startTime': '',
'finishTime': '',
'expiry': '',
'exitcode': '',
'stdout': '',
'stderr': '',
'outputfolder': '',
'endpoint': '',
'workflowId': '',
'asConfigId': '',
'tavernaRunning': '',
'owner': '',
'wfRunning': '',
'output': ''
}
ret['endpoint'] = self.url
ret['workflowId'] = self.workflowId
ret['asConfigId'] = self.asConfigId
ret['tavernaRunning'] = self.isAlive()
ret['owner'] = self.username
if wfRunId:
wfJob = Workflow.query.filter_by(workflowRunId=wfRunId).first()
ret['wfRunning'] = self.isWorkflowAlive(wfRunId)
if wfJob:
ret['outputfolder'] = wfJob.outputfolder
else:
ret['wfRunning'] = False
return ret
if ret['wfRunning']:
infos = ["status", "createTime", "expiry", "startTime",
"finishTime"]
for info in infos:
headers = {"Content-type": "text/plain",
'Authorization': 'Basic %s' % self.userAndPass}
ret[info] = self.getInfo(wfRunId, info, headers)
additional_info = {'stderr': "listeners/io/properties/stderr",
'stdout': "listeners/io/properties/stdout",
'exitcode': "listeners/io/properties/exitcode"}
for info in additional_info.keys():
ret[info] = self.getInfo(wfRunId, additional_info[info],
headers)
headers = {"Content-type": "text/plain",
'Authorization': 'Basic %s' % self.userAndPass,
'Accept': 'application/xml'}
out = self.getInfo(wfRunId, "output", headers)
if out != "":
enhanced = self.enhanceWorkflowOutputs(wfRunId, out)
if len(enhanced) >= len(wfJob.output):
ret['output'] = enhanced # enhanced outputs should increase in lenght with time. A decrease is an indication of a prossible synchronization problem.
else:
ret['output'] = wfJob.output # when in doubt, use the previous value
else:
ret['output'] = wfJob.output
if wfJob:
wfJob.update(ret)
db.session.commit()
elif wfJob:
ret.update({
'status': wfJob.status,
'createTime': wfJob.createTime,
'startTime': wfJob.startTime,
'finishTime': wfJob.finishTime,
'expiry': wfJob.expiry,
'exitcode': wfJob.exitcode,
'stdout': wfJob.stdout,
'stderr': wfJob.stderr,
'outputfolder': wfJob.outputfolder,
'output': wfJob.output
})
return ret
def getInfo(self, wfRunId, info, headers):
""" return the workflow id requested info as a string
Arguments:
wfRunId (string): the workflow unique identifier
info (string): code name for the information requested
headers (string): headers for the GET operation
Returns:
string. The requested info as a string
"""
response = requests.get('%s/%s/%s' % (self.url, wfRunId, info),
headers=headers,
verify=False)
if response.status_code == 200:
return response.content
return ""
def startWorkflow(self, wfRunId):
""" start the workflow with the given workflow id
Arguments:
workflowId (string): the workflow unique identifier
Returns:
dictionary::
Success -- Ture
Failure -- False
"""
response = requests.put(
"%s/%s/status" % (self.url, wfRunId),
data="Operating",
headers={
"Content-type": "text/plain",
'Authorization': 'Basic %s' % self.userAndPass
},
verify=False)
if response.status_code in [200, 201, 202]:
return True
raise Exception('Error starting workflow on Taverna Server %s' %
response.status_code)
def setExpiry(self, wfRunId, expiry):
""" set a new expiry date
Arguments:
wfRunId (string): the workflow run unique identifier
Returns:
dictionary::
Success -- {'workflowId':'a string value', 'info01':'a string value', 'info02':'a string value',..}
Failure -- {'workflowId':'', 'error.description':'', error.code:''}
"""
response = requests.put(
"%s/%s/expiry" % (self.url, wfRunId),
data=expiry,
headers={
"Content-type": "text/plain",
'Authorization': 'Basic %s' % self.userAndPass
},
verify=False)
if response.status_code in [200, 201, 202]:
return True
return False
def deleteWorkflow(self, wfRunId):
""" delete the workflow with the given workflow id
Arguments:
workflowId (string): the workflow unique identifier
Returns:
dictionary::
Success -- True
Failure -- False
"""
if self.isWorkflowAlive(wfRunId):
response = requests.delete(
"%s/%s" % (self.url, wfRunId),
headers={
"Content-type": "text/plain",
'Authorization': 'Basic %s' % self.userAndPass
},
verify=False)
if response.status_code == 204:
return True
else:
return True
return False
def toDictionary(self):
""" return a dictionary with object properties"""
return {'username': self.username,
'url': self.url,
'workflowId': self.workflowId,
'asConfigId': self.asConfigId,
'count': self.count}
############################################################################
# html methods
@app.route("/")
def hello():
""" index method return the application title
Routed at: "/"
"""
return "Welcome to the VPH-Share Workflow Manager Application"
############################################################################
# utility methods
def alert_user_by_email(mail_from,
mail_to,
subject,
mail_template,
dictionary={}):
"""
Send an email to the user with the given template
This method will be replaced by the Master Interface notification service
"""
msg = MIMEText(render_template(mail_template, **dictionary), 'html')
msg['Subject'] = subject
msg['From'] = mail_from
msg['To'] = mail_to
try:
s = smtplib.SMTP(app.config.get('SMTP_HOST', '') or 'localhost')
s.sendmail(mail_from, mail_to, msg.as_string())
s.quit()
except BaseException, e:
pass
def notify_user_by_mi():
"""
send a notification message that will be shown to the Master interface
"""
def submition_work_around(execution, server, ticket, tavernaURL,
workflowDefinition):
workflow_worker_built_failed = True
while workflow_worker_built_failed:
serverManager.deleteWorkflow(server.workflowId, ticket)
server.valid = False
db.session.commit()
tavernaServerId = serverManager.createWorkflow(ticket)
atomicServiceConfigId = serverManager.getAtomicServiceConfigId(
server.tavernaServerCloudId, ticket)
if tavernaServerId and atomicServiceConfigId:
print "retry::Taverna Server id %s, atomic config id %s" % (
str(tavernaServerId), str(atomicServiceConfigId))
appliance_configuration_instance_id = serverManager.startAtomicService(
atomicServiceConfigId, tavernaServerId, ticket)
if appliance_configuration_instance_id:
endpoint = app.config["CLOUDFACACE_PROXY_ENDPOINT"] % str(
appliance_configuration_instance_id)
if endpoint:
if tavernaURL is not "":
endpoint = tavernaURL
print "retry::Taverna Server endpoint %s" % endpoint
# now it can be created Taverna server instance
server.url = endpoint
server.workflowId = tavernaServerId
server.asConfigId = atomicServiceConfigId
execution.tavernaId = tavernaServerId
db.session.commit()
else:
raise Exception('Error booting Taverna server')
else:
raise Exception('Error starting Atomic service')
else:
raise Exception('Error contacting cloud facade service')
timeout = 50
while server.isAlive() is not True and timeout > 0:
timeout -= 1
time.sleep(5)
if timeout == 0:
raise Exception('Taverna Server is not reachable.')
try:
return server.createWorkflow(workflowDefinition)
except Exception, e:
## here start the implementation of the workaround
# the workaround restart anytime the Taverna Server in the cloud
# until the WM is not able to submit the workflow.
sentry.captureException()
workflow_worker_built_failed = (
e.message ==
"Submitting workflow failed failed to build workflow run worker"
)
raise Exception("Submitting workflow failed")
############################################################################
# xmlrpc methods
def execute_workflow(ticket,
eid,
workflowTitle,
tavernaServerCloudId,
workflowDefinition,
inputDefinition,
tavernaURL="",
submitionWorkAround=False):
user = extractUserFromTicket(ticket)
execution = Execution.query.filter_by(username=user['username'],
eid=eid).first()
if execution is not None:
#reset execution before start
deleteExecution(eid, ticket)
execution = Execution(user['username'], eid)
db.session.add(execution)
db.session.commit()
#Now we don't have a stable taverna server then we have to create a new one for every execution
server = TavernaServer.query.filter_by(
username=user['username'],
tavernaServerCloudId=tavernaServerCloudId,
valid=True).first()
# remeber try execept
try:
if server is None or server.isAlive() is not True:
#if the server is not avaible ask to the cloud to start a new one
tavernaServerId = serverManager.createWorkflow(ticket)
atomicServiceConfigId = serverManager.getAtomicServiceConfigId(
tavernaServerCloudId, ticket)
if tavernaServerId and atomicServiceConfigId:
execution.status = 1
print "Taverna Server id %s, atomic config id %s" % (
str(tavernaServerId), str(atomicServiceConfigId))
db.session.commit()
appliance_configuration_instance_id = serverManager.startAtomicService(
atomicServiceConfigId, tavernaServerId, ticket)
if appliance_configuration_instance_id:
execution.status = 2
db.session.commit()
endpoint = app.config["CLOUDFACACE_PROXY_ENDPOINT"] % str(
appliance_configuration_instance_id)
if endpoint:
if tavernaURL is not "":
endpoint = tavernaURL
print "Taverna Server endpoint %s" % endpoint
# now it can be created Taverna server instance
server = TavernaServer(
user['username'], endpoint, tavernaServerId,
atomicServiceConfigId, tavernaServerCloudId)
execution.tavernaId = tavernaServerId
execution.status = 3
db.session.add(server)
db.session.commit()
else:
raise Exception('Error booting Taverna server')
else: