|
| 1 | +"""This module contains the code to profile the execution.""" |
| 2 | +import csv |
| 3 | +import json |
| 4 | +import sys |
| 5 | +import time |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import click |
| 9 | +from _pytask.config import hookimpl |
| 10 | +from _pytask.console import console |
| 11 | +from _pytask.database import db |
| 12 | +from _pytask.enums import ColorCode |
| 13 | +from _pytask.enums import ExitCode |
| 14 | +from _pytask.exceptions import CollectionError |
| 15 | +from _pytask.exceptions import ConfigurationError |
| 16 | +from _pytask.nodes import FilePathNode |
| 17 | +from _pytask.nodes import reduce_node_name |
| 18 | +from _pytask.pluginmanager import get_plugin_manager |
| 19 | +from _pytask.session import Session |
| 20 | +from _pytask.shared import get_first_non_none_value |
| 21 | +from pony import orm |
| 22 | +from rich.table import Table |
| 23 | +from rich.traceback import Traceback |
| 24 | + |
| 25 | + |
| 26 | +class Runtime(db.Entity): |
| 27 | + """Record of runtimes of tasks.""" |
| 28 | + |
| 29 | + task = orm.PrimaryKey(str) |
| 30 | + date = orm.Required(float) |
| 31 | + duration = orm.Required(float) |
| 32 | + |
| 33 | + |
| 34 | +@hookimpl(tryfirst=True) |
| 35 | +def pytask_extend_command_line_interface(cli: click.Group): |
| 36 | + """Extend the command line interface.""" |
| 37 | + cli.add_command(profile) |
| 38 | + |
| 39 | + |
| 40 | +@hookimpl |
| 41 | +def pytask_parse_config(config, config_from_cli): |
| 42 | + """Parse the configuration.""" |
| 43 | + config["export"] = get_first_non_none_value( |
| 44 | + config_from_cli, key="export", default=None |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +@hookimpl |
| 49 | +def pytask_post_parse(config): |
| 50 | + """Register the export option.""" |
| 51 | + config["pm"].register(ExportNameSpace) |
| 52 | + config["pm"].register(DurationNameSpace) |
| 53 | + config["pm"].register(FileSizeNameSpace) |
| 54 | + |
| 55 | + |
| 56 | +@hookimpl(hookwrapper=True) |
| 57 | +def pytask_execute_task(task): |
| 58 | + """Attach the duration of the execution to the task.""" |
| 59 | + start = time.time() |
| 60 | + yield |
| 61 | + end = time.time() |
| 62 | + task.attributes["duration"] = (start, end) |
| 63 | + |
| 64 | + |
| 65 | +@hookimpl |
| 66 | +def pytask_execute_task_process_report(report): |
| 67 | + """Store runtime of successfully finishing tasks in database.""" |
| 68 | + task = report.task |
| 69 | + duration = task.attributes.get("duration") |
| 70 | + if report.success and duration is not None: |
| 71 | + _create_or_update_runtime(task.name, *duration) |
| 72 | + |
| 73 | + |
| 74 | +@orm.db_session |
| 75 | +def _create_or_update_runtime(task_name, start, end): |
| 76 | + """Create or update a runtime entry.""" |
| 77 | + try: |
| 78 | + runtime = Runtime[task_name] |
| 79 | + except orm.ObjectNotFound: |
| 80 | + Runtime(task=task_name, date=start, duration=end - start) |
| 81 | + else: |
| 82 | + for attr, val in [("date", start), ("duration", end - start)]: |
| 83 | + setattr(runtime, attr, val) |
| 84 | + |
| 85 | + |
| 86 | +@click.command() |
| 87 | +@click.option( |
| 88 | + "--export", |
| 89 | + type=str, |
| 90 | + default=None, |
| 91 | + help="Export the profile in the specified format.", |
| 92 | +) |
| 93 | +def profile(**config_from_cli): |
| 94 | + """Show profile information on collected tasks.""" |
| 95 | + config_from_cli["command"] = "profile" |
| 96 | + |
| 97 | + try: |
| 98 | + # Duplication of the same mechanism in :func:`pytask.main.main`. |
| 99 | + pm = get_plugin_manager() |
| 100 | + from _pytask import cli |
| 101 | + |
| 102 | + pm.register(cli) |
| 103 | + pm.hook.pytask_add_hooks(pm=pm) |
| 104 | + |
| 105 | + config = pm.hook.pytask_configure(pm=pm, config_from_cli=config_from_cli) |
| 106 | + session = Session.from_config(config) |
| 107 | + |
| 108 | + except (ConfigurationError, Exception): |
| 109 | + session = Session({}, None) |
| 110 | + session.exit_code = ExitCode.CONFIGURATION_FAILED |
| 111 | + console.print(Traceback.from_exception(*sys.exc_info())) |
| 112 | + |
| 113 | + else: |
| 114 | + try: |
| 115 | + session.hook.pytask_log_session_header(session=session) |
| 116 | + session.hook.pytask_collect(session=session) |
| 117 | + session.hook.pytask_resolve_dependencies(session=session) |
| 118 | + |
| 119 | + profile = {task.name: {} for task in session.tasks} |
| 120 | + session.hook.pytask_profile_add_info_on_task( |
| 121 | + session=session, tasks=session.tasks, profile=profile |
| 122 | + ) |
| 123 | + profile = _process_profile(profile) |
| 124 | + |
| 125 | + _print_profile_table(profile, session.tasks, session.config["paths"]) |
| 126 | + |
| 127 | + session.hook.pytask_profile_export_profile(session=session, profile=profile) |
| 128 | + |
| 129 | + console.rule(style=ColorCode.NEUTRAL) |
| 130 | + |
| 131 | + except CollectionError: |
| 132 | + session.exit_code = ExitCode.COLLECTION_FAILED |
| 133 | + |
| 134 | + except Exception: |
| 135 | + session.exit_code = ExitCode.FAILED |
| 136 | + console.print_exception() |
| 137 | + console.rule(style=ColorCode.FAILED) |
| 138 | + |
| 139 | + sys.exit(session.exit_code) |
| 140 | + |
| 141 | + |
| 142 | +def _print_profile_table(profile, tasks, paths): |
| 143 | + """Print the profile table.""" |
| 144 | + name_to_task = {task.name: task for task in tasks} |
| 145 | + info_names = _get_info_names(profile) |
| 146 | + |
| 147 | + console.print() |
| 148 | + if profile: |
| 149 | + table = Table("Task") |
| 150 | + for name in info_names: |
| 151 | + table.add_column(name, justify="right") |
| 152 | + |
| 153 | + for task_name, info in profile.items(): |
| 154 | + reduced_name = reduce_node_name(name_to_task[task_name], paths) |
| 155 | + infos = [str(i) for i in info.values()] |
| 156 | + table.add_row(reduced_name, *infos) |
| 157 | + |
| 158 | + console.print(table) |
| 159 | + else: |
| 160 | + console.print("No information is stored on the collected tasks.") |
| 161 | + |
| 162 | + |
| 163 | +class DurationNameSpace: |
| 164 | + @staticmethod |
| 165 | + @hookimpl |
| 166 | + def pytask_profile_add_info_on_task(tasks, profile): |
| 167 | + runtimes = _collect_runtimes([task.name for task in tasks]) |
| 168 | + for name, duration in runtimes.items(): |
| 169 | + profile[name]["Last Duration (in s)"] = round(duration, 2) |
| 170 | + |
| 171 | + |
| 172 | +@orm.db_session |
| 173 | +def _collect_runtimes(task_names): |
| 174 | + """Collect runtimes.""" |
| 175 | + runtimes = [Runtime.get(task=task_name) for task_name in task_names] |
| 176 | + runtimes = [r for r in runtimes if r is not None] |
| 177 | + return {r.task: r.duration for r in runtimes} |
| 178 | + |
| 179 | + |
| 180 | +class FileSizeNameSpace: |
| 181 | + @staticmethod |
| 182 | + @hookimpl |
| 183 | + def pytask_profile_add_info_on_task(session, tasks, profile): |
| 184 | + for task in tasks: |
| 185 | + successors = list(session.dag.successors(task.name)) |
| 186 | + if successors: |
| 187 | + sum_bytes = 0 |
| 188 | + for successor in successors: |
| 189 | + node = session.dag.nodes[successor]["node"] |
| 190 | + if isinstance(node, FilePathNode): |
| 191 | + try: |
| 192 | + sum_bytes += node.path.stat().st_size |
| 193 | + except FileNotFoundError: |
| 194 | + pass |
| 195 | + |
| 196 | + profile[task.name]["Size of Products"] = _to_human_readable_size( |
| 197 | + sum_bytes |
| 198 | + ) |
| 199 | + |
| 200 | + |
| 201 | +def _to_human_readable_size(bytes_, units=None): |
| 202 | + """Convert bytes to a human readable size.""" |
| 203 | + units = [" bytes", "KB", "MB", "GB", "TB"] if units is None else units |
| 204 | + return ( |
| 205 | + str(bytes_) + units[0] |
| 206 | + if bytes_ < 1024 |
| 207 | + else _to_human_readable_size(bytes_ >> 10, units[1:]) |
| 208 | + ) |
| 209 | + |
| 210 | + |
| 211 | +def _process_profile(profile): |
| 212 | + """Process profile to make it ready for printing and storing.""" |
| 213 | + info_names = _get_info_names(profile) |
| 214 | + if info_names: |
| 215 | + complete_profiles = { |
| 216 | + task_name: { |
| 217 | + attr_name: profile[task_name].get(attr_name, "") |
| 218 | + for attr_name in info_names |
| 219 | + } |
| 220 | + for task_name in sorted(profile) |
| 221 | + } |
| 222 | + else: |
| 223 | + complete_profiles = {} |
| 224 | + return complete_profiles |
| 225 | + |
| 226 | + |
| 227 | +class ExportNameSpace: |
| 228 | + @staticmethod |
| 229 | + @hookimpl(trylast=True) |
| 230 | + def pytask_profile_export_profile(session, profile): |
| 231 | + extension = session.config["export"] |
| 232 | + |
| 233 | + if extension == "csv": |
| 234 | + _export_to_csv(profile) |
| 235 | + elif extension == "json": |
| 236 | + _export_to_json(profile) |
| 237 | + elif extension is None: |
| 238 | + pass |
| 239 | + else: |
| 240 | + raise ValueError(f"The export option '{extension}' cannot be handled.") |
| 241 | + |
| 242 | + |
| 243 | +def _export_to_csv(profile): |
| 244 | + """Export profile to csv.""" |
| 245 | + info_names = _get_info_names(profile) |
| 246 | + path = Path.cwd().joinpath("profile.csv") |
| 247 | + |
| 248 | + with open(path, "w", newline="") as file: |
| 249 | + writer = csv.writer(file) |
| 250 | + writer.writerow(("Task", *info_names)) |
| 251 | + for task_name, info in profile.items(): |
| 252 | + writer.writerow((task_name, *info.values())) |
| 253 | + |
| 254 | + |
| 255 | +def _export_to_json(profile): |
| 256 | + """Export profile to json.""" |
| 257 | + json_ = json.dumps(profile) |
| 258 | + path = Path.cwd().joinpath("profile.json") |
| 259 | + path.write_text(json_) |
| 260 | + |
| 261 | + |
| 262 | +def _get_info_names(profile): |
| 263 | + """Get names of infos of tasks.""" |
| 264 | + info_names = sorted(set().union(*[set(val) for val in profile.values()])) |
| 265 | + return info_names |
0 commit comments