|
| 1 | +import re |
| 2 | +import pandas as pd |
| 3 | +from pathlib import Path |
| 4 | +import subprocess |
| 5 | +import shlex |
| 6 | + |
| 7 | +import os # only temporarily needed for printf debugging |
| 8 | +import numpy as np |
| 9 | + |
| 10 | + |
| 11 | +def time_to_seconds(time_str): |
| 12 | + """Convert SLURM time format to seconds.""" |
| 13 | + if pd.isna(time_str) or time_str.strip() == "": |
| 14 | + return 0 |
| 15 | + parts = time_str.split(":") |
| 16 | + |
| 17 | + if len(parts) == 3: # H:M:S |
| 18 | + return int(parts[0]) * 3600 + int(parts[1]) * 60 + float(parts[2]) |
| 19 | + elif len(parts) == 2: # M:S |
| 20 | + return int(parts[0]) * 60 + float(parts[1]) |
| 21 | + elif len(parts) == 1: # S |
| 22 | + return float(parts[0]) |
| 23 | + return 0 |
| 24 | + |
| 25 | + |
| 26 | +def parse_maxrss(maxrss): |
| 27 | + """Convert MaxRSS to MB.""" |
| 28 | + if pd.isna(maxrss) or maxrss.strip() == "" or maxrss == "0": |
| 29 | + return 0 |
| 30 | + match = re.match(r"(\d+(?:\.\d+)?)([KMG]?)", maxrss) |
| 31 | + if match: |
| 32 | + value, unit = match.groups() |
| 33 | + value = float(value) |
| 34 | + unit_multipliers = {"K": 1 / 1024, "M": 1, "G": 1024} |
| 35 | + return value * unit_multipliers.get(unit, 1) |
| 36 | + return 0 |
| 37 | + |
| 38 | + |
| 39 | +def parse_reqmem(reqmem, number_of_nodes=1): |
| 40 | + """Convert requested memory to MB.""" |
| 41 | + if pd.isna(reqmem) or reqmem.strip() == "": |
| 42 | + return 0 |
| 43 | + # 4Gc (per-CPU) / 16Gn (per-node) / 2.5G |
| 44 | + match = re.match(r"(\d+(?:\.\d+)?)([KMG])?([cn]|/node)?", reqmem) |
| 45 | + if match: |
| 46 | + value, unit, per_unit = match.groups() |
| 47 | + value = float(value) |
| 48 | + unit_multipliers = {"K": 1 / 1024, "M": 1, "G": 1024} |
| 49 | + mem_mb = value * unit_multipliers.get(unit, 1) |
| 50 | + if per_unit in ("n", "/node"): # per-node |
| 51 | + nodes = 1 if pd.isna(number_of_nodes) else number_of_nodes |
| 52 | + return mem_mb * nodes |
| 53 | + # `/c` or `c` → per-CPU; caller may multiply later |
| 54 | + return mem_mb # Default case (per CPU or total) |
| 55 | + return 0 |
| 56 | + |
| 57 | + |
| 58 | +def create_efficiency_report(e_threshold, run_uuid, e_report_path, logger): |
| 59 | + """ |
| 60 | + Fetch sacct job data for a Snakemake workflow |
| 61 | + and compute efficiency metrics. |
| 62 | + """ |
| 63 | + cmd = f"sacct --name={run_uuid} --parsable2 --noheader" |
| 64 | + cmd += ( |
| 65 | + " --format=JobID,JobName,Comment,Elapsed,TotalCPU," "NNodes,NCPUS,MaxRSS,ReqMem" |
| 66 | + ) |
| 67 | + |
| 68 | + try: |
| 69 | + result = subprocess.run( |
| 70 | + shlex.split(cmd), capture_output=True, text=True, check=True |
| 71 | + ) |
| 72 | + raw = result.stdout.strip() |
| 73 | + if not raw: |
| 74 | + logger.warning(f"No job data found for workflow {run_uuid}.") |
| 75 | + return None |
| 76 | + lines = raw.split("\n") |
| 77 | + |
| 78 | + except subprocess.CalledProcessError: |
| 79 | + logger.error(f"Failed to retrieve job data for workflow {run_uuid}.") |
| 80 | + return None |
| 81 | + |
| 82 | + # Convert to DataFrame |
| 83 | + df = pd.DataFrame( |
| 84 | + (line.split("|") for line in lines), |
| 85 | + columns=[ |
| 86 | + "JobID", |
| 87 | + "JobName", |
| 88 | + "Comment", |
| 89 | + "Elapsed", |
| 90 | + "TotalCPU", |
| 91 | + "NNodes", |
| 92 | + "NCPUS", |
| 93 | + "MaxRSS", |
| 94 | + "ReqMem", |
| 95 | + ], |
| 96 | + ) |
| 97 | + |
| 98 | + # If the "Comment" column is empty, |
| 99 | + # a) delete the column |
| 100 | + # b) issue a warning |
| 101 | + if df["Comment"].replace("", pd.NA).isna().all(): |
| 102 | + logger.warning( |
| 103 | + f"No comments found for workflow {run_uuid}. " |
| 104 | + "This field is used to store the rule name. " |
| 105 | + "Please ensure that the 'comment' field is set for your cluster. " |
| 106 | + "Administrators can set this up in the SLURM configuration." |
| 107 | + ) |
| 108 | + df.drop(columns=["Comment"], inplace=True) |
| 109 | + # remember, that the comment column is not available |
| 110 | + nocomment = True |
| 111 | + # else: rename the column to 'RuleName' |
| 112 | + else: |
| 113 | + df.rename(columns={"Comment": "RuleName"}, inplace=True) |
| 114 | + nocomment = False |
| 115 | + # Convert types |
| 116 | + df["NNodes"] = pd.to_numeric(df["NNodes"], errors="coerce") |
| 117 | + df["NCPUS"] = pd.to_numeric(df["NCPUS"], errors="coerce") |
| 118 | + |
| 119 | + # Convert time fields |
| 120 | + df["Elapsed_sec"] = df["Elapsed"].apply(time_to_seconds) |
| 121 | + df["TotalCPU_sec"] = df["TotalCPU"].apply(time_to_seconds) |
| 122 | + |
| 123 | + # Compute CPU efficiency |
| 124 | + df["CPU Efficiency (%)"] = ( |
| 125 | + df["TotalCPU_sec"] |
| 126 | + / (df["Elapsed_sec"].clip(lower=1) * df["NCPUS"].clip(lower=1)) |
| 127 | + ) * 100 |
| 128 | + df.replace([np.inf, -np.inf], 0, inplace=True) |
| 129 | + |
| 130 | + # Convert MaxRSS |
| 131 | + df["MaxRSS_MB"] = df["MaxRSS"].apply(parse_maxrss) |
| 132 | + |
| 133 | + # Convert ReqMem and calculate memory efficiency |
| 134 | + df["RequestedMem_MB"] = df.apply( |
| 135 | + lambda row: parse_reqmem(row["ReqMem"], row["NNodes"]), axis=1 |
| 136 | + ) |
| 137 | + df["Memory Usage (%)"] = df.apply( |
| 138 | + lambda row: ( |
| 139 | + (row["MaxRSS_MB"] / row["RequestedMem_MB"] * 100) |
| 140 | + if row["RequestedMem_MB"] > 0 |
| 141 | + else 0 |
| 142 | + ), |
| 143 | + axis=1, |
| 144 | + ) |
| 145 | + |
| 146 | + df["Memory Usage (%)"] = df["Memory Usage (%)"].fillna(0).round(2) |
| 147 | + |
| 148 | + # Drop all rows containing "batch" or "extern" as job names |
| 149 | + df = df[~df["JobName"].str.contains("batch|extern", na=False)] |
| 150 | + |
| 151 | + # Log warnings for low efficiency |
| 152 | + for _, row in df.iterrows(): |
| 153 | + if row["CPU Efficiency (%)"] < e_threshold: |
| 154 | + if nocomment: |
| 155 | + logger.warning( |
| 156 | + f"Job {row['JobID']} ({row['JobName']}) " |
| 157 | + f"has low CPU efficiency: {row['CPU Efficiency (%)']}%." |
| 158 | + ) |
| 159 | + else: |
| 160 | + # if the comment column is available, we can use it to |
| 161 | + # identify the rule name |
| 162 | + logger.warning( |
| 163 | + f"Job {row['JobID']} for rule '{row['RuleName']}' " |
| 164 | + f"({row['JobName']}) has low CPU efficiency: " |
| 165 | + f"{row['CPU Efficiency (%)']}%." |
| 166 | + ) |
| 167 | + |
| 168 | + # we construct a path object to allow for a customi |
| 169 | + # logdir, if specified |
| 170 | + p = Path() |
| 171 | + |
| 172 | + # Save the report to a CSV file |
| 173 | + logfile = f"efficiency_report_{run_uuid}.csv" |
| 174 | + if e_report_path: |
| 175 | + logfile = Path(e_report_path) / logfile |
| 176 | + else: |
| 177 | + logfile = p.cwd() / logfile |
| 178 | + # ensure the directory exists |
| 179 | + logfile.parent.mkdir(parents=True, exist_ok=True) |
| 180 | + df.to_csv(logfile) |
| 181 | + |
| 182 | + # write out the efficiency report at normal verbosity in any case |
| 183 | + logger.info(f"Efficiency report for workflow {run_uuid} saved to {logfile}.") |
| 184 | + # state directory contents for debugging purposes |
| 185 | + logger.debug(f"Current directory contents in '{p.cwd()}': {os.listdir(p.cwd())}") |
0 commit comments