1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
|
import numbers
import time
import sys
import math
from datetime import timedelta
from string import Template
class StatusDisplay:
resources = ["cores", "gpus", "memory", "disk"]
def __init__(self, interval=10):
self.interval = interval
self._last_update_report = 0
def active(self):
raise NotImplementedError
def update(self, queue=None, force=False):
now = time.time()
if not force:
if self._last_update_report + self.interval > now:
return
self._last_update_report = now
(q_info, rw_info, rc_info, app_info) = self.generate_table_data(queue)
self.update_display(q_info, rw_info, rc_info, app_info)
def update_display(self, queue_info, resources_worker_info, resources_category_info, app_info):
raise NotImplementedError
def generate_table_data(self, queue=None):
queue_s = None
app_s = None
if queue:
try:
queue_s = queue.status("queue")[0]
except Exception as e:
print("Error reading work queue status: {}".format(e), file=sys.stderr)
try:
app_s = queue.application_info()
except Exception as e:
print("Error reading application information status: {}".format(e), file=sys.stderr)
rc_info = self.generate_resource_category_tables(queue_s)
rw_info = self.generate_resource_worker_tables(queue_s)
q_info = self.generate_queue_table(queue_s)
app_info = self.generate_app_table(app_s)
return (q_info, rw_info, rc_info, app_info)
def generate_resource_worker_tables(self, queue_s):
if not queue_s:
return None
suffixes = [("largest", "largest worker"), ("inuse", "allocated"), ("total", "total")]
rs = []
header = ["application resources"] + StatusDisplay.resources
rs.append(header)
for s, l in suffixes:
d = self._dict_from_q(queue_s, s)
rs.append(self.resources_to_row(d, l, "na"))
return [rs]
def generate_resource_category_tables(self, queue_s):
if not queue_s:
return None
categories = queue_s["categories"]
largest_worker = None
if queue_s["workers_connected"] > 0:
largest_worker = self._dict_from_q(queue_s, "largest")
categories.sort(key=lambda c: c["category"])
cs = []
for c in categories:
ct = []
header = [c["category"]] + StatusDisplay.resources
ct.append(header)
larger_worker = self.resources_check_limits(c["max_allocation"], largest_worker)
if larger_worker:
ct.append(["current workers are too small!"] + larger_worker)
allocs = [
("max_seen", "largest seen", "na"),
("first_allocation", "current allocation", "whole worker"),
("max_allocation", "maximum allocation", "whole worker"),
]
for k, l, na in allocs:
try:
alloc = self.resources_to_row(c[k], l, na)
if alloc:
ct.append(alloc)
except KeyError:
pass
cs.append(ct)
return cs
def generate_queue_table(self, queue_s):
if not queue_s:
return None
stats = [
"port",
"tasks_done",
"tasks_waiting",
"tasks_running",
"tasks_exhausted_attempts",
"workers_connected",
"workers_busy",
]
pairs = list((key.replace("_", " "), str(queue_s[key])) for key in stats)
pairs.append(("sent", self.with_units("disk", queue_s["bytes_sent"] / 1e6, "na")))
pairs.append(("received", self.with_units("disk", queue_s["bytes_received"] / 1e6, "na")))
pairs.append(("total send time", str(timedelta(seconds=math.ceil(queue_s["time_send"] / 1e6)))))
pairs.append(("total receive time", str(timedelta(seconds=math.ceil(queue_s["time_send"] / 1e6)))))
pairs.append(("total good task time", str(timedelta(seconds=math.ceil(queue_s["time_workers_execute_good"] / 1e6)))))
pairs.append(("total task time", str(timedelta(seconds=math.ceil(queue_s["time_workers_execute"] / 1e6)))))
pairs.append(("runtime", str(timedelta(seconds=math.ceil(time.time() - queue_s["time_when_started"] / 1e6)))))
return pairs
def generate_app_table(self, app_s):
if not app_s:
return None
try:
app_info = app_s["application_info"]
values = app_info["values"]
units = app_info.get("units", {})
except KeyError:
return None
pairs = []
try:
for key in values:
name = key.replace("_", " ")
unit = units.get(key, None)
value = values[key]
if unit == "MB":
value = self.with_units("disk", value, "na")
elif unit:
value = f"{value} {unit}"
else:
value = str(value)
pairs.append((name, value))
except Exception as e:
pairs = [("internal error reading status", str(e))]
return pairs
def resources_to_row(self, values, alloc, na="na"):
rs = [alloc]
for r in StatusDisplay.resources:
try:
value = values[r]
value_with_units = self.with_units(r, value, na)
except KeyError:
value_with_units = na
rs.append(value_with_units)
return rs
def resources_check_limits(self, values, limit):
if not limit:
return None
limits_broken = False
rs = []
for r in StatusDisplay.resources:
try:
largest = limit[r]
value = values[r]
check = "ok"
if isinstance(value, numbers.Number) and isinstance(largest, numbers.Number) and value > largest:
limits_broken = True
check = f"{self.with_units(r, largest, '')} is too small"
except KeyError:
pass
rs.append(check)
if limits_broken:
return rs
return None
def with_units(self, resource, value, na):
if value is None:
return na
if not isinstance(value, numbers.Number):
return str(value)
if value < 0:
return na
if resource not in ["memory", "disk"]:
return f"{value:.1f}"
multipliers = ["MB", "GB", "TB"]
for m in multipliers:
if value < 1000:
break
value /= 1000.0
return f"{value:.2f} {m}"
def _dict_from_q(self, queue_s, suffix):
return {r: queue_s[f"{r}_{suffix}"] for r in StatusDisplay.resources}
class JupyterDisplay(StatusDisplay):
style = """
<style>
table {
border: 1px solid white;
border-collapse: collapse;
width: 100%;
}
th {
background-color: #96D4D4;
text-align: right;
}
td {
background-color: #f6f8ff;
padding-right: 15px;
text-align: right;
}
td.over {
text-align: right;
background-color: #ffcccc;
}
</style>
"""
tbl_fmt = Template(
f"""
<head>
{style}
</head>
<body>
<table>
$header
$rows
</table>
</body>
"""
)
hdr_fmt = Template('<th colspan="$span"> $value </th>')
cell_fmt = Template("<td> $value </td>")
cell_over_fmt = Template('<td class="over"> $value </td>')
row_fmt = Template("<tr> $cells </tr>")
def __init__(self, interval=10):
super().__init__(interval)
self._output = None
try:
import IPython
import ipywidgets as ws
if "IPKernelApp" in IPython.get_ipython().config:
self._queue_display = ws.HTML(value="")
self._app_display = ws.HTML(value="")
self._worker_display = ws.HTML(value="")
self._category_display = ws.HTML(value="")
self._output = ws.GridspecLayout(1, 8, grid_gap="20px")
self._output[0, :3] = ws.VBox([self._app_display, self._queue_display])
self._output[0, 3:] = ws.VBox([self._worker_display, self._category_display])
IPython.display.display(self._output)
except (ImportError, AttributeError):
pass
def active(self):
return bool(self._output)
def update_display(self, queue_info, resources_worker_info, resources_category_info, app_info):
if app_info:
self._app_display.value = self.table_of_pairs(app_info, "application info")
if queue_info:
self._queue_display.value = self.table_of_pairs(queue_info, "queue stats")
if resources_worker_info:
self._worker_display.value = self.table_of_resources(resources_worker_info)
if resources_category_info:
self._category_display.value = self.table_of_resources(resources_category_info)
def table_of_pairs(self, pairs, label):
header = JupyterDisplay.row_fmt.substitute(cells=JupyterDisplay.hdr_fmt.substitute(value=label, span=2))
rows = []
if pairs:
for pair in pairs:
row = self.make_row(pair)
rows.append(row)
return self.make_table(header, rows)
def table_of_resources(self, groups):
rows = []
for rs in groups:
rows.append(self.make_row(rs[0], fmt=lambda v: JupyterDisplay.hdr_fmt.substitute(value=v, span=0)))
rows.extend(map(lambda r: self.make_row(r), rs[1:]))
return self.make_table("", rows)
def make_table(self, header, rows):
return JupyterDisplay.tbl_fmt.substitute(header=header, rows="\n".join(rows))
def make_row(self, cells_info, fmt=None):
if not fmt:
def fmt(v):
return JupyterDisplay.cell_fmt.substitute(value=v)
try:
if cells_info[0][-1] == "!":
def fmt(v):
return JupyterDisplay.cell_over_fmt.substitute(value=v)
except IndexError:
pass
cells = map(lambda v: fmt(v), cells_info)
return JupyterDisplay.row_fmt.substitute(cells=" ".join(cells))
# vim: set sts=4 sw=4 ts=4 expandtab ft=python:
|