This repository has been 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
/
utils.py
executable file
·5379 lines (4710 loc) · 217 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
import logging
from dbs.apis.dbsClient import DbsApi
import httplib
import os
import socket
import json
import collections
from collections import defaultdict
import random
import copy
import pickle
import time
import math
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
from RucioClient import RucioClient
## 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)
def mongo_client():
import pymongo, ssl
return pymongo.MongoClient('mongodb://%s/?ssl=true' % mongo_db_url,
ssl_cert_reqs=ssl.CERT_NONE)
class unifiedConfiguration:
def __init__(self, configFile='unifiedConfiguration.json'):
# Explicitly set configFile to 'None' once you want to read from MongoDB
self.configFile = configFile
if self.configFile is None:
self.configs = self.configFile
else:
try:
self.configs = json.loads(open(self.configFile).read())
except Exception as ex:
print("Could not read configuration file: %s\nException: %s" %
(self.configFile, str(ex)))
sys.exit(124)
if self.configs is None:
try:
self.client = mongo_client()
self.db = self.client.unified.unifiedConfiguration
except Exception as ex:
print ("Could not reach pymongo.\n Exception: \n%s" % str(ex))
# self.configs = json.loads(open(self.configFile).read())
sys.exit(124)
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:
availables = [o['name'] for o in self.db.find_one()]
print parameter, 'is not defined in mongo configuration'
print ','.join(availables), 'possible'
sys.exit(124)
SC = unifiedConfiguration('serviceConfiguration.json')
mongo_db_url = SC.get('mongo_db_url')
dbs_url = os.getenv('UNIFIED_DBS3_READER', SC.get('dbs_url'))
dbs_url_writer = os.getenv('UNIFIED_DBS3_WRITER', SC.get('dbs_url_writer'))
phedex_url = os.getenv('UNIFIED_PHEDEX', SC.get('phedex_url'))
reqmgr_url = os.getenv('UNIFIED_REQMGR', SC.get('reqmgr_url'))
monitor_dir = os.getenv('UNIFIED_MON', SC.get('monitor_dir'))
monitor_eos_dir = SC.get('monitor_eos_dir')
monitor_dir = monitor_eos_dir
monitor_pub_dir = os.getenv('UNIFIED_MON', SC.get('monitor_pub_eos_dir'))
monitor_pub_eos_dir = SC.get('monitor_pub_eos_dir')
monitor_pub_dir = monitor_pub_eos_dir
base_dir = os.getenv('UNIFIED_DIR', SC.get('base_dir'))
base_eos_dir = SC.get('base_eos_dir')
unified_url = os.getenv('UNIFIED_URL', SC.get('unified_url'))
unified_url_eos = SC.get('unified_url_eos')
unified_url = unified_url_eos
url_eos = unified_url_eos
unified_pub_url = os.getenv('UNIFIED_URL', SC.get('unified_pub_url'))
cache_dir = SC.get('cache_dir')
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
else:
d[k] = v
return d
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"]}
if 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 {})
response = conn.getresponse()
data = response.read()
o = json.loads( data )
hits = o['hits']['hits']
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
"""
_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'):
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):
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 )
except Exception as e:
print "failed"
print str(e)
pass
def sendEmail( subject, text, sender=None, destination=None ):
UC = unifiedConfiguration()
email_destination = UC.get("email_destination")
if not destination:
destination = email_destination
else:
destination = list(set(destination))
if not sender:
map_who = {
'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 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 = make_x509_conn(url)
r1=conn.request("GET",there)
r2=conn.getresponse()
if l:
return json.loads(r2.read())
else:
return r2
class UnifiedLock:
def __init__(self, acquire=True):
self.owner = "%s-%s"%(socket.gethostname(), os.getpid())
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
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 lockInfo:
def __init__(self, andwrite=True):
self.owner = "%s-%s"%(socket.gethostname(), os.getpid())
self.unifiedlock = UnifiedLock()
def release(self, item ):
try:
self._release(item)
except Exception as e:
print "failed to release"
print str(e)
def _release(self, item ):
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.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 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 assignSession import session, Lock
print "---",comment,"---"
for l in session.query(Lock).all():
print l.item,l.lock
print "------"+"-"*len(comment)
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 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 }})
def checkMemory():
import resource
rusage_denom = 1024.
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / rusage_denom
return mem
class componentInfo:
def __init__(self, block=True, mcm=None, soft=None, keep_trying=False, check_timeout = 120):
self.checks = componentCheck(block, mcm, soft, keep_trying)
self.check_timeout = check_timeout
# start the checking
self.checks.start()
def check(self):
check_start = time.mktime(time.gmtime())
# on timeout
ping = 10
while self.checks.is_alive():
now = time.mktime(time.gmtime())
if (now-check_start) > self.check_timeout:
alarm = "Timeout in checking the sanity of components %d > %d , while checking on %s"%(now-check_start,self.check_timeout, self.checks.checking)
sendLog('componentInfo',alarm, level='critical')
return False
print "componentInfo, ping",now,check_start,now-check_start
time.sleep(ping)
self.status = self.checks.status
print "componentInfo, going with"
print self.checks.go
return self.checks.go
class componentCheck(threading.Thread):
def __init__(self, block=True, mcm=None, soft=None, keep_trying=False):
threading.Thread.__init__(self)
self.daemon = True
if soft is None:
self.soft = ['mcm','wtc', 'mongo' , 'jira'] ##components that are not mandatory
else:
self.soft = soft
self.block = block
self.status ={
'reqmgr' : False,
'mcm' : False,
'dbs' : False,
'cmsr' : False,
'wtc' : False,
'eos' : False,
'mongo' : False,
'jira' : False
}
self.code = 0
self.keep_trying = keep_trying
self.go = False
self.checking=None
def run(self):
self.go = self.check()
print "componentCheck finished"
def check_cmsr(self):
from assignSession import session, Workflow
all_info = session.query(Workflow).filter(Workflow.name.contains('1')).all()
def check_reqmgr(self):
data = getReqmgrInfo(reqmgr_url)
def check_mcm(self):
from McMClient import McMClient
mcmC = McMClient(dev=False)
test = mcmC.getA('requests',page=0)
time.sleep(1)
if not test:
raise Exception("mcm is corrupted")
def check_dbs(self):
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:
raise Exception("dbs corrupted")
def check_wtc(self):
from wtcClient import wtcClient
WC = wtcClient()
a = WC.get_actions()
if a is None:
raise Exception("No action can be retrieved")
def check_eos(self):
eosfile = base_eos_dir+'/%s-testfile'%os.getpid()
oo = eosFile(eosfile)
oo.write("Testing I/O on eos")
r = oo.close() ## commits to eos
if r:
r = os.system('env EOS_MGM_URL=root://eoscms.cern.ch eos rm %s'% eosfile)
if not r == 0:
raise Exception("failed to I/O on eos")
def check_mongo(self):
db = agentInfoDB()
infos = [a['status'] for a in db.find()]
def check_jira(self):
from JIRAClient import JIRAClient
JC = JIRAClient()
opened = JC.find({'status': 'OPEN'})
def check(self):
ecode = 120
for component in sorted(self.status):
ecode+=1
self.checking = component
while True:
try:
print "checking on",component
sys.stdout.flush()
getattr(self,'check_%s'%component)()
self.status[component] = True
break
except Exception as e:
self.tell(component)
if self.keep_trying:
print "re-checking on",component
time.sleep(30)
continue
import traceback
print traceback.format_exc()
print component,"is unreachable"
print str(e)
if self.block and not (self.soft and component in self.soft):
self.code = ecode
return False
break
print json.dumps( self.status, indent=2)
sys.stdout.flush()
return True
def tell(self, c):
host = socket.gethostname()
sendLog('componentInfo',"The %s component is unreachable from %s"%(c, host), level='critical')
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def read_file(target):
content = open(target).read()
if target.endswith('json'):
if is_json(content):
return content
else:
print("Opening an invalid json file")
sendLog("eosRead","Error reading json file {} at {}".format(target, datetime.datetime.now()), level='critical')
return "{}"
else:
return content
def eosRead(filename,trials=5):
filename = filename.replace('//','/')
if not filename.startswith('/eos/'):
print filename,"is not an eos path in eosRead"
T=0
while T<trials:
T+=1
try:
return read_file(filename)
except Exception as e:
print "failed to read",filename,"from eos"
time.sleep(2)
cache = (cache_dir+'/'+filename.replace('/','_')).replace('//','/')
r = os.system('env EOS_MGM_URL=root://eoscms.cern.ch eos cp %s %s'%( filename, cache ))
if r==0:
return read_file(cache)
print "unable to read from eos"
return None
class eosFile(object):
def __init__(self, filename, opt='w', trials=5):
if not filename.startswith('/eos/'):
print filename,"is not an eos path"
sys.exit(2)
self.opt = opt
self.eos_filename = filename.replace('//','/')
self.cache_filename = (cache_dir+'/'+filename.replace('/','_')).replace('//','/')
self.cache = open(self.cache_filename, self.opt)
self.trials = trials
def write(self, something):
self.cache.write( something )
return self
def close(self):
self.cache.close()
bail_and_email = False
T = 0
while T < self.trials:
T += 1
try:
print "moving",self.cache_filename,"to",self.eos_filename
print("Attempt {}".format(T))
r = os.system("env EOS_MGM_URL=root://eoscms.cern.ch eos cp %s %s"%( self.cache_filename, self.eos_filename))
if r==0 and os.path.getsize(self.eos_filename) > 0: return True
print "not able to copy to eos",self.eos_filename,"with code",r
time.sleep(30)
if bail_and_email:
h = socket.gethostname()
print 'eos is acting up on %s on %s. not able to copy %s to eos code %s'%( h, time.asctime(), self.eos_filename, r)
break
except Exception as e:
print "Failed to copy",self.eos_filename,"with",str(e)
if bail_and_email:
h = socket.gethostname()
print 'eos is acting up on %s on %s. not able to copy %s to eos \n%s'%( h, time.asctime(), self.eos_filename, str(e))
break
else:
time.sleep(30)
h = socket.gethostname()
msg = 'eos is acting up on %s on %s. not able to copy %s to eos'%( h, time.asctime(), self.eos_filename)
sendEmail('eosFile',msg)
print(msg)
return False
class batchInfo:
def __init__(self):
self.client = mongo_client()
self.db = self.client.unified.batchInfo
def update(self, name, a_list):
ex = self.db.find_one({'name' : name})
if ex:
ex['ids'] = list(set(list(ex['ids'])+list(a_list)))
else:
ex = {'ids': list(a_list)}
self.add( name, ex)
def add(self, name, content):
## update if necessary
self.db.update_one({'name' : name},
{"$set": content},
upsert = True
)
def content(self):
c = {}
for o in self.db.find():
c[o['name']] = o['ids']
return c
def all(self):
return [o['name'] for o in self.db.find()]
def pop(self, name):
self.db.delete_one({'name': name})
class campaignInfo:
def __init__(self):
self.campaigns = {}
self.client = mongo_client()
self.db = self.client.unified.campaignsConfiguration
self.campaigns = self.content()
SI = global_SI()
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)] )
def content(self):
uc = {}
for c in self.db.find():
c.pop("_id")
uc[c.pop("name")] = c
return uc
def all(self, c_type = None):
return [o['name'] for o in self.db.find() if (c_type == None or o.get('type',None) == c_type)]
def update(self, c_dict, c_type=None):
for k,v in c_dict.items():
self.add( k, v, c_type=c_type)
def add(self, name, content, c_type=None):
## update if needed
content['name'] = name
if c_type:
content['type'] = c_type
self.db.update_one({'name' : name},
{"$set": content},
upsert = True
)
def pop(self, item_name):
print "removing",item_name,"from campaign configuration"
self.db.delete_one({'name' : item_name})
def go(self, c, s=None):
GO = False
if c in self.campaigns and self.campaigns[c]['go']:
if 'labels' in self.campaigns[c]:
if s!=None:
GO = (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
GO = False
else:
GO = True
elif c in self.campaigns and not self.campaigns[c]['go']:
if s and 'pilot' in s.lower():
GO = True
else:
print "Not allowed to go for",c
GO = False
return GO
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 allSecondaries(self):
secs = set()
for c in self.campaigns:
if self.campaigns[c].get('go'):
for sec in self.campaigns[c].get('secondaries',{}):
if not sec: continue
secs.add( sec )
return sorted(secs)
class moduleLock(object):
def __init__(self,component=None, silent=False, wait=False, max_wait = 18000, locking=True):
if not component:
component = sys._getframe(1).f_code.co_name
self.poll = 30
self.pid = os.getpid()
self.host = socket.gethostname()
self.component = component
self.wait = wait
self.silent= silent
self.max_wait = max_wait
self.locking = locking
self.client = mongo_client()
self.db = self.client.unified.moduleLock
def check(self, hours_before_kill = 24):
host = socket.gethostname()
locks = [l for l in self.db.find({'host' : host})]
now = time.mktime(time.gmtime())
for lock in locks:
pid = lock.get('pid',None)
print "checking on %s on %s"%( pid, host)
on_since = now - lock.get('time',now)
if on_since > (hours_before_kill*60*60):
alarm = "process %s on %s for module %s is running since %s : killing"%( pid, host, lock.get('component',None), display_time( on_since))
sendLog('heartbeat', alarm, level='critical')
os.system('sudo kill -9 %s'%(pid))
time.sleep(2)
if not os.path.isdir('/proc/%s'% pid):
alarm = "process %s is not present on %s"%( pid, host)
sendLog('heartbeat', alarm, level='critical')
self.db.delete_one({ '_id' : lock.get('_id',None)})
def all_locks(self):
locks = [l for l in self.db.find()]
print "module locks available in mongodb"
print sorted(locks)
def clean(self, component=None, pid=None, host=None):
sdoc = {'component' : component}
if pid is not None:
sdoc.update({'pid' : pid})
if host is not None:
sdoc.update({'host' : host})
self.db.delete_many( sdoc )
def __call__(self):
print "module lock for component",self.component,"from mongo db"
polled = 0
nogo = True
locks = []
i_try = 0
while True:
if not self.locking:
nogo = False
break
## check from existing such lock, solely based on the component, nothing else
locks = [l for l in self.db.find({'component' : self.component})]
if locks:
if not self.wait:
nogo =True
break
else:
print "Waiting for other %s components to stop running \n%s" % ( self.component , locks)
time.sleep( self.poll )
polled += self.poll
else:
## nothing is in the way. go ahead
nogo = False
break
i_try += 1
if self.max_wait and polled > self.max_wait:
print "stop waiting for %s to be released"% ( self.component )
break
if not nogo:
## insert a lock doc
n = time.gmtime()
now = time.mktime( n )
nows = time.asctime( n )
lockdoc = {'component' : self.component,
'host' : self.host,
'pid' : self.pid,
'time' : now,
'date' : nows}
self.db.insert_one( lockdoc )
#print lockdoc
else:
if not self.silent:
msg = 'There are %s instances running.Possible deadlock. Tried for %d [s] \n%s'%(len(locks),
polled,
locks)
sendLog('heartbeat', msg , level='critical')
print msg
return nogo
def __del__(self):
# remove the lock doc
self.clean( component = self.component,
pid = self.pid,
host = self.host)
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
def getWMStats(url):
conn = make_x509_conn(url)
url = '/wmstatsserver/data/requestcache'
r1=conn.request("GET",url,headers={"Accept":"application/json"})
r2=conn.getresponse()
return json.loads(r2.read())['result'][0]
def get_dashbssb(path_name, ssb_metric):
return runWithRetries(_get_dashbssb, [path_name, ssb_metric],{})
def _get_dashbssb(path_name, ssb_metric):
with open('Unified/monit_secret.json') as monit:
conf = json.load(monit)
query = """'{"search_type":"query_then_fetch","ignore_unavailable":true,"index":["monit_prod_cmssst_*","monit_prod_cmssst_*"]}
{"size":1,"query":{"bool":{"filter":[{"range":{"metadata.timestamp":{"gte":"now-2d","lte":"now","format":"epoch_millis"}}},{"query_string":{"analyze_wildcard":true,"query":"metadata.type: ssbmetric AND metadata.type_prefix:raw AND metadata.path: %s"}}]}},"sort":{"metadata.timestamp":{"order":"desc","unmapped_type":"boolean"}},"script_fields":{},"docvalue_fields":["metadata.timestamp"]}
'"""%(str(path_name))
TIMESTAMP = json.loads(os.popen('curl -s -X POST %s -H "Authorization: Bearer %s" -H "Content-Type: application/json" -d %s'%(conf["url"],conf["token"],query)).read())["responses"][0]["hits"]["hits"][0]["_source"]["metadata"]["timestamp"]