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.
 
 
 

269 lines
11 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 hashlib
  8. import itertools
  9. import json
  10. import logging
  11. import os
  12. import pprint
  13. import re
  14. import requests
  15. import sys
  16. import time
  17. logger = logging.getLogger()
  18. class UploadError(Exception):
  19. def __init__(self, message, r = None, uploadId = None, parts = None):
  20. self.message = message
  21. self.r = r
  22. self.uploadId = uploadId
  23. self.parts = parts
  24. class PreventCompletionError(UploadError):
  25. 'Raised in place of completing the upload when --no-complete is active'
  26. def get_ia_access_secret(configFile = None):
  27. if configFile is None:
  28. # 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 2021.
  29. xdgConfigHome = os.environ.get('XDG_CONFIG_HOME')
  30. if not xdgConfigHome or not os.path.isabs(xdgConfigHome) or not os.path.isdir(xdgConfigHome):
  31. # Per the XDG Base Dir specification, this should be $HOME/.config. Unfortunately, $HOME does not exist on all systems. Therefore, we use ~/.config here.
  32. # On a POSIX-compliant system, where $HOME must always be set, the XDG spec will be followed precisely.
  33. xdgConfigHome = os.path.join(os.path.expanduser('~'), '.config')
  34. for candidate in [os.path.join(xdgConfigHome, 'internetarchive', 'ia.ini'),
  35. os.path.join(os.path.expanduser('~'), '.config', 'ia.ini'),
  36. os.path.join(os.path.expanduser('~'), '.ia')]:
  37. if os.path.isfile(candidate):
  38. configFile = candidate
  39. break
  40. # (End of the identical code)
  41. elif not os.path.isfile(configFile):
  42. configFile = None
  43. if not configFile:
  44. raise RuntimeError('Could not find ia configuration file; did you run `ia configure`?')
  45. config = configparser.RawConfigParser()
  46. config.read(configFile)
  47. if 's3' not in config or 'access' not in config['s3'] or 'secret' not in config['s3']:
  48. raise RuntimeError('Could not read configuration; did you run `ia configure`?')
  49. access = config['s3']['access']
  50. secret = config['s3']['secret']
  51. return access, secret
  52. def metadata_to_headers(metadata):
  53. # metadata is a dict or a list of 2-tuples.
  54. # Returns the headers for the IA S3 request as a dict.
  55. headers = {}
  56. counters = collections.defaultdict(int) # How often each metadata key has been seen
  57. if isinstance(metadata, dict):
  58. metadata = metadata.items()
  59. for key, value in metadata:
  60. headers[f'x-archive-meta{counters[key]:02d}-{key.replace("_", "--")}'] = value.encode('utf-8')
  61. counters[key] += 1
  62. return headers
  63. def upload(item, filename, metadata, *, iaConfigFile = None, partSize = 4, tries = 3, queueDerive = True, keepOldVersion = True, complete = True, uploadId = None, parts = None):
  64. f = sys.stdin.buffer
  65. # Read `ia` config
  66. access, secret = get_ia_access_secret(iaConfigFile)
  67. url = f'https://s3.us.archive.org/{item}/{filename}'
  68. headers = {'Authorization': f'LOW {access}:{secret}'}
  69. if uploadId is None:
  70. # Initiate multipart upload
  71. logger.info(f'Initiating multipart upload for {filename} in {item}')
  72. metadataHeaders = metadata_to_headers(metadata)
  73. r = requests.post(f'{url}?uploads', headers = {**headers, 'x-amz-auto-make-bucket': '1', **metadataHeaders})
  74. if r.status_code != 200:
  75. raise UploadError(f'Could not initiate multipart upload; got status {r.status_code} from IA S3', r = r)
  76. # Fight me!
  77. m = re.search(r'<uploadid>([^<]*)</uploadid>', r.text, re.IGNORECASE)
  78. if not m or not m[1]:
  79. raise UploadError('Could not find upload ID in IA S3 response', r = r)
  80. uploadId = m[1]
  81. logger.info(f'Got upload ID {uploadId}')
  82. # Upload the data in parts
  83. if parts is None:
  84. parts = []
  85. for partNumber in itertools.count(start = len(parts) + 1):
  86. data = f.read(partSize)
  87. if not data:
  88. # We're done!
  89. break
  90. logger.info(f'Uploading part {partNumber} ({len(data)} bytes)')
  91. logger.info('Calculating MD5')
  92. h = hashlib.md5(data)
  93. logger.info(f'MD5: {h.hexdigest()}')
  94. contentMd5 = base64.b64encode(h.digest()).decode('ascii')
  95. for attempt in range(1, tries + 1):
  96. if attempt > 1:
  97. logger.info(f'Retrying part {partNumber}')
  98. try:
  99. r = requests.put(f'{url}?partNumber={partNumber}&uploadId={uploadId}', headers = {**headers, 'Content-MD5': contentMd5}, data = data)
  100. except (ConnectionError, requests.exceptions.RequestException) as e:
  101. err = f'error {type(e).__module__}.{type(e).__name__} {e!s}'
  102. else:
  103. if r.status_code == 200:
  104. break
  105. err = f'status {r.status_code}'
  106. sleepTime = min(3 ** attempt, 30)
  107. retrying = f', retrying after {sleepTime} seconds' if attempt < tries else ''
  108. logger.error(f'Got {err} from IA S3 on uploading part {partNumber}{retrying}')
  109. if attempt == tries:
  110. raise UploadError(f'Got {err} from IA S3 on uploading part {partNumber}', r = r, uploadId = uploadId, parts = parts)
  111. time.sleep(sleepTime)
  112. logger.info(f'Upload OK, ETag: {r.headers["ETag"]}')
  113. parts.append((partNumber, r.headers['ETag']))
  114. # If --no-complete is used, raise the special error to be caught in main for pretty printing.
  115. if not complete:
  116. logger.info('Not completing upload')
  117. raise PreventCompletionError('', uploadId = uploadId, parts = parts)
  118. # Complete upload
  119. logger.info('Completing upload')
  120. # FUCKING FIGHT ME!
  121. completeData = '<CompleteMultipartUpload>' + ''.join(f'<Part><PartNumber>{partNumber}</PartNumber><ETag>{etag}</ETag></Part>' for partNumber, etag in parts) + '</CompleteMultipartUpload>'
  122. completeData = completeData.encode('utf-8')
  123. extraHeaders = {'x-archive-queue-derive': '1' if queueDerive else '0', 'x-archive-keep-old-version': '1' if keepOldVersion else '0'}
  124. for attempt in range(1, tries + 1):
  125. if attempt > 1:
  126. logger.info('Retrying completion request')
  127. r = requests.post(f'{url}?uploadId={uploadId}', headers = {**headers, **extraHeaders}, data = completeData)
  128. if r.status_code == 200:
  129. break
  130. retrying = f', retrying' if attempt < tries else ''
  131. logger.error(f'Could not complete upload; got status {r.status_code} from IA S3{retrying}')
  132. if attempt == tries:
  133. raise UploadError(f'Could not complete upload; got status {r.status_code} from IA S3', r = r, uploadId = uploadId, parts = parts)
  134. logger.info('Done!')
  135. def abort(item, filename, uploadId, *, iaConfigFile = None, tries = 3):
  136. # Read `ia` config
  137. access, secret = get_ia_access_secret(iaConfigFile)
  138. url = f'https://s3.us.archive.org/{item}/{filename}'
  139. headers = {'Authorization': f'LOW {access}:{secret}'}
  140. # Delete upload
  141. logger.info(f'Aborting upload {uploadId}')
  142. for attempt in range(1, tries + 1):
  143. if attempt > 1:
  144. logger.info('Retrying abort request')
  145. r = requests.delete(f'{url}?uploadId={uploadId}', headers = headers)
  146. if r.status_code == 204:
  147. break
  148. retrying = f', retrying' if attempt < tries else ''
  149. logger.error(f'Could not abort upload; got status {r.status_code} from IA S3{retrying}')
  150. if attempt == tries:
  151. raise UploadError(f'Could not abort upload; got status {r.status_code} from IA S3', r = r, uploadId = uploadId)
  152. logger.info('Done!')
  153. def main():
  154. def metadata(x):
  155. if ':' not in x:
  156. raise ValueError
  157. return x.split(':', 1)
  158. def size(x):
  159. try:
  160. return int(x)
  161. except ValueError:
  162. pass
  163. if x.endswith('M'):
  164. return int(x[:-1]) * 1024 ** 2
  165. elif x.endswith('G'):
  166. return int(x[:-1]) * 1024 ** 3
  167. raise ValueError
  168. def parts(x):
  169. try:
  170. o = json.loads(base64.b64decode(x))
  171. except json.JSONDecodeError as e:
  172. raise ValueError from e
  173. if not isinstance(o, list) or not all(isinstance(e, list) and len(e) == 2 for e in o):
  174. raise ValueError
  175. if [i for i, _ in o] != list(range(1, len(o) + 1)):
  176. raise ValueError
  177. return o
  178. parser = argparse.ArgumentParser()
  179. 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)')
  180. parser.add_argument('--no-derive', dest = 'queueDerive', action = 'store_false', help = 'disable queueing a derive task')
  181. parser.add_argument('--clobber', dest = 'keepOldVersion', action = 'store_false', help = 'enable clobbering existing files')
  182. 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)')
  183. parser.add_argument('--tries', type = int, default = 3, metavar = 'N', help = 'retry on S3 errors (default: 3)')
  184. parser.add_argument('--no-complete', dest = 'complete', action = 'store_false', help = 'disable completing the upload when stdin is exhausted')
  185. parser.add_argument('--upload-id', dest = 'uploadId', help = 'upload ID when resuming or aborting an upload')
  186. parser.add_argument('--parts', type = parts, help = 'previous parts data for resumption; can only be used with --upload-id')
  187. 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')
  188. parser.add_argument('item', help = 'identifier of the target item')
  189. parser.add_argument('filename', help = 'filename to store the data to')
  190. 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")
  191. args = parser.parse_args()
  192. if (args.parts or args.abort) and not args.uploadId:
  193. parser.error('--parts and --abort can only be used together with --upload-id')
  194. if args.uploadId and bool(args.parts) == bool(args.abort):
  195. parser.error('--upload-id requires exactly one of --parts and --abort')
  196. logging.basicConfig(level = logging.INFO, format = '{asctime}.{msecs:03.0f} {levelname} {name} {message}', datefmt = '%Y-%m-%d %H:%M:%S', style = '{')
  197. try:
  198. if not args.abort:
  199. upload(
  200. args.item,
  201. args.filename,
  202. args.metadata,
  203. iaConfigFile = args.iaConfigFile,
  204. partSize = args.partSize,
  205. tries = args.tries,
  206. queueDerive = args.queueDerive,
  207. keepOldVersion = args.keepOldVersion,
  208. complete = args.complete,
  209. uploadId = args.uploadId,
  210. parts = args.parts,
  211. )
  212. else:
  213. abort(
  214. args.item,
  215. args.filename,
  216. args.uploadId,
  217. iaConfigFile = args.iaConfigFile,
  218. tries = args.tries,
  219. )
  220. except (RuntimeError, UploadError) as e:
  221. if isinstance(e, PreventCompletionError):
  222. level = logging.INFO
  223. else:
  224. logger.exception('Unhandled exception raised')
  225. level = logging.WARNING
  226. if isinstance(e, UploadError):
  227. if e.r is not None:
  228. logger.info(pprint.pformat(vars(e.r.request)), exc_info = False)
  229. logger.info(pprint.pformat(vars(e.r)), exc_info = False)
  230. if e.uploadId:
  231. logger.log(level, f'Upload ID for resumption or abortion: {e.uploadId}', exc_info = False)
  232. if e.parts:
  233. parts = base64.b64encode(json.dumps(e.parts, separators = (',', ':')).encode('ascii')).decode('ascii')
  234. logger.log(level, f'Previous parts data for resumption: {parts}', exc_info = False)
  235. if __name__ == '__main__':
  236. main()