Tooling for managing asset compression, storage, and retrieval
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.

628 lines
20 KiB

  1. #!/usr/bin/env python
  2. import asyncio
  3. import collections.abc
  4. import hashlib
  5. import io
  6. import json
  7. import os
  8. import platform
  9. import sys
  10. import tempfile
  11. from typing import List, Dict, Callable
  12. import click
  13. from minio import Minio, ResponseError
  14. from minio.error import NoSuchKey
  15. # Size of the buffer to read files with
  16. BUF_SIZE = 4096
  17. ###########
  18. # AsyncIO #
  19. ###########
  20. async def run_command_shell(
  21. command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, on_success: Callable = ()):
  22. """Run command in subprocess (shell).
  23. Note:
  24. This can be used if you wish to execute e.g. "copy"
  25. on Windows, which can only be executed in the shell.
  26. """
  27. process = await asyncio.create_subprocess_shell(
  28. command, stdout=stdout, stderr=stderr
  29. )
  30. process_stdout, process_stderr = await process.communicate()
  31. if process.returncode == 0:
  32. on_success()
  33. if stdout != asyncio.subprocess.DEVNULL:
  34. result = process_stdout.decode().strip()
  35. return result
  36. else:
  37. return None
  38. def make_chunks(tasks, chunk_size):
  39. """Yield successive chunk_size-sized chunks from tasks.
  40. Note:
  41. Taken from https://stackoverflow.com/a/312464
  42. modified for python 3 only
  43. """
  44. for i in range(0, len(tasks), chunk_size):
  45. yield tasks[i: i + chunk_size]
  46. def run_asyncio_commands(tasks, max_concurrent_tasks=0):
  47. """Run tasks asynchronously using asyncio and return results.
  48. If max_concurrent_tasks are set to 0, no limit is applied.
  49. Note:
  50. By default, Windows uses SelectorEventLoop, which does not support
  51. subprocesses. Therefore ProactorEventLoop is used on Windows.
  52. https://docs.python.org/3/library/asyncio-eventloops.html#windows
  53. """
  54. all_results = []
  55. if max_concurrent_tasks == 0:
  56. chunks = [tasks]
  57. num_chunks = len(chunks)
  58. else:
  59. chunks = make_chunks(tasks=tasks, chunk_size=max_concurrent_tasks)
  60. num_chunks = len(list(make_chunks(tasks=tasks, chunk_size=max_concurrent_tasks)))
  61. if asyncio.get_event_loop().is_closed():
  62. asyncio.set_event_loop(asyncio.new_event_loop())
  63. if platform.system() == "Windows":
  64. asyncio.set_event_loop(asyncio.ProactorEventLoop())
  65. loop = asyncio.get_event_loop()
  66. chunk = 1
  67. for tasks_in_chunk in chunks:
  68. commands = asyncio.gather(*tasks_in_chunk)
  69. results = loop.run_until_complete(commands)
  70. all_results += results
  71. chunk += 1
  72. loop.close()
  73. return all_results
  74. ###########
  75. # Helpers #
  76. ###########
  77. def update(d, u):
  78. for k, v in u.items():
  79. if isinstance(v, collections.abc.Mapping):
  80. d[k] = update(d.get(k, {}), v)
  81. else:
  82. d[k] = v
  83. return d
  84. def get_metadata_name(key):
  85. return METADATA_PREFIX + 'SHA256SUM'.capitalize()
  86. def get_clean_stdin_iterator(stdin_stream):
  87. return (line for line in [line.strip() for line in stdin_stream if line.strip() != ''])
  88. def strip_prefix(prefix: str, file: str) -> str:
  89. if file.startswith(prefix):
  90. return file.replace(prefix, '')
  91. return file
  92. def get_file_identity(ctx_obj, file):
  93. if 'REMOVE_PREFIX' in ctx_obj and ctx_obj['REMOVE_PREFIX'] is not None:
  94. path = strip_prefix(ctx_obj['REMOVE_PREFIX'], file)
  95. else:
  96. path = file
  97. if os.pathsep != '/':
  98. path = '/'.join(path.split(os.pathsep))
  99. return path
  100. def list_s3_dir(s3: Minio, bucket: str, prefix: str) -> List[str]:
  101. found_files = []
  102. for obj in s3.list_objects_v2(bucket, prefix=prefix):
  103. if obj.is_dir:
  104. found_files.extend(list_s3_dir(s3, bucket, obj.object_name))
  105. else:
  106. found_files.append(obj.object_name)
  107. return found_files
  108. def get_s3_client(config: any) -> Minio:
  109. host = config['host']
  110. secure = config['secure']
  111. access_key = config['access']
  112. secret_key = config['secret']
  113. return Minio(host, secure=secure, access_key=access_key, secret_key=secret_key)
  114. def prep_s3(ctx):
  115. s3_config = ctx.obj['CONFIG']['s3']
  116. s3_bucket = ctx.obj['CONTEXT']
  117. s3 = get_s3_client(s3_config)
  118. if not s3.bucket_exists(s3_bucket):
  119. s3.make_bucket(s3_bucket)
  120. return s3_bucket, s3
  121. def get_file_sha256sum(stored_data, profile, file):
  122. stored_file_hash = stored_data['sha256sum']
  123. stored_profile_hash = stored_data['profileHash']
  124. sha256sum = hashlib.sha256()
  125. with open(file, 'rb') as f:
  126. for byte_block in iter(lambda: f.read(BUF_SIZE), b""):
  127. sha256sum.update(byte_block)
  128. calculated_file_hash = sha256sum.hexdigest()
  129. return stored_profile_hash, stored_file_hash, calculated_file_hash
  130. def get_string_sha256sum(string: str, encoding='utf-8') -> str:
  131. sha256sum = hashlib.sha256()
  132. with io.BytesIO(json.dumps(string).encode(encoding)) as c:
  133. for byte_block in iter(lambda: c.read(BUF_SIZE), b''):
  134. sha256sum.update(byte_block)
  135. return sha256sum.hexdigest()
  136. def add_nested_key(config: Dict[str, any], path: List[str], value: str) -> bool:
  137. target = path[0].lower()
  138. if len(path) == 1:
  139. config[target] = value
  140. return True
  141. else:
  142. if target not in config:
  143. config[target] = {}
  144. add_nested_key(config[target], path[1:],value)
  145. return False
  146. def read_env_config(prefix, separator='__') -> any:
  147. prefix = prefix+separator
  148. env_config = {}
  149. environment_variables = [env for env in os.environ.keys() if env.startswith(prefix)]
  150. for env in environment_variables:
  151. path = env[len(prefix):].split('__')
  152. add_nested_key(env_config, path, os.environ[env])
  153. return env_config
  154. def load_config(path: str) -> any:
  155. combined_config = {}
  156. with open(
  157. os.path.join(
  158. os.path.dirname(os.path.realpath(__file__)),
  159. 'acm-config-default.json'),
  160. 'r') as combined_config_file:
  161. combined_config = json.load(combined_config_file)
  162. config = {}
  163. with open(path, 'r') as config_file:
  164. config = json.load(config_file)
  165. # Setup concurrency
  166. if 'concurrency' in config:
  167. config['concurrency'] = abs(int(config['concurrency']))
  168. else:
  169. config['concurrency'] = 0
  170. update(combined_config, config)
  171. update(combined_config, read_env_config('ACM'))
  172. # Calculate profiles hash
  173. profile_hashes={}
  174. profile_hashes['all'] = get_string_sha256sum(json.dumps(combined_config['profiles']))
  175. for profile in combined_config['profiles'].keys():
  176. profile_hashes[profile] = get_string_sha256sum(json.dumps(combined_config['profiles'][profile]))
  177. combined_config['profileHashes'] = profile_hashes
  178. return combined_config
  179. @click.group()
  180. @click.option('-d', '--debug/--no-debug', default=False)
  181. @click.option('-c', '--config', default=lambda: os.path.join(os.getcwd(), 'acm-config.json'), show_default=True)
  182. @click.option('-s', '--stdin/--no-stdin', default=False)
  183. @click.option('--remove-prefix', default=None)
  184. @click.option('--add-prefix', default=None)
  185. @click.pass_context
  186. def cli(ctx, debug, config, stdin, remove_prefix, add_prefix):
  187. ctx.ensure_object(dict)
  188. ctx.obj['DEBUG'] = debug
  189. ctx.obj['CONFIG'] = load_config(config)
  190. ctx.obj['READ_STDIN'] = stdin
  191. ctx.obj['REMOVE_PREFIX'] = remove_prefix
  192. ctx.obj['ADD_PREFIX'] = add_prefix
  193. ####################
  194. # Generic Commands #
  195. ####################
  196. @cli.command(name="config")
  197. @click.pass_context
  198. def print_config(ctx):
  199. print(json.dumps(ctx.obj['CONFIG'], indent=2, sort_keys=True))
  200. ###############################
  201. # S3 Storage Focused Commands #
  202. ###############################
  203. @cli.command(name="list")
  204. @click.option('--sha256sum/--no-sha256sum', default=False)
  205. @click.option('--suffix', default=None)
  206. @click.option('-x', '--context', required=True)
  207. @click.option('--print-identity/--no-print-identity', default=False)
  208. @click.pass_context
  209. def list_files(ctx, context, sha256sum, suffix, print_identity):
  210. ctx.obj['CONTEXT'] = context
  211. s3_config = ctx.obj['CONFIG']['s3']
  212. s3_bucket = ctx.obj['CONTEXT']
  213. s3 = get_s3_client(s3_config)
  214. if not s3.bucket_exists(s3_bucket):
  215. s3.make_bucket(s3_bucket)
  216. found_files: List[str] = []
  217. found_objects: List[str] = []
  218. for obj in s3.list_objects_v2(s3_bucket, recursive=False):
  219. if obj.is_dir:
  220. found_objects.extend(list_s3_dir(s3, s3_bucket, obj.object_name))
  221. else:
  222. found_objects.append(obj.object_name)
  223. for obj in found_objects:
  224. file = obj
  225. if 'REMOVE_PREFIX' in ctx.obj and ctx.obj['REMOVE_PREFIX'] is not None:
  226. file = os.path.join(ctx.obj['REMOVE_PREFIX'], file)
  227. if suffix is not None and suffix in file:
  228. file = file.replace(suffix, '')
  229. file = file.strip()
  230. if sha256sum:
  231. file_object = s3.get_object(s3_bucket, obj)
  232. stored_data = json.load(file_object)
  233. sha256sum_value = stored_data['sha256sum']
  234. file = f'{sha256sum_value} {file}'
  235. elif print_identity:
  236. file_object = s3.get_object(s3_bucket, obj)
  237. stored_data = json.load(file_object)
  238. found_files.append(stored_data['storedAssetIdentity'])
  239. else:
  240. found_files.append(file)
  241. print(os.linesep.join(found_files))
  242. @cli.command(name="match")
  243. @click.option('-x', '--context', required=True)
  244. @click.option('--print-identity/--no-print-identity', default=False)
  245. @click.option('-p', '--profile', default='all')
  246. @click.argument('files', nargs=-1)
  247. @click.pass_context
  248. def check_matched_files_hashes(ctx, context, print_identity, profile, files):
  249. """
  250. List all files that have matching stored sha256sum and profile hash
  251. """
  252. ctx.obj['CONTEXT'] = context
  253. s3_bucket, s3 = prep_s3(ctx)
  254. matching_files: List[str] = []
  255. if ctx.obj['READ_STDIN']:
  256. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  257. for file in files:
  258. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  259. try:
  260. file_object = s3.get_object(s3_bucket, file_identity)
  261. stored_data = json.load(file_object)
  262. stored_profile_hash, stored_file_hash, calculated_file_hash = get_file_sha256sum(stored_data, profile, file)
  263. if calculated_file_hash == stored_file_hash \
  264. and ctx.obj['CONFIG']['profileHashes'][profile] == stored_profile_hash:
  265. if print_identity:
  266. matching_files.append(stored_data['storedAssetIdentity'])
  267. else:
  268. matching_files.append(file)
  269. except NoSuchKey as e:
  270. continue
  271. except ValueError or ResponseError as e:
  272. print(f'ERROR: {file} {e}')
  273. print(os.linesep.join(matching_files))
  274. @cli.command(name="check")
  275. @click.option('-x', '--context', required=True)
  276. @click.option('-p', '--profile', default='all')
  277. @click.argument('files', nargs=-1)
  278. @click.pass_context
  279. def check_changed_files_hashes(ctx, context, profile, files):
  280. """
  281. List all files that do not have a matching sha256sum or profile hash
  282. """
  283. ctx.obj['CONTEXT'] = context
  284. s3_bucket, s3 = prep_s3(ctx)
  285. changed_files: List[str] = []
  286. if ctx.obj['READ_STDIN']:
  287. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  288. for file in files:
  289. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  290. try:
  291. file_object = s3.get_object(s3_bucket, file_identity)
  292. stored_data = json.load(file_object)
  293. stored_profile_hash, stored_file_hash, calculated_file_hash = get_file_sha256sum(stored_data, profile, file)
  294. if calculated_file_hash != stored_file_hash \
  295. or ctx.obj['CONFIG']['profileHashes'][profile] != stored_profile_hash:
  296. changed_files.append(file)
  297. except NoSuchKey as e:
  298. changed_files.append(file)
  299. except ValueError or ResponseError as e:
  300. print(f'ERROR: {file} {e}')
  301. print(os.linesep.join(changed_files))
  302. @cli.command(name="update")
  303. @click.option('-x', '--context', required=True)
  304. @click.option('--input-and-identity/--no-input-and-identity', default=False)
  305. @click.option('-p', '--profile', default='all')
  306. @click.argument('files', nargs=-1)
  307. @click.pass_context
  308. def update_changed_files_hashes(ctx, context, input_and_identity, profile, files):
  309. """
  310. Store new data objects for the provided files
  311. """
  312. ctx.obj['CONTEXT'] = context
  313. s3_bucket, s3 = prep_s3(ctx)
  314. updated_files: List[str] = []
  315. if ctx.obj['READ_STDIN']:
  316. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  317. for file in files:
  318. identity = None
  319. if input_and_identity:
  320. file, identity = file.split('\t')
  321. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  322. try:
  323. sha256sum = hashlib.sha256()
  324. with open(file, 'rb') as f:
  325. for byte_block in iter(lambda: f.read(BUF_SIZE), b''):
  326. sha256sum.update(byte_block)
  327. calculated_file_hash = sha256sum.hexdigest()
  328. object_data = {
  329. "sourcePath": file,
  330. "storedAssetIdentity": identity,
  331. "identity": file_identity,
  332. "sha256sum": calculated_file_hash,
  333. "profileHash": ctx.obj['CONFIG']['profileHashes'][profile]
  334. }
  335. with io.BytesIO(json.dumps(object_data, sort_keys=True, indent=None).encode('utf-8')) as data:
  336. data.seek(0, os.SEEK_END)
  337. data_length = data.tell()
  338. data.seek(0)
  339. s3.put_object(
  340. s3_bucket,
  341. file_identity,
  342. data,
  343. data_length,
  344. content_type="application/json",
  345. metadata={}
  346. )
  347. updated_files.append(file)
  348. except ValueError or ResponseError as e:
  349. print(f'ERROR: {file} {e}')
  350. print(os.linesep.join(updated_files))
  351. @cli.command(name="store")
  352. @click.option('-x', '--context', required=True)
  353. @click.argument('files', nargs=-1)
  354. @click.pass_context
  355. def store_files(ctx, context, files):
  356. """
  357. Store specified files in a <context> bucket for retrieval.
  358. """
  359. ctx.obj['CONTEXT'] = context
  360. s3_bucket, s3 = prep_s3(ctx)
  361. stored_files: List[str] = []
  362. if ctx.obj['READ_STDIN']:
  363. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  364. for file in files:
  365. file_identity = get_file_identity(ctx.obj, file)
  366. try:
  367. s3.fput_object(
  368. s3_bucket,
  369. file_identity,
  370. file,
  371. content_type="application/octet-stream"
  372. )
  373. if 'ADD_PREFIX' in ctx.obj and ctx.obj['ADD_PREFIX'] is not None:
  374. stored_files.append(os.path.join(ctx.obj['ADD_PREFIX'], file_identity))
  375. else:
  376. stored_files.append(file)
  377. except ResponseError as e:
  378. print(f'ERROR: {file} {e}', file=sys.stderr)
  379. print(os.linesep.join(stored_files))
  380. @cli.command(name="retrieve")
  381. @click.option('-x', '--context', required=True)
  382. @click.option('-d', '--destination', default=None)
  383. @click.argument('files', nargs=-1)
  384. @click.pass_context
  385. def retrieve_files(ctx, context, destination, files):
  386. """
  387. Retrieve specified files from a <context> bucket
  388. """
  389. ctx.obj['CONTEXT'] = context
  390. s3_bucket, s3 = prep_s3(ctx)
  391. retrieved_files: List[str] = []
  392. if ctx.obj['READ_STDIN']:
  393. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  394. for file in files:
  395. file_identity = get_file_identity(ctx.obj, file)
  396. file_destination = file
  397. if destination is not None:
  398. file_destination = os.path.join(destination, file_identity)
  399. try:
  400. s3.fget_object(
  401. s3_bucket,
  402. file_identity,
  403. file_destination
  404. )
  405. retrieved_files.append(file_destination)
  406. except NoSuchKey as e:
  407. print(f'ERROR: {file_identity} {file_destination} {e}', file=sys.stderr)
  408. except ResponseError as e:
  409. print(f'ERROR: {file_destination} {e}', file=sys.stderr)
  410. print(os.linesep.join(retrieved_files))
  411. ######################################
  412. # Asset Compression Focused Commands #
  413. ######################################
  414. @cli.command(name="compress")
  415. @click.option('-p', '--profile', default='default')
  416. @click.option('-c', '--content', default='all')
  417. @click.option('-d', '--destination', default=None)
  418. @click.option('--print-input-and-identity/--no-print-input-and-identity', default=False)
  419. @click.argument('files', nargs=-1)
  420. @click.pass_context
  421. def compress_assets(ctx, profile, content, destination, print_input_and_identity, files):
  422. profiles = ctx.obj['CONFIG']['profiles']
  423. if profile not in profiles:
  424. raise ValueError(f'Unrecognized profile: {profile}')
  425. default_profile: Dict[str, any] = profiles['default']
  426. profile: Dict[str, any] = profiles[profile]
  427. if content != 'all':
  428. if content not in profile and content not in default_profile:
  429. raise ValueError(f'Unrecognized content: {content}')
  430. content_configurations = []
  431. if content == 'all':
  432. content_names: set = set()
  433. for content_name in profile.keys():
  434. content_names.add(content_name)
  435. content_configurations.append(profile[content_name])
  436. for content_name in default_profile.keys():
  437. if content_name not in content_names:
  438. content_names.add(content_name)
  439. content_configurations.append(default_profile[content_name])
  440. else:
  441. if content in profile:
  442. content_configurations.append(profile[content])
  443. else:
  444. content_configurations.append(default_profile[content])
  445. if ctx.obj['READ_STDIN']:
  446. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  447. if destination is None:
  448. destination = tempfile.mkdtemp()
  449. compressed_files = []
  450. tasks = []
  451. def store_filename(storage_list: List[str], filename: str):
  452. """
  453. A simple lambda wrapper to asynchronously add processed files to the list
  454. :param storage_list:
  455. :param filename:
  456. :return:
  457. """
  458. return lambda: storage_list.append(filename)
  459. for input_file in files:
  460. for content_configuration in content_configurations:
  461. if any([input_file.endswith(extension) for extension in content_configuration['extensions']]):
  462. file = input_file
  463. if 'REMOVE_PREFIX' in ctx.obj and ctx.obj['REMOVE_PREFIX'] is not None:
  464. file = strip_prefix(ctx.obj['REMOVE_PREFIX'], input_file)
  465. if 'preserveInputExtension' in content_configuration \
  466. and content_configuration['preserveInputExtension']:
  467. output_file = os.path.join(destination, file)
  468. else:
  469. output_file_without_ext = os.path.splitext(os.path.join(destination, file))[0]
  470. output_file = f'{output_file_without_ext}.{content_configuration["outputExtension"]}'
  471. output_file_identity = get_file_identity({'REMOVE_PREFIX': destination}, output_file)
  472. output_file_dir = os.path.dirname(output_file)
  473. os.makedirs(output_file_dir, exist_ok=True)
  474. command: str = content_configuration['command'] \
  475. .replace('{{input_file}}', f'\'{input_file}\'') \
  476. .replace('{{output_file}}', f'\'{output_file}\'')
  477. tasks.append(
  478. run_command_shell(
  479. command,
  480. stdout=asyncio.subprocess.DEVNULL,
  481. stderr=asyncio.subprocess.DEVNULL,
  482. on_success=store_filename(
  483. compressed_files,
  484. f'{input_file}\t{output_file_identity}' if print_input_and_identity else output_file
  485. )
  486. )
  487. )
  488. results = run_asyncio_commands(
  489. tasks, max_concurrent_tasks=ctx.obj['CONFIG']['concurrency']
  490. )
  491. print(os.linesep.join(compressed_files))
  492. if __name__ == '__main__':
  493. cli(obj={})