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.
 
 
 

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