This repository was archived by the owner on Sep 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathutils.py
More file actions
executable file
·8236 lines (7219 loc) · 332 KB
/
utils.py
File metadata and controls
executable file
·8236 lines (7219 loc) · 332 KB
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
import sys
import urllib, urllib2
import logging
from dbs.apis.dbsClient import DbsApi
#import reqMgrClient
import httplib
import os
import socket
import json
import collections
from collections import defaultdict
import random
from xml.dom.minidom import getDOMImplementation
import copy
import pickle
import itertools
import time
import math
import hashlib
import threading
import glob
import datetime
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email.utils import make_msgid
#
## add local python paths
for p in ['/usr/lib64/python2.7/site-packages','/usr/lib/python2.7/site-packages']:
if not p in sys.path: sys.path.append(p)
dbs_url = os.getenv('UNIFIED_DBS3_READER' ,'https://cmsweb.cern.ch/dbs/prod/global/DBSReader')
dbs_url_writer = os.getenv('UNIFIED_DBS3_WRITER','https://cmsweb.cern.ch/dbs/prod/global/DBSWriter')
phedex_url = os.getenv('UNIFIED_PHEDEX','cmsweb.cern.ch')
reqmgr_url = os.getenv('UNIFIED_REQMGR','cmsweb.cern.ch')
monitor_dir = os.getenv('UNIFIED_MON','/data/unified/www/')
#monitor_eos_dir = "/eos/project/c/cms-unified-logs/www/"
monitor_eos_dir = '/eos/cms/store/unified/www/'
monitor_dir = monitor_eos_dir
monitor_pub_dir = os.getenv('UNIFIED_MON','/data/unified/www/public/')
#monitor_pub_eos_dir = "/eos/project/c/cms-unified-logs/www/public/"
monitor_pub_eos_dir = "/eos/cms/store/unified/www/public/"
monitor_pub_dir = monitor_pub_eos_dir
base_dir = os.getenv('UNIFIED_DIR','/data/unified/')
#base_eos_dir = "/eos/project/c/cms-unified-logs/"
base_eos_dir = "/eos/cms/store/unified/"
#unified_url = os.getenv('UNIFIED_URL','https://vocms049.cern.ch/unified/')
unified_url = os.getenv('UNIFIED_URL','https://cms-unified.web.cern.ch/cms-unified/')
unified_url_eos = "https://cms-unified.web.cern.ch/cms-unified/"
unified_url = unified_url_eos
url_eos = unified_url_eos
#unified_pub_url = os.getenv('UNIFIED_URL','https://vocms049.cern.ch/unified/public/')
unified_pub_url = os.getenv('UNIFIED_URL','https://cms-unified.web.cern.ch/cms-unified/public/')
cache_dir = '/data/unified-cache/'
mongo_db_url = 'vocms0274.cern.ch'
FORMAT = "%(module)s.%(funcName)s(%(lineno)s) => %(message)s (%(asctime)s)"
DATEFMT = "%Y-%m-%d %H:%M:%S"
logging.basicConfig(format = FORMAT, datefmt = DATEFMT, level=logging.DEBUG)
do_html_in_each_module = False
def deep_update(d, u):
for k, v in u.items():
if isinstance(v, collections.Mapping) or isinstance(v, dict):
default = v.copy()
default.clear()
r = deep_update(d.get(k, default), v)
d[k] = r
#elif isinstance(v, list):
# d[k]=d.get(k,[])
# d[k].extend( v )
#elif isinstance(v, set):
# d[k]=d.get(k,set())
# d[k].update( v )
else:
d[k] = v
return d
def sendDashboard( subject, text, criticality='info', show=True):
### this sends something to the dashboard ES for error, info, messages
pass
def sendLog( subject, text , wfi = None, show=True ,level='info'):
try:
try_sendLog( subject, text , wfi, show, level)
except Exception as e:
print "failed to send log to elastic search"
print str(e)
sendEmail('failed logging',subject+text+str(e))
def new_searchLog( q, actor=None, limit=50 ):
conn = httplib.HTTPSConnection( 'es-unified7.cern.ch' )
return _searchLog(q, actor, limit,conn, prefix = '/es/unified-logs/_doc', h = es_header())
def _searchLog( q, actor, limit, conn, prefix, h = None):
goodquery={
"query": {
"bool": {
"must": [
{
"wildcard": {
"meta": "*%s*"%q
}
},
]
}
},
"sort": [
{
"timestamp": "desc"
}
],
"_source": [
"text",
"subject",
"date",
"meta",
#"_id"
]
}
goodquery={"query": {"bool": {"must": [{"wildcard": {"meta": "*%s*"%q}}]}}, "sort": [{"timestamp": "desc"}], "_source": ["text", "subject", "date", "meta"]}
if actor:
#goodquery['query']['bool']['must'][0]['wildcard']['subject'] = actor
goodquery['query']['bool']['filter'] = { "term" : { "subject" : actor}}
turl = prefix+'/_search?size=%d'%limit
print turl
conn.request("GET" , turl, json.dumps(goodquery) ,headers = h if h else {})
## not it's just a matter of sending that query to ES.
#lq = q.replace(':', '\:').replace('-','\\-')
#conn.request("GET" , '/logs/_search?q=text:%s'% lq)
response = conn.getresponse()
data = response.read()
o = json.loads( data )
#print o
#print o['hits']['total']
hits = o['hits']['hits']
#if actor:
# hits = [h for h in hits if h['_source']['subject']==actor]
return hits
def es_header():
entrypointname,password = open('Unified/secret_es.txt').readline().split(':')
import base64
auth = base64.encodestring(('%s:%s' % (entrypointname, password)).replace('\n', '')).replace('\n', '')
header = { "Authorization": "Basic %s"% auth, "Content-Type": "application/json"}
return header
def new_sendLog( subject, text , wfi = None, show=True, level='info'):
conn = httplib.HTTPSConnection( 'es-unified7.cern.ch' )
conn.request("GET", "/es", headers=es_header())
response = conn.getresponse()
data = response.read()
print data
## historical information on how the schema was created
"""
schema= {
"date": {
"type": "string",
"index": "not_analyzed"
},
"author": {
"type": "string"
},
"subject": {
"type": "string"
},
"text": {
"type": "string",
"index": "not_analyzed"
},
"meta": {
"type": "string",
"index": "not_analyzed"
},
"timestamp": {
"type": "double"
}
}
content = {}
settings = {
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}}}
content.update( settings )
content.update({ "mappings" : {"log" : { "properties" : schema}}})
conn.request("PUT", "/es/unified-logs", json.dumps( content ), headers = es_header())
response = conn.getresponse()
data = response.read()
print data
return
"""
#conn.request('GET', "/es/unified-logs", headers = es_header())
#response = conn.getresponse()
#data = response.read()
#print data
#return
_try_sendLog( subject, text, wfi, show, level, conn = conn, prefix='/es/unified-logs', h = es_header())
def try_sendLog( subject, text , wfi = None, show=True, level='info'):
#conn = httplib.HTTPConnection( 'cms-elastic-fe.cern.ch:9200' )
#_try_sendLog(subject, text , wfi, show, level, conn = conn)
## send it to the new instance too. Without showing it
re_conn = httplib.HTTPSConnection( 'es-unified7.cern.ch' )
_try_sendLog( subject, text, wfi, show, level, conn = re_conn, prefix='/es/unified-logs', h = es_header())
def _try_sendLog( subject, text , wfi = None, show=True, level='info', conn= None, prefix= '/es/unified-logs', h =None):
#conn = httplib.HTTPConnection( 'cms-elastic-fe.cern.ch:9200' )
meta_text="level:%s\n"%level
if wfi:
## add a few markers automatically
meta_text += '\n\n'+'\n'.join(map(lambda i : 'id: %s'%i, wfi.getPrepIDs()))
_,prim,_,sec = wfi.getIO()
if prim:
meta_text += '\n\n'+'\n'.join(map(lambda i : 'in:%s'%i, prim))
if sec:
meta_text += '\n\n'+'\n'.join(map(lambda i : 'pu:%s'%i, sec))
out = filter(lambda d : not any([c in d for c in ['FAKE','None']]),wfi.request['OutputDatasets'])
if out:
meta_text += '\n\n'+'\n'.join(map(lambda i : 'out:%s'%i, out))
meta_text += '\n\n'+wfi.request['RequestName']
now_ = time.gmtime()
now = time.mktime( now_ )
now_d = time.asctime( now_ )
doc = {"author" : os.getenv('USER'),
"subject" : subject,
"text" : text ,
"meta" : meta_text,
"timestamp" : now,
"date" : now_d}
if show:
print text
encodedParams = urllib.urlencode( doc )
conn.request("POST" , prefix+'/_doc/', json.dumps(doc), headers = h if h else {})
response = conn.getresponse()
data = response.read()
try:
res = json.loads( data )
#print res
#print 'log:',res['_id'],"was created"
except Exception as e:
print "failed"
print str(e)
pass
def sendEmail( subject, text, sender=None, destination=None ):
#print subject
#print text
#print sender
#print destination
UC = unifiedConfiguration()
email_destination = UC.get("email_destination")
if not destination:
destination = email_destination
else:
destination = list(set(destination))
if not sender:
map_who = { #'vlimant' : 'vlimant@cern.ch',
'mcremone' : 'matteoc@fnal.gov',
'qnguyen' : 'thong.nguyen@cern.ch'
}
user = os.getenv('USER')
if user in map_who:
sender = map_who[user]
else:
sender = 'cmsunified@cern.ch'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = COMMASPACE.join( destination )
msg['Date'] = formatdate(localtime=True)
new_msg_ID = make_msgid()
msg['Subject'] = '[Ops] '+subject
msg.attach(MIMEText(text))
smtpObj = smtplib.SMTP()
smtpObj.connect()
smtpObj.sendmail(sender, destination, msg.as_string())
smtpObj.quit()
def condorLogger(agent, workflow, wmbs, errorcode_s):
"""
mechanism to get the condor log out of the agent to a visible place
"""
pass
def cmsswLogger(errorcode_s):
"""
mechanism to get the cmsrun log (from node, or eos) to a visible place
"""
pass
def url_encode_params(params = {}):
"""
encodes given parameters dictionary. Dictionary values
can contain list, in that case, encoded params will look
like this: param=val1¶m=val2...
"""
params_list = []
for key, value in params.items():
if isinstance(value, list):
params_list.extend([(key, x) for x in value])
else:
params_list.append((key, value))
return urllib.urlencode(params_list)
def download_data(url = None, params = None, headers = None, logger = None):
"""
Returns data got from server.
params has to be a dictionary, which can contain
"key : [value1, value2,...], and that will be
converted to key=value1&key=value2&...
"""
if not logger:
logger = logging
try:
if params:
params = url_encode_params(params)
url = "{url}?{params}".format(url = url, params = params)
response = urllib2.urlopen(url)
data = response.read()
return data
except urllib2.HTTPError as err:
error = "{msg} (HTTP Error: {code})"
logger.error(error.format(code = err.code, msg = err.msg))
logger.error("URL called: {url}".format(url = url))
return None
def download_file(url, params, path = None, logger = None):
if not logger:
logger = logging
if params:
params = url_encode_params(params)
url = "{url}?{params}".format(url = url, params = params)
logger.debug(url)
try:
filename, message = urllib.urlretrieve(url)
return filename
except urllib2.HTTPError as err:
error = "{msg} (HTTP Error: {code})"
logger.error(error.format(code = err.code, msg = err.msg))
logger.error("URL called: {url}".format(url = url))
return None
def make_x509_conn(url=reqmgr_url,max_try=5):
tries = 0
while tries<max_try:
try:
conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
return conn
except:
tries+=1
pass
return None
def GET(url, there, l=True):
#conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
conn = make_x509_conn(url)
r1=conn.request("GET",there)
r2=conn.getresponse()
if l:
return json.loads(r2.read())
else:
return r2
def check_ggus( ticket ):
conn = make_x509_conn('ggus.eu')
#conn = httplib.HTTPSConnection('ggus.eu', cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
r1=conn.request("GET",'/index.php?mode=ticket_info&ticket_id=%s&writeFormat=XML'%ticket)
r2=conn.getresponse()
print r2
return False
def getSubscriptions(url, dataset):
conn = make_x509_conn(url)
#conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
there = '/phedex/datasvc/json/prod/subscriptions?dataset='+dataset
r1=conn.request("GET", there)
r2=conn.getresponse()
result = json.loads(r2.read())
items=result['phedex']
return items
def listRequests(url, dataset, site=None):
conn = make_x509_conn(url)
#conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
there = '/phedex/datasvc/json/prod/requestlist?dataset='+dataset
r1=conn.request("GET", there)
r2=conn.getresponse()
result = json.loads(r2.read())
items=result['phedex']['request']
res= defaultdict(list)
for item in items:
for node in item['node']:
if site and node['name']!=site: continue
if not item['id'] in res[node['name']]:
res[node['name']].append(item['id'])
for s in res:
res[s] = sorted(res[s])
return dict(res)
def listCustodial(url, site='T1_*MSS'):
conn = make_x509_conn(url)
#conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
there = '/phedex/datasvc/json/prod/requestlist?node=%s&decision=pending'%site
r1=conn.request("GET", there)
r2=conn.getresponse()
result = json.loads(r2.read())
items=result['phedex']['request']
res= defaultdict(list)
for item in items:
if item['type'] != 'xfer': continue
for node in item['node']:
if not item['id'] in res[node['name']]:
res[node['name']].append(item['id'])
for s in res:
res[s] = sorted(res[s])
return dict(res)
def listDelete(url, user, site=None):
conn = make_x509_conn(url)
#conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
there = '/phedex/datasvc/json/prod/requestlist?type=delete&approval=pending&requested_by=%s'% user
if site:
there += 'node=%s'% ','.join(site)
r1=conn.request("GET", there)
r2=conn.getresponse()
result = json.loads(r2.read())
items=result['phedex']['request']
#print json.dumps(items, indent=2)
return list(itertools.chain.from_iterable([(subitem['name'],item['requested_by'],item['id']) for subitem in item['node'] if subitem['decision']=='pending' ] for item in items))
def listSubscriptions(url, dataset, within_sites=None):
conn = make_x509_conn(url)
#conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
r1=conn.request("GET",'/phedex/datasvc/json/prod/requestlist?dataset=%s'%(dataset))
r2=conn.getresponse()
result = json.loads(r2.read())
items=result['phedex']['request']
destinations ={}
deletes = defaultdict(int)
for item in items:
for node in item['node']:
site = node['name']
if item['type'] == 'delete' and node['decision'] in [ 'approved','pending']:
deletes[ site ] = max(deletes[ site ], node['time_decided'])
for item in items:
for node in item['node']:
if item['type']!='xfer': continue
site = node['name']
if within_sites and not site in within_sites: continue
#print item
if not 'MSS' in site:
## pending delete
if site in deletes and not deletes[site]: continue
## delete after transfer
#print node['time_decided'],site
if site in deletes and deletes[site] > node['time_decided']: continue
destinations[site]=(item['id'], node['decision']=='approved')
#print node['name'],node['decision']
#print node
#print destinations
return destinations
def pass_to_dynamo( items, N ,sites = None, group = None ):
check_N_times = 1
while True:
check_N_times-=1
try:
return _pass_to_dynamo( items, N, sites, group)
except Exception as e:
if check_N_times<=0:
print "Failed to pass %s to dynamo"% items
print str(e)
return False
def _pass_to_dynamo( items, N ,sites = None, group = None ):
start = time.mktime(time.gmtime())
if sites == None or sites == []:
sites = ['T2_*','T1_*_Disk']
if type(items)==str:
items = items.split(',')
conn = make_x509_conn('dynamo.mit.edu')
par = {'item' : items, 'site': sites, 'n':N}
if group:
par.update( {'group' : group })
#params = urllib.urlencode(par)
print par
#print params
par.update({'cache':'y'})
conn.request("POST","/registry/request/copy", json.dumps(par))
response = conn.getresponse()
data = response.read()
#print data
stop = time.mktime(time.gmtime())
print stop-start,"[s] to hand over to dynamo of",items
try:
res = json.loads( data )
isOK = (res['result'] == "OK")
if not isOK: print json.dumps( res, indent=2)
return isOK
except Exception as e:
#if data.replace('\n','') == '':
# print "consider blank as OK"
# return True
print "Failed _pass_to_dynamo"
print "---"
print data
print "---"
print str(e)
return False
class UnifiedLock:
def __init__(self, acquire=True):
self.owner = "%s-%s"%(socket.gethostname(), os.getpid())
#self.owner = owner
if acquire: self.acquire()
def acquire(self):
from assignSession import session, LockOfLock
## insert a new object with the proper time stamp
ll = LockOfLock( lock=True,
time = time.mktime( time.gmtime()),
owner = self.owner)
session.add( ll )
session.commit()
def deadlock(self):
host = os.getenv('HOST',os.getenv('HOSTNAME',socket.gethostname()))
from assignSession import session, LockOfLock
to_remove = []
for ll in session.query(LockOfLock).filter(LockOfLock.lock== True).filter(LockOfLock.owner.contains(host)).all():
print ll.owner
try:
host,pid = ll.owner.split('-')
process = os.popen('ps -e -f | grep %s | grep -v grep'%pid).read()
if not process:
print "the lock",ll,"is a deadlock"
to_remove.append( ll )
else:
print "the lock on",ll.owner,"is legitimate"
except:
print ll.owner,"is not good"
if to_remove:
for ll in to_remove:
session.delete( ll )
session.commit()
def clean(self):
##TODO: remove deadlocks
##TODO: remove old entries to keep the db under control
return
now = time.mktime(time.gmtime())
from assignSession import session, LockOfLock
for ll in session.query(LockOfLock).all():
## one needs to go and check the process on the corresponding machine
pass
session.commit()
def __del__(self):
self.release()
def release(self):
from assignSession import session, LockOfLock
for ll in session.query(LockOfLock).filter(LockOfLock.owner == self.owner).all():
ll.lock = False
ll.endtime = time.mktime( time.gmtime())
session.commit()
class DynamoLock:
def __init__(self, owner=None, wait=True, timeout=None, acquire=True):
self.owner = owner
self.go = False
self.wait = wait
self.timeout = timeout
if acquire: self.acquire()
def acquire(self):
wait = 30
waited = 0
while True:
self.go = not self.check()
if not self.go and self.wait:
waited += wait
if self.timeout and waited > self.timeout:
break
time.sleep(wait)
print "wait on dynamo"
break
print "dynamo lock acquired",self.go
#self.go = lock_DDM(owner=self.owner, wait=self.wait, timeout=self.timeout)
def free(self):
return self.go
def check(self):
retry = 3
while retry:
try:
return self._check()
except Exception as e:
print "Failed to check on dynamo",retry
print(str(e))
retry-=1
time.sleep(5)
return True
def _check(self):
conn = make_x509_conn('dynamo.mit.edu')
r1 = conn.request("GET",'/data/applock/check?app=detox')
r2 = conn.getresponse()
r = json.loads(r2.read())
if (r['result'] == 'OK' and r['message'] == 'Locked'):
print "waiting on dynamo",r
locked = True
else:
locked = False
return locked
def deadlock(self):
from assignSession import session, LockOfLock
Ulocks = session.query(LockOfLock).filter(LockOfLock.lock == True).all()
if not Ulocks:
## noone on this end is currently supposed to handshake with dynamo
# does not work out
self.full_release()
def __del__(self):
if self.go: self.release()
def release(self):
#unlock_DDM(self.owner)
pass
def full_release(self):
## release as many times as necessary to get it free
while self.check():
self.release()
def unlock_DDM(owner=None):
try:
return _lock_DDM(owner=owner, lock=False, wait=None, timeout=None)
except Exception as e:
print "Failure in unlocking DDM"
print str(e)
return False
def lock_DDM(owner=None, wait=True, timeout=None):
try:
return _lock_DDM(owner=owner, lock=True, wait=wait, timeout=timeout)
except Exception as e:
print "Failure in locking DDM"
print str(e)
return False
def _lock_DDM(owner=None, lock=True, wait=True, timeout=None):
print "deprecated"
sys.exit(5)
return
conn = make_x509_conn('dynamo.mit.edu')
go = False
waited = 0
sleep = 30
service = 'unified' ## could be replaced with some owner
if owner: service+= '-'+owner
if lock:
while True:
conn.request("POST","/registry/applock/lock?service=%s&app=detox"% service )
response = conn.getresponse()
data = response.read()
res = json.loads( data )
if res['result'].lower() == 'wait':
time.sleep( sleep )
waited += sleep
elif res['result'].lower() == 'ok':
print "we locked dynamo for",service
go = True
break
else:
go = False
print res
break
if timeout and waited>timeout:
print "locking dynamo has timedout for",service
go = False
else:
conn.request("POST","/registry/applock/unlock?service=%s&app=detox"% service)
response = conn.getresponse()
data = response.read()
res = json.loads( data )
if res['result'].lower() == 'ok':
print "we unlocked dynamo for",service
go = True
else:
print 'possible deadlock on',service
print res
go = True
return go
class lockInfo:
def __init__(self, andwrite=True):
self.owner = "%s-%s"%(socket.gethostname(), os.getpid())
self.ddmlock = DynamoLock( owner = None, timeout = 10*60)
self.unifiedlock = UnifiedLock()
def free(self):
return self.ddmlock.free()
def release(self, item ):
try:
self._release(item)
except Exception as e:
print "failed to release"
print str(e)
def _release(self, item ):
#from dataLock import locksession, Lock
from assignSession import session, Lock
l = session.query(Lock).filter(Lock.item == item).first()
if not l:
sendLog('lockInfo',"[Release] %s to be released is not locked"%item)
else:
sendLog('lockInfo',"[Release] releasing %s"%item)
l.lock = False
session.commit()
def islocked( self, item):
from assignSession import session, Lock
l = session.query(Lock).filter(Lock.item == item).first()
return (l and l.lock)
def _lock(self, item, site, reason):
if not item:
sendEmail('lockInfo', "trying to lock item %s" % item)
print "[ERROR] trying to lock item",item
from assignSession import session, Lock
l = session.query(Lock).filter(Lock.item == item).first()
do_com = False
if not l:
print "in lock, making a new object for",item
l = Lock(lock=False)
#l.site = site
l.item = item
l.is_block = '#' in item
session.add ( l )
do_com = True
else:
print "lock for",item,"already existing",l.lock
now = time.mktime(time.gmtime())
## overwrite the lock
message = "[Lock] %s"%item
if l.lock != True:
l.lock = True
do_com = True
message+=" being locked"
if reason and reason!=l.reason:
l.reason = reason
do_com =True
message+=" because of %s"%reason
if do_com:
sendLog('lockInfo',message)
l.time = now
session.commit()
def lock(self, item, site='', reason=None):
try:
self._lock( item, site, reason)
except Exception as e:
## to be removed once we have a fully functional lock db
print "could not lock",item,"at",site
print str(e)
def items(self, locked=True):
#from dataLock import locksession, Lock
from assignSession import session, Lock
ret = sorted([ l.item for l in session.query(Lock).all() if l.lock==locked])
return ret
def tell(self, comment):
#from dataLock import locksession, Lock
from assignSession import session, Lock
print "---",comment,"---"
for l in session.query(Lock).all():
print l.item,l.lock
print "------"+"-"*len(comment)
def mongo_client():
import pymongo,ssl
return pymongo.MongoClient('mongodb://%s/?ssl=true'%mongo_db_url, ssl_cert_reqs=ssl.CERT_NONE)
class statusHistory:
def __init__(self):
self.client = mongo_client()
self.db = self.client.unified.statusHistory
def content(self):
c = {}
for doc in self.db.find():
c[int(doc['time'])] = doc
return c
def add(self, now, info):
info['time'] = time.mktime(now)
info['date'] = time.asctime(now)
self.db.insert_one( info )
def trim(self, now, days):
now = time.mktime(now)
for doc in self.db.find():
if (float(now)-float(doc['time'])) > days*24*60*60:
print "trim history of",doc['_id']
self.db.delete_one( {'_id' : doc['_id']})
class replacedBlocks:
def __init__(self):
self.client = mongo_client()
self.db = self.client.unified.replacedBlocks
def add(self, blocks):
for block in blocks:
self.db.update_one({'name' : block},
{'$set' : {'name' : block,
'time' : time.mktime( time.gmtime() )
}},
upsert=True)
def test(self, block):
## return "already replaced"
b = self.db.find_one({'name' : block})
return True if b else False
class transferDataset:
def __init__(self):
self.client = mongo_client()
self.db = self.client.unified.transferDataset
self.added = set()
## one time sync
#for k,v in json.loads(eosRead('/eos/cms/store/unified/datasets_by_phid.json')).items():
# self.add(int(k),v)
def add(self, phedexid, datasets):
self.added.add( phedexid )
self.db.update({'phedexid' :phedexid},
{'$set' : {
'phedexid' :phedexid,
'datasets' : datasets}},
upsert = True)
def content(self):
r = {}
for t in self.db.find():
r[t['phedexid']] = t['datasets']
return r
def __del__(self):
if self.added:
phids = [t['phedexid'] for t in self.db.find()]
for phid in phids:
if not phid in self.added:
while self.db.find_one({'phedexid' : phid}):
self.db.delete_one({'phedexid' : phid})
class transferStatuses:
def __init__(self):
self.client = mongo_client()
self.db = self.client.unified.cachedTransferStatuses
def pop(self, phedexid):
self.db.delete_one({'phedexid' : phedexid})
def add(self, phedexid, status):
to_insert = copy.deepcopy( status )
to_insert['phedexid'] = phedexid
self.db.update_one( {'phedexid' : phedexid},
{"$set": to_insert },
upsert=True
)
def all(self):
all = self.db.find()
if all:
return [d['phedexid'] for d in all ]
else:
return []
def content(self):
rd = {}
for d in self.db.find():
d.pop('_id')
ii = d.pop('phedexid')
rd[ii] = dict(d)
return rd
class StartStopInfo:
def __init__(self):
self.client = mongo_client()
self.db = self.client.unified.startStopTime
def pushStartStopTime(self, component, start, stop):
doc = { 'component' : component,
'start' : int(start),
}
if stop is not None:
doc.update({
'stop' : int(stop),
'lap' : int(stop)-int(start)
})
self.db.update_one( {'component': component, 'start' : int(start)},
{"$set": doc},
upsert = True)
def get(self, component, metric='lap'):
res = [oo[metric] for oo in sorted(self.db.find({'component' : component}), key = lambda o : o['start']) if metric in oo]
return res
def purge(self, now, since_in_days):
then = now - (since_in_days*24*60*60)
self.db.delete_many( { 'start' : {'$lt': then }})
class unifiedConfiguration:
def __init__(self):
self.configs = json.loads(open('unifiedConfiguration.json').read()) ## switch to None once you want to read it from mongodb
if self.configs is None:
try:
self.client = mongo_client()
self.db = self.client.unified.unifiedConfiguration
quest = self.db.find_one()
except:
print "could not reach pymongo"
self.configs = json.loads(open('unifiedConfiguration.json').read())
def get(self, parameter):
if self.configs:
if parameter in self.configs:
return self.configs[parameter]['value']
else:
print parameter,'is not defined in global configuration'
print ','.join(self.configs.keys()),'possible'
sys.exit(124)
else:
found = self.db.find_one({"name": parameter})
if found:
found.pop("_id")
found.pop("name")
return found
else: