forked from CMSCompOps/WmAgentScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
3934 lines (3462 loc) · 167 KB
/
utils.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
import sys
import urllib, urllib2
import logging
from dbs.apis.dbsClient import DbsApi
#import reqMgrClient
import httplib
import os
import json
from collections import defaultdict
import random
from xml.dom.minidom import getDOMImplementation
import copy
import pickle
import itertools
import time
import math
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email.utils import make_msgid
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','/afs/cern.ch/user/c/cmst2/www/unified/')
base_dir = os.getenv('UNIFIED_DIR','/afs/cern.ch/user/c/cmst2/Unified/')
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)
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 searchLog( q ,limit=50 ):
conn = httplib.HTTPConnection( 'cms-elastic-fe.cern.ch:9200' )
goodquery={
"query": {
"bool": {
"must": [
{
"wildcard": {
"meta": "*%s*"%q
}
},
#{
#"term": {
# "subject": "assignor"
# }
# }
]
}
},
"sort": [
{
"timestamp": "desc"
}
],
"_source": [
"text",
"subject",
"date",
"meta"
]
}
conn.request("POST" , '/logs/_search?size=%d'%limit, json.dumps(goodquery))
## 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']
return o['hits']['hits']
def try_sendLog( subject, text , wfi = None, show=True, level='info'):
#import pdb
#pdb.set_trace()
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" , '/logs/log/', json.dumps(doc))
response = conn.getresponse()
data = response.read()
try:
res = json.loads( data )
#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
if not destination:
destination = ['vlimant@cern.ch','matteoc@fnal.gov']
else:
destination = list(set(destination+['vlimant@cern.ch','matteoc@fnal.gov']))
if not sender:
map_who = { 'vlimant' : 'vlimant@cern.ch',
'mcremone' : 'matteoc@fnal.gov' }
user = os.getenv('USER')
if user in map_who:
sender = map_who[user]
else:
sender = 'vlimant@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 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 GET(url, there, l=True):
conn = httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
r1=conn.request("GET",there)
r2=conn.getresponse()
if l:
return json.loads(r2.read())
else:
return r2
def check_ggus( ticket ):
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 = 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 = 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 = 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 = 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 = 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
#import dataLock
class newLockInfo:
def __init__(self):
self.db = json.loads(open('%s/globallocks.json'%monitor_dir).read())
os.system('echo `date` > %s/globallocks.json.lock'%monitor_dir)
def __del__(self):
open('%s/globallocks.json.new'%monitor_dir,'w').write(json.dumps( sorted(list(set(self.db))) , indent=2 ))
os.system('mv %s/globallocks.json.new %s/globallocks.json'%(monitor_dir,monitor_dir))
os.system('rm -f %s/globallocks.json.lock'%monitor_dir)
def lock(self, dataset):
print "[new lock]",dataset,"to be locked"
# just put the
if dataset in self.db:
print "\t",dataset,"was already locked"
else:
self.db.append(dataset)
def release(self, dataset):
print "[new lock] should never release datasets"
#return
if not dataset in self.db:
print "\t",dataset,"was not locked already"
else:
print "taking",dataset,"out of the lock"
self.db.remove( dataset )
class lockInfo:
def __init__(self):
pass
def __del__(self):
if random.random() < 0.5:
print "Cleaning locks"
#self.clean_block()
self.clean_unlock()
print "... cleaning locks done"
jdump = {}
for l in dataLock.locksession.query(dataLock.Lock).all():
## don't print lock=False ??
#if not l.lock: continue
site= l.site
if not site in jdump: jdump[site] = {}
jdump[site][l.item] = {
'lock' : l.lock,
'time' : l.time,
'date' : time.asctime( time.gmtime(l.time) ),
'reason' : l.reason
}
now = time.mktime(time.gmtime())
jdump['lastupdate'] = now
open('%s/datalocks.json.new'%monitor_dir,'w').write( json.dumps( jdump , indent=2))
os.system('mv %s/datalocks.json.new %s/datalocks.json'%(monitor_dir,monitor_dir))
def _lock(self, item, site, reason):
print "[lock] of %s at %s because of %s"%( item, site, reason )
now = time.mktime(time.gmtime())
l = dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.site == site).filter(dataLock.Lock.item == item).first()
if not l:
l = dataLock.Lock(lock=False)
l.site = site
l.item = item
l.is_block = '#' in item
dataLock.locksession.add ( l )
if l.lock:
print l.item,item,"already locked at",site
## overwrite the lock
l.reason = reason
l.time = now
l.lock = True
dataLock.locksession.commit()
def lock(self, item, site, reason):
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 _release(self, item, site, reason='releasing'):
print "[lock release] of %s at %s because of %s" %( item, site, reason)
now = time.mktime(time.gmtime())
# get the lock on the item itself
l = dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.site==site).filter(dataLock.Lock.item==item).first()
if not l:
print item,"was not locked at",site
l = dataLock.Lock(lock=False)
l.site = site
l.item = item
l.is_block = '#' in item
dataLock.locksession.add ( l )
dataLock.locksession.commit()
#then unlock all of everything starting with item (itself for block, all block for dataset)
for l in dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.site==site).filter(dataLock.Lock.item.startswith(item)).all():
l.time = now
l.reason = reason
l.lock = False
dataLock.locksession.commit()
def release_except(self, item, except_site, reason='releasing'):
print "[lock release] of %s except at %s because of %s" %( item, except_site, reason)
try:
for l in dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.item.startswith(item)).all():
site = l.site
if not site in except_site:
self._release(l.item, site, reason)
else:
print "We are told to not release",item,"at site",site,"per request of",except_site
except Exception as e:
print "could not unlock",item,"everywhere but",except_site
print str(e)
def release_everywhere(self, item, reason='releasing'):
print "[lock release] of %s everywhere because of %s" % ( item, reason )
try:
for l in dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.item.startswith(item)).all():
site = l.site
self._release(item, site, reason)
except Exception as e:
print "could not unlock",item,"everywhere"
print str(e)
def release(self, item, site, reason='releasing'):
print "[lock release] of %s at %s because of %s" %( item, site, reason)
try:
self._release(item, site, reason)
except Exception as e:
print "could not unlock",item,"at",site
print str(e)
def tell(self, comment):
print "---",comment,"---"
for l in dataLock.locksession.query(dataLock.Lock).all():
print l.item,l.site,l.lock
print "------"+"-"*len(comment)
def clean_block(self, view=False):
print "start cleaning lock info"
## go and remove all blocks for which the dataset is specified
# if the dataset is locked, nothing matters for blocks -> remove
# if the dataset is unlocked, it means we don't want to keep anything of it -> remove
clean_timeout=0
for l in dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.lock==True).filter(dataLock.Lock.is_block==False).all():
site = l.site
item = l.item
if view: print item,"@",site
## get all the blocks at that site, for that dataset, under the same condition
for block in dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.site==site).filter(dataLock.Lock.item.startswith(item)).filter(dataLock.Lock.is_block==True).all():
print "removing lock item for",block.item,"at",site,"due to the presence of overriding dataset information"
dataLock.locksession.delete( block )
clean_timeout+=1
if view: print block.name
if clean_timeout> 10: break
dataLock.locksession.commit()
if clean_timeout> 10: break
def clean_unlock(self, view=False):
clean_timeout=0
## go and remove all items that have 'lock':False
for l in dataLock.locksession.query(dataLock.Lock).filter(dataLock.Lock.lock==False).all():
print "removing lock=false for",l.item,"at",l.site
dataLock.locksession.delete( l )
clean_timeout+=1
#if clean_timeout> 10: break
dataLock.locksession.commit()
class unifiedConfiguration:
def __init__(self):
self.configs = json.loads(open('%s/WmAgentScripts/unifiedConfiguration.json'%base_dir).read())
def get(self, parameter):
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)
def checkDownTime():
conn = httplib.HTTPSConnection(reqmgr_url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
r1=conn.request("GET",'/couchdb/reqmgr_workload_cache/jbadillo_BTV-RunIISpring15MiniAODv2-00011_00081_v0__151030_162715_5312')
r2=conn.getresponse()
r = r2.read()
if r2.status ==503:#if 'The site you requested is not unavailable' in r:
return True
else:
return False
class componentInfo:
def __init__(self, block=True, mcm=False,soft=None):
self.mcm = mcm
self.soft = soft
self.block = block
self.status ={
'reqmgr' : False,
'mcm' : False,
'dbs' : False,
'phedex' : False
}
self.code = 0
#if not self.check():
# sys.exit( self.code)
def check(self):
try:
print "checking reqmgr"
if 'testbed' in reqmgr_url:
wfi = workflowInfo(reqmgr_url,'sryu_B2G-Summer12DR53X-00743_v4_v2_150126_223017_1156')
else:
wfi = workflowInfo(reqmgr_url,'pdmvserv_task_B2G-RunIIWinter15wmLHE-00067__v1_T_150505_082426_497')
self.status['reqmgr'] = True
except Exception as e:
import traceback
print traceback.format_exc()
self.tell('reqmgr')
print reqmgr_url,"unreachable"
print str(e)
if self.block and not (self.soft and 'reqmgr' in self.soft):
self.code = 123
return False
from McMClient import McMClient
if self.mcm:
try:
mcmC = McMClient(dev=False)
print "checking mcm"
test = mcmC.getA('requests',page=0)
time.sleep(1)
if not test:
self.tell('mcm')
print "mcm corrupted"
if self.block and not (self.soft and 'mcm' in self.soft):
self.code = 124
return False
else:
self.status['mcm'] = True
except Exception as e:
self.tell('mcm')
print "mcm unreachable"
print str(e)
if self.block and not (self.soft and 'mcm' in self.soft):
self.code = 125
return False
try:
print "checking dbs"
dbsapi = DbsApi(url=dbs_url)
if 'testbed' in dbs_url:
blocks = dbsapi.listBlockSummaries( dataset = '/QDTojWinc_NC_M-1200_TuneZ2star_8TeV-madgraph/Summer12pLHE-DMWM_Validation_DONOTDELETE_Alan_TEST-v1/GEN', detail=True)
else:
blocks = dbsapi.listBlockSummaries( dataset = '/TTJets_mtop1695_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIIWinter15GS-MCRUN2_71_V1-v1/GEN-SIM', detail=True)
if not blocks:
self.tell('dbs')
print "dbs corrupted"
if self.block and not (self.soft and 'dbs' in self.soft):
self.code = 126
return False
else:
self.status['dbs'] = True
except Exception as e:
self.tell('dbs')
print "dbs unreachable"
print str(e)
if self.block and not (self.soft and 'dbs' in self.soft):
self.code = 127
return False
try:
print "checking phedex"
if 'testbed' in dbs_url:
cust = findCustodialLocation(phedex_url,'/TTJets_mtop1695_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIIWinter15GS-MCRUN2_71_V1-v1/GEN-SIM')
else:
cust = findCustodialLocation(phedex_url,'/TTJets_mtop1695_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIIWinter15GS-MCRUN2_71_V1-v1/GEN-SIM')
self.status['phedex'] = True
except Exception as e:
self.tell('phedex')
print "phedex unreachable"
print str(e)
if self.block and not (self.soft and 'phedex' in self.soft):
self.code = 128
return False
print json.dumps( self.status, indent=2)
return True
def tell(self, c):
sendEmail("%s Component Down"%c,"The component is down, just annoying you with this","vlimant@cern.ch",['vlimant@cern.ch','matteoc@fnal.gov'])
class campaignInfo:
def __init__(self):
#this contains accessor to aggreed campaigns, with maybe specific parameters
self.campaigns = json.loads(open('%s/WmAgentScripts/campaigns.json'%base_dir).read())
SI = siteInfo()
for c in self.campaigns:
if 'parameters' in self.campaigns[c]:
if 'SiteBlacklist' in self.campaigns[c]['parameters']:
for black in copy.deepcopy(self.campaigns[c]['parameters']['SiteBlacklist']):
if black.endswith('*'):
self.campaigns[c]['parameters']['SiteBlacklist'].remove( black )
reg = black[0:-1]
self.campaigns[c]['parameters']['SiteBlacklist'].extend( [site for site in (SI.all_sites) if site.startswith(reg)] )
#print self.campaigns[c]['parameters']['SiteBlacklist']
def go(self, c, s=None):
if c in self.campaigns and self.campaigns[c]['go']:
if 'labels' in self.campaigns[c]:
if s!=None:
return (s in self.campaigns[c]['labels']) or any([l in s for l in self.campaigns[c]['labels']])
else:
print "Not allowed to go for",c,s
return False
else:
return True
else:
print "Not allowed to go for",c
return False
def get(self, c, key, default):
if c in self.campaigns:
if key in self.campaigns[c]:
return copy.deepcopy(self.campaigns[c][key])
return copy.deepcopy(default)
def parameters(self, c):
if c in self.campaigns and 'parameters' in self.campaigns[c]:
return self.campaigns[c]['parameters']
else:
return {}
def notRunningBefore( component, time_out = 60*5 ):
s = 10
while True:
if time_out<0:
print "Could not wait any longer for %s to finish"% component
return False
process_check = filter(None,os.popen('ps -f -e | grep %s.py | grep -v grep |grep python'%component).read().split('\n'))
if len(process_check):
## there is still the component running. wait
time.sleep(s)
time_out-=s
continue
break
return True
def duplicateLock(component=None):
if not component:
## get the caller
component = sys._getframe(1).f_code.co_name
## check that no other instances of assignor is running
process_check = filter(None,os.popen('ps -f -e | grep %s.py | grep -v grep |grep python'%component).read().split('\n'))
if len(process_check)>1:
## another component is running on the machine : stop
sendEmail('overlapping %s'%component,'There are %s instances running %s'%(len(process_check), '\n'.join(process_check)))
print "quitting because of overlapping processes"
return True
return False
def userLock(component=None):
if not component:
## get the caller
component = sys._getframe(1).f_code.co_name
lockers = ['dmytro','mcremone','vlimant']
for who in lockers:
if os.path.isfile('/afs/cern.ch/user/%s/%s/public/ops/%s.lock'%(who[0],who,component)):
print "disabled by",who
return True
return False
class docCache:
def __init__(self):
self.cache = {}
def default_expiration():
return 20*60+random.random()*10*60
self.cache['ssb_106'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=106&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_107'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=107&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_108'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=108&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_109'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=109&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_136'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=136&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_158'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=158&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_237'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=237&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_159'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=159&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['ssb_160'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl -s --retry 5 "http://dashb-ssb.cern.ch/dashboard/request.py/getplotdata?columnid=160&batch=1&lastdata=1"').read())['csvdata'],
'cachefile' : None,
'default' : []
}
self.cache['gwmsmon_totals'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl --retry 5 -s http://cms-gwmsmon.cern.ch/poolview/json/totals').read()),
'cachefile' : None,
'default' : {}
}
self.cache['mcore_ready'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl --retry 5 -s http://cmsgwms-frontend-global.cern.ch/vofrontend/stage/mcore_siteinfo.json').read()),
'cachefile' : None,
'default' : {}
}
self.cache['gwmsmon_prod_site_summary' ] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl --retry 5 -s http://cms-gwmsmon.cern.ch/prodview//json/site_summary').read()),
'cachefile' : None,
'default' : {}
}
self.cache['gwmsmon_site_summary' ] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads(os.popen('curl --retry 5 -s http://cms-gwmsmon.cern.ch/totalview//json/site_summary').read()),
'cachefile' : None,
'default' : {}
}
self.cache['detox_sites'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : os.popen('curl --retry 5 -s http://t3serv001.mit.edu/~cmsprod/IntelROCCS/Detox/SitesInfo.txt').read().split('\n'),
'cachefile' : None,
'default' : ""
}
self.cache['T1_DE_KIT_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T1_DE_KIT_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['T1_US_FNAL_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T1_US_FNAL_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['T1_ES_PIC_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T1_ES_PIC_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['T1_UK_RAL_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T1_UK_RAL_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['T1_IT_CNAF_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T1_IT_CNAF_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['T1_FR_CCIN2P3_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T1_FR_CCIN2P3_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['T1_RU_JINR_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T1_RU_JINR_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['T0_CH_CERN_MSS_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : getNodeUsage(phedex_url,'T0_CH_CERN_MSS'),
'cachefile' : None,
'default' : ""
}
self.cache['mss_usage'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads( os.popen('curl -s --retry 5 http://cmsmonitoring.web.cern.ch/cmsmonitoring/StorageOverview/latest/StorageOverview.json').read()),
'cachefile' : None,
'default' : {}
}
self.cache['hlt_cloud'] = {
'data' : None,
'timestamp' : time.mktime( time.gmtime()),
'expiration' : default_expiration(),
'getter' : lambda : json.loads( os.popen('curl -s --retry 1 --connect-timeout 5 http://137.138.184.204/cache-manager/images/cloudStatus.json').read()),
'cachefile' : None,
'default' : {}
}
#create the cache files from the labels
for src in self.cache:
self.cache[src]['cachefile'] = '.'+src+'.cache.json'
def get(self, label, fresh=False):
now = time.mktime( time.gmtime())
if label in self.cache:
try:
cache = self.cache[label]
if not cache['data']:
#check the file version
if os.path.isfile(cache['cachefile']):
print "load",label,"from file",cache['cachefile']
f_cache = json.loads(open(cache['cachefile']).read())
cache['data' ] = f_cache['data']
cache['timestamp' ] = f_cache['timestamp']
else:
print "no file cache for", label,"getting fresh"
cache['data'] = cache['getter']()
cache['timestamp'] = now
open(cache['cachefile'],'w').write( json.dumps({'data': cache['data'], 'timestamp' : cache['timestamp']}, indent=2) )
## check the time stamp
if cache['expiration']+cache['timestamp'] < now or fresh:
print "getting fresh",label
cache['data'] = cache['getter']()
cache['timestamp'] = now
open(cache['cachefile'],'w').write( json.dumps({'data': cache['data'], 'timestamp' : cache['timestamp']}, indent=2) )
return cache['data']
except Exception as e:
print "failed to get",label
print str(e)
return copy.deepcopy(cache['default'])
def getNodes(url, kind):
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/nodes')
r2=conn.getresponse()
result = json.loads(r2.read())
return [node['name'] for node in result['phedex']['node'] if node['kind']==kind]
def getNodeUsage(url, node):
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/nodeusage?node=%s'%node)
r2=conn.getresponse()
result = json.loads(r2.read())
if len(result['phedex']['node']):
s= max([sum([node[k] for k in node.keys() if k.endswith('_node_bytes')]) for node in result['phedex']['node']])
return int(s / 1023.**4) #in TB
else:
return None
dataCache = docCache()
class DSS:
def __init__(self):
try:
self.bdb = json.loads(open('bdss.json').read())
except:
print "no bank of dataset size. starting fresh"
self.bdb = {}
def _get(self, dataset ):
if not dataset in self.bdb:
print "fetching info of",dataset
self.bdb[dataset] = getDatasetBlockSize( dataset )
def get(self, dataset ):
return self.get_size( dataset )
def get_size(self, dataset):
self._get( dataset )
return sum( self.bdb[dataset].values() )
def get_block_size(self, dataset):
self._get( dataset )
return sum( self.bdb[dataset].values() ), copy.deepcopy( self.bdb[dataset] )
def __del__(self):
## pop when too many entries
if len(self.bdb) > 1000:
keys = self.bdb.keys()
random.shuffle(keys)
for k in keys[:1000]:
self.bdb.pop(k)
try:
open('bdss.json','w').write( json.dumps( self.bdb ))
except:
print "no access to bdss.json"
class siteInfo:
def __init__(self):