auto-optimize 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- auto_optimize/__init__.py +3 -0
- auto_optimize/__main__.py +5 -0
- auto_optimize/cli.py +651 -0
- auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
- auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
- auto_optimize/skills/auto-optimize-code/VERSION +1 -0
- auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
- auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
- auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
- auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
- auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
- auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
- auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
- auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
- auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
- auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
- auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
- auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
- auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
- auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
- auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
- auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
- auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
- auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
- auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
- auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
- auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
- auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
- auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
- auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
- auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
- auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
- auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
- auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
- auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
- auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
- auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
- auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
- auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
- auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
- auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
- auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
- auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
- auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
- auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
- auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
- auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
- auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
- auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
- auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
- auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
- auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
- auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
- auto_optimize-1.0.0.dist-info/METADATA +610 -0
- auto_optimize-1.0.0.dist-info/RECORD +67 -0
- auto_optimize-1.0.0.dist-info/WHEEL +4 -0
- auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
- auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,684 @@
|
|
|
1
|
+
"""Publish a search's state as JSON files a Jupyter server can serve.
|
|
2
|
+
|
|
3
|
+
Jupyter serves `/files/` sandboxed, so a page mounted there cannot call back
|
|
4
|
+
to the server. A page mounted inside a trusted notebook output is not, and
|
|
5
|
+
reads files through Jupyter's authenticated Contents API. This daemon is the
|
|
6
|
+
other half: it scans the run and writes the JSON the page reads into a
|
|
7
|
+
directory under the Jupyter root.
|
|
8
|
+
|
|
9
|
+
python3 monitor_writer.py <work>/autooptimize --out ~/autoopt-monitor/<project>
|
|
10
|
+
|
|
11
|
+
Nothing here writes to the search directory and nothing here listens on a
|
|
12
|
+
port. `autoopt_monitor.py --start` is the usual way to start one.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import io
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import sys
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import time
|
|
22
|
+
import shutil
|
|
23
|
+
import signal
|
|
24
|
+
import socket
|
|
25
|
+
import hashlib
|
|
26
|
+
import argparse
|
|
27
|
+
import logging
|
|
28
|
+
import threading
|
|
29
|
+
import contextlib
|
|
30
|
+
|
|
31
|
+
from collections import deque
|
|
32
|
+
|
|
33
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
34
|
+
sys.path.insert(0, HERE)
|
|
35
|
+
|
|
36
|
+
from scan import RunScanner
|
|
37
|
+
from gpu_scan import shared_dir
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
ASSETS = ('dashboard.css', 'dashboard.js', 'index.html')
|
|
41
|
+
PAYLOADS = ('state.json', 'resources.json')
|
|
42
|
+
|
|
43
|
+
# The modules that decide the payload's shape. A writer imports them once and
|
|
44
|
+
# publishes that shape for as long as it lives; the mount compares this stamp
|
|
45
|
+
# and replaces a writer whose stamp differs.
|
|
46
|
+
SOURCES = ('scan.py', 'gpu_scan.py', 'monitor_writer.py',
|
|
47
|
+
os.path.join('..', 'autoopt.py'))
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger('autoopt-monitor')
|
|
50
|
+
|
|
51
|
+
# Two hosts can mount one payload directory (a network filesystem), and
|
|
52
|
+
# neither sees the other's lock or pid: each would publish its own GPUs into
|
|
53
|
+
# it, and the page would flip between them. So a publishing writer leaves a
|
|
54
|
+
# heartbeat beside the payload, and a writer on another host with the weaker
|
|
55
|
+
# claim pauses.
|
|
56
|
+
HOST = socket.gethostname()
|
|
57
|
+
HEARTBEAT = 'writer.host'
|
|
58
|
+
|
|
59
|
+
# A page that wants live GPU cards touches LIVE every few seconds. While the
|
|
60
|
+
# file is younger than LIVE_SECONDS the hardware thread samples every
|
|
61
|
+
# LIVE_INTERVAL; when the page stops (a closed or hidden tab, the toggle off)
|
|
62
|
+
# the writer is back on its own clock within LIVE_SECONDS.
|
|
63
|
+
LIVE = 'live.json'
|
|
64
|
+
LIVE_SECONDS = 10.0
|
|
65
|
+
LIVE_INTERVAL = 1.0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _stamp(names, directory):
|
|
69
|
+
stamps = []
|
|
70
|
+
|
|
71
|
+
for name in names:
|
|
72
|
+
try:
|
|
73
|
+
stamps.append(int(os.path.getmtime(os.path.join(directory, name))))
|
|
74
|
+
except OSError:
|
|
75
|
+
continue
|
|
76
|
+
|
|
77
|
+
return str(max(stamps) if stamps else 0)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def code_version():
|
|
81
|
+
"""A stamp for the scanner's code, so a stale writer can be spotted."""
|
|
82
|
+
|
|
83
|
+
return _stamp(SOURCES, HERE)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def assets_version():
|
|
87
|
+
"""A stamp for the front end, so a running writer can refresh it and an
|
|
88
|
+
open page can tell it is older than what is published."""
|
|
89
|
+
|
|
90
|
+
return _stamp(ASSETS, os.path.join(HERE, 'static'))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _round(value, digits=5):
|
|
94
|
+
"""Shrink the payload, keeping five digits that mean something.
|
|
95
|
+
|
|
96
|
+
Five significant figures below 1, five decimals at or above it. Plain
|
|
97
|
+
`round(x, 5)` sends every p-value to 0.0; sig-fig rounding above 1 would
|
|
98
|
+
move a unix timestamp by hours.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
if isinstance(value, float):
|
|
102
|
+
if value != value:
|
|
103
|
+
return None
|
|
104
|
+
if value in (float('inf'), float('-inf')) or value == 0:
|
|
105
|
+
return value
|
|
106
|
+
|
|
107
|
+
magnitude = math.floor(math.log10(abs(value)))
|
|
108
|
+
places = digits if magnitude >= 0 else digits - magnitude - 1
|
|
109
|
+
|
|
110
|
+
return round(value, min(places, 17))
|
|
111
|
+
if isinstance(value, dict):
|
|
112
|
+
return {key: _round(item, digits) for key, item in value.items()}
|
|
113
|
+
if isinstance(value, (list, tuple)):
|
|
114
|
+
return [_round(item, digits) for item in value]
|
|
115
|
+
|
|
116
|
+
return value
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def dumps(payload):
|
|
120
|
+
"""The payload as the page reads it: numbers rounded, no spaces."""
|
|
121
|
+
|
|
122
|
+
return json.dumps(_round(payload), separators=(',', ':'),
|
|
123
|
+
default=lambda value: None)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def write_text(path, text):
|
|
127
|
+
"""Atomically, so the page never reads half a file. The temporary name
|
|
128
|
+
is per process and thread: two writers sharing one name interleave
|
|
129
|
+
into a file that is not JSON."""
|
|
130
|
+
|
|
131
|
+
tmp = '{}.{}-{}.tmp'.format(path, os.getpid(), threading.get_ident())
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
with open(tmp, 'w') as out:
|
|
135
|
+
out.write(text)
|
|
136
|
+
|
|
137
|
+
os.replace(tmp, path)
|
|
138
|
+
finally:
|
|
139
|
+
if os.path.exists(tmp):
|
|
140
|
+
os.unlink(tmp)
|
|
141
|
+
|
|
142
|
+
return os.path.getsize(path)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def write_json(path, payload):
|
|
146
|
+
return write_text(path, dumps(payload))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# The keys of state.json that change on every scan whatever the search did.
|
|
150
|
+
VOLATILE = ('generated', 'uptime')
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class StateWriter:
|
|
154
|
+
"""Writes state.json, serializing each snapshot once.
|
|
155
|
+
|
|
156
|
+
The snapshot without its VOLATILE stamps is serialized and hashed, and
|
|
157
|
+
the stamps are appended to that text. With `skip_unchanged`, a snapshot
|
|
158
|
+
whose digest equals the last one written is not written again: at a
|
|
159
|
+
thousand iterations state.json is megabytes, and an idle search
|
|
160
|
+
rewrites the same bytes every scan. It is off by default because the
|
|
161
|
+
page's pulse takes `generated` changing as the sign the publisher is
|
|
162
|
+
alive; once the page reads `writer.scanned` from resources.json, which
|
|
163
|
+
every good scan sets, it can be turned on (`--skip-unchanged`)."""
|
|
164
|
+
|
|
165
|
+
def __init__(self, path, skip_unchanged=False):
|
|
166
|
+
self.path = path
|
|
167
|
+
self.skip_unchanged = skip_unchanged
|
|
168
|
+
self.digest = None
|
|
169
|
+
|
|
170
|
+
def write(self, snapshot):
|
|
171
|
+
"""The bytes written, or None when the write was skipped."""
|
|
172
|
+
|
|
173
|
+
body = dumps({key: value for key, value in snapshot.items()
|
|
174
|
+
if key not in VOLATILE})
|
|
175
|
+
digest = hashlib.sha1(body.encode()).hexdigest()
|
|
176
|
+
|
|
177
|
+
if self.skip_unchanged and digest == self.digest and os.path.exists(
|
|
178
|
+
self.path):
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
stamps = ','.join('{}:{}'.format(json.dumps(key), dumps(snapshot[key]))
|
|
182
|
+
for key in VOLATILE if key in snapshot)
|
|
183
|
+
|
|
184
|
+
if stamps:
|
|
185
|
+
body = body[:-1] + (',' if body != '{}' else '') + stamps + '}'
|
|
186
|
+
|
|
187
|
+
size = write_text(self.path, body)
|
|
188
|
+
self.digest = digest
|
|
189
|
+
|
|
190
|
+
return size
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def claim(out_dir):
|
|
194
|
+
"""An open file holding the lock that makes this process the only writer
|
|
195
|
+
into `out_dir`, or None when another writer holds it. Held for the
|
|
196
|
+
process's life and released by the kernel however it ends, so it cannot
|
|
197
|
+
go stale the way `writer.pid` does. It lives on local memory, not beside
|
|
198
|
+
the payload: locks on a network filesystem stall."""
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
import fcntl
|
|
202
|
+
except ImportError:
|
|
203
|
+
return True
|
|
204
|
+
|
|
205
|
+
path = os.path.join(shared_dir(), 'writer-{}.lock'.format(hashlib.sha1(
|
|
206
|
+
os.path.abspath(out_dir).encode()).hexdigest()[:16]))
|
|
207
|
+
handle = open(path, 'a')
|
|
208
|
+
|
|
209
|
+
try:
|
|
210
|
+
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
211
|
+
except BlockingIOError:
|
|
212
|
+
handle.close()
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
return handle
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def install_assets(out_dir):
|
|
219
|
+
"""Copy the front end next to the JSON so `/files/` can serve it.
|
|
220
|
+
|
|
221
|
+
Stylesheet and script requests made by the notebook page are same-origin,
|
|
222
|
+
so the sandbox on `/files/` does not apply to them. plotly.min.js comes
|
|
223
|
+
from the installed Python package, so the page needs no CDN.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
227
|
+
|
|
228
|
+
for name in ASSETS:
|
|
229
|
+
shutil.copy2(os.path.join(HERE, 'static', name),
|
|
230
|
+
os.path.join(out_dir, name))
|
|
231
|
+
|
|
232
|
+
target = os.path.join(out_dir, 'plotly.min.js')
|
|
233
|
+
|
|
234
|
+
if not os.path.exists(target):
|
|
235
|
+
try:
|
|
236
|
+
import plotly
|
|
237
|
+
source = os.path.join(os.path.dirname(plotly.__file__),
|
|
238
|
+
'package_data', 'plotly.min.js')
|
|
239
|
+
|
|
240
|
+
if os.path.exists(source):
|
|
241
|
+
shutil.copy2(source, target)
|
|
242
|
+
except ImportError:
|
|
243
|
+
logger.warning('plotly is not installed; the charts will not '
|
|
244
|
+
'render and the page will say so')
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# Payloads live beside the run they describe, so there is no single
|
|
248
|
+
# directory to list to find them. One small file per live writer, here, keeps
|
|
249
|
+
# discovery a directory listing. It is read by Python only and never served to
|
|
250
|
+
# the browser, so a hidden path is safe for it.
|
|
251
|
+
INDEX = '~/.cache/autoopt-monitor'
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def index_path(out_dir):
|
|
255
|
+
"""The index entry naming `out_dir`, one file per payload directory.
|
|
256
|
+
|
|
257
|
+
The readable slug alone collides (`/a/b-c` and `/a-b/c`), so a hash of
|
|
258
|
+
the whole path follows it."""
|
|
259
|
+
|
|
260
|
+
path = os.path.abspath(os.path.expanduser(out_dir))
|
|
261
|
+
slug = re.sub(r'[^A-Za-z0-9._-]+', '-', path.strip(os.sep)).strip('-')
|
|
262
|
+
slug += '-' + hashlib.sha1(path.encode()).hexdigest()[:8]
|
|
263
|
+
|
|
264
|
+
return os.path.join(os.path.expanduser(INDEX), slug + '.writer')
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def index_entries():
|
|
268
|
+
"""Every payload directory an index entry points at, live or not."""
|
|
269
|
+
|
|
270
|
+
base = os.path.expanduser(INDEX)
|
|
271
|
+
out = []
|
|
272
|
+
|
|
273
|
+
for name in (sorted(os.listdir(base)) if os.path.isdir(base) else []):
|
|
274
|
+
if not name.endswith('.writer'):
|
|
275
|
+
continue
|
|
276
|
+
|
|
277
|
+
try:
|
|
278
|
+
with open(os.path.join(base, name)) as infile:
|
|
279
|
+
out.append(infile.readline().strip())
|
|
280
|
+
except OSError:
|
|
281
|
+
continue
|
|
282
|
+
|
|
283
|
+
return out
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def forget(out_dir):
|
|
287
|
+
"""Drop the index entry for `out_dir`, if any."""
|
|
288
|
+
|
|
289
|
+
try:
|
|
290
|
+
os.unlink(index_path(out_dir))
|
|
291
|
+
except OSError:
|
|
292
|
+
pass
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def read_heartbeat(out_dir):
|
|
296
|
+
try:
|
|
297
|
+
with open(os.path.join(out_dir, HEARTBEAT)) as infile:
|
|
298
|
+
beat = json.load(infile)
|
|
299
|
+
except (OSError, ValueError):
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
return beat if isinstance(beat, dict) else None
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def live_requested(out_dir, now=None, window=LIVE_SECONDS):
|
|
306
|
+
"""Whether a page asked for live samples within `window` seconds. The
|
|
307
|
+
file's own mtime says when, so no clock but the file system's is used."""
|
|
308
|
+
|
|
309
|
+
try:
|
|
310
|
+
age = (now or time.time()) - os.path.getmtime(os.path.join(out_dir, LIVE))
|
|
311
|
+
except OSError:
|
|
312
|
+
return False
|
|
313
|
+
|
|
314
|
+
return -window < age < window
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def yields_to(mine, other, now, stale):
|
|
318
|
+
"""Whether the writer whose heartbeat would be `mine` leaves the
|
|
319
|
+
directory to the one that wrote `other`, the writer publishing there:
|
|
320
|
+
one on another host, heard from within `stale` seconds. It keeps the
|
|
321
|
+
directory unless this writer sees the search's processes and it does
|
|
322
|
+
not, so the strip ends on the GPUs the search runs on and stays there
|
|
323
|
+
between the search's jobs. The heartbeat file holds one writer, so two
|
|
324
|
+
hosts never both pause."""
|
|
325
|
+
|
|
326
|
+
if (not other or other.get('host') in (None, mine['host'])
|
|
327
|
+
or now - (other.get('at') or 0) > stale):
|
|
328
|
+
return False
|
|
329
|
+
|
|
330
|
+
return not (mine.get('search') and not other.get('search'))
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
class _Stop(BaseException):
|
|
334
|
+
"""Raised by the SIGTERM handler. Not an Exception, so the per-tick
|
|
335
|
+
handlers that keep the loop alive do not swallow a stop."""
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
class Busy(RuntimeError):
|
|
339
|
+
"""Another writer holds `out_dir`'s lock."""
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def run(root, out_dir, interval, resource_interval, skip_unchanged=False):
|
|
343
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
344
|
+
|
|
345
|
+
# Taken before anything is written, so two starts racing past the
|
|
346
|
+
# pidfile check cannot both publish.
|
|
347
|
+
lock = claim(out_dir)
|
|
348
|
+
if lock is None:
|
|
349
|
+
raise Busy('a writer is already publishing into {}'.format(out_dir))
|
|
350
|
+
|
|
351
|
+
scanner = RunScanner(root)
|
|
352
|
+
install_assets(out_dir)
|
|
353
|
+
|
|
354
|
+
pidfile = os.path.join(out_dir, 'writer.pid')
|
|
355
|
+
|
|
356
|
+
# The start time pins the PID to this process: a pidfile outlives a
|
|
357
|
+
# kill -9, and the kernel hands its PID to something else.
|
|
358
|
+
tmp = '{}.{}.tmp'.format(pidfile, os.getpid())
|
|
359
|
+
with open(tmp, 'w') as out:
|
|
360
|
+
out.write('{}\n{}\n{}\n{} {}\n{}\n'.format(os.getpid(), scanner.root,
|
|
361
|
+
code_version(), float(interval), float(resource_interval),
|
|
362
|
+
(process_identity(os.getpid()) or (None, None))[1] or ''))
|
|
363
|
+
os.replace(tmp, pidfile)
|
|
364
|
+
|
|
365
|
+
entry = index_path(out_dir)
|
|
366
|
+
os.makedirs(os.path.dirname(entry), exist_ok=True)
|
|
367
|
+
|
|
368
|
+
with open(entry, 'w') as out:
|
|
369
|
+
out.write('{}\n'.format(os.path.abspath(out_dir)))
|
|
370
|
+
|
|
371
|
+
stopping = threading.Event()
|
|
372
|
+
paused = threading.Event()
|
|
373
|
+
since = time.time()
|
|
374
|
+
stale = max(10.0, 3 * float(resource_interval))
|
|
375
|
+
|
|
376
|
+
try:
|
|
377
|
+
# Only the main thread may install a handler; run in a thread (a test
|
|
378
|
+
# server), the daemon thread dies with the process instead. The handler
|
|
379
|
+
# raises, so a stop cuts a long scan or a sleep short rather than waiting
|
|
380
|
+
# for it.
|
|
381
|
+
if threading.current_thread() is threading.main_thread():
|
|
382
|
+
def stop(*args):
|
|
383
|
+
if not stopping.is_set():
|
|
384
|
+
stopping.set()
|
|
385
|
+
raise _Stop()
|
|
386
|
+
|
|
387
|
+
for sig in (signal.SIGTERM, signal.SIGINT):
|
|
388
|
+
signal.signal(sig, stop)
|
|
389
|
+
|
|
390
|
+
# What the writer reports about itself, in resources.json: the gaps it
|
|
391
|
+
# actually keeps between scans and between hardware samples, which the
|
|
392
|
+
# page's freshness check uses in place of the configured intervals.
|
|
393
|
+
# Each cadence is the longest of the last few gaps: a sample served
|
|
394
|
+
# from nvidia-smi's short cache follows a slow one at once, and the
|
|
395
|
+
# last gap alone would swing between the two.
|
|
396
|
+
# `scanned` is when the last scan succeeded, whether or not it
|
|
397
|
+
# rewrote state.json (StateWriter).
|
|
398
|
+
status = {'interval': float(interval),
|
|
399
|
+
'resource_interval': float(resource_interval),
|
|
400
|
+
'state_cadence': None, 'resource_cadence': None,
|
|
401
|
+
'scan_error': None, 'scan_error_at': None, 'live': False,
|
|
402
|
+
'scanned': None}
|
|
403
|
+
gaps = {'state': deque(maxlen=5), 'resource': deque(maxlen=5)}
|
|
404
|
+
|
|
405
|
+
def lap(kind, gap):
|
|
406
|
+
gaps[kind].append(gap)
|
|
407
|
+
status[kind + '_cadence'] = max(gaps[kind])
|
|
408
|
+
|
|
409
|
+
# Hardware sampling runs on its own thread: nvidia-smi on a busy host
|
|
410
|
+
# takes seconds per query, and the scan and a stop must not wait on it.
|
|
411
|
+
def hardware():
|
|
412
|
+
last = None
|
|
413
|
+
scanner.hardware.history_gap = 0.9 * resource_interval
|
|
414
|
+
|
|
415
|
+
while not stopping.is_set():
|
|
416
|
+
start = time.time()
|
|
417
|
+
live = live_requested(out_dir, start)
|
|
418
|
+
scanner.hardware.live = live
|
|
419
|
+
status['live'] = live
|
|
420
|
+
|
|
421
|
+
try:
|
|
422
|
+
mine = {'host': HOST, 'pid': os.getpid(), 'since': since,
|
|
423
|
+
'search': any(p.get('is_root') for p in
|
|
424
|
+
scanner.hardware.processes())}
|
|
425
|
+
other = read_heartbeat(out_dir)
|
|
426
|
+
|
|
427
|
+
if yields_to(mine, other, start, stale):
|
|
428
|
+
if not paused.is_set():
|
|
429
|
+
logger.info('paused: %s publishes this directory',
|
|
430
|
+
other['host'])
|
|
431
|
+
paused.set()
|
|
432
|
+
last = None
|
|
433
|
+
else:
|
|
434
|
+
if paused.is_set():
|
|
435
|
+
logger.info('resumed: no other host publishes '
|
|
436
|
+
'this directory')
|
|
437
|
+
paused.clear()
|
|
438
|
+
write_json(os.path.join(out_dir, HEARTBEAT),
|
|
439
|
+
dict(mine, at=start))
|
|
440
|
+
payload = scanner.hardware.resources()
|
|
441
|
+
if last is not None:
|
|
442
|
+
lap('resource', start - last)
|
|
443
|
+
last = start
|
|
444
|
+
payload['writer'] = dict(status)
|
|
445
|
+
write_json(os.path.join(out_dir, 'resources.json'),
|
|
446
|
+
payload)
|
|
447
|
+
except Exception as error:
|
|
448
|
+
logger.warning('resources: %s', error)
|
|
449
|
+
|
|
450
|
+
gap = min(resource_interval, LIVE_INTERVAL) if live else resource_interval
|
|
451
|
+
stopping.wait(max(0.05, start + gap - time.time()))
|
|
452
|
+
|
|
453
|
+
threading.Thread(target=hardware, name='hardware', daemon=True).start()
|
|
454
|
+
|
|
455
|
+
installed = assets_version()
|
|
456
|
+
states = StateWriter(os.path.join(out_dir, 'state.json'),
|
|
457
|
+
skip_unchanged)
|
|
458
|
+
last_state = None
|
|
459
|
+
readme_seen = {}
|
|
460
|
+
diff_seen = {}
|
|
461
|
+
os.makedirs(os.path.join(out_dir, 'readmes'), exist_ok=True)
|
|
462
|
+
os.makedirs(os.path.join(out_dir, 'diffs'), exist_ok=True)
|
|
463
|
+
logger.info('publishing %s to %s', scanner.root, out_dir)
|
|
464
|
+
|
|
465
|
+
while not stopping.is_set():
|
|
466
|
+
start = time.time()
|
|
467
|
+
|
|
468
|
+
# The front end is copied in at start-up and again whenever it
|
|
469
|
+
# changes, so a long-running writer serves the current page.
|
|
470
|
+
if assets_version() != installed:
|
|
471
|
+
install_assets(out_dir)
|
|
472
|
+
installed = assets_version()
|
|
473
|
+
logger.info('front end changed; reinstalled it')
|
|
474
|
+
|
|
475
|
+
# Another host publishes this directory (the hardware thread
|
|
476
|
+
# decides): scan and write nothing until it stops.
|
|
477
|
+
if paused.is_set():
|
|
478
|
+
last_state = None
|
|
479
|
+
time.sleep(0.5)
|
|
480
|
+
continue
|
|
481
|
+
|
|
482
|
+
# autoopt.fail() prints its reason to stderr and raises SystemExit
|
|
483
|
+
# (a config.json that fails validation): caught here, so one bad
|
|
484
|
+
# edit to the search is a published error, not a dead writer.
|
|
485
|
+
said = io.StringIO()
|
|
486
|
+
|
|
487
|
+
try:
|
|
488
|
+
with contextlib.redirect_stderr(said):
|
|
489
|
+
snapshot = scanner.snapshot()
|
|
490
|
+
|
|
491
|
+
# An open page compares this with the ?v= it was loaded with
|
|
492
|
+
# and asks for the cell to be re-run when they differ.
|
|
493
|
+
snapshot['assets'] = installed
|
|
494
|
+
size = states.write(snapshot)
|
|
495
|
+
|
|
496
|
+
# Whole READMEs for the tree's node panel, one small file per
|
|
497
|
+
# iteration, rewritten only when its README.md changes.
|
|
498
|
+
for identifier, (mtime, text) in scanner.readmes(readme_seen).items():
|
|
499
|
+
write_json(os.path.join(out_dir, 'readmes', '%d.json' % identifier),
|
|
500
|
+
{'id': identifier, 'text': text})
|
|
501
|
+
readme_seen[identifier] = mtime
|
|
502
|
+
|
|
503
|
+
# Each settled iteration's code change against its parent for
|
|
504
|
+
# the diff panel: written once per commit pair, newest first,
|
|
505
|
+
# a few seconds of git per scan at most.
|
|
506
|
+
for identifier, (payload, pair) in scanner.diffs(
|
|
507
|
+
snapshot['iterations'], diff_seen).items():
|
|
508
|
+
write_json(os.path.join(out_dir, 'diffs', '%d.json' % identifier),
|
|
509
|
+
payload)
|
|
510
|
+
diff_seen[identifier] = pair
|
|
511
|
+
|
|
512
|
+
if last_state is not None:
|
|
513
|
+
lap('state', start - last_state)
|
|
514
|
+
last_state = start
|
|
515
|
+
status['scan_error'] = status['scan_error_at'] = None
|
|
516
|
+
status['scanned'] = start
|
|
517
|
+
logger.info('state %s, %d iterations, %d running, '
|
|
518
|
+
'frontier %s', 'unchanged, not rewritten' if size is None
|
|
519
|
+
else '{:.0f} kB'.format(size / 1024),
|
|
520
|
+
snapshot['counts']['iterations'],
|
|
521
|
+
snapshot['counts']['running'], snapshot['frontier']['value'])
|
|
522
|
+
except (Exception, SystemExit) as error:
|
|
523
|
+
reason = said.getvalue().strip() or '{}: {}'.format(
|
|
524
|
+
type(error).__name__, error)
|
|
525
|
+
status['scan_error'], status['scan_error_at'] = reason, time.time()
|
|
526
|
+
logger.warning('state: %s', reason)
|
|
527
|
+
else:
|
|
528
|
+
if said.getvalue():
|
|
529
|
+
sys.stderr.write(said.getvalue())
|
|
530
|
+
|
|
531
|
+
# Slices, not one long sleep: the handler raises out of it, but
|
|
532
|
+
# a stop set from elsewhere is only seen between slices.
|
|
533
|
+
deadline = start + interval
|
|
534
|
+
|
|
535
|
+
while not stopping.is_set() and time.time() < deadline:
|
|
536
|
+
time.sleep(min(0.5, max(0.05, deadline - time.time())))
|
|
537
|
+
except _Stop:
|
|
538
|
+
pass
|
|
539
|
+
finally:
|
|
540
|
+
stopping.set()
|
|
541
|
+
|
|
542
|
+
# Only our own: removing a successor's pidfile hides a live writer
|
|
543
|
+
# from every later start, which then starts another beside it.
|
|
544
|
+
try:
|
|
545
|
+
with open(pidfile) as infile:
|
|
546
|
+
ours = infile.readline().strip() == str(os.getpid())
|
|
547
|
+
if ours:
|
|
548
|
+
os.unlink(pidfile)
|
|
549
|
+
forget(out_dir)
|
|
550
|
+
except OSError:
|
|
551
|
+
pass
|
|
552
|
+
|
|
553
|
+
logger.info('stopped')
|
|
554
|
+
|
|
555
|
+
if lock is not True:
|
|
556
|
+
lock.close()
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def process_identity(pid):
|
|
560
|
+
"""`(argv, start)` for a running `pid`, or None when there is no such
|
|
561
|
+
process. `start` is an opaque token, equal across calls for one process
|
|
562
|
+
and different for a later one given the same PID. Either is None where
|
|
563
|
+
this platform cannot tell: /proc first, then psutil, then only whether
|
|
564
|
+
the PID exists."""
|
|
565
|
+
|
|
566
|
+
try:
|
|
567
|
+
with open('/proc/{}/cmdline'.format(pid), 'rb') as infile:
|
|
568
|
+
argv = [a.decode(errors='replace') for a in
|
|
569
|
+
infile.read().split(b'\0') if a]
|
|
570
|
+
with open('/proc/{}/stat'.format(pid)) as infile:
|
|
571
|
+
start = infile.read().rsplit(')', 1)[1].split()[19]
|
|
572
|
+
|
|
573
|
+
return argv, start
|
|
574
|
+
except FileNotFoundError:
|
|
575
|
+
if os.path.isdir('/proc/self'):
|
|
576
|
+
return None
|
|
577
|
+
except (OSError, IndexError):
|
|
578
|
+
pass
|
|
579
|
+
|
|
580
|
+
try:
|
|
581
|
+
import psutil
|
|
582
|
+
except ImportError:
|
|
583
|
+
psutil = None
|
|
584
|
+
|
|
585
|
+
if psutil is not None:
|
|
586
|
+
try:
|
|
587
|
+
process = psutil.Process(pid)
|
|
588
|
+
return process.cmdline(), repr(process.create_time())
|
|
589
|
+
except psutil.NoSuchProcess: # a zombie is one too
|
|
590
|
+
return None
|
|
591
|
+
except psutil.Error:
|
|
592
|
+
return None, None
|
|
593
|
+
|
|
594
|
+
try:
|
|
595
|
+
os.kill(pid, 0)
|
|
596
|
+
except ProcessLookupError:
|
|
597
|
+
return None
|
|
598
|
+
except OSError:
|
|
599
|
+
pass
|
|
600
|
+
|
|
601
|
+
return None, None
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def writer_info(out_dir):
|
|
605
|
+
"""`{pid, root, code, intervals}` for a live writer publishing into
|
|
606
|
+
`out_dir`, else None; `intervals` is `[interval, resource_interval]`.
|
|
607
|
+
|
|
608
|
+
The run is part of the answer: a live writer watching a different run is
|
|
609
|
+
the one case that silently shows the wrong numbers under the right name.
|
|
610
|
+
A pidfile with no code stamp reports none, which reads as stale.
|
|
611
|
+
|
|
612
|
+
The PID must still be a writer: its command line names
|
|
613
|
+
`monitor_writer.py` and its start time matches the one recorded, where
|
|
614
|
+
the platform can tell. Otherwise a stale pidfile would have `--stop` and
|
|
615
|
+
a handover SIGTERM whatever process now holds the PID.
|
|
616
|
+
"""
|
|
617
|
+
|
|
618
|
+
try:
|
|
619
|
+
with open(os.path.join(out_dir, 'writer.pid')) as infile:
|
|
620
|
+
pid = int(infile.readline().strip())
|
|
621
|
+
root = infile.readline().strip()
|
|
622
|
+
code = infile.readline().strip()
|
|
623
|
+
clocks = [float(x) for x in infile.readline().split()] or None
|
|
624
|
+
started = infile.readline().strip() or None
|
|
625
|
+
except (OSError, ValueError):
|
|
626
|
+
return None
|
|
627
|
+
|
|
628
|
+
identity = process_identity(pid)
|
|
629
|
+
|
|
630
|
+
if identity is None:
|
|
631
|
+
return None
|
|
632
|
+
|
|
633
|
+
argv, start = identity
|
|
634
|
+
|
|
635
|
+
if argv is not None and not any(os.path.basename(a) == 'monitor_writer.py'
|
|
636
|
+
for a in argv):
|
|
637
|
+
return None
|
|
638
|
+
|
|
639
|
+
if started is not None and start is not None and started != start:
|
|
640
|
+
return None
|
|
641
|
+
|
|
642
|
+
return {'pid': pid, 'root': root, 'code': code or None, 'intervals': clocks}
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def alive(out_dir):
|
|
646
|
+
info = writer_info(out_dir)
|
|
647
|
+
|
|
648
|
+
return info['pid'] if info else None
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def main(argv=None):
|
|
652
|
+
parser = argparse.ArgumentParser(description=__doc__,
|
|
653
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
654
|
+
parser.add_argument('root', help='the autooptimize/ directory to watch')
|
|
655
|
+
parser.add_argument('--out', required=True,
|
|
656
|
+
help='where to publish; must be under the Jupyter root')
|
|
657
|
+
parser.add_argument('--interval', type=float, default=20.0,
|
|
658
|
+
help='seconds between full scans (default: %(default)s)')
|
|
659
|
+
parser.add_argument('--resource-interval', type=float, default=3.0,
|
|
660
|
+
help='seconds between hardware samples (default: %(default)s)')
|
|
661
|
+
parser.add_argument('--skip-unchanged', action='store_true',
|
|
662
|
+
help='write state.json only when a scan changed it; for a page that '
|
|
663
|
+
'reads the scan time from resources.json (`writer.scanned`)')
|
|
664
|
+
args = parser.parse_args(argv)
|
|
665
|
+
|
|
666
|
+
logging.basicConfig(level=logging.INFO,
|
|
667
|
+
format='%(asctime)s %(levelname)s %(message)s')
|
|
668
|
+
|
|
669
|
+
out_dir = os.path.abspath(os.path.expanduser(args.out))
|
|
670
|
+
running = alive(out_dir)
|
|
671
|
+
|
|
672
|
+
if running:
|
|
673
|
+
parser.error('a writer is already publishing there (pid {})'.format(
|
|
674
|
+
running))
|
|
675
|
+
|
|
676
|
+
try:
|
|
677
|
+
run(args.root, out_dir, args.interval, args.resource_interval,
|
|
678
|
+
args.skip_unchanged)
|
|
679
|
+
except Busy as error:
|
|
680
|
+
parser.error(str(error))
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
if __name__ == '__main__':
|
|
684
|
+
main()
|