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,850 @@
|
|
|
1
|
+
"""Show the auto-optimize-code monitor inside a JupyterLab notebook.
|
|
2
|
+
|
|
3
|
+
import autoopt_monitor as am
|
|
4
|
+
am.show('<work>/autooptimize')
|
|
5
|
+
|
|
6
|
+
The page renders in the notebook's own origin, so it can read its data
|
|
7
|
+
through Jupyter's Contents API; a background writer keeps that data fresh.
|
|
8
|
+
Nothing is installed into Jupyter and nothing is restarted.
|
|
9
|
+
|
|
10
|
+
python3 autoopt_monitor.py <root> --start # write <work>/dashboard.ipynb, start the writer
|
|
11
|
+
python3 autoopt_monitor.py --status [<root>] # publishers (of one search): pid, search, out dir
|
|
12
|
+
python3 autoopt_monitor.py --stop [<root>] # stop one search's publishers, or all
|
|
13
|
+
python3 autoopt_monitor.py <root> --export out.html # one self-contained, read-only file
|
|
14
|
+
|
|
15
|
+
`<root>` is a search's `autooptimize/` directory, or the directory holding it;
|
|
16
|
+
`<work>` is the second, where the notebook goes.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import sys
|
|
22
|
+
import glob
|
|
23
|
+
import warnings
|
|
24
|
+
import json
|
|
25
|
+
import time
|
|
26
|
+
import hashlib
|
|
27
|
+
import importlib
|
|
28
|
+
import subprocess
|
|
29
|
+
import urllib.parse
|
|
30
|
+
|
|
31
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
32
|
+
sys.path.insert(0, os.path.dirname(HERE)) # autoopt.py
|
|
33
|
+
sys.path.insert(0, HERE)
|
|
34
|
+
|
|
35
|
+
import autoopt
|
|
36
|
+
import gpu_scan
|
|
37
|
+
import scan
|
|
38
|
+
import monitor_writer
|
|
39
|
+
|
|
40
|
+
# A notebook cell reloads this module and nothing else, so a long-lived kernel
|
|
41
|
+
# would keep stale copies of the modules below. Reload them innermost first,
|
|
42
|
+
# so each reload binds the fresh copy of the one under it.
|
|
43
|
+
for _module in ('autoopt', 'gpu_scan', 'scan', 'monitor_writer'):
|
|
44
|
+
try:
|
|
45
|
+
globals()[_module] = importlib.reload(sys.modules[_module])
|
|
46
|
+
except Exception as _error: # a broken edit must not hide itself
|
|
47
|
+
print('could not reload {}: {}'.format(_module, _error))
|
|
48
|
+
|
|
49
|
+
DEFAULT_BASE = '~/autoopt-monitor'
|
|
50
|
+
NOTEBOOK = 'dashboard.ipynb'
|
|
51
|
+
RUN_MARKER = 'config.json'
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def check_run(root):
|
|
55
|
+
"""Resolve a search directory, failing loudly on the usual mistake.
|
|
56
|
+
|
|
57
|
+
Accepts the `autooptimize/` directory or the project holding it. Pointing
|
|
58
|
+
at anything else otherwise renders an empty dashboard rather than an
|
|
59
|
+
error.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
root = os.path.abspath(os.path.expanduser(root))
|
|
63
|
+
|
|
64
|
+
if os.path.exists(os.path.join(root, RUN_MARKER)):
|
|
65
|
+
return root
|
|
66
|
+
|
|
67
|
+
nested = os.path.join(root, 'autooptimize')
|
|
68
|
+
|
|
69
|
+
if os.path.exists(os.path.join(nested, RUN_MARKER)):
|
|
70
|
+
return nested
|
|
71
|
+
|
|
72
|
+
raise ValueError('{} has no {}; point this at the autooptimize/ directory '
|
|
73
|
+
'of a search, or at the directory holding it.'.format(root, RUN_MARKER))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run_slug(root):
|
|
77
|
+
"""The fallback publish directory's name for a search: its project's
|
|
78
|
+
name and a hash of its full resolved path.
|
|
79
|
+
|
|
80
|
+
`/.../my-tool/autooptimize` becomes `my-tool-<8 hex>`: the
|
|
81
|
+
search directory is always called `autooptimize`, so the project above it
|
|
82
|
+
is what a reader recognises, and the hash keeps two projects with one
|
|
83
|
+
name from sharing (and each start stealing) the directory.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
path = os.path.realpath(os.path.abspath(os.path.expanduser(root)))
|
|
87
|
+
parts = [p for p in path.rstrip(os.sep).split(os.sep) if p]
|
|
88
|
+
name = (parts[-2] if len(parts) > 1 and parts[-1] == 'autooptimize'
|
|
89
|
+
else parts[-1] if parts else 'search')
|
|
90
|
+
name = re.sub(r'[^A-Za-z0-9._-]+', '-', name).strip('-') or 'search'
|
|
91
|
+
|
|
92
|
+
return '{}-{}'.format(name, hashlib.sha1(path.encode()).hexdigest()[:8])
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def default_out_dir(root, base=DEFAULT_BASE):
|
|
96
|
+
"""Where a run publishes: inside the run itself when that works.
|
|
97
|
+
|
|
98
|
+
Keeping the payload beside the run means deleting the run deletes its
|
|
99
|
+
monitor with it, rather than orphaning a directory in the home root. Two
|
|
100
|
+
cases cannot do that, and fall back to `base`: a run outside the tree
|
|
101
|
+
Jupyter serves, which the page could not read, and a run directory this
|
|
102
|
+
user cannot write to, such as someone else's.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
root = os.path.abspath(os.path.expanduser(root))
|
|
106
|
+
served, _ = jupyter_root(under=root)
|
|
107
|
+
|
|
108
|
+
if (root == served or root.startswith(served + os.sep)) \
|
|
109
|
+
and os.access(root, os.W_OK):
|
|
110
|
+
return os.path.join(root, 'monitor')
|
|
111
|
+
|
|
112
|
+
return os.path.join(os.path.abspath(os.path.expanduser(base)),
|
|
113
|
+
run_slug(root))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def jupyter_servers():
|
|
117
|
+
"""Every Jupyter server this user is running, newest first."""
|
|
118
|
+
|
|
119
|
+
# jupyter_core knows the platform's runtime directory (macOS keeps it
|
|
120
|
+
# under ~/Library/Jupyter); the Linux default stands in without it.
|
|
121
|
+
# Its first import warns that it is moving to platformdirs. The warning
|
|
122
|
+
# is ignored rather than JUPYTER_PLATFORM_DIRS set: that would move the
|
|
123
|
+
# directory away from the one the running servers write to.
|
|
124
|
+
try:
|
|
125
|
+
with warnings.catch_warnings():
|
|
126
|
+
warnings.simplefilter('ignore', DeprecationWarning)
|
|
127
|
+
from jupyter_core.paths import jupyter_runtime_dir
|
|
128
|
+
runtimes = [jupyter_runtime_dir()]
|
|
129
|
+
except Exception:
|
|
130
|
+
runtimes = []
|
|
131
|
+
|
|
132
|
+
runtimes += [os.path.expanduser('~/.local/share/jupyter/runtime'),
|
|
133
|
+
os.environ.get('JUPYTER_RUNTIME_DIR')]
|
|
134
|
+
paths = [path for runtime in runtimes if runtime
|
|
135
|
+
for path in glob.glob(os.path.join(runtime, 'jpserver-*.json'))]
|
|
136
|
+
|
|
137
|
+
servers = []
|
|
138
|
+
|
|
139
|
+
for path in sorted(set(paths), key=os.path.getmtime, reverse=True):
|
|
140
|
+
try:
|
|
141
|
+
with open(path) as infile:
|
|
142
|
+
info = json.load(infile)
|
|
143
|
+
except (OSError, ValueError):
|
|
144
|
+
continue
|
|
145
|
+
|
|
146
|
+
servers.append((os.path.abspath(os.path.expanduser(
|
|
147
|
+
info.get('root_dir') or '~')), info.get('base_url') or '/'))
|
|
148
|
+
|
|
149
|
+
return servers
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def jupyter_root(under=None):
|
|
153
|
+
"""The directory the running Jupyter serves, and its base URL.
|
|
154
|
+
|
|
155
|
+
With several servers running, prefer the one that serves `under`: the
|
|
156
|
+
newest is not necessarily the one this notebook is open in.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
servers = jupyter_servers()
|
|
160
|
+
|
|
161
|
+
if under:
|
|
162
|
+
under = os.path.abspath(os.path.expanduser(under))
|
|
163
|
+
|
|
164
|
+
for root, base in servers:
|
|
165
|
+
if under == root or under.startswith(root + os.sep):
|
|
166
|
+
return root, base
|
|
167
|
+
|
|
168
|
+
return servers[0] if servers else (os.path.expanduser('~'), '/')
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def writer_processes(any_copy=False):
|
|
172
|
+
"""This user's running `monitor_writer.py` processes from this
|
|
173
|
+
dashboard, found by process rather than by directory: a writer started by
|
|
174
|
+
hand with `--out` anywhere. `[{pid, run, out_dir}]`, from /proc.
|
|
175
|
+
`any_copy` takes a writer from any copy of the script, such as another
|
|
176
|
+
checkout of the skill."""
|
|
177
|
+
|
|
178
|
+
script = os.path.realpath(os.path.join(HERE, 'monitor_writer.py'))
|
|
179
|
+
found = []
|
|
180
|
+
|
|
181
|
+
for pid, argv, cwd in _own_processes():
|
|
182
|
+
|
|
183
|
+
at = [i for i, a in enumerate(argv) if a.endswith('monitor_writer.py')
|
|
184
|
+
and (any_copy or os.path.realpath(os.path.join(cwd, a)) == script)]
|
|
185
|
+
if not at:
|
|
186
|
+
continue
|
|
187
|
+
|
|
188
|
+
rest = argv[at[0] + 1:]
|
|
189
|
+
out = rest[rest.index('--out') + 1] if '--out' in rest[:-1] else None
|
|
190
|
+
positional = [a for i, a in enumerate(rest) if not a.startswith('-')
|
|
191
|
+
and (i == 0 or not rest[i - 1].startswith('--'))]
|
|
192
|
+
|
|
193
|
+
if out and positional:
|
|
194
|
+
found.append({'pid': int(pid),
|
|
195
|
+
'run': os.path.abspath(os.path.join(cwd, positional[0])),
|
|
196
|
+
'out_dir': os.path.abspath(os.path.join(cwd,
|
|
197
|
+
os.path.expanduser(out)))})
|
|
198
|
+
|
|
199
|
+
return found
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _own_processes():
|
|
203
|
+
"""`(pid, argv, cwd)` for this user's processes: from /proc, else from
|
|
204
|
+
psutil, else none, since without either nothing can be found."""
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
pids = [p for p in os.listdir('/proc') if p.isdigit()]
|
|
208
|
+
except OSError:
|
|
209
|
+
pids = None
|
|
210
|
+
|
|
211
|
+
if pids is None:
|
|
212
|
+
try:
|
|
213
|
+
import psutil
|
|
214
|
+
except ImportError:
|
|
215
|
+
return
|
|
216
|
+
|
|
217
|
+
for proc in psutil.process_iter(['pid', 'uids', 'cmdline', 'cwd']):
|
|
218
|
+
info = proc.info
|
|
219
|
+
if info.get('uids') is not None and info['uids'].real == os.getuid() \
|
|
220
|
+
and info.get('cmdline') and info.get('cwd'):
|
|
221
|
+
yield str(info['pid']), info['cmdline'], info['cwd']
|
|
222
|
+
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
for pid in pids:
|
|
226
|
+
try:
|
|
227
|
+
if os.stat('/proc/' + pid).st_uid != os.getuid():
|
|
228
|
+
continue
|
|
229
|
+
with open('/proc/{}/cmdline'.format(pid), 'rb') as infile:
|
|
230
|
+
argv = [a.decode(errors='replace') for a in
|
|
231
|
+
infile.read().split(b'\0') if a]
|
|
232
|
+
cwd = os.readlink('/proc/{}/cwd'.format(pid))
|
|
233
|
+
except OSError:
|
|
234
|
+
continue
|
|
235
|
+
|
|
236
|
+
yield pid, argv, cwd
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def status(base=DEFAULT_BASE):
|
|
240
|
+
"""Every run currently being published, wherever its payload lives.
|
|
241
|
+
|
|
242
|
+
Payloads sit beside their runs, so there is no one directory to list. The
|
|
243
|
+
writer index names them. `base` is also scanned, including the base
|
|
244
|
+
itself, for a writer started by hand with `--out` pointing there.
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
base = os.path.abspath(os.path.expanduser(base))
|
|
248
|
+
|
|
249
|
+
candidates = list(monitor_writer.index_entries())
|
|
250
|
+
candidates += [base] + [os.path.join(base, name) for name in
|
|
251
|
+
(sorted(os.listdir(base)) if os.path.isdir(base) else [])]
|
|
252
|
+
|
|
253
|
+
out, seen = [], set()
|
|
254
|
+
|
|
255
|
+
for out_dir in candidates:
|
|
256
|
+
out_dir = os.path.abspath(os.path.expanduser(out_dir))
|
|
257
|
+
|
|
258
|
+
if out_dir in seen:
|
|
259
|
+
continue
|
|
260
|
+
|
|
261
|
+
seen.add(out_dir)
|
|
262
|
+
info = monitor_writer.writer_info(out_dir)
|
|
263
|
+
|
|
264
|
+
if info:
|
|
265
|
+
out.append({'run': info['root'], 'out_dir': out_dir,
|
|
266
|
+
'pid': info['pid']})
|
|
267
|
+
else:
|
|
268
|
+
# The entry outlived its writer: a kill -9, or a reboot.
|
|
269
|
+
monitor_writer.forget(out_dir)
|
|
270
|
+
|
|
271
|
+
# And by process: a writer that never reached the index (another copy of
|
|
272
|
+
# the script, an unwritable ~/.cache) is still this user's monitor_writer.py.
|
|
273
|
+
pids = {entry['pid'] for entry in out}
|
|
274
|
+
out += [entry for entry in writer_processes() if entry['pid'] not in pids]
|
|
275
|
+
|
|
276
|
+
return out
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _alive(pid):
|
|
280
|
+
"""True while `pid` runs; a zombie (exited, not yet reaped by the
|
|
281
|
+
process that started it) counts as gone."""
|
|
282
|
+
|
|
283
|
+
try:
|
|
284
|
+
os.kill(pid, 0)
|
|
285
|
+
except ProcessLookupError:
|
|
286
|
+
return False
|
|
287
|
+
except OSError:
|
|
288
|
+
pass
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
with open('/proc/{}/stat'.format(pid)) as infile:
|
|
292
|
+
return infile.read().rsplit(')', 1)[1].split()[0] != 'Z'
|
|
293
|
+
except FileNotFoundError:
|
|
294
|
+
if os.path.isdir('/proc/self'):
|
|
295
|
+
return False
|
|
296
|
+
except (OSError, IndexError):
|
|
297
|
+
pass
|
|
298
|
+
|
|
299
|
+
try:
|
|
300
|
+
import psutil
|
|
301
|
+
return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE
|
|
302
|
+
except ImportError:
|
|
303
|
+
return True
|
|
304
|
+
except Exception:
|
|
305
|
+
return False
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _terminate(out_dir, pid):
|
|
309
|
+
"""SIGTERM, then wait up to 10 s for the process to go and its pidfile
|
|
310
|
+
with it."""
|
|
311
|
+
|
|
312
|
+
try:
|
|
313
|
+
os.kill(pid, 15)
|
|
314
|
+
except OSError:
|
|
315
|
+
return
|
|
316
|
+
|
|
317
|
+
for _ in range(40):
|
|
318
|
+
if not _alive(pid) and (monitor_writer.writer_info(out_dir)
|
|
319
|
+
or {}).get('pid') != pid:
|
|
320
|
+
return
|
|
321
|
+
|
|
322
|
+
time.sleep(0.25)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def writers_into(out_dir):
|
|
326
|
+
"""The pid of every writer publishing into `out_dir`: the one its
|
|
327
|
+
pidfile names first, then any other found by process, from any copy of
|
|
328
|
+
the script. A writer whose pidfile a later one overwrote keeps
|
|
329
|
+
publishing, invisible to the pidfile, and racing it over every payload."""
|
|
330
|
+
|
|
331
|
+
named = monitor_writer.alive(out_dir)
|
|
332
|
+
others = [entry['pid'] for entry in writer_processes(any_copy=True)
|
|
333
|
+
if entry['out_dir'] == out_dir and entry['pid'] != named]
|
|
334
|
+
|
|
335
|
+
return ([named] if named else []) + others
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def publishers(root):
|
|
339
|
+
"""Every writer publishing the search `root`, wherever it writes:
|
|
340
|
+
`[{pid, run, out_dir}]`, by process, from any copy of the script."""
|
|
341
|
+
|
|
342
|
+
root = os.path.abspath(os.path.expanduser(root))
|
|
343
|
+
found = []
|
|
344
|
+
|
|
345
|
+
for entry in writer_processes(any_copy=True):
|
|
346
|
+
try:
|
|
347
|
+
if check_run(entry['run']) == root:
|
|
348
|
+
found.append(entry)
|
|
349
|
+
except ValueError:
|
|
350
|
+
continue
|
|
351
|
+
|
|
352
|
+
return found
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def start_writer(root, out_dir, interval=20.0, resource_interval=3.0):
|
|
356
|
+
"""Start the publisher unless a current one already serves this run.
|
|
357
|
+
|
|
358
|
+
A writer on a different run is replaced, since it would show the wrong
|
|
359
|
+
numbers under the right name. A writer on this run that started before the
|
|
360
|
+
current scanner code is replaced too, since it keeps publishing the
|
|
361
|
+
payload shape it started with. A writer of this run into another
|
|
362
|
+
directory is stopped: a search has one publisher.
|
|
363
|
+
"""
|
|
364
|
+
|
|
365
|
+
root = os.path.abspath(os.path.expanduser(root))
|
|
366
|
+
out_dir = os.path.abspath(os.path.expanduser(out_dir))
|
|
367
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
368
|
+
|
|
369
|
+
info = monitor_writer.writer_info(out_dir)
|
|
370
|
+
clocks = [float(interval), float(resource_interval)]
|
|
371
|
+
|
|
372
|
+
# Only the pidfile's writer may stay; any other was orphaned by a lost
|
|
373
|
+
# pidfile and would publish beside it for as long as it lives.
|
|
374
|
+
extra = [pid for pid in writers_into(out_dir)
|
|
375
|
+
if not info or pid != info['pid']]
|
|
376
|
+
|
|
377
|
+
if extra:
|
|
378
|
+
print('Stopping {} other writer{} publishing into {} (pid {}).'.format(
|
|
379
|
+
len(extra), '' if len(extra) == 1 else 's', out_dir,
|
|
380
|
+
', '.join(map(str, extra))))
|
|
381
|
+
for pid in extra:
|
|
382
|
+
_terminate(out_dir, pid)
|
|
383
|
+
|
|
384
|
+
for entry in publishers(root):
|
|
385
|
+
if entry['out_dir'] != out_dir:
|
|
386
|
+
print('Stopping the writer publishing {} into {} (pid {}); {} will '
|
|
387
|
+
'publish it.'.format(root, entry['out_dir'], entry['pid'],
|
|
388
|
+
out_dir))
|
|
389
|
+
_terminate(entry['out_dir'], entry['pid'])
|
|
390
|
+
|
|
391
|
+
if info and info['root'] == root \
|
|
392
|
+
and info['code'] == monitor_writer.code_version() \
|
|
393
|
+
and info['intervals'] == clocks:
|
|
394
|
+
return info['pid'], False
|
|
395
|
+
|
|
396
|
+
if info and info['root'] == root:
|
|
397
|
+
print('Restarting the writer (pid {}): {}.'.format(info['pid'],
|
|
398
|
+
'it predates the current scanner' if info['code']
|
|
399
|
+
!= monitor_writer.code_version() else 'its intervals were {}, not {}'
|
|
400
|
+
.format(info['intervals'], clocks)))
|
|
401
|
+
_terminate(out_dir, info['pid'])
|
|
402
|
+
|
|
403
|
+
elif info:
|
|
404
|
+
print('Stopping the writer on {} (pid {}); {} will publish '
|
|
405
|
+
'{}.'.format(info['root'], info['pid'], out_dir, root))
|
|
406
|
+
_terminate(out_dir, info['pid'])
|
|
407
|
+
|
|
408
|
+
# Drop the previous search's files, or the wait below would accept
|
|
409
|
+
# them as the new writer's output. Its whole READMEs are moved aside, not
|
|
410
|
+
# deleted: the new writer writes only its own, so any left would
|
|
411
|
+
# show under the new search's ids.
|
|
412
|
+
for name in monitor_writer.PAYLOADS:
|
|
413
|
+
try:
|
|
414
|
+
os.unlink(os.path.join(out_dir, name))
|
|
415
|
+
except OSError:
|
|
416
|
+
pass
|
|
417
|
+
|
|
418
|
+
for name in ('readmes', 'diffs'):
|
|
419
|
+
stale = os.path.join(out_dir, name)
|
|
420
|
+
if os.path.isdir(stale):
|
|
421
|
+
os.rename(stale, '{}.{}-{}'.format(stale,
|
|
422
|
+
time.strftime('%Y%m%d-%H%M%S'), os.getpid()))
|
|
423
|
+
|
|
424
|
+
log = open(os.path.join(out_dir, 'writer.log'), 'a')
|
|
425
|
+
process = subprocess.Popen([sys.executable,
|
|
426
|
+
os.path.join(HERE, 'monitor_writer.py'), root, '--out', out_dir,
|
|
427
|
+
'--interval', str(interval), '--resource-interval',
|
|
428
|
+
str(resource_interval)], cwd=HERE, stdout=log, stderr=log,
|
|
429
|
+
stdin=subprocess.DEVNULL, start_new_session=True)
|
|
430
|
+
|
|
431
|
+
# Wait for the pidfile to name this run, not merely for a state.json to
|
|
432
|
+
# exist: after a handover the previous search's may still be on disk. And for
|
|
433
|
+
# resources.json, which its own thread writes one hardware sample after
|
|
434
|
+
# start (seconds on a busy host): a page mounted before it polls a 404.
|
|
435
|
+
exited = None
|
|
436
|
+
|
|
437
|
+
for _ in range(120):
|
|
438
|
+
current = monitor_writer.writer_info(out_dir)
|
|
439
|
+
|
|
440
|
+
if current and current['root'] == root and all(os.path.exists(
|
|
441
|
+
os.path.join(out_dir, name)) for name in ('state.json',
|
|
442
|
+
'resources.json')):
|
|
443
|
+
break
|
|
444
|
+
|
|
445
|
+
# Ours exiting is a failure, unless a start running at the same
|
|
446
|
+
# moment took the directory's lock first: then its writer is the
|
|
447
|
+
# one to wait for, and it gets 10 s to write its pidfile.
|
|
448
|
+
if process.poll() is not None:
|
|
449
|
+
exited = exited or time.time()
|
|
450
|
+
if time.time() - exited > 10:
|
|
451
|
+
raise RuntimeError('the writer exited; see '
|
|
452
|
+
+ os.path.join(out_dir, 'writer.log'))
|
|
453
|
+
|
|
454
|
+
time.sleep(0.5)
|
|
455
|
+
|
|
456
|
+
if current and current['pid'] != process.pid:
|
|
457
|
+
return current['pid'], False
|
|
458
|
+
|
|
459
|
+
return process.pid, True
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def stop_writer(root=None, out_dir=None, base=DEFAULT_BASE):
|
|
463
|
+
"""Stop every publisher watching `root`, the one in `out_dir`, or all.
|
|
464
|
+
|
|
465
|
+
Every publisher of the run, not only the default directory's: one
|
|
466
|
+
started by hand elsewhere would keep the page updating from a writer the
|
|
467
|
+
user thinks they stopped.
|
|
468
|
+
"""
|
|
469
|
+
|
|
470
|
+
if out_dir is not None:
|
|
471
|
+
targets = [os.path.abspath(os.path.expanduser(out_dir))]
|
|
472
|
+
elif root is not None:
|
|
473
|
+
root = os.path.abspath(os.path.expanduser(root))
|
|
474
|
+
targets = [e['out_dir'] for e in status(base) if e['run'] == root]
|
|
475
|
+
else:
|
|
476
|
+
targets = [e['out_dir'] for e in status(base)]
|
|
477
|
+
|
|
478
|
+
stopped = []
|
|
479
|
+
|
|
480
|
+
for target in dict.fromkeys(targets):
|
|
481
|
+
for pid in writers_into(target):
|
|
482
|
+
# Wait, as a handover does: `--status` right after must not
|
|
483
|
+
# still list it.
|
|
484
|
+
_terminate(target, pid)
|
|
485
|
+
stopped.append(pid)
|
|
486
|
+
|
|
487
|
+
return stopped
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def make_notebook(root, path=None, out_dir=None, overwrite=True, **kwargs):
|
|
491
|
+
"""Write a one-cell notebook that renders the monitor for `root`.
|
|
492
|
+
|
|
493
|
+
The default is `dashboard.ipynb` in the search's directory, beside
|
|
494
|
+
`autooptimize/`, so the notebook sits with the run it watches. Pass
|
|
495
|
+
`overwrite=False` to keep one the user has edited.
|
|
496
|
+
"""
|
|
497
|
+
|
|
498
|
+
root = check_run(root)
|
|
499
|
+
path = os.path.abspath(os.path.expanduser(path
|
|
500
|
+
or os.path.join(os.path.dirname(root), NOTEBOOK)))
|
|
501
|
+
|
|
502
|
+
if os.path.exists(path) and not overwrite:
|
|
503
|
+
return path
|
|
504
|
+
|
|
505
|
+
# Outside the served tree the file is fine but can never be opened in
|
|
506
|
+
# Lab, which looks like the monitor not working.
|
|
507
|
+
served_root, _ = jupyter_root(under=path)
|
|
508
|
+
|
|
509
|
+
if not path.startswith(served_root + os.sep):
|
|
510
|
+
print('warning: {} is outside the directory Jupyter serves ({}), so '
|
|
511
|
+
'it will not appear in the file browser.'.format(path, served_root))
|
|
512
|
+
|
|
513
|
+
if out_dir is not None:
|
|
514
|
+
kwargs = dict(kwargs, out_dir=out_dir)
|
|
515
|
+
|
|
516
|
+
extra = ''.join(',\n\t{}={!r}'.format(k, v) for k, v in kwargs.items())
|
|
517
|
+
|
|
518
|
+
# Reload on every run: the kernel outlives the cell.
|
|
519
|
+
code = ('import sys, importlib\n'
|
|
520
|
+
'sys.path.insert(0, {!r})\n'
|
|
521
|
+
'import autoopt_monitor as am\n'
|
|
522
|
+
'am = importlib.reload(am)\n'
|
|
523
|
+
'\n'
|
|
524
|
+
'am.show({!r}{})\n'.format(HERE, root, extra))
|
|
525
|
+
|
|
526
|
+
notebook = {
|
|
527
|
+
# `id` is required from nbformat 4.5; without it every read warns.
|
|
528
|
+
'cells': [{'cell_type': 'code', 'id': 'monitor',
|
|
529
|
+
'execution_count': None, 'metadata': {}, 'outputs': [],
|
|
530
|
+
'source': code.splitlines(keepends=True)}],
|
|
531
|
+
'metadata': {'kernelspec': {'display_name': 'Python 3',
|
|
532
|
+
'language': 'python', 'name': 'python3'},
|
|
533
|
+
'language_info': {'name': 'python'}},
|
|
534
|
+
'nbformat': 4, 'nbformat_minor': 5,
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
with open(path, 'w') as out:
|
|
538
|
+
json.dump(notebook, out, indent=1)
|
|
539
|
+
|
|
540
|
+
return path
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _body_markup():
|
|
544
|
+
"""The markup, taken from the standalone page so the two never drift."""
|
|
545
|
+
|
|
546
|
+
with open(os.path.join(HERE, 'static', 'index.html')) as infile:
|
|
547
|
+
page = infile.read()
|
|
548
|
+
|
|
549
|
+
body = re.search(r'<body[^>]*>(.*)</body>', page, re.S).group(1)
|
|
550
|
+
|
|
551
|
+
return re.sub(r'<script\b.*?</script>', '', body, flags=re.S).strip()
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def show(root, out_dir=None, interval=20.0, resource_interval=3.0,
|
|
555
|
+
writer=True, base=DEFAULT_BASE):
|
|
556
|
+
"""Render the monitor for `root` in this notebook.
|
|
557
|
+
|
|
558
|
+
Parameters
|
|
559
|
+
----------
|
|
560
|
+
root: str
|
|
561
|
+
The `autooptimize/` directory to watch, or the directory holding it.
|
|
562
|
+
|
|
563
|
+
out_dir: str, optional
|
|
564
|
+
Where the JSON is published. Defaults to `<root>/monitor` when that
|
|
565
|
+
is inside the directory Jupyter serves and writable, else
|
|
566
|
+
`<base>/<project>-<hash>`. Must be inside the directory Jupyter
|
|
567
|
+
serves, because the page reads it through the Contents API.
|
|
568
|
+
|
|
569
|
+
interval, resource_interval: float, optional
|
|
570
|
+
Seconds between full scans, and between hardware samples.
|
|
571
|
+
|
|
572
|
+
writer: bool, optional
|
|
573
|
+
Start the publisher if it is not running. False renders against data
|
|
574
|
+
someone else is publishing.
|
|
575
|
+
"""
|
|
576
|
+
|
|
577
|
+
from IPython.display import display, HTML, Javascript
|
|
578
|
+
|
|
579
|
+
root = check_run(root)
|
|
580
|
+
out_dir = os.path.abspath(os.path.expanduser(out_dir
|
|
581
|
+
or default_out_dir(root, base)))
|
|
582
|
+
|
|
583
|
+
served_root, base_url = jupyter_root(under=out_dir)
|
|
584
|
+
|
|
585
|
+
if not out_dir.startswith(served_root + os.sep):
|
|
586
|
+
raise ValueError('{} is outside the directory Jupyter serves ({}); '
|
|
587
|
+
'the page could not read it. Pass out_dir= somewhere under '
|
|
588
|
+
'{}.'.format(out_dir, served_root, served_root))
|
|
589
|
+
|
|
590
|
+
# Install the current front end now: a long-lived writer may be mid-sleep.
|
|
591
|
+
monitor_writer.install_assets(out_dir)
|
|
592
|
+
|
|
593
|
+
if writer:
|
|
594
|
+
start_writer(root, out_dir, interval, resource_interval)
|
|
595
|
+
|
|
596
|
+
# Encoded per segment: a space, '#' or '?' in a directory name would
|
|
597
|
+
# otherwise end the path inside the /files/ and Contents API URLs.
|
|
598
|
+
relative = '/'.join(urllib.parse.quote(part, safe='') for part in
|
|
599
|
+
os.path.relpath(out_dir, served_root).split(os.sep))
|
|
600
|
+
mount = 'autoopt-{}'.format(int(time.time() * 1000))
|
|
601
|
+
|
|
602
|
+
display(HTML('<div id="{}" class="autoopt-root"></div>'.format(mount)))
|
|
603
|
+
display(Javascript(_BOOTSTRAP % {
|
|
604
|
+
'mount': json.dumps(mount),
|
|
605
|
+
'base': json.dumps(base_url if base_url.endswith('/')
|
|
606
|
+
else base_url + '/'),
|
|
607
|
+
'dir': json.dumps(relative),
|
|
608
|
+
'body': json.dumps(_body_markup()),
|
|
609
|
+
'version': json.dumps(monitor_writer.assets_version()),
|
|
610
|
+
'state_interval': int(interval * 1000),
|
|
611
|
+
'resource_interval': int(resource_interval * 1000),
|
|
612
|
+
'writer_log': json.dumps(os.path.join(out_dir, 'writer.log')),
|
|
613
|
+
}))
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
_BOOTSTRAP = r"""
|
|
617
|
+
(async () => {
|
|
618
|
+
const mount = document.getElementById(%(mount)s);
|
|
619
|
+
if (!mount) return;
|
|
620
|
+
|
|
621
|
+
const base = %(base)s;
|
|
622
|
+
const dir = %(dir)s;
|
|
623
|
+
const files = base + 'files/' + dir + '/';
|
|
624
|
+
const bust = '?v=' + %(version)s;
|
|
625
|
+
|
|
626
|
+
const once = (tag, attrs) => new Promise((resolve, reject) => {
|
|
627
|
+
const key = attrs.href || attrs.src;
|
|
628
|
+
if (document.querySelector(`${tag}[data-autoopt="${key}"]`))
|
|
629
|
+
return resolve();
|
|
630
|
+
|
|
631
|
+
const node = document.createElement(tag);
|
|
632
|
+
Object.assign(node, attrs);
|
|
633
|
+
node.dataset.autoopt = key;
|
|
634
|
+
node.onload = resolve;
|
|
635
|
+
node.onerror = () => reject(new Error('could not load ' + key));
|
|
636
|
+
document.head.append(node);
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
const contents = async (name) => {
|
|
640
|
+
const url = base + 'api/contents/' + dir + '/' + name
|
|
641
|
+
+ '?content=1&type=file&format=text&_=' + Date.now();
|
|
642
|
+
const response = await fetch(url, {credentials: 'same-origin'});
|
|
643
|
+
if (!response.ok) throw new Error(name + ': ' + response.status);
|
|
644
|
+
return JSON.parse((await response.json()).content);
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
// A write the publisher reads only for its age: Jupyter's contents API
|
|
648
|
+
// takes the PUT with the XSRF token it set as a cookie.
|
|
649
|
+
const live = async () => {
|
|
650
|
+
const cookie = document.cookie.split('; ').find((c) => c.startsWith('_xsrf='));
|
|
651
|
+
const response = await fetch(base + 'api/contents/' + dir + '/live.json', {
|
|
652
|
+
method: 'PUT', credentials: 'same-origin',
|
|
653
|
+
headers: {'Content-Type': 'application/json',
|
|
654
|
+
'X-XSRFToken': cookie ? decodeURI(cookie.slice(6)) : ''},
|
|
655
|
+
body: JSON.stringify({type: 'file', format: 'text', content: '{}'})});
|
|
656
|
+
if (!response.ok) throw new Error('live.json: ' + response.status);
|
|
657
|
+
};
|
|
658
|
+
|
|
659
|
+
mount.textContent = 'Loading the dashboard…';
|
|
660
|
+
|
|
661
|
+
try {
|
|
662
|
+
await once('link', {rel: 'stylesheet', href: files + 'dashboard.css' + bust});
|
|
663
|
+
await once('script', {src: files + 'plotly.min.js'}).catch(() => {});
|
|
664
|
+
// A module, so re-running the cell after an update does not collide
|
|
665
|
+
// with the copy the page already loaded.
|
|
666
|
+
await once('script', {src: files + 'dashboard.js' + bust, type: 'module'});
|
|
667
|
+
} catch (error) {
|
|
668
|
+
mount.textContent = String(error);
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
mount.innerHTML = %(body)s;
|
|
673
|
+
|
|
674
|
+
window.startAutoopt(mount, {
|
|
675
|
+
state: () => contents('state.json'),
|
|
676
|
+
resources: () => contents('resources.json'),
|
|
677
|
+
readme: (id) => contents('readmes/' + id + '.json'),
|
|
678
|
+
diff: (id) => contents('diffs/' + id + '.json'),
|
|
679
|
+
live,
|
|
680
|
+
}, {stateInterval: %(state_interval)d,
|
|
681
|
+
resourceInterval: %(resource_interval)d, writerLog: %(writer_log)s});
|
|
682
|
+
})();
|
|
683
|
+
"""
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def shareable(resources):
|
|
687
|
+
"""The host sample without what names the machine or its other users:
|
|
688
|
+
the hostname, the GPUs' serial numbers, and who holds a lease and why.
|
|
689
|
+
The export is a file people pass around; the live page is not."""
|
|
690
|
+
|
|
691
|
+
resources = dict(resources, hostname=None)
|
|
692
|
+
resources['gpus'] = [dict(gpu, uuid=None, lease={'user': 'leased',
|
|
693
|
+
'note': 'holder left out of the export'} if gpu.get('lease') else None)
|
|
694
|
+
for gpu in resources.get('gpus') or []]
|
|
695
|
+
|
|
696
|
+
return resources
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def export(root, path):
|
|
700
|
+
"""Write one self-contained, read-only HTML file of the search as it is.
|
|
701
|
+
|
|
702
|
+
Inlines the stylesheet, plotly, the script and every payload the page
|
|
703
|
+
reads, so the file opens anywhere with no Jupyter and no publisher. The
|
|
704
|
+
page shows "snapshot of <time>" in place of the pulse. Returns the path
|
|
705
|
+
and the size in bytes.
|
|
706
|
+
"""
|
|
707
|
+
|
|
708
|
+
root = check_run(root)
|
|
709
|
+
scanner = scan.RunScanner(root)
|
|
710
|
+
|
|
711
|
+
snapshot = scanner.snapshot()
|
|
712
|
+
files = {'state.json': snapshot,
|
|
713
|
+
'resources.json': shareable(scanner.hardware.resources())}
|
|
714
|
+
for identifier, (mtime, text) in scanner.readmes().items():
|
|
715
|
+
files['readmes/%d.json' % identifier] = {'id': identifier, 'text': text}
|
|
716
|
+
for identifier, (payload, pair) in scanner.diffs(snapshot['iterations'],
|
|
717
|
+
budget=None).items():
|
|
718
|
+
files['diffs/%d.json' % identifier] = payload
|
|
719
|
+
|
|
720
|
+
def read(name):
|
|
721
|
+
with open(os.path.join(HERE, 'static', name)) as infile:
|
|
722
|
+
return infile.read()
|
|
723
|
+
|
|
724
|
+
# An inline `</script` ends the element early, wherever it appears. In
|
|
725
|
+
# the code it is escaped; the data escapes every `<`, since `<!--` then
|
|
726
|
+
# `<script` in a README would keep `</script>` from closing it at all.
|
|
727
|
+
inline = lambda text: re.sub(r'</(script)', r'<\\/\1', text,
|
|
728
|
+
flags=re.I)
|
|
729
|
+
|
|
730
|
+
try:
|
|
731
|
+
import plotly
|
|
732
|
+
except ImportError:
|
|
733
|
+
raise ImportError('--export inlines plotly.min.js from the plotly '
|
|
734
|
+
'package, which is not installed here: pip install plotly') from None
|
|
735
|
+
|
|
736
|
+
with open(os.path.join(os.path.dirname(plotly.__file__), 'package_data',
|
|
737
|
+
'plotly.min.js')) as infile:
|
|
738
|
+
plotly_js = infile.read()
|
|
739
|
+
|
|
740
|
+
data = json.dumps({'generated': time.time(),
|
|
741
|
+
'files': monitor_writer._round(files)}, separators=(',', ':'),
|
|
742
|
+
default=lambda value: None).replace('<', '\\u003c')
|
|
743
|
+
|
|
744
|
+
# The home directory, as JSON spells it, written as ~ wherever a path
|
|
745
|
+
# starts with it.
|
|
746
|
+
home = os.path.expanduser('~').rstrip('/')
|
|
747
|
+
if home:
|
|
748
|
+
data = re.sub(re.escape(json.dumps(home)[1:-1]) + r'(?=/|")', '~', data)
|
|
749
|
+
|
|
750
|
+
page = read('index.html').replace(' data-standalone', '')
|
|
751
|
+
page = page.replace('<link rel="stylesheet" href="dashboard.css">',
|
|
752
|
+
'<style>\n' + read('dashboard.css') + '\n</style>')
|
|
753
|
+
page = page.replace('<script src="plotly.min.js"></script>',
|
|
754
|
+
'<script>' + inline(plotly_js) + '</script>')
|
|
755
|
+
page = page.replace('<script type="module" src="dashboard.js"></script>',
|
|
756
|
+
'<script id="autoopt-snapshot" type="application/json">' + data
|
|
757
|
+
+ '</script>\n<script type="module">\n' + inline(read('dashboard.js'))
|
|
758
|
+
+ '\n</script>')
|
|
759
|
+
|
|
760
|
+
path = os.path.abspath(os.path.expanduser(path))
|
|
761
|
+
with open(path, 'w') as out:
|
|
762
|
+
out.write(page)
|
|
763
|
+
|
|
764
|
+
return path, os.path.getsize(path)
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
def main(argv=None):
|
|
768
|
+
import argparse
|
|
769
|
+
|
|
770
|
+
parser = argparse.ArgumentParser(description='Write the one-cell monitor '
|
|
771
|
+
'notebook for a search, or manage the publishers behind them.')
|
|
772
|
+
parser.add_argument('root', nargs='?', help='the autooptimize/ directory, '
|
|
773
|
+
'or the directory holding it')
|
|
774
|
+
parser.add_argument('-o', '--path', help='where to write the notebook '
|
|
775
|
+
'(default: {} beside autooptimize/)'.format(NOTEBOOK))
|
|
776
|
+
parser.add_argument('--out', help='where to publish the JSON (default: '
|
|
777
|
+
'where this search\'s publisher already writes, else <root>/monitor, '
|
|
778
|
+
'else {}/<project>-<hash>); must be under the directory Jupyter '
|
|
779
|
+
'serves. --start stops a publisher of this search writing elsewhere'
|
|
780
|
+
.format(DEFAULT_BASE))
|
|
781
|
+
parser.add_argument('--no-overwrite', action='store_true',
|
|
782
|
+
help='keep an existing notebook rather than replacing it')
|
|
783
|
+
parser.add_argument('--start', action='store_true', help='also start the '
|
|
784
|
+
'publisher, so the page has data before anyone opens the notebook')
|
|
785
|
+
parser.add_argument('--interval', type=float, default=20.0,
|
|
786
|
+
help='seconds between scans; written into the notebook, and a running '
|
|
787
|
+
'publisher on another interval is restarted (default: 20)')
|
|
788
|
+
parser.add_argument('--status', action='store_true',
|
|
789
|
+
help='list the publishers, only those watching root if given, and exit; '
|
|
790
|
+
'this lists other sessions\' searches too')
|
|
791
|
+
parser.add_argument('--stop', action='store_true',
|
|
792
|
+
help='stop the publishers for root, or every one if root is omitted; '
|
|
793
|
+
'returns once they have exited')
|
|
794
|
+
parser.add_argument('--export', metavar='HTML', help='write one '
|
|
795
|
+
'self-contained, read-only HTML file of root as it is, and exit')
|
|
796
|
+
args = parser.parse_args(argv)
|
|
797
|
+
|
|
798
|
+
if args.status:
|
|
799
|
+
wanted = check_run(args.root) if args.root else None
|
|
800
|
+
|
|
801
|
+
for entry in status():
|
|
802
|
+
if wanted and entry['run'] != wanted:
|
|
803
|
+
continue
|
|
804
|
+
print('{}\t{}\t{}'.format(entry['pid'], entry['run'],
|
|
805
|
+
entry['out_dir']))
|
|
806
|
+
|
|
807
|
+
elif args.stop:
|
|
808
|
+
for pid in stop_writer(check_run(args.root) if args.root else None):
|
|
809
|
+
print('stopped {}'.format(pid))
|
|
810
|
+
|
|
811
|
+
elif args.root is None:
|
|
812
|
+
parser.error('a search directory is required')
|
|
813
|
+
|
|
814
|
+
elif args.export:
|
|
815
|
+
path, size = export(args.root, args.export)
|
|
816
|
+
print('{}\t{:.1f} MB'.format(path, size / 1024 ** 2))
|
|
817
|
+
|
|
818
|
+
else:
|
|
819
|
+
root = check_run(args.root)
|
|
820
|
+
# Without --out, where this search's publisher already writes, so a
|
|
821
|
+
# second --start reports it instead of starting one beside it.
|
|
822
|
+
live = [entry['out_dir'] for entry in publishers(root)]
|
|
823
|
+
default = default_out_dir(root)
|
|
824
|
+
out_dir = os.path.abspath(os.path.expanduser(args.out or (default
|
|
825
|
+
if default in live or not live else live[0])))
|
|
826
|
+
|
|
827
|
+
print(make_notebook(root, path=args.path, out_dir=out_dir,
|
|
828
|
+
overwrite=not args.no_overwrite, interval=args.interval))
|
|
829
|
+
|
|
830
|
+
if args.start:
|
|
831
|
+
served_root, _ = jupyter_root(under=out_dir)
|
|
832
|
+
if not out_dir.startswith(served_root + os.sep):
|
|
833
|
+
print('warning: {} is outside the directory Jupyter serves '
|
|
834
|
+
'({}); the page will not be able to read it, and show() '
|
|
835
|
+
'will refuse it.'.format(out_dir, served_root))
|
|
836
|
+
|
|
837
|
+
pid, started = start_writer(root, out_dir, interval=args.interval)
|
|
838
|
+
print('{} publisher pid {} -> {}'.format('started' if started
|
|
839
|
+
else 'already running', pid, out_dir))
|
|
840
|
+
|
|
841
|
+
return 0
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
if __name__ == '__main__':
|
|
845
|
+
# A wrong directory is a message, not a traceback.
|
|
846
|
+
try:
|
|
847
|
+
sys.exit(main())
|
|
848
|
+
except (ValueError, ImportError) as error:
|
|
849
|
+
print('error: {}'.format(error), file=sys.stderr)
|
|
850
|
+
sys.exit(1)
|