forked from mxcube/HardwareObjects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ISPyBClient2.py
2270 lines (1844 loc) · 81.5 KB
/
ISPyBClient2.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
"""
A client for ISPyB Webservices.
"""
import logging
import gevent
import suds; logging.getLogger("suds").setLevel(logging.INFO)
import os
import itertools
import time
from suds.transport.http import HttpAuthenticated
from suds.client import Client
from suds import WebFault
from suds.sudsobject import asdict
from urllib.error import URLError
from HardwareRepository.BaseHardwareObjects import HardwareObject
from datetime import datetime
from collections import namedtuple
from pprint import pformat
# Production web-services: http://160.103.210.1:8080/ispyb-ejb3/ispybWS/
# Test web-services: http://160.103.210.4:8080/ispyb-ejb3/ispybWS/
# The WSDL root is configured in the hardware object XML file.
#_WS_USERNAME, _WS_PASSWORD can be configured in the HardwareObject XML file.
_WSDL_ROOT = ''
_WS_BL_SAMPLE_URL = _WSDL_ROOT + 'ToolsForBLSampleWebService?wsdl'
_WS_SHIPPING_URL = _WSDL_ROOT + 'ToolsForShippingWebService?wsdl'
_WS_COLLECTION_URL = _WSDL_ROOT + 'ToolsForCollectionWebService?wsdl'
_WS_AUTOPROC_URL = _WSDL_ROOT + 'ToolsForAutoprocessingWebService?wsdl'
_WS_USERNAME = 'ispybws1'
_WS_PASSWORD = '!5pybws1'
_CONNECTION_ERROR_MSG = "Could not connect to ISPyB, please verify that " + \
"the server is running and that your " + \
"configuration is correct"
SampleReference = namedtuple('SampleReference', ['code',
'container_reference',
'sample_reference',
'container_code'])
def trace(fun):
def _trace(*args):
log_msg = "lims client " + fun.__name__ + " called with: "
for arg in args[1:]:
try:
log_msg += pformat(arg, indent = 4, width = 80) + ', '
except:
pass
logging.getLogger("ispyb_client").debug(log_msg)
result = fun(*args)
try:
result_msg = "lims client " + fun.__name__ + \
" returned with: " + pformat(result, indent = 4, width = 80)
except:
pass
logging.getLogger("ispyb_client").debug(result_msg)
return result
return _trace
def in_greenlet(fun):
def _in_greenlet(*args, **kwargs):
log_msg = "lims client " + fun.__name__ + " called with: "
for arg in args[1:]:
try:
log_msg += pformat(arg, indent = 4, width = 80) + ', '
except:
pass
logging.getLogger("ispyb_client").debug(log_msg)
task = gevent.spawn(fun, *args)
if kwargs.get("wait", False):
task.get()
return _in_greenlet
def utf_encode(res_d):
for key in res_d.keys():
if isinstance(res_d[key], dict):
utf_encode(res_d)
if isinstance(res_d[key], suds.sax.text.Text):
try:
res_d[key] = res_d[key].encode('utf8', 'ignore')
except:
pass
return res_d
class ISPyBClient2(HardwareObject):
"""
Web-service client for ISPyB.
"""
def __init__(self, name):
HardwareObject.__init__(self, name)
self.ldapConnection=None
self.beamline_name = "unknown"
self.__shipping = None
self.__collection = None
self.__tools_ws = None
self.__translations = {}
self.__disabled = False
self.authServerType = None
self.loginType = None
self.loginTranslate = None
self.ws_username = None
self.ws_password = None
def init(self):
"""
Init method declared by HardwareObject.
"""
self.authServerType = self.getProperty('authServerType') or "ldap"
if self.authServerType == "ldap":
# Initialize ldap
self.ldapConnection=self.getObjectByRole('ldapServer')
if self.ldapConnection is None:
logging.getLogger("HWR").debug('LDAP Server is not available')
self.loginType = self.getProperty("loginType") or "proposal"
self.loginTranslate = self.getProperty("loginTranslate") or True
self.session_hwobj = self.getObjectByRole('session')
self.beamline_name = self.session_hwobj.beamline_name
self.ws_username = self.getProperty('ws_username')
if not self.ws_username:
self.ws_username = _WS_USERNAME
self.ws_password = self.getProperty('ws_password')
if not self.ws_password:
self.ws_password = _WS_PASSWORD
try:
# ws_root is a property in the configuration xml file
if self.ws_root:
global _WSDL_ROOT
global _WS_BL_SAMPLE_URL
global _WS_SHIPPING_URL
global _WS_COLLECTION_URL
global _WS_SCREENING_URL
global _WS_AUTOPROC_URL
_WSDL_ROOT = self.ws_root.strip()
_WS_BL_SAMPLE_URL = _WSDL_ROOT + \
'ToolsForBLSampleWebService?wsdl'
_WS_SHIPPING_URL = _WSDL_ROOT + \
'ToolsForShippingWebService?wsdl'
_WS_COLLECTION_URL = _WSDL_ROOT + \
'ToolsForCollectionWebService?wsdl'
_WS_AUTOPROC_URL = _WSDL_ROOT + \
'ToolsForAutoprocessingWebService?wsdl'
t1 = HttpAuthenticated(username = self.ws_username,
password = self.ws_password)
t2 = HttpAuthenticated(username = self.ws_username,
password = self.ws_password)
t3 = HttpAuthenticated(username = self.ws_username,
password = self.ws_password)
t4 = HttpAuthenticated(username = self.ws_username,
password = self.ws_password)
try:
self.__shipping = Client(_WS_SHIPPING_URL, timeout = 3,
transport = t1, cache = None)
self.__collection = Client(_WS_COLLECTION_URL, timeout = 3,
transport = t2, cache = None)
self.__tools_ws = Client(_WS_BL_SAMPLE_URL, timeout = 3,
transport = t3, cache = None)
self.__autoproc_ws = Client(_WS_AUTOPROC_URL, timeout = 3,
transport = t4, cache = None)
# ensure that suds do not create those files in tmp
self.__shipping.set_options(cache=None)
self.__collection.set_options(cache=None)
self.__tools_ws.set_options(cache=None)
self.__autoproc_ws.set_options(cache=None)
except URLError:
logging.getLogger("ispyb_client")\
.exception(_CONNECTION_ERROR_MSG)
return
except:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
return
# Add the porposal codes defined in the configuration xml file
# to a directory. Used by translate()
try:
proposals = self.session_hwobj['proposals']
for proposal in proposals:
code = proposal.code
self.__translations[code] = {}
try:
self.__translations[code]['ldap'] = proposal.ldap
except AttributeError:
pass
try:
self.__translations[code]['ispyb'] = proposal.ispyb
except AttributeError:
pass
try:
self.__translations[code]['gui'] = proposal.gui
except AttributeError:
pass
except IndexError:
pass
def get_login_type(self):
return self.loginType
def translate(self, code, what):
"""
Given a proposal code, returns the correct code to use in the GUI,
or what to send to LDAP, user office database, or the ISPyB database.
"""
try:
translated = self.__translations[code][what]
except KeyError:
translated = code
return translated
def clear_daily_email(self):
raise NotImplementedException("Depricated ?")
def send_email(self):
raise NotImplementedException("Depricated ?")
@trace
def get_proposal_by_username(self, username):
proposal_code = ""
proposal_number = 0
empty_dict = {'Proposal': {}, 'Person': {}, 'Laboratory': {}, 'Session': {}, 'status': {'code':'error'}}
if not self.__shipping:
logging.getLogger("ispyb_client").\
warning("Error in get_proposal: Could not connect to server," + \
" returning empty proposal")
return empty_dict
try:
try:
person = self.__shipping.service.findPersonByLogin(username, os.environ["SMIS_BEAMLINE_NAME"])
except WebFault as e:
logging.getLogger("ispyb_client").warning(e.message)
person = {}
try:
proposal = self.__shipping.service.findProposalByLoginAndBeamline(username, os.environ["SMIS_BEAMLINE_NAME"])
if not proposal:
logging.getLogger("ispyb_client").warning("Error in get_proposal: No proposal has been found to the user, returning empty proposal")
return empty_dict
proposal_code = proposal.code
proposal_number = proposal.number
except WebFault as e:
logging.getLogger("ispyb_client").warning(e.message)
proposal = {}
try:
lab = self.__shipping.service.findLaboratoryByCodeAndNumber(proposal_code, proposal_number)
except WebFault as e:
logging.getLogger("ispyb_client").warning(e.message)
lab = {}
try:
res_sessions = self.__collection.service.\
findSessionsByProposalAndBeamLine(proposal_code,
proposal_number,
os.environ["SMIS_BEAMLINE_NAME"])
sessions = []
# Handels a list of sessions
for session in res_sessions:
if session is not None :
try:
session.startDate = \
datetime.strftime(session.startDate,
"%Y-%m-%d %H:%M:%S")
session.endDate = \
datetime.strftime(session.endDate,
"%Y-%m-%d %H:%M:%S")
except:
pass
sessions.append(utf_encode(asdict(session)))
except WebFault as e:
logging.getLogger("ispyb_client").warning(e.message)
sessions = []
except URLError:
logging.getLogger("ispyb_client").warning(_CONNECTION_ERROR_MSG)
return empty_dict
logging.getLogger("ispyb_client").info( str(sessions) )
return {'Proposal': utf_encode(asdict(proposal)),
'Person': utf_encode(asdict(person)),
'Laboratory': utf_encode(asdict(lab)),
'Session': sessions,
'status': {'code':'ok'}}
@trace
def get_proposal(self, proposal_code, proposal_number):
"""
Returns the tuple (Proposal, Person, Laboratory, Session, Status).
Containing the data from the coresponding tables in the database
the status of the database operations are returned in Status.
:param proposal_code: The proposal code
:type proposal_code: str
:param proposal_number: The proposal number
:type propsoal_number: int
:returns: The dict (Proposal, Person, Laboratory, Sessions, Status).
:rtype: dict
"""
if self.__shipping:
try:
try:
person = self.__shipping.service.\
findPersonByProposal(proposal_code,
proposal_number)
if not person:
person = {}
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
person = {}
try:
proposal = self.__shipping.service.\
findProposal(proposal_code,
proposal_number)
if proposal:
proposal.code = proposal_code
else:
return {'Proposal': {},
'Person': {},
'Laboratory': {},
'Session': {},
'status': {'code':'error'}}
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
proposal = {}
try:
lab = None
#lab = self.__shipping.service.findLaboratoryByCodeAndNumber(proposal_code, proposal_number)
lab = self.__shipping.service.findLaboratoryByProposal(proposal_code, proposal_number)
if not lab:
lab = {}
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
lab = {}
try:
res_sessions = self.__collection.service.\
findSessionsByProposalAndBeamLine(proposal_code,
proposal_number,
self.beamline_name)
sessions = []
# Handels a list of sessions
for session in res_sessions:
if session is not None :
try:
session.startDate = \
datetime.strftime(session.startDate,
"%Y-%m-%d %H:%M:%S")
session.endDate = \
datetime.strftime(session.endDate,
"%Y-%m-%d %H:%M:%S")
except:
pass
sessions.append(utf_encode(asdict(session)))
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
sessions = []
except URLError:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
return {'Proposal': {},
'Person': {},
'Laboratory': {},
'Session': {},
'status': {'code':'error'}}
return {'Proposal': utf_encode(asdict(proposal)),
'Person': utf_encode(asdict(person)),
'Laboratory': utf_encode(asdict(lab)),
'Session': sessions,
'status': {'code':'ok'}}
else:
logging.getLogger("ispyb_client").\
exception("Error in get_proposal: Could not connect to server," + \
" returning empty proposal")
return {'Proposal': {},
'Person': {},
'Laboratory': {},
'Session': {},
'status': {'code':'error'}}
@trace
def get_proposal_by_username(self, username):
proposal_code = ""
proposal_number = 0
empty_dict = {'Proposal': {}, 'Person': {}, 'Laboratory': {}, 'Session': {}, 'status': {'code':'error'}}
if not self.__shipping:
logging.getLogger("ispyb_client").\
warning("Error in get_proposal: Could not connect to server," + \
" returning empty proposal")
return empty_dict
try:
try:
person = self.__shipping.service.findPersonByLogin(username, self.beamline_name)
except WebFault as e:
logging.getLogger("ispyb_client").warning(str(e))
person = {}
try:
proposal = self.__shipping.service.findProposalByLoginAndBeamline(username, self.beamline_name)
if not proposal:
logging.getLogger("ispyb_client").warning("Error in get_proposal: No proposal has been found to the user, returning empty proposal")
return empty_dict
proposal_code = proposal.code
proposal_number = proposal.number
except WebFault as e:
logging.getLogger("ispyb_client").warning(str(e))
proposal = {}
try:
lab = self.__shipping.service.findLaboratoryByCodeAndNumber(proposal_code, proposal_number)
except WebFault as e:
logging.getLogger("ispyb_client").warning(str(e))
lab = {}
try:
res_sessions = self.__collection.service.\
findSessionsByProposalAndBeamLine(proposal_code,
proposal_number,
self.beamline_name)
sessions = []
# Handels a list of sessions
for session in res_sessions:
if session is not None :
try:
session.startDate = \
datetime.strftime(session.startDate,
"%Y-%m-%d %H:%M:%S")
session.endDate = \
datetime.strftime(session.endDate,
"%Y-%m-%d %H:%M:%S")
except:
pass
sessions.append(utf_encode(asdict(session)))
except WebFault as e:
logging.getLogger("ispyb_client").warning(str(e))
sessions = []
except URLError:
logging.getLogger("ispyb_client").warning(_CONNECTION_ERROR_MSG)
return empty_dict
logging.getLogger("ispyb_client").info( str(sessions) )
return {'Proposal': utf_encode(asdict(proposal)),
'Person': utf_encode(asdict(person)),
'Laboratory': utf_encode(asdict(lab)),
'Session': sessions,
'status': {'code':'ok'}}
@trace
def get_session_local_contact(self, session_id):
"""
Retrieves the person entry associated with the session id <session_id>
:param session_id:
:type session_id: int
:returns: Person object as dict.
:rtype: dict
"""
if self.__shipping:
try:
person = self.__shipping.service.\
findPersonBySessionIdLocalContact(session_id)
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
person = {}
except URLError:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
person = {}
if person is None:
return {}
else:
utf_encode(asdict(person))
else:
logging.getLogger("ispyb_client").\
exception("Error in get_session_local_contact: Could not get " + \
"local contact")
return {}
def _ispybLogin (self, loginID, psd):
# to do, check how it is done in EMBL
return True, "True"
def login (self,loginID, psd, ldap_connection=None):
if ldap_connection is None:
ldap_connection = self.ldapConnection
login_name=loginID
prpopsal_code = ""
prpopsal_number = ""
# For porposal login, split the loginID to code and numbers
if self.loginType == "proposal" :
proposal_code = "".join(itertools.takewhile(lambda c: not c.isdigit(), loginID))
proposal_number = loginID[len(proposal_code):]
# if translation of the loginID is needed, need to be tested by ESRF
if self.loginTranslate is True:
login_name=self.translate(proposal_code,'ldap')+str(proposal_number)
# Authentication
if self.authServerType == 'ldap':
logging.getLogger('HWR').debug('LDAP login')
ok, msg=ldap_connection.login(login_name,psd)
elif self.authServerType == 'ispyb':
logging.getLogger('HWR').debug('ISPyB login')
ok, msg=self._ispybLogin(login_name,psd)
else:
raise Exception ("Authentication server type is not defined")
if not ok:
msg="%s." % msg.capitalize()
# refuse Login
return {'status':{ "code": "error", "msg": msg }, 'Proposal': None, 'session': None}
# login succeed, get proposal and sessions
#logging.getLogger('HWR').debug('Logged in: querying ISPyB database...')
if self.loginType == "proposal":
# get the proposal ID
prop=self.get_proposal(proposal_code,proposal_number)
elif self.loginType =="user":
prop=self.get_proposal_by_username(loginID)
# Check if everything went ok
prop_ok=True
try:
prop_ok=(prop['status']['code']=='ok')
except KeyError:
prop_ok=False
if not prop_ok:
#todo
msg = "Couldn't contact the ISPyB database server: you've been logged as the local user.\nYour experiments' information will not be stored in ISPyB"
return {'status':{ "code": "ispybDown", "msg": msg }, 'Proposal': None, 'session': None}
# logging.getLogger('HWR').debug('Proposal is fine, get sessions from ISPyB...')
# logging.getLogger('HWR').debug(prop)
proposal=prop['Proposal']
todays_session=self.get_todays_session(prop)
# logging.getLogger('HWR').debug(todays_session)
return {'status':{ "code": "ok", "msg": msg }, 'Proposal': proposal,
'session': todays_session,
"local_contact": self.get_session_local_contact(todays_session['session']['sessionId']),
"person": prop['Person'],
"laboratory": prop['Laboratory']}
def get_todays_session(self, prop):
try:
sessions=prop['Session']
except KeyError:
sessions=None
# Check if there are sessions in the proposal
todays_session=None
if sessions is None or len(sessions)==0:
pass
else:
# Check for today's session
for session in sessions:
beamline=session['beamlineName']
start_date="%s 00:00:00" % session['startDate'].split()[0]
end_date="%s 23:59:59" % session['endDate'].split()[0]
try:
start_struct=time.strptime(start_date,"%Y-%m-%d %H:%M:%S")
except ValueError:
pass
else:
try:
end_struct=time.strptime(end_date,"%Y-%m-%d %H:%M:%S")
except ValueError:
pass
else:
start_time=time.mktime(start_struct)
end_time=time.mktime(end_struct)
current_time=time.time()
# Check beamline name
if beamline==self.beamline_name:
# Check date
if current_time>=start_time and current_time<=end_time:
todays_session=session
break
new_session_flag= False
if todays_session is None:
# a newSession will be created, UI (Qt, web) can decide to accept the newSession or not
new_session_flag= True
current_time=time.localtime()
start_time=time.strftime("%Y-%m-%d 00:00:00", current_time)
end_time=time.mktime(current_time)+60*60*24
tomorrow=time.localtime(end_time)
end_time=time.strftime("%Y-%m-%d 07:59:59", tomorrow)
# Create a session
new_session_dict={}
new_session_dict['proposalId']=prop['Proposal']['proposalId']
new_session_dict['startDate']=start_time
new_session_dict['endDate']=end_time
new_session_dict['beamlineName']=self.beamline_name
new_session_dict['scheduled']=0
new_session_dict['nbShifts']=3
new_session_dict['comments']="Session created by the BCM"
session_id=self.create_session(new_session_dict)
new_session_dict['sessionId']=session_id
todays_session=new_session_dict
localcontact=None
logging.getLogger('HWR').debug('create new session')
else:
session_id=todays_session['sessionId']
logging.getLogger('HWR').debug('getting local contact for %s' % session_id)
localcontact=self.get_session_local_contact(session_id)
is_inhouse = self.session_hwobj.is_inhouse(prop['Proposal']["code"], prop['Proposal']["number"])
return {"session": todays_session,"new_session_flag":new_session_flag, "is_inhouse": is_inhouse}
@trace
def store_data_collection(self, *args, **kwargs):
try:
return self._store_data_collection(*args, **kwargs)
except gevent.GreenletExit:
# aborted by user ('kill')
raise
except:
# if anything else happens, let upper level process continue
# (not a fatal error), but display exception still
logging.exception("Could not store data collection")
return (0,0,0)
def _store_data_collection(self, mx_collection, beamline_setup = None):
"""
Stores the data collection mx_collection, and the beamline setup
if provided.
:param mx_collection: The data collection parameters.
:type mx_collection: dict
:param beamline_setup: The beamline setup.
:type beamline_setup: dict
:returns: None
"""
if self.__disabled:
return (0,0,0)
if self.__collection:
data_collection = ISPyBValueFactory().\
from_data_collect_parameters(self.__collection, mx_collection)
if beamline_setup:
lims_beamline_setup = ISPyBValueFactory.\
from_bl_config(self.__collection, beamline_setup)
lims_beamline_setup.synchrotronMode = \
data_collection.synchrotronMode
self.store_beamline_setup(mx_collection['sessionId'],
lims_beamline_setup )
detector_params = \
ISPyBValueFactory().detector_from_blc(beamline_setup,
mx_collection)
detector = self.find_detector(*detector_params)
detector_id = 0
if detector:
detector_id = detector.detectorId
data_collection.detectorId = detector_id
collection_id = self.__collection.service.\
storeOrUpdateDataCollection(data_collection)
return (collection_id, detector_id)
else:
logging.getLogger("ispyb_client").\
exception("Error in store_data_collection: could not connect" + \
" to server")
@trace
def store_beamline_setup(self, session_id, beamline_setup):
"""
Stores the beamline setup dict <beamline_setup>.
:param session_id: The session id that the beamline_setup
should be associated with.
:type session_id: int
:param beamline_setup: The dictonary with beamline settings.
:type beamline_setup: dict
:returns beamline_setup_id: The database id of the beamline setup.
:rtype: str
"""
blSetupId = None
if self.__collection:
session = {}
try:
session = self.get_session(session_id)
except:
logging.getLogger("ispyb_client").exception(\
"ISPyBClient: exception in store_beam_line_setup")
else:
if session is not None:
try:
blSetupId = self.__collection.service.\
storeOrUpdateBeamLineSetup(beamline_setup)
session['beamLineSetupId'] = blSetupId
self.update_session(session)
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
except URLError:
logging.getLogger("ispyb_client").\
exception(_CONNECTION_ERROR_MSG)
else:
logging.getLogger("ispyb_client").\
exception("Error in store_beamline_setup: could not connect" + \
" to server")
return blSetupId
#@trace
@in_greenlet
def update_data_collection(self, mx_collection, wait=False):
"""
Updates the datacollction mx_collection, this requires that the
collectionId attribute is set and exists in the database.
:param mx_collection: The dictionary with collections parameters.
:type mx_collection: dict
:returns: None
"""
if self.__disabled:
return
if self.__collection:
if 'collection_id' in mx_collection:
try:
# Update the data collection group
self.store_data_collection_group(mx_collection)
data_collection = ISPyBValueFactory().\
from_data_collect_parameters(self.__collection, mx_collection)
self.__collection.service.\
storeOrUpdateDataCollection(data_collection)
except WebFault:
logging.getLogger("ispyb_client").\
exception("ISPyBClient: exception in update_data_collection")
except URLError:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
else:
logging.getLogger("ispyb_client").error("Error in update_data_collection: " + \
"collection-id missing, the ISPyB data-collection is not updated.")
else:
logging.getLogger("ispyb_client").\
exception("Error in update_data_collection: could not connect" + \
" to server")
@trace
def update_bl_sample(self, bl_sample):
"""
Creates or stos a BLSample entry.
:param sample_dict: A dictonary with the properties for the entry.
:type sample_dict: dict
"""
if self.__disabled:
return {}
if self.__tools_ws:
try:
status = self.__tools_ws.service.\
storeOrUpdateBLSample(bl_sample)
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
status = {}
except URLError:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
return status
else:
logging.getLogger("ispyb_client").\
exception("Error in update_bl_sample: could not connect to server")
#@in_greenlet
def store_image(self, image_dict):
"""
Stores the image (image parameters) <image_dict>
:param image_dict: A dictonary with image pramaters.
:type image_dict: dict
:returns: None
"""
if self.__disabled:
return
if self.__collection:
if 'dataCollectionId' in image_dict:
try:
image_id = self.__collection.service.storeOrUpdateImage(image_dict)
return image_id
except WebFault:
logging.getLogger("ispyb_client").\
exception("ISPyBClient: exception in store_image")
except URLError:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
else:
logging.getLogger("ispyb_client").error("Error in store_image: " + \
"data_collection_id missing, could not store image in ISPyB")
else:
logging.getLogger("ispyb_client").\
exception("Error in store_image: could not connect to server")
def __find_sample(self, sample_ref_list, code = None, location = None):
"""
Returns the sample with the matching "search criteria" <code> and/or
<location> with-in the list sample_ref_list.
The sample_ref object is defined in the head of the file.
:param sample_ref_list: The list of sample_refs to search.
:type sample_ref: list
:param code: The vial datamatrix code (or bar code)
:param type: str
:param location: A tuple (<basket>, <vial>) to search for.
:type location: tuple
"""
for sample_ref in sample_ref_list:
if code and location:
if sample_ref.code == code and \
sample_ref.container_reference == location[0] and \
sample_ref.sample_reference == location[1]:
return sample_ref
elif code:
if sample_ref.code == code:
return sample_ref
elif location:
if sample_ref.container_reference == location[0] and \
sample_ref.sample_reference == location[1]:
return sample_ref
return None
@trace
def get_samples(self, proposal_id, session_id):
response_samples = None
if self.__tools_ws:
try:
response_samples = self.__tools_ws.service.\
findSampleInfoLightForProposal(proposal_id,
self.beamline_name)
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
except URLError:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
else:
logging.getLogger("ispyb_client").\
exception("Error in store_image: could not connect to server")
return response_samples
@trace
def get_session_samples(self, proposal_id, session_id, sample_refs):
"""
Retrives the list of samples associated with the session <session_id>.
The samples from ISPyB is cross checked with the ones that are
currently in the sample changer.
The datamatrix code read by the sample changer is used in case
of conflict.
:param proposal_id: ISPyB proposal id.
:type proposal_id: int
:param session_id: ISPyB session id to retreive samples for.
:type session_id: int
:param sample_refs: The list of samples currently in the
sample changer. As a list of sample_ref
objects
:type sample_refs: list (of sample_ref objects).
:returns: A list with sample_ref objects.
:rtype: list
"""
if self.__tools_ws:
sample_references = []
session = self.get_session(session_id)
response_samples = []
for sample_ref in sample_refs:
sample_reference = SampleReference(*sample_ref)
sample_references.append(sample_reference)
try:
response_samples = self.__tools_ws.service.\
findSampleInfoLightForProposal(proposal_id,
self.beamline_name)
except WebFault as e:
logging.getLogger("ispyb_client").exception(str(e))
except URLError:
logging.getLogger("ispyb_client").exception(_CONNECTION_ERROR_MSG)
samples = []
for sample in response_samples:
try:
loc = [None, None]
try:
loc[0]=int(sample.containerSampleChangerLocation)
except:
pass
try:
loc[1]=int(sample.sampleLocation)
except:
pass