The little things give you away... A collection of various small helper stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

441 lines
17 KiB

  1. #!/usr/bin/env python3
  2. # Only external dependency: requests
  3. import argparse
  4. import base64
  5. import collections
  6. import concurrent.futures
  7. import configparser
  8. import contextlib
  9. import functools
  10. import hashlib
  11. import io
  12. import itertools
  13. import json
  14. import logging
  15. import os
  16. import pprint
  17. import re
  18. import requests
  19. import sys
  20. import time
  21. try:
  22. import tqdm
  23. except ImportError:
  24. tqdm = None
  25. import types
  26. logger = logging.getLogger()
  27. class UploadError(Exception):
  28. def __init__(self, message, r = None, uploadId = None, parts = None):
  29. self.message = message
  30. self.r = r
  31. self.uploadId = uploadId
  32. self.parts = parts
  33. class PreventCompletionError(UploadError):
  34. 'Raised in place of completing the upload when --no-complete is active'
  35. def get_ia_access_secret(configFile = None):
  36. if 'IA_S3_ACCESS' in os.environ and 'IA_S3_SECRET' in os.environ:
  37. return os.environ['IA_S3_ACCESS'], os.environ['IA_S3_SECRET']
  38. if configFile is None:
  39. # This part of the code is identical (except for style changes) to the one in internetarchive and was written from scratch by JustAnotherArchivist in May and December 2021.
  40. candidates = []
  41. if os.environ.get('IA_CONFIG_FILE'):
  42. candidates.append(os.environ['IA_CONFIG_FILE'])
  43. xdgConfigHome = os.environ.get('XDG_CONFIG_HOME')
  44. if not xdgConfigHome or not os.path.isabs(xdgConfigHome) or not os.path.isdir(xdgConfigHome):
  45. # Per the XDG Base Dir specification, this should be $HOME/.config. Unfortunately, $HOME does not exist on all systems. Therefore, we use ~/.config here.
  46. # On a POSIX-compliant system, where $HOME must always be set, the XDG spec will be followed precisely.
  47. xdgConfigHome = os.path.join(os.path.expanduser('~'), '.config')
  48. candidates.append(os.path.join(xdgConfigHome, 'internetarchive', 'ia.ini'))
  49. candidates.append(os.path.join(os.path.expanduser('~'), '.config', 'ia.ini'))
  50. candidates.append(os.path.join(os.path.expanduser('~'), '.ia'))
  51. for candidate in candidates:
  52. if os.path.isfile(candidate):
  53. configFile = candidate
  54. break
  55. # (End of the identical code)
  56. elif not os.path.isfile(configFile):
  57. configFile = None
  58. if not configFile:
  59. raise RuntimeError('Could not find ia configuration file; did you run `ia configure`?')
  60. config = configparser.RawConfigParser()
  61. config.read(configFile)
  62. if 's3' not in config or 'access' not in config['s3'] or 'secret' not in config['s3']:
  63. raise RuntimeError('Could not read configuration; did you run `ia configure`?')
  64. access = config['s3']['access']
  65. secret = config['s3']['secret']
  66. return access, secret
  67. def metadata_to_headers(metadata):
  68. # metadata is a dict or a list of 2-tuples.
  69. # Returns the headers for the IA S3 request as a dict.
  70. headers = {}
  71. counters = collections.defaultdict(int) # How often each metadata key has been seen
  72. if isinstance(metadata, dict):
  73. metadata = metadata.items()
  74. for key, value in metadata:
  75. headers[f'x-archive-meta{counters[key]:02d}-{key.replace("_", "--")}'] = value.encode('utf-8')
  76. counters[key] += 1
  77. return headers
  78. def readinto_size_limit(fin, fout, size, blockSize = 1048576):
  79. while size:
  80. d = fin.read(min(blockSize, size))
  81. if not d:
  82. break
  83. fout.write(d)
  84. size -= len(d)
  85. @contextlib.contextmanager
  86. def file_progress_bar(f, mode, description, size = None):
  87. if size is None:
  88. pos = f.tell()
  89. f.seek(0, io.SEEK_END)
  90. size = f.tell() - pos
  91. f.seek(pos, io.SEEK_SET)
  92. if tqdm is not None:
  93. with tqdm.tqdm(total = size, unit = 'iB', unit_scale = True, unit_divisor = 1024, desc = description) as t:
  94. wrappedFile = tqdm.utils.CallbackIOWrapper(t.update, f, mode)
  95. yield wrappedFile
  96. else:
  97. # Simple progress bar that just prints a new line with elapsed time and size in MiB on every read or write
  98. processedSize = 0
  99. startTime = time.time()
  100. def _progress(inc):
  101. nonlocal processedSize
  102. processedSize += inc
  103. proc = f'{processedSize / size * 100 :.0f}%, ' if size else ''
  104. of = f' of {size / 1048576 :.2f}' if size else ''
  105. print(f'\r{description}: {proc}{processedSize / 1048576 :.2f}{of} MiB, {time.time() - startTime :.1f} s', end = '', file = sys.stderr)
  106. class Wrapper:
  107. def __init__(self, wrapped):
  108. object.__setattr__(self, '_wrapped', wrapped)
  109. def __getattr__(self, name):
  110. return getattr(self._wrapped, name)
  111. def __setattr__(self, name, value):
  112. return setattr(self._wrapped, name, value)
  113. func = getattr(f, mode)
  114. @functools.wraps(func)
  115. def _readwrite(self, *args, **kwargs):
  116. nonlocal mode
  117. res = func(*args, **kwargs)
  118. if mode == 'write':
  119. data, args = args[0], args[1:]
  120. else:
  121. data = res
  122. _progress(len(data))
  123. return res
  124. wrapper = Wrapper(f)
  125. object.__setattr__(wrapper, mode, types.MethodType(_readwrite, wrapper))
  126. yield wrapper
  127. print(f'\rdone {description}, {processedSize / 1048576 :.2f} MiB in {time.time() - startTime :.1f} seconds', file = sys.stderr) # EOL when it's done
  128. @contextlib.contextmanager
  129. def maybe_file_progress_bar(progress, f, *args, **kwargs):
  130. if progress:
  131. with file_progress_bar(f, *args, **kwargs) as r:
  132. yield r
  133. else:
  134. yield f
  135. def upload_one(url, uploadId, partNumber, data, contentMd5, size, headers, progress, tries):
  136. for attempt in range(1, tries + 1):
  137. if attempt > 1:
  138. logger.info(f'Retrying part {partNumber}')
  139. try:
  140. with maybe_file_progress_bar(progress, data, 'read', f'uploading {partNumber}', size = size) as w:
  141. r = requests.put(f'{url}?partNumber={partNumber}&uploadId={uploadId}', headers = {**headers, 'Content-MD5': contentMd5}, data = w)
  142. except (ConnectionError, requests.exceptions.RequestException) as e:
  143. err = f'error {type(e).__module__}.{type(e).__name__} {e!s}'
  144. else:
  145. if r.status_code == 200:
  146. break
  147. err = f'status {r.status_code}'
  148. sleepTime = min(3 ** attempt, 30)
  149. retrying = f', retrying after {sleepTime} seconds' if attempt < tries else ''
  150. logger.error(f'Got {err} from IA S3 on uploading part {partNumber}{retrying}')
  151. if attempt == tries:
  152. raise UploadError(f'Got {err} from IA S3 on uploading part {partNumber}', r = r, uploadId = uploadId) # parts is added in wait_first
  153. time.sleep(sleepTime)
  154. data.seek(0)
  155. return partNumber, r.headers['ETag']
  156. def wait_first(tasks, parts):
  157. task = tasks.popleft()
  158. done, _ = concurrent.futures.wait({task})
  159. assert task in done
  160. try:
  161. partNumber, eTag = task.result()
  162. except UploadError as e:
  163. # The upload task can't add an accurate parts list, so add that here and reraise
  164. e.parts = parts
  165. raise
  166. parts.append((partNumber, eTag))
  167. logger.info(f'Upload of part {partNumber} OK, ETag: {eTag}')
  168. def upload(item, filename, metadata, *, iaConfigFile = None, partSize = 100*1024*1024, tries = 3, concurrency = 1, queueDerive = True, keepOldVersion = True, complete = True, uploadId = None, parts = None, progress = True):
  169. f = sys.stdin.buffer
  170. # Read `ia` config
  171. access, secret = get_ia_access_secret(iaConfigFile)
  172. url = f'https://s3.us.archive.org/{item}/{filename}'
  173. headers = {'Authorization': f'LOW {access}:{secret}'}
  174. if uploadId is None:
  175. # Initiate multipart upload
  176. logger.info(f'Initiating multipart upload for {filename} in {item}')
  177. metadataHeaders = metadata_to_headers(metadata)
  178. r = requests.post(f'{url}?uploads', headers = {**headers, 'x-amz-auto-make-bucket': '1', **metadataHeaders})
  179. if r.status_code != 200:
  180. raise UploadError(f'Could not initiate multipart upload; got status {r.status_code} from IA S3', r = r)
  181. # Fight me!
  182. m = re.search(r'<uploadid>([^<]*)</uploadid>', r.text, re.IGNORECASE)
  183. if not m or not m[1]:
  184. raise UploadError('Could not find upload ID in IA S3 response', r = r)
  185. uploadId = m[1]
  186. logger.info(f'Got upload ID {uploadId}')
  187. # Wait for the item to exist; if the above created the item, it takes a little while for IA to actually create the bucket, and uploads would fail with a 404 until then.
  188. for attempt in range(1, tries + 1):
  189. logger.info(f'Checking for existence of {item}')
  190. r = requests.get(f'https://s3.us.archive.org/{item}/', headers = headers)
  191. if r.status_code == 200:
  192. break
  193. sleepTime = min(3 ** attempt, 30)
  194. retrying = f', retrying after {sleepTime} seconds' if attempt < tries else ''
  195. logger.error(f'Got status code {r.status_code} from IA S3 on checking for item existence{retrying}')
  196. if attempt == tries:
  197. raise UploadError('Item still does not exist', r = r, uploadId = uploadId, parts = parts)
  198. time.sleep(sleepTime)
  199. # Upload the data in parts
  200. if parts is None:
  201. parts = []
  202. tasks = collections.deque()
  203. with concurrent.futures.ThreadPoolExecutor(max_workers = concurrency) as executor:
  204. for partNumber in itertools.count(start = len(parts) + 1):
  205. while len(tasks) >= concurrency:
  206. wait_first(tasks, parts)
  207. data = io.BytesIO()
  208. with maybe_file_progress_bar(progress, data, 'write', 'reading input') as w:
  209. readinto_size_limit(f, w, partSize)
  210. data.seek(0)
  211. size = len(data.getbuffer())
  212. if not size:
  213. # We're done!
  214. break
  215. logger.info(f'Uploading part {partNumber} ({size} bytes)')
  216. logger.info('Calculating MD5')
  217. h = hashlib.md5(data.getbuffer())
  218. logger.info(f'MD5: {h.hexdigest()}')
  219. contentMd5 = base64.b64encode(h.digest()).decode('ascii')
  220. task = executor.submit(upload_one, url, uploadId, partNumber, data, contentMd5, size, headers, progress, tries)
  221. tasks.append(task)
  222. while tasks:
  223. wait_first(tasks, parts)
  224. # If --no-complete is used, raise the special error to be caught in main for pretty printing.
  225. if not complete:
  226. logger.info('Not completing upload')
  227. raise PreventCompletionError('', uploadId = uploadId, parts = parts)
  228. # Complete upload
  229. logger.info('Completing upload')
  230. # FUCKING FIGHT ME!
  231. completeData = '<CompleteMultipartUpload>' + ''.join(f'<Part><PartNumber>{partNumber}</PartNumber><ETag>{etag}</ETag></Part>' for partNumber, etag in parts) + '</CompleteMultipartUpload>'
  232. completeData = completeData.encode('utf-8')
  233. extraHeaders = {'x-archive-queue-derive': '1' if queueDerive else '0', 'x-archive-keep-old-version': '1' if keepOldVersion else '0'}
  234. for attempt in range(1, tries + 1):
  235. if attempt > 1:
  236. logger.info('Retrying completion request')
  237. r = requests.post(f'{url}?uploadId={uploadId}', headers = {**headers, **extraHeaders}, data = completeData)
  238. if r.status_code == 200:
  239. break
  240. retrying = f', retrying' if attempt < tries else ''
  241. logger.error(f'Could not complete upload; got status {r.status_code} from IA S3{retrying}')
  242. if attempt == tries:
  243. raise UploadError(f'Could not complete upload; got status {r.status_code} from IA S3', r = r, uploadId = uploadId, parts = parts)
  244. logger.info('Done!')
  245. def list_uploads(item, *, tries = 3):
  246. # No auth needed
  247. url = f'https://s3.us.archive.org/{item}/?uploads'
  248. # This endpoint redirects to the server storing the item under ia######.s3dns.us.archive.org, but those servers present an invalid TLS certificate for *.us.archive.org.
  249. class IAS3CertificateFixHTTPAdapter(requests.adapters.HTTPAdapter):
  250. def init_poolmanager(self, *args, **kwargs):
  251. kwargs['assert_hostname'] = 's3.us.archive.org'
  252. return super().init_poolmanager(*args, **kwargs)
  253. for attempt in range(1, tries + 1):
  254. r = requests.get(url, allow_redirects = False)
  255. if r.status_code == 307 and '.s3dns.us.archive.org' in r.headers['Location']:
  256. s3dnsUrl = r.headers['Location']
  257. s3dnsUrl = s3dnsUrl.replace('http://', 'https://')
  258. s3dnsUrl = s3dnsUrl.replace('.s3dns.us.archive.org:80/', '.s3dns.us.archive.org/')
  259. domain = s3dnsUrl[8:s3dnsUrl.find('/', 9)]
  260. s = requests.Session()
  261. s.mount(f'https://{domain}/', IAS3CertificateFixHTTPAdapter())
  262. r = s.get(s3dnsUrl)
  263. if r.status_code == 200:
  264. print(f'In-progress uploads for {item} (initiation datetime, upload ID, filename):')
  265. for upload in re.findall(r'<Upload>.*?</Upload>', r.text):
  266. uploadId = re.search(r'<UploadId>(.*?)</UploadId>', upload).group(1)
  267. filename = re.search(r'<Key>(.*?)</Key>', upload).group(1)
  268. date = re.search(r'<Initiated>(.*?)</Initiated>', upload).group(1)
  269. print(f'{date} {uploadId} {filename}')
  270. break
  271. retrying = f', retrying' if attempt < tries else ''
  272. logger.error(f'Could not list uploads; got status {r.status_code} from IA S3{retrying}')
  273. if attempt == tries:
  274. raise UploadError(f'Could not list uploads; got status {r.status_code} from IA S3', r = r)
  275. def abort(item, filename, uploadId, *, iaConfigFile = None, tries = 3):
  276. # Read `ia` config
  277. access, secret = get_ia_access_secret(iaConfigFile)
  278. url = f'https://s3.us.archive.org/{item}/{filename}'
  279. headers = {'Authorization': f'LOW {access}:{secret}'}
  280. # Delete upload
  281. logger.info(f'Aborting upload {uploadId}')
  282. for attempt in range(1, tries + 1):
  283. if attempt > 1:
  284. logger.info('Retrying abort request')
  285. r = requests.delete(f'{url}?uploadId={uploadId}', headers = headers)
  286. if r.status_code == 204:
  287. break
  288. retrying = f', retrying' if attempt < tries else ''
  289. logger.error(f'Could not abort upload; got status {r.status_code} from IA S3{retrying}')
  290. if attempt == tries:
  291. raise UploadError(f'Could not abort upload; got status {r.status_code} from IA S3', r = r, uploadId = uploadId)
  292. logger.info('Done!')
  293. def main():
  294. def metadata(x):
  295. if ':' not in x:
  296. raise ValueError
  297. return x.split(':', 1)
  298. def size(x):
  299. try:
  300. return int(x)
  301. except ValueError:
  302. pass
  303. if x.endswith('M'):
  304. return int(float(x[:-1]) * 1024 ** 2)
  305. elif x.endswith('G'):
  306. return int(float(x[:-1]) * 1024 ** 3)
  307. raise ValueError
  308. def parts(x):
  309. try:
  310. o = json.loads(base64.b64decode(x))
  311. except json.JSONDecodeError as e:
  312. raise ValueError from e
  313. if not isinstance(o, list) or not all(isinstance(e, list) and len(e) == 2 for e in o):
  314. raise ValueError
  315. if [i for i, _ in o] != list(range(1, len(o) + 1)):
  316. raise ValueError
  317. return o
  318. parser = argparse.ArgumentParser()
  319. parser.add_argument('--partsize', dest = 'partSize', type = size, default = size('100M'), help = 'size of each chunk to buffer in memory and upload (default: 100M = 100 MiB)')
  320. parser.add_argument('--no-derive', dest = 'queueDerive', action = 'store_false', help = 'disable queueing a derive task')
  321. parser.add_argument('--clobber', dest = 'keepOldVersion', action = 'store_false', help = 'enable clobbering existing files')
  322. parser.add_argument('--ia-config-file', dest = 'iaConfigFile', metavar = 'FILE', help = 'path to the ia CLI config file (default: search the same paths as ia)')
  323. parser.add_argument('--tries', type = int, default = 3, metavar = 'N', help = 'retry on S3 errors (default: 3)')
  324. parser.add_argument('--concurrency', '--concurrent', type = int, default = 1, metavar = 'N', help = 'upload N parts in parallel (default: 1)')
  325. parser.add_argument('--no-complete', dest = 'complete', action = 'store_false', help = 'disable completing the upload when stdin is exhausted')
  326. parser.add_argument('--no-progress', dest = 'progress', action = 'store_false', help = 'disable progress bar')
  327. parser.add_argument('--upload-id', dest = 'uploadId', help = 'upload ID when resuming or aborting an upload')
  328. parser.add_argument('--parts', type = parts, help = 'previous parts data for resumption; can only be used with --upload-id')
  329. parser.add_argument('--abort', action = 'store_true', help = 'aborts an upload; can only be used with --upload-id; most other options are ignored when this is used')
  330. parser.add_argument('--list', action = 'store_true', help = 'list in-progress uploads for item; most other options are ignored when this is used')
  331. parser.add_argument('item', help = 'identifier of the target item')
  332. parser.add_argument('filename', nargs = '?', help = 'filename to store the data to')
  333. parser.add_argument('metadata', nargs = '*', type = metadata, help = "metadata for the item in the form 'key:value'; only has an effect if the item doesn't exist yet")
  334. args = parser.parse_args()
  335. if (args.parts or args.abort) and not args.uploadId:
  336. parser.error('--parts and --abort can only be used together with --upload-id')
  337. if args.uploadId and (args.parts is not None) == bool(args.abort):
  338. parser.error('--upload-id requires exactly one of --parts and --abort')
  339. if args.abort and args.list:
  340. parser.error('--abort and --list cannot be used together')
  341. if not args.list and not args.filename:
  342. parser.error('filename is required when not using --list')
  343. logging.basicConfig(level = logging.INFO, format = '{asctime}.{msecs:03.0f} {levelname} {name} {message}', datefmt = '%Y-%m-%d %H:%M:%S', style = '{')
  344. try:
  345. if not args.abort and not args.list:
  346. upload(
  347. args.item,
  348. args.filename,
  349. args.metadata,
  350. iaConfigFile = args.iaConfigFile,
  351. partSize = args.partSize,
  352. tries = args.tries,
  353. concurrency = args.concurrency,
  354. queueDerive = args.queueDerive,
  355. keepOldVersion = args.keepOldVersion,
  356. complete = args.complete,
  357. uploadId = args.uploadId,
  358. parts = args.parts,
  359. progress = args.progress,
  360. )
  361. elif args.list:
  362. list_uploads(args.item, tries = args.tries)
  363. else:
  364. abort(
  365. args.item,
  366. args.filename,
  367. args.uploadId,
  368. iaConfigFile = args.iaConfigFile,
  369. tries = args.tries,
  370. )
  371. except (RuntimeError, UploadError) as e:
  372. if isinstance(e, PreventCompletionError):
  373. level = logging.INFO
  374. status = 0
  375. else:
  376. logger.exception('Unhandled exception raised')
  377. level = logging.WARNING
  378. status = 1
  379. if isinstance(e, UploadError):
  380. if e.r is not None:
  381. logger.info(pprint.pformat(vars(e.r.request)), exc_info = False)
  382. logger.info(pprint.pformat(vars(e.r)), exc_info = False)
  383. if e.uploadId:
  384. logger.log(level, f'Upload ID for resumption or abortion: {e.uploadId}', exc_info = False)
  385. parts = base64.b64encode(json.dumps(e.parts, separators = (',', ':')).encode('ascii')).decode('ascii')
  386. logger.log(level, f'Previous parts data for resumption: {parts}', exc_info = False)
  387. sys.exit(status)
  388. if __name__ == '__main__':
  389. main()