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.
 
 
 

353 lines
13 KiB

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