Debian Codegraph @

src/con_duct/cli.py

raw symbols SCIP
1 import argparse
2 import logging
3 import os
4 from pathlib import Path
5 import re
6 import sys
7 import textwrap
8 from typing import List, Optional
9 from con_duct import __version__
10 from con_duct._duct_main import DUCT_OUTPUT_PREFIX, EXECUTION_SUMMARY_FORMAT
11 from con_duct._duct_main import execute as duct_execute
12 from con_duct._models import Outputs, RecordTypes, SessionMode
13 from con_duct.ls import LS_FIELD_CHOICES, ls
14 from con_duct.plot import CPU_MODE_PS_PCPU, CPU_MODES, matplotlib_plot
15 from con_duct.pprint_json import pprint_json
16
17 # Default .env file search paths (in precedence order)
18 DEFAULT_CONFIG_PATHS_LIST = (
19 "/etc/duct/.env",
20 "${XDG_CONFIG_HOME:-~/.config}/duct/.env",
21 ".duct/.env",
22 )
23 DEFAULT_CONFIG_PATHS = os.pathsep.join(DEFAULT_CONFIG_PATHS_LIST)
24
25
26 def load_duct_env_files() -> List[tuple[str, str]]:
27 """Load environment variables from .env files in multiple locations.
28
29 Searches for .env files specified in DUCT_CONFIG_PATHS (or DEFAULT_CONFIG_PATHS).
30 Files are loaded in reverse order so later files override earlier ones.
31
32 Environment variables already set in the environment will NOT be overridden
33 by values from .env files, maintaining proper precedence:
34 CLI args > explicit env vars > .env files > hardcoded defaults
35
36 Gracefully handles missing python-dotenv package or missing .env files.
37
38 Returns:
39 List of (level_name, message) tuples for deferred logging.
40 """
41 log_buffer: List[tuple[str, str]] = []
42
43 try:
44 from dotenv import load_dotenv
45 except ImportError:
46 # python-dotenv not installed, skip .env file loading
47 log_buffer.append(
48 ("INFO", "python-dotenv not installed, skipping .env file loading")
49 )
50 return log_buffer
51
52 config_paths_str = os.getenv("DUCT_CONFIG_PATHS", DEFAULT_CONFIG_PATHS)
53 log_buffer.append(("DEBUG", f"Searching for .env files in: {config_paths_str}"))
54
55 # Expand ${VAR:-default} syntax in the paths string ie ${XDG_CONFIG_HOME:-~/.config}
56 def expand_var(match: re.Match) -> str:
57 var_expr = match.group(1)
58 if ":-" in var_expr:
59 var_name, default = var_expr.split(":-", 1)
60 return os.getenv(var_name, default)
61 return os.getenv(var_expr, "")
62
63 config_paths_str = re.sub(r"\$\{([^}]+)\}", expand_var, config_paths_str)
64 search_paths = [
65 val for p in config_paths_str.split(os.pathsep) if (val := p.strip())
66 ]
67
68 # Load in reverse order so later paths override earlier ones (once set, vars are skipped)
69 loaded_count = 0
70 for path in reversed(search_paths):
71 expanded_path = Path(path).expanduser()
72 if expanded_path.exists():
73 log_buffer.append(("INFO", f"Loading .env file: {expanded_path}"))
74 try:
75 load_dotenv(expanded_path, override=False)
76 loaded_count += 1
77 except PermissionError as e:
78 log_buffer.append(
79 ("WARNING", f"Cannot read .env file {expanded_path}: {e}")
80 )
81 except ValueError as e:
82 log_buffer.append(
83 ("WARNING", f"Skipping malformed .env file {expanded_path}: {e}")
84 )
85 else:
86 log_buffer.append(
87 ("DEBUG", f".env file not found (skipping): {expanded_path}")
88 )
89
90 if loaded_count == 0:
91 log_buffer.append(("INFO", "No .env files found"))
92
93 return log_buffer
94
95
96 def _replay_early_logs(log_buffer: List[tuple[str, str]]) -> None:
97 """Replay buffered log messages through the configured logger.
98
99 Should be called after setup_logging() to ensure buffered messages from
100 .env file loading are properly logged with the user's chosen log level.
101
102 Args:
103 log_buffer: List of (level_name, message) tuples to replay.
104 """
105 for level_name, message in log_buffer:
106 lgr.log(getattr(logging, level_name), message)
107
108
109 lgr = logging.getLogger("con-duct")
110
111 # Format default config paths as a bulleted list for help text
112 _config_paths_list = "\n".join(f" - {path}" for path in DEFAULT_CONFIG_PATHS_LIST)
113
114 ABOUT_DUCT = f"""
115 duct is a lightweight wrapper that collects execution data for an arbitrary
116 command. This command can be invoked as either 'duct' or 'con-duct run'.
117
118 Execution data includes execution time, system information, and resource usage
119 statistics of the command and all its child processes. It is intended to
120 simplify the problem of recording the resources necessary to execute a command,
121 particularly in an HPC environment.
122
123 Resource usage is determined by polling (at a sample-interval).
124 During execution, duct produces a JSON lines (see https://jsonlines.org) file
125 with one data point recorded for each report (at a report-interval).
126
127 limitations:
128 Duct uses session id to track the command process and its children, so it
129 cannot handle the situation where a process creates a new session.
130 If a command spawns child processes, duct will collect data on them, but
131 duct exits as soon as the primary process exits.
132
133 environment variables:
134 Many duct options can be configured by environment variables (which are
135 overridden by command line options).
136
137 DUCT_LOG_LEVEL: see --log-level
138 DUCT_OUTPUT_PREFIX: see --output-prefix
139 DUCT_SUMMARY_FORMAT: see --summary-format
140 DUCT_SAMPLE_INTERVAL: see --sample-interval
141 DUCT_REPORT_INTERVAL: see --report-interval
142 DUCT_CAPTURE_OUTPUTS: see --capture-outputs
143 DUCT_MESSAGE: see --message
144 DUCT_CONFIG_PATHS: paths to .env files separated by platform path separator
145 (':' on Unix) (see below)
146
147 .env files:
148 Environment variables can also be set via .env files. By default, duct
149 searches the following locations (later files override earlier ones):
150
151 {_config_paths_list}
152
153 Override the search paths by setting DUCT_CONFIG_PATHS with paths separated
154 by the platform path separator (':' on Unix)
155 (e.g., export DUCT_CONFIG_PATHS="/custom/path.env:~/.myduct.env").
156
157 Example .env file content:
158 # Set default log level
159 DUCT_LOG_LEVEL=DEBUG
160
161 # Configure intervals
162 DUCT_SAMPLE_INTERVAL=2.0
163 DUCT_REPORT_INTERVAL=120.0
164
165 # Set default output location
166 DUCT_OUTPUT_PREFIX=~/duct-logs/{{datetime}}-{{pid}}_
167
168 # Add execution notes (multiline)
169 DUCT_MESSAGE="Experiment run for paper revision
170 Using updated dataset from 2025-10-30
171 See lab notebook page 42 for details"
172
173 Supported .env syntax (via python-dotenv):
174 - KEY=value (basic assignment)
175 - KEY="value with spaces" (quoted values)
176 - KEY='single quotes' (single-quoted values)
177 - # comments (hash comments)
178 - Empty lines (ignored)
179 - Multiline values (use quotes)
180
181 Precedence (highest to lowest):
182 1. Command line arguments
183 2. Explicit environment variables
184 3. .env file values (later paths override earlier paths)
185 4. Hardcoded defaults
186
187 Notes:
188 - .env file support requires python-dotenv (pip install con-duct[all])
189 - DUCT_CONFIG_PATHS cannot be set in .env files (must be set before loading)
190 - Malformed, unreadable, or missing .env files are skipped and logged
191 """
192
193
194 class CustomHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
195 """Override allows helptext to respect newlines in ABOUT_DUCT"""
196
197 def _fill_text(self, text: str, width: int, _indent: str) -> str:
198 return "\n".join([textwrap.fill(line, width) for line in text.splitlines()])
199
200
201 def _create_common_parser() -> argparse.ArgumentParser:
202 """Create a parser with common arguments shared across all commands."""
203 parser = argparse.ArgumentParser(add_help=False) # help provided by child
204 parser.add_argument(
205 "-l",
206 "--log-level",
207 default=os.getenv("DUCT_LOG_LEVEL", "INFO").upper(),
208 choices=("NONE", "CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"),
209 type=str.upper,
210 help="Level of log output to stderr, use NONE to entirely disable.",
211 )
212 parser.add_argument(
213 "-q",
214 "--quiet",
215 action="store_true",
216 help="[deprecated, use log level NONE] Disable duct logging output (to stderr)",
217 )
218 return parser
219
220
221 def setup_logging(args: argparse.Namespace) -> None:
222 """Configure logging based on parsed arguments.
223
224 Handles both --log-level and --quiet flags, applying them consistently
225 across all subcommands.
226 """
227 log_level = args.log_level
228
229 # Handle deprecated --quiet flag
230 if args.quiet:
231 log_level = "NONE"
232
233 # Special case: NONE means disable all logging
234 if log_level == "NONE":
235 logging.disable(logging.CRITICAL)
236 else:
237 logging.basicConfig(
238 format="%(asctime)s [%(levelname)-8s] %(name)s: %(message)s",
239 datefmt="%Y-%m-%dT%H:%M:%S%z",
240 level=log_level,
241 )
242
243
244 def _create_run_parser() -> argparse.ArgumentParser:
245 """Create and configure the argument parser for the 'run' command."""
246 parser = argparse.ArgumentParser(
247 allow_abbrev=False,
248 description=ABOUT_DUCT,
249 formatter_class=CustomHelpFormatter,
250 add_help=False, # help provided by child
251 )
252 parser.add_argument(
253 "command",
254 metavar="command [command_args ...]",
255 help="The command to execute, along with its arguments.",
256 )
257 parser.add_argument(
258 "--version", action="version", version=f"%(prog)s {__version__}"
259 )
260 parser.add_argument(
261 "command_args", nargs=argparse.REMAINDER, help="Arguments for the command."
262 )
263 parser.add_argument(
264 "-p",
265 "--output-prefix",
266 type=str,
267 default=DUCT_OUTPUT_PREFIX,
268 help="File string format to be used as a prefix for the files -- the captured "
269 "stdout and stderr and the resource usage logs. The understood variables are "
270 "{datetime} and {pid}. "
271 "Leading directories will be created if they do not exist. "
272 "You can also provide value via DUCT_OUTPUT_PREFIX env variable. ",
273 )
274 parser.add_argument(
275 "--summary-format",
276 type=str,
277 default=os.getenv("DUCT_SUMMARY_FORMAT", EXECUTION_SUMMARY_FORMAT),
278 help="Output template to use when printing the summary following execution. "
279 "Accepts custom conversion flags: "
280 "!S: Converts filesizes to human readable units, green if measured, red if None. "
281 "!E: Colors exit code, green if falsey, red if truthy, and red if None. "
282 "!X: Colors green if truthy, red if falsey. "
283 "!N: Colors green if not None, red if None",
284 )
285 parser.add_argument(
286 "--colors",
287 action="store_true",
288 default=os.getenv("DUCT_COLORS", False),
289 help="Use colors in duct output.",
290 )
291 parser.add_argument(
292 "--clobber",
293 action="store_true",
294 help="Replace log files if they already exist.",
295 )
296 parser.add_argument(
297 "--sample-interval",
298 "--s-i",
299 type=float,
300 default=float(os.getenv("DUCT_SAMPLE_INTERVAL", "1.0")),
301 help="Interval in seconds between status checks of the running process. "
302 "Sample interval must be less than or equal to report interval, and it achieves the "
303 "best results when sample is significantly less than the runtime of the process. "
304 "Values below 1.0 behave erratically.",
305 )
306 parser.add_argument(
307 "--report-interval",
308 "--r-i",
309 type=float,
310 default=float(os.getenv("DUCT_REPORT_INTERVAL", "60.0")),
311 help="Interval in seconds at which to report aggregated data.",
312 )
313 parser.add_argument(
314 "--fail-time",
315 "--f-t",
316 type=float,
317 default=float(os.getenv("DUCT_FAIL_TIME", "3.0")),
318 help="If command fails in less than this specified time (seconds), duct would remove logs. "
319 "Set to 0 if you would like to keep logs for a failing command regardless of its run time. "
320 "Set to negative (e.g. -1) if you would like to not keep logs for any failing command.",
321 )
322
323 parser.add_argument(
324 "-c",
325 "--capture-outputs",
326 default=os.getenv("DUCT_CAPTURE_OUTPUTS", "all"),
327 choices=list(Outputs),
328 type=Outputs,
329 help="Record stdout, stderr, all, or none to log files. "
330 "You can also provide value via DUCT_CAPTURE_OUTPUTS env variable.",
331 )
332 parser.add_argument(
333 "-o",
334 "--outputs",
335 default="all",
336 choices=list(Outputs),
337 type=Outputs,
338 help="Print stdout, stderr, all, or none to stdout/stderr respectively.",
339 )
340 parser.add_argument(
341 "-t",
342 "--record-types",
343 default="all",
344 choices=list(RecordTypes),
345 type=RecordTypes,
346 help="Record system-summary, processes-samples, or all",
347 )
348 parser.add_argument(
349 "-m",
350 "--message",
351 type=str,
352 default=os.getenv("DUCT_MESSAGE", ""),
353 help="Record a descriptive message about the purpose of this execution. "
354 "You can also provide value via DUCT_MESSAGE env variable.",
355 )
356 parser.add_argument(
357 "--mode",
358 default="new-session",
359 choices=list(SessionMode),
360 type=SessionMode,
361 help="Session mode: 'new-session' creates a new session for the command (default), "
362 "'current-session' tracks the current session instead of starting a new one. "
363 "Useful for tracking slurm jobs or other commands that should run in the current session.",
364 )
365 return parser
366
367
368 def _create_pp_parser() -> argparse.ArgumentParser:
369 """Create and configure the argument parser for the 'pp' command."""
370 parser = argparse.ArgumentParser(
371 add_help=False, # help provided by child
372 )
373 parser.add_argument("file_path", help="JSON file to pretty print.")
374 parser.add_argument(
375 "-H",
376 "--humanize",
377 action="store_true",
378 help="Convert numeric values to human-readable format",
379 )
380 return parser
381
382
383 def _create_plot_parser() -> argparse.ArgumentParser:
384 """Create and configure the argument parser for the 'plot' command."""
385 parser = argparse.ArgumentParser(
386 add_help=False, # help provided by child
387 )
388 parser.add_argument("file_path", help="duct-produced usage file.")
389 parser.add_argument(
390 "-o",
391 "--output",
392 help="Output path for the image file. If not specified, plot will be shown "
393 "interactively (requires a display). Use this option in headless/server environments.",
394 default=None,
395 )
396 parser.add_argument(
397 "--min-ratio",
398 type=float,
399 default=3.0,
400 help="Minimum ratio for axis unit selection (default: 3.0). Lower values use larger units sooner. "
401 "Use -1 to always use base units (seconds, bytes).",
402 )
403 parser.add_argument(
404 "--cpu",
405 choices=CPU_MODES,
406 default=CPU_MODE_PS_PCPU,
407 help="Which CPU value to plot. 'ps-pcpu' uses the raw lifetime ratio "
408 "from ps with no transformation. 'ps-cpu-timepoint' computes a "
409 "delta-corrected time-point estimate from consecutive (pcpu, etime) "
410 "pairs.",
411 )
412 return parser
413
414
415 def _create_ls_parser() -> argparse.ArgumentParser:
416 """Create and configure the argument parser for the 'ls' command."""
417 parser = argparse.ArgumentParser(
418 add_help=False, # help provided by child
419 )
420 parser.add_argument(
421 "-f",
422 "--format",
423 choices=("auto", "pyout", "summaries", "json", "json_pp", "yaml"),
424 default="auto",
425 help="Output format. TODO Fixme. 'auto' chooses 'pyout' if pyout library is installed,"
426 " 'summaries' otherwise.",
427 )
428 parser.add_argument(
429 "-F",
430 "--fields",
431 nargs="+",
432 metavar="FIELD",
433 help=f"List of fields to show. Prefix is always included implicitly as the first field. "
434 f"Available choices: {', '.join(sorted(LS_FIELD_CHOICES))}.",
435 choices=LS_FIELD_CHOICES,
436 default=[
437 "command",
438 "exit_code",
439 "wall_clock_time",
440 "peak_rss",
441 ],
442 )
443 parser.add_argument(
444 "--colors",
445 action="store_true",
446 default=os.getenv("DUCT_COLORS", False),
447 help="Use colors in duct output.",
448 )
449 parser.add_argument(
450 "paths",
451 nargs="*",
452 help="Path to duct report files, only `info.json` would be considered. "
453 "If not provided, the program will glob for files that match DUCT_OUTPUT_PREFIX.",
454 )
455 parser.add_argument(
456 "-e",
457 "--eval-filter",
458 help="Python expression to filter results based on available fields. "
459 "The expression is evaluated for each entry, and only those that return True are included. "
460 "See --fields for all supported fields. "
461 "Example: --eval-filter \"filter_this=='yes'\" filters entries where 'filter_this' is 'yes'. "
462 "You can use 're' for regex operations (e.g., --eval-filter \"re.search('2025.02.09.*', prefix)\").",
463 )
464 parser.add_argument(
465 "--reverse",
466 action="store_true",
467 help="List entries in reverse order (most recent first).",
468 )
469 return parser
470
471
472 def run_command(args: argparse.Namespace) -> int:
473 """Execute a command with duct monitoring."""
474 kwargs = vars(args).copy()
475 # Remove arguments that are not for duct_execute
476 for key in ("func", "log_level", "quiet"):
477 kwargs.pop(key, None)
478 return duct_execute(**kwargs)
479
480
481 def execute(args: argparse.Namespace) -> int:
482 """Execute the subcommand function and return its exit code."""
483 result = args.func(args)
484 if not isinstance(result, int):
485 raise TypeError(
486 f"Each con-duct subcommand must return an int returncode, got {type(result)}"
487 )
488 return result
489
490
491 def duct_entrypoint() -> None:
492 """Entry point for the 'duct' command - delegates to 'con-duct run'."""
493 os.execvp("con-duct", ["con-duct", "run"] + sys.argv[1:])
494
495
496 def main(argv: Optional[List[str]] = None) -> None:
497 # Load .env files before parser creation so defaults pick up env vars
498 env_log_buffer = load_duct_env_files()
499
500 parser = argparse.ArgumentParser(
501 prog="con-duct",
502 description="A suite of commands to manage or manipulate con-duct logs.",
503 usage="con-duct <command> [options]",
504 )
505 parser.add_argument(
506 "--version", action="version", version=f"%(prog)s {__version__}"
507 )
508 common_parser = _create_common_parser()
509 subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
510
511 # Subcommand: run
512 parser_run = subparsers.add_parser(
513 "run",
514 help="Execute a command with duct monitoring.",
515 description=ABOUT_DUCT,
516 parents=[common_parser, _create_run_parser()],
517 formatter_class=CustomHelpFormatter,
518 allow_abbrev=False,
519 prog="con-duct run",
520 )
521 parser_run.set_defaults(func=run_command)
522
523 # Subcommand: pp
524 parser_pp = subparsers.add_parser(
525 "pp",
526 help="Pretty print a JSON log.",
527 parents=[common_parser, _create_pp_parser()],
528 prog="con-duct pp",
529 )
530 parser_pp.set_defaults(func=pprint_json)
531
532 # Subcommand: plot
533 parser_plot = subparsers.add_parser(
534 "plot",
535 help="Plot resource usage for an execution.",
536 parents=[common_parser, _create_plot_parser()],
537 prog="con-duct plot",
538 )
539 parser_plot.set_defaults(func=matplotlib_plot)
540
541 parser_ls = subparsers.add_parser(
542 "ls",
543 help="Print execution information for all matching runs.",
544 parents=[common_parser, _create_ls_parser()],
545 prog="con-duct ls",
546 )
547 parser_ls.set_defaults(func=ls)
548
549 args = parser.parse_args(argv)
550
551 if args.command is None:
552 parser.print_help()
553 return
554
555 setup_logging(args)
556 _replay_early_logs(env_log_buffer)
557 sys.exit(execute(args))
558
559
560 # To allow users or devs to invoke the `cli.py` directly
561 # instead of the entrypoint `con-duct`
562 # (used mainly by PyInstaller)
563 if __name__ == "__main__":
564 main()