Debian Codegraph @

src/con_duct/_duct_main.py

raw symbols SCIP
1 from __future__ import annotations
2 from importlib.metadata import version
3 import logging
4 import os
5 import signal
6 import subprocess
7 import threading
8 import time
9 from typing import IO, TextIO
10 from con_duct._models import LogPaths, Outputs, RecordTypes, SessionMode
11 from con_duct._output import TailPipe, prepare_outputs, remove_files, safe_close_files
12 from con_duct._signals import SigIntHandler
13 from con_duct._tracker import Report, monitor_process
14
15 __version__ = version("con-duct")
16
17 lgr = logging.getLogger("con-duct")
18
19 DUCT_OUTPUT_PREFIX = os.getenv("DUCT_OUTPUT_PREFIX", ".duct/logs/{datetime}-{pid}_")
20 EXECUTION_SUMMARY_FORMAT = (
21 "Summary:\n"
22 "Exit Code: {exit_code!E}\n"
23 "Command: {command}\n"
24 "Log files location: {logs_prefix}\n"
25 "Wall Clock Time: {wall_clock_time:.3f} sec\n"
26 "Memory Peak Usage (RSS): {peak_rss!S}\n"
27 "Memory Average Usage (RSS): {average_rss!S}\n"
28 "Virtual Memory Peak Usage (VSZ): {peak_vsz!S}\n"
29 "Virtual Memory Average Usage (VSZ): {average_vsz!S}\n"
30 "Memory Peak Percentage: {peak_pmem:.2f!N}%\n"
31 "Memory Average Percentage: {average_pmem:.2f!N}%\n"
32 "CPU Peak Usage: {peak_pcpu:.2f!N}%\n"
33 "Average CPU Usage: {average_pcpu:.2f!N}%\n"
34 )
35
36
37 def execute(
38 command: str,
39 command_args: list[str],
40 output_prefix: str,
41 sample_interval: float,
42 report_interval: float,
43 fail_time: float,
44 clobber: bool,
45 capture_outputs: Outputs,
46 outputs: Outputs,
47 record_types: RecordTypes,
48 summary_format: str,
49 colors: bool,
50 mode: SessionMode,
51 message: str = "",
52 ) -> int:
53 """A wrapper to execute a command, monitor and log the process details.
54
55 Returns exit code of the executed process.
56 """
57 if report_interval < sample_interval:
58 raise ValueError(
59 "--report-interval must be greater than or equal to --sample-interval."
60 )
61 if sample_interval < 1.0:
62 lgr.warning(
63 "--sample-interval=%.3f is below 1.0s and may behave erratically. "
64 "See docs/resource-statistics.md for details.",
65 sample_interval,
66 )
67
68 log_paths = LogPaths.create(output_prefix, pid=os.getpid())
69 try:
70 log_paths.prepare_paths(clobber, capture_outputs)
71 except FileExistsError as e:
72 lgr.error("%s", e)
73 return 1
74 stdout, stderr = prepare_outputs(capture_outputs, outputs, log_paths)
75 stdout_file: TextIO | IO[bytes] | int | None
76 if isinstance(stdout, TailPipe):
77 stdout_file = open(stdout.file_path, "wb")
78 else:
79 stdout_file = stdout
80 stderr_file: TextIO | IO[bytes] | int | None
81 if isinstance(stderr, TailPipe):
82 stderr_file = open(stderr.file_path, "wb")
83 else:
84 stderr_file = stderr
85
86 working_directory = os.getcwd()
87 full_command = " ".join([str(command)] + command_args)
88 files_to_close = [stdout_file, stdout, stderr_file, stderr]
89
90 report = Report(
91 command,
92 command_args,
93 log_paths,
94 summary_format,
95 working_directory,
96 colors,
97 clobber,
98 message=message,
99 )
100 files_to_close.append(report.usage_file)
101
102 report.start_time = time.time()
103 try:
104 report.process = process = subprocess.Popen(
105 [str(command)] + command_args,
106 stdout=stdout_file,
107 stderr=stderr_file,
108 start_new_session=(mode == SessionMode.NEW_SESSION),
109 cwd=report.working_directory,
110 )
111 except FileNotFoundError:
112 # We failed to execute due to file not found in PATH
113 # We should remove log etc files since they are 0-sized
114 # degenerates etc
115 safe_close_files(files_to_close)
116 remove_files(log_paths, assert_empty=True)
117 # mimicking behavior of bash and zsh.
118 lgr.error("%s: command not found", command)
119 return 127 # seems what zsh and bash return then
120
121 signal.signal(signal.SIGINT, SigIntHandler(process.pid))
122 lgr.info("duct %s is executing %r...", __version__, full_command)
123 lgr.info("Log files will be written to %s", log_paths.prefix)
124 try:
125 if mode == SessionMode.NEW_SESSION:
126 report.session_id = os.getsid(
127 process.pid
128 ) # Get session ID of the new process
129 else: # CURRENT_SESSION mode
130 report.session_id = os.getsid(
131 os.getpid()
132 ) # Get session ID of duct's own process
133 except ProcessLookupError: # process has already finished
134 # TODO: log this at least.
135 pass
136 stop_event = threading.Event()
137 if record_types.has_processes_samples():
138 monitoring_args = [
139 report,
140 process,
141 report_interval,
142 sample_interval,
143 stop_event,
144 ]
145 monitoring_thread = threading.Thread(
146 target=monitor_process, args=monitoring_args
147 )
148 monitoring_thread.start()
149 else:
150 monitoring_thread = None
151
152 if record_types.has_system_summary():
153 env_thread = threading.Thread(target=report.collect_environment)
154 env_thread.start()
155 sys_info_thread = threading.Thread(target=report.get_system_info)
156 sys_info_thread.start()
157 else:
158 env_thread, sys_info_thread = None, None
159
160 process.wait()
161 report.end_time = time.time()
162 lgr.debug("Process ended, setting stop_event to stop monitoring thread")
163 stop_event.set()
164 if monitoring_thread is not None:
165 lgr.debug("Waiting for monitoring thread to finish")
166 monitoring_thread.join()
167 lgr.debug("Monitoring thread finished")
168
169 # If we have any extra samples that haven't been written yet, do it now
170 if report.current_sample is not None:
171 report.write_subreport()
172
173 report.process = process
174 if env_thread is not None:
175 lgr.debug("Waiting for environment collection thread to finish")
176 env_thread.join()
177 lgr.debug("Environment collection finished")
178
179 if sys_info_thread is not None:
180 lgr.debug("Waiting for system information collection thread to finish")
181 sys_info_thread.join()
182 lgr.debug("System information collection finished")
183
184 if record_types.has_system_summary():
185 with open(log_paths.info, "w") as system_logs:
186 report.run_time_seconds = f"{report.end_time - report.start_time}"
187 system_logs.write(report.dump_json())
188 safe_close_files(files_to_close)
189 if process.returncode != 0 and (report.elapsed_time < fail_time or fail_time < 0):
190 lgr.info(
191 "Removing log files since command failed%s.",
192 f" in less than {fail_time} seconds" if fail_time > 0 else "",
193 )
194 remove_files(log_paths)
195 else:
196 lgr.info(report.execution_summary_formatted)
197 return report.process.returncode