| 1 |
import argparse |
| 2 |
from collections import OrderedDict |
| 3 |
import glob |
| 4 |
import json |
| 5 |
import logging |
| 6 |
import re |
| 7 |
from types import ModuleType |
| 8 |
from typing import Any, Dict, List, Optional |
| 9 |
from con_duct._constants import __schema_version__ |
| 10 |
from con_duct._duct_main import DUCT_OUTPUT_PREFIX |
| 11 |
from con_duct._formatter import SummaryFormatter |
| 12 |
from con_duct._utils import parse_version |
| 13 |
from con_duct.json_utils import is_info_file |
| 14 |
|
| 15 |
try: |
| 16 |
import pyout |
| 17 |
except ImportError: |
| 18 |
pyout = None |
| 19 |
|
| 20 |
try: |
| 21 |
import yaml |
| 22 |
except ImportError: |
| 23 |
yaml: Optional[ModuleType] = None |
| 24 |
|
| 25 |
|
| 26 |
lgr = logging.getLogger(__name__) |
| 27 |
|
| 28 |
VALUE_TRANSFORMATION_MAP: Dict[str, str] = { |
| 29 |
"average_pcpu": "{value:.2f!N}%", |
| 30 |
"average_pmem": "{value:.2f!N}%", |
| 31 |
"average_rss": "{value!S}", |
| 32 |
"average_vsz": "{value!S}", |
| 33 |
"end_time": "{value:.2f!N}", |
| 34 |
"exit_code": "{value!E}", |
| 35 |
"memory_total": "{value!S}", |
| 36 |
"peak_pcpu": "{value:.2f!N}%", |
| 37 |
"peak_pmem": "{value:.2f!N}%", |
| 38 |
"peak_rss": "{value!S}", |
| 39 |
"peak_vsz": "{value!S}", |
| 40 |
"start_time": "{value:.2f!N}", |
| 41 |
"wall_clock_time": "{value:.3f} sec", |
| 42 |
} |
| 43 |
|
| 44 |
NON_TRANSFORMED_FIELDS: List[str] = [ |
| 45 |
"command", |
| 46 |
"cpu_total", |
| 47 |
"duct_version", |
| 48 |
"gpu", |
| 49 |
"hostname", |
| 50 |
"info", |
| 51 |
"logs_prefix", |
| 52 |
"message", |
| 53 |
"num_samples", |
| 54 |
"num_reports", |
| 55 |
"prefix", |
| 56 |
"schema_version", |
| 57 |
"stderr", |
| 58 |
"stdout", |
| 59 |
"uid", |
| 60 |
"usage", |
| 61 |
"user", |
| 62 |
"working_directory", |
| 63 |
] |
| 64 |
|
| 65 |
LS_FIELD_CHOICES: List[str] = ( |
| 66 |
list(VALUE_TRANSFORMATION_MAP.keys()) + NON_TRANSFORMED_FIELDS |
| 67 |
) |
| 68 |
MINIMUM_SCHEMA_VERSION: str = "0.2.0" |
| 69 |
|
| 70 |
|
| 71 |
def load_duct_runs( |
| 72 |
info_files: List[str], eval_filter: Optional[str] = None |
| 73 |
) -> List[Dict[str, Any]]: |
| 74 |
loaded: List[Dict[str, Any]] = [] |
| 75 |
for info_file in info_files: |
| 76 |
with open(info_file) as file: |
| 77 |
try: |
| 78 |
this: Dict[str, Any] = json.load(file) |
| 79 |
|
| 80 |
this["prefix"] = info_file.split("info.json")[0] |
| 81 |
if parse_version(this["schema_version"]) < parse_version( |
| 82 |
MINIMUM_SCHEMA_VERSION |
| 83 |
): |
| 84 |
lgr.debug( |
| 85 |
f"Skipping {this['prefix']}, schema version {this['schema_version']} " |
| 86 |
f"is below minimum schema version {MINIMUM_SCHEMA_VERSION}." |
| 87 |
) |
| 88 |
continue |
| 89 |
ensure_compliant_schema(this) |
| 90 |
if eval_filter is not None and not ( |
| 91 |
eval_results := eval(eval_filter, _flatten_dict(this), dict(re=re)) |
| 92 |
): |
| 93 |
lgr.debug( |
| 94 |
"Filtering out %s due to filter results matching: %s", |
| 95 |
this, |
| 96 |
eval_results, |
| 97 |
) |
| 98 |
continue |
| 99 |
|
| 100 |
loaded.append(this) |
| 101 |
except json.JSONDecodeError as exc: |
| 102 |
|
| 103 |
if exc.pos == 0 and not exc.doc.strip(): |
| 104 |
lgr.debug("Skipping empty file %s", info_file) |
| 105 |
else: |
| 106 |
lgr.warning("Failed to load file %s: %s", file, exc) |
| 107 |
except Exception as exc: |
| 108 |
lgr.warning("Failed to load file %s: %s", file, exc) |
| 109 |
return loaded |
| 110 |
|
| 111 |
|
| 112 |
def ensure_compliant_schema(info_dict: dict) -> None: |
| 113 |
if parse_version(info_dict["schema_version"]) == parse_version(__schema_version__): |
| 114 |
return |
| 115 |
|
| 116 |
if parse_version(info_dict["schema_version"]) < parse_version("0.2.1"): |
| 117 |
info_dict["execution_summary"]["working_directory"] = "" |
| 118 |
|
| 119 |
if parse_version(info_dict["schema_version"]) < parse_version("0.2.2"): |
| 120 |
info_dict["message"] = "" |
| 121 |
|
| 122 |
|
| 123 |
def process_run_data( |
| 124 |
run_data_list: List[Dict[str, Any]], fields: List[str], formatter: SummaryFormatter |
| 125 |
) -> List[OrderedDict[str, Any]]: |
| 126 |
output_rows: List[OrderedDict[str, Any]] = [] |
| 127 |
for row in run_data_list: |
| 128 |
flattened = _flatten_dict(row) |
| 129 |
try: |
| 130 |
restricted = _restrict_row(fields, flattened) |
| 131 |
except KeyError: |
| 132 |
lgr.warning( |
| 133 |
"Failed to pick fields of interest from a record, skipping. Record was: %s", |
| 134 |
list(flattened), |
| 135 |
) |
| 136 |
continue |
| 137 |
formatted = _format_row(restricted, formatter) |
| 138 |
output_rows.append(formatted) |
| 139 |
return output_rows |
| 140 |
|
| 141 |
|
| 142 |
def _flatten_dict(d: Dict[str, Any]) -> Dict[str, Any]: |
| 143 |
items: List[tuple[str, Any]] = [] |
| 144 |
for k, v in d.items(): |
| 145 |
if isinstance(v, dict): |
| 146 |
items.extend(_flatten_dict(v).items()) |
| 147 |
else: |
| 148 |
items.append((k, v)) |
| 149 |
return dict(items) |
| 150 |
|
| 151 |
|
| 152 |
def _restrict_row(field_list: List[str], row: Dict[str, Any]) -> OrderedDict[str, Any]: |
| 153 |
restricted: OrderedDict[str, Any] = OrderedDict() |
| 154 |
|
| 155 |
restricted["prefix"] = row["prefix"] |
| 156 |
for field in field_list: |
| 157 |
if field != "prefix" and field in row: |
| 158 |
restricted[field.split(".")[-1]] = row[field] |
| 159 |
return restricted |
| 160 |
|
| 161 |
|
| 162 |
def _format_row( |
| 163 |
row: OrderedDict[str, Any], formatter: SummaryFormatter |
| 164 |
) -> OrderedDict[str, Any]: |
| 165 |
transformed: OrderedDict[str, Any] = OrderedDict() |
| 166 |
for col, value in row.items(): |
| 167 |
transformation: Optional[str] = VALUE_TRANSFORMATION_MAP.get(col) |
| 168 |
if transformation is not None: |
| 169 |
value = formatter.format(transformation, value=value) |
| 170 |
transformed[col] = value |
| 171 |
return transformed |
| 172 |
|
| 173 |
|
| 174 |
def pyout_ls(run_data_list: List[OrderedDict[str, Any]], enable_colors: bool) -> None: |
| 175 |
"""Generate and print a tabular table using pyout.""" |
| 176 |
if pyout is None: |
| 177 |
raise RuntimeError("pyout is required for this output format.") |
| 178 |
|
| 179 |
color_styles = { |
| 180 |
"E": dict( |
| 181 |
color=dict( |
| 182 |
re_lookup=[ |
| 183 |
["^0$", "green"], |
| 184 |
[".*", "red"], |
| 185 |
] |
| 186 |
) |
| 187 |
), |
| 188 |
"N": dict( |
| 189 |
color=dict( |
| 190 |
re_lookup=[ |
| 191 |
[f"^{SummaryFormatter.NONE}", "red"], |
| 192 |
[".*", "green"], |
| 193 |
] |
| 194 |
) |
| 195 |
), |
| 196 |
} |
| 197 |
|
| 198 |
color_styles["S"] = color_styles["N"] |
| 199 |
|
| 200 |
pattern = re.compile(r"!([A-Z])") |
| 201 |
conversion_map = ( |
| 202 |
{ |
| 203 |
k: color_styles[match.group(1)] |
| 204 |
for k, v in VALUE_TRANSFORMATION_MAP.items() |
| 205 |
if (match := pattern.search(v)) |
| 206 |
} |
| 207 |
if enable_colors |
| 208 |
else {} |
| 209 |
) |
| 210 |
with pyout.Tabular( |
| 211 |
style=dict( |
| 212 |
header_=dict(bold=True, transform=str.upper), |
| 213 |
**conversion_map, |
| 214 |
), |
| 215 |
mode="final", |
| 216 |
) as table: |
| 217 |
for row in run_data_list: |
| 218 |
table(row) |
| 219 |
|
| 220 |
|
| 221 |
def ls(args: argparse.Namespace) -> int: |
| 222 |
if not args.paths: |
| 223 |
pattern = f"{DUCT_OUTPUT_PREFIX[:DUCT_OUTPUT_PREFIX.index('{')]}*" |
| 224 |
args.paths = [p for p in glob.glob(pattern)] |
| 225 |
|
| 226 |
if args.format == "auto": |
| 227 |
args.format = "summaries" if pyout is None else "pyout" |
| 228 |
|
| 229 |
formatter = SummaryFormatter( |
| 230 |
enable_colors=False if args.format == "pyout" else args.colors |
| 231 |
) |
| 232 |
info_files = [path for path in args.paths if is_info_file(path)] |
| 233 |
run_data_raw = load_duct_runs(info_files, args.eval_filter) |
| 234 |
output_rows = process_run_data(run_data_raw, args.fields, formatter) |
| 235 |
|
| 236 |
if args.reverse: |
| 237 |
output_rows = list(reversed(output_rows)) |
| 238 |
|
| 239 |
if args.format == "summaries": |
| 240 |
for row in output_rows: |
| 241 |
for col, value in row.items(): |
| 242 |
if not col == "prefix": |
| 243 |
col = f"\t{col}" |
| 244 |
print(f"{col.replace('_', ' ').title()}: {value}") |
| 245 |
elif args.format == "pyout": |
| 246 |
if pyout is None: |
| 247 |
raise RuntimeError("Install pyout for pyout output") |
| 248 |
pyout_ls(output_rows, args.colors) |
| 249 |
elif args.format == "json": |
| 250 |
print(json.dumps(output_rows)) |
| 251 |
elif args.format == "json_pp": |
| 252 |
print(json.dumps(output_rows, indent=2)) |
| 253 |
elif args.format == "yaml": |
| 254 |
if yaml is None: |
| 255 |
raise RuntimeError("Install PyYaml yaml output") |
| 256 |
plain_rows = [dict(row) for row in output_rows] |
| 257 |
print(yaml.dump(plain_rows, default_flow_style=False)) |
| 258 |
else: |
| 259 |
raise RuntimeError( |
| 260 |
f"Unexpected format encountered: {args.format}. This should have been caught by argparse.", |
| 261 |
) |
| 262 |
return 0 |