-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrangler_checks.py
2010 lines (1866 loc) · 90.2 KB
/
wrangler_checks.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
from __future__ import print_function, unicode_literals
from ..utils import (
check_function,
action_function,
)
from ..run_result import CheckResult, ActionResult
from dcicutils import ff_utils
from dcicutils.env_utils import FF_PROD_BUCKET_ENV
import re
import requests
import json
import datetime
import time
import itertools
import random
from fuzzywuzzy import fuzz
import boto3
from .helpers import wrangler_utils
from collections import Counter
# use a random number to stagger checks
random_wait = 20
@check_function(cmp_to_last=False)
def workflow_run_has_deleted_input_file(connection, **kwargs):
"""Checks all wfrs that are not deleted, and have deleted input files
There is an option to compare to the last, and only report new cases (cmp_to_last)
The full output has 2 keys, because we report provenance wfrs but not run action on them
problematic_provenance: stores uuid of deleted file, and the wfr that is not deleted
problematic_wfr: stores deleted file, wfr to be deleted, and its downstream items (qcs and output files)
"""
check = CheckResult(connection, 'workflow_run_has_deleted_input_file')
check.status = "PASS"
check.action = "patch_workflow_run_to_deleted"
my_key = connection.ff_keys
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
# run the check
search_query = 'search/?type=WorkflowRun&status!=deleted&input_files.value.status=deleted&limit=all'
bad_wfrs = ff_utils.search_metadata(search_query, key=my_key)
if kwargs.get('cmp_to_last', False):
# filter out wfr uuids from last run if so desired
prevchk = check.get_latest_result()
if prevchk:
prev_wfrs = prevchk.get('full_output', [])
filtered = [b.get('uuid') for b in bad_wfrs if b.get('uuid') not in prev_wfrs]
bad_wfrs = filtered
if not bad_wfrs:
check.summmary = check.description = "No live WorkflowRuns linked to deleted input Files"
return check
brief = str(len(bad_wfrs)) + " live WorkflowRuns linked to deleted input Files"
# problematic_provenance stores uuid of deleted file, and the wfr that is not deleted
# problematic_wfr stores deleted file, wfr to be deleted, and its downstream items (qcs and output files)
fulloutput = {'problematic_provenance': [], 'problematic_wfrs': []}
no_of_items_to_delete = 0
def fetch_wfr_associated(wfr_info):
"""Given wfr_uuid, find associated output files and qcs"""
wfr_as_list = []
wfr_as_list.append(wfr_info['uuid'])
if wfr_info.get('output_files'):
for o in wfr_info['output_files']:
if o.get('value'):
wfr_as_list.append(o['value']['uuid'])
if o.get('value_qc'):
wfr_as_list.append(o['value_qc']['uuid'])
if wfr_info.get('output_quality_metrics'):
for qc in wfr_info['output_quality_metrics']:
if qc.get('value'):
wfr_as_list.append(qc['value']['uuid'])
return list(set(wfr_as_list))
for wfr in bad_wfrs:
infiles = wfr.get('input_files', [])
delfile = [f.get('value').get('uuid') for f in infiles if f.get('value').get('status') == 'deleted'][0]
if wfr['display_title'].startswith('File Provenance Tracking'):
fulloutput['problematic_provenance'].append([delfile, wfr['uuid']])
else:
del_list = fetch_wfr_associated(wfr)
fulloutput['problematic_wfrs'].append([delfile, wfr['uuid'], del_list])
no_of_items_to_delete += len(del_list)
check.summary = "Live WorkflowRuns found linked to deleted Input Files"
check.description = "{} live workflows were found linked to deleted input files - \
found {} items to delete, use action for cleanup".format(len(bad_wfrs), no_of_items_to_delete)
if fulloutput.get('problematic_provenance'):
brief += " ({} provenance tracking)"
check.brief_output = brief
check.full_output = fulloutput
check.status = 'WARN'
check.action_message = "Will attempt to patch %s workflow_runs with deleted inputs to status=deleted." % str(len(bad_wfrs))
check.allow_action = True # allows the action to be run
return check
@action_function()
def patch_workflow_run_to_deleted(connection, **kwargs):
action = ActionResult(connection, 'patch_workflow_run_to_deleted')
check_res = action.get_associated_check_result(kwargs)
action_logs = {'patch_failure': [], 'patch_success': []}
my_key = connection.ff_keys
for a_case in check_res['full_output']['problematic_wfrs']:
wfruid = a_case[1]
del_list = a_case[2]
patch_data = {'status': 'deleted'}
for delete_me in del_list:
try:
ff_utils.patch_metadata(patch_data, obj_id=delete_me, key=my_key)
except Exception as e:
acc_and_error = [delete_me, str(e)]
action_logs['patch_failure'].append(acc_and_error)
else:
action_logs['patch_success'].append(wfruid + " - " + delete_me)
action.output = action_logs
action.status = 'DONE'
if action_logs.get('patch_failure'):
action.status = 'FAIL'
return action
@check_function(uuid_list=None, false_positives=None, add_to_result=None)
def biorxiv_is_now_published(connection, **kwargs):
''' To restrict the check to just certain biorxivs use a comma separated list
of biorxiv uuids in uuid_list kwarg. This is useful if you want to
only perform the replacement on a subset of the potential matches - i.e.
re-run the check with a uuid list and then perform the actions on the result
of the restricted check.
Known cases of incorrect associations are stored in the check result in
the 'false_positive' field of full_output. To add new entries to this field use the
'false_positive' kwarg with format "rxiv_uuid1: number_part_only_of_PMID, rxiv_uuid2: ID ..."
eg. fd3827e5-bc4c-4c03-bf22-919ee8f4351f:31010829 and to reset to empty use 'RESET'
There are some examples of the title and author list being different enough so
that the pubmid esearch query doesn't find the journal article. In order to
allow the replacement, movement of all the relevant fields and adding static sections
in the action - a parameter is provided to manually input a mapping between biorxiv (uuid)
to journal article (PMID:ID) - to add that pairing to the result full_output. It will
be acted on by the associated action format of input is uuid PMID:nnnnnn, uuid PMID:nnnnnn
'''
check = CheckResult(connection, 'biorxiv_is_now_published')
chkstatus = ''
chkdesc = ''
check.action = "add_pub_and_replace_biorxiv"
fulloutput = {'biorxivs2check': {}, 'false_positives': {}, 'GEO datasets found': {}}
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
# see if a 'manual' mapping was provided as a parameter
fndcnt = 0
if kwargs.get('add_to_result'):
b2p = [pair.strip().split(' ') for pair in kwargs.get('add_to_result').split(',')]
fulloutput['biorxivs2check'].update({b.strip(): [p.strip()] for b, p in b2p})
fndcnt = len(b2p)
search = 'search/?'
if kwargs.get('uuid_list'):
suffix = '&'.join(['uuid={}'.format(u) for u in [uid.strip() for uid in kwargs.get('uuid_list').split(',')]])
else:
suffix = 'journal=bioRxiv&type=Publication&status=current&limit=all'
# run the check
search_query = search + suffix
biorxivs = ff_utils.search_metadata(search_query, key=connection.ff_keys)
if not biorxivs and not fndcnt:
check.status = "FAIL"
check.description = "Could not retrieve biorxiv records from fourfront"
return check
# here is where we get any previous or current false positives
last_result = check.get_primary_result()
# if last one was fail, find an earlier check with non-FAIL status
it = 0
while last_result['status'] == 'ERROR' or not last_result['kwargs'].get('primary'):
it += 1
# this is a daily check, so look for checks with 12h iteration
hours = it * 12
last_result = check.get_closest_result(diff_hours=hours)
# if this is going forever kill it
if hours > 100:
err_msg = 'Can not find a non-FAIL check in last 100 hours'
check.brief_output = err_msg
check.full_output = {}
check.status = 'ERROR'
return check
last_result = last_result.get('full_output')
try:
false_pos = last_result.get('false_positives', {})
except AttributeError: # if check errored last result is a list of error rather than a dict
false_pos = {}
fp_input = kwargs.get('false_positives')
if fp_input:
fps = [fp.strip() for fp in fp_input.split(',')]
for fp in fps:
if fp == 'RESET': # reset the saved dict to empty
false_pos = {}
continue
id_vals = [i.strip() for i in fp.split(':')]
false_pos.setdefault(id_vals[0], []).append(id_vals[1])
fulloutput['false_positives'] = false_pos
pubmed_url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmode=json'
problems = {}
for bx in biorxivs:
title = bx.get('title')
authors = bx.get('authors')
buuid = bx.get('uuid')
if not (title and authors):
# problem with biorxiv record in ff
problems.setdefault('missing metadata', []).append(buuid)
if not chkstatus or chkstatus != 'WARN':
chkstatus = 'WARN'
msg = "some biorxiv records are missing metadata used for search\n"
if msg not in chkdesc:
chkdesc = chkdesc + msg
# first search with title
suffix = '&field=title&term={}'.format(title)
title_query = pubmed_url + suffix
time.sleep(1)
do_author_search = False
ids = []
res = requests.get(title_query)
if res.status_code == 200:
result = res.json().get('esearchresult')
if not result or not result.get('idlist'):
do_author_search = True
else:
ids = result.get('idlist')
else:
do_author_search = True # problem with request to pubmed
if do_author_search and authors:
author_string = '&term=' + '%20'.join(['{}[Author]'.format(a.split(' ')[-1]) for a in authors])
author_query = pubmed_url + author_string
time.sleep(1)
res = requests.get(author_query)
if res.status_code == 200:
result = res.json().get('esearchresult')
if result and result.get('idlist'):
ids = result.get('idlist')
if buuid in false_pos:
ids = [i for i in ids if i not in false_pos[buuid]]
if ids:
# we have possible article(s) - populate check_result
fndcnt += 1
fulloutput['biorxivs2check'][buuid] = ['PMID:' + id for id in ids]
# look for GEO datasets
for id_ in ids:
result = requests.get('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/'
'elink.fcgi?dbfrom=pubmed&db=gds&id={}&retmode=json'.format(id_))
if result.status_code != 200:
continue
geo_ids = [num for link in json.loads(result.text).get('linksets', [])
for item in link.get('linksetdbs', []) for num in item.get('links', [])]
geo_accs = []
for geo_id in geo_ids:
geo_result = requests.get('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/'
'efetch.fcgi?db=gds&id={}'.format(geo_id))
if geo_result.status_code == 200:
geo_accs.extend([item for item in geo_result.text.split() if item.startswith('GSE')])
if geo_accs:
fulloutput['GEO datasets found']['PMID:' + id_] = geo_accs
if fndcnt != 0:
chkdesc = "Candidate Biorxivs to replace found\n" + chkdesc
if not chkstatus:
chkstatus = 'WARN'
check.allow_action = True
else:
chkdesc = "No Biorxivs to replace\n" + chkdesc
if not chkstatus:
chkstatus = 'PASS'
check.allow_action = False
check.status = chkstatus
check.summary = check.description = chkdesc
check.brief_output = fndcnt
check.full_output = fulloutput
return check
@action_function()
def add_pub_and_replace_biorxiv(connection, **kwargs):
action = ActionResult(connection, 'add_pub_and_replace_biorxiv')
action_log = {}
biorxiv_check_result = action.get_associated_check_result(kwargs)
check_output = biorxiv_check_result.get('full_output', {})
to_replace = check_output.get('biorxivs2check', {})
for buuid, pmids in to_replace.items():
error = ''
if len(pmids) > 1:
pmstr = ', '.join(pmids)
action_log[buuid] = 'multiple pmids {} - manual intervention needed!'.format(pmstr)
continue
pmid = pmids[0]
biorxiv = None
# get biorxiv info
try:
biorxiv = ff_utils.get_metadata(buuid, key=connection.ff_keys, add_on='frame=object')
except Exception as e:
error = 'Problem getting biorxiv - msg: ' + str(e)
else:
if not biorxiv:
error = 'Biorxiv not found!'
if error:
action_log[buuid] = error
continue
# prepare a post/patch for transferring data
existing_fields = {}
fields_to_patch = {}
fields2transfer = [
'lab', 'award', 'categories', 'exp_sets_prod_in_pub',
'exp_sets_used_in_pub', 'published_by'
]
fields2flag = ['static_headers', 'static_content']
post_metadata = {f: biorxiv.get(f) for f in fields2transfer if biorxiv.get(f) is not None}
post_metadata['ID'] = pmid
post_metadata['status'] = 'current'
if 'url' in biorxiv:
post_metadata['aka'] = biorxiv.get('url')
flags = {f: biorxiv.get(f) for f in fields2flag if biorxiv.get(f) is not None}
if flags:
action_log[buuid] = 'Static content to check: ' + str(flags)
# first try to post the pub
pub_upd_res = None
pub = None
try:
pub_upd_res = ff_utils.post_metadata(post_metadata, 'publication', key=connection.ff_keys)
except Exception as e:
error = str(e)
else:
if pub_upd_res.get('status') != 'success':
error = pub_upd_res.get('status')
if error:
if "'code': 422" in error:
# there is a conflict-see if pub is already in portal
pub_search_res = None
error = '' # reset error
try:
search = 'search/?type=Publication&ID={}&frame=object'.format(post_metadata['ID'])
pub_search_res = ff_utils.search_metadata(search, key=connection.ff_keys)
except Exception as e:
error = 'SEARCH failure for {} - msg: {}'.format(pmid, str(e))
else:
if not pub_search_res or len(pub_search_res) != 1:
error = 'SEARCH for {} returned zero or multiple results'.format(pmid)
if error:
action_log[buuid] = error
continue
# a single pub with that pmid is found - try to patch it
pub = pub_search_res[0]
for f, v in post_metadata.items():
if pub.get(f):
if f == 'status' and pub.get(f) != v:
fields_to_patch[f] = v
if f != 'ID':
existing_fields[f] = pub.get(f)
else:
fields_to_patch[f] = v
if fields_to_patch:
try:
puuid = pub.get('uuid')
pub_upd_res = ff_utils.patch_metadata(fields_to_patch, puuid, key=connection.ff_keys)
except Exception as e:
error = 'PATCH failure for {} msg: '.format(pmid, str(e))
else:
if pub_upd_res.get('status') != 'success':
error = 'PATCH failure for {} msg: '.format(pmid, pub_upd_res.get('status'))
if error:
action_log[buuid] = error
continue
else: # all the fields already exist on the item
msg = 'NOTHING TO AUTO PATCH - {} already has all the fields in the biorxiv - WARNING values may be different!'.format(pmid)
action_log[buuid] = {
'message': msg,
'existing': existing_fields,
'possibly_new': post_metadata
}
else:
error = 'POST failure for {} msg: {}'.format(pmid, error)
action_log[buuid] = error
continue
else:
pub = pub_upd_res['@graph'][0]
# here we have successfully posted or patched a pub
# generate a static header with link to new pub and set status of biorxiv to replaced
if not pub:
action_log[buuid] = 'NEW PUB INFO NOT AVAILABLE'
continue
header_alias = "static_header:replaced_biorxiv_{}_by_{}".format(biorxiv.get('uuid'), pmid.replace(':', '_'))
header_name = "static-header.replaced_item_{}".format(biorxiv.get('uuid'))
header_post = {
"body": "This biorxiv set was replaced by [{0}]({2}{1}/).".format(pmid, pub.get('uuid'), connection.ff_server),
"award": biorxiv.get('award'),
"lab": biorxiv.get('lab'),
"name": header_name,
"section_type": "Item Page Header",
"options": {"title_icon": "info", "default_open": True, "filetype": "md", "collapsible": False},
"title": "Note: Replaced Biorxiv",
"status": 'released',
"aliases": [header_alias]
}
huuid = None
try_search = False
try:
header_res = ff_utils.post_metadata(header_post, 'static_section', key=connection.ff_keys)
except Exception as e:
error = 'FAILED TO POST STATIC SECTION {} - msg: '.format(str(e))
try_search = True
else:
try:
huuid = header_res['@graph'][0].get('uuid')
except (KeyError, AttributeError) as e: # likely a conflict - search for existing section by name
try_search = True
if try_search:
try:
search = 'search/?type=UserContent&name={}&frame=object'.format(header_name)
header_search_res = ff_utils.search_metadata(search, key=connection.ff_keys)
except Exception as e:
error = 'SEARCH failure for {} - msg: {}'.format(header_name, str(e))
else:
if header_search_res and len(header_search_res) == 1:
huuid = header_search_res[0].get('uuid')
else:
error = 'PROBLEM WITH STATIC SECTION CREATION - manual intervention needed'
if error:
action_log[buuid] = error
patch_json = {'status': 'replaced'}
if huuid: # need to see if other static content exists and add this one
existing_content = biorxiv.get('static_content', [])
existing_content.append({'content': huuid, 'location': 'header'})
patch_json['static_content'] = existing_content
try:
replace_res = ff_utils.patch_metadata(patch_json, buuid, key=connection.ff_keys)
except Exception as e:
error = 'FAILED TO UPDATE STATUS FOR {} - msg: '.format(buuid, str(e))
else:
if replace_res.get('status') != 'success':
error = 'FAILED TO UPDATE STATUS FOR {} - msg: '.format(buuid, replace_res.get('status'))
# do we want to add a flag to indicate if it was post or patch
if existing_fields:
# report that it was an incomplete patch
msg = 'PARTIAL PATCH'
action_log[buuid] = {
'message': msg,
'existing': existing_fields,
'possibly_new': fields_to_patch,
'all_rxiv_data': post_metadata
}
else:
action_log[buuid] = {'message': 'DATA TRANSFERED TO ' + pmid}
if error:
action_log[buuid].update({'error': error})
action.status = 'DONE'
action.output = action_log
return action
@check_function()
def item_counts_by_type(connection, **kwargs):
def process_counts(count_str):
# specifically formatted for FF health page
ret = {}
split_str = count_str.split()
ret[split_str[0].strip(':')] = int(split_str[1])
ret[split_str[2].strip(':')] = int(split_str[3])
return ret
check = CheckResult(connection, 'item_counts_by_type')
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
# run the check
item_counts = {}
warn_item_counts = {}
req_location = ''.join([connection.ff_server, 'counts?format=json'])
counts_res = ff_utils.authorized_request(req_location, auth=connection.ff_keys)
if counts_res.status_code >= 400:
check.status = 'ERROR'
check.description = 'Error (bad status code %s) connecting to the counts endpoint at: %s.' % (counts_res.status_code, req_location)
return check
counts_json = json.loads(counts_res.text)
for index in counts_json['db_es_compare']:
counts = process_counts(counts_json['db_es_compare'][index])
item_counts[index] = counts
if counts['DB'] != counts['ES']:
warn_item_counts[index] = counts
# add ALL for total counts
total_counts = process_counts(counts_json['db_es_total'])
item_counts['ALL'] = total_counts
# set fields, store result
if not item_counts:
check.status = 'FAIL'
check.summary = check.description = 'Error on fourfront health page'
elif warn_item_counts:
check.status = 'WARN'
check.summary = check.description = 'DB and ES item counts are not equal'
check.brief_output = warn_item_counts
else:
check.status = 'PASS'
check.summary = check.description = 'DB and ES item counts are equal'
check.full_output = item_counts
return check
@check_function()
def change_in_item_counts(connection, **kwargs):
# use this check to get the comparison
check = CheckResult(connection, 'change_in_item_counts')
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
counts_check = CheckResult(connection, 'item_counts_by_type')
latest_check = counts_check.get_primary_result()
# get_item_counts run closest to 10 mins
prior_check = counts_check.get_closest_result(diff_hours=24)
if not latest_check.get('full_output') or not prior_check.get('full_output'):
check.status = 'ERROR'
check.description = 'There are no counts_check results to run this check with.'
return check
diff_counts = {}
# drill into full_output
latest = latest_check['full_output']
prior = prior_check['full_output']
# get any keys that are in prior but not latest
prior_unique = list(set(prior.keys()) - set(latest.keys()))
for index in latest:
if index == 'ALL':
continue
if index not in prior:
diff_counts[index] = {'DB': latest[index]['DB'], 'ES': 0}
else:
diff_DB = latest[index]['DB'] - prior[index]['DB']
if diff_DB != 0:
diff_counts[index] = {'DB': diff_DB, 'ES': 0}
for index in prior_unique:
diff_counts[index] = {'DB': -1 * prior[index]['DB'], 'ES': 0}
# now do a metadata search to make sure they match
# date_created endpoints for the FF search
# XXX: We should revisit if we really think this search is necessary. - will 3-26-2020
to_date = datetime.datetime.strptime(latest_check['uuid'], "%Y-%m-%dT%H:%M:%S.%f").strftime('%Y-%m-%d+%H:%M')
from_date = datetime.datetime.strptime(prior_check['uuid'], "%Y-%m-%dT%H:%M:%S.%f").strftime('%Y-%m-%d+%H:%M')
# tracking items and ontology terms must be explicitly searched for
search_query = ''.join(['search/?type=Item&type=OntologyTerm&type=TrackingItem',
'&frame=object&date_created.from=',
from_date, '&date_created.to=', to_date])
search_resp = ff_utils.search_metadata(search_query, key=connection.ff_keys)
# add deleted/replaced items
search_query += '&status=deleted&status=replaced'
search_resp.extend(ff_utils.search_metadata(search_query, key=connection.ff_keys))
for res in search_resp:
# Stick with given type name in CamelCase since this is now what we get on the counts page
_type = res['@type'][0]
_entry = diff_counts.get(_type)
if not _entry:
diff_counts[_type] = _entry = {'DB': 0, 'ES': 0}
if _type in diff_counts:
_entry['ES'] += 1
check.ff_link = ''.join([connection.ff_server, 'search/?type=Item&',
'type=OntologyTerm&type=TrackingItem&date_created.from=',
from_date, '&date_created.to=', to_date])
check.brief_output = diff_counts
# total created items from diff counts (exclude any negative counts)
total_counts_db = sum([diff_counts[coll]['DB'] for coll in diff_counts if diff_counts[coll]['DB'] >= 0])
# see if we have negative counts
# allow negative counts, but make note of, for the following types
purged_types = ['TrackingItem', 'HiglassViewConfig']
negative_types = [tp for tp in diff_counts if (diff_counts[tp]['DB'] < 0 and tp not in purged_types)]
inconsistent_types = [tp for tp in diff_counts if (diff_counts[tp]['DB'] != diff_counts[tp]['ES'] and tp not in purged_types)]
if negative_types:
negative_str = ', '.join(negative_types)
check.status = 'FAIL'
check.summary = 'DB counts decreased in the past day for %s' % negative_str
check.description = ('Positive numbers represent an increase in counts. '
'Some DB counts have decreased!')
elif inconsistent_types:
check.status = 'WARN'
check.summary = 'Change in DB counts does not match search result for new items'
check.description = ('Positive numbers represent an increase in counts. '
'The change in counts does not match search result for new items.')
else:
check.status = 'PASS'
check.summary = 'There are %s new items in the past day' % total_counts_db
check.description = check.summary + '. Positive numbers represent an increase in counts.'
check.description += ' Excluded types: %s' % ', '.join(purged_types)
return check
@check_function(file_type=None, status=None, file_format=None, search_add_on=None)
def identify_files_without_filesize(connection, **kwargs):
check = CheckResult(connection, 'identify_files_without_filesize')
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
# must set this to be the function name of the action
check.action = "patch_file_size"
check.allow_action = True
default_filetype = 'File'
default_stati = 'released%20to%20project&status=released&status=uploaded&status=pre-release'
filetype = kwargs.get('file_type') or default_filetype
stati = 'status=' + (kwargs.get('status') or default_stati)
search_query = 'search/?type={}&{}&frame=object&file_size=No value'.format(filetype, stati)
ff = kwargs.get('file_format')
if ff is not None:
ff = '&file_format.file_format=' + ff
search_query += ff
addon = kwargs.get('search_add_on')
if addon is not None:
if not addon.startswith('&'):
addon = '&' + addon
search_query += addon
problem_files = []
file_hits = ff_utils.search_metadata(search_query, key=connection.ff_keys, page_limit=200)
if not file_hits:
check.allow_action = False
check.summary = 'All files have file size'
check.description = 'All files have file size'
check.status = 'PASS'
return check
for hit in file_hits:
hit_dict = {
'accession': hit.get('accession'),
'uuid': hit.get('uuid'),
'@type': hit.get('@type'),
'upload_key': hit.get('upload_key')
}
problem_files.append(hit_dict)
check.brief_output = '{} files with no file size'.format(len(problem_files))
check.full_output = problem_files
check.status = 'WARN'
check.summary = 'File metadata found without file_size'
status_str = 'pre-release/released/released to project/uploaded'
if kwargs.get('status'):
status_str = kwargs.get('status')
type_str = ''
if kwargs.get('file_type'):
type_str = kwargs.get('file_type') + ' '
ff_str = ''
if kwargs.get('file_format'):
ff_str = kwargs.get('file_format') + ' '
check.description = "{cnt} {type}{ff}files that are {st} don't have file_size.".format(
cnt=len(problem_files), type=type_str, st=status_str, ff=ff_str)
check.action_message = "Will attempt to patch file_size for %s files." % str(len(problem_files))
check.allow_action = True # allows the action to be run
return check
@action_function()
def patch_file_size(connection, **kwargs):
action = ActionResult(connection, 'patch_file_size')
action_logs = {'s3_file_not_found': [], 'patch_failure': [], 'patch_success': []}
# get the associated identify_files_without_filesize run result
filesize_check_result = action.get_associated_check_result(kwargs)
for hit in filesize_check_result.get('full_output', []):
bucket = connection.ff_s3.outfile_bucket if 'FileProcessed' in hit['@type'] else connection.ff_s3.raw_file_bucket
head_info = connection.ff_s3.does_key_exist(hit['upload_key'], bucket)
if not head_info:
action_logs['s3_file_not_found'].append(hit['accession'])
else:
patch_data = {'file_size': head_info['ContentLength']}
try:
ff_utils.patch_metadata(patch_data, obj_id=hit['uuid'], key=connection.ff_keys)
except Exception as e:
acc_and_error = '\n'.join([hit['accession'], str(e)])
action_logs['patch_failure'].append(acc_and_error)
else:
action_logs['patch_success'].append(hit['accession'])
action.status = 'DONE'
action.output = action_logs
return action
@check_function(reset=False)
def new_or_updated_items(connection, **kwargs):
''' Currently restricted to experiment sets and experiments
search query can be modified if desired
keeps a running total of number of new/changed items from
when the last time the 'reset' action was run
'''
class DictQuery(dict):
def get(self, path, default=None):
keys = path.split(".")
val = None
for key in keys:
if val:
if isinstance(val, list):
val = [v.get(key, default) if v else None for v in val]
else:
val = val.get(key, default)
else:
val = dict.get(self, key, default)
if not val:
break
return val
seen = {}
dcic = {}
def get_non_dcic_user(user, seen, dcic):
dciclab = "4DN DCIC, HMS"
try:
user = user.get('uuid')
except AttributeError:
pass
if user in dcic:
return None
if user in seen and user not in dcic:
return seen.get(user)
user_item = ff_utils.get_metadata(user, key=connection.ff_keys)
seen[user] = user_item.get('display_title')
if user_item.get('lab').get('display_title') == dciclab:
dcic[user] = True
return None
return user_item.get('display_title')
check = CheckResult(connection, 'new_or_updated_items')
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
rundate = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M')
last_result = check.get_latest_result()
if last_result is None or last_result.get('status') == 'ERROR' or kwargs.get('reset') is True:
# initial set up when run on each environment - should produce 0 counts
# maybe also use for reset?
check.brief_output = {'reset_date': rundate}
check.full_output = {'reset_date': rundate}
check.status = 'PASS'
check.summary = 'Counters reset to 0'
return check
days_since = 7
last_check_date = last_result.get('uuid')
last_reset_date = last_result.get('brief_output').get('reset_date')
check.brief_output = {'reset_date': last_reset_date}
check.full_output = {'reset_date': last_reset_date}
days_ago = (datetime.datetime.utcnow() - datetime.timedelta(days=days_since)).strftime('%Y-%m-%dT%H:%M')
label2date = {
'since last check': last_check_date,
'since last reset': last_reset_date,
'in the last %d days' % days_since: days_ago
}
earliest_date = min([last_check_date, last_reset_date, days_ago])
search = 'search/?status=in review by lab&type={type}'
brief_output = {}
full_output = {}
warn = False
# fields used for reporting
item_flds = ['accession', 'lab.uuid', 'lab.display_title', 'submitted_by.uuid',
'last_modified.modified_by.uuid']
# can add or remove item types here
types2chk = ['ExperimentSet', 'Experiment']
for itype in types2chk:
chk_query = search.format(type=itype)
item_results = ff_utils.search_metadata(chk_query, key=connection.ff_keys, page_limit=200)
for item in item_results:
submitter = None
modifier = None
created = item.get('date_created')
modified = None
if item.get('last_modified', None) is not None:
modified = item.get('last_modified').get('date_modified')
# check to see if modified and created are essentially the same and if so ignore modified
minute_created = ':'.join(created.split(':')[0:2])
minute_modified = ':'.join(modified.split(':')[0:2])
if minute_created == minute_modified:
modified = None
if created and created > earliest_date:
submitter = get_non_dcic_user(item.get('submitted_by'), seen, dcic)
if modified and modified > earliest_date:
modifier = get_non_dcic_user(item.get('last_modified').get('modified_by'), seen, dcic)
# now we're ready to see which bucket item goes into
if submitter or modifier:
# we've got an item newer or modified since earliest date
item_info = {fld: DictQuery(item).get(fld) for fld in item_flds}
labname = item_info.get('lab.display_title')
labuuid = item_info.get('lab.uuid')
if submitter:
brief_output.setdefault(submitter, {}).setdefault(labname, {}).setdefault(itype, {})
full_output.setdefault(submitter, {}).setdefault(labname, {}).setdefault(itype, {})
for label, date in label2date.items():
newlabel = 'New ' + label
brief_output[submitter][labname][itype].setdefault(newlabel, 0)
full_output[submitter][labname][itype].setdefault(newlabel, 'None')
if created > date:
warn = True
# newlabel = 'New ' + label
# brief_output[submitter][labname][itype].setdefault(newlabel, 0)
brief_output[submitter][labname][itype][newlabel] += 1
# full_output[submitter][labname][itype].setdefault(newlabel, {'search': '', 'accessions': []})
if full_output[submitter][labname][itype][newlabel] == 'None' or not full_output[submitter][labname][itype][newlabel].get('search'):
searchdate, _ = date.split('T')
newsearch = '{server}/search/?q=date_created:[{date} TO *]&type={itype}&lab.uuid={lab}&submitted_by.uuid={sub}&status=in review by lab'.format(
server=connection.ff_server, date=searchdate, itype=itype, lab=labuuid, sub=item_info.get('submitted_by.uuid')
)
full_output[submitter][labname][itype][newlabel] = {'search': newsearch}
full_output[submitter][labname][itype][newlabel].setdefault('accessions', []).append(item_info['accession'])
if modifier:
brief_output.setdefault(modifier, {}).setdefault(labname, {}).setdefault(itype, {})
full_output.setdefault(modifier, {}).setdefault(labname, {}).setdefault(itype, {})
for label, date in label2date.items():
modlabel = 'Modified ' + label
brief_output[modifier][labname][itype].setdefault(modlabel, 0)
full_output[modifier][labname][itype].setdefault(modlabel, 'None')
if modified > date:
warn = True
# modlabel = 'Modified ' + label
# brief_output[modifier][labname][itype].setdefault(modlabel, 0)
brief_output[modifier][labname][itype][modlabel] += 1
# full_output[modifier][labname][itype].setdefault(modlabel, {'search': '', 'accessions': []})
if full_output[modifier][labname][itype][modlabel] == 'None' or not full_output[modifier][labname][itype][modlabel].get('search'):
searchdate, _ = date.split('T')
modsearch = '{server}search/?q=last_modified.date_modified:[{date} TO *]&type={itype}&lab.uuid={lab}&last_modified.modified_by.uuid={mod}status=in review by lab'.format(
server=connection.ff_server, date=searchdate, itype=itype, lab=labuuid, mod=item_info.get('last_modified.modified_by.uuid')
)
full_output[modifier][labname][itype][modlabel] = {'search': modsearch}
full_output[modifier][labname][itype][modlabel].setdefault('accessions', []).append(item_info['accession'])
check.brief_output.update(brief_output)
check.full_output.update(full_output)
if warn is True:
check.status = 'WARN'
check.summary = 'In review Experiments or ExperimentSets submitted or modified'
description = "Experiments or ExperimentSets with status='in review by lab' have been submitted or modified by non-DCIC users since last reset or in the past %d days." % days_since
check.description = description
else:
check.status = 'PASS'
check.summary = 'No newly submitted or modified Experiments or ExperimentSets since last reset'
return check
@check_function()
def clean_up_webdev_wfrs(connection, **kwargs):
def patch_wfr_and_log(wfr, full_output):
uuid = wfr['uuid']
patch_json = {'uuid': uuid, 'status': 'deleted'}
# no need to patch again
if uuid in full_output['success']:
return
try:
ff_utils.patch_metadata(patch_json, uuid, key=connection.ff_keys)
except Exception as exc:
# log something about str(exc)
full_output['failure'].append('%s. %s' % (uuid, str(exc)))
else:
# successful patch
full_output['success'].append(uuid)
check = CheckResult(connection, 'clean_up_webdev_wfrs')
check.full_output = {'success': [], 'failure': []}
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
# input for test pseudo hi-c-processing-bam
response = ff_utils.get_metadata('68f38e45-8c66-41e2-99ab-b0b2fcd20d45',
key=connection.ff_keys)
wfrlist = response['workflow_run_inputs']
for entry in wfrlist:
patch_wfr_and_log(entry, check.full_output)
wfrlist = response['workflow_run_outputs']
for entry in wfrlist:
patch_wfr_and_log(entry, check.full_output)
# input for test md5 and bwa-mem
response = ff_utils.get_metadata('f4864029-a8ad-4bb8-93e7-5108f462ccaa',
key=connection.ff_keys)
wfrlist = response['workflow_run_inputs']
for entry in wfrlist:
patch_wfr_and_log(entry, check.full_output)
# input for test md5 and bwa-mem
response = ff_utils.get_metadata('f4864029-a8ad-4bb8-93e7-5108f462ccaa',
key=connection.ff_keys)
wfrlist = response['workflow_run_inputs']
for entry in wfrlist:
patch_wfr_and_log(entry, check.full_output)
if check.full_output['failure']:
check.status = 'WARN'
check.summary = 'One or more WFR patches failed'
else:
check.status = 'PASS'
if check.full_output['success']:
check.summary = 'All WFR patches successful'
else:
check.summary = 'No WFR patches run'
return check
@check_function()
def validate_entrez_geneids(connection, **kwargs):
''' query ncbi to see if geneids are valid
'''
check = CheckResult(connection, 'validate_entrez_geneids')
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
problems = {}
timeouts = 0
search_query = 'search/?type=Gene&limit=all&field=geneid'
genes = ff_utils.search_metadata(search_query, key=connection.ff_keys)
if not genes:
check.status = "FAIL"
check.description = "Could not retrieve gene records from fourfront"
return check
geneids = [g.get('geneid') for g in genes]
query = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&id={id}"
for gid in geneids:
if timeouts > 5:
check.status = "FAIL"
check.description = "Too many ncbi timeouts. Maybe they're down."
return check
gquery = query.format(id=gid)
# make 3 attempts to query gene at ncbi
for count in range(3):
resp = requests.get(gquery)
if resp.status_code == 200:
break
if resp.status_code == 429:
time.sleep(0.334)
continue
if count == 2:
timeouts += 1
problems[gid] = 'ncbi timeout'
try:
rtxt = resp.text
except AttributeError:
problems[gid] = 'empty response'
else:
if rtxt.startswith('Error'):
problems[gid] = 'not a valid geneid'
if problems:
check.summary = "{} problematic entrez gene ids.".format(len(problems))
check.brief_output = problems
check.description = "Problematic Gene IDs found"
check.status = "WARN"
else:
check.status = "PASS"
check.description = "GENE IDs are all valid"
return check
@check_function(scope='all')
def users_with_pending_lab(connection, **kwargs):
"""Define comma seperated emails in scope
if you want to work on a subset of all the results"""
check = CheckResult(connection, 'users_with_pending_lab')
# add random wait
wait = round(random.uniform(0.1, random_wait), 1)
time.sleep(wait)
check.action = 'finalize_user_pending_labs'
check.full_output = []
check.status = 'PASS'
cached_items = {} # store labs/PIs for performance
mismatch_users = []
# do not look for deleted/replaced users
scope = kwargs.get('scope')
search_q = '/search/?type=User&pending_lab!=No+value&frame=object'
# want to see all results or a subset defined by the scope
if scope == 'all':
pass
else:
emails = [mail.strip() for mail in scope.split(',')]
for an_email in emails:
search_q += '&email=' + an_email
search_res = ff_utils.search_metadata(search_q, key=connection.ff_keys)
for res in search_res:
user_fields = ['uuid', 'email', 'pending_lab', 'lab', 'title', 'job_title']
user_append = {k: res.get(k) for k in user_fields}
check.full_output.append(user_append)
# Fail if we have a pending lab and lab that do not match
if user_append['lab'] and user_append['pending_lab'] != user_append['lab']:
check.status = 'FAIL'
mismatch_users.append(user_append['uuid'])
continue
# cache the lab and PI contact info
if user_append['pending_lab'] not in cached_items:
to_cache = {}
pending_meta = ff_utils.get_metadata(user_append['pending_lab'], key=connection.ff_keys,