This repository was archived by the owner on Mar 28, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscripts.py
More file actions
3429 lines (2925 loc) · 121 KB
/
scripts.py
File metadata and controls
3429 lines (2925 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import logging
import os
import random
import re
import subprocess
import sys
import traceback
import unicodedata
import uuid
from collections import defaultdict
from enum import Enum
from pdb import set_trace
from sqlalchemy import and_, exists, text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from .config import CannotLoadConfiguration, Configuration
from .coverage import CollectionCoverageProviderJob, CoverageProviderProgress
from .external_search import ExternalSearchIndex, Filter, SearchIndexCoverageProvider
from .lane import Lane
from .metadata_layer import (
LinkData,
MetaToModelUtility,
ReplacementPolicy,
TimestampData,
)
from .mirror import MirrorUploader
from .model import (
BaseCoverageRecord,
CachedFeed,
Collection,
Complaint,
ConfigurationSetting,
Contributor,
CustomList,
DataSource,
Edition,
ExternalIntegration,
Hyperlink,
Identifier,
Library,
LicensePool,
LicensePoolDeliveryMechanism,
Patron,
PresentationCalculationPolicy,
Representation,
SessionManager,
Subject,
Timestamp,
Work,
WorkCoverageRecord,
create,
get_one,
get_one_or_create,
production_session,
site_configuration_has_changed,
)
from .model.configuration import ExternalIntegrationLink
from .monitor import CollectionMonitor, ReaperMonitor
from .opds_import import OPDSImporter, OPDSImportMonitor
from .util import fast_query_count
from .util.datetime_helpers import strptime_utc, to_utc, utc_now
from .util.personal_names import contributor_name_match_ratio, display_name_to_sort_name
from .util.worker_pools import DatabasePool
class Script(object):
@property
def _db(self):
if not hasattr(self, "_session"):
self._session = production_session()
return self._session
@property
def script_name(self):
"""Find or guess the name of the script.
This is either the .name of the Script object or the name of
the class.
"""
return getattr(self, "name", self.__class__.__name__)
@property
def log(self):
if not hasattr(self, "_log"):
self._log = logging.getLogger(self.script_name)
return self._log
@property
def data_directory(self):
return Configuration.data_directory()
@classmethod
def parse_command_line(cls, _db=None, cmd_args=None):
parser = cls.arg_parser()
return parser.parse_known_args(cmd_args)[0]
@classmethod
def arg_parser(cls):
raise NotImplementedError()
@classmethod
def parse_time(cls, time_string):
"""Try to pass the given string as a time."""
if not time_string:
return None
for format in ("%Y-%m-%d", "%m/%d/%Y", "%Y%m%d"):
for hours in ("", " %H:%M:%S"):
full_format = format + hours
try:
parsed = strptime_utc(time_string, full_format)
return parsed
except ValueError as e:
continue
raise ValueError("Could not parse time: %s" % time_string)
def __init__(self, _db=None, *args, **kwargs):
"""Basic constructor.
:_db: A database session to be used instead of
creating a new one. Useful in tests.
"""
if _db:
self._session = _db
def run(self):
self.load_configuration()
DataSource.well_known_sources(self._db)
start_time = utc_now()
try:
timestamp_data = self.do_run()
if not isinstance(timestamp_data, TimestampData):
# Ignore any nonstandard return value from do_run().
timestamp_data = None
self.update_timestamp(timestamp_data, start_time, None)
except Exception as e:
logging.error("Fatal exception while running script: %s", e, exc_info=e)
stack_trace = traceback.format_exc()
self.update_timestamp(None, start_time, stack_trace)
raise
def load_configuration(self):
if not Configuration.cdns_loaded_from_database():
Configuration.load(self._db)
def update_timestamp(self, timestamp_data, start_time, exception):
"""By default scripts have no timestamp of their own.
Most scripts either work through Monitors or CoverageProviders,
which have their own logic for creating timestamps, or they
are designed to be run interactively from the command-line, so
facts about when they last ran are not relevant.
:param start_time: The time the script started running.
:param exception: A stack trace for the exception, if any,
that stopped the script from running.
"""
pass
class TimestampScript(Script):
"""A script that automatically records a timestamp whenever it runs."""
def __init__(self, *args, **kwargs):
super(TimestampScript, self).__init__(*args, **kwargs)
self.timestamp_collection = None
def update_timestamp(self, timestamp_data, start, exception):
"""Update the appropriate Timestamp for this script.
:param timestamp_data: A TimestampData representing what the script
itself thinks its timestamp should look like. Data will be filled in
where it is missing, but it will not be modified if present.
:param start: The time at which this script believes the
service started running. The script itself may change this
value for its own purposes.
:param exception: The exception with which this script
believes the service stopped running. The script itself may
change this value for its own purposes.
"""
if timestamp_data is None:
timestamp_data = TimestampData()
timestamp_data.finalize(
self.script_name,
Timestamp.SCRIPT_TYPE,
self.timestamp_collection,
start=start,
exception=exception,
)
timestamp_data.apply(self._db)
class RunMonitorScript(Script):
def __init__(self, monitor, _db=None, **kwargs):
super(RunMonitorScript, self).__init__(_db)
if issubclass(monitor, CollectionMonitor):
self.collection_monitor = monitor
self.collection_monitor_kwargs = kwargs
self.monitor = None
self.name = self.collection_monitor.SERVICE_NAME
else:
self.collection_monitor = None
if callable(monitor):
monitor = monitor(self._db, **kwargs)
self.monitor = monitor
self.name = self.monitor.service_name
def do_run(self):
if self.monitor:
self.monitor.run()
elif self.collection_monitor:
logging.warn(
"Running a CollectionMonitor by delegating to RunCollectionMonitorScript. "
"It would be better if you used RunCollectionMonitorScript directly."
)
RunCollectionMonitorScript(
self.collection_monitor, self._db, **self.collection_monitor_kwargs
).run()
class RunMultipleMonitorsScript(Script):
"""Run a number of monitors in sequence.
Currently the Monitors are run one at a time. It should be
possible to take a command-line argument that runs all the
Monitors in batches, each in its own thread. Unfortunately, it's
tough to know in a given situation that this won't overload the
system.
"""
def __init__(self, _db=None, **kwargs):
"""Constructor.
:param kwargs: Keyword arguments to pass into the `monitors` method
when building the Monitor objects.
"""
super(RunMultipleMonitorsScript, self).__init__(_db)
self.kwargs = kwargs
def monitors(self, **kwargs):
"""Find all the Monitors that need to be run.
:return: A list of Monitor objects.
"""
raise NotImplementedError()
def do_run(self):
for monitor in self.monitors(**self.kwargs):
try:
monitor.run()
except Exception as e:
# This is bad, but not so bad that we should give up trying
# to run the other Monitors.
if monitor.collection:
collection_name = monitor.collection.name
else:
collection_name = None
monitor.exception = e
self.log.error(
"Error running monitor %s for collection %s: %s",
self.name,
collection_name,
e,
exc_info=e,
)
class RunReaperMonitorsScript(RunMultipleMonitorsScript):
"""Run all the monitors found in ReaperMonitor.REGISTRY"""
name = "Run all reaper monitors"
def monitors(self, **kwargs):
return [cls(self._db, **kwargs) for cls in ReaperMonitor.REGISTRY]
class RunCoverageProvidersScript(Script):
"""Alternate between multiple coverage providers."""
def __init__(self, providers, _db=None):
super(RunCoverageProvidersScript, self).__init__(_db=_db)
self.providers = []
for i in providers:
if callable(i):
i = i(self._db)
self.providers.append(i)
def do_run(self):
providers = list(self.providers)
if not providers:
self.log.info("No CoverageProviders to run.")
progress = []
while providers:
random.shuffle(providers)
for provider in providers:
self.log.debug("Running %s", provider.service_name)
try:
provider_progress = provider.run_once_and_update_timestamp()
progress.append(provider_progress)
except Exception as e:
self.log.error(
"Error in %r, moving on to next CoverageProvider.",
provider,
exc_info=e,
)
self.log.debug("Completed %s", provider.service_name)
providers.remove(provider)
return progress
class RunCollectionCoverageProviderScript(RunCoverageProvidersScript):
"""Run the same CoverageProvider code for all Collections that
get their licenses from the appropriate place.
"""
def __init__(self, provider_class, _db=None, providers=None, **kwargs):
_db = _db or self._db
providers = providers or list()
if provider_class:
providers += self.get_providers(_db, provider_class, **kwargs)
super(RunCollectionCoverageProviderScript, self).__init__(providers, _db=_db)
def get_providers(self, _db, provider_class, **kwargs):
return list(provider_class.all(_db, **kwargs))
class RunThreadedCollectionCoverageProviderScript(Script):
"""Run coverage providers in multiple threads."""
DEFAULT_WORKER_SIZE = 5
def __init__(self, provider_class, worker_size=None, _db=None, **provider_kwargs):
super(RunThreadedCollectionCoverageProviderScript, self).__init__(_db)
self.worker_size = worker_size or self.DEFAULT_WORKER_SIZE
self.session_factory = SessionManager.sessionmaker(session=self._db)
# Use a database from the factory.
if not _db:
# Close the new, autogenerated database session.
self._session.close()
self._session = self.session_factory()
self.provider_class = provider_class
self.provider_kwargs = provider_kwargs
def run(self, pool=None):
"""Runs a CollectionCoverageProvider with multiple threads and
updates the timestamp accordingly.
:param pool: A DatabasePool (or other) object for use in testing
environments.
"""
collections = self.provider_class.collections(self._db)
if not collections:
return
for collection in collections:
provider = self.provider_class(collection, **self.provider_kwargs)
with (
pool or DatabasePool(self.worker_size, self.session_factory)
) as job_queue:
query_size, batch_size = self.get_query_and_batch_sizes(provider)
# Without a commit, the query to count which items need
# coverage hangs in the database, blocking the threads.
self._db.commit()
offset = 0
# TODO: We create a separate 'progress' object
# for each job, and each will overwrite the timestamp
# value as its complets. It woudl be better if all the
# jobs could share a single 'progress' object.
while offset < query_size:
progress = CoverageProviderProgress(start=utc_now())
progress.offset = offset
job = CollectionCoverageProviderJob(
collection,
self.provider_class,
progress,
**self.provider_kwargs,
)
job_queue.put(job)
offset += batch_size
def get_query_and_batch_sizes(self, provider):
qu = provider.items_that_need_coverage(
count_as_covered=BaseCoverageRecord.DEFAULT_COUNT_AS_COVERED
)
return fast_query_count(qu), provider.batch_size
class RunWorkCoverageProviderScript(RunCollectionCoverageProviderScript):
"""Run a WorkCoverageProvider on every relevant Work in the system."""
# This class overrides RunCollectionCoverageProviderScript just to
# take advantage of the constructor; it doesn't actually use the
# concept of 'collections' at all.
def get_providers(self, _db, provider_class, **kwargs):
return [provider_class(_db, **kwargs)]
class InputScript(Script):
@classmethod
def read_stdin_lines(self, stdin):
"""Read lines from a (possibly mocked, possibly empty) standard input."""
if stdin is not sys.stdin or not os.isatty(0):
# A file has been redirected into standard input. Grab its
# lines.
lines = [x.strip() for x in stdin.readlines()]
else:
lines = []
return lines
class IdentifierInputScript(InputScript):
"""A script that takes identifiers as command line inputs."""
DATABASE_ID = "Database ID"
@classmethod
def parse_command_line(
cls, _db=None, cmd_args=None, stdin=sys.stdin, *args, **kwargs
):
parser = cls.arg_parser()
parsed = parser.parse_args(cmd_args)
stdin = cls.read_stdin_lines(stdin)
return cls.look_up_identifiers(_db, parsed, stdin, *args, **kwargs)
@classmethod
def look_up_identifiers(
cls, _db, parsed, stdin_identifier_strings, *args, **kwargs
):
"""Turn identifiers as specified on the command line into
real database Identifier objects.
"""
data_source = None
if parsed.identifier_data_source:
data_source = DataSource.lookup(_db, parsed.identifier_data_source)
if _db and parsed.identifier_type:
# We can also call parse_identifier_list.
identifier_strings = parsed.identifier_strings
if stdin_identifier_strings:
identifier_strings = identifier_strings + stdin_identifier_strings
parsed.identifiers = cls.parse_identifier_list(
_db,
parsed.identifier_type,
data_source,
identifier_strings,
*args,
**kwargs,
)
else:
# The script can call parse_identifier_list later if it
# wants to.
parsed.identifiers = None
return parsed
@classmethod
def arg_parser(cls):
parser = argparse.ArgumentParser()
parser.add_argument(
"--identifier-type",
help='Process identifiers of this type. If IDENTIFIER is not specified, all identifiers of this type will be processed. To name identifiers by their database ID, use --identifier-type="Database ID"',
)
parser.add_argument(
"--identifier-data-source",
help="Process only identifiers which have a LicensePool associated with this DataSource",
)
parser.add_argument(
"identifier_strings",
help="A specific identifier to process.",
metavar="IDENTIFIER",
nargs="*",
)
return parser
@classmethod
def parse_identifier_list(
cls, _db, identifier_type, data_source, arguments, autocreate=False
):
"""Turn a list of identifiers into a list of Identifier objects.
The list of arguments is probably derived from a command-line
parser such as the one defined in
IdentifierInputScript.arg_parser().
This makes it easy to identify specific identifiers on the
command line. Examples:
1 2
a b c
"""
identifiers = []
if not identifier_type:
raise ValueError(
"No identifier type specified! Use '--identifier-type=\"Database ID\"' to name identifiers by database ID."
)
if len(arguments) == 0:
if data_source:
identifiers = (
_db.query(Identifier)
.join(Identifier.licensed_through)
.filter(
Identifier.type == identifier_type,
LicensePool.data_source == data_source,
)
.all()
)
return identifiers
for arg in arguments:
if identifier_type == cls.DATABASE_ID:
try:
arg = int(arg)
except ValueError as e:
# We'll print out a warning later.
arg = None
if arg:
identifier = get_one(_db, Identifier, id=arg)
else:
identifier, ignore = Identifier.for_foreign_id(
_db, identifier_type, arg, autocreate=autocreate
)
if not identifier:
logging.warn("Could not load identifier %s/%s", identifier_type, arg)
if identifier:
identifiers.append(identifier)
return identifiers
class LibraryInputScript(InputScript):
"""A script that operates on one or more Libraries."""
@classmethod
def parse_command_line(cls, _db=None, cmd_args=None, *args, **kwargs):
parser = cls.arg_parser(_db)
parsed = parser.parse_args(cmd_args)
return cls.look_up_libraries(_db, parsed, *args, **kwargs)
@classmethod
def arg_parser(cls, _db, multiple_libraries=True):
parser = argparse.ArgumentParser()
library_names = sorted(l.short_name for l in _db.query(Library))
library_names = '"' + '", "'.join(library_names) + '"'
parser.add_argument(
"libraries",
help="Name of a specific library to process. Libraries on this system: %s"
% library_names,
metavar="SHORT_NAME",
nargs="*" if multiple_libraries else 1,
)
return parser
@classmethod
def look_up_libraries(cls, _db, parsed, *args, **kwargs):
"""Turn library names as specified on the command line into real
Library objects.
"""
if _db:
library_strings = parsed.libraries
if library_strings:
parsed.libraries = cls.parse_library_list(
_db, library_strings, *args, **kwargs
)
else:
# No libraries are specified. We will be processing
# every library.
parsed.libraries = _db.query(Library).all()
else:
# Database is not active yet. The script can call
# parse_library_list later if it wants to.
parsed.libraries = None
return parsed
@classmethod
def parse_library_list(cls, _db, arguments):
"""Turn a list of library short names into a list of Library objects.
The list of arguments is probably derived from a command-line
parser such as the one defined in
LibraryInputScript.arg_parser().
"""
if len(arguments) == 0:
return []
libraries = []
for arg in arguments:
if not arg:
continue
for field in (Library.short_name, Library.name):
try:
library = _db.query(Library).filter(field == arg).one()
except NoResultFound:
continue
except MultipleResultsFound:
continue
if library:
libraries.append(library)
break
else:
logging.warn("Could not find library %s", arg)
return libraries
def do_run(self, *args, **kwargs):
parsed = self.parse_command_line(self._db, *args, **kwargs)
self.process_libraries(parsed.libraries)
def process_libraries(self, libraries):
for library in libraries:
self.process_library(library)
def process_library(self, library):
raise NotImplementedError()
class PatronInputScript(LibraryInputScript):
"""A script that operates on one or more Patrons."""
@classmethod
def parse_command_line(
cls, _db=None, cmd_args=None, stdin=sys.stdin, *args, **kwargs
):
parser = cls.arg_parser(_db)
parsed = parser.parse_args(cmd_args)
if stdin:
stdin = cls.read_stdin_lines(stdin)
parsed = super(PatronInputScript, cls).look_up_libraries(
_db, parsed, *args, **kwargs
)
return cls.look_up_patrons(_db, parsed, stdin, *args, **kwargs)
@classmethod
def arg_parser(cls, _db):
parser = super(PatronInputScript, cls).arg_parser(_db, multiple_libraries=False)
parser.add_argument(
"identifiers",
help="A specific patron identifier to process.",
metavar="IDENTIFIER",
nargs="+",
)
return parser
@classmethod
def look_up_patrons(cls, _db, parsed, stdin_patron_strings, *args, **kwargs):
"""Turn patron identifiers as specified on the command line into real
Patron objects.
"""
if _db:
patron_strings = parsed.identifiers
library = parsed.libraries[0]
if stdin_patron_strings:
patron_strings = patron_strings + stdin_patron_strings
parsed.patrons = cls.parse_patron_list(
_db, library, patron_strings, *args, **kwargs
)
else:
# Database is not active yet. The script can call
# parse_patron_list later if it wants to.
parsed.patrons = None
return parsed
@classmethod
def parse_patron_list(cls, _db, library, arguments):
"""Turn a list of patron identifiers into a list of Patron objects.
The list of arguments is probably derived from a command-line
parser such as the one defined in
PatronInputScript.arg_parser().
"""
if len(arguments) == 0:
return []
patrons = []
for arg in arguments:
if not arg:
continue
for field in (
Patron.authorization_identifier,
Patron.username,
Patron.external_identifier,
):
try:
patron = (
_db.query(Patron)
.filter(field == arg)
.filter(Patron.library_id == library.id)
.one()
)
except NoResultFound:
continue
except MultipleResultsFound:
continue
if patron:
patrons.append(patron)
break
else:
logging.warn("Could not find patron %s", arg)
return patrons
def do_run(self, *args, **kwargs):
parsed = self.parse_command_line(self._db, *args, **kwargs)
self.process_patrons(parsed.patrons)
def process_patrons(self, patrons):
for patron in patrons:
self.process_patron(patron)
def process_patron(self, patron):
raise NotImplementedError()
class LaneSweeperScript(LibraryInputScript):
"""Do something to each lane in a library."""
def process_library(self, library):
from .lane import WorkList
top_level = WorkList.top_level_for_library(self._db, library)
queue = [top_level]
while queue:
new_queue = []
for l in queue:
if isinstance(l, Lane):
l = self._db.merge(l)
if self.should_process_lane(l):
self.process_lane(l)
self._db.commit()
for sublane in l.children:
new_queue.append(sublane)
queue = new_queue
def should_process_lane(self, lane):
return True
def process_lane(self, lane):
pass
class CustomListSweeperScript(LibraryInputScript):
"""Do something to each custom list in a library."""
def process_library(self, library):
lists = self._db.query(CustomList).filter(CustomList.library_id == library.id)
for l in lists:
self.process_custom_list(l)
self._db.commit()
def process_custom_list(self, custom_list):
pass
class SubjectInputScript(Script):
"""A script whose command line filters the set of Subjects.
:return: a 2-tuple (subject type, subject filter) that can be
passed into the SubjectSweepMonitor constructor.
"""
@classmethod
def arg_parser(cls):
parser = argparse.ArgumentParser()
parser.add_argument("--subject-type", help="Process subjects of this type")
parser.add_argument(
"--subject-filter",
help="Process subjects whose names or identifiers match this substring",
)
return parser
class RunCoverageProviderScript(IdentifierInputScript):
"""Run a single coverage provider."""
@classmethod
def arg_parser(cls):
parser = IdentifierInputScript.arg_parser()
parser.add_argument(
"--cutoff-time",
help="Update existing coverage records if they were originally created after this time.",
)
return parser
@classmethod
def parse_command_line(cls, _db, cmd_args=None, stdin=sys.stdin, *args, **kwargs):
parser = cls.arg_parser()
parsed = parser.parse_args(cmd_args)
stdin = cls.read_stdin_lines(stdin)
parsed = cls.look_up_identifiers(_db, parsed, stdin, *args, **kwargs)
if parsed.cutoff_time:
parsed.cutoff_time = cls.parse_time(parsed.cutoff_time)
return parsed
def __init__(
self, provider, _db=None, cmd_args=None, *provider_args, **provider_kwargs
):
super(RunCoverageProviderScript, self).__init__(_db)
parsed_args = self.parse_command_line(self._db, cmd_args)
if parsed_args.identifier_type:
self.identifier_type = parsed_args.identifier_type
self.identifier_types = [self.identifier_type]
else:
self.identifier_type = None
self.identifier_types = []
if parsed_args.identifiers:
self.identifiers = parsed_args.identifiers
else:
self.identifiers = []
if callable(provider):
kwargs = self.extract_additional_command_line_arguments()
kwargs.update(provider_kwargs)
provider = provider(
self._db, *provider_args, cutoff_time=parsed_args.cutoff_time, **kwargs
)
self.provider = provider
self.name = self.provider.service_name
def extract_additional_command_line_arguments(self):
"""A hook method for subclasses.
Turns command-line arguments into additional keyword arguments
to the CoverageProvider constructor.
By default, pass in a value used only by CoverageProvider
(as opposed to WorkCoverageProvider).
"""
return {
"input_identifiers": self.identifiers,
}
def do_run(self):
if self.identifiers:
self.provider.run_on_specific_identifiers(self.identifiers)
else:
self.provider.run()
class ShowLibrariesScript(Script):
"""Show information about the libraries on a server."""
name = "List the libraries on this server."
@classmethod
def arg_parser(cls):
parser = argparse.ArgumentParser()
parser.add_argument(
"--short-name",
help="Only display information for the library with the given short name",
)
parser.add_argument(
"--show-secrets",
help="Print out secrets associated with the library.",
action="store_true",
)
return parser
def do_run(self, _db=None, cmd_args=None, output=sys.stdout):
_db = _db or self._db
args = self.parse_command_line(_db, cmd_args=cmd_args)
if args.short_name:
library = get_one(_db, Library, short_name=args.short_name)
libraries = [library]
else:
libraries = _db.query(Library).order_by(Library.name).all()
if not libraries:
output.write("No libraries found.\n")
for library in libraries:
output.write("\n".join(library.explain(include_secrets=args.show_secrets)))
output.write("\n")
class ConfigurationSettingScript(Script):
@classmethod
def _parse_setting(self, setting):
"""Parse a command-line setting option into a key-value pair."""
if not "=" in setting:
raise ValueError(
'Incorrect format for setting: "%s". Should be "key=value"' % setting
)
return setting.split("=", 1)
@classmethod
def add_setting_argument(self, parser, help):
"""Modify an ArgumentParser to indicate that the script takes
command-line settings.
"""
parser.add_argument("--setting", help=help, action="append")
def apply_settings(self, settings, obj):
"""Treat `settings` as a list of command-line argument settings,
and apply each one to `obj`.
"""
if not settings:
return None
for setting in settings:
key, value = self._parse_setting(setting)
obj.setting(key).value = value
class ConfigureSiteScript(ConfigurationSettingScript):
"""View or update site-wide configuration."""
def __init__(self, _db=None, config=Configuration):
self.config = config
super(ConfigureSiteScript, self).__init__(_db=_db)
@classmethod
def arg_parser(cls):
parser = argparse.ArgumentParser()
parser.add_argument(
"--show-secrets",
help="Include secrets when displaying site settings.",
action="store_true",
default=False,
)
cls.add_setting_argument(
parser,
'Set a site-wide setting, such as default_nongrouped_feed_max_age. Format: --setting="default_nongrouped_feed_max_age=1200"',
)
parser.add_argument(
"--force",
help="Set a site-wide setting even if the key isn't a known setting.",
dest="force",
action="store_true",
)
return parser
def do_run(self, _db=None, cmd_args=None, output=sys.stdout):
_db = _db or self._db
args = self.parse_command_line(_db, cmd_args=cmd_args)
if args.setting:
for setting in args.setting:
key, value = self._parse_setting(setting)
if not args.force and not key in [
s.get("key") for s in self.config.SITEWIDE_SETTINGS
]:
raise ValueError(
"'%s' is not a known site-wide setting. Use --force to set it anyway."
% key
)
else:
ConfigurationSetting.sitewide(_db, key).value = value
output.write(
"\n".join(
ConfigurationSetting.explain(_db, include_secrets=args.show_secrets)
)
)
site_configuration_has_changed(_db)
_db.commit()
class ConfigureLibraryScript(ConfigurationSettingScript):
"""Create a library or change its settings."""
name = "Change a library's settings"
@classmethod
def arg_parser(cls):
parser = argparse.ArgumentParser()
parser.add_argument(
"--name",
help="Official name of the library",
)
parser.add_argument(
"--short-name",
help="Short name of the library",
)
cls.add_setting_argument(
parser,
'Set a per-library setting, such as terms-of-service. Format: --setting="terms-of-service=https://example.library/tos"',
)
return parser
def do_run(self, _db=None, cmd_args=None, output=sys.stdout):
_db = _db or self._db
args = self.parse_command_line(_db, cmd_args=cmd_args)
if not args.short_name:
raise ValueError("You must identify the library by its short name.")
# Are we talking about an existing library?
libraries = _db.query(Library).all()
if libraries: