A VCS repository archival tool
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

449 wiersze
17 KiB

  1. import abc
  2. #import codearchiver.modules # In get_module_class
  3. import codearchiver.storage
  4. import codearchiver.version
  5. import collections
  6. import contextlib
  7. import dataclasses
  8. import datetime
  9. import functools
  10. import logging
  11. import os
  12. import queue
  13. import requests
  14. import time
  15. import typing
  16. import weakref
  17. _logger = logging.getLogger(__name__)
  18. class InputURL:
  19. '''
  20. An input URL
  21. This primarily exists so multiple modules can access the content behind the URL for checks in `Module.matches` without fetching multiple times.
  22. It also handles the module name prefix in the scheme part of the URL. Note that `InputURL.url` is then the part without the module name.
  23. '''
  24. def __init__(self, url: str):
  25. if 0 < url.find('+') < url.find('://'):
  26. # '+' and '://' appear in the URL in this order and there is at least one character each before the + as well as between the two
  27. self._moduleScheme, self._url = url.split('+', 1)
  28. else:
  29. self._moduleScheme = None
  30. self._url = url
  31. self._response = None
  32. @property
  33. def url(self) -> str:
  34. '''URL without the module scheme prefix (if any)'''
  35. return self._url
  36. @property
  37. def moduleScheme(self) -> typing.Optional[str]:
  38. '''Module scheme prefix (if one is included, else `None`)'''
  39. return self._moduleScheme
  40. @property
  41. def content(self) -> str:
  42. '''HTTP response body upon fetching the URL with GET'''
  43. if self._response is None:
  44. self._response = HttpClient().get(self.url)
  45. return self._response.text
  46. def __repr__(self):
  47. return f'{type(self).__module__}.{type(self).__name__}({self._url!r})'
  48. @dataclasses.dataclass
  49. class Result:
  50. '''Container for the result of a module'''
  51. id: str
  52. '''A unique ID for this result'''
  53. files: list[tuple[str, typing.Optional['Metadata']]] = dataclasses.field(default_factory = list)
  54. '''List of filenames produced by the run, optionally with metadata'''
  55. submoduleResults: list[tuple['Module', 'Result']] = dataclasses.field(default_factory = list)
  56. '''List of related submodules and their results'''
  57. class MetadataValidationError(ValueError):
  58. pass
  59. @dataclasses.dataclass
  60. class MetadataField:
  61. key: str
  62. required: bool
  63. repeatable: bool
  64. class Metadata(list[tuple[str, str]]):
  65. '''Metadata (key-value mapping, possibly with repeated keys) of a file produced by a module'''
  66. fields: tuple[MetadataField] = (
  67. MetadataField('codearchiver version', required = True, repeatable = False),
  68. MetadataField('Module', required = True, repeatable = False),
  69. MetadataField('Metadata version', required = True, repeatable = False),
  70. MetadataField('ID', required = True, repeatable = False),
  71. MetadataField('Input URL', required = True, repeatable = False),
  72. MetadataField('Filename', required = True, repeatable = False),
  73. MetadataField('Retrieval start time', required = True, repeatable = False),
  74. MetadataField('Retrieval end time', required = True, repeatable = False),
  75. )
  76. '''The fields for this metadata collection'''
  77. version: int = 0
  78. '''Version, incremented on every backward-incompatible change'''
  79. _allFieldsCache: typing.Optional[tuple[MetadataField]] = None
  80. def append(self, *args):
  81. if len(args) == 1:
  82. args = args[0]
  83. return super().append(args)
  84. # This should be a @classmethod, too, but that's deprecated since Python 3.11.
  85. @property
  86. def _allFields(self):
  87. '''All fields known by this metadata collection, own ones and all from superclasses'''
  88. if type(self)._allFieldsCache is None:
  89. fields = []
  90. for cls in reversed(type(self).mro()):
  91. fields.extend(getattr(cls, 'fields', []))
  92. type(self)._allFieldsCache = tuple(fields)
  93. return type(self)._allFieldsCache
  94. def validate(self):
  95. '''Check that all keys and values conform to the specification'''
  96. keyCounts = collections.Counter(key for key, _ in self)
  97. keys = set(keyCounts)
  98. permittedKeys = set(field.key for field in self._allFields)
  99. unrecognisedKeys = keys - permittedKeys
  100. requiredKeys = set(field.key for field in self._allFields if field.required)
  101. missingRequiredKeys = requiredKeys - keys
  102. repeatableKeys = set(field.key for field in self._allFields if field.repeatable)
  103. repeatedKeys = set(key for key, count in keyCounts.items() if count > 1)
  104. repeatedUnrepeatableKeys = repeatedKeys - repeatableKeys
  105. errors = []
  106. if unrecognisedKeys:
  107. errors.append(f'unrecognised key(s): {", ".join(sorted(unrecognisedKeys))}')
  108. if missingRequiredKeys:
  109. errors.append(f'missing required key(s): {", ".join(sorted(missingRequiredKeys))}')
  110. if repeatedUnrepeatableKeys:
  111. errors.append(f'repeated unrepeatable key(s): {", ".join(sorted(repeatedUnrepeatableKeys))}')
  112. if errors:
  113. raise MetadataValidationError('; '.join(errors))
  114. def matches(self, criteria: list[tuple[str, typing.Union[str, tuple[str]]]]) -> bool:
  115. '''
  116. Check whether the criteria match this metadata collection
  117. Each criterion consists of a key and one or more possible values. A criterion matches if at least one of the specified values is present in the metadata.
  118. Multiple criteria may use the same key to perform an AND search.
  119. The metadata is a match if all criteria match.
  120. '''
  121. criteria = criteria.copy()
  122. _logger.debug(f'Searching metadata for {criteria!r}')
  123. keysOfInterest = set(key for key, _ in criteria)
  124. for key, value in self:
  125. if key not in keysOfInterest:
  126. continue
  127. _logger.debug(f'Potentially interesting entry: {key!r} = {value!r}')
  128. matched = [] # Indices to remove from remaining criteria
  129. for i, (keyCriterion, valueCriterion) in enumerate(criteria):
  130. if keyCriterion != key:
  131. continue
  132. if isinstance(valueCriterion, str) and valueCriterion == value:
  133. _logger.debug('Str match')
  134. matched.append(i)
  135. elif isinstance(valueCriterion, tuple) and value in valueCriterion:
  136. _logger.debug('Tuple match')
  137. matched.append(i)
  138. for i in reversed(matched):
  139. _logger.debug(f'Matched remaining criterion {i}: {criteria[i]}')
  140. del criteria[i]
  141. if not criteria:
  142. break
  143. _logger.debug(f'Remaining unmatched criteria: {criteria!r}')
  144. return not bool(criteria)
  145. def serialise(self) -> str:
  146. '''Convert the metadata to a string suitable for e.g. a simple text file storage'''
  147. self.validate()
  148. return ''.join(f'{key}: {value}\n' for key, value in self)
  149. @classmethod
  150. def deserialise(cls, f: typing.Union[str, bytes, os.PathLike, typing.TextIO], *, validate = True):
  151. '''Import a serialised metadata from a filename or file-like object'''
  152. if isinstance(f, (str, bytes, os.PathLike)):
  153. cm = open(f, 'r')
  154. else:
  155. cm = contextlib.nullcontext(f)
  156. with cm as fp:
  157. o = cls((key, value[:-1]) for key, value in map(functools.partial(str.split, sep = ': '), fp))
  158. if validate:
  159. o.validate()
  160. return o
  161. class HttpError(Exception):
  162. '''An HTTP request failed too many times.'''
  163. class HttpClient:
  164. '''A thin wrapper HTTP client around Requests with exponential backoff retries and a default user agent for all requests.'''
  165. defaultRetries: int = 3
  166. '''Default number of retries on errors unless overridden on creating the HttpClient object'''
  167. defaultUserAgent: str = f'codearchiver/{codearchiver.version.__version__}'
  168. '''Default user agent unless overridden on instantiation or by overriding via the headers kwarg'''
  169. def __init__(self, retries: typing.Optional[int] = None, userAgent: typing.Optional[str] = None):
  170. self._session = requests.Session()
  171. self._retries = retries if retries else self.defaultRetries
  172. self._userAgent = userAgent if userAgent else self.defaultUserAgent
  173. def request(self,
  174. method,
  175. url,
  176. params = None,
  177. data = None,
  178. headers: typing.Optional[dict[str, str]] = None,
  179. timeout: int = 10,
  180. responseOkCallback: typing.Optional[typing.Callable[[requests.Response], tuple[bool, typing.Optional[str]]]] = None,
  181. ) -> requests.Response:
  182. '''
  183. Make an HTTP request
  184. For the details on `method`, `url`, `params`, and `data`, refer to the Requests documentation on the constructor of `requests.Request`.
  185. For details on `timeout`, see `requests.adapters.HTTPAdapter.send`.
  186. `headers` can be used to specify any HTTP headers. Note that this is case-sensitive. To override the user agent, include a value for the `User-Agent` key here.
  187. `responseOkCallback` can be used to control whether a response is considered acceptable or not. By default, all HTTP responses are considered fine. If specified, this callable must produce a boolean marking whether the response is successful and an error message string. The string is used for logging purposes when the success flag is `False`; it should be `None` if the first return value is `True`.
  188. '''
  189. mergedHeaders = {'User-Agent': self._userAgent}
  190. if headers:
  191. mergedHeaders.update(headers)
  192. headers = mergedHeaders
  193. for attempt in range(self._retries + 1):
  194. # The request is newly prepared on each retry because of potential cookie updates.
  195. req = self._session.prepare_request(requests.Request(method, url, params = params, data = data, headers = headers))
  196. _logger.info(f'Retrieving {req.url}')
  197. _logger.debug(f'... with headers: {headers!r}')
  198. if data:
  199. _logger.debug(f'... with data: {data!r}')
  200. try:
  201. r = self._session.send(req, timeout = timeout)
  202. except requests.exceptions.RequestException as exc:
  203. if attempt < self._retries:
  204. retrying = ', retrying'
  205. level = logging.WARNING
  206. else:
  207. retrying = ''
  208. level = logging.ERROR
  209. _logger.log(level, f'Error retrieving {req.url}: {exc!r}{retrying}')
  210. else:
  211. if responseOkCallback is not None:
  212. success, msg = responseOkCallback(r)
  213. else:
  214. success, msg = (True, None)
  215. msg = f': {msg}' if msg else ''
  216. if success:
  217. _logger.debug(f'{req.url} retrieved successfully{msg}')
  218. return r
  219. else:
  220. if attempt < self._retries:
  221. retrying = ', retrying'
  222. level = logging.WARNING
  223. else:
  224. retrying = ''
  225. level = logging.ERROR
  226. _logger.log(level, f'Error retrieving {req.url}{msg}{retrying}')
  227. if attempt < self._retries:
  228. sleepTime = 1.0 * 2**attempt # exponential backoff: sleep 1 second after first attempt, 2 after second, 4 after third, etc.
  229. _logger.info(f'Waiting {sleepTime:.0f} seconds')
  230. time.sleep(sleepTime)
  231. else:
  232. msg = f'{self._retries + 1} requests to {req.url} failed, giving up.'
  233. _logger.fatal(msg)
  234. raise HttpError(msg)
  235. raise RuntimeError('Reached unreachable code')
  236. def get(self, *args, **kwargs):
  237. '''Make a GET request. This is equivalent to calling `.request('GET', ...)`.'''
  238. return self.request('GET', *args, **kwargs)
  239. def post(self, *args, **kwargs):
  240. '''Make a POST request. This is equivalent to calling `.request('POST', ...)`.'''
  241. return self.request('POST', *args, **kwargs)
  242. class ModuleMeta(abc.ABCMeta):
  243. '''Metaclass of modules. This is used to keep track of which modules exist and selecting them. It also enforces module name restrictions and prevents name collisions.'''
  244. __modulesByName: dict[str, typing.Type['Module']] = {}
  245. def __new__(cls, *args, **kwargs):
  246. class_ = super().__new__(cls, *args, **kwargs)
  247. if class_.name is not None:
  248. if class_.name.strip('abcdefghijklmnopqrstuvwxyz-') != '':
  249. raise RuntimeError(f'Invalid class name: {class_.name!r}')
  250. if class_.name in cls.__modulesByName:
  251. raise RuntimeError(f'Class name collision: {class_.name!r} is already known')
  252. cls.__modulesByName[class_.name] = weakref.ref(class_)
  253. _logger.info(f'Found {class_.name!r} module {class_.__module__}.{class_.__name__}')
  254. else:
  255. _logger.info(f'Found nameless module {class_.__module__}.{class_.__name__}')
  256. return class_
  257. @classmethod
  258. def get_module_by_name(cls, name: str) -> typing.Optional[typing.Type['Module']]:
  259. '''Get a module by name if one exists'''
  260. if classRef := cls.__modulesByName.get(name):
  261. class_ = classRef()
  262. if class_ is None:
  263. _logger.info(f'Module {name!r} is gone, dropping')
  264. del cls.__modulesByName[name]
  265. return class_
  266. @classmethod
  267. def iter_modules(cls) -> typing.Iterator[typing.Type['Module']]:
  268. '''Iterate over all known modules'''
  269. # Housekeeping first: remove dead modules
  270. for name in list(cls.__modulesByName): # create a copy of the names list so the dict can be modified in the loop
  271. if cls.__modulesByName[name]() is None:
  272. _logger.info(f'Module {name!r} is gone, dropping')
  273. del cls.__modulesByName[name]
  274. for name, classRef in cls.__modulesByName.items():
  275. class_ = classRef()
  276. if class_ is None:
  277. # Module class no longer exists, skip
  278. # Even though dead modules are removed above, it's possible that the code consuming this iterator drops/deletes modules.
  279. continue
  280. yield class_
  281. @classmethod
  282. def drop(cls, module: 'Module'):
  283. '''
  284. Remove a module from the list of known modules
  285. If a Module subclass is destroyed after `del MyModule`, it is also eventually removed from the list. However, as that relies on garbage collection, it should not be depended on and modules should be dropped with this method explicitly.
  286. '''
  287. if module.name is not None and module.name in cls.__modulesByName:
  288. del cls.__modulesByName[module.name]
  289. _logger.info(f'Module {module.name!r} dropped')
  290. def __del__(self, *args, **kwargs):
  291. if self.name is not None and self.name in type(self).__modulesByName:
  292. _logger.info(f'Module {self.name!r} is being destroyed, dropping')
  293. del type(self).__modulesByName[self.name]
  294. # type has no __del__ method, no need to call it.
  295. class Module(metaclass = ModuleMeta):
  296. '''An abstract base class for a module.'''
  297. name: typing.Optional[str] = None
  298. '''The name of the module. Modules without a name are ignored. Names must be unique and may only contain a-z and hyphens.'''
  299. MetadataClass: typing.Optional[typing.Type[Metadata]] = None
  300. '''The Metadata class corresponding to this module, if any.'''
  301. @staticmethod
  302. def matches(inputUrl: InputURL) -> bool:
  303. '''Whether or not this module is for handling `inputUrl`.'''
  304. return False
  305. def __init__(self, inputUrl: InputURL, storage: typing.Optional[codearchiver.storage.Storage] = None, id_: typing.Optional[str] = None):
  306. self._inputUrl = inputUrl
  307. self._url = inputUrl.url
  308. self._storage = storage
  309. self._id = id_
  310. if self._id is None and type(self).name is not None:
  311. self._id = f'{type(self).name}_{self._url.replace("/", "_")}_{datetime.datetime.utcnow():%Y%m%dT%H%M%SZ}'
  312. self._httpClient = HttpClient()
  313. @abc.abstractmethod
  314. def process(self) -> Result:
  315. '''Perform the relevant retrieval(s)'''
  316. def create_metadata(self, filename: str, startTime: datetime.datetime, endTime: datetime.datetime) -> Metadata:
  317. '''
  318. Create a basic Metadata instance appropriate for this module
  319. `startTime` and `endTime` must be in UTC (e.g. `datetime.datetime.utcnow()`). They should reflect the moments just before and after all interaction with the remote system.
  320. '''
  321. if type(self).MetadataClass is None or type(self).name is None:
  322. raise RuntimeError('Module lacks an MetadataClass or a name; cannot create metadata')
  323. idx = type(self).MetadataClass()
  324. idx.append('codearchiver version', codearchiver.version.__version__)
  325. idx.append('Module', type(self).name)
  326. metadataVersions = []
  327. for cls in reversed(type(self).MetadataClass.mro()):
  328. version = cls.__dict__.get('version')
  329. if version is None:
  330. continue
  331. metadataVersions.append(f'{cls.__module__}.{cls.__qualname__}/{version}')
  332. idx.append('Metadata version', ' '.join(metadataVersions))
  333. idx.append('ID', self._id)
  334. idx.append('Input URL', self._url)
  335. idx.append('Filename', filename)
  336. idx.append('Retrieval start time', startTime.strftime('%Y-%m-%d %H:%M:%S.%f UTC'))
  337. idx.append('Retrieval end time', endTime.strftime('%Y-%m-%d %H:%M:%S.%f UTC'))
  338. return idx
  339. def __repr__(self):
  340. return f'{type(self).__module__}.{type(self).__name__}({self._inputUrl!r})'
  341. def get_module_class(inputUrl: InputURL) -> typing.Type[Module]:
  342. '''Get the Module class most suitable for handling `inputUrl`.'''
  343. # Ensure that modules are imported
  344. # This can't be done at the top because the modules need to refer back to the Module class.
  345. import codearchiver.modules
  346. # Check if the URL references one of the modules directly
  347. if inputUrl.moduleScheme:
  348. if module := ModuleMeta.get_module_by_name(inputUrl.moduleScheme):
  349. _logger.info(f'Selecting module {module.__module__}.{module.__name__}')
  350. return module
  351. else:
  352. raise RuntimeError(f'No module with name {inputUrl.moduleScheme!r} exists')
  353. # Check if exactly one of the modules matches
  354. matches = [class_ for class_ in ModuleMeta.iter_modules() if class_.matches(inputUrl)]
  355. if len(matches) >= 2:
  356. _logger.error('Multiple matching modules for input URL')
  357. _logger.debug(f'Matching modules: {matches!r}')
  358. raise RuntimeError('Multiple matching modules for input URL')
  359. if matches:
  360. _logger.info(f'Selecting module {matches[0].__module__}.{matches[0].__name__}')
  361. return matches[0]
  362. raise RuntimeError('No matching modules for input URL')
  363. def get_module_instance(inputUrl: InputURL, **kwargs) -> Module:
  364. '''Get an instance of the Module class most suitable for handling `inputUrl`.'''
  365. return get_module_class(inputUrl)(inputUrl, **kwargs)