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.

626 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 S3 Settings
  166. config['s3']['access'] = os.getenv('ACM_S3_ACCESS')
  167. config['s3']['secret'] = os.getenv('ACM_S3_SECRET')
  168. # Setup concurrency
  169. if 'concurrency' in config:
  170. config['concurrency'] = abs(int(config['concurrency']))
  171. else:
  172. config['concurrency'] = 0
  173. update(combined_config, config)
  174. update(combined_config, read_env_config('ACM'))
  175. # Calculate profiles hash
  176. profile_hashes={}
  177. profile_hashes['all'] = get_string_sha256sum(json.dumps(combined_config['profiles']))
  178. for profile in combined_config['profiles'].keys():
  179. profile_hashes[profile] = get_string_sha256sum(json.dumps(combined_config['profiles'][profile]))
  180. combined_config['profileHashes'] = profile_hashes
  181. return combined_config
  182. @click.group()
  183. @click.option('-d', '--debug/--no-debug', default=False)
  184. @click.option('-c', '--config', default=lambda: os.path.join(os.getcwd(), 'acm-config.json'), show_default=True)
  185. @click.option('-s', '--stdin/--no-stdin', default=False)
  186. @click.option('--remove-prefix', default=None)
  187. @click.option('--add-prefix', default=None)
  188. @click.pass_context
  189. def cli(ctx, debug, config, stdin, remove_prefix, add_prefix):
  190. ctx.ensure_object(dict)
  191. ctx.obj['DEBUG'] = debug
  192. ctx.obj['CONFIG'] = load_config(config)
  193. ctx.obj['READ_STDIN'] = stdin
  194. ctx.obj['REMOVE_PREFIX'] = remove_prefix
  195. ctx.obj['ADD_PREFIX'] = add_prefix
  196. ####################
  197. # Generic Commands #
  198. ####################
  199. @cli.command(name="config")
  200. @click.pass_context
  201. def print_config(ctx):
  202. print(json.dumps(ctx.obj['CONFIG'], indent=2, sort_keys=True))
  203. ###############################
  204. # S3 Storage Focused Commands #
  205. ###############################
  206. @cli.command(name="list")
  207. @click.option('--sha256sum/--no-sha256sum', default=False)
  208. @click.option('--suffix', default=None)
  209. @click.option('-x', '--context', required=True)
  210. @click.pass_context
  211. def list_files(ctx, context, sha256sum, suffix):
  212. ctx.obj['CONTEXT'] = context
  213. s3_config = ctx.obj['CONFIG']['s3']
  214. s3_bucket = ctx.obj['CONTEXT']
  215. s3 = get_s3_client(s3_config)
  216. if not s3.bucket_exists(s3_bucket):
  217. s3.make_bucket(s3_bucket)
  218. found_files: List[str] = []
  219. found_objects: List[str] = []
  220. for obj in s3.list_objects_v2(s3_bucket, recursive=False):
  221. if obj.is_dir:
  222. found_objects.extend(list_s3_dir(s3, s3_bucket, obj.object_name))
  223. else:
  224. found_objects.append(obj.object_name)
  225. for obj in found_objects:
  226. file = obj
  227. if 'REMOVE_PREFIX' in ctx.obj and ctx.obj['REMOVE_PREFIX'] is not None:
  228. file = os.path.join(ctx.obj['REMOVE_PREFIX'], file)
  229. if suffix is not None and suffix in file:
  230. file = file.replace(suffix, '')
  231. file = file.strip()
  232. if sha256sum:
  233. stat = s3.stat_object(s3_bucket, obj)
  234. sha256sum_value = stat.metadata[get_metadata_name("SHA256SUM")]
  235. file = f'{sha256sum_value} {file}'
  236. found_files.append(file)
  237. print(os.linesep.join(found_files))
  238. @cli.command(name="match")
  239. @click.option('-x', '--context', required=True)
  240. @click.option('--print-identity/--no-print-identity', default=False)
  241. @click.option('-p', '--profile', default='all')
  242. @click.argument('files', nargs=-1)
  243. @click.pass_context
  244. def check_matched_files_hashes(ctx, context, print_identity, profile, files):
  245. """
  246. List all files that have matching stored sha256sum and profile hash
  247. """
  248. ctx.obj['CONTEXT'] = context
  249. s3_bucket, s3 = prep_s3(ctx)
  250. matching_files: List[str] = []
  251. if ctx.obj['READ_STDIN']:
  252. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  253. for file in files:
  254. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  255. try:
  256. file_object = s3.get_object(s3_bucket, file_identity)
  257. stored_data = json.load(file_object)
  258. stored_profile_hash, stored_file_hash, calculated_file_hash = get_file_sha256sum(stored_data, profile, file)
  259. if calculated_file_hash == stored_file_hash \
  260. and ctx.obj['CONFIG']['profileHashes'][profile] == stored_profile_hash:
  261. if print_identity:
  262. matching_files.append(stored_data['storedAssetIdentity'])
  263. else:
  264. matching_files.append(file)
  265. except NoSuchKey as e:
  266. continue
  267. except ValueError or ResponseError as e:
  268. print(f'ERROR: {file} {e}')
  269. print(os.linesep.join(matching_files))
  270. @cli.command(name="check")
  271. @click.option('-x', '--context', required=True)
  272. @click.option('-p', '--profile', default='all')
  273. @click.argument('files', nargs=-1)
  274. @click.pass_context
  275. def check_changed_files_hashes(ctx, context, profile, files):
  276. """
  277. List all files that do not have a matching sha256sum or profile hash
  278. """
  279. ctx.obj['CONTEXT'] = context
  280. s3_bucket, s3 = prep_s3(ctx)
  281. changed_files: List[str] = []
  282. if ctx.obj['READ_STDIN']:
  283. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  284. for file in files:
  285. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  286. try:
  287. file_object = s3.get_object(s3_bucket, file_identity)
  288. stored_data = json.load(file_object)
  289. stored_profile_hash, stored_file_hash, calculated_file_hash = get_file_sha256sum(stored_data, profile, file)
  290. if calculated_file_hash != stored_file_hash \
  291. or ctx.obj['CONFIG']['profileHashes'][profile] != stored_profile_hash:
  292. changed_files.append(file)
  293. except NoSuchKey as e:
  294. changed_files.append(file)
  295. except ValueError or ResponseError as e:
  296. print(f'ERROR: {file} {e}')
  297. print(os.linesep.join(changed_files))
  298. @cli.command(name="update")
  299. @click.option('-x', '--context', required=True)
  300. @click.option('--input-and-identity/--no-input-and-identity', default=False)
  301. @click.option('-p', '--profile', default='all')
  302. @click.argument('files', nargs=-1)
  303. @click.pass_context
  304. def update_changed_files_hashes(ctx, context, input_and_identity, profile, files):
  305. """
  306. Store new data objects for the provided files
  307. """
  308. ctx.obj['CONTEXT'] = context
  309. s3_bucket, s3 = prep_s3(ctx)
  310. updated_files: List[str] = []
  311. if ctx.obj['READ_STDIN']:
  312. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  313. for file in files:
  314. identity = None
  315. if input_and_identity:
  316. file, identity = file.split('\t')
  317. file_identity = f'{get_file_identity(ctx.obj, file)}.json'
  318. try:
  319. sha256sum = hashlib.sha256()
  320. with open(file, 'rb') as f:
  321. for byte_block in iter(lambda: f.read(BUF_SIZE), b''):
  322. sha256sum.update(byte_block)
  323. calculated_file_hash = sha256sum.hexdigest()
  324. object_data = {
  325. "sourcePath": file,
  326. "storedAssetIdentity": identity,
  327. "identity": file_identity,
  328. "sha256sum": calculated_file_hash,
  329. "profileHash": ctx.obj['CONFIG']['profileHashes'][profile]
  330. }
  331. with io.BytesIO(json.dumps(object_data, sort_keys=True, indent=None).encode('utf-8')) as data:
  332. data.seek(0, os.SEEK_END)
  333. data_length = data.tell()
  334. data.seek(0)
  335. s3.put_object(
  336. s3_bucket,
  337. file_identity,
  338. data,
  339. data_length,
  340. content_type="application/json",
  341. metadata={}
  342. )
  343. updated_files.append(file)
  344. except ValueError or ResponseError as e:
  345. print(f'ERROR: {file} {e}')
  346. print(os.linesep.join(updated_files))
  347. @cli.command(name="store")
  348. @click.option('-x', '--context', required=True)
  349. @click.argument('files', nargs=-1)
  350. @click.pass_context
  351. def store_files(ctx, context, files):
  352. """
  353. Store specified files in a <context> bucket for retrieval.
  354. """
  355. ctx.obj['CONTEXT'] = context
  356. s3_bucket, s3 = prep_s3(ctx)
  357. stored_files: List[str] = []
  358. if ctx.obj['READ_STDIN']:
  359. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  360. for file in files:
  361. file_identity = get_file_identity(ctx.obj, file)
  362. try:
  363. s3.fput_object(
  364. s3_bucket,
  365. file_identity,
  366. file,
  367. content_type="application/octet-stream"
  368. )
  369. if 'ADD_PREFIX' in ctx.obj and ctx.obj['ADD_PREFIX'] is not None:
  370. stored_files.append(os.path.join(ctx.obj['ADD_PREFIX'], file_identity))
  371. else:
  372. stored_files.append(file)
  373. except ResponseError as e:
  374. print(f'ERROR: {file} {e}', file=sys.stderr)
  375. print(os.linesep.join(stored_files))
  376. @cli.command(name="retrieve")
  377. @click.option('-x', '--context', required=True)
  378. @click.option('-d', '--destination', default=None)
  379. @click.argument('files', nargs=-1)
  380. @click.pass_context
  381. def retrieve_files(ctx, context, destination, files):
  382. """
  383. Retrieve specified files from a <context> bucket
  384. """
  385. ctx.obj['CONTEXT'] = context
  386. s3_bucket, s3 = prep_s3(ctx)
  387. retrieved_files: List[str] = []
  388. if ctx.obj['READ_STDIN']:
  389. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  390. for file in files:
  391. file_identity = get_file_identity(ctx.obj, file)
  392. file_destination = file
  393. if destination is not None:
  394. file_destination = os.path.join(destination, file_identity)
  395. try:
  396. s3.fget_object(
  397. s3_bucket,
  398. file_identity,
  399. file_destination
  400. )
  401. retrieved_files.append(file_destination)
  402. except NoSuchKey as e:
  403. print(f'ERROR: {file_identity} {file_destination} {e}', file=sys.stderr)
  404. except ResponseError as e:
  405. print(f'ERROR: {file_destination} {e}', file=sys.stderr)
  406. print(os.linesep.join(retrieved_files))
  407. ######################################
  408. # Asset Compression Focused Commands #
  409. ######################################
  410. @cli.command(name="compress")
  411. @click.option('-p', '--profile', default='default')
  412. @click.option('-c', '--content', default='all')
  413. @click.option('-d', '--destination', default=None)
  414. @click.option('--print-input-and-identity/--no-print-input-and-identity', default=False)
  415. @click.argument('files', nargs=-1)
  416. @click.pass_context
  417. def compress_assets(ctx, profile, content, destination, print_input_and_identity, files):
  418. profiles = ctx.obj['CONFIG']['profiles']
  419. if profile not in profiles:
  420. raise ValueError(f'Unrecognized profile: {profile}')
  421. default_profile: Dict[str, any] = profiles['default']
  422. profile: Dict[str, any] = profiles[profile]
  423. if content != 'all':
  424. if content not in profile and content not in default_profile:
  425. raise ValueError(f'Unrecognized content: {content}')
  426. content_configurations = []
  427. if content == 'all':
  428. content_names: set = set()
  429. for content_name in profile.keys():
  430. content_names.add(content_name)
  431. content_configurations.append(profile[content_name])
  432. for content_name in default_profile.keys():
  433. if content_name not in content_names:
  434. content_names.add(content_name)
  435. content_configurations.append(default_profile[content_name])
  436. else:
  437. if content in profile:
  438. content_configurations.append(profile[content])
  439. else:
  440. content_configurations.append(default_profile[content])
  441. if ctx.obj['READ_STDIN']:
  442. files = get_clean_stdin_iterator(click.get_text_stream('stdin'))
  443. if destination is None:
  444. destination = tempfile.mkdtemp()
  445. compressed_files = []
  446. tasks = []
  447. def store_filename(storage_list: List[str], filename: str):
  448. """
  449. A simple lambda wrapper to asynchronously add processed files to the list
  450. :param storage_list:
  451. :param filename:
  452. :return:
  453. """
  454. return lambda: storage_list.append(filename)
  455. for input_file in files:
  456. for content_configuration in content_configurations:
  457. if any([input_file.endswith(extension) for extension in content_configuration['extensions']]):
  458. file = input_file
  459. if 'REMOVE_PREFIX' in ctx.obj and ctx.obj['REMOVE_PREFIX'] is not None:
  460. file = strip_prefix(ctx.obj['REMOVE_PREFIX'], input_file)
  461. if 'preserveInputExtension' in content_configuration \
  462. and content_configuration['preserveInputExtension']:
  463. output_file = os.path.join(destination, file)
  464. else:
  465. output_file_without_ext = os.path.splitext(os.path.join(destination, file))[0]
  466. output_file = f'{output_file_without_ext}.{content_configuration["outputExtension"]}'
  467. output_file_identity = get_file_identity({'REMOVE_PREFIX': destination}, output_file)
  468. output_file_dir = os.path.dirname(output_file)
  469. os.makedirs(output_file_dir, exist_ok=True)
  470. command: str = content_configuration['command'] \
  471. .replace('{{input_file}}', f'\'{input_file}\'') \
  472. .replace('{{output_file}}', f'\'{output_file}\'')
  473. tasks.append(
  474. run_command_shell(
  475. command,
  476. stdout=asyncio.subprocess.DEVNULL,
  477. stderr=asyncio.subprocess.DEVNULL,
  478. on_success=store_filename(
  479. compressed_files,
  480. f'{input_file}\t{output_file_identity}' if print_input_and_identity else output_file
  481. )
  482. )
  483. )
  484. results = run_asyncio_commands(
  485. tasks, max_concurrent_tasks=ctx.obj['CONFIG']['concurrency']
  486. )
  487. print(os.linesep.join(compressed_files))
  488. if __name__ == '__main__':
  489. cli(obj={})