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.
 
 
 

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