From 6c0740bb8c3f834149041da130b839c9cbda2339 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 10:13:54 +1000 Subject: [PATCH 01/13] Allow for disabling of parallel processing of `qmk find` and `qmk mass-compile`. --- lib/python/qmk/cli/find.py | 3 +- lib/python/qmk/cli/mass_compile.py | 5 ++-- lib/python/qmk/search.py | 46 ++++++++++++++++++++---------- 3 files changed, 36 insertions(+), 18 deletions(-) diff --git a/lib/python/qmk/cli/find.py b/lib/python/qmk/cli/find.py index 2836eb8a5421..b11f35fce5a3 100644 --- a/lib/python/qmk/cli/find.py +++ b/lib/python/qmk/cli/find.py @@ -15,6 +15,7 @@ ) @cli.argument('-p', '--print', arg_only=True, action='append', default=[], help="For each matched target, print the value of the supplied info.json key. May be passed multiple times.") @cli.argument('-km', '--keymap', type=str, default='default', help="The keymap name to build. Default is 'default'.") +@cli.argument('-x', '--disable-parallel-parsing', arg_only=True, action='store_true', help="Disables parallel parsing of files, useful for debugging stalls.") @cli.subcommand('Find builds which match supplied search criteria.') def find(cli): """Search through all keyboards and keymaps for a given search criteria. @@ -23,7 +24,7 @@ def find(cli): if len(cli.args.filter) == 0 and len(cli.args.print) > 0: cli.log.warning('No filters supplied -- keymaps not parsed, unable to print requested values.') - targets = search_keymap_targets(cli.args.keymap, cli.args.filter, cli.args.print) + targets = search_keymap_targets(cli.args.keymap, cli.args.filter, cli.args.print, parallel=not cli.args.disable_parallel_parsing) for keyboard, keymap, print_vals in targets: print(f'{keyboard}:{keymap}') diff --git a/lib/python/qmk/cli/mass_compile.py b/lib/python/qmk/cli/mass_compile.py index 1227f435e74e..16ee64515e41 100755 --- a/lib/python/qmk/cli/mass_compile.py +++ b/lib/python/qmk/cli/mass_compile.py @@ -79,6 +79,7 @@ def mass_compile_targets(targets, clean, dry_run, no_temp, parallel, env): @cli.argument('-j', '--parallel', type=int, default=1, help="Set the number of parallel make jobs; 0 means unlimited.") @cli.argument('-c', '--clean', arg_only=True, action='store_true', help="Remove object files before compiling.") @cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually build, just show the commands to be run.") +@cli.argument('-x', '--disable-parallel-parsing', arg_only=True, action='store_true', help="Disables parallel parsing of files, useful for debugging stalls.") @cli.argument( '-f', '--filter', @@ -95,8 +96,8 @@ def mass_compile(cli): """Compile QMK Firmware against all keyboards. """ if len(cli.args.builds) > 0: - targets = search_make_targets(cli.args.builds, cli.args.filter) + targets = search_make_targets(cli.args.builds, cli.args.filter, parallel=not cli.args.disable_parallel_parsing) else: - targets = search_keymap_targets(cli.args.keymap, cli.args.filter) + targets = search_keymap_targets(cli.args.keymap, cli.args.filter, parallel=not cli.args.disable_parallel_parsing) return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.args.no_temp, cli.args.parallel, cli.args.env) diff --git a/lib/python/qmk/search.py b/lib/python/qmk/search.py index 0b5d48921898..5da083a45562 100644 --- a/lib/python/qmk/search.py +++ b/lib/python/qmk/search.py @@ -54,7 +54,7 @@ def _load_keymap_info(kb_km): return (kb_km[0], kb_km[1], keymap_json(kb_km[0], kb_km[1])) -def expand_make_targets(targets: List[str]) -> List[Tuple[str, str]]: +def expand_make_targets(targets: List[str], parallel=True) -> List[Tuple[str, str]]: """Expand a list of make targets into a list of (keyboard, keymap) tuples. Caters for 'all' in either keyboard or keymap, or both. @@ -66,10 +66,10 @@ def expand_make_targets(targets: List[str]) -> List[Tuple[str, str]]: cli.log.error(f"Invalid build target: {target}") return [] split_targets.append((split_target[0], split_target[1])) - return expand_keymap_targets(split_targets) + return expand_keymap_targets(split_targets, parallel) -def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = None) -> List[Tuple[str, str]]: +def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = None, parallel=True) -> List[Tuple[str, str]]: """Expand a keyboard input and keymap input into a list of (keyboard, keymap) tuples. Caters for 'all' in either keyboard or keymap, or both. @@ -78,17 +78,25 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = all_keyboards = qmk.keyboard.list_keyboards() if keyboard == 'all': - with multiprocessing.Pool() as pool: + + def _inner_func(pool): + _map_func = pool.imap_unordered if pool is not None else map if keymap == 'all': cli.log.info('Retrieving list of all keyboards and keymaps...') targets = [] - for kb in pool.imap_unordered(_all_keymaps, all_keyboards): + for kb in _map_func(_all_keymaps, all_keyboards): targets.extend(kb) return targets else: cli.log.info(f'Retrieving list of keyboards with keymap "{keymap}"...') keyboard_filter = functools.partial(_keymap_exists, keymap=keymap) - return [(kb, keymap) for kb in filter(lambda e: e is not None, pool.imap_unordered(keyboard_filter, all_keyboards))] + return [(kb, keymap) for kb in filter(lambda e: e is not None, _map_func(keyboard_filter, all_keyboards))] + + if parallel: + with multiprocessing.Pool() as pool: + return _inner_func(pool) + return _inner_func(None) + else: if keymap == 'all': keyboard = qmk.keyboard.resolve_keyboard(keyboard) @@ -98,17 +106,17 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = return [(qmk.keyboard.resolve_keyboard(keyboard), keymap)] -def expand_keymap_targets(targets: List[Tuple[str, str]]) -> List[Tuple[str, str]]: +def expand_keymap_targets(targets: List[Tuple[str, str]], parallel=True) -> List[Tuple[str, str]]: """Expand a list of (keyboard, keymap) tuples inclusive of 'all', into a list of explicit (keyboard, keymap) tuples. """ overall_targets = [] all_keyboards = qmk.keyboard.list_keyboards() for target in targets: - overall_targets.extend(_expand_keymap_target(target[0], target[1], all_keyboards)) + overall_targets.extend(_expand_keymap_target(target[0], target[1], all_keyboards, parallel)) return list(sorted(set(overall_targets))) -def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]: +def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: """Filter a list of (keyboard, keymap) tuples based on the supplied filters. Optionally includes the values of the queried info.json keys. @@ -117,8 +125,16 @@ def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str targets = [(kb, km, {}) for kb, km in target_list] else: cli.log.info('Parsing data for all matching keyboard/keymap combinations...') - with multiprocessing.Pool() as pool: - valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in pool.imap_unordered(_load_keymap_info, target_list)] + + def _inner_func(pool): + _map_func = pool.imap_unordered if pool is not None else map + return [(e[0], e[1], dotty(e[2])) for e in _map_func(_load_keymap_info, target_list)] + + if parallel: + with multiprocessing.Pool() as pool: + valid_keymaps = _inner_func(pool) + else: + valid_keymaps = _inner_func(None) function_re = re.compile(r'^(?P[a-zA-Z]+)\((?P[a-zA-Z0-9_\.]+)(,\s*(?P[^#]+))?\)$') equals_re = re.compile(r'^(?P[a-zA-Z0-9_\.]+)\s*=\s*(?P[^#]+)$') @@ -179,13 +195,13 @@ def f(e): return targets -def search_keymap_targets(keymap='default', filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]: +def search_keymap_targets(keymap='default', filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: """Search for build targets matching the supplied criteria. """ - return list(sorted(_filter_keymap_targets(expand_keymap_targets([('all', keymap)]), filters, print_vals), key=lambda e: (e[0], e[1]))) + return list(sorted(_filter_keymap_targets(expand_keymap_targets([('all', keymap)], parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) -def search_make_targets(targets: List[str], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]: +def search_make_targets(targets: List[str], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: """Search for build targets matching the supplied criteria. """ - return list(sorted(_filter_keymap_targets(expand_make_targets(targets), filters, print_vals), key=lambda e: (e[0], e[1]))) + return list(sorted(_filter_keymap_targets(expand_make_targets(targets, parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) From 2808171cad9f9eff317b2a95dcc92ecd168a1f75 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 10:39:53 +1000 Subject: [PATCH 02/13] Parameterise `search_keymap_targets()` so that it can be fed an array of tuples, instead of just a keymap name. --- lib/python/qmk/cli/find.py | 2 +- lib/python/qmk/cli/mass_compile.py | 2 +- lib/python/qmk/search.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/python/qmk/cli/find.py b/lib/python/qmk/cli/find.py index b11f35fce5a3..364a57886b63 100644 --- a/lib/python/qmk/cli/find.py +++ b/lib/python/qmk/cli/find.py @@ -24,7 +24,7 @@ def find(cli): if len(cli.args.filter) == 0 and len(cli.args.print) > 0: cli.log.warning('No filters supplied -- keymaps not parsed, unable to print requested values.') - targets = search_keymap_targets(cli.args.keymap, cli.args.filter, cli.args.print, parallel=not cli.args.disable_parallel_parsing) + targets = search_keymap_targets([('all', cli.args.keymap)], cli.args.filter, cli.args.print, parallel=not cli.args.disable_parallel_parsing) for keyboard, keymap, print_vals in targets: print(f'{keyboard}:{keymap}') diff --git a/lib/python/qmk/cli/mass_compile.py b/lib/python/qmk/cli/mass_compile.py index 16ee64515e41..ccf4c53408f7 100755 --- a/lib/python/qmk/cli/mass_compile.py +++ b/lib/python/qmk/cli/mass_compile.py @@ -98,6 +98,6 @@ def mass_compile(cli): if len(cli.args.builds) > 0: targets = search_make_targets(cli.args.builds, cli.args.filter, parallel=not cli.args.disable_parallel_parsing) else: - targets = search_keymap_targets(cli.args.keymap, cli.args.filter, parallel=not cli.args.disable_parallel_parsing) + targets = search_keymap_targets([('all', cli.args.keymap)], cli.args.filter, parallel=not cli.args.disable_parallel_parsing) return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.args.no_temp, cli.args.parallel, cli.args.env) diff --git a/lib/python/qmk/search.py b/lib/python/qmk/search.py index 5da083a45562..07ec1aa6f651 100644 --- a/lib/python/qmk/search.py +++ b/lib/python/qmk/search.py @@ -195,10 +195,10 @@ def f(e): return targets -def search_keymap_targets(keymap='default', filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: +def search_keymap_targets(targets: List[Tuple[str, str]] = [('all', 'default')], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: """Search for build targets matching the supplied criteria. """ - return list(sorted(_filter_keymap_targets(expand_keymap_targets([('all', keymap)], parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) + return list(sorted(_filter_keymap_targets(expand_keymap_targets(targets, parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) def search_make_targets(targets: List[str], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: From 06316a1cd44c84740b2277e8938c4d39bf2ef35c Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 11:25:53 +1000 Subject: [PATCH 03/13] Simplification of parallelisation. --- lib/python/qmk/search.py | 66 ++++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/lib/python/qmk/search.py b/lib/python/qmk/search.py index 07ec1aa6f651..b31f615f4f12 100644 --- a/lib/python/qmk/search.py +++ b/lib/python/qmk/search.py @@ -25,6 +25,24 @@ def _set_log_level(level): return old +@contextlib.contextmanager +def parallelize(parallel): + with contextlib.suppress(ImportError): + from mpire import WorkerPool + if parallel: + with WorkerPool() as pool: + yield functools.partial(pool.imap_unordered, progress_bar=True) + else: + yield map + return + + if parallel: + with multiprocessing.Pool() as pool: + yield pool.imap_unordered + else: + yield map + + @contextlib.contextmanager def ignore_logging(): old = _set_log_level(logging.CRITICAL) @@ -47,11 +65,15 @@ def _keymap_exists(keyboard, keymap): return keyboard if qmk.keymap.locate_keymap(keyboard, keymap) is not None else None -def _load_keymap_info(kb_km): +def _load_keymap_info(arg0, arg1=None): """Returns a tuple of (keyboard, keymap, info.json) for the given keyboard/keymap combination. + + Caters for the different unpacking requirements of each variatn of imap_unordered(). """ with ignore_logging(): - return (kb_km[0], kb_km[1], keymap_json(kb_km[0], kb_km[1])) + if arg1 is None: + return (arg0[0], arg0[1], keymap_json(arg0[0], arg0[1])) + return (arg0, arg1, keymap_json(arg0, arg1)) def expand_make_targets(targets: List[str], parallel=True) -> List[Tuple[str, str]]: @@ -78,25 +100,18 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = all_keyboards = qmk.keyboard.list_keyboards() if keyboard == 'all': - - def _inner_func(pool): - _map_func = pool.imap_unordered if pool is not None else map - if keymap == 'all': - cli.log.info('Retrieving list of all keyboards and keymaps...') - targets = [] - for kb in _map_func(_all_keymaps, all_keyboards): + if keymap == 'all': + cli.log.info('Retrieving list of all keyboards and keymaps...') + targets = [] + with parallelize(parallel) as map_func: + for kb in map_func(_all_keymaps, all_keyboards): targets.extend(kb) - return targets - else: - cli.log.info(f'Retrieving list of keyboards with keymap "{keymap}"...') - keyboard_filter = functools.partial(_keymap_exists, keymap=keymap) - return [(kb, keymap) for kb in filter(lambda e: e is not None, _map_func(keyboard_filter, all_keyboards))] - - if parallel: - with multiprocessing.Pool() as pool: - return _inner_func(pool) - return _inner_func(None) - + return targets + else: + cli.log.info(f'Retrieving list of keyboards with keymap "{keymap}"...') + keyboard_filter = functools.partial(_keymap_exists, keymap=keymap) + with parallelize(parallel) as map_func: + return [(kb, keymap) for kb in filter(lambda e: e is not None, map_func(keyboard_filter, all_keyboards))] else: if keymap == 'all': keyboard = qmk.keyboard.resolve_keyboard(keyboard) @@ -126,15 +141,8 @@ def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str else: cli.log.info('Parsing data for all matching keyboard/keymap combinations...') - def _inner_func(pool): - _map_func = pool.imap_unordered if pool is not None else map - return [(e[0], e[1], dotty(e[2])) for e in _map_func(_load_keymap_info, target_list)] - - if parallel: - with multiprocessing.Pool() as pool: - valid_keymaps = _inner_func(pool) - else: - valid_keymaps = _inner_func(None) + with parallelize(parallel) as map_func: + valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in map_func(_load_keymap_info, target_list)] function_re = re.compile(r'^(?P[a-zA-Z]+)\((?P[a-zA-Z0-9_\.]+)(,\s*(?P[^#]+))?\)$') equals_re = re.compile(r'^(?P[a-zA-Z0-9_\.]+)\s*=\s*(?P[^#]+)$') From 68032751800284d13cc2c128031ec51fd4cdec49 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 11:33:45 +1000 Subject: [PATCH 04/13] Typos and cleanup. --- lib/python/qmk/search.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/lib/python/qmk/search.py b/lib/python/qmk/search.py index b31f615f4f12..4c61f3328815 100644 --- a/lib/python/qmk/search.py +++ b/lib/python/qmk/search.py @@ -27,20 +27,19 @@ def _set_log_level(level): @contextlib.contextmanager def parallelize(parallel): + if not parallel: + yield map + return + with contextlib.suppress(ImportError): from mpire import WorkerPool - if parallel: - with WorkerPool() as pool: - yield functools.partial(pool.imap_unordered, progress_bar=True) - else: - yield map + with WorkerPool() as pool: + yield functools.partial(pool.imap_unordered, progress_bar=True) return - if parallel: - with multiprocessing.Pool() as pool: - yield pool.imap_unordered - else: - yield map + with multiprocessing.Pool() as pool: + yield pool.imap_unordered + return @contextlib.contextmanager @@ -68,7 +67,7 @@ def _keymap_exists(keyboard, keymap): def _load_keymap_info(arg0, arg1=None): """Returns a tuple of (keyboard, keymap, info.json) for the given keyboard/keymap combination. - Caters for the different unpacking requirements of each variatn of imap_unordered(). + Caters for the different unpacking requirements of each variant of map()/imap_unordered(). """ with ignore_logging(): if arg1 is None: @@ -140,7 +139,6 @@ def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str targets = [(kb, km, {}) for kb, km in target_list] else: cli.log.info('Parsing data for all matching keyboard/keymap combinations...') - with parallelize(parallel) as map_func: valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in map_func(_load_keymap_info, target_list)] From 0110a4f79de198161187d9a428877fb71a653824 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 12:35:12 +1000 Subject: [PATCH 05/13] Move `parallelize` to util.py. --- lib/python/qmk/search.py | 19 +------------------ lib/python/qmk/util.py | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 18 deletions(-) create mode 100644 lib/python/qmk/util.py diff --git a/lib/python/qmk/search.py b/lib/python/qmk/search.py index 4c61f3328815..9acc59668f6a 100644 --- a/lib/python/qmk/search.py +++ b/lib/python/qmk/search.py @@ -4,12 +4,12 @@ import functools import fnmatch import logging -import multiprocessing import re from typing import List, Tuple from dotty_dict import dotty from milc import cli +from qmk.util import parallelize from qmk.info import keymap_json import qmk.keyboard import qmk.keymap @@ -25,23 +25,6 @@ def _set_log_level(level): return old -@contextlib.contextmanager -def parallelize(parallel): - if not parallel: - yield map - return - - with contextlib.suppress(ImportError): - from mpire import WorkerPool - with WorkerPool() as pool: - yield functools.partial(pool.imap_unordered, progress_bar=True) - return - - with multiprocessing.Pool() as pool: - yield pool.imap_unordered - return - - @contextlib.contextmanager def ignore_logging(): old = _set_log_level(logging.CRITICAL) diff --git a/lib/python/qmk/util.py b/lib/python/qmk/util.py new file mode 100644 index 000000000000..d57bce951c99 --- /dev/null +++ b/lib/python/qmk/util.py @@ -0,0 +1,27 @@ +"""Utility functions. +""" +import contextlib +import functools +import multiprocessing + +@contextlib.contextmanager +def parallelize(do_parallel): + """Returns a function that can be used in place of a map() call. + + Attempts to use `mpire`, falling back to `multiprocessing` if it's not + available. If parallelization is not requested, returns the original map() + function. + """ + if not do_parallel: + yield map + return + + with contextlib.suppress(ImportError): + from mpire import WorkerPool + with WorkerPool() as pool: + yield functools.partial(pool.imap_unordered, progress_bar=True) + return + + with multiprocessing.Pool() as pool: + yield pool.imap_unordered + return From bf40eebf73955f404149d7562b3c9f036afe73f8 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 12:48:13 +1000 Subject: [PATCH 06/13] `qmk format-python` --- lib/python/qmk/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/python/qmk/util.py b/lib/python/qmk/util.py index d57bce951c99..47c43a76f51c 100644 --- a/lib/python/qmk/util.py +++ b/lib/python/qmk/util.py @@ -4,6 +4,7 @@ import functools import multiprocessing + @contextlib.contextmanager def parallelize(do_parallel): """Returns a function that can be used in place of a map() call. @@ -24,4 +25,3 @@ def parallelize(do_parallel): with multiprocessing.Pool() as pool: yield pool.imap_unordered - return From 4a4cb6c44d2afe675ad44d1289667d17373f1477 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 14:49:32 +1000 Subject: [PATCH 07/13] `cli.args` should not be used for "saveable" settings. --- lib/python/qmk/cli/mass_compile.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/python/qmk/cli/mass_compile.py b/lib/python/qmk/cli/mass_compile.py index ccf4c53408f7..33dac16927e6 100755 --- a/lib/python/qmk/cli/mass_compile.py +++ b/lib/python/qmk/cli/mass_compile.py @@ -96,8 +96,8 @@ def mass_compile(cli): """Compile QMK Firmware against all keyboards. """ if len(cli.args.builds) > 0: - targets = search_make_targets(cli.args.builds, cli.args.filter, parallel=not cli.args.disable_parallel_parsing) + targets = search_make_targets(cli.args.builds, cli.args.filter, parallel=not cli.config.mass_compile.disable_parallel_parsing) else: - targets = search_keymap_targets([('all', cli.args.keymap)], cli.args.filter, parallel=not cli.args.disable_parallel_parsing) + targets = search_keymap_targets([('all', cli.config.mass_compile.keymap)], cli.args.filter, parallel=not cli.config.mass_compile.disable_parallel_parsing) - return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.args.no_temp, cli.args.parallel, cli.args.env) + return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.config.mass_compile.no_temp, cli.config.mass_compile.parallel, cli.args.env) From c5aaa25b6c23949de266ed158e6a6973c0441cae Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 15:51:51 +1000 Subject: [PATCH 08/13] `qmk config` --- lib/python/qmk/cli/find.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/python/qmk/cli/find.py b/lib/python/qmk/cli/find.py index 364a57886b63..b99f04bca63a 100644 --- a/lib/python/qmk/cli/find.py +++ b/lib/python/qmk/cli/find.py @@ -24,7 +24,7 @@ def find(cli): if len(cli.args.filter) == 0 and len(cli.args.print) > 0: cli.log.warning('No filters supplied -- keymaps not parsed, unable to print requested values.') - targets = search_keymap_targets([('all', cli.args.keymap)], cli.args.filter, cli.args.print, parallel=not cli.args.disable_parallel_parsing) + targets = search_keymap_targets([('all', cli.config.find.keymap)], cli.args.filter, cli.args.print, parallel=not cli.config.find.disable_parallel_parsing) for keyboard, keymap, print_vals in targets: print(f'{keyboard}:{keymap}') From 74d37f8e4e666f27b0dcad84615c90e60f31bf65 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 16:06:38 +1000 Subject: [PATCH 09/13] Further simplification. --- lib/python/qmk/cli/find.py | 3 +-- lib/python/qmk/cli/mass_compile.py | 5 ++--- lib/python/qmk/search.py | 33 ++++++++++++++---------------- lib/python/qmk/util.py | 31 ++++++++++++++++++++++++++-- 4 files changed, 47 insertions(+), 25 deletions(-) diff --git a/lib/python/qmk/cli/find.py b/lib/python/qmk/cli/find.py index b99f04bca63a..f2135bbc16c8 100644 --- a/lib/python/qmk/cli/find.py +++ b/lib/python/qmk/cli/find.py @@ -15,7 +15,6 @@ ) @cli.argument('-p', '--print', arg_only=True, action='append', default=[], help="For each matched target, print the value of the supplied info.json key. May be passed multiple times.") @cli.argument('-km', '--keymap', type=str, default='default', help="The keymap name to build. Default is 'default'.") -@cli.argument('-x', '--disable-parallel-parsing', arg_only=True, action='store_true', help="Disables parallel parsing of files, useful for debugging stalls.") @cli.subcommand('Find builds which match supplied search criteria.') def find(cli): """Search through all keyboards and keymaps for a given search criteria. @@ -24,7 +23,7 @@ def find(cli): if len(cli.args.filter) == 0 and len(cli.args.print) > 0: cli.log.warning('No filters supplied -- keymaps not parsed, unable to print requested values.') - targets = search_keymap_targets([('all', cli.config.find.keymap)], cli.args.filter, cli.args.print, parallel=not cli.config.find.disable_parallel_parsing) + targets = search_keymap_targets([('all', cli.config.find.keymap)], cli.args.filter, cli.args.print) for keyboard, keymap, print_vals in targets: print(f'{keyboard}:{keymap}') diff --git a/lib/python/qmk/cli/mass_compile.py b/lib/python/qmk/cli/mass_compile.py index 33dac16927e6..06e6e411a72a 100755 --- a/lib/python/qmk/cli/mass_compile.py +++ b/lib/python/qmk/cli/mass_compile.py @@ -79,7 +79,6 @@ def mass_compile_targets(targets, clean, dry_run, no_temp, parallel, env): @cli.argument('-j', '--parallel', type=int, default=1, help="Set the number of parallel make jobs; 0 means unlimited.") @cli.argument('-c', '--clean', arg_only=True, action='store_true', help="Remove object files before compiling.") @cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually build, just show the commands to be run.") -@cli.argument('-x', '--disable-parallel-parsing', arg_only=True, action='store_true', help="Disables parallel parsing of files, useful for debugging stalls.") @cli.argument( '-f', '--filter', @@ -96,8 +95,8 @@ def mass_compile(cli): """Compile QMK Firmware against all keyboards. """ if len(cli.args.builds) > 0: - targets = search_make_targets(cli.args.builds, cli.args.filter, parallel=not cli.config.mass_compile.disable_parallel_parsing) + targets = search_make_targets(cli.args.builds, cli.args.filter) else: - targets = search_keymap_targets([('all', cli.config.mass_compile.keymap)], cli.args.filter, parallel=not cli.config.mass_compile.disable_parallel_parsing) + targets = search_keymap_targets([('all', cli.config.mass_compile.keymap)], cli.args.filter) return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.config.mass_compile.no_temp, cli.config.mass_compile.parallel, cli.args.env) diff --git a/lib/python/qmk/search.py b/lib/python/qmk/search.py index 9acc59668f6a..12b239ac6722 100644 --- a/lib/python/qmk/search.py +++ b/lib/python/qmk/search.py @@ -9,7 +9,7 @@ from dotty_dict import dotty from milc import cli -from qmk.util import parallelize +from qmk.util import parallel_map from qmk.info import keymap_json import qmk.keyboard import qmk.keymap @@ -58,7 +58,7 @@ def _load_keymap_info(arg0, arg1=None): return (arg0, arg1, keymap_json(arg0, arg1)) -def expand_make_targets(targets: List[str], parallel=True) -> List[Tuple[str, str]]: +def expand_make_targets(targets: List[str]) -> List[Tuple[str, str]]: """Expand a list of make targets into a list of (keyboard, keymap) tuples. Caters for 'all' in either keyboard or keymap, or both. @@ -70,10 +70,10 @@ def expand_make_targets(targets: List[str], parallel=True) -> List[Tuple[str, st cli.log.error(f"Invalid build target: {target}") return [] split_targets.append((split_target[0], split_target[1])) - return expand_keymap_targets(split_targets, parallel) + return expand_keymap_targets(split_targets) -def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = None, parallel=True) -> List[Tuple[str, str]]: +def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = None) -> List[Tuple[str, str]]: """Expand a keyboard input and keymap input into a list of (keyboard, keymap) tuples. Caters for 'all' in either keyboard or keymap, or both. @@ -85,15 +85,13 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = if keymap == 'all': cli.log.info('Retrieving list of all keyboards and keymaps...') targets = [] - with parallelize(parallel) as map_func: - for kb in map_func(_all_keymaps, all_keyboards): - targets.extend(kb) + for kb in parallel_map(_all_keymaps, all_keyboards): + targets.extend(kb) return targets else: cli.log.info(f'Retrieving list of keyboards with keymap "{keymap}"...') keyboard_filter = functools.partial(_keymap_exists, keymap=keymap) - with parallelize(parallel) as map_func: - return [(kb, keymap) for kb in filter(lambda e: e is not None, map_func(keyboard_filter, all_keyboards))] + return [(kb, keymap) for kb in filter(lambda e: e is not None, parallel_map(keyboard_filter, all_keyboards))] else: if keymap == 'all': keyboard = qmk.keyboard.resolve_keyboard(keyboard) @@ -103,17 +101,17 @@ def _expand_keymap_target(keyboard: str, keymap: str, all_keyboards: List[str] = return [(qmk.keyboard.resolve_keyboard(keyboard), keymap)] -def expand_keymap_targets(targets: List[Tuple[str, str]], parallel=True) -> List[Tuple[str, str]]: +def expand_keymap_targets(targets: List[Tuple[str, str]]) -> List[Tuple[str, str]]: """Expand a list of (keyboard, keymap) tuples inclusive of 'all', into a list of explicit (keyboard, keymap) tuples. """ overall_targets = [] all_keyboards = qmk.keyboard.list_keyboards() for target in targets: - overall_targets.extend(_expand_keymap_target(target[0], target[1], all_keyboards, parallel)) + overall_targets.extend(_expand_keymap_target(target[0], target[1], all_keyboards)) return list(sorted(set(overall_targets))) -def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: +def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]: """Filter a list of (keyboard, keymap) tuples based on the supplied filters. Optionally includes the values of the queried info.json keys. @@ -122,8 +120,7 @@ def _filter_keymap_targets(target_list: List[Tuple[str, str]], filters: List[str targets = [(kb, km, {}) for kb, km in target_list] else: cli.log.info('Parsing data for all matching keyboard/keymap combinations...') - with parallelize(parallel) as map_func: - valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in map_func(_load_keymap_info, target_list)] + valid_keymaps = [(e[0], e[1], dotty(e[2])) for e in parallel_map(_load_keymap_info, target_list)] function_re = re.compile(r'^(?P[a-zA-Z]+)\((?P[a-zA-Z0-9_\.]+)(,\s*(?P[^#]+))?\)$') equals_re = re.compile(r'^(?P[a-zA-Z0-9_\.]+)\s*=\s*(?P[^#]+)$') @@ -184,13 +181,13 @@ def f(e): return targets -def search_keymap_targets(targets: List[Tuple[str, str]] = [('all', 'default')], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: +def search_keymap_targets(targets: List[Tuple[str, str]] = [('all', 'default')], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]: """Search for build targets matching the supplied criteria. """ - return list(sorted(_filter_keymap_targets(expand_keymap_targets(targets, parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) + return list(sorted(_filter_keymap_targets(expand_keymap_targets(targets), filters, print_vals), key=lambda e: (e[0], e[1]))) -def search_make_targets(targets: List[str], filters: List[str] = [], print_vals: List[str] = [], parallel=True) -> List[Tuple[str, str, List[Tuple[str, str]]]]: +def search_make_targets(targets: List[str], filters: List[str] = [], print_vals: List[str] = []) -> List[Tuple[str, str, List[Tuple[str, str]]]]: """Search for build targets matching the supplied criteria. """ - return list(sorted(_filter_keymap_targets(expand_make_targets(targets, parallel), filters, print_vals, parallel), key=lambda e: (e[0], e[1]))) + return list(sorted(_filter_keymap_targets(expand_make_targets(targets), filters, print_vals), key=lambda e: (e[0], e[1]))) diff --git a/lib/python/qmk/util.py b/lib/python/qmk/util.py index 47c43a76f51c..87915d2151df 100644 --- a/lib/python/qmk/util.py +++ b/lib/python/qmk/util.py @@ -4,24 +4,51 @@ import functools import multiprocessing +from milc import cli +from milc.subcommand import config + @contextlib.contextmanager -def parallelize(do_parallel): +def parallelize(): """Returns a function that can be used in place of a map() call. Attempts to use `mpire`, falling back to `multiprocessing` if it's not available. If parallelization is not requested, returns the original map() function. """ - if not do_parallel: + + # Work out if we've already got a config value for parallel searching + if not cli.config.user.parallel_search: + parallel_search = True + else: + parallel_search = cli.config.user.parallel_search + + # If we haven't already written a value, write it to the file + if cli.config.user.parallel_search != parallel_search: + cli.args.read_only = False + cli.config.user.parallel_search = parallel_search + config.set_config('user', 'parallel_search', parallel_search) + cli.save_config() + + # Non-parallel searches use use `map()` + if not parallel_search: yield map return + # Prefer mpire's `WorkerPool` if it's available with contextlib.suppress(ImportError): from mpire import WorkerPool with WorkerPool() as pool: yield functools.partial(pool.imap_unordered, progress_bar=True) return + # Otherwise fall back to multiprocessing's `Pool` with multiprocessing.Pool() as pool: yield pool.imap_unordered + + +def parallel_map(*args, **kwargs): + """Effectively runs `map()` but executes it in parallel if necessary. + """ + with parallelize() as map_fn: + return map_fn(*args, **kwargs) From d300b555584b767b728d78de2557806443b911d0 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Fri, 29 Sep 2023 16:13:28 +1000 Subject: [PATCH 10/13] Actually allow for `False` --- lib/python/qmk/util.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/python/qmk/util.py b/lib/python/qmk/util.py index 87915d2151df..0fcab3d413fb 100644 --- a/lib/python/qmk/util.py +++ b/lib/python/qmk/util.py @@ -18,7 +18,7 @@ def parallelize(): """ # Work out if we've already got a config value for parallel searching - if not cli.config.user.parallel_search: + if cli.config.user.parallel_search is None: parallel_search = True else: parallel_search = cli.config.user.parallel_search @@ -26,9 +26,9 @@ def parallelize(): # If we haven't already written a value, write it to the file if cli.config.user.parallel_search != parallel_search: cli.args.read_only = False - cli.config.user.parallel_search = parallel_search config.set_config('user', 'parallel_search', parallel_search) cli.save_config() + cli.config.user.parallel_search = parallel_search # Non-parallel searches use use `map()` if not parallel_search: From b8fd11e16149f07ab8c7040a104624cf67086ee6 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Sat, 7 Oct 2023 20:43:40 +1100 Subject: [PATCH 11/13] Update lib/python/qmk/util.py Co-authored-by: Duncan Sutherland --- lib/python/qmk/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/python/qmk/util.py b/lib/python/qmk/util.py index 0fcab3d413fb..b1c4c7366b1a 100644 --- a/lib/python/qmk/util.py +++ b/lib/python/qmk/util.py @@ -30,7 +30,7 @@ def parallelize(): cli.save_config() cli.config.user.parallel_search = parallel_search - # Non-parallel searches use use `map()` + # Non-parallel searches use `map()` if not parallel_search: yield map return From 4554eabd0b3e7c2283c80a8d4cceec6d189a3f43 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Mon, 16 Oct 2023 13:21:06 +1100 Subject: [PATCH 12/13] Fixup use of multiprocessing. --- lib/python/qmk/util.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/python/qmk/util.py b/lib/python/qmk/util.py index b1c4c7366b1a..7a485fef0936 100644 --- a/lib/python/qmk/util.py +++ b/lib/python/qmk/util.py @@ -5,7 +5,6 @@ import multiprocessing from milc import cli -from milc.subcommand import config @contextlib.contextmanager @@ -23,13 +22,6 @@ def parallelize(): else: parallel_search = cli.config.user.parallel_search - # If we haven't already written a value, write it to the file - if cli.config.user.parallel_search != parallel_search: - cli.args.read_only = False - config.set_config('user', 'parallel_search', parallel_search) - cli.save_config() - cli.config.user.parallel_search = parallel_search - # Non-parallel searches use `map()` if not parallel_search: yield map @@ -51,4 +43,8 @@ def parallel_map(*args, **kwargs): """Effectively runs `map()` but executes it in parallel if necessary. """ with parallelize() as map_fn: - return map_fn(*args, **kwargs) + # This needs to be enclosed in a `list()` as some implementations return + # a generator function, which means the scope of the pool is closed off + # before the results are returned. Returning a list ensures results are + # materialised before any worker pool is shut down. + return list(map_fn(*args, **kwargs)) From 88b4c33fcde4794d1abe564dc79d75b13694b5f7 Mon Sep 17 00:00:00 2001 From: Nick Brassel Date: Mon, 16 Oct 2023 13:55:05 +1100 Subject: [PATCH 13/13] Ensure consistent experience with `parallelize()`, regardless of backend. --- lib/python/qmk/search.py | 8 ++------ lib/python/qmk/util.py | 10 ++++++++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/python/qmk/search.py b/lib/python/qmk/search.py index 12b239ac6722..a74450ca87d9 100644 --- a/lib/python/qmk/search.py +++ b/lib/python/qmk/search.py @@ -47,15 +47,11 @@ def _keymap_exists(keyboard, keymap): return keyboard if qmk.keymap.locate_keymap(keyboard, keymap) is not None else None -def _load_keymap_info(arg0, arg1=None): +def _load_keymap_info(kb_km): """Returns a tuple of (keyboard, keymap, info.json) for the given keyboard/keymap combination. - - Caters for the different unpacking requirements of each variant of map()/imap_unordered(). """ with ignore_logging(): - if arg1 is None: - return (arg0[0], arg0[1], keymap_json(arg0[0], arg0[1])) - return (arg0, arg1, keymap_json(arg0, arg1)) + return (kb_km[0], kb_km[1], keymap_json(kb_km[0], kb_km[1])) def expand_make_targets(targets: List[str]) -> List[Tuple[str, str]]: diff --git a/lib/python/qmk/util.py b/lib/python/qmk/util.py index 7a485fef0936..db7debd5788f 100644 --- a/lib/python/qmk/util.py +++ b/lib/python/qmk/util.py @@ -1,7 +1,6 @@ """Utility functions. """ import contextlib -import functools import multiprocessing from milc import cli @@ -30,8 +29,15 @@ def parallelize(): # Prefer mpire's `WorkerPool` if it's available with contextlib.suppress(ImportError): from mpire import WorkerPool + from mpire.utils import make_single_arguments with WorkerPool() as pool: - yield functools.partial(pool.imap_unordered, progress_bar=True) + + def _worker(func, *args): + # Ensure we don't unpack tuples -- mpire's `WorkerPool` tries to do so normally so we tell it not to. + for r in pool.imap_unordered(func, make_single_arguments(*args, generator=False), progress_bar=True): + yield r + + yield _worker return # Otherwise fall back to multiprocessing's `Pool`