-
Notifications
You must be signed in to change notification settings - Fork 0
/
CdrLongReports.py
2142 lines (1872 loc) · 82.2 KB
/
CdrLongReports.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
# ----------------------------------------------------------------------
# CDR Reports too long to be run directly from CGI.
#
# BZIssue::1264 - Different filter set for OrgProtocolReview report
# BZIssue::1319 - Modifications to glossary term search report
# BZIssue::1337 - Modified displayed string; formatting changes
# BZIssue::1702
# BZIssue::3134 - Modifications to Protocol Processing Status report
# BZIssue::3627 - Modifications for OSP report
# BZIssue::4626 - Added class ProtocolOwnershipTransfer
# BZIssue::4711 - Adding GrantNo column to report output
# BZIssue::5086 - Changes to the Transferred Protocols Report (Issue 4626)
# BZIssue::5123 - Audio Pronunciation Tracking Report
# BZIssue::5237 - Report for publication document counts fails on
# non-production server
# BZIssue::5244 - URL Check report not working
# JIRA::OCECDR-4183 - support searching Spanish summaries
# JIRA::OCECDR-4216 and JIRA::OCECDR-4219 - URL check mods
# Extensive reorganization and cleanup January 2017
# JIRA::OCECDR-4284 - Fix Glossary Term and Variant Search report
# JIRA::OCECDR-4547 - Add section title for summaries
# ----------------------------------------------------------------------
# Standard library modules
import argparse
import datetime
from functools import cached_property
import re
import socket
import sys
import urllib.parse
# Third-party packages
import lxml.etree as etree
import requests
# Local modules.
import cdr
import cdrbatch
import cdrcgi
from cdrapi import db
from cdrapi.docs import Doc
from cdrapi.settings import Tier
from cdrapi.users import Session
class BatchReport:
"""
Base class for individual long-running reports.
Class attributes:
B - lxml module for building HTML pages
SUMMARY_LANGUAGE - path to element identifying language of a PDQ summary
SUMMARY_AUDIENCE - path to element identifying language of a PDQ summary
SUMMARY_METADATA - path to metadata block in a PDQ summary document
GTC - top level element of a CDR glossary term concept document
GTC_LANGUAGES - ISO language values indexed by display name
GTC_RELATED_REF - path to link element in a GlossaryTermConcept doc
GTC_USE_WITH - path to language attribute for a GTC link element
EMAILFROM - sender for email messages sent for the reports
REPORTS_BASE - directory where reports are store
CMD - path to this script
STAMP - YYYYMMDDHHMMSS timestamp string
LOGNAME - default name for the log (".log" will be added to the filename)
LOGLEVEL - default verbosity for logging
TIER - where we're running
Instance attributes:
logger - object for writing log entries (standard library logging model)
start - datetime object for processing initiation
elapsed - number of seconds since program start
max_time - optional ceiling on the amount of time the report should run
throttle - whether it is possible to stop the report before completion
cursor - the database cursor provided by the batch job's object
name - the name the report job type is know by
title - the string used for the HTML head/title element (optional)
banner - string displayed at the top of the report (optional)
format - one of "html" or "excel"
debug - if True, do extra logging
queued - if True, the job is queued in the database (the usual case)
verbose - if True, display progress on the console (for testing)
"""
import lxml.html.builder as B
TIER = Tier()
SUMMARY_LANGUAGE = "/Summary/SummaryMetaData/SummaryLanguage"
SUMMARY_AUDIENCE = "/Summary/SummaryMetaData/SummaryAudience"
SUMMARY_BOARD = "/Summary/SummaryMetaData/PDQBoard/Board/@cdr:ref"
SUMMARY_METADATA = "/Summary/SummaryMetaData"
GTC_LANGUAGES = {"English": "en", "Spanish": "es"}
DEFINITIONS = {"en": "TermDefinition", "es": "TranslatedTermDefinition"}
GTC = "GlossaryTermConcept"
GTC_RELATED_REF = "/%s/RelatedInformation/RelatedExternalRef" % GTC
GTC_USE_WITH = "%s/@UseWith" % GTC_RELATED_REF
EMAILFROM = 'cdr@%s' % cdr.CBIIT_NAMES[1]
REPORTS_BASE = cdr.BASEDIR + "/reports"
CMD = "lib/Python/CdrLongReports.py"
STAMP = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
LOGNAME = "reports"
LOGLEVEL = "info"
def __init__(self, job, name, title=None, banner=None):
"""
Collect the common parameters for the job.
"""
self.start = datetime.datetime.now()
self.debug = job.getParm("debug") == "True"
self.logger = self.get_logger()
self.job = job
self.elapsed = 0.0
self.throttle = job.getParm("throttle") == "True"
self.max_time = self.int_parm("max_time")
self.cursor = job.getCursor()
self.name = name
self.title = title or name
self.banner = banner or self.title
self.format = job.getParm("format") or "html"
self.queued = job.getJobId() and True or False
self.verbose = job.getParm("verbose") == "True"
def run(self):
"""
Create the report and let the user know where it is.
"""
self.job.setProgressMsg("Report started")
self.logger.info("Starting %s report", self.name)
report_filename = self.write_report()
self.notify_users(report_filename)
self.logger.info("Completed %s report", self.name)
def write_report(self):
"""
Create and save the report and return the base file name.
"""
name = "%s-%d" % (self.name.replace(" ", ""), self.job.getJobId())
if self.format == "html":
report = self.create_html_report()
name += ".html"
path = "%s/%s" % (self.REPORTS_BASE, name)
open(path, "wb").write(report.encode("utf-8"))
else:
workbook = self.create_excel_report()
name += ".xlsx"
path = "%s/%s" % (self.REPORTS_BASE, name)
workbook.save(path)
self.logger.info("Saved %s", path)
path = path.replace("/", "\\")
command = f"{cdr.FIX_PERMISSIONS} {path}"
cdr.run_command(command)
self.logger.info("Adjusted report permissions")
return name
def create_report_url(self, name):
"""
Create the link to the CGI script which serves up the report.
"""
base = cdr.CBIIT_NAMES[2]
if self.format == "html":
return "%s/CdrReports/%s" % (base, name)
else:
base += cdrcgi.BASE
return "%s/GetReportWorkbook.py?name=%s" % (base, name)
def create_html_report(self):
"""
Assemble and serialize the HTML document for the report.
"""
report = self.B.HTML(self.head(), self.body())
opts = {
"encoding": "unicode",
"pretty_print": True,
"method": "html",
"doctype": "<!DOCTYPE html>"
}
return etree.tostring(report, **opts)
def head(self):
"""
Assemble the head block element for the HTML report.
Can be overridden by the derived classes, but that wouldn't
normally be necessary.
"""
return self.B.HEAD(
self.B.META(charset="utf-8"),
self.B.TITLE("%s Report" % self.title),
self.B.STYLE(self.style())
)
def body(self):
"""
Start the HTML body block and let the derived class fill it in.
"""
body = self.B.BODY(
self.B.H1(self.banner),
self.B.H2(str(datetime.date.today()))
)
return self.fill_body(body)
def fill_body(self, body):
"""
Add the payload content for the report.
Will be overridden by the derived classes. This version results
in an empty report.
"""
return body
def create_excel_report(self):
"""
Create the Excel styles object and workbook and let the caller
add the worksheets to it.
"""
self.excel = cdrcgi.Excel(wrap=True)
self.add_sheets()
return self.excel.book
def add_sheets(self):
"""
Derived classes implement this to add the report's worksheets.
"""
pass
def get_logger(self):
"""
Create a logging object.
Separated out so derived classes can completely customize this.
"""
level = self.debug and "debug" or self.LOGLEVEL
return cdr.Logging.get_logger(self.LOGNAME, level=level)
def notify_users(self, filename):
"""
Send a link to the new report in an email message and post it
to the database.
"""
url = self.create_report_url(filename)
self.logger.info("url: %s", url)
args = self.TIER.name, self.name
subject = "[CDR %s] Report results - %s Report" % args
args = self.name, url
body = "The %s report you requested can be viewed at\n%s\n" % args
self.send_mail(subject, body)
link = "<a href='%s'><u>%s</u></a>" % (url, url)
message = "%s<br>Report available at %s" % (self.activity(), link)
self.job.setProgressMsg(message)
self.job.setStatus(cdrbatch.ST_COMPLETED)
return url
def activity(self):
"""
Create the string that summarizes what was done to create the report.
This is generally displayed in a different font at the bottom of
the report. Typically this will be overriden for an individual
report. For example
"Processed 123 urls for 314 link elements in 2.09 seconds."
"""
elapsed = (datetime.datetime.now() - self.start).total_seconds()
return "processing time: %s seconds" % elapsed
def style(self):
"""
Create the CSS rules for an HTML report.
Derived classes can provide customized style rules for the individual
reports by overriding this method, or (more frequently) by implementing
its own version of selectors (see below).
"""
selectors = self.selectors()
lines = []
for selector in sorted(selectors):
rules = selectors[selector]
rules = [("%s: %s;" % rule) for rule in list(rules.items())]
lines.append("%s { %s }" % (selector, " ".join(rules)))
css = "\n".join(lines)
if self.verbose:
sys.stderr.write("<style>\n%s\n</style>\n" % css)
return css
def selectors(self):
"""
Provide a dictionary of CSS rules indexed by selectors.
This will be serialized for inclusion in the head block
of the HTML document for the report by the style() method
above. A derived class would typically provide its own
version of this method, invoking this base class version
and then making specific modifications before returning
it to the caller.
"""
return {
"*": {"font-family": "Arial, sans-serif"},
".right": {"text-align": "right"},
".left": {"text-align": "left"},
".center": {"text-align": "center"},
".red": {"color": "red"},
".strong": {"font-weight": "bold"},
".error": {"color": "darkred"},
"p.processing": {
"color": "green",
"font-style": "italic",
"font-size": "9pt"
},
"h1, h2": {"text-align": "center", "font-family": "serif"},
"h1": {"font-size": "16pt"},
"h2": {"font-size": "13pt"},
"table": {"border-collapse": "collapse"},
"th, td": {
"font-family": "Arial",
"border": "1px solid grey",
"padding": "2px",
"font-size": "10pt"
}
}
def quitting_time(self):
"""
Tell the caller whether report processing should finish early.
This is provided to allow the user to run a report in a quick
sample version, usually for testing or a preview of the full
report (for example, by setting a ceiling for run time).
Derived classes can customize the method to replace or
augment the logic provided here.
"""
self.elapsed = (datetime.datetime.now() - self.start).total_seconds()
if not self.throttle:
return False
if self.max_time and self.elapsed > self.max_time:
if self.verbose:
sys.stderr.write("%s > %s\n" % (self.elapsed, self.max_time))
return True
def int_parm(self, name):
"""
Pull an integer value from the job's parameter set in a safe way.
"""
try:
return int(self.job.getParm(name))
except Exception:
return 0
def get_boards(self):
"""
Pull PDQ board IDs from the parameter set as a sequence of integers.
"""
boards = self.job.getParm("boards")
if not boards:
return []
if not isinstance(boards, (list, tuple)):
boards = [boards]
if "all" in boards:
return []
return [int(board) for board in boards]
def get_doc_type(self, doc_id):
"""
Find the CDR document type for a specific document.
"""
query = db.Query("doc_type t", "t.name")
query.join("document d", "d.doc_type = t.id")
query.where(query.Condition("d.id", doc_id))
rows = query.execute(self.cursor).fetchall()
return rows[0][0] if rows else None
def log_query(self, query):
"""
Optionally (depending on whether debugging is turned on) log
the SQL query and its parameters (if any).
"""
self.logger.debug("SQL query\n%s", query)
parms = query.parms()
if parms:
self.logger.debug("query parameters: %s", query.parms())
def send_mail(self, subject, message):
"""
Send mail to the recipients specified for the job.
"""
email = self.job.getEmail()
if not email:
self.logger.error("No email address provided")
else:
self.logger.info("Sending email report to %s", email)
recips = email.replace(',', ' ').replace(';', ' ').split()
opts = dict(subject=subject, body=message)
cdr.EmailMessage(self.EMAILFROM, recips, **opts).send()
@classmethod
def summary_board_subquery(cls, boards, language=None):
"""
Assemble a database query which can be used to narrow the set
of PDQ summaries by PDQ board(s) and optionally by language.
The logic is complicated by the fact that the link to the
board responsible for a Spanish summary is not stored in
that summary's document, but is instead stored in the document
for the English summary of which it is a translation. So we
have to use two separate queries for finding a board's summaries
in English and in Spanish. To find summaries for a given board
(or set of boards) we use the SQL UNION of the two queries.
Pass:
boards - sequence of integers for PDQ board IDs; cannot be empty
language - "English" or "Spanish" (optional)
Return:
db.Query object
"""
# Double conversion ensures we have integers, guarding against attacks.
boards = ", ".join([str(int(board)) for board in boards])
if not language or language == "English":
english_query = db.Query("query_term", "doc_id")
english_query.where(f"path = '{cls.SUMMARY_BOARD}'")
english_query.where(f"int_val in ({boards})")
if language:
return english_query
if not language or language == "Spanish":
spanish_query = db.Query("query_term s", "s.doc_id")
spanish_query.join("query_term e", "e.doc_id = s.int_val")
spanish_query.where("s.path = '/Summary/TranslationOf/@cdr:ref'")
spanish_query.where(f"e.path = '{cls.SUMMARY_BOARD}'")
spanish_query.where(f"e.int_val in ({boards})")
if language:
return spanish_query
return english_query.union(spanish_query)
@classmethod
def test_filename_base(cls):
"""
Generate the default filename base (without extension) for testing.
"""
# pylint: disable=no-member
return "%s-%s" % (cls.NAME.replace(" ", "_"), cls.STAMP)
@classmethod
def arg_parser(cls, suffix=".html"):
"""
Create a parser for command-line options of the test harness.
"""
default_filename = cls.test_filename_base() + suffix
# pylint: disable=no-member
parser = argparse.ArgumentParser(
usage='CdrLongReports.py "%s" [options]' % cls.NAME,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Performs a %s test report." % cls.NAME
)
# pylint: enable=no-member
parser.add_argument("--full-run", action="store_false",
dest="throttle",
help="don't throttle the amount of time "
"or processing performed for the test run")
parser.add_argument("--max-time", type=int, default=10,
help="if throttling is on, stop after MAX_TIME "
"seconds")
parser.add_argument("--debug", "-d", action="store_true",
help="write additional logging information")
parser.add_argument("--verbose", "-v", action="store_true",
help="write details to the console for testing")
parser.add_argument("--filename", default=default_filename,
help="where to save test report")
return parser
@classmethod
def run_test(cls, arg_parser, format="html"):
"""
Called from test_harness for an individual report type to run
a report from the command line and save the results.
Suppress false positives from pylint, which doesn't understand
that only instances of the derived classes are created, and the
derived classes are suppliers of some of the arguments passed
to the base class constructor.
"""
import logging
# pylint: disable=no-member
logger = logging.getLogger(cls.NAME)
logger.info("Starting %s report", cls.NAME)
# pylint: enable=no-member
args = vars(arg_parser.parse_args())
cls.announce_test(args)
filename = args.pop("filename")
args = list(args.items())
# pylint: disable-next=no-member
job = cdrbatch.CdrBatch(jobName=cls.NAME, command=cls.CMD, args=args)
if format == "html":
# pylint: disable-next=no-value-for-parameter
report = cls(job).create_html_report()
open(filename, "wb").write(report.encode("utf-8"))
else:
# pylint: disable-next=no-value-for-parameter
cls(job).create_excel_report().save(filename)
sys.stderr.write("\nsaved %s\n\n" % filename)
logger.info("Saved %s", filename)
# pylint: disable-next=no-member
logger.info("Completed %s report", cls.NAME)
@classmethod
def announce_test(cls, args):
sys.stderr.write("\n%s\n\n" % ("-" * 78))
# pylint: disable-next=no-member
sys.stderr.write("Running %s test report\n\n" % cls.NAME)
if args:
sys.stderr.write("Run-time options:\n")
for name in sorted(args):
sys.stderr.write("%25s: %s\n" % (name, args[name]))
sys.stderr.write("\n")
class URLChecker(BatchReport):
"""
Base class for two reports on links with problems.
"""
def __init__(self, job, name, title=None, banner=None):
"""
Collect the options stored for this report job.
"""
BatchReport.__init__(self, job, name, title, banner)
self.doc_type = job.getParm("doc_type") or "Summary"
self.doc_id = job.getParm("doc_id")
if self.doc_id:
self.doc_type = self.get_doc_type(self.doc_id)
self.boards = self.get_boards()
self.max_urls = self.int_parm("max_urls")
self.connect_timeout = self.int_parm("connect_timeout") or 5
self.read_timeout = self.int_parm("read_timeout") or 10
self.check_certs = job.getParm("check_certs") == "True"
self.audience = job.getParm("audience")
self.language = job.getParm("language")
self.show_redirects = False
if not self.check_certs:
self.suppress_cert_warning()
if self.verbose:
sys.stderr.write("throttle is %s\n" % self.throttle)
sys.stderr.write("max_urls is %s\n" % self.max_urls)
sys.stderr.write("max_time is %s\n" % self.max_time)
def table(self):
"""
Fetch the data rows and insert them into the report's table.
As a side effect, the string describing the processing performed
to generate the report is assembled and stored in the report
object here.
"""
self.links_tested = 0
rows = self.get_report_rows()
elapsed = (datetime.datetime.now() - self.start).total_seconds()
self.message = ("Checked %d urls for %d of %d links in %s seconds." %
(len(self.pages), self.links_tested,
len(self.links), elapsed))
# pylint: disable=no-member
headers = [self.B.TH(header) for header in self.COLUMN_HEADERS]
table_class = self.B.CLASS(self.TABLE_CLASS)
# pylint: enable=no-member
return self.B.TABLE(table_class, self.B.TR(*headers), *rows)
def get_report_rows(self):
"""
Select the links to be checked and put the ones with problems in the
rows for the report's table.
"""
self.Page.REQUEST_OPTS = {
"timeout": (self.connect_timeout, self.read_timeout),
"verify": self.check_certs,
"allow_redirects": not self.show_redirects
}
try:
self.links = self.find_links() # pylint: disable=no-member
except Exception as e:
self.logger.exception("fetching external links for report")
self.job.fail("Fetching external links for report: %s" % e)
if self.verbose:
sys.stderr.write("%d links fetched\n" % len(self.links))
self.pages = {}
rows = []
for link in self.links:
page = self.pages.get(link.url)
if not page:
if self.quitting_time():
break
page = self.pages[link.url] = self.Page(self, link.url)
if self.verbose:
message_strings = self.elapsed, repr(link.url)
sys.stderr.write("%s -- checked %s\n" % message_strings)
if link.in_scope(page):
rows.append(link.make_row(page))
self.links_tested += 1
if self.queued:
message_strings = self.links_tested, len(self.links)
message = "Checked %d of %d links" % message_strings
self.job.setProgressMsg(message)
return rows
def quitting_time(self):
"""
Determine whether we can quit early.
The base class implementation is invoked first to see if we've
passed the time threshold. We also check to see if we have already
processed the maximum number of URLs the user wants us to check.
"""
if not self.throttle:
return False
if BatchReport.quitting_time(self):
return True
if self.max_urls and len(self.pages) >= self.max_urls:
if self.verbose:
sys.stderr.write("%s >= %s\n" % (len(self.pages),
self.max_urls))
return True
def activity(self):
"""
Return the string describing report processing information.
This string is constructed by the table() method above.
"""
return self.message
def suppress_cert_warning(self):
"""
Prevent security warning output from garbling HTML report pages.
"""
# pylint: disable=import-error, no-member
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class Page:
"""
Information about the health of the web resource addressed by a URL.
"""
dead_hosts = {}
def __init__(self, report, url):
"""
Determine whether the URL has problems.
We look for:
1. malformed URLs
2. unresponsive web servers
3. wrong URL schema
4. response code other than OK (200)
5. host name lookup failure
6. request timeout
7. (optionally) problems with invalid SSL certificates
We cache the results of checking each URL so we don't try
to process the same URL more than once. We also remember
web servers we know aren't alive as another optimization.
The URL cache is in the report object. The dead host
cache is stored in this class. (Dead host cache disabled;
see note below on remember_dead_host() method.)
The derived classes are responsible for closing the response
object, if that is appropriate.
"""
self.url = url
self.problem = self.response = None
components = urllib.parse.urlparse(url)
host = components.netloc
if not host:
self.problem = "Malformed URL"
elif components.netloc in self.dead_hosts:
self.problem = self.dead_hosts[host]
elif components.scheme not in ("http", "https"):
self.problem = "Unexpected scheme"
else:
try:
self.response = requests.get(url, **self.REQUEST_OPTS)
code = self.response.status_code
if code != 200:
try:
reason = str(self.response.reason, "utf-8")
except Exception:
reason = str(self.response.reason)
self.problem = "%d: %s" % (code, reason)
except IOError as e:
problem = str(e)
if "getaddrinfo failed" in problem:
self.problem = "host name lookup failure"
self.remember_dead_host(host, self.problem)
elif "ConnectTimeoutError":
self.problem = "connection timeout"
else:
self.problem = "IOError: %s" % e
report.logger.error("%s, %s", url, self.problem)
except socket.error: # pylint: disable=no-member
self.problem = "Host not responding"
self.remember_dead_host(host, self.problem)
report.logger.error("%s not responding", host)
except Exception as e:
self.problem = str(e)
report.logger.error("%s: %s", url, self.problem)
@classmethod
def remember_dead_host(cls, host, problem):
"""
Cache the information about a problem with a particular web server.
XXX 2017-02-19 ============================================
We've had to eliminate the dead host optimization, because
of a bug somewhere in the stack (the Windows firewall,
perhaps?). For some reason, the 301 response we get back
from www.cancer.gov when we submit a "GET /cam" request
never reaches the socket layer, resulting in an exception
being thrown. If we take that exception to mean that the
web server for www.cancer.gov is off line, we'll make the
wrong assumption about all subsequent URLs for that host.
See https://github.com/psf/requests/issues/3880 and
https://github.com/python/cpython/issues/73853.
XXX 2017-02-19 ============================================
"""
return
cls.dead_hosts[host] = problem
@classmethod
def test_harness(cls):
"""
Run a test report from the command line, bypassing the reporting queue.
"""
parser = cls.arg_parser(".html")
parser.add_argument("--doc-type", default="Summary",
help="CDR document type for report selections")
parser.add_argument("--max-urls", type=int, default=100,
help="stop after checking this many URLs "
"if throttling")
parser.add_argument("--connect-timeout", type=int, default=5,
help="wait this long for the socket connection")
parser.add_argument("--read-timeout", type=int, default=30,
help="wait READ_TIMEOUT seconds for web server")
parser.add_argument("--check-certs", action="store_true",
help="report invalid SSL certificates as errors")
parser.add_argument("--audience", default="Patient",
help="restrict report to this audience",
choices=("Patient", "Health Professional"))
parser.add_argument("--language", default="English",
help="restrict report to one language",
choices=("English", "Spanish"))
parser.add_argument("--boards", metavar="BOARD-ID", nargs="*",
help="restrict report by PDQ Board ID(s)")
if cls is BrokenExternalLinks:
parser.add_argument("--show-redirects", action="store_true",
help="report redirected URLs as problems")
if cls is PageTitleMismatches:
parser.add_argument("--show-all", action="store_true",
help="also display matching titles")
cls.run_test(parser, "html")
class BrokenExternalLinks(URLChecker):
"""
Report on external links with problems. BZIssues 903 and 3374.
Modified extensively for JIRA ticket OCECDR-4219.
"""
NAME = "Broken URLs"
TITLE = "URL Check"
BANNER = "CDR Report on Inactive Hyperlinks"
TABLE_CLASS = "url-check"
COLUMN_HEADERS = ("CDR ID", "Title", "Stored URL", "Problem", "Element")
def __init__(self, job):
"""
Collect the options stored for this report job.
"""
URLChecker.__init__(self, job, self.NAME, self.TITLE, self.BANNER)
self.show_redirects = job.getParm("show_redirects") == "True"
if self.doc_type == "Summary":
BrokenExternalLinks.COLUMN_HEADERS += ("Section Title",)
def fill_body(self, body):
"""
Add the heading, table, and processing activity summary to
the page HTML.
"""
return self.B.BODY(
self.B.H1(self.banner),
self.B.H2(self.doc_type),
self.table(),
self.B.P(self.message, self.B.CLASS("processing"))
)
def find_links(self):
"""
Find the links to be checked, using the user-supplied selection
criteria.
The selection logic is delicately tricky. Exactly one document type
must be specified for the report, unless a document ID is provided
to narrow the report to links in a single document, in which case
the document type is retrieved from the database. Depending on the
document type, other filtering criteria may be provided.
For glossary term concept documents, we look in two places: the
links stored in language-specific definition blocks, and links
stored outside the definition blocks in RelatedExternalRef element
with a @UseWith attribute specifying language usage for the links.
The links in the definition are audience specific (patients or
health professionals), whereas the links outside the definitions
are not. We use an SQL UNION of two separate queries to implement
this logic. Note that even if a CDR ID is specified to narrow
the report to links in a single document, we still apply this
logic to the GlossaryTermConcept documents to filter by language
and/or audience as appropriate.
Summary documents are somewhat less complicated in one sense:
if a summary document is selected, then all of the external
links in that document are selected for checking. Unlike the
GlossaryTermConcept documents, a PDQ summary document has
exactly one language and one audience. This simplification
is paid for by the complexity of supporting narrowing of the
result set to summaries linked to a specific PDQ board (a
requirement added in January 2017). The summary_board_subquery()
in the base class for a fuller explanation of how this is done.
For any other document type, no other special filtering is needed.
"""
fields = "u.doc_id", "d.title", "u.value", "u.path", "u.node_loc"
query = db.Query("query_term u", *fields).unique()
query.where("u.value LIKE 'http%'")
query.join("document d", "d.id = u.doc_id")
if not self.doc_id:
query.where("d.active_status = 'A'")
if self.doc_type == "GlossaryTermConcept":
if self.language or self.audience:
query.where("u.path = '%s/@cdr:xref'" % self.GTC_RELATED_REF)
if self.language:
language = self.GTC_LANGUAGES[self.language]
query.join("query_term l", "l.doc_id = u.doc_id",
"l.node_loc = u.node_loc")
query.where("l.path = '%s'" % self.GTC_USE_WITH)
query.where("l.value = '%s'" % language)
definition = self.DEFINITIONS[language]
def_path = "/%s/%s" % (self.GTC, definition)
else:
def_path = "/GlossaryTermConcept%TermDefinition"
query2 = db.Query("query_term u", *fields)
query2.where("u.path LIKE '%s%%/@cdr:xref'" % def_path)
query2.join("document d", "d.id = u.doc_id")
if not self.doc_id:
query2.where("d.active_status = 'A'")
if self.audience:
query2.join("query_term a", "a.doc_id = u.doc_id",
"a.node_loc = u.node_loc")
query2.where("a.path LIKE '%s%%/Audience'" % def_path)
query2.where("a.value = '%s'" % self.audience)
query2.where("u.value LIKE 'http%'")
query.union(query2)
else:
query.where("u.path LIKE '/GlossaryTermConcept/%/@cdr:xref'")
else:
query.where("u.path LIKE '/%s/%%/@cdr:xref'" % self.doc_type)
if self.doc_id:
query.where(query.Condition("u.doc_id", self.doc_id))
elif self.doc_type == "Summary":
if self.boards:
sq = self.summary_board_subquery(self.boards, self.language)
query.where(query.Condition("u.doc_id", sq, "IN"))
elif self.language:
query.join("query_term l", "l.doc_id = u.doc_id")
query.where("l.path = '%s'" % self.SUMMARY_LANGUAGE)
query.where("l.value = '%s'" % self.language)
if self.audience:
query.join("query_term a", "a.doc_id = u.doc_id")
query.where("a.path = '%s'" % self.SUMMARY_AUDIENCE)
query.where("a.value = '%ss'" % self.audience)
self.log_query(query)
rows = query.execute(self.cursor).fetchall()
return [self.Link(self, *row) for row in rows]
def selectors(self):
"""
Customize the style rules applied the report's display.
"""
selectors = BatchReport.selectors(self)
selectors["table.url-check"] = {"width": "100%"}
selectors["table.url-check th"] = {
"background-color": "silver",
"text-align": "left"
}
selectors["table.url-check th, table.url-check td"] = {
"border": "solid white 1px"
}
return selectors
class Link:
"""
External links found in the CDR documents.
"""
def __init__(self, report, doc_id, title, url, path, node_loc):
"""
Store the values for a row in the result set from the
database query.
"""
self.report = report
self.doc_id = doc_id
self.title = title
self.url = url
self.path = path
self.node_loc = node_loc
@property
def section_title(self):
"""
Title of innermost enclosing summary section where link is found
None if this is not a link in a Cancer Information Summary.
An empty string if it is a CIS, but no section title is found
(very unlikely).
"""
if not hasattr(self, "_section_title"):
self._section_title = None
if self.path.startswith("/Summary/"):
self._section_title = ""
top_loc = self.node_loc[:4]
query = db.Query("query_term", "value", "node_loc")
query.where(query.Condition("LEFT(node_loc, 4)", top_loc))
query.where("path LIKE '/Summary/%SummarySection/Title'")
query.where(query.Condition("doc_id", self.doc_id))
rows = query.execute(self.report.cursor).fetchall()
loc_len = 0
for title, node_loc in rows:
section_loc = node_loc[:-4]
if self.node_loc.startswith(section_loc):
if loc_len < len(section_loc):
self._section_title = title
loc_len = len(section_loc)
return self._section_title
def in_scope(self, page):
"""
Should this link be included on the report?
"""
return page.problem and True or False
def make_row(self, page):
"""
Assemble the table row describing problems with a link to this URL.
"""
B = self.report.B
element = self.path.split("/")[-2]
link = B.A(page.url, href=page.url, target="_blank")
url = "/cgi-bin/cdr/QcReport.py?DocId={:d}".format(self.doc_id)
qclink = B.A(str(self.doc_id), href=url, target="_blank")
row = B.TR(
B.TD(qclink, B.CLASS("center")),
B.TD(self.title, B.CLASS("left")),
B.TD(link, B.CLASS("left")),