@bbcsoftwarefactory/skills 0.1.1 → 1.1.3

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.
Files changed (71) hide show
  1. package/dist/index.json +2 -3
  2. package/dist/skills/code-quality-gate/SKILL.md +4 -5
  3. package/dist/skills/code-quality-gate/references/gate-bigo.md +1 -1
  4. package/dist/skills/delivery-coordinator/SKILL.md +7 -8
  5. package/dist/skills/delivery-coordinator/references/hud-output.md +1 -1
  6. package/dist/skills/delivery-coordinator/references/issue-claim.md +5 -5
  7. package/dist/skills/delivery-coordinator/references/issue-dedup.md +1 -1
  8. package/dist/skills/delivery-coordinator/references/worktree-isolation.md +2 -2
  9. package/dist/skills/greptile-review-loop/SKILL.md +3 -4
  10. package/dist/skills/greptile-review-loop/references/review-protocol.md +1 -1
  11. package/dist/skills/issue-reviewer/SKILL.md +10 -13
  12. package/dist/skills/issue-reviewer/references/review-format.md +1 -1
  13. package/dist/skills/issue-reviewer/references/triage.md +6 -6
  14. package/dist/skills/question-gate/SKILL.md +6 -8
  15. package/dist/skills/question-gate/references/client-hooks.md +10 -10
  16. package/dist/skills/question-gate/references/diagram-routing.md +3 -3
  17. package/dist/skills/skill-clean-architecture/SKILL.md +2 -3
  18. package/dist/skills/skill-clean-architecture/references/source-headers.md +2 -3
  19. package/dist/skills/tool-depot/references/readonly-access.md +1 -1
  20. package/dist/skills/tool-depot/references/tool-catalog.json +2 -2
  21. package/dist/skills/watcher-observability/SKILL.md +3 -4
  22. package/dist/skills/watcher-observability/references/batch-protocol.md +6 -6
  23. package/dist/skills/watcher-observability/references/configuration.md +1 -1
  24. package/dist/skills/watcher-observability/references/error-scan.md +1 -1
  25. package/dist/skills/watcher-observability/references/live-protocol.md +8 -8
  26. package/dist/skills/watcher-observability/references/server-account.md +8 -8
  27. package/dist/skills/watcher-observability/server/watcher-gate.sh +1 -1
  28. package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +10 -7
  29. package/dist/skills/workflow-auditor/SKILL.md +3 -5
  30. package/dist/skills/workflow-auditor/references/audit-protocol.md +3 -3
  31. package/dist/skills/workflow-auditor/references/ledger.md +1 -1
  32. package/package.json +26 -27
  33. package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +0 -225
  34. package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +0 -200
  35. package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +0 -363
  36. package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +0 -220
  37. package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +0 -263
  38. package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +0 -221
  39. package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +0 -123
  40. package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +0 -124
  41. package/dist/skills/greptile-review-loop/scripts/review-loop.py +0 -435
  42. package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +0 -331
  43. package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +0 -239
  44. package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +0 -311
  45. package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +0 -90
  46. package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +0 -168
  47. package/dist/skills/question-gate/scripts/triage-question.py +0 -713
  48. package/dist/skills/question-gate/tests/question-corpus.test.sh +0 -32
  49. package/dist/skills/question-gate/tests/triage-question.test.sh +0 -441
  50. package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +0 -427
  51. package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +0 -222
  52. package/dist/skills/watcher-observability/scripts/error-scan.py +0 -318
  53. package/dist/skills/watcher-observability/scripts/resolve-containers.py +0 -155
  54. package/dist/skills/watcher-observability/scripts/save-counts.py +0 -381
  55. package/dist/skills/watcher-observability/scripts/summarize-logs.py +0 -113
  56. package/dist/skills/watcher-observability/scripts/watch-live.py +0 -606
  57. package/dist/skills/watcher-observability/tests/error-scan.test.sh +0 -257
  58. package/dist/skills/watcher-observability/tests/live-windows.test.sh +0 -177
  59. package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +0 -87
  60. package/dist/skills/watcher-observability/tests/save-counts.test.sh +0 -338
  61. package/dist/skills/watcher-observability/tests/sleuth.test.sh +0 -176
  62. package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +0 -105
  63. package/dist/skills/watcher-observability/tests/watcher-config.test.sh +0 -70
  64. package/dist/skills/workflow-auditor/scripts/audit-ledger.py +0 -624
  65. package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +0 -183
  66. package/dist/skills/workflow-auditor/scripts/render-workflow.py +0 -201
  67. package/dist/skills/workflow-auditor/scripts/validate-skills.py +0 -444
  68. package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +0 -660
  69. package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +0 -93
  70. package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +0 -135
  71. package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +0 -190
@@ -1,318 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Error-only scan over an approved container's recent Docker logs.
3
-
4
- Reads either `docker logs --since=<minutes>m --timestamps` or
5
- `docker logs --tail=<lines> --timestamps` once, filters locally, and reports
6
- only warn/error records and known failure signatures. Read-only, bounded by a
7
- deadline and a byte ceiling, no remote shell pipeline.
8
- """
9
-
10
- import json
11
- import os
12
- from pathlib import Path
13
- from queue import Empty, Queue
14
- import re
15
- import runpy
16
- import subprocess
17
- import sys
18
- from threading import Thread
19
- from time import monotonic
20
-
21
- SCRIPTS = Path(__file__).resolve().parent
22
- CONTAINER = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]*', re.ASCII)
23
- MAX_BYTES = 16 * 1024 * 1024
24
- MAX_MINUTES = 120
25
- MAX_TAIL = 50_000
26
- MAX_ROWS = 40
27
- DEADLINE = 60
28
- # Streaming (#52): read in blocks through a bounded queue, so at most
29
- # READ_SIZE * QUEUE_BLOCKS bytes wait unprocessed and memory does not grow with
30
- # the size of the remote output.
31
- READ_SIZE = 65536
32
- QUEUE_BLOCKS = 16
33
- HELP = ('Usage: python -I -B scripts/error-scan.py [--project <uuid>] <ssh-alias> <exact-container> '
34
- '[minutes | --tail <lines>]\n'
35
- 'Read one bounded window once (1-120 minutes, or 1-50000 lines) and report '
36
- 'only warn/error signal.\n'
37
- '--project keeps only lines that contain that project uuid (any field name, any case).')
38
- # #45: containers are shared by customers. A uuid is matched as a plain string so the
39
- # filter does not depend on the field name (projectId, project_id, ...).
40
- PROJECT = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)
41
-
42
- # runpy, not import: `python -I` keeps this directory off sys.path. Read only names
43
- # listed in watch-live.py's SHARED_API (enforced by tests/error-scan.test.sh).
44
- W = runpy.run_path(str(SCRIPTS / 'watch-live.py'))
45
- TIMESTAMP, PLAIN_LEVEL, PLAIN_PATTERNS = W['TIMESTAMP'], W['PLAIN_LEVEL'], W['PLAIN_PATTERNS']
46
- strip_headers = W['strip_headers']
47
- PATTERNS, LEVELS, json_level, json_hit = W['PATTERNS'], W['LEVELS'], W['json_level'], W['json_hit']
48
-
49
- EVENT = re.compile(r'"event":"([^"]+)"')
50
-
51
- # Digests are rebuilt from fixed strings only (#39). A denylist of regexes let
52
- # fragments of passwords, API keys, cookies and internal hosts through; with an
53
- # allowlist, any token that is not a known diagnostic word becomes [redacted],
54
- # so log content can never supply output characters.
55
- DIGEST_WORDS = frozenset((
56
- 'error', 'errors', 'warn', 'warning', 'fatal', 'critical', 'failed', 'failure', 'fails', 'fail',
57
- 'timeout', 'timed', 'out', 'refused', 'reset', 'closed', 'broken', 'pipe', 'connection',
58
- 'connect', 'socket', 'retry', 'retrying', 'retries', 'unavailable', 'upstream', 'downstream',
59
- 'denied', 'forbidden', 'unauthorized', 'auth', 'authentication', 'expired', 'invalid',
60
- 'missing', 'not', 'found', 'exceeded', 'limit', 'rate', 'quota', 'crash', 'crashed', 'killed',
61
- 'memory', 'disk', 'full', 'database', 'db', 'query', 'request', 'response', 'webhook', 'message',
62
- 'send', 'sent', 'delivery', 'deliver', 'template', 'queue', 'job', 'worker', 'payment', 'charge',
63
- 'handshake', 'tls', 'ssl', 'dns', 'lookup', 'parse', 'json', 'unexpected', 'token', 'status',
64
- 'server', 'client', 'internal', 'gateway', 'bad', 'service', 'for', 'to', 'from', 'with', 'on',
65
- 'in', 'of', 'the', 'a', 'an', 'is', 'was', 'while', 'after', 'during', 'cannot', 'could',
66
- ))
67
- DIGEST_EXACT = {**W['CODES'], **W['EXCEPTIONS']}
68
- DIGEST_MESSAGE_KEYS = ('msg', 'message', 'error', 'err')
69
- DIGEST_TOKENS, DIGEST_CHARS = 16, 220
70
- REDACTED = '[redacted]'
71
-
72
-
73
- def digest(body, record=None):
74
- """Allowlisted excerpt: known diagnostic words, error codes and exception names only."""
75
- text = body
76
- if isinstance(record, dict):
77
- text = next((record[key] for key in DIGEST_MESSAGE_KEYS if isinstance(record.get(key), str)), '')
78
- out = []
79
- for raw in text.split()[:DIGEST_TOKENS]:
80
- token = raw.strip('.,;:()[]{}"\'!?')
81
- word = DIGEST_EXACT.get(token) or (token.lower() if token.lower() in DIGEST_WORDS else REDACTED)
82
- if word != REDACTED or not out or out[-1] != REDACTED:
83
- out.append(word)
84
- return ' '.join(out)[:DIGEST_CHARS]
85
-
86
-
87
- def classify(line):
88
- body = strip_headers(line.strip())
89
- record = None
90
- brace = body.find('{')
91
- if brace >= 0 and body.rstrip().endswith('}'):
92
- try:
93
- record = json.loads(body[brace:])
94
- except (ValueError, RecursionError):
95
- record = None
96
- level = json_level(record) if isinstance(record, dict) else None
97
- hit = json_hit(record) if isinstance(record, dict) else None
98
- if level is None:
99
- match = PLAIN_LEVEL.search(body)
100
- level = LEVELS[(match[1] or match[2]).lower()] if match else None
101
- if hit is None:
102
- hit = next((i for i, regex in enumerate(PLAIN_PATTERNS) if regex.search(body)), None)
103
- return level or ('error' if hit is not None else None), hit, body, record
104
-
105
-
106
- def selector_flag(selector):
107
- kind, value = selector
108
- return f'--since={value}m' if kind == 'since' else f'--tail={value}'
109
-
110
-
111
- def selector_label(selector):
112
- kind, value = selector
113
- return f'{value}m' if kind == 'since' else f'{value}l'
114
-
115
-
116
- class Tally:
117
- """Counts, signatures, events and evidence rows, fed one decoded segment at a time."""
118
-
119
- def __init__(self, project=None):
120
- self.project, self.filtered = project, 0
121
- self.counts = dict.fromkeys(('error', 'warn', 'info', 'debug', 'unclassified'), 0)
122
- self.hits = [0] * len(PATTERNS)
123
- self.events, self.rows = {}, []
124
-
125
- def feed(self, segment):
126
- # A segment never contains b'\n', and UTF-8 multibyte sequences cannot span
127
- # it, so decoding per segment and applying splitlines() gives exactly what
128
- # the old whole-buffer data.decode(...).splitlines() gave.
129
- for raw in segment.decode('utf-8', errors='replace').splitlines():
130
- if not raw.strip():
131
- continue
132
- if self.project and self.project not in raw.lower():
133
- self.filtered += 1 # another project, or no project in context
134
- continue
135
- level, hit, body, record = classify(raw)
136
- self.counts[level or 'unclassified'] += 1
137
- if hit is not None:
138
- self.hits[hit] += 1
139
- event = EVENT.search(raw)
140
- if event:
141
- self.events[event.group(1)] = self.events.get(event.group(1), 0) + 1
142
- if (level in ('error', 'warn') or hit is not None) and len(self.rows) < MAX_ROWS:
143
- self.rows.append({'level': level or 'signature',
144
- 'signature': PATTERNS[hit][0] if hit is not None else None,
145
- 'digest': digest(body, record)})
146
-
147
-
148
- def stop(proc):
149
- if proc.poll() is None:
150
- proc.kill()
151
- proc.wait()
152
-
153
-
154
- def scan(alias, container, selector, project=None):
155
- argv = ['ssh', '-nT', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes',
156
- '-o', 'UpdateHostKeys=no', '-o', 'ClearAllForwardings=yes',
157
- '-o', 'PermitLocalCommand=no', '-o', 'ControlPath=none', alias,
158
- 'docker', 'logs', selector_flag(selector), '--timestamps', '--', container]
159
- started = monotonic()
160
- proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
161
- stderr=subprocess.DEVNULL, bufsize=0)
162
- blocks = Queue(maxsize=QUEUE_BLOCKS)
163
-
164
- def read():
165
- # A thread, not select(): pipes are not selectable on Windows. The bounded
166
- # queue blocks this reader when the parser falls behind (backpressure).
167
- with proc.stdout as pipe:
168
- while True:
169
- try:
170
- data = pipe.read(READ_SIZE)
171
- except (OSError, ValueError):
172
- data = b''
173
- blocks.put(data)
174
- if not data:
175
- return
176
-
177
- Thread(target=read, daemon=True).start()
178
- tally, pending, total = Tally(project), b'', 0
179
- try:
180
- while True:
181
- try:
182
- data = blocks.get(timeout=max(0, started + DEADLINE - monotonic()))
183
- except Empty:
184
- raise SystemExit('Watcher scan failed; no counts.') from None
185
- if not data:
186
- break
187
- total += len(data)
188
- if total > MAX_BYTES:
189
- raise SystemExit(f'Watcher scan refused: output over the {MAX_BYTES} byte ceiling.')
190
- pending += data
191
- cut = pending.rfind(b'\n')
192
- if cut >= 0:
193
- for segment in pending[:cut].split(b'\n'):
194
- tally.feed(segment)
195
- pending = pending[cut + 1:]
196
- if pending:
197
- tally.feed(pending)
198
- try:
199
- code = proc.wait(timeout=max(0, started + DEADLINE - monotonic()))
200
- except subprocess.TimeoutExpired:
201
- raise SystemExit('Watcher scan failed; no counts.') from None
202
- if code != 0:
203
- raise SystemExit('Watcher scan failed; no counts.')
204
- finally:
205
- stop(proc)
206
- return tally.counts, tally.hits, tally.events, tally.rows, total, tally.filtered
207
-
208
-
209
- def save(alias, container, selector, counts, hits, events, rows, nbytes, project=None, filtered=0):
210
- # Clean windows are not reports: only signal runs create an artifact.
211
- if not rows and not counts['error'] and not counts['warn']:
212
- return None
213
- root = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True,
214
- text=True, timeout=5)
215
- if root.returncode != 0:
216
- return None
217
- base = Path(root.stdout.strip())
218
- ignore = base / '.gitignore'
219
- try:
220
- ignore_info = ignore.lstat()
221
- except OSError:
222
- return None
223
- import stat as _stat
224
- if not _stat.S_ISREG(ignore_info.st_mode) or ignore_info.st_nlink != 1:
225
- return None
226
- if getattr(ignore_info, 'st_file_attributes', 0) & getattr(_stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0):
227
- return None
228
- if '/tmp_logs/' not in ignore.read_text(errors='replace').splitlines():
229
- return None
230
- tmp_base = base / 'tmp_logs'
231
- try:
232
- info = tmp_base.lstat()
233
- if not _stat.S_ISDIR(info.st_mode):
234
- return None
235
- if getattr(info, 'st_file_attributes', 0) & getattr(_stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0):
236
- return None
237
- except FileNotFoundError:
238
- pass
239
- chk = subprocess.run(['git', '-C', str(base), 'check-ignore', '-q', 'tmp_logs/scan'],
240
- capture_output=True, timeout=5)
241
- if chk.returncode != 0:
242
- return None
243
- target = tmp_base / 'scan'
244
- target.mkdir(parents=True, exist_ok=True, mode=0o700)
245
- try:
246
- t_info = target.lstat()
247
- if not _stat.S_ISDIR(t_info.st_mode) or (getattr(t_info, 'st_file_attributes', 0) & getattr(_stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0)):
248
- return None
249
- except OSError:
250
- return None
251
- kind, value = selector
252
- name = target / f'{kind}-{value}-{os.getpid()}.json'
253
- payload = {'mode': 'error-scan', 'source': {'alias': alias, 'container': container},
254
- 'selector': {'kind': kind, 'value': value}, 'bytes_read': nbytes,
255
- 'counts': counts, 'signatures': {PATTERNS[i][0]: n for i, n in enumerate(hits) if n},
256
- 'events': events, 'rows': rows}
257
- if project:
258
- payload.update(project=project, filtered_out=filtered)
259
- flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0)
260
- fd = os.open(name, flags, 0o600)
261
- with os.fdopen(fd, 'w', encoding='utf-8') as handle:
262
- json.dump(payload, handle, indent=1)
263
- return name
264
-
265
-
266
- def parse_selector(argv):
267
- if len(argv) == 2:
268
- return ('since', 15)
269
- if len(argv) == 3 and argv[2].isdigit() and 1 <= int(argv[2]) <= MAX_MINUTES:
270
- return ('since', int(argv[2]))
271
- if len(argv) == 4 and argv[2] == '--tail' and argv[3].isdigit() \
272
- and 1 <= int(argv[3]) <= MAX_TAIL:
273
- return ('tail', int(argv[3]))
274
- return None
275
-
276
-
277
- def main(argv):
278
- project = None
279
- if argv[:1] == ['--project']:
280
- if len(argv) < 2 or not PROJECT.fullmatch(argv[1]):
281
- print(HELP, file=sys.stderr)
282
- return 1
283
- project, argv = argv[1].lower(), argv[2:]
284
- if not 2 <= len(argv) <= 4:
285
- print(HELP, file=sys.stderr)
286
- return 1
287
- try:
288
- alias_ok = W['alias_pattern']()
289
- except W['ConfigError'] as error:
290
- print(error, file=sys.stderr)
291
- return 1
292
- alias, container = argv[0], argv[1]
293
- selector = parse_selector(argv)
294
- if not alias_ok.fullmatch(alias) or not CONTAINER.fullmatch(container) or selector is None:
295
- print(HELP, file=sys.stderr)
296
- return 1
297
- counts, hits, events, rows, nbytes, filtered = scan(alias, container, selector, project)
298
- total = sum(counts.values())
299
- scope = f' project={project} filtered_out={filtered}' if project else ''
300
- print(f'scan alias={alias} container={container} selector={selector_label(selector)} '
301
- f'lines={total} bytes={nbytes}{scope}')
302
- print('severity ' + ' '.join(f'{k}={v}' for k, v in counts.items()))
303
- ranked = sorted(((PATTERNS[i][0], n) for i, n in enumerate(hits) if n), key=lambda item: -item[1])
304
- print('signatures ' + (', '.join(f'{name}:{n}' for name, n in ranked) or 'none'))
305
- top = sorted(events.items(), key=lambda item: -item[1])[:8]
306
- print('events ' + (', '.join(f'{name}:{n}' for name, n in top) or 'none'))
307
- print(f'evidence rows={len(rows)}')
308
- for row in rows:
309
- sig = f" sig={row['signature']}" if row['signature'] else ''
310
- print(f" [{row['level']}]{sig} {row['digest']}")
311
- saved = save(alias, container, selector, counts, hits, events, rows, nbytes, project, filtered)
312
- if saved:
313
- print(f'saved={saved}')
314
- return 0
315
-
316
-
317
- if __name__ == '__main__':
318
- raise SystemExit(main(sys.argv[1:]))
@@ -1,155 +0,0 @@
1
- #!/usr/bin/env python3
2
- """resolve-containers.py: validate a Watcher target, resolving `prefix*` remotely.
3
-
4
- Usage: python3 -I -B scripts/resolve-containers.py <ssh-alias> <container|literal-prefix*>
5
-
6
- An exact name or ID is only shape-validated and echoed back without SSH (no
7
- existence check; capture fails later if it does not exist). A trailing-* prefix
8
- is resolved with one names-only, filtered `docker ps`; names are published only
9
- after the entire discovery succeeds: exit 0, never partial output.
10
-
11
- Same limits as the retired Bash resolver: 15 s deadline plus 2 s before a forced
12
- kill, an 8 KiB output cutoff and at most 16 distinct names. The remote command
13
- string is unchanged because server/watcher-gate.sh allows it verbatim. Standard
14
- library only; needs only `ssh` (ADR 0001).
15
- """
16
-
17
- from queue import Empty, Queue
18
- from pathlib import Path
19
- import re
20
- import runpy
21
- import shutil
22
- import subprocess
23
- import sys
24
- from threading import Thread
25
- from time import monotonic
26
-
27
- # runpy, not import: `python -I` keeps this directory off sys.path. Read only names
28
- # listed in watch-live.py's SHARED_API (enforced by tests/error-scan.test.sh).
29
- W = runpy.run_path(str(Path(__file__).resolve().parent / 'watch-live.py'))
30
- NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]*', re.ASCII)
31
- INVALID = 'Watcher requires a valid SSH alias and container name, ID, or literal prefix followed by *.'
32
- FAILED = 'Watcher container discovery failed; no snapshot.'
33
- SSH_OPTIONS = ('-nT', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'UpdateHostKeys=no',
34
- '-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no', '-o', 'ControlPath=none')
35
- DEADLINE, KILL_GRACE, CUTOFF, MAX_NAMES, READ_SIZE = 15, 2, 8192, 16, 4096
36
-
37
-
38
- class DiscoveryFailed(Exception):
39
- """Discovery output is unusable; publish nothing."""
40
-
41
-
42
- def remote_command(prefix):
43
- # Every prefix byte is allowlisted, so single quotes keep the regex and the Go
44
- # template literal; dots are escaped to stay literal in Docker's name filter.
45
- return f"docker ps --filter 'name=^/?{prefix.replace('.', chr(92) + '.')}.*$' --format '{{{{.Names}}}}'"
46
-
47
-
48
- def read_bounded(process):
49
- """Return output below CUTOFF bytes, or raise if it is cut, late or failing."""
50
- chunks = Queue()
51
-
52
- def drain():
53
- with process.stdout as pipe:
54
- while True:
55
- try:
56
- data = pipe.read(READ_SIZE)
57
- except (OSError, ValueError):
58
- data = b''
59
- chunks.put(data)
60
- if not data:
61
- return
62
-
63
- started = monotonic()
64
- Thread(target=drain, daemon=True).start()
65
- out = bytearray()
66
- while True:
67
- try:
68
- data = chunks.get(timeout=max(0, started + DEADLINE - monotonic()))
69
- except Empty:
70
- raise DiscoveryFailed('deadline') from None
71
- if not data:
72
- break
73
- out += data
74
- if len(out) >= CUTOFF:
75
- raise DiscoveryFailed('cutoff')
76
- try:
77
- code = process.wait(timeout=max(0, started + DEADLINE - monotonic()))
78
- except subprocess.TimeoutExpired:
79
- raise DiscoveryFailed('deadline') from None
80
- if code != 0:
81
- raise DiscoveryFailed('status')
82
- return bytes(out)
83
-
84
-
85
- def stop(process):
86
- if process.poll() is None:
87
- process.terminate()
88
- try:
89
- process.wait(timeout=KILL_GRACE)
90
- except subprocess.TimeoutExpired:
91
- process.kill()
92
- process.wait()
93
-
94
-
95
- def parse(output, prefix):
96
- """First-seen distinct names, each a valid name starting with the literal prefix."""
97
- if output and not output.endswith(b'\n'):
98
- raise DiscoveryFailed('partial')
99
- names = []
100
- for raw in output.split(b'\n')[:-1] if output else []:
101
- try:
102
- name = raw.decode('ascii')
103
- except UnicodeDecodeError:
104
- raise DiscoveryFailed('bytes') from None
105
- if not NAME.fullmatch(name) or not name.startswith(prefix):
106
- raise DiscoveryFailed('name')
107
- if name not in names:
108
- names.append(name)
109
- if len(names) > MAX_NAMES:
110
- raise DiscoveryFailed('too many')
111
- return names
112
-
113
-
114
- def resolve(alias, selector):
115
- """Return the exact names for a valid target; raise ValueError or DiscoveryFailed."""
116
- if not W['alias_pattern']().fullmatch(alias):
117
- raise ValueError('alias')
118
- if NAME.fullmatch(selector):
119
- return [selector]
120
- if not selector.endswith('*') or not NAME.fullmatch(selector[:-1]):
121
- raise ValueError('selector')
122
- prefix = selector[:-1]
123
- ssh = shutil.which('ssh')
124
- if not ssh:
125
- raise DiscoveryFailed('ssh')
126
- process = subprocess.Popen([ssh, *SSH_OPTIONS, alias, remote_command(prefix)], stdin=subprocess.DEVNULL,
127
- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)
128
- try:
129
- return parse(read_bounded(process), prefix)
130
- finally:
131
- stop(process)
132
-
133
-
134
- def main(argv):
135
- if len(argv) != 2:
136
- print(INVALID, file=sys.stderr)
137
- return 1
138
- try:
139
- names = resolve(*argv)
140
- except W['ConfigError'] as error:
141
- print(error, file=sys.stderr)
142
- return 1
143
- except ValueError:
144
- print(INVALID, file=sys.stderr)
145
- return 1
146
- except (DiscoveryFailed, OSError, subprocess.SubprocessError):
147
- print(FAILED, file=sys.stderr)
148
- return 1
149
- if names:
150
- sys.stdout.write(''.join(name + '\n' for name in names))
151
- return 0
152
-
153
-
154
- if __name__ == '__main__':
155
- sys.exit(main(sys.argv[1:]))